arj7192 commited on
Commit
36f24b2
·
verified ·
1 Parent(s): 264c783

Delete fonts/app.py

Browse files
Files changed (1) hide show
  1. fonts/app.py +0 -575
fonts/app.py DELETED
@@ -1,575 +0,0 @@
1
- import spaces
2
- import os
3
- import gradio as gr
4
- import easyocr
5
- import numpy as np
6
- import cv2
7
- import base64
8
- import torch
9
- from shapely import Polygon
10
- from ultralytics import YOLO
11
-
12
- from io import BytesIO
13
- from openai import OpenAI
14
- from PIL import Image, ImageDraw, ImageFont
15
-
16
- from diffusers.utils import load_image, check_min_version
17
- from controlnet_flux import FluxControlNetModel
18
- from transformer_flux import FluxTransformer2DModel
19
- from pipeline_flux_controlnet_inpaint import FluxControlNetInpaintingPipeline
20
-
21
- import huggingface_hub
22
- huggingface_hub.login(os.getenv('HF_TOKEN_FLUX'))
23
-
24
- bubble_detection_model = YOLO("speech_bubble_model.pt")
25
-
26
- language_to_ocr = {
27
- 'Simplified Chinese': 'ch_sim',
28
- 'Traditional Chinese': 'ch_tra',
29
- 'Korean': 'ko',
30
- 'Japanese': 'ja',
31
- 'English': 'en',
32
- }
33
-
34
- OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
35
-
36
- MARKDOWN = """
37
- # Made by Nativ
38
- """
39
-
40
- check_min_version("0.30.2")
41
- transformer = FluxTransformer2DModel.from_pretrained(
42
- "black-forest-labs/FLUX.1-dev", subfolder='transformer', torch_dytpe=torch.bfloat16
43
- )
44
-
45
- cuda_device =torch.device("cuda")
46
- # Build pipeline
47
- controlnet = FluxControlNetModel.from_pretrained("alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta", torch_dtype=torch.bfloat16)
48
- pipe = FluxControlNetInpaintingPipeline.from_pretrained(
49
- "black-forest-labs/FLUX.1-dev",
50
- controlnet=controlnet,
51
- transformer=transformer,
52
- torch_dtype=torch.bfloat16
53
- ).to(cuda_device)
54
- pipe.transformer.to(torch.bfloat16)
55
- pipe.controlnet.to(torch.bfloat16)
56
-
57
-
58
- def localize_boxes(merged_results, img_boxes, source_language, target_language):
59
- # Convert image to base64
60
- buffered = BytesIO()
61
- img_boxes.save(buffered, format="PNG")
62
- img_str = base64.b64encode(buffered.getvalue()).decode()
63
-
64
- print(merged_results)
65
-
66
- prompt = f"""You are an expert translator and localization specialist with deep understanding of both {source_language} and {target_language} cultures.
67
-
68
- Task: Translate the detected text while preserving the cultural context and maintaining visual harmony. Make the results in capital letters.
69
-
70
- Source Text and Coordinates:
71
- {merged_results}
72
-
73
- Requirements:
74
- 1. Maintain the original meaning and tone while adapting to {target_language} cultural context
75
- 2. Keep translations concise and visually balanced (similar character length when possible)
76
- 3. Preserve any:
77
- - Brand names
78
- - Product names
79
- - Technical terms
80
- - Numbers and units
81
- 4. Consider the visual context from the provided image
82
- 5. Use appropriate formality level for {target_language}
83
- 6. Maintain any special formatting (if present)
84
-
85
- Format your response EXACTLY as a JSON-like list of dictionaries. Keep the box coordinates EXACTLY as they are, do not change them, only translate the text.
86
- [{{'box': [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], 'text': 'translated_text'}}]
87
-
88
- Important: Only output the JSON format above, no explanations or additional text."""
89
-
90
- client = OpenAI(api_key=OPENAI_API_KEY)
91
-
92
- response = client.chat.completions.create(
93
- model="gpt-4o",
94
- messages=[
95
- {
96
- "role": "user",
97
- "content": [
98
- {"type": "text", "text": prompt},
99
- {
100
- "type": "image_url",
101
- "image_url": {
102
- "url": f"data:image/png;base64,{img_str}"
103
- }
104
- }
105
- ]
106
- }
107
- ],
108
- max_tokens=1000,
109
- temperature=0
110
- )
111
-
112
- try:
113
- translation_text = response.choices[0].message.content
114
- translation_text = translation_text.replace("```json", "").replace("```", "").strip()
115
- translated_results = eval(translation_text)
116
- return translated_results
117
- except Exception as e:
118
- print(f"Error parsing GPT-4o response: {e}")
119
- return merged_results
120
-
121
- def merge_boxes(boxes, image_shape, distance_threshold=10):
122
- """Merge boxes that are close to each other and return their associated text"""
123
- if not boxes:
124
- return []
125
-
126
- # Extract boxes and create mapping to original data
127
- boxes_only = [box[0] for box in boxes]
128
- texts = [box[1] for box in boxes] # Extract the text content
129
-
130
- # Create a binary mask of all boxes
131
- height, width = image_shape[:2]
132
- mask = np.zeros((height, width), dtype=np.uint8)
133
-
134
- # Draw all boxes on mask and create a mapping of pixel positions to box indices
135
- box_indices_map = {} # Will store which original box each pixel belongs to
136
- for idx, coords in enumerate(boxes_only):
137
- pts = np.array(coords, dtype=np.int32)
138
- cv2.fillPoly(mask, [pts], 255)
139
- # Store the indices of boxes for each filled pixel
140
- y_coords, x_coords = np.where(mask == 255)
141
- for y, x in zip(y_coords, x_coords):
142
- if (y, x) not in box_indices_map:
143
- box_indices_map[(y, x)] = []
144
- box_indices_map[(y, x)].append(idx)
145
-
146
- # Dilate to connect nearby components
147
- kernel = np.ones((distance_threshold, distance_threshold), np.uint8)
148
- dilated = cv2.dilate(mask, kernel, iterations=1)
149
-
150
- # Find connected components
151
- num_labels, labels = cv2.connectedComponents(dilated)
152
-
153
- # Create new merged boxes with their associated text
154
- merged_results = []
155
- for label in range(1, num_labels): # Skip background (0)
156
- points = np.where(labels == label)
157
- if len(points[0]): # If component is not empty
158
- y0, x0 = points[0].min(), points[1].min()
159
- y1, x1 = points[0].max(), points[1].max()
160
- # Add small padding
161
- x0 = max(0, x0 - 2)
162
- y0 = max(0, y0 - 2)
163
- x1 = min(width, x1 + 2)
164
- y1 = min(height, y1 + 2)
165
-
166
- # Find all original boxes that overlap with this merged box
167
- box_indices = set()
168
- for y in range(y0, y1+1):
169
- for x in range(x0, x1+1):
170
- if (y, x) in box_indices_map:
171
- box_indices.update(box_indices_map[(y, x)])
172
-
173
- # Combine text from all overlapping boxes
174
- combined_text = ' '.join([texts[idx] for idx in box_indices])
175
-
176
- merged_results.append({
177
- 'box': [[x0, y0], [x1, y0], [x1, y1], [x0, y1]],
178
- 'text': combined_text
179
- })
180
- return merged_results
181
-
182
- def is_box_inside_yolo(box, yolo_boxes, overlap_threshold=0.5):
183
- """
184
- Check if a text box is inside any of the YOLO-detected speech bubbles.
185
- box: [[x0,y0], [x1,y0], [x1,y1], [x0,y1]]
186
- yolo_boxes: list of YOLO boxes in xywh format
187
- overlap_threshold: minimum overlap ratio required to consider the text inside bubble
188
- """
189
- text_poly = Polygon(box)
190
- text_area = text_poly.area
191
-
192
- for yolo_box in yolo_boxes:
193
- x_center, y_center, width, height = yolo_box
194
- x1, y1 = x_center - width / 2, y_center - height / 2
195
- x2, y2 = x_center + width / 2, y_center + height / 2
196
- bubble_box = [[x1, y1], [x2, y1], [x2, y2], [x1, y2]]
197
- bubble_poly = Polygon(bubble_box)
198
-
199
- # Calculate intersection
200
- if text_poly.intersects(bubble_poly):
201
- intersection = text_poly.intersection(bubble_poly)
202
- overlap_ratio = intersection.area / text_area
203
- if overlap_ratio >= overlap_threshold:
204
- return True
205
-
206
- return False
207
-
208
- def remove_text_regions(image, boxes, yolo_boxes):
209
- """Fill detected text regions with white"""
210
- img_removed = image.copy()
211
- mask = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
212
-
213
- # Fill all detected boxes with white
214
- for box in boxes:
215
- pts = np.array(box[0], dtype=np.int32)
216
- if is_box_inside_yolo(box[0], yolo_boxes):
217
- cv2.fillPoly(img_removed, [pts], (255, 255, 255, 255))
218
- cv2.fillPoly(mask, [pts], (255, 255, 255, 255))
219
-
220
- img_removed_rgb = cv2.cvtColor(img_removed, cv2.COLOR_BGR2RGB)
221
-
222
- return img_removed_rgb, mask
223
-
224
- def fit_text_to_box(text, merged_coordinates, angle=0, font_path):
225
- """
226
- Adjusts the text to fit optimally inside the given box dimensions.
227
-
228
- Args:
229
- text (str): The text to fit.
230
- box_size (tuple): A tuple (width, height) specifying the box dimensions.
231
- font_path (str): Path to the font file to be used.
232
-
233
- Returns:
234
- PIL.Image: An image with the text fitted inside the box.
235
- """
236
- width, height = merged_coordinates[1][0] - merged_coordinates[0][0], merged_coordinates[2][1] - merged_coordinates[1][1]
237
- font_size = 1
238
-
239
- # Create a dummy image to measure text size
240
- dummy_image = Image.new('RGB', (width, height))
241
- draw = ImageDraw.Draw(dummy_image)
242
-
243
- # Load a small font initially
244
- font = ImageFont.truetype(font_path, font_size)
245
-
246
- while True:
247
- # Break text into lines that fit within the width
248
- words = text.split()
249
- lines = []
250
- current_line = []
251
- for word in words:
252
- test_line = " ".join(current_line + [word])
253
- test_width = draw.textlength(test_line, font=font)
254
- if test_width <= width:
255
- current_line.append(word)
256
- else:
257
- lines.append(" ".join(current_line))
258
- current_line = [word]
259
- if current_line:
260
- lines.append(" ".join(current_line))
261
-
262
- # Calculate total height required for the lines
263
- line_height = font.getbbox('A')[3] + 5 # Add line spacing
264
- total_height = len(lines) * line_height
265
-
266
- # Check if text fits within the height
267
- if total_height > height or any(draw.textlength(line, font=font) > width for line in lines):
268
- break
269
-
270
- # Increment font size
271
- font_size += 1
272
- font = ImageFont.truetype(font_path, font_size)
273
-
274
- # Use the last fitting font
275
- font_size -= 1
276
- font = ImageFont.truetype(font_path, font_size)
277
-
278
- # Create the final image with a transparent background
279
- image = Image.new('RGBA', (width, height), (255, 255, 255, 0))
280
- draw = ImageDraw.Draw(image)
281
-
282
- # Center the text vertically and horizontally
283
- lines = []
284
- current_line = []
285
- for word in text.split():
286
- test_line = " ".join(current_line + [word])
287
- if draw.textlength(test_line, font=font) <= width:
288
- current_line.append(word)
289
- else:
290
- lines.append(" ".join(current_line))
291
- current_line = [word]
292
- if current_line:
293
- lines.append(" ".join(current_line))
294
-
295
- line_height = font.getbbox('A')[3] + 5
296
- total_text_height = len(lines) * line_height
297
- y_offset = (height - total_text_height) // 2
298
-
299
- for line in lines:
300
- text_width = draw.textlength(line, font=font)
301
- x_offset = (width - text_width) // 2
302
- draw.text((x_offset, y_offset), line, font=font, fill="black")
303
- y_offset += line_height
304
-
305
- rotated_image = image.rotate(0, expand=True)
306
-
307
- return rotated_image
308
-
309
- def shorten_box(merged_coordinates, pct=0):
310
- # Calculate the center of the box
311
- center_x = (merged_coordinates[0][0] + merged_coordinates[2][0]) / 2
312
- center_y = (merged_coordinates[0][1] + merged_coordinates[2][1]) / 2
313
-
314
- # Calculate the width and height of the box
315
- width = merged_coordinates[1][0] - merged_coordinates[0][0]
316
- height = merged_coordinates[2][1] - merged_coordinates[1][1]
317
-
318
- # Shrink width and height by 10%
319
- new_width = width * 1-pct/100.
320
- new_height = height * 1-pct/100.
321
-
322
- # Calculate the new coordinates
323
- merged_coordinates_new = np.array([
324
- [center_x - new_width / 2, center_y - new_height / 2], # Top-left
325
- [center_x + new_width / 2, center_y - new_height / 2], # Top-right
326
- [center_x + new_width / 2, center_y + new_height / 2], # Bottom-right
327
- [center_x - new_width / 2, center_y + new_height / 2] # Bottom-left
328
- ], dtype=int)
329
-
330
- return merged_coordinates_new
331
-
332
-
333
- def detect_and_show_text(reader, image):
334
- """Detect text and show bounding boxes"""
335
- if isinstance(image, Image.Image):
336
- img_array = np.array(image)
337
- else:
338
- img_array = image
339
-
340
- # Get YOLO results first
341
- yolo_results = bubble_detection_model(img_array, conf=7)[0]
342
- yolo_boxes = yolo_results.boxes.xywh.cpu().numpy() # Get YOLO boxes in xywh format
343
-
344
- # Detect text
345
- results = reader.readtext(img_array, text_threshold=0.6)
346
-
347
- # Create visualization
348
- img_boxes = img_array.copy()
349
-
350
- # Ensure we're working with RGB
351
- if len(img_array.shape) == 3:
352
- if img_array.shape[2] == 3: # If it's a 3-channel image
353
- img_boxes = cv2.cvtColor(img_boxes, cv2.COLOR_BGR2RGB)
354
-
355
- # Draw original EasyOCR boxes on img_boxes
356
- for result in results:
357
- pts = np.array(result[0], dtype=np.int32)
358
- cv2.polylines(img_boxes, [pts], isClosed=True, color=(0, 255, 0), thickness=2) # Draw original boxes in green
359
-
360
- # Remove text and merge boxes for visualization
361
- img_removed, mask = remove_text_regions(img_array, results, yolo_boxes)
362
- merged_results = merge_boxes(results, img_array.shape)
363
-
364
- # Draw merged detection boxes and text (if needed)
365
- for merged_result in merged_results:
366
- pts = np.array(merged_result['box'], dtype=np.int32)
367
- # Color the box red if inside bubble, blue if outside
368
- color = (0, 0, 255) if is_box_inside_yolo(merged_result['box'], yolo_boxes) else (255, 0, 0)
369
- cv2.polylines(img_boxes, [pts], True, color, 2) # Draw merged boxes in red or blue
370
-
371
- # Convert to RGB
372
- img_boxes_rgb = cv2.cvtColor(img_boxes, cv2.COLOR_BGR2RGB)
373
- img_removed_rgb = cv2.cvtColor(img_removed, cv2.COLOR_BGR2RGB)
374
- mask_rgba = cv2.cvtColor(mask, cv2.COLOR_RGB2RGBA)
375
-
376
- # Get YOLO visualization without labels
377
- bubbles_img = yolo_results.plot(labels=False)
378
-
379
- # Convert to PIL Images
380
- img_boxes_pil = Image.fromarray(img_boxes_rgb)
381
- img_removed_pil = Image.fromarray(img_removed_rgb)
382
- bubbles_img_pil = Image.fromarray(bubbles_img)
383
- mask_pil = Image.fromarray(mask_rgba)
384
-
385
- return img_boxes_pil, bubbles_img_pil, img_removed_pil, merged_results, mask_pil
386
-
387
-
388
- def position_text_back(text, merged_coordinates, inpainted_image, font_path):
389
- coords = shorten_box(merged_coordinates)
390
- top_left_coords = coords[0]
391
- text_image = fit_text_to_box(text, coords, font_path)
392
-
393
- # Create a transparent layer to blend
394
- layer = Image.new("RGBA", inpainted_image.size, (0, 0, 0, 0))
395
-
396
- # Paste the text image onto the transparent layer at the specified position
397
- layer.paste(text_image, tuple(top_left_coords), mask=text_image)
398
-
399
- # Ensure both images are in "RGBA" mode
400
- if inpainted_image.mode != "RGBA":
401
- inpainted_image = inpainted_image.convert("RGBA")
402
- if layer.mode != "RGBA":
403
- layer = layer.convert("RGBA")
404
-
405
- # Blend the transparent layer with the inpainted image
406
- blended_image = Image.alpha_composite(inpainted_image, layer)
407
-
408
- return blended_image
409
-
410
- @spaces.GPU()
411
- def process(image, mask,
412
- prompt="background",
413
- negative_prompt="text",
414
- controlnet_conditioning_scale=0.9,
415
- guidance_scale=3.5,
416
- seed=124,
417
- num_inference_steps=10,
418
- true_guidance_scale=3.5
419
- ):
420
- size = (768, 768)
421
- image_pil = Image.fromarray(image)
422
- image_or = image_pil.copy()
423
-
424
- image_pil = image_pil.convert("RGB").resize(size)
425
- mask = mask.convert("RGB").resize(size)
426
- generator = torch.Generator(device="cuda").manual_seed(seed)
427
- result = pipe(
428
- prompt=prompt,
429
- height=size[1],
430
- width=size[0],
431
- control_image=image_pil,
432
- control_mask=mask,
433
- num_inference_steps=num_inference_steps,
434
- generator=generator,
435
- controlnet_conditioning_scale=controlnet_conditioning_scale,
436
- guidance_scale=guidance_scale,
437
- negative_prompt=negative_prompt,
438
- true_guidance_scale=true_guidance_scale
439
- ).images[0]
440
-
441
- return result.resize((image_or.size[:2]))
442
-
443
-
444
- @spaces.GPU()
445
- def process_image(image, source_language, target_language, mode, font):
446
- """Main processing function for Gradio"""
447
- if image is None:
448
- return None, None, None, []
449
-
450
- # Initialize reader (equivalent to what handle_localization did)
451
- easy_ocr_lan = language_to_ocr.get(source_language, 'en')
452
- reader = easyocr.Reader([easy_ocr_lan], model_storage_directory='.', gpu=False)
453
-
454
- # Detect text and get results
455
- img_with_boxes, img_bubbles, img_removed_text, merged_results, mask = detect_and_show_text(reader, image)
456
-
457
- if mode == "Basic":
458
- img_inpainted = img_removed_text
459
- else:
460
- img_inpainted = process(image, mask)
461
-
462
- # Get translations
463
- translations = localize_boxes(
464
- merged_results,
465
- img_with_boxes,
466
- source_language,
467
- target_language
468
- )
469
-
470
- # Create initial result with translations
471
- final_result = img_inpainted.copy()
472
- for translation in translations:
473
- box = translation['box']
474
- text = translation['text']
475
- final_result = position_text_back(text, box, final_result, font_path=f"fonts/{font}.ttf")
476
-
477
- # Return all results directly (no need to store in session state)
478
- return img_with_boxes, img_bubbles, img_inpainted, final_result, translations, np.array(mask)
479
-
480
-
481
- def update_translations(image, edited_texts, translations_list, img_removed_text, font):
482
- """Update the image with edited translations"""
483
- if image is None or img_removed_text is None:
484
- return None
485
-
486
- # Convert numpy array back to PIL Image
487
- img_removed = Image.fromarray(img_removed_text)
488
- final_result = img_removed.copy()
489
-
490
- # Update the translations with edited texts
491
- for trans, new_text in zip(translations_list, edited_texts.split('\n')):
492
- trans['text'] = new_text.strip()
493
- box = trans['box']
494
- final_result = position_text_back(new_text, box, final_result, font_path=f"fonts/{font}.ttf")
495
-
496
- return np.array(final_result)
497
-
498
-
499
-
500
- with gr.Blocks(title="Nativ - Demo") as demo:
501
- # Store translations list in state
502
- translations_state = gr.State([])
503
-
504
- gr.Markdown("# Nativ - Demo")
505
-
506
- with gr.Row():
507
- with gr.Column():
508
- # Input components
509
- input_image = gr.Image(type="numpy", label="Upload Image")
510
- source_language = gr.Dropdown(
511
- choices=['Simplified Chinese', 'Traditional Chinese', 'Korean', 'Japanese', 'English'],
512
- value='Simplified Chinese',
513
- label="Source Language"
514
- )
515
- target_language = gr.Dropdown(
516
- choices=['English', 'Spanish', 'Chinese', 'Korean', 'French', 'Japanese'],
517
- value='English',
518
- label="Target Language"
519
- )
520
- # Toggle for mode selection
521
- localization_mode = gr.Radio(
522
- choices=["Basic", "Advanced"],
523
- value="Basic",
524
- label="Localization Mode"
525
- )
526
- font_selector_i = gr.Dropdown(
527
- choices=['Arial', 'Ldfcomicsansbold', 'Times New Roman', 'georgia', 'calibri', 'Verdana', 'omniscript_bold', 'helvetica'], # Add more fonts as needed
528
- value='omniscript_bold',
529
- label="Select Font"
530
- )
531
- process_btn = gr.Button("Localize")
532
-
533
- with gr.Column():
534
- # Output components
535
- speech_bubbles = gr.Image(type="numpy", label="Detected Speech Bubbles", interactive=False)
536
- detected_boxes = gr.Image(type="numpy", label="Detected Text Regions", interactive=False)
537
- removed_text = gr.Image(type="numpy", label="Removed Text", interactive=False)
538
- final_output = gr.Image(type="numpy", label="Final Result", interactive=False)
539
-
540
- # Translation editing section
541
- with gr.Row():
542
- translations_text = gr.Textbox(
543
- label="Edit Translations (one per line)",
544
- lines=5,
545
- placeholder="Edit translations here..."
546
- )
547
- font_selector_f = gr.Dropdown(
548
- choices=['Arial', 'Ldfcomicsansbold', 'Times New Roman', 'georgia', 'calibri', 'Verdana', 'omniscript_bold', 'helvetica'], # Add more fonts as needed
549
- value='Arial',
550
- label="Select Font"
551
- )
552
- update_btn = gr.Button("Apply Changes")
553
-
554
- def process_and_show_translations(image, source_lang, target_lang, mode, font):
555
- boxes, bubbles, removed, final, translations, mask = process_image(image, source_lang, target_lang, mode, font)
556
- # Extract just the texts and join with newlines
557
- texts = '\n'.join(t['text'] for t in translations)
558
- return boxes, bubbles, removed, final, texts, translations
559
-
560
- # Process button click
561
- process_btn.click(
562
- fn=process_and_show_translations,
563
- inputs=[input_image, source_language, target_language, localization_mode, font_selector_i],
564
- outputs=[detected_boxes, speech_bubbles, removed_text, final_output, translations_text, translations_state]
565
- )
566
-
567
- # Update translations button click
568
- update_btn.click(
569
- fn=update_translations,
570
- inputs=[input_image, translations_text, translations_state, removed_text, font_selector_f],
571
- outputs=final_output
572
- )
573
-
574
-
575
- demo.launch(debug=False, show_error=True,share=True)