Spaces:
Sleeping
Sleeping
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) | |