Update app.py
Browse files
app.py
CHANGED
@@ -2,6 +2,8 @@ import barcode
|
|
2 |
from barcode.writer import ImageWriter
|
3 |
import base64
|
4 |
import gradio as gr
|
|
|
|
|
5 |
|
6 |
def encode_file_to_base64(file_path):
|
7 |
"""Reads any file and encodes it to base64."""
|
@@ -10,17 +12,25 @@ def encode_file_to_base64(file_path):
|
|
10 |
return encoded_data
|
11 |
|
12 |
def generate_barcode(data: str, barcode_type: str = "code128"):
|
13 |
-
"""Generates a barcode from given data."""
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
def barcode_interface(input_type, text, file, barcode_type):
|
21 |
if input_type == "Text" and text:
|
22 |
-
|
23 |
-
return generate_barcode(encoded_text, barcode_type)
|
24 |
elif input_type == "File" and file:
|
25 |
encoded_file = encode_file_to_base64(file.name)
|
26 |
return generate_barcode(encoded_file, barcode_type)
|
@@ -35,7 +45,7 @@ interface = gr.Interface(
|
|
35 |
gr.File(label="Upload File"),
|
36 |
gr.Dropdown(["code128", "ean13", "ean8"], label="Barcode Type", value="code128"),
|
37 |
],
|
38 |
-
outputs=gr.Image(type="
|
39 |
description="Generate a Barcode from either text or any file.",
|
40 |
css="footer {visibility: hidden}"
|
41 |
)
|
|
|
2 |
from barcode.writer import ImageWriter
|
3 |
import base64
|
4 |
import gradio as gr
|
5 |
+
from io import BytesIO
|
6 |
+
from PIL import Image
|
7 |
|
8 |
def encode_file_to_base64(file_path):
|
9 |
"""Reads any file and encodes it to base64."""
|
|
|
12 |
return encoded_data
|
13 |
|
14 |
def generate_barcode(data: str, barcode_type: str = "code128"):
|
15 |
+
"""Generates a barcode from given data and returns an image in memory."""
|
16 |
+
try:
|
17 |
+
barcode_class = barcode.get_barcode_class(barcode_type)
|
18 |
+
barcode_instance = barcode_class(data, writer=ImageWriter())
|
19 |
+
|
20 |
+
# Simpan barcode ke dalam BytesIO
|
21 |
+
output = BytesIO()
|
22 |
+
barcode_instance.write(output)
|
23 |
+
|
24 |
+
# Buka gambar dengan PIL untuk memastikan kompatibilitas dengan Gradio
|
25 |
+
output.seek(0)
|
26 |
+
img = Image.open(output)
|
27 |
+
return img
|
28 |
+
except Exception as e:
|
29 |
+
return f"Error: {str(e)}"
|
30 |
|
31 |
def barcode_interface(input_type, text, file, barcode_type):
|
32 |
if input_type == "Text" and text:
|
33 |
+
return generate_barcode(text, barcode_type)
|
|
|
34 |
elif input_type == "File" and file:
|
35 |
encoded_file = encode_file_to_base64(file.name)
|
36 |
return generate_barcode(encoded_file, barcode_type)
|
|
|
45 |
gr.File(label="Upload File"),
|
46 |
gr.Dropdown(["code128", "ean13", "ean8"], label="Barcode Type", value="code128"),
|
47 |
],
|
48 |
+
outputs=gr.Image(type="numpy", label="Generated Barcode"),
|
49 |
description="Generate a Barcode from either text or any file.",
|
50 |
css="footer {visibility: hidden}"
|
51 |
)
|