ginipick commited on
Commit
af59de2
·
verified ·
1 Parent(s): 46d91b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -275
app.py CHANGED
@@ -6,6 +6,7 @@ from datetime import datetime
6
  from PIL import Image, ImageDraw
7
  from math import cos, sin, radians
8
 
 
9
  def create_border_decoration(qr_image, decoration_prompt="flowers"):
10
  # Convert QR image to RGB if it's not
11
  if qr_image.mode != 'RGB':
@@ -49,298 +50,248 @@ def create_border_decoration(qr_image, decoration_prompt="flowers"):
49
 
50
  return decorated_image
51
 
52
- # Inside create_interface(), update the border_decoration section:
53
- border_decoration = gr.Textbox(
54
- label="Border Decoration Prompt",
55
- placeholder="Enter decoration style (e.g., flowers, simple, modern)",
56
- value="flowers" # Default value
57
- )
58
-
59
- # Update the create_qr function:
60
- def create_qr(
61
- content,
62
- qr_type,
63
- fill_color,
64
- back_color,
65
- box_size,
66
- border_size,
67
- error_correction,
68
- border_decoration="flowers" # Default value
69
- ):
70
- # QR 코드 데이터 포맷팅
71
- formatted_data = format_data(content, qr_type)
72
-
73
- # 에러 수정 레벨 설정
74
- error_levels = {
75
- "Low (7%)": qrcode.constants.ERROR_CORRECT_L,
76
- "Medium (15%)": qrcode.constants.ERROR_CORRECT_M,
77
- "Quartile (25%)": qrcode.constants.ERROR_CORRECT_Q,
78
- "High (30%)": qrcode.constants.ERROR_CORRECT_H
79
- }
80
-
81
- # QR 코드 생성
82
- qr = qrcode.QRCode(
83
- version=1,
84
- error_correction=error_levels[error_correction],
85
- box_size=box_size,
86
- border=border_size,
87
- )
88
-
89
- qr.add_data(formatted_data)
90
- qr.make(fit=True)
91
-
92
- # QR 이미지 생성
93
- qr_img = qr.make_image(fill_color=fill_color, back_color=back_color)
94
-
95
- # Add border decoration if specified
96
- if border_decoration.strip(): # Only if decoration prompt is not empty
97
- qr_img = create_border_decoration(qr_img, border_decoration)
98
-
99
- # 파일 저장
100
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
101
- random_id = random.randint(1000, 9999)
102
- filename = f"qrfile/qr_{timestamp}_{random_id}.png"
103
-
104
- # 디렉토리 확인 및 생성
105
- os.makedirs("qrfile", exist_ok=True)
106
-
107
- # 이미지 저장
108
- qr_img.save(filename)
109
- cleanup_old_files("qrfile/", max_files=100)
110
-
111
- return filename, formatted_data
112
 
113
  # 데이터 포맷팅 함수
114
  def format_data(content, qr_type):
115
- if not content:
116
- return ""
117
-
118
- format_rules = {
119
- "URL": lambda x: f"https://{x}" if not x.startswith(('http://', 'https://')) else x,
120
- "Email": lambda x: f"mailto:{x}",
121
- "Phone": lambda x: f"tel:{x}",
122
- "SMS": lambda x: f"sms:{x}",
123
- "WhatsApp": lambda x: f"whatsapp://send?text={x}",
124
- "Location": lambda x: f"geo:{x}",
125
- "Wi-Fi": lambda x: f"WIFI:S:{x};;",
126
- "Text": lambda x: x,
127
- "vCard": lambda x: f"BEGIN:VCARD\nVERSION:3.0\n{x}\nEND:VCARD"
128
- }
129
-
130
- return format_rules[qr_type](content.strip())
131
 
132
  # 파일 정리 함수
133
  def cleanup_old_files(directory, max_files):
134
- files = [f for f in os.listdir(directory) if f.endswith('.png')]
135
- if len(files) > max_files:
136
- files.sort(key=lambda x: os.path.getctime(os.path.join(directory, x)))
137
- for f in files[:-max_files]:
138
- try:
139
- os.remove(os.path.join(directory, f))
140
- except:
141
- continue
142
-
143
- def get_example_placeholder(qr_type):
144
- examples = {
145
- "URL": "example.com or https://example.com",
146
- "Email": "[email protected]",
147
- "Phone": "+1234567890",
148
- "SMS": "+1234567890",
149
- "WhatsApp": "Hello World!",
150
- "Location": "37.7749,-122.4194",
151
- "Wi-Fi": "MyWiFiNetwork",
152
- "Text": "Any text you want to encode",
153
- "vCard": "FN:John Doe\nTEL:+1234567890\nEMAIL:[email protected]"
154
- }
155
- return examples.get(qr_type, "Enter your content here...")
156
 
157
  def format_example_text(qr_type):
158
- examples = {
159
- "URL": "• Direct URL: https://example.com\n• Without https: example.com",
160
- "Email": "• Basic: [email protected]\n• With subject: [email protected]?subject=Hello",
161
- "Phone": "• International: +1234567890\n• Local: 01012345678",
162
- "SMS": "• Basic: +1234567890\n• With message: +1234567890?body=Hello",
163
- "WhatsApp": "• Message: Hello World!\n• With number: +1234567890:Hello",
164
- "Location": "• Coordinates: 37.7749,-122.4194\n• With zoom: 37.7749,-122.4194,15z",
165
- "Wi-Fi": "• Network name only: MyWiFiNetwork\n• With password: WIFI:S:MyNetwork;P:password;;",
166
- "Text": "• Simple text: Hello World!\n• Multiple lines: Line 1\\nLine 2",
167
- "vCard": "• Basic:\nFN:John Doe\nTEL:+1234567890\nEMAIL:[email protected]\n• Extended:\nFN:John Doe\nTEL:+1234567890\nEMAIL:[email protected]\nADR:;;123 Street;City;State;12345;Country"
168
- }
169
- return examples.get(qr_type, "Enter your content here...")
170
 
171
- # Gradio 인터페이스 생성
172
  # Gradio 인터페이스 생성
173
  def create_interface():
174
- # 테마 설정
175
- theme = gr.themes.Soft(
176
- primary_hue="blue",
177
- secondary_hue="indigo",
178
- ).set(
179
- body_background_fill="*neutral_50",
180
- block_background_fill="*neutral_100",
181
- button_primary_background_fill="*primary_500",
182
- )
183
-
184
- # 인터페이스 구성
185
- with gr.Blocks(theme=theme, title="QR Canvas") as demo:
186
- gr.Markdown(
187
- """
188
- # 🎯 QR CANVAS
189
- Create customized QR codes for various purposes with professional styling options.
190
- """
191
- )
192
-
193
- gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fginipick-QR-Canvas.hf.space">
194
- <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fginipick-QR-Canvas.hf.space&countColor=%23263759" />
195
- </a>""")
196
-
197
- with gr.Row():
198
- with gr.Column(scale=2):
199
- # 입력 섹션
200
- qr_type = gr.Dropdown(
201
- choices=[
202
- "URL",
203
- "Email",
204
- "Phone",
205
- "SMS",
206
- "WhatsApp",
207
- "Location",
208
- "Wi-Fi",
209
- "Text",
210
- "vCard"
211
- ],
212
- value="URL",
213
- label="QR Code Type"
214
- )
215
-
216
- content = gr.Textbox(
217
- label="Content",
218
- placeholder="Enter your content here...",
219
- lines=3
220
- )
221
-
222
- example_format = gr.Textbox(
223
- value=format_example_text("URL"),
224
- label="Format Examples",
225
- interactive=False,
226
- lines=6
227
- )
228
-
229
- with gr.Row():
230
- fill_color = gr.ColorPicker(
231
- label="QR Code Color",
232
- value="#000000"
233
- )
234
- back_color = gr.ColorPicker(
235
- label="Background Color",
236
- value="#FFFFFF"
237
- )
238
-
239
- with gr.Row():
240
- box_size = gr.Slider(
241
- minimum=1,
242
- maximum=20,
243
- value=10,
244
- step=1,
245
- label="QR Code Size"
246
- )
247
- border_size = gr.Slider(
248
- minimum=0,
249
- maximum=10,
250
- value=4,
251
- step=1,
252
- label="Border Size"
253
- )
254
-
255
- error_correction = gr.Dropdown(
256
- choices=[
257
- "Low (7%)",
258
- "Medium (15%)",
259
- "Quartile (25%)",
260
- "High (30%)"
261
- ],
262
- value="Medium (15%)",
263
- label="Error Correction Level"
264
- )
265
-
266
- border_decoration = gr.Textbox(
267
- label="Border Decoration Prompt",
268
- placeholder="Enter decoration style (e.g., flowers, simple, modern)",
269
- value="flowers" # Default value
270
- )
271
-
272
- generate_btn = gr.Button(
273
- "Generate QR Code",
274
- variant="primary"
275
- )
276
-
277
- with gr.Column(scale=1):
278
- # 출력 섹션
279
- output_image = gr.Image(
280
- label="Generated QR Code",
281
- type="filepath"
282
- )
283
- output_data = gr.Textbox(
284
- label="Formatted Data",
285
- interactive=False
286
- )
287
-
288
- def update_example(qr_type):
289
- return format_example_text(qr_type)
290
-
291
- # 이벤트 핸들러
292
- qr_type.change(
293
- fn=update_example,
294
- inputs=[qr_type],
295
- outputs=example_format
296
- )
297
-
298
- generate_btn.click(
299
- fn=create_qr,
300
- inputs=[
301
- content,
302
- qr_type,
303
- fill_color,
304
- back_color,
305
- box_size,
306
- border_size,
307
- error_correction,
308
- border_decoration
309
- ],
310
- outputs=[output_image, output_data]
311
- )
312
-
313
- # 사용 안내
314
- gr.Markdown(
315
- """
316
- ### 📝 Instructions
317
- 1. Select the QR code type from the dropdown menu
318
- 2. Enter your content following the format examples shown
319
- 3. Customize the appearance using the color pickers and sliders
320
- 4. Click 'Generate QR Code' to create your custom QR code
321
-
322
- ### 💡 Tips
323
- - Use higher error correction levels for better scan reliability
324
- - Ensure sufficient contrast between QR code and background colors
325
- - Keep the content concise for better readability
326
- - Follow the format examples for best results
327
- """
328
- )
329
-
330
- return demo
331
 
332
  if __name__ == "__main__":
333
  try:
334
- # 출력 디렉토리 생성
335
  os.makedirs("qrfile", exist_ok=True)
336
-
337
- # 인터페이스 생성 및 실행
338
  demo = create_interface()
339
  demo.launch(
340
- server_name="0.0.0.0", # 모든 IP에서 접근 가능
341
- server_port=7860, # 포트 지정
342
- share=True, # 공유 링크 생성
343
- debug=True # 디버그 모드 활성화
344
  )
345
  except Exception as e:
346
  print(f"Error starting the application: {e}")
 
6
  from PIL import Image, ImageDraw
7
  from math import cos, sin, radians
8
 
9
+ # 테두리 장식 함수
10
  def create_border_decoration(qr_image, decoration_prompt="flowers"):
11
  # Convert QR image to RGB if it's not
12
  if qr_image.mode != 'RGB':
 
50
 
51
  return decorated_image
52
 
53
+ # QR 코드 생성 함수
54
+ def create_qr(content, qr_type, fill_color, back_color, box_size, border_size, error_correction, border_decoration="flowers"):
55
+ # QR 코드 데이터 포맷팅
56
+ formatted_data = format_data(content, qr_type)
57
+
58
+ # 에러 수정 레벨 설정
59
+ error_levels = {
60
+ "Low (7%)": qrcode.constants.ERROR_CORRECT_L,
61
+ "Medium (15%)": qrcode.constants.ERROR_CORRECT_M,
62
+ "Quartile (25%)": qrcode.constants.ERROR_CORRECT_Q,
63
+ "High (30%)": qrcode.constants.ERROR_CORRECT_H
64
+ }
65
+
66
+ # QR 코드 생성
67
+ qr = qrcode.QRCode(
68
+ version=1,
69
+ error_correction=error_levels[error_correction],
70
+ box_size=box_size,
71
+ border=border_size,
72
+ )
73
+
74
+ qr.add_data(formatted_data)
75
+ qr.make(fit=True)
76
+
77
+ # QR 이미지 생성
78
+ qr_img = qr.make_image(fill_color=fill_color, back_color=back_color)
79
+
80
+ # Add border decoration if specified
81
+ if border_decoration.strip(): # Only if decoration prompt is not empty
82
+ qr_img = create_border_decoration(qr_img, border_decoration)
83
+
84
+ # 파일 저장
85
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
86
+ random_id = random.randint(1000, 9999)
87
+ filename = f"qrfile/qr_{timestamp}_{random_id}.png"
88
+
89
+ # 디렉토리 확인 및 생성
90
+ os.makedirs("qrfile", exist_ok=True)
91
+
92
+ # 이미지 저장
93
+ qr_img.save(filename)
94
+ cleanup_old_files("qrfile/", max_files=100)
95
+
96
+ return filename, formatted_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  # 데이터 포맷팅 함수
99
  def format_data(content, qr_type):
100
+ if not content:
101
+ return ""
102
+
103
+ format_rules = {
104
+ "URL": lambda x: f"https://{x}" if not x.startswith(('http://', 'https://')) else x,
105
+ "Email": lambda x: f"mailto:{x}",
106
+ "Phone": lambda x: f"tel:{x}",
107
+ "SMS": lambda x: f"sms:{x}",
108
+ "WhatsApp": lambda x: f"whatsapp://send?text={x}",
109
+ "Location": lambda x: f"geo:{x}",
110
+ "Wi-Fi": lambda x: f"WIFI:S:{x};;",
111
+ "Text": lambda x: x,
112
+ "vCard": lambda x: f"BEGIN:VCARD\nVERSION:3.0\n{x}\nEND:VCARD"
113
+ }
114
+
115
+ return format_rules[qr_type](content.strip())
116
 
117
  # 파일 정리 함수
118
  def cleanup_old_files(directory, max_files):
119
+ files = [f for f in os.listdir(directory) if f.endswith('.png')]
120
+ if len(files) > max_files:
121
+ files.sort(key=lambda x: os.path.getctime(os.path.join(directory, x)))
122
+ for f in files[:-max_files]:
123
+ try:
124
+ os.remove(os.path.join(directory, f))
125
+ except:
126
+ continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  def format_example_text(qr_type):
129
+ examples = {
130
+ "URL": "• Direct URL: https://example.com\n• Without https: example.com",
131
+ "Email": "• Basic: [email protected]\n• With subject: [email protected]?subject=Hello",
132
+ "Phone": "• International: +1234567890\n• Local: 01012345678",
133
+ "SMS": "• Basic: +1234567890\n• With message: +1234567890?body=Hello",
134
+ "WhatsApp": "• Message: Hello World!\n• With number: +1234567890:Hello",
135
+ "Location": "• Coordinates: 37.7749,-122.4194\n• With zoom: 37.7749,-122.4194,15z",
136
+ "Wi-Fi": "• Network name only: MyWiFiNetwork\n• With password: WIFI:S:MyNetwork;P:password;;",
137
+ "Text": "• Simple text: Hello World!\n• Multiple lines: Line 1\\nLine 2",
138
+ "vCard": "• Basic:\nFN:John Doe\nTEL:+1234567890\nEMAIL:[email protected]\n• Extended:\nFN:John Doe\nTEL:+1234567890\nEMAIL:[email protected]\nADR:;;123 Street;City;State;12345;Country"
139
+ }
140
+ return examples.get(qr_type, "Enter your content here...")
141
 
 
142
  # Gradio 인터페이스 생성
143
  def create_interface():
144
+ theme = gr.themes.Soft(
145
+ primary_hue="blue",
146
+ secondary_hue="indigo",
147
+ ).set(
148
+ body_background_fill="*neutral_50",
149
+ block_background_fill="*neutral_100",
150
+ button_primary_background_fill="*primary_500",
151
+ )
152
+
153
+ with gr.Blocks(theme=theme, title="QR Canvas") as demo:
154
+ gr.Markdown(
155
+ """
156
+ # 🎯 QR CANVAS
157
+ Create customized QR codes for various purposes with professional styling options.
158
+ """
159
+ )
160
+
161
+ gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fginipick-QR-Canvas.hf.space">
162
+ <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fginipick-QR-Canvas.hf.space&countColor=%23263759" />
163
+ </a>""")
164
+
165
+ with gr.Row():
166
+ with gr.Column(scale=2):
167
+ qr_type = gr.Dropdown(
168
+ choices=["URL", "Email", "Phone", "SMS", "WhatsApp", "Location", "Wi-Fi", "Text", "vCard"],
169
+ value="URL",
170
+ label="QR Code Type"
171
+ )
172
+
173
+ content = gr.Textbox(
174
+ label="Content",
175
+ placeholder="Enter your content here...",
176
+ lines=3
177
+ )
178
+
179
+ example_format = gr.Textbox(
180
+ value=format_example_text("URL"),
181
+ label="Format Examples",
182
+ interactive=False,
183
+ lines=6
184
+ )
185
+
186
+ with gr.Row():
187
+ fill_color = gr.ColorPicker(
188
+ label="QR Code Color",
189
+ value="#000000"
190
+ )
191
+ back_color = gr.ColorPicker(
192
+ label="Background Color",
193
+ value="#FFFFFF"
194
+ )
195
+
196
+ with gr.Row():
197
+ box_size = gr.Slider(
198
+ minimum=1,
199
+ maximum=20,
200
+ value=10,
201
+ step=1,
202
+ label="QR Code Size"
203
+ )
204
+ border_size = gr.Slider(
205
+ minimum=0,
206
+ maximum=10,
207
+ value=4,
208
+ step=1,
209
+ label="Border Size"
210
+ )
211
+
212
+ error_correction = gr.Dropdown(
213
+ choices=[
214
+ "Low (7%)",
215
+ "Medium (15%)",
216
+ "Quartile (25%)",
217
+ "High (30%)"
218
+ ],
219
+ value="Medium (15%)",
220
+ label="Error Correction Level"
221
+ )
222
+
223
+ border_decoration = gr.Textbox(
224
+ label="Border Decoration Prompt",
225
+ placeholder="Enter decoration style (e.g., flowers, simple, modern)",
226
+ value="flowers"
227
+ )
228
+
229
+ generate_btn = gr.Button(
230
+ "Generate QR Code",
231
+ variant="primary"
232
+ )
233
+
234
+ with gr.Column(scale=1):
235
+ output_image = gr.Image(
236
+ label="Generated QR Code",
237
+ type="filepath"
238
+ )
239
+ output_data = gr.Textbox(
240
+ label="Formatted Data",
241
+ interactive=False
242
+ )
243
+
244
+ def update_example(qr_type):
245
+ return format_example_text(qr_type)
246
+
247
+ qr_type.change(
248
+ fn=update_example,
249
+ inputs=[qr_type],
250
+ outputs=example_format
251
+ )
252
+
253
+ generate_btn.click(
254
+ fn=create_qr,
255
+ inputs=[
256
+ content,
257
+ qr_type,
258
+ fill_color,
259
+ back_color,
260
+ box_size,
261
+ border_size,
262
+ error_correction,
263
+ border_decoration
264
+ ],
265
+ outputs=[output_image, output_data]
266
+ )
267
+
268
+ gr.Markdown(
269
+ """
270
+ ### 📝 Instructions
271
+ 1. Select the QR code type from the dropdown menu
272
+ 2. Enter your content following the format examples shown
273
+ 3. Customize the appearance using the color pickers and sliders
274
+ 4. Click 'Generate QR Code' to create your custom QR code
275
+
276
+ ### 💡 Tips
277
+ - Use higher error correction levels for better scan reliability
278
+ - Ensure sufficient contrast between QR code and background colors
279
+ - Keep the content concise for better readability
280
+ - Follow the format examples for best results
281
+ """
282
+ )
283
+
284
+ return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
  if __name__ == "__main__":
287
  try:
 
288
  os.makedirs("qrfile", exist_ok=True)
 
 
289
  demo = create_interface()
290
  demo.launch(
291
+ server_name="0.0.0.0",
292
+ server_port=7860,
293
+ share=True,
294
+ debug=True
295
  )
296
  except Exception as e:
297
  print(f"Error starting the application: {e}")