Spaces:
Sleeping
Sleeping
File size: 1,575 Bytes
11ff2f2 e1f3ebd af74360 3d156ef b8adac9 11ff2f2 af74360 11ff2f2 9c6f546 3d156ef 11ff2f2 9c6f546 3d156ef 11ff2f2 9c6f546 bcb8d08 af74360 11ff2f2 9c6f546 3d156ef 11ff2f2 9c6f546 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 |
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)
|