import gradio as gr import barcode from barcode.writer import SVGWriter from io import BytesIO import tempfile import os # Barcode explanations BARCODE_EXPLANATIONS = { "EAN13": ( "EAN-13 (International Article Number) is a 13-digit barcode widely used for retail products globally. " "It encodes a GS1 prefix (country or organization), manufacturer code, product code, and a check digit. " "EAN-13 is compatible with UPC systems and is essential for international product identification." ), "Code128": ( "Code 128 is a high-density, variable-length barcode that can encode all ASCII characters (letters, numbers, symbols). " "It is commonly used in logistics and shipping due to its ability to store complex data in a compact form and includes a checksum for error detection." ), "UPC": ( "UPC (Universal Product Code) is a 12-digit barcode used mainly in North America for retail product identification. " "It consists of a manufacturer code, item number, and a check digit. UPCs streamline inventory and checkout processes in stores." ), "ISBN13": ( "ISBN-13 is a 13-digit identifier for books, encoded as an EAN-13 barcode. " "It uniquely identifies books internationally and is essential for publishers, libraries, and retailers." ), } def generate_barcode_svg(text, barcode_type): BARCODE_CLASSES = { "EAN13": barcode.get_barcode_class('ean13'), "Code128": barcode.get_barcode_class('code128'), "UPC": barcode.get_barcode_class('upc'), "ISBN13": barcode.get_barcode_class('isbn13'), } explanation = BARCODE_EXPLANATIONS.get(barcode_type, "No explanation available.") try: bc_class = BARCODE_CLASSES[barcode_type] svg_buffer = BytesIO() bc = bc_class(text, writer=SVGWriter()) bc.write(svg_buffer) svg_data = svg_buffer.getvalue().decode("utf-8") # Save SVG to a temporary file and return the file path tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".svg") tmp.write(svg_data.encode("utf-8")) tmp.close() return explanation, svg_data, tmp.name except Exception as e: return f"Error: {str(e)}", None, None with gr.Blocks() as demo: gr.Markdown("# Barcode Generator (SVG Output with Download)") with gr.Row(): text_input = gr.Textbox(label="Text to encode") barcode_type = gr.Dropdown( ["EAN13", "Code128", "UPC", "ISBN13"], value="Code128", label="Barcode Type" ) explanation_box = gr.Markdown(label="Barcode Explanation") svg_output = gr.HTML(label="Generated Barcode (SVG)") download_btn = gr.File(label="Download SVG") btn = gr.Button("Generate Barcode") btn.click( generate_barcode_svg, inputs=[text_input, barcode_type], outputs=[explanation_box, svg_output, download_btn] ) demo.launch()