import barcode from barcode.writer import ImageWriter import base64 import gradio as gr 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.""" barcode_class = barcode.get_barcode_class(barcode_type) barcode_instance = barcode_class(data, writer=ImageWriter()) output_path = "barcode.png" barcode_instance.save(output_path) return output_path def barcode_interface(input_type, text, file, barcode_type): if input_type == "Text" and text: encoded_text = base64.b64encode(text.encode('utf-8')).decode('utf-8') return generate_barcode(encoded_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="filepath", label="Generated Barcode"), description="Generate a Barcode from either text or any file.", css="footer {visibility: hidden}" ) interface.launch(share=True)