NerveGear commited on
Commit
21baa9f
·
verified ·
1 Parent(s): 74fcdad

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import io
3
+ from PIL import Image
4
+
5
+ import barcode
6
+ from barcode.writer import ImageWriter
7
+ import qrcode
8
+ from pylibdmtx import encode
9
+
10
+ def generate_barcode(barcode_type, data):
11
+ if barcode_type == 'EAN13':
12
+ try:
13
+ ean = barcode.get('ean13', data, writer=ImageWriter())
14
+ except Exception as e:
15
+ return f"Error: {e}"
16
+ buffer = io.BytesIO()
17
+ ean.write(buffer)
18
+ buffer.seek(0)
19
+ img = Image.open(buffer)
20
+ return img
21
+ elif barcode_type == 'QR Code':
22
+ img = qrcode.make(data)
23
+ return img
24
+ elif barcode_type == 'DataMatrix':
25
+ try:
26
+ encoded = encode(data.encode('utf-8'))
27
+ except Exception as e:
28
+ return f"Error: {e}"
29
+ buffer = io.BytesIO(encoded.png)
30
+ img = Image.open(buffer)
31
+ return img
32
+ else:
33
+ return "Unsupported barcode type."
34
+
35
+ with gr.Blocks() as demo:
36
+ gr.Markdown("### 條碼生成器 (EAN13, QR Code, DataMatrix)")
37
+ barcode_type = gr.Radio(['EAN13', 'QR Code', 'DataMatrix'], value='EAN13', label="選擇條碼格式")
38
+ data_input = gr.Textbox(label="輸入條碼內容", value="123456789012")
39
+ output = gr.Image(label="生成的條碼")
40
+ error_msg = gr.Textbox(visible=False, interactive=False)
41
+
42
+ def on_generate(barcode_type, data):
43
+ result = generate_barcode(barcode_type, data)
44
+ if isinstance(result, str): # error message
45
+ error_msg.visible = True
46
+ error_msg.value = result
47
+ return None
48
+ else:
49
+ error_msg.visible = False
50
+ error_msg.value = ""
51
+ return result
52
+
53
+ data_input.change(on_generate, [barcode_type, data_input], output)
54
+ barcode_type.change(on_generate, [barcode_type, data_input], output)
55
+
56
+ demo.launch()