prithivMLmods commited on
Commit
4148e9b
·
verified ·
1 Parent(s): 81fbde1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +248 -330
app.py CHANGED
@@ -6,152 +6,59 @@ import traceback
6
  from io import BytesIO
7
  from typing import Any, Dict, List, Optional, Tuple
8
  import re
9
- import warnings
10
 
11
  import fitz # PyMuPDF
12
  import gradio as gr
13
  import requests
14
  import torch
15
- from PIL import Image, ImageDraw, ImageFont
16
- from transformers import AutoModelForCausalLM, AutoProcessor, VisionEncoderDecoderModel
17
  from huggingface_hub import snapshot_download
 
18
  from qwen_vl_utils import process_vision_info
19
-
20
- # Suppress the FutureWarning for cleaner output (optional)
21
- warnings.filterwarnings(
22
- "ignore",
23
- category=FutureWarning,
24
- message="Both `num_logits_to_keep` and `logits_to_keep` are set"
25
- )
26
-
27
- # JavaScript for theme refresh
28
- js_func = """
29
- function refresh() {
30
- const url = new URL(window.location);
31
- if (url.searchParams.get('__theme') !== 'dark') {
32
- url.searchParams.set('__theme', 'dark');
33
- window.location.href = url.href;
34
- }
35
- }
36
- """
37
 
38
  # Constants
39
  MIN_PIXELS = 3136
40
  MAX_PIXELS = 11289600
41
  IMAGE_FACTOR = 28
42
 
43
- # Prompt for dots.ocr
44
  prompt = """Please output the layout information from the PDF image, including each layout element's bbox, its category, and the corresponding text content within the bbox.
45
 
46
  1. Bbox format: [x1, y1, x2, y2]
47
- 2. Layout Categories: ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']
 
 
48
  3. Text Extraction & Formatting Rules:
49
- - Picture: omit the text field
50
- - Formula: format as LaTeX
51
- - Table: format as HTML
52
- - Others: format as Markdown
53
- 4. Constraints:
54
- - Use original text, no translation
55
- - Sort elements by human reading order
56
- 5. Final Output: Single JSON object
57
- """
58
 
59
- # Model loading functions
60
- def load_model(model_name):
61
- if model_name == "dots.ocr":
62
- model_id = "rednote-hilab/dots.ocr"
63
- model_path = "./models/dots-ocr-local"
64
- snapshot_download(
65
- repo_id=model_id,
66
- local_dir=model_path,
67
- local_dir_use_symlinks=False,
68
- )
69
- model = AutoModelForCausalLM.from_pretrained(
70
- model_path,
71
- attn_implementation="flash_attention_2",
72
- torch_dtype=torch.bfloat16,
73
- device_map="auto",
74
- trust_remote_code=True
75
- )
76
- processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
77
- elif model_name == "Dolphin":
78
- model_id = "ByteDance/Dolphin"
79
- processor = AutoProcessor.from_pretrained(model_id)
80
- model = VisionEncoderDecoderModel.from_pretrained(model_id)
81
- model.eval()
82
- device = "cuda" if torch.cuda.is_available() else "cpu"
83
- model.to(device)
84
- model = model.half() # Use half precision
85
- else:
86
- raise ValueError(f"Unknown model: {model_name}")
87
- return model, processor
88
-
89
- # Inference functions
90
- def inference_dots_ocr(model, processor, image, prompt, max_new_tokens):
91
- messages = [
92
- {
93
- "role": "user",
94
- "content": [
95
- {"type": "image", "image": image},
96
- {"type": "text", "text": prompt}
97
- ]
98
- }
99
- ]
100
- text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
101
- image_inputs, video_inputs = process_vision_info(messages)
102
- inputs = processor(
103
- text=[text],
104
- images=image_inputs,
105
- videos=video_inputs,
106
- padding=True,
107
- return_tensors="pt",
108
- )
109
- inputs = inputs.to(model.device)
110
- with torch.no_grad():
111
- generated_ids = model.generate(
112
- **inputs,
113
- max_new_tokens=max_new_tokens,
114
- do_sample=False # Temperature removed previously to fix another warning
115
- )
116
- generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
117
- output_text = processor.batch_decode(
118
- generated_ids_trimmed,
119
- skip_special_tokens=True,
120
- clean_up_tokenization_spaces=False
121
- )
122
- return output_text[0] if output_text else ""
123
-
124
- def inference_dolphin(model, processor, image):
125
- pixel_values = processor(image, return_tensors="pt").pixel_values.to(model.device).half()
126
- generated_ids = model.generate(pixel_values)
127
- generated_text = processor.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
128
- return generated_text
129
-
130
- # Load models at startup
131
- models = {
132
- "dots.ocr": load_model("dots.ocr"),
133
- "Dolphin": load_model("Dolphin")
134
- }
135
 
136
- # Global state for PDF handling
137
- pdf_cache = {
138
- "images": [],
139
- "current_page": 0,
140
- "total_pages": 0,
141
- "file_type": None,
142
- "is_parsed": False,
143
- "results": []
144
- }
145
 
146
- # Utility functions
147
  def round_by_factor(number: int, factor: int) -> int:
 
148
  return round(number / factor) * factor
149
 
150
- def smart_resize(height: int, width: int, factor: int = 28, min_pixels: int = 3136, max_pixels: int = 11289600):
 
 
 
 
 
 
 
151
  if max(height, width) / min(height, width) > 200:
152
  raise ValueError(f"Aspect ratio must be < 200, got {max(height, width) / min(height, width)}")
153
  h_bar = max(factor, round_by_factor(height, factor))
154
  w_bar = max(factor, round_by_factor(width, factor))
 
155
  if h_bar * w_bar > max_pixels:
156
  beta = math.sqrt((height * width) / max_pixels)
157
  h_bar = round_by_factor(height / beta, factor)
@@ -163,6 +70,7 @@ def smart_resize(height: int, width: int, factor: int = 28, min_pixels: int = 31
163
  return h_bar, w_bar
164
 
165
  def fetch_image(image_input, min_pixels: int = None, max_pixels: int = None):
 
166
  if isinstance(image_input, str):
167
  if image_input.startswith(("http://", "https://")):
168
  response = requests.get(image_input)
@@ -173,20 +81,29 @@ def fetch_image(image_input, min_pixels: int = None, max_pixels: int = None):
173
  image = image_input.convert('RGB')
174
  else:
175
  raise ValueError(f"Invalid image input type: {type(image_input)}")
176
- if min_pixels or max_pixels:
 
177
  min_pixels = min_pixels or MIN_PIXELS
178
  max_pixels = max_pixels or MAX_PIXELS
179
- height, width = smart_resize(image.height, image.width, factor=IMAGE_FACTOR, min_pixels=min_pixels, max_pixels=max_pixels)
 
 
 
 
 
 
180
  image = image.resize((width, height), Image.LANCZOS)
 
181
  return image
182
 
183
  def load_images_from_pdf(pdf_path: str) -> List[Image.Image]:
 
184
  images = []
185
  try:
186
  pdf_document = fitz.open(pdf_path)
187
  for page_num in range(len(pdf_document)):
188
  page = pdf_document.load_page(page_num)
189
- mat = fitz.Matrix(2.0, 2.0)
190
  pix = page.get_pixmap(matrix=mat)
191
  img_data = pix.tobytes("ppm")
192
  image = Image.open(BytesIO(img_data)).convert('RGB')
@@ -198,66 +115,43 @@ def load_images_from_pdf(pdf_path: str) -> List[Image.Image]:
198
  return images
199
 
200
  def draw_layout_on_image(image: Image.Image, layout_data: List[Dict]) -> Image.Image:
 
201
  img_copy = image.copy()
202
  draw = ImageDraw.Draw(img_copy)
 
203
  colors = {
204
- 'Caption': '#FF6B6B', 'Footnote': '#4ECDC4', 'Formula': '#45B7D1', 'List-item': '#96CEB4',
205
- 'Page-footer': '#FFEAA7', 'Page-header': '#DDA0DD', 'Picture': '#FFD93D', 'Section-header': '#6C5CE7',
206
- 'Table': '#FD79A8', 'Text': '#74B9FF', 'Title': '#E17055'
 
207
  }
 
208
  try:
209
- font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 12)
210
- except Exception:
211
- font = ImageFont.load_default()
212
- try:
213
  for item in layout_data:
214
  if 'bbox' in item and 'category' in item:
215
  bbox = item['bbox']
216
  category = item['category']
217
  color = colors.get(category, '#000000')
 
218
  draw.rectangle(bbox, outline=color, width=2)
 
219
  label = category
220
  label_bbox = draw.textbbox((0, 0), label, font=font)
221
- label_width = label_bbox[2] - label_bbox[0]
222
- label_height = label_bbox[3] - label_bbox[1]
223
- label_x = bbox[0]
224
- label_y = max(0, bbox[1] - label_height - 2)
225
  draw.rectangle([label_x, label_y, label_x + label_width + 4, label_y + label_height + 2], fill=color)
226
  draw.text((label_x + 2, label_y + 1), label, fill='white', font=font)
227
  except Exception as e:
228
  print(f"Error drawing layout: {e}")
 
229
  return img_copy
230
 
231
- def is_arabic_text(text: str) -> bool:
232
- if not text:
233
- return False
234
- header_pattern = r'^#{1,6}\s+(.+)$'
235
- paragraph_pattern = r'^(?!#{1,6}\s|!\[|```|\||\s*[-*+]\s|\s*\d+\.\s)(.+)$'
236
- content_text = []
237
- for line in text.split('\n'):
238
- line = line.strip()
239
- if not line:
240
- continue
241
- header_match = re.match(header_pattern, line, re.MULTILINE)
242
- if header_match:
243
- content_text.append(header_match.group(1))
244
- continue
245
- if re.match(paragraph_pattern, line, re.MULTILINE):
246
- content_text.append(line)
247
- if not content_text:
248
- return False
249
- combined_text = ' '.join(content_text)
250
- arabic_chars = 0
251
- total_chars = 0
252
- for char in combined_text:
253
- if char.isalpha():
254
- total_chars += 1
255
- if ('\u0600' <= char <= '\u06FF') or ('\u0750' <= char <= '\u077F') or ('\u08A0' <= char <= '\u08FF'):
256
- arabic_chars += 1
257
- return total_chars > 0 and (arabic_chars / total_chars) > 0.5
258
-
259
  def layoutjson2md(image: Image.Image, layout_data: List[Dict], text_key: str = 'text') -> str:
 
260
  import base64
 
261
  markdown_lines = []
262
  try:
263
  sorted_items = sorted(layout_data, key=lambda x: (x.get('bbox', [0, 0, 0, 0])[1], x.get('bbox', [0, 0, 0, 0])[0]))
@@ -265,23 +159,21 @@ def layoutjson2md(image: Image.Image, layout_data: List[Dict], text_key: str = '
265
  category = item.get('category', '')
266
  text = item.get(text_key, '')
267
  bbox = item.get('bbox', [])
268
- if category == 'Picture':
269
- if bbox and len(bbox) == 4:
270
- try:
271
- x1, y1, x2, y2 = [max(0, int(x)) if i < 2 else min(image.width if i % 2 == 0 else image.height, int(x)) for i, x in enumerate(bbox)]
272
- if x2 > x1 and y2 > y1:
273
- cropped_img = image.crop((x1, y1, x2, y2))
274
- buffer = BytesIO()
275
- cropped_img.save(buffer, format='PNG')
276
- img_data = base64.b64encode(buffer.getvalue()).decode()
277
- markdown_lines.append(f'<image-card alt="Image" src="data:image/png;base64,{img_data}" ></image-card>\n')
278
- else:
279
- markdown_lines.append('<image-card alt="Image" src="Image region detected" ></image-card>\n')
280
- except Exception as e:
281
- print(f"Error processing image region: {e}")
282
- markdown_lines.append('<image-card alt="Image" src="Image detected" ></image-card>\n')
283
- else:
284
- markdown_lines.append('<image-card alt="Image" src="Image detected" ></image-card>\n')
285
  elif not text:
286
  continue
287
  elif category == 'Title':
@@ -293,15 +185,9 @@ def layoutjson2md(image: Image.Image, layout_data: List[Dict], text_key: str = '
293
  elif category == 'List-item':
294
  markdown_lines.append(f"- {text}\n")
295
  elif category == 'Table':
296
- if text.strip().startswith('<'):
297
- markdown_lines.append(f"{text}\n")
298
- else:
299
- markdown_lines.append(f"**Table:** {text}\n")
300
  elif category == 'Formula':
301
- if text.strip().startswith('$') or '\\' in text:
302
- markdown_lines.append(f"$$ \n{text}\n $$\n") # Fixed formatting, removed extra spaces
303
- else:
304
- markdown_lines.append(f"**Formula:** {text}\n")
305
  elif category == 'Caption':
306
  markdown_lines.append(f"*{text}*\n")
307
  elif category == 'Footnote':
@@ -314,37 +200,122 @@ def layoutjson2md(image: Image.Image, layout_data: List[Dict], text_key: str = '
314
  except Exception as e:
315
  print(f"Error converting to markdown: {e}")
316
  return str(layout_data)
 
317
  return "\n".join(markdown_lines)
318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  def load_file_for_preview(file_path: str) -> Tuple[Optional[Image.Image], str]:
 
320
  global pdf_cache
321
  if not file_path or not os.path.exists(file_path):
322
  return None, "No file selected"
 
323
  file_ext = os.path.splitext(file_path)[1].lower()
324
  try:
325
  if file_ext == '.pdf':
326
  images = load_images_from_pdf(file_path)
327
  if not images:
328
  return None, "Failed to load PDF"
329
- pdf_cache.update({
330
- "images": images,
331
- "current_page": 0,
332
- "total_pages": len(images),
333
- "file_type": "pdf",
334
- "is_parsed": False,
335
- "results": []
336
- })
337
  return images[0], f"Page 1 / {len(images)}"
338
  elif file_ext in ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']:
339
  image = Image.open(file_path).convert('RGB')
340
- pdf_cache.update({
341
- "images": [image],
342
- "current_page": 0,
343
- "total_pages": 1,
344
- "file_type": "image",
345
- "is_parsed": False,
346
- "results": []
347
- })
348
  return image, "Page 1 / 1"
349
  else:
350
  return None, f"Unsupported file format: {file_ext}"
@@ -352,108 +323,28 @@ def load_file_for_preview(file_path: str) -> Tuple[Optional[Image.Image], str]:
352
  print(f"Error loading file: {e}")
353
  return None, f"Error loading file: {str(e)}"
354
 
355
- @spaces.GPU()
356
- def process_document(file_path, model_choice, max_tokens, min_pix, max_pix):
357
- global pdf_cache
358
- if not file_path:
359
- return None, "Please upload a file first.", None
360
- model, processor = models[model_choice]
361
- image, page_info = load_file_for_preview(file_path)
362
- if image is None:
363
- return None, page_info, None
364
- if pdf_cache["file_type"] == "pdf":
365
- all_results = []
366
- for i, img in enumerate(pdf_cache["images"]):
367
- if model_choice == "dots.ocr":
368
- raw_output = inference_dots_ocr(model, processor, img, prompt, max_tokens)
369
- try:
370
- layout_data = json.loads(raw_output)
371
- processed_image = draw_layout_on_image(img, layout_data)
372
- markdown_content = layoutjson2md(img, layout_data)
373
- result = {
374
- 'processed_image': processed_image,
375
- 'markdown_content': markdown_content,
376
- 'layout_result': layout_data
377
- }
378
- except Exception:
379
- result = {
380
- 'processed_image': img,
381
- 'markdown_content': raw_output,
382
- 'layout_result': None
383
- }
384
- else: # Dolphin
385
- text = inference_dolphin(model, processor, img)
386
- result = f"## Page {i+1}\n\n{text}" if text else "No text extracted"
387
- all_results.append(result)
388
- pdf_cache["results"] = all_results
389
- pdf_cache["is_parsed"] = True
390
- first_result = all_results[0]
391
- if model_choice == "dots.ocr":
392
- markdown_update = gr.update(value=first_result['markdown_content'], rtl=is_arabic_text(first_result['markdown_content']))
393
- return first_result['processed_image'], markdown_update, first_result['layout_result']
394
- else:
395
- markdown_update = gr.update(value=first_result, rtl=is_arabic_text(first_result))
396
- return None, markdown_update, None
397
- else:
398
- if model_choice == "dots.ocr":
399
- raw_output = inference_dots_ocr(model, processor, image, prompt, max_tokens)
400
- try:
401
- layout_data = json.loads(raw_output)
402
- processed_image = draw_layout_on_image(image, layout_data)
403
- markdown_content = layoutjson2md(image, layout_data)
404
- result = {
405
- 'processed_image': processed_image,
406
- 'markdown_content': markdown_content,
407
- 'layout_result': layout_data
408
- }
409
- except Exception:
410
- result = {
411
- 'processed_image': image,
412
- 'markdown_content': raw_output,
413
- 'layout_result': None
414
- }
415
- pdf_cache["results"] = [result]
416
- else: # Dolphin
417
- text = inference_dolphin(model, processor, image)
418
- result = text if text else "No text extracted"
419
- pdf_cache["results"] = [result]
420
- pdf_cache["is_parsed"] = True
421
- if model_choice == "dots.ocr":
422
- markdown_update = gr.update(value=result['markdown_content'], rtl=is_arabic_text(result['markdown_content']))
423
- return result['processed_image'], markdown_update, result['layout_result']
424
- else:
425
- markdown_update = gr.update(value=result, rtl=is_arabic_text(result))
426
- return None, markdown_update, None
427
-
428
  def turn_page(direction: str) -> Tuple[Optional[Image.Image], str, Any, Optional[Image.Image], Optional[Dict]]:
 
429
  global pdf_cache
430
  if not pdf_cache["images"]:
431
  return None, '<div class="page-info">No file loaded</div>', "No results yet", None, None
432
- if direction == "prev":
433
- pdf_cache["current_page"] = max(0, pdf_cache["current_page"] - 1)
434
- elif direction == "next":
435
- pdf_cache["current_page"] = min(pdf_cache["total_pages"] - 1, pdf_cache["current_page"] + 1)
436
  index = pdf_cache["current_page"]
437
  current_image_preview = pdf_cache["images"][index]
438
  page_info_html = f'<div class="page-info">Page {index + 1} / {pdf_cache["total_pages"]}</div>'
439
- if pdf_cache["is_parsed"] and index < len(pdf_cache["results"]):
 
 
440
  result = pdf_cache["results"][index]
441
- if isinstance(result, dict): # dots.ocr
442
- markdown_content = result.get('markdown_content', 'No content available')
443
- processed_img = result.get('processed_image', None)
444
- layout_json = result.get('layout_result', None)
445
- else: # Dolphin
446
- markdown_content = result
447
- processed_img = None
448
- layout_json = None
449
- else:
450
- markdown_content = "Page not processed yet"
451
- processed_img = None
452
- layout_json = None
453
- markdown_update = gr.update(value=markdown_content, rtl=is_arabic_text(markdown_content))
454
- return current_image_preview, page_info_html, markdown_update, processed_img, layout_json
455
 
456
  def create_gradio_interface():
 
457
  css = """
458
  .main-container { max-width: 1400px; margin: 0 auto; }
459
  .header-text { text-align: center; color: #2c3e50; margin-bottom: 20px; }
@@ -471,75 +362,102 @@ def create_gradio_interface():
471
  .model-status { padding: 10px; border-radius: 8px; margin: 10px 0; text-align: center; font-weight: bold; }
472
  .status-ready { background: #d1edff; color: #0c5460; border: 1px solid #b8daff; }
473
  """
474
- with gr.Blocks(theme="bethecloud/storj_theme", css=css, js=js_func) as demo:
 
475
  gr.HTML("""
476
  <div class="title" style="text-align: center">
477
- <h1>Dot<span style="color: red;">●</span><strong></strong>OCR vs Dolphin🐬</h1>
478
  <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
479
  Advanced vision-language model for image/PDF to markdown document processing
480
  </p>
481
  </div>
482
  """)
 
483
  with gr.Row():
484
  with gr.Column(scale=1):
485
- file_input = gr.File(
486
- label="Upload Image or PDF",
487
- file_types=[".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".pdf"],
488
- type="filepath"
489
  )
 
 
 
 
 
 
 
490
  image_preview = gr.Image(label="Preview", type="pil", interactive=False, height=300)
491
  with gr.Row():
492
- prev_page_btn = gr.Button(" Previous", size="md")
493
  page_info = gr.HTML('<div class="page-info">No file loaded</div>')
494
- next_page_btn = gr.Button("Next ", size="md")
495
- model_choice = gr.Radio(
496
- choices=["dots.ocr", "Dolphin"],
497
- label="Select Model",
498
- value="dots.ocr"
499
- )
500
  with gr.Accordion("Advanced Settings", open=False):
501
  max_new_tokens = gr.Slider(minimum=1000, maximum=32000, value=24000, step=1000, label="Max New Tokens")
502
  min_pixels = gr.Number(value=MIN_PIXELS, label="Min Pixels")
503
  max_pixels = gr.Number(value=MAX_PIXELS, label="Max Pixels")
504
- process_btn = gr.Button("🔥 Process Document", variant="primary", elem_classes=["process-button"], size="lg")
505
- clear_btn = gr.Button("Clear Document", variant="secondary")
 
506
  with gr.Column(scale=2):
507
  with gr.Tabs():
508
- with gr.Tab("✦︎ Processed Image"):
509
  processed_image = gr.Image(label="Image with Layout Detection", type="pil", interactive=False, height=500)
510
- with gr.Tab("🀥 Extracted Content"):
511
  markdown_output = gr.Markdown(value="Click 'Process Document' to see extracted content...", height=500)
512
- with gr.Tab(" Layout JSON"):
513
  json_output = gr.JSON(label="Layout Analysis Results", value=None)
514
- with gr.Row():
515
- examples = gr.Examples(
516
- examples=["examples/sample_image1.png", "examples/sample_image2.png", "examples/sample_pdf.pdf"],
517
- inputs=file_input,
518
- label="Example Documents"
519
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520
  def handle_file_upload(file_path):
521
  image, page_info = load_file_for_preview(file_path)
522
  return image, page_info
523
-
524
  def clear_all():
525
  global pdf_cache
526
  pdf_cache = {"images": [], "current_page": 0, "total_pages": 0, "file_type": None, "is_parsed": False, "results": []}
527
  return None, None, '<div class="page-info">No file loaded</div>', None, "Click 'Process Document' to see extracted content...", None
528
-
529
  file_input.change(handle_file_upload, inputs=[file_input], outputs=[image_preview, page_info])
530
  prev_page_btn.click(lambda: turn_page("prev"), outputs=[image_preview, page_info, markdown_output, processed_image, json_output])
531
  next_page_btn.click(lambda: turn_page("next"), outputs=[image_preview, page_info, markdown_output, processed_image, json_output])
532
- process_btn.click(
533
- process_document,
534
- inputs=[file_input, model_choice, max_new_tokens, min_pixels, max_pixels],
535
- outputs=[processed_image, markdown_output, json_output]
536
- )
537
- clear_btn.click(
538
- clear_all,
539
- outputs=[file_input, image_preview, page_info, processed_image, markdown_output, json_output]
540
- )
541
  return demo
542
 
543
  if __name__ == "__main__":
544
  demo = create_gradio_interface()
545
- demo.queue(max_size=30).launch(debug=True, show_error=True) # Removed share=True
 
6
  from io import BytesIO
7
  from typing import Any, Dict, List, Optional, Tuple
8
  import re
 
9
 
10
  import fitz # PyMuPDF
11
  import gradio as gr
12
  import requests
13
  import torch
 
 
14
  from huggingface_hub import snapshot_download
15
+ from PIL import Image, ImageDraw, ImageFont
16
  from qwen_vl_utils import process_vision_info
17
+ from transformers import AutoModelForCausalLM, AutoProcessor, Qwen2_5_VLForConditionalGeneration
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  # Constants
20
  MIN_PIXELS = 3136
21
  MAX_PIXELS = 11289600
22
  IMAGE_FACTOR = 28
23
 
24
+ # Prompts
25
  prompt = """Please output the layout information from the PDF image, including each layout element's bbox, its category, and the corresponding text content within the bbox.
26
 
27
  1. Bbox format: [x1, y1, x2, y2]
28
+
29
+ 2. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].
30
+
31
  3. Text Extraction & Formatting Rules:
32
+ - Picture: For the 'Picture' category, the text field should be omitted.
33
+ - Formula: Format its text as LaTeX.
34
+ - Table: Format its text as HTML.
35
+ - All Others (Text, Title, etc.): Format their text as Markdown.
 
 
 
 
 
36
 
37
+ 4. Constraints:
38
+ - The output text must be the original text from the image, with no translation.
39
+ - All layout elements must be sorted according to human reading order.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ 5. Final Output: The entire output must be a single JSON object.
42
+ """
 
 
 
 
 
 
 
43
 
44
+ # Utility Functions
45
  def round_by_factor(number: int, factor: int) -> int:
46
+ """Returns the closest integer to 'number' that is divisible by 'factor'."""
47
  return round(number / factor) * factor
48
 
49
+ def smart_resize(
50
+ height: int,
51
+ width: int,
52
+ factor: int = 28,
53
+ min_pixels: int = 3136,
54
+ max_pixels: int = 11289600,
55
+ ):
56
+ """Rescales the image so that dimensions are divisible by 'factor', within pixel range, maintaining aspect ratio."""
57
  if max(height, width) / min(height, width) > 200:
58
  raise ValueError(f"Aspect ratio must be < 200, got {max(height, width) / min(height, width)}")
59
  h_bar = max(factor, round_by_factor(height, factor))
60
  w_bar = max(factor, round_by_factor(width, factor))
61
+
62
  if h_bar * w_bar > max_pixels:
63
  beta = math.sqrt((height * width) / max_pixels)
64
  h_bar = round_by_factor(height / beta, factor)
 
70
  return h_bar, w_bar
71
 
72
  def fetch_image(image_input, min_pixels: int = None, max_pixels: int = None):
73
+ """Fetch and process an image."""
74
  if isinstance(image_input, str):
75
  if image_input.startswith(("http://", "https://")):
76
  response = requests.get(image_input)
 
81
  image = image_input.convert('RGB')
82
  else:
83
  raise ValueError(f"Invalid image input type: {type(image_input)}")
84
+
85
+ if min_pixels is not None or max_pixels is not None:
86
  min_pixels = min_pixels or MIN_PIXELS
87
  max_pixels = max_pixels or MAX_PIXELS
88
+ height, width = smart_resize(
89
+ image.height,
90
+ image.width,
91
+ factor=IMAGE_FACTOR,
92
+ min_pixels=min_pixels,
93
+ max_pixels=max_pixels
94
+ )
95
  image = image.resize((width, height), Image.LANCZOS)
96
+
97
  return image
98
 
99
  def load_images_from_pdf(pdf_path: str) -> List[Image.Image]:
100
+ """Load images from PDF file."""
101
  images = []
102
  try:
103
  pdf_document = fitz.open(pdf_path)
104
  for page_num in range(len(pdf_document)):
105
  page = pdf_document.load_page(page_num)
106
+ mat = fitz.Matrix(2.0, 2.0) # Increase resolution
107
  pix = page.get_pixmap(matrix=mat)
108
  img_data = pix.tobytes("ppm")
109
  image = Image.open(BytesIO(img_data)).convert('RGB')
 
115
  return images
116
 
117
  def draw_layout_on_image(image: Image.Image, layout_data: List[Dict]) -> Image.Image:
118
+ """Draw layout bounding boxes on image."""
119
  img_copy = image.copy()
120
  draw = ImageDraw.Draw(img_copy)
121
+
122
  colors = {
123
+ 'Caption': '#FF6B6B', 'Footnote': '#4ECDC4', 'Formula': '#45B7D1',
124
+ 'List-item': '#96CEB4', 'Page-footer': '#FFEAA7', 'Page-header': '#DDA0DD',
125
+ 'Picture': '#FFD93D', 'Section-header': '#6C5CE7', 'Table': '#FD79A8',
126
+ 'Text': '#74B9FF', 'Title': '#E17055'
127
  }
128
+
129
  try:
130
+ font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 12) or ImageFont.load_default()
 
 
 
131
  for item in layout_data:
132
  if 'bbox' in item and 'category' in item:
133
  bbox = item['bbox']
134
  category = item['category']
135
  color = colors.get(category, '#000000')
136
+
137
  draw.rectangle(bbox, outline=color, width=2)
138
+
139
  label = category
140
  label_bbox = draw.textbbox((0, 0), label, font=font)
141
+ label_width, label_height = label_bbox[2] - label_bbox[0], label_bbox[3] - label_bbox[1]
142
+
143
+ label_x, label_y = bbox[0], max(0, bbox[1] - label_height - 2)
 
144
  draw.rectangle([label_x, label_y, label_x + label_width + 4, label_y + label_height + 2], fill=color)
145
  draw.text((label_x + 2, label_y + 1), label, fill='white', font=font)
146
  except Exception as e:
147
  print(f"Error drawing layout: {e}")
148
+
149
  return img_copy
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  def layoutjson2md(image: Image.Image, layout_data: List[Dict], text_key: str = 'text') -> str:
152
+ """Convert layout JSON to markdown format."""
153
  import base64
154
+
155
  markdown_lines = []
156
  try:
157
  sorted_items = sorted(layout_data, key=lambda x: (x.get('bbox', [0, 0, 0, 0])[1], x.get('bbox', [0, 0, 0, 0])[0]))
 
159
  category = item.get('category', '')
160
  text = item.get(text_key, '')
161
  bbox = item.get('bbox', [])
162
+
163
+ if category == 'Picture' and bbox and len(bbox) == 4:
164
+ try:
165
+ x1, y1, x2, y2 = [max(0, int(x1)), max(0, int(y1)), min(image.width, int(x2)), min(image.height, int(y2))]
166
+ if x2 > x1 and y2 > y1:
167
+ cropped_img = image.crop((x1, y1, x2, y2))
168
+ buffer = BytesIO()
169
+ cropped_img.save(buffer, format='PNG')
170
+ img_data = base64.b64encode(buffer.getvalue()).decode()
171
+ markdown_lines.append(f"![Image](data:image/png;base64,{img_data})\n")
172
+ else:
173
+ markdown_lines.append("![Image](Image region detected)\n")
174
+ except Exception as e:
175
+ print(f"Error processing image region: {e}")
176
+ markdown_lines.append("![Image](Image detected)\n")
 
 
177
  elif not text:
178
  continue
179
  elif category == 'Title':
 
185
  elif category == 'List-item':
186
  markdown_lines.append(f"- {text}\n")
187
  elif category == 'Table':
188
+ markdown_lines.append(f"{text}\n" if text.strip().startswith('<') else f"**Table:** {text}\n")
 
 
 
189
  elif category == 'Formula':
190
+ markdown_lines.append(f"$$\n{text}\n$$\n" if text.strip().startswith('$') or '\\' in text else f"**Formula:** {text}\n")
 
 
 
191
  elif category == 'Caption':
192
  markdown_lines.append(f"*{text}*\n")
193
  elif category == 'Footnote':
 
200
  except Exception as e:
201
  print(f"Error converting to markdown: {e}")
202
  return str(layout_data)
203
+
204
  return "\n".join(markdown_lines)
205
 
206
+ # Load Models
207
+ device = "cuda" if torch.cuda.is_available() else "cpu"
208
+
209
+ # Load dot.ocr
210
+ model_id = "rednote-hilab/dots.ocr"
211
+ model_path = "./models/dots-ocr-local"
212
+ snapshot_download(repo_id=model_id, local_dir=model_path, local_dir_use_symlinks=False)
213
+ model = AutoModelForCausalLM.from_pretrained(
214
+ model_path,
215
+ attn_implementation="flash_attention_2",
216
+ torch_dtype=torch.bfloat16,
217
+ device_map="auto",
218
+ trust_remote_code=True
219
+ )
220
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
221
+
222
+ # Load Camel-Doc-OCR-062825
223
+ MODEL_ID_M = "prithivMLmods/Camel-Doc-OCR-062825"
224
+ processor_m = AutoProcessor.from_pretrained(MODEL_ID_M, trust_remote_code=True)
225
+ model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
226
+ MODEL_ID_M,
227
+ trust_remote_code=True,
228
+ torch_dtype=torch.float16
229
+ ).to(device).eval()
230
+
231
+ # Load Megalodon-OCR-Sync-0713
232
+ MODEL_ID_T = "prithivMLmods/Megalodon-OCR-Sync-0713"
233
+ processor_t = AutoProcessor.from_pretrained(MODEL_ID_T, trust_remote_code=True)
234
+ model_t = Qwen2_5_VLForConditionalGeneration.from_pretrained(
235
+ MODEL_ID_T,
236
+ trust_remote_code=True,
237
+ torch_dtype=torch.float16
238
+ ).to(device).eval()
239
+
240
+ # Model Dictionary
241
+ model_dict = {
242
+ "dot.ocr": {"model": model, "processor": processor, "process_layout": True},
243
+ "Camel-Doc-OCR-062825": {"model": model_m, "processor": processor_m, "process_layout": False},
244
+ "Megalodon-OCR-Sync-0713": {"model": model_t, "processor": processor_t, "process_layout": False},
245
+ }
246
+
247
+ # Global State
248
+ pdf_cache = {"images": [], "current_page": 0, "total_pages": 0, "file_type": None, "is_parsed": False, "results": []}
249
+
250
+ @spaces.GPU()
251
+ def inference(model, processor, image: Image.Image, prompt: str, max_new_tokens: int = 24000) -> str:
252
+ """Run inference on an image with the given prompt using the specified model and processor."""
253
+ try:
254
+ messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": prompt}]}]
255
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
256
+ image_inputs, video_inputs = process_vision_info(messages)
257
+ inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt").to(device)
258
+
259
+ with torch.no_grad():
260
+ generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False, temperature=0.1)
261
+ generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
262
+ output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
263
+ return output_text[0] if output_text else ""
264
+ except Exception as e:
265
+ print(f"Error during inference: {e}")
266
+ traceback.print_exc()
267
+ return f"Error during inference: {str(e)}"
268
+
269
+ def process_image(
270
+ image: Image.Image,
271
+ model,
272
+ processor,
273
+ process_layout: bool,
274
+ min_pixels: Optional[int] = None,
275
+ max_pixels: Optional[int] = None
276
+ ) -> Dict[str, Any]:
277
+ """Process a single image with the specified model and processor."""
278
+ try:
279
+ if min_pixels is not None or max_pixels is not None:
280
+ image = fetch_image(image, min_pixels=min_pixels, max_pixels=max_pixels)
281
+
282
+ raw_output = inference(model, processor, image, prompt)
283
+ result = {'original_image': image, 'raw_output': raw_output, 'processed_image': image, 'layout_result': None, 'markdown_content': raw_output}
284
+
285
+ if process_layout:
286
+ try:
287
+ layout_data = json.loads(raw_output)
288
+ result['layout_result'] = layout_data
289
+ result['processed_image'] = draw_layout_on_image(image, layout_data)
290
+ result['markdown_content'] = layoutjson2md(image, layout_data, text_key='text')
291
+ except json.JSONDecodeError:
292
+ print("Failed to parse JSON output, using raw output")
293
+ except Exception as e:
294
+ print(f"Error processing layout: {e}")
295
+
296
+ return result
297
+ except Exception as e:
298
+ print(f"Error processing image: {e}")
299
+ traceback.print_exc()
300
+ return {'original_image': image, 'raw_output': str(e), 'processed_image': image, 'layout_result': None, 'markdown_content': str(e)}
301
+
302
  def load_file_for_preview(file_path: str) -> Tuple[Optional[Image.Image], str]:
303
+ """Load file for preview (supports PDF and images)."""
304
  global pdf_cache
305
  if not file_path or not os.path.exists(file_path):
306
  return None, "No file selected"
307
+
308
  file_ext = os.path.splitext(file_path)[1].lower()
309
  try:
310
  if file_ext == '.pdf':
311
  images = load_images_from_pdf(file_path)
312
  if not images:
313
  return None, "Failed to load PDF"
314
+ pdf_cache.update({"images": images, "current_page": 0, "total_pages": len(images), "file_type": "pdf", "is_parsed": False, "results": []})
 
 
 
 
 
 
 
315
  return images[0], f"Page 1 / {len(images)}"
316
  elif file_ext in ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']:
317
  image = Image.open(file_path).convert('RGB')
318
+ pdf_cache.update({"images": [image], "current_page": 0, "total_pages": 1, "file_type": "image", "is_parsed": False, "results": []})
 
 
 
 
 
 
 
319
  return image, "Page 1 / 1"
320
  else:
321
  return None, f"Unsupported file format: {file_ext}"
 
323
  print(f"Error loading file: {e}")
324
  return None, f"Error loading file: {str(e)}"
325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  def turn_page(direction: str) -> Tuple[Optional[Image.Image], str, Any, Optional[Image.Image], Optional[Dict]]:
327
+ """Navigate through PDF pages and update outputs."""
328
  global pdf_cache
329
  if not pdf_cache["images"]:
330
  return None, '<div class="page-info">No file loaded</div>', "No results yet", None, None
331
+
332
+ pdf_cache["current_page"] = max(0, pdf_cache["current_page"] - 1) if direction == "prev" else min(pdf_cache["total_pages"] - 1, pdf_cache["current_page"] + 1)
 
 
333
  index = pdf_cache["current_page"]
334
  current_image_preview = pdf_cache["images"][index]
335
  page_info_html = f'<div class="page-info">Page {index + 1} / {pdf_cache["total_pages"]}</div>'
336
+
337
+ markdown_content, processed_img, layout_json = "Page not processed yet", None, None
338
+ if pdf_cache["is_parsed"] and index < len(pdf_cache["results"]) and pdf_cache["results"][index]:
339
  result = pdf_cache["results"][index]
340
+ markdown_content = result.get('markdown_content') or result.get('raw_output', 'No content available')
341
+ processed_img = result.get('processed_image')
342
+ layout_json = result.get('layout_result')
343
+
344
+ return current_image_preview, page_info_html, markdown_content, processed_img, layout_json
 
 
 
 
 
 
 
 
 
345
 
346
  def create_gradio_interface():
347
+ """Create the Gradio interface."""
348
  css = """
349
  .main-container { max-width: 1400px; margin: 0 auto; }
350
  .header-text { text-align: center; color: #2c3e50; margin-bottom: 20px; }
 
362
  .model-status { padding: 10px; border-radius: 8px; margin: 10px 0; text-align: center; font-weight: bold; }
363
  .status-ready { background: #d1edff; color: #0c5460; border: 1px solid #b8daff; }
364
  """
365
+
366
+ with gr.Blocks(theme="bethecloud/storj_theme", css=css, title="Dot●OCR Comparator") as demo:
367
  gr.HTML("""
368
  <div class="title" style="text-align: center">
369
+ <h1>Dot<span style="color: red;">●</span>OCR Comparator</h1>
370
  <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
371
  Advanced vision-language model for image/PDF to markdown document processing
372
  </p>
373
  </div>
374
  """)
375
+
376
  with gr.Row():
377
  with gr.Column(scale=1):
378
+ model_choice = gr.Radio(
379
+ choices=["dot.ocr", "Camel-Doc-OCR-062825", "Megalodon-OCR-Sync-0713"],
380
+ label="Select Model",
381
+ value="dot.ocr"
382
  )
383
+ file_input = gr.File(label="Upload Image or PDF", file_types=[".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".pdf"], type="filepath")
384
+ with gr.Row():
385
+ examples = gr.Examples(
386
+ examples=["examples/sample_image1.png", "examples/sample_image2.png", "examples/sample_pdf.pdf"],
387
+ inputs=file_input,
388
+ label="Example Documents"
389
+ )
390
  image_preview = gr.Image(label="Preview", type="pil", interactive=False, height=300)
391
  with gr.Row():
392
+ prev_page_btn = gr.Button(" Previous", size="md")
393
  page_info = gr.HTML('<div class="page-info">No file loaded</div>')
394
+ next_page_btn = gr.Button("Next ", size="md")
 
 
 
 
 
395
  with gr.Accordion("Advanced Settings", open=False):
396
  max_new_tokens = gr.Slider(minimum=1000, maximum=32000, value=24000, step=1000, label="Max New Tokens")
397
  min_pixels = gr.Number(value=MIN_PIXELS, label="Min Pixels")
398
  max_pixels = gr.Number(value=MAX_PIXELS, label="Max Pixels")
399
+ process_btn = gr.Button("🚀 Process Document", variant="primary", elem_classes=["process-button"], size="lg")
400
+ clear_btn = gr.Button("🗑️ Clear All", variant="secondary")
401
+
402
  with gr.Column(scale=2):
403
  with gr.Tabs():
404
+ with gr.Tab("🖼️ Processed Image"):
405
  processed_image = gr.Image(label="Image with Layout Detection", type="pil", interactive=False, height=500)
406
+ with gr.Tab("📝 Extracted Content"):
407
  markdown_output = gr.Markdown(value="Click 'Process Document' to see extracted content...", height=500)
408
+ with gr.Tab("📋 Layout JSON"):
409
  json_output = gr.JSON(label="Layout Analysis Results", value=None)
410
+
411
+ def process_document(file_path, model_choice, max_tokens, min_pix, max_pix):
412
+ """Process the uploaded document with the selected model."""
413
+ global pdf_cache
414
+ if not file_path:
415
+ return None, "Please upload a file first.", None
416
+ if model_choice not in model_dict:
417
+ return None, "Invalid model selected", None
418
+
419
+ selected_model = model_dict[model_choice]["model"]
420
+ selected_processor = model_dict[model_choice]["processor"]
421
+ process_layout = model_dict[model_choice]["process_layout"]
422
+
423
+ image, page_info = load_file_for_preview(file_path)
424
+ if image is None:
425
+ return None, page_info, None
426
+
427
+ if pdf_cache["file_type"] == "pdf":
428
+ all_results, all_markdown = [], []
429
+ for i, img in enumerate(pdf_cache["images"]):
430
+ result = process_image(img, selected_model, selected_processor, process_layout, int(min_pix) if min_pix else None, int(max_pix) if max_pix else None)
431
+ all_results.append(result)
432
+ if result.get('markdown_content'):
433
+ all_markdown.append(f"## Page {i+1}\n\n{result['markdown_content']}")
434
+ pdf_cache["results"] = all_results
435
+ pdf_cache["is_parsed"] = True
436
+ first_result = all_results[0]
437
+ return first_result['processed_image'], "\n\n---\n\n".join(all_markdown), first_result['layout_result']
438
+ else:
439
+ result = process_image(image, selected_model, selected_processor, process_layout, int(min_pix) if min_pix else None, int(max_pix) if max_pix else None)
440
+ pdf_cache["results"] = [result]
441
+ pdf_cache["is_parsed"] = True
442
+ return result['processed_image'], result['markdown_content'] or "No content extracted", result['layout_result']
443
+
444
  def handle_file_upload(file_path):
445
  image, page_info = load_file_for_preview(file_path)
446
  return image, page_info
447
+
448
  def clear_all():
449
  global pdf_cache
450
  pdf_cache = {"images": [], "current_page": 0, "total_pages": 0, "file_type": None, "is_parsed": False, "results": []}
451
  return None, None, '<div class="page-info">No file loaded</div>', None, "Click 'Process Document' to see extracted content...", None
452
+
453
  file_input.change(handle_file_upload, inputs=[file_input], outputs=[image_preview, page_info])
454
  prev_page_btn.click(lambda: turn_page("prev"), outputs=[image_preview, page_info, markdown_output, processed_image, json_output])
455
  next_page_btn.click(lambda: turn_page("next"), outputs=[image_preview, page_info, markdown_output, processed_image, json_output])
456
+ process_btn.click(process_document, inputs=[file_input, model_choice, max_new_tokens, min_pixels, max_pixels], outputs=[processed_image, markdown_output, json_output])
457
+ clear_btn.click(clear_all, outputs=[file_input, image_preview, page_info, processed_image, markdown_output, json_output])
458
+
 
 
 
 
 
 
459
  return demo
460
 
461
  if __name__ == "__main__":
462
  demo = create_gradio_interface()
463
+ demo.queue(max_size=50).launch(share=False, debug=True, show_error=True)