Severian commited on
Commit
5800e85
·
verified ·
1 Parent(s): 44a693b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -22
app.py CHANGED
@@ -70,7 +70,7 @@ SAMPLER_MAP = {
70
  "DEIS": lambda config: DEISMultistepScheduler.from_config(config),
71
  }
72
 
73
- def scan_qr_code(image):
74
  # Convert gradio image to PIL Image if necessary
75
  if isinstance(image, np.ndarray):
76
  image = Image.fromarray(image)
@@ -82,7 +82,7 @@ def scan_qr_code(image):
82
  np_image = np.array(gray_image)
83
 
84
  # Preprocess the image
85
- _, binary_image = cv2.threshold(np_image, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
86
 
87
  # List to store successful scans
88
  successful_scans = []
@@ -92,7 +92,7 @@ def scan_qr_code(image):
92
  qr = qrcode.QRCode()
93
  qr.add_data('')
94
  qr.decode(gray_image)
95
- successful_scans.append(qr.data.decode('utf-8'))
96
  except Exception as e:
97
  print(f"qrcode library failed: {str(e)}")
98
 
@@ -101,7 +101,7 @@ def scan_qr_code(image):
101
  qr_detector = cv2.QRCodeDetector()
102
  retval, decoded_info, points, straight_qrcode = qr_detector.detectAndDecodeMulti(np_image)
103
  if retval:
104
- successful_scans.extend(decoded_info)
105
  except Exception as e:
106
  print(f"OpenCV failed: {str(e)}")
107
 
@@ -110,13 +110,13 @@ def scan_qr_code(image):
110
  reader = BarCodeReader()
111
  results = reader.decode(np_image)
112
  if results:
113
- successful_scans.extend([result.parsed for result in results])
114
 
115
  # If no results, try with the binary image
116
  if not results:
117
  results = reader.decode(binary_image)
118
  if results:
119
- successful_scans.extend([result.parsed for result in results])
120
  except Exception as e:
121
  print(f"zxing-cpp failed: {str(e)}")
122
 
@@ -128,12 +128,12 @@ def scan_qr_code(image):
128
  reader = BarCodeReader()
129
  results = reader.decode(temp_file.name)
130
  if results:
131
- successful_scans.extend([result.parsed for result in results])
132
  os.unlink(temp_file.name)
133
  except Exception as e:
134
  print(f"Temporary file scanning failed: {str(e)}")
135
 
136
- return successful_scans[0] if successful_scans else None
137
 
138
  @spaces.GPU()
139
  def inference(
@@ -148,6 +148,7 @@ def inference(
148
  qrcode_image: Image.Image | None = None,
149
  use_qr_code_as_init_image = True,
150
  sampler = "DPM++ Karras SDE",
 
151
  ):
152
  try:
153
  if prompt is None or prompt == "":
@@ -193,11 +194,15 @@ def inference(
193
  strength=float(strength),
194
  num_inference_steps=50,
195
  )
196
- return out.images[0] # type: ignore
 
 
 
 
197
  except Exception as e:
198
  print(f"Error in inference: {str(e)}")
199
  # Return a blank image in case of an error
200
- return Image.new('RGB', (768, 768), color='white')
201
 
202
 
203
 
@@ -205,35 +210,25 @@ with gr.Blocks(theme=gr.themes.Monochrome()) as blocks:
205
  gr.Markdown(
206
  """
207
  ![Yamamoto Logo](https://cdn-uploads.huggingface.co/production/uploads/64740cf7485a7c8e1bd51ac9/_VyYxp5qE_nRZ_LJqBxmL.webp)
208
-
209
  # 🎨 Yamamoto QR Code Art Generator
210
-
211
  ## Transform Your QR Codes into Brand Masterpieces
212
-
213
  Welcome to Yamamoto's innovative QR Code Art Generator! This cutting-edge tool empowers our creative team to craft
214
  visually stunning, on-brand QR codes that perfectly blend functionality with artistic expression.
215
-
216
  ## 🚀 How It Works:
217
-
218
  1. **Enter Your QR Code Content**: Start by inputting the URL or text for your QR code.
219
  2. **Craft Your Prompt**: Describe the artistic style or theme you envision for your QR code.
220
  3. **Fine-tune with Advanced Settings**: Adjust parameters to perfect your creation (see tips below).
221
  4. **Generate and Iterate**: Click 'Run' to create your art, then refine as needed.
222
-
223
  ## 🌟 Tips for Spectacular Results:
224
-
225
  - **Artistic Freedom**: Set between 0.8 and 0.95 for a balance of creativity and scannability.
226
  - **QR Code Visibility**: Aim for 0.6 to 2.0 to ensure your code is both artistic and functional.
227
  - **Prompt Crafting**: Use vivid, specific descriptions that align with your brand identity.
228
  - **Experimentation**: Don't hesitate to try different settings and prompts to find your perfect style!
229
-
230
  ## 🎭 Prompt Ideas to Spark Your Creativity:
231
-
232
  - "A serene Japanese garden with cherry blossoms and a koi pond"
233
  - "A futuristic cityscape with neon lights and flying cars"
234
  - "An abstract painting with swirling colors and geometric shapes"
235
  - "A vintage-style travel poster featuring iconic landmarks"
236
-
237
  Remember, the magic lies in the details of your prompt and the fine-tuning of your settings.
238
  Happy creating!
239
  """
@@ -373,6 +368,22 @@ with gr.Blocks(theme=gr.themes.Monochrome()) as blocks:
373
  Try **-1** if you want to explore and generate different designs. If you find something you really love, write down the seed number and use it again to recreate the same design.
374
  """
375
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  with gr.Row():
377
  run_btn = gr.Button("🎨 Create Your QR Art", variant="primary")
378
 
@@ -428,10 +439,11 @@ with gr.Blocks(theme=gr.themes.Monochrome()) as blocks:
428
  qr_code_image,
429
  use_qr_code_as_init_image,
430
  sampler,
 
431
  ],
432
- outputs=[result_image],
433
  concurrency_limit=20
434
  )
435
 
436
  blocks.queue(max_size=20,api_open=False)
437
- blocks.launch(share=bool(os.environ.get("SHARE", False)), show_api=True)
 
70
  "DEIS": lambda config: DEISMultistepScheduler.from_config(config),
71
  }
72
 
73
+ def scan_qr_code(image, sensitivity=0.5):
74
  # Convert gradio image to PIL Image if necessary
75
  if isinstance(image, np.ndarray):
76
  image = Image.fromarray(image)
 
82
  np_image = np.array(gray_image)
83
 
84
  # Preprocess the image
85
+ _, binary_image = cv2.threshold(np_image, int(255 * sensitivity), 255, cv2.THRESH_BINARY)
86
 
87
  # List to store successful scans
88
  successful_scans = []
 
92
  qr = qrcode.QRCode()
93
  qr.add_data('')
94
  qr.decode(gray_image)
95
+ successful_scans.append(("qrcode library", qr.data.decode('utf-8')))
96
  except Exception as e:
97
  print(f"qrcode library failed: {str(e)}")
98
 
 
101
  qr_detector = cv2.QRCodeDetector()
102
  retval, decoded_info, points, straight_qrcode = qr_detector.detectAndDecodeMulti(np_image)
103
  if retval:
104
+ successful_scans.extend([("OpenCV", info) for info in decoded_info if info])
105
  except Exception as e:
106
  print(f"OpenCV failed: {str(e)}")
107
 
 
110
  reader = BarCodeReader()
111
  results = reader.decode(np_image)
112
  if results:
113
+ successful_scans.extend([("zxing-cpp", result.parsed) for result in results])
114
 
115
  # If no results, try with the binary image
116
  if not results:
117
  results = reader.decode(binary_image)
118
  if results:
119
+ successful_scans.extend([("zxing-cpp (binary)", result.parsed) for result in results])
120
  except Exception as e:
121
  print(f"zxing-cpp failed: {str(e)}")
122
 
 
128
  reader = BarCodeReader()
129
  results = reader.decode(temp_file.name)
130
  if results:
131
+ successful_scans.extend([("zxing-cpp (file)", result.parsed) for result in results])
132
  os.unlink(temp_file.name)
133
  except Exception as e:
134
  print(f"Temporary file scanning failed: {str(e)}")
135
 
136
+ return successful_scans
137
 
138
  @spaces.GPU()
139
  def inference(
 
148
  qrcode_image: Image.Image | None = None,
149
  use_qr_code_as_init_image = True,
150
  sampler = "DPM++ Karras SDE",
151
+ verify_sensitivity: float = 0.5,
152
  ):
153
  try:
154
  if prompt is None or prompt == "":
 
194
  strength=float(strength),
195
  num_inference_steps=50,
196
  )
197
+
198
+ # Verify the generated QR code
199
+ verify_result = scan_qr_code(out.images[0], sensitivity=verify_sensitivity)
200
+
201
+ return out.images[0], verify_result
202
  except Exception as e:
203
  print(f"Error in inference: {str(e)}")
204
  # Return a blank image in case of an error
205
+ return Image.new('RGB', (768, 768), color='white'), []
206
 
207
 
208
 
 
210
  gr.Markdown(
211
  """
212
  ![Yamamoto Logo](https://cdn-uploads.huggingface.co/production/uploads/64740cf7485a7c8e1bd51ac9/_VyYxp5qE_nRZ_LJqBxmL.webp)
 
213
  # 🎨 Yamamoto QR Code Art Generator
 
214
  ## Transform Your QR Codes into Brand Masterpieces
 
215
  Welcome to Yamamoto's innovative QR Code Art Generator! This cutting-edge tool empowers our creative team to craft
216
  visually stunning, on-brand QR codes that perfectly blend functionality with artistic expression.
 
217
  ## 🚀 How It Works:
 
218
  1. **Enter Your QR Code Content**: Start by inputting the URL or text for your QR code.
219
  2. **Craft Your Prompt**: Describe the artistic style or theme you envision for your QR code.
220
  3. **Fine-tune with Advanced Settings**: Adjust parameters to perfect your creation (see tips below).
221
  4. **Generate and Iterate**: Click 'Run' to create your art, then refine as needed.
 
222
  ## 🌟 Tips for Spectacular Results:
 
223
  - **Artistic Freedom**: Set between 0.8 and 0.95 for a balance of creativity and scannability.
224
  - **QR Code Visibility**: Aim for 0.6 to 2.0 to ensure your code is both artistic and functional.
225
  - **Prompt Crafting**: Use vivid, specific descriptions that align with your brand identity.
226
  - **Experimentation**: Don't hesitate to try different settings and prompts to find your perfect style!
 
227
  ## 🎭 Prompt Ideas to Spark Your Creativity:
 
228
  - "A serene Japanese garden with cherry blossoms and a koi pond"
229
  - "A futuristic cityscape with neon lights and flying cars"
230
  - "An abstract painting with swirling colors and geometric shapes"
231
  - "A vintage-style travel poster featuring iconic landmarks"
 
232
  Remember, the magic lies in the details of your prompt and the fine-tuning of your settings.
233
  Happy creating!
234
  """
 
368
  Try **-1** if you want to explore and generate different designs. If you find something you really love, write down the seed number and use it again to recreate the same design.
369
  """
370
  )
371
+
372
+ verify_sensitivity = gr.Slider(
373
+ minimum=0.1,
374
+ maximum=1.0,
375
+ step=0.05,
376
+ value=0.5,
377
+ visible=True
378
+ label="Verify Sensitivity",
379
+ )
380
+ gr.Markdown(
381
+ """
382
+ **Verify Sensitivity** controls how sensitive the QR code scanner is when verifying the generated image.
383
+ A lower value (closer to 0.1) makes the scanner more sensitive and able to detect less clear QR codes,
384
+ while a higher value (closer to 1.0) requires clearer, more distinct QR codes to be detected.
385
+ """
386
+ )
387
  with gr.Row():
388
  run_btn = gr.Button("🎨 Create Your QR Art", variant="primary")
389
 
 
439
  qr_code_image,
440
  use_qr_code_as_init_image,
441
  sampler,
442
+ verify_sensitivity,
443
  ],
444
+ outputs=[result_image, scan_result],
445
  concurrency_limit=20
446
  )
447
 
448
  blocks.queue(max_size=20,api_open=False)
449
+ blocks.launch(share=bool(os.environ.get("SHARE", False)), show_api=True)