taellinglin commited on
Commit
7b912e5
·
verified ·
1 Parent(s): 81f5032

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -25
app.py CHANGED
@@ -248,8 +248,15 @@ def predict_text(image: Image.Image):
248
 
249
 
250
  # New helper function: generate label images grid
251
- def generate_labels(font_file=None, num_labels: int = 20):
 
 
 
 
 
 
252
  global font_path
 
253
 
254
  try:
255
  if font_file:
@@ -257,44 +264,46 @@ def generate_labels(font_file=None, num_labels: int = 20):
257
  with open(font_file.name, "rb") as uploaded:
258
  with open(font_path, "wb") as f:
259
  f.write(uploaded.read())
260
-
261
- if font_path is None or not os.path.exists(font_path):
262
  font = ImageFont.load_default()
263
  else:
264
- font = ImageFont.truetype(font_path, 25)
265
 
266
- labels = ["".join(np.random.choice(list(CHARS), np.random.randint(4, 7))) for _ in range(num_labels)]
 
 
 
 
267
 
268
- cols = min(5, num_labels)
269
- rows = math.ceil(num_labels / cols)
270
- cell_w, cell_h = IMAGE_WIDTH, IMAGE_HEIGHT
 
 
271
 
272
- grid_img = Image.new("L", (cols * cell_w, rows * cell_h), color=255)
273
- draw = ImageDraw.Draw(grid_img)
274
 
275
- spacing = 0 # <-- spacing between characters
 
 
276
 
277
- for idx, label in enumerate(labels):
278
- x = (idx % cols) * cell_w
279
- y = (idx // cols) * cell_h + 10
280
 
281
- # Draw each character with spacing
282
- char_x = x + 10 # small left margin
283
- char_y = y + (cell_h - font.size) // 2
284
 
285
- for char in label:
286
- draw.text((char_x, char_y), char, font=font, fill=0)
287
- char_w = font.getbbox(char)[2] - font.getbbox(char)[0]
288
- char_x += char_w + spacing # move right with spacing
289
-
290
- return grid_img
291
 
292
  except Exception as e:
293
  print("Error in generate_labels:", e)
294
  error_img = Image.new("RGB", (512, 128), color=(255, 255, 255))
295
  draw = ImageDraw.Draw(error_img)
296
  draw.text((10, 50), f"Error: {str(e)}", fill=(255, 0, 0))
297
- return error_img
298
 
299
 
300
 
@@ -334,7 +343,12 @@ with gr.Blocks() as demo:
334
  gen_button = gr.Button("Generate Label Grid")
335
  label_image = gr.Image(label="Generated Labels", type="pil")
336
 
337
- gen_button.click(fn=generate_labels, inputs=[font_file_labels, num_labels], outputs=label_image)
 
 
 
 
 
338
 
339
 
340
 
 
248
 
249
 
250
  # New helper function: generate label images grid
251
+ CHARS = string.ascii_letters + string.digits + string.punctuation
252
+
253
+ FONT_SIZE = 32
254
+ PADDING = 8
255
+ LABEL_DIR = "./labels"
256
+
257
+ def generate_labels(font_file=None, num_labels: int = 25):
258
  global font_path
259
+ os.makedirs(LABEL_DIR, exist_ok=True)
260
 
261
  try:
262
  if font_file:
 
264
  with open(font_file.name, "rb") as uploaded:
265
  with open(font_path, "wb") as f:
266
  f.write(uploaded.read())
267
+ if not font_file or not os.path.exists(font_path):
 
268
  font = ImageFont.load_default()
269
  else:
270
+ font = ImageFont.truetype(font_path, FONT_SIZE)
271
 
272
+ images = []
273
+ labels = [
274
+ "".join(np.random.choice(list(CHARS), np.random.randint(4, 7)))
275
+ for _ in range(num_labels)
276
+ ]
277
 
278
+ for label in labels:
279
+ # Measure actual text bounding box
280
+ dummy_img = Image.new("L", (1, 1))
281
+ draw = ImageDraw.Draw(dummy_img)
282
+ bbox = draw.textbbox((0, 0), label, font=font)
283
 
284
+ text_width = bbox[2] - bbox[0]
285
+ text_height = bbox[3] - bbox[1]
286
 
287
+ # Compute final image size with padding
288
+ image_width = text_width + 2 * PADDING
289
+ image_height = text_height + 2 * PADDING
290
 
291
+ img = Image.new("L", (image_width, image_height), color=255)
292
+ draw = ImageDraw.Draw(img)
293
+ draw.text((PADDING, PADDING), label, font=font, fill=0)
294
 
295
+ filename = f"{LABEL_DIR}/{label}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}.png"
296
+ img.save(filename)
297
+ images.append(img)
298
 
299
+ return images
 
 
 
 
 
300
 
301
  except Exception as e:
302
  print("Error in generate_labels:", e)
303
  error_img = Image.new("RGB", (512, 128), color=(255, 255, 255))
304
  draw = ImageDraw.Draw(error_img)
305
  draw.text((10, 50), f"Error: {str(e)}", fill=(255, 0, 0))
306
+ return [error_img]
307
 
308
 
309
 
 
343
  gen_button = gr.Button("Generate Label Grid")
344
  label_image = gr.Image(label="Generated Labels", type="pil")
345
 
346
+ gen_button.click(
347
+ fn=generate_labels,
348
+ inputs=[font_file_labels, num_labels],
349
+ outputs=gr.Gallery(label="Label Images", show_label=True)
350
+ )
351
+
352
 
353
 
354