File size: 2,427 Bytes
11ff2f2
 
e1f3ebd
af74360
b020f7f
 
97e1f27
2fe855a
af74360
3d156ef
 
 
 
 
b8adac9
11ff2f2
b020f7f
 
 
 
 
 
 
 
 
 
 
 
97e1f27
 
 
 
 
 
2fe855a
 
 
97e1f27
2fe855a
 
b020f7f
97e1f27
af74360
11ff2f2
9c6f546
b020f7f
9c6f546
3d156ef
11ff2f2
9c6f546
 
bcb8d08
af74360
11ff2f2
9c6f546
 
3d156ef
 
11ff2f2
9c6f546
2fe855a
11ff2f2
cac2d9a
bcb8d08
 
11ff2f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import barcode
from barcode.writer import ImageWriter
import base64
import gradio as gr
from io import BytesIO
from PIL import Image
import datetime
import os

def encode_file_to_base64(file_path):
    """Reads any file and encodes it to base64."""
    with open(file_path, "rb") as f:
        encoded_data = base64.b64encode(f.read()).decode("utf-8")
    return encoded_data

def generate_barcode(data: str, barcode_type: str = "code128"):
    """Generates a barcode from given data and returns an image in memory."""
    try:
        barcode_class = barcode.get_barcode_class(barcode_type)
        barcode_instance = barcode_class(data, writer=ImageWriter())

        # Simpan barcode ke dalam BytesIO
        output = BytesIO()
        barcode_instance.write(output)

        # Buka gambar dengan PIL untuk memastikan kompatibilitas dengan Gradio
        output.seek(0)
        img = Image.open(output)
        
        # Simpan gambar dengan nama file dinamis
        timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
        file_name = f"flowly_ai_premium_barcode_generator_{timestamp}.png"
        
        # Simpan file gambar sebagai PNG
        file_path = os.path.join("generated_barcodes", file_name)
        os.makedirs(os.path.dirname(file_path), exist_ok=True)  # Ensure the directory exists
        img.save(file_path)
        
        # Mengembalikan gambar untuk ditampilkan di Gradio dan path file untuk diunduh
        return img, file_path
    except Exception as e:
        return f"Error: {str(e)}", None

def barcode_interface(input_type, text, file, barcode_type):
    if input_type == "Text" and text:
        return generate_barcode(text, barcode_type)
    elif input_type == "File" and file:
        encoded_file = encode_file_to_base64(file.name)
        return generate_barcode(encoded_file, barcode_type)
    else:
        return None

interface = gr.Interface(
    fn=barcode_interface,
    inputs=[
        gr.Radio(["Text", "File"], label="Input Type", value="Text"),
        gr.Textbox(label="Enter Text"),
        gr.File(label="Upload File"),
        gr.Dropdown(["code128", "ean13", "ean8"], label="Barcode Type", value="code128"),
    ],
    outputs=[gr.Image(type="numpy", label="Generated Barcode"), gr.File(label="Download Barcode")],
    description="Generate a Barcode from either text or any file.",
    css="footer {visibility: hidden}"
)

interface.launch(share=True)