Pradeep018 commited on
Commit
bc3d187
Β·
verified Β·
1 Parent(s): f915ff9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +904 -0
app.py ADDED
@@ -0,0 +1,904 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import json
3
+ import math
4
+ import os
5
+ import traceback
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
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
+
50
+ def smart_resize(
51
+ height: int,
52
+ width: int,
53
+ factor: int = 28,
54
+ min_pixels: int = 3136,
55
+ max_pixels: int = 11289600,
56
+ ):
57
+ """Rescales the image so that the following conditions are met:
58
+ 1. Both dimensions (height and width) are divisible by 'factor'.
59
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
60
+ 3. The aspect ratio of the image is maintained as closely as possible.
61
+ """
62
+ if max(height, width) / min(height, width) > 200:
63
+ raise ValueError(
64
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
65
+ )
66
+ h_bar = max(factor, round_by_factor(height, factor))
67
+ w_bar = max(factor, round_by_factor(width, factor))
68
+
69
+ if h_bar * w_bar > max_pixels:
70
+ beta = math.sqrt((height * width) / max_pixels)
71
+ h_bar = round_by_factor(height / beta, factor)
72
+ w_bar = round_by_factor(width / beta, factor)
73
+ elif h_bar * w_bar < min_pixels:
74
+ beta = math.sqrt(min_pixels / (height * width))
75
+ h_bar = round_by_factor(height * beta, factor)
76
+ w_bar = round_by_factor(width * beta, factor)
77
+ return h_bar, w_bar
78
+
79
+
80
+ def fetch_image(image_input, min_pixels: int = None, max_pixels: int = None):
81
+ """Fetch and process an image"""
82
+ if isinstance(image_input, str):
83
+ if image_input.startswith(("http://", "https://")):
84
+ response = requests.get(image_input)
85
+ image = Image.open(BytesIO(response.content)).convert('RGB')
86
+ else:
87
+ image = Image.open(image_input).convert('RGB')
88
+ elif isinstance(image_input, Image.Image):
89
+ image = image_input.convert('RGB')
90
+ else:
91
+ raise ValueError(f"Invalid image input type: {type(image_input)}")
92
+
93
+ if min_pixels is not None or max_pixels is not None:
94
+ min_pixels = min_pixels or MIN_PIXELS
95
+ max_pixels = max_pixels or MAX_PIXELS
96
+ height, width = smart_resize(
97
+ image.height,
98
+ image.width,
99
+ factor=IMAGE_FACTOR,
100
+ min_pixels=min_pixels,
101
+ max_pixels=max_pixels
102
+ )
103
+ image = image.resize((width, height), Image.LANCZOS)
104
+
105
+ return image
106
+
107
+
108
+ def load_images_from_pdf(pdf_path: str) -> List[Image.Image]:
109
+ """Load images from PDF file"""
110
+ images = []
111
+ try:
112
+ pdf_document = fitz.open(pdf_path)
113
+ for page_num in range(len(pdf_document)):
114
+ page = pdf_document.load_page(page_num)
115
+ # Convert page to image
116
+ mat = fitz.Matrix(2.0, 2.0) # Increase resolution
117
+ pix = page.get_pixmap(matrix=mat)
118
+ img_data = pix.tobytes("ppm")
119
+ image = Image.open(BytesIO(img_data)).convert('RGB')
120
+ images.append(image)
121
+ pdf_document.close()
122
+ except Exception as e:
123
+ print(f"Error loading PDF: {e}")
124
+ return []
125
+ return images
126
+
127
+
128
+ def draw_layout_on_image(image: Image.Image, layout_data: List[Dict]) -> Image.Image:
129
+ """Draw layout bounding boxes on image"""
130
+ img_copy = image.copy()
131
+ draw = ImageDraw.Draw(img_copy)
132
+
133
+ # Colors for different categories
134
+ colors = {
135
+ 'Caption': '#FF6B6B',
136
+ 'Footnote': '#4ECDC4',
137
+ 'Formula': '#45B7D1',
138
+ 'List-item': '#96CEB4',
139
+ 'Page-footer': '#FFEAA7',
140
+ 'Page-header': '#DDA0DD',
141
+ 'Picture': '#FFD93D',
142
+ 'Section-header': '#6C5CE7',
143
+ 'Table': '#FD79A8',
144
+ 'Text': '#74B9FF',
145
+ 'Title': '#E17055'
146
+ }
147
+
148
+ try:
149
+ # Load a font
150
+ try:
151
+ font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 12)
152
+ except Exception:
153
+ font = ImageFont.load_default()
154
+
155
+ for item in layout_data:
156
+ if 'bbox' in item and 'category' in item:
157
+ bbox = item['bbox']
158
+ category = item['category']
159
+ color = colors.get(category, '#000000')
160
+
161
+ # Draw rectangle
162
+ draw.rectangle(bbox, outline=color, width=2)
163
+
164
+ # Draw label
165
+ label = category
166
+ label_bbox = draw.textbbox((0, 0), label, font=font)
167
+ label_width = label_bbox[2] - label_bbox[0]
168
+ label_height = label_bbox[3] - label_bbox[1]
169
+
170
+ # Position label above the box
171
+ label_x = bbox[0]
172
+ label_y = max(0, bbox[1] - label_height - 2)
173
+
174
+ # Draw background for label
175
+ draw.rectangle(
176
+ [label_x, label_y, label_x + label_width + 4, label_y + label_height + 2],
177
+ fill=color
178
+ )
179
+
180
+ # Draw text
181
+ draw.text((label_x + 2, label_y + 1), label, fill='white', font=font)
182
+
183
+ except Exception as e:
184
+ print(f"Error drawing layout: {e}")
185
+
186
+ return img_copy
187
+
188
+
189
+ def is_arabic_text(text: str) -> bool:
190
+ """Check if text in headers and paragraphs contains mostly Arabic characters"""
191
+ if not text:
192
+ return False
193
+
194
+ # Extract text from headers and paragraphs only
195
+ # Match markdown headers (# ## ###) and regular paragraph text
196
+ header_pattern = r'^#{1,6}\s+(.+)$'
197
+ paragraph_pattern = r'^(?!#{1,6}\s|!\[|```|\||\s*[-*+]\s|\s*\d+\.\s)(.+)$'
198
+
199
+ content_text = []
200
+
201
+ for line in text.split('\n'):
202
+ line = line.strip()
203
+ if not line:
204
+ continue
205
+
206
+ # Check for headers
207
+ header_match = re.match(header_pattern, line, re.MULTILINE)
208
+ if header_match:
209
+ content_text.append(header_match.group(1))
210
+ continue
211
+
212
+ # Check for paragraph text (exclude lists, tables, code blocks, images)
213
+ if re.match(paragraph_pattern, line, re.MULTILINE):
214
+ content_text.append(line)
215
+
216
+ if not content_text:
217
+ return False
218
+
219
+ # Join all content text and check for Arabic characters
220
+ combined_text = ' '.join(content_text)
221
+
222
+ # Arabic Unicode ranges
223
+ arabic_chars = 0
224
+ total_chars = 0
225
+
226
+ for char in combined_text:
227
+ if char.isalpha():
228
+ total_chars += 1
229
+ # Arabic script ranges
230
+ if ('\u0600' <= char <= '\u06FF') or ('\u0750' <= char <= '\u077F') or ('\u08A0' <= char <= '\u08FF'):
231
+ arabic_chars += 1
232
+
233
+ if total_chars == 0:
234
+ return False
235
+
236
+ # Consider text as Arabic if more than 50% of alphabetic characters are Arabic
237
+ return (arabic_chars / total_chars) > 0.5
238
+
239
+
240
+ def layoutjson2md(image: Image.Image, layout_data: List[Dict], text_key: str = 'text') -> str:
241
+ """Convert layout JSON to markdown format"""
242
+ import base64
243
+ from io import BytesIO
244
+
245
+ markdown_lines = []
246
+
247
+ try:
248
+ # Sort items by reading order (top to bottom, left to right)
249
+ sorted_items = sorted(layout_data, key=lambda x: (x.get('bbox', [0, 0, 0, 0])[1], x.get('bbox', [0, 0, 0, 0])[0]))
250
+
251
+ for item in sorted_items:
252
+ category = item.get('category', '')
253
+ text = item.get(text_key, '')
254
+ bbox = item.get('bbox', [])
255
+
256
+ if category == 'Picture':
257
+ # Extract image region and embed it
258
+ if bbox and len(bbox) == 4:
259
+ try:
260
+ # Extract the image region
261
+ x1, y1, x2, y2 = bbox
262
+ # Ensure coordinates are within image bounds
263
+ x1, y1 = max(0, int(x1)), max(0, int(y1))
264
+ x2, y2 = min(image.width, int(x2)), min(image.height, int(y2))
265
+
266
+ if x2 > x1 and y2 > y1:
267
+ cropped_img = image.crop((x1, y1, x2, y2))
268
+
269
+ # Convert to base64 for embedding
270
+ buffer = BytesIO()
271
+ cropped_img.save(buffer, format='PNG')
272
+ img_data = base64.b64encode(buffer.getvalue()).decode()
273
+
274
+ # Add as markdown image
275
+ markdown_lines.append(f"![Image](data:image/png;base64,{img_data})\n")
276
+ else:
277
+ markdown_lines.append("![Image](Image region detected)\n")
278
+ except Exception as e:
279
+ print(f"Error processing image region: {e}")
280
+ markdown_lines.append("![Image](Image detected)\n")
281
+ else:
282
+ markdown_lines.append("![Image](Image detected)\n")
283
+ elif not text:
284
+ continue
285
+ elif category == 'Title':
286
+ markdown_lines.append(f"# {text}\n")
287
+ elif category == 'Section-header':
288
+ markdown_lines.append(f"## {text}\n")
289
+ elif category == 'Text':
290
+ markdown_lines.append(f"{text}\n")
291
+ elif category == 'List-item':
292
+ markdown_lines.append(f"- {text}\n")
293
+ elif category == 'Table':
294
+ # If text is already HTML, keep it as is
295
+ if text.strip().startswith('<'):
296
+ markdown_lines.append(f"{text}\n")
297
+ else:
298
+ markdown_lines.append(f"**Table:** {text}\n")
299
+ elif category == 'Formula':
300
+ # If text is LaTeX, format it properly
301
+ if text.strip().startswith('$') or '\\' in text:
302
+ markdown_lines.append(f"$$\n{text}\n$$\n")
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':
308
+ markdown_lines.append(f"^{text}^\n")
309
+ elif category in ['Page-header', 'Page-footer']:
310
+ # Skip headers and footers in main content
311
+ continue
312
+ else:
313
+ markdown_lines.append(f"{text}\n")
314
+
315
+ markdown_lines.append("") # Add spacing
316
+
317
+ except Exception as e:
318
+ print(f"Error converting to markdown: {e}")
319
+ return str(layout_data)
320
+
321
+ return "\n".join(markdown_lines)
322
+
323
+ # Initialize model and processor at script level
324
+ model_id = "rednote-hilab/dots.ocr"
325
+ model_path = "./models/dots-ocr-local"
326
+ snapshot_download(
327
+ repo_id=model_id,
328
+ local_dir=model_path,
329
+ local_dir_use_symlinks=False, # Recommended to set to False to avoid symlink issues
330
+ )
331
+ model = AutoModelForCausalLM.from_pretrained(
332
+ model_path,
333
+ attn_implementation="flash_attention_2",
334
+ torch_dtype=torch.bfloat16,
335
+ device_map="auto",
336
+ trust_remote_code=True
337
+ )
338
+ processor = AutoProcessor.from_pretrained(
339
+ model_path,
340
+ trust_remote_code=True
341
+ )
342
+
343
+ # Global state variables
344
+ device = "cuda" if torch.cuda.is_available() else "cpu"
345
+
346
+ # PDF handling state
347
+ pdf_cache = {
348
+ "images": [],
349
+ "current_page": 0,
350
+ "total_pages": 0,
351
+ "file_type": None,
352
+ "is_parsed": False,
353
+ "results": []
354
+ }
355
+ @spaces.GPU()
356
+ def inference(image: Image.Image, prompt: str, max_new_tokens: int = 24000) -> str:
357
+ """Run inference on an image with the given prompt"""
358
+ try:
359
+ if model is None or processor is None:
360
+ raise RuntimeError("Model not loaded. Please check model initialization.")
361
+
362
+ # Prepare messages in the expected format
363
+ messages = [
364
+ {
365
+ "role": "user",
366
+ "content": [
367
+ {
368
+ "type": "image",
369
+ "image": image
370
+ },
371
+ {"type": "text", "text": prompt}
372
+ ]
373
+ }
374
+ ]
375
+
376
+ # Apply chat template
377
+ text = processor.apply_chat_template(
378
+ messages,
379
+ tokenize=False,
380
+ add_generation_prompt=True
381
+ )
382
+
383
+ # Process vision information
384
+ image_inputs, video_inputs = process_vision_info(messages)
385
+
386
+ # Prepare inputs
387
+ inputs = processor(
388
+ text=[text],
389
+ images=image_inputs,
390
+ videos=video_inputs,
391
+ padding=True,
392
+ return_tensors="pt",
393
+ )
394
+
395
+ # Move to device
396
+ inputs = inputs.to(device)
397
+
398
+ # Generate output
399
+ with torch.no_grad():
400
+ generated_ids = model.generate(
401
+ **inputs,
402
+ max_new_tokens=max_new_tokens,
403
+ do_sample=False,
404
+ temperature=0.1
405
+ )
406
+
407
+ # Decode output
408
+ generated_ids_trimmed = [
409
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
410
+ ]
411
+
412
+ output_text = processor.batch_decode(
413
+ generated_ids_trimmed,
414
+ skip_special_tokens=True,
415
+ clean_up_tokenization_spaces=False
416
+ )
417
+
418
+ return output_text[0] if output_text else ""
419
+
420
+ except Exception as e:
421
+ print(f"Error during inference: {e}")
422
+ traceback.print_exc()
423
+ return f"Error during inference: {str(e)}"
424
+
425
+
426
+ def process_image(
427
+ image: Image.Image,
428
+ min_pixels: Optional[int] = None,
429
+ max_pixels: Optional[int] = None
430
+ ) -> Dict[str, Any]:
431
+ """Process a single image with the specified prompt mode"""
432
+ try:
433
+ # Resize image if needed
434
+ if min_pixels is not None or max_pixels is not None:
435
+ image = fetch_image(image, min_pixels=min_pixels, max_pixels=max_pixels)
436
+
437
+ # Run inference with the default prompt
438
+ raw_output = inference(image, prompt)
439
+
440
+ # Process results based on prompt mode
441
+ result = {
442
+ 'original_image': image,
443
+ 'raw_output': raw_output,
444
+ 'processed_image': image,
445
+ 'layout_result': None,
446
+ 'markdown_content': None
447
+ }
448
+
449
+ # Try to parse JSON and create visualizations (since we're doing layout analysis)
450
+ try:
451
+ # Try to parse JSON output
452
+ layout_data = json.loads(raw_output)
453
+ result['layout_result'] = layout_data
454
+
455
+ # Create visualization with bounding boxes
456
+ try:
457
+ processed_image = draw_layout_on_image(image, layout_data)
458
+ result['processed_image'] = processed_image
459
+ except Exception as e:
460
+ print(f"Error drawing layout: {e}")
461
+ result['processed_image'] = image
462
+
463
+ # Generate markdown from layout data
464
+ try:
465
+ markdown_content = layoutjson2md(image, layout_data, text_key='text')
466
+ result['markdown_content'] = markdown_content
467
+ except Exception as e:
468
+ print(f"Error generating markdown: {e}")
469
+ result['markdown_content'] = raw_output
470
+
471
+ except json.JSONDecodeError:
472
+ print("Failed to parse JSON output, using raw output")
473
+ result['markdown_content'] = raw_output
474
+
475
+ return result
476
+
477
+ except Exception as e:
478
+ print(f"Error processing image: {e}")
479
+ traceback.print_exc()
480
+ return {
481
+ 'original_image': image,
482
+ 'raw_output': f"Error processing image: {str(e)}",
483
+ 'processed_image': image,
484
+ 'layout_result': None,
485
+ 'markdown_content': f"Error processing image: {str(e)}"
486
+ }
487
+
488
+
489
+ def load_file_for_preview(file_path: str) -> Tuple[Optional[Image.Image], str]:
490
+ """Load file for preview (supports PDF and images)"""
491
+ global pdf_cache
492
+
493
+ if not file_path or not os.path.exists(file_path):
494
+ return None, "No file selected"
495
+
496
+ file_ext = os.path.splitext(file_path)[1].lower()
497
+
498
+ try:
499
+ if file_ext == '.pdf':
500
+ # Load PDF pages
501
+ images = load_images_from_pdf(file_path)
502
+ if not images:
503
+ return None, "Failed to load PDF"
504
+
505
+ pdf_cache.update({
506
+ "images": images,
507
+ "current_page": 0,
508
+ "total_pages": len(images),
509
+ "file_type": "pdf",
510
+ "is_parsed": False,
511
+ "results": []
512
+ })
513
+
514
+ return images[0], f"Page 1 / {len(images)}"
515
+
516
+ elif file_ext in ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']:
517
+ # Load single image
518
+ image = Image.open(file_path).convert('RGB')
519
+
520
+ pdf_cache.update({
521
+ "images": [image],
522
+ "current_page": 0,
523
+ "total_pages": 1,
524
+ "file_type": "image",
525
+ "is_parsed": False,
526
+ "results": []
527
+ })
528
+
529
+ return image, "Page 1 / 1"
530
+ else:
531
+ return None, f"Unsupported file format: {file_ext}"
532
+
533
+ except Exception as e:
534
+ print(f"Error loading file: {e}")
535
+ return None, f"Error loading file: {str(e)}"
536
+
537
+
538
+ def turn_page(direction: str) -> Tuple[Optional[Image.Image], str, Any, Optional[Image.Image], Optional[Dict]]:
539
+ """Navigate through PDF pages and update all relevant outputs."""
540
+ global pdf_cache
541
+
542
+ if not pdf_cache["images"]:
543
+ return None, '<div class="page-info">No file loaded</div>', "No results yet", None, None
544
+
545
+ if direction == "prev":
546
+ pdf_cache["current_page"] = max(0, pdf_cache["current_page"] - 1)
547
+ elif direction == "next":
548
+ pdf_cache["current_page"] = min(
549
+ pdf_cache["total_pages"] - 1,
550
+ pdf_cache["current_page"] + 1
551
+ )
552
+
553
+ index = pdf_cache["current_page"]
554
+ current_image_preview = pdf_cache["images"][index]
555
+ page_info_html = f'<div class="page-info">Page {index + 1} / {pdf_cache["total_pages"]}</div>'
556
+
557
+ # Initialize default result values
558
+ markdown_content = "Page not processed yet"
559
+ processed_img = None
560
+ layout_json = None
561
+
562
+ # Get results for current page if available
563
+ if (pdf_cache["is_parsed"] and
564
+ index < len(pdf_cache["results"]) and
565
+ pdf_cache["results"][index]):
566
+
567
+ result = pdf_cache["results"][index]
568
+ markdown_content = result.get('markdown_content') or result.get('raw_output', 'No content available')
569
+ processed_img = result.get('processed_image', None) # Get the processed image
570
+ layout_json = result.get('layout_result', None) # Get the layout JSON
571
+
572
+ # Check for Arabic text to set RTL property
573
+ if is_arabic_text(markdown_content):
574
+ markdown_update = gr.update(value=markdown_content, rtl=True)
575
+ else:
576
+ markdown_update = markdown_content
577
+
578
+ return current_image_preview, page_info_html, markdown_update, processed_img, layout_json
579
+
580
+
581
+ def create_gradio_interface():
582
+ """Create the Gradio interface"""
583
+
584
+ # Custom CSS
585
+ css = """
586
+ .main-container {
587
+ max-width: 1400px;
588
+ margin: 0 auto;
589
+ }
590
+
591
+ .header-text {
592
+ text-align: center;
593
+ color: #2c3e50;
594
+ margin-bottom: 20px;
595
+ }
596
+
597
+ .process-button {
598
+ border: none !important;
599
+ color: white !important;
600
+ font-weight: bold !important;
601
+ }
602
+
603
+ .process-button:hover {
604
+ transform: translateY(-2px) !important;
605
+ box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important;
606
+ }
607
+
608
+ .info-box {
609
+ border: 1px solid #dee2e6;
610
+ border-radius: 8px;
611
+ padding: 15px;
612
+ margin: 10px 0;
613
+ }
614
+
615
+ .page-info {
616
+ text-align: center;
617
+ padding: 8px 16px;
618
+ border-radius: 20px;
619
+ font-weight: bold;
620
+ margin: 10px 0;
621
+ }
622
+
623
+ .model-status {
624
+ padding: 10px;
625
+ border-radius: 8px;
626
+ margin: 10px 0;
627
+ text-align: center;
628
+ font-weight: bold;
629
+ }
630
+
631
+ .status-ready {
632
+ background: #d1edff;
633
+ color: #0c5460;
634
+ border: 1px solid #b8daff;
635
+ }
636
+ """
637
+
638
+ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="Dots.OCR Demo") as demo:
639
+
640
+ # Header
641
+ gr.HTML("""
642
+ <div class="title" style="text-align: center">
643
+ <h1>πŸ” Dot-OCR - Multilingual Document Text Extraction</h1>
644
+ <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
645
+ A state-of-the-art image/pdf-to-markdown vision language model for intelligent document processing
646
+ </p>
647
+ <div style="display: flex; justify-content: center; gap: 20px; margin: 15px 0;">
648
+ <a href="https://huggingface.co/rednote-hilab/dots.ocr" target="_blank" style="text-decoration: none; color: #2563eb; font-weight: 500;">
649
+ πŸ“š Hugging Face Model
650
+ </a>
651
+ <a href="https://github.com/rednote-hilab/dots.ocr/blob/master/assets/blog.md" target="_blank" style="text-decoration: none; color: #2563eb; font-weight: 500;">
652
+ πŸ“ Release Blog
653
+ </a>
654
+ <a href="https://github.com/rednote-hilab/dots.ocr" target="_blank" style="text-decoration: none; color: #2563eb; font-weight: 500;">
655
+ πŸ’» GitHub Repository
656
+ </a>
657
+ </div>
658
+ </div>
659
+ """)
660
+
661
+ # Main interface
662
+ with gr.Row():
663
+ # Left column - Input and controls
664
+ with gr.Column(scale=1):
665
+
666
+ # File input
667
+ file_input = gr.File(
668
+ label="Upload Image or PDF",
669
+ file_types=[".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".pdf"],
670
+ type="filepath"
671
+ )
672
+
673
+ # Image preview
674
+ image_preview = gr.Image(
675
+ label="Preview",
676
+ type="pil",
677
+ interactive=False,
678
+ height=300
679
+ )
680
+
681
+ # Page navigation for PDFs
682
+ with gr.Row():
683
+ prev_page_btn = gr.Button("β—€ Previous", size="md")
684
+ page_info = gr.HTML('<div class="page-info">No file loaded</div>')
685
+ next_page_btn = gr.Button("Next β–Ά", size="md")
686
+
687
+ # Advanced settings
688
+ with gr.Accordion("Advanced Settings", open=False):
689
+ max_new_tokens = gr.Slider(
690
+ minimum=1000,
691
+ maximum=32000,
692
+ value=24000,
693
+ step=1000,
694
+ label="Max New Tokens",
695
+ info="Maximum number of tokens to generate"
696
+ )
697
+
698
+ min_pixels = gr.Number(
699
+ value=MIN_PIXELS,
700
+ label="Min Pixels",
701
+ info="Minimum image resolution"
702
+ )
703
+
704
+ max_pixels = gr.Number(
705
+ value=MAX_PIXELS,
706
+ label="Max Pixels",
707
+ info="Maximum image resolution"
708
+ )
709
+
710
+ # Process button
711
+ process_btn = gr.Button(
712
+ "πŸš€ Process Document",
713
+ variant="primary",
714
+ elem_classes=["process-button"],
715
+ size="lg"
716
+ )
717
+
718
+ # Clear button
719
+ clear_btn = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
720
+
721
+ # Right column - Results
722
+ with gr.Column(scale=2):
723
+
724
+ # Results tabs
725
+ with gr.Tabs():
726
+ # Processed image tab
727
+ with gr.Tab("πŸ–ΌοΈ Processed Image"):
728
+ processed_image = gr.Image(
729
+ label="Image with Layout Detection",
730
+ type="pil",
731
+ interactive=False,
732
+ height=500
733
+ )
734
+ # Markdown output tab
735
+ with gr.Tab("πŸ“ Extracted Content"):
736
+ markdown_output = gr.Markdown(
737
+ value="Click 'Process Document' to see extracted content...",
738
+ height=500
739
+ )
740
+ # JSON layout tab
741
+ with gr.Tab("πŸ“‹ Layout JSON"):
742
+ json_output = gr.JSON(
743
+ label="Layout Analysis Results",
744
+ value=None
745
+ )
746
+
747
+ # Event handlers
748
+ def process_document(file_path, max_tokens, min_pix, max_pix):
749
+ """Process the uploaded document"""
750
+ global pdf_cache
751
+
752
+ try:
753
+ if not file_path:
754
+ return None, "Please upload a file first.", None
755
+
756
+ if model is None:
757
+ return None, "Model not loaded. Please refresh the page and try again.", None
758
+
759
+ # Load and preview file
760
+ image, page_info = load_file_for_preview(file_path)
761
+ if image is None:
762
+ return None, page_info, None
763
+
764
+ # Process the image(s)
765
+ if pdf_cache["file_type"] == "pdf":
766
+ # Process all pages for PDF
767
+ all_results = []
768
+ all_markdown = []
769
+
770
+ for i, img in enumerate(pdf_cache["images"]):
771
+ result = process_image(
772
+ img,
773
+ min_pixels=int(min_pix) if min_pix else None,
774
+ max_pixels=int(max_pix) if max_pix else None
775
+ )
776
+ all_results.append(result)
777
+ if result.get('markdown_content'):
778
+ all_markdown.append(f"## Page {i+1}\n\n{result['markdown_content']}")
779
+
780
+ pdf_cache["results"] = all_results
781
+ pdf_cache["is_parsed"] = True
782
+
783
+ # Show results for first page
784
+ first_result = all_results[0]
785
+ combined_markdown = "\n\n---\n\n".join(all_markdown)
786
+
787
+ # Check if the combined markdown contains mostly Arabic text
788
+ if is_arabic_text(combined_markdown):
789
+ markdown_update = gr.update(value=combined_markdown, rtl=True)
790
+ else:
791
+ markdown_update = combined_markdown
792
+
793
+ return (
794
+ first_result['processed_image'],
795
+ markdown_update,
796
+ first_result['layout_result']
797
+ )
798
+ else:
799
+ # Process single image
800
+ result = process_image(
801
+ image,
802
+ min_pixels=int(min_pix) if min_pix else None,
803
+ max_pixels=int(max_pix) if max_pix else None
804
+ )
805
+
806
+ pdf_cache["results"] = [result]
807
+ pdf_cache["is_parsed"] = True
808
+
809
+ # Check if the content contains mostly Arabic text
810
+ content = result['markdown_content'] or "No content extracted"
811
+ if is_arabic_text(content):
812
+ markdown_update = gr.update(value=content, rtl=True)
813
+ else:
814
+ markdown_update = content
815
+
816
+ return (
817
+ result['processed_image'],
818
+ markdown_update,
819
+ result['layout_result']
820
+ )
821
+
822
+ except Exception as e:
823
+ error_msg = f"Error processing document: {str(e)}"
824
+ print(error_msg)
825
+ traceback.print_exc()
826
+ return None, error_msg, None
827
+
828
+ def handle_file_upload(file_path):
829
+ """Handle file upload and show preview"""
830
+ if not file_path:
831
+ return None, "No file loaded"
832
+
833
+ image, page_info = load_file_for_preview(file_path)
834
+ return image, page_info
835
+
836
+ def handle_page_turn(direction):
837
+ """Handle page navigation"""
838
+ image, page_info, result = turn_page(direction)
839
+ return image, page_info, result
840
+
841
+ def clear_all():
842
+ """Clear all data and reset interface"""
843
+ global pdf_cache
844
+
845
+ pdf_cache = {
846
+ "images": [], "current_page": 0, "total_pages": 0,
847
+ "file_type": None, "is_parsed": False, "results": []
848
+ }
849
+
850
+ return (
851
+ None, # file_input
852
+ None, # image_preview
853
+ '<div class="page-info">No file loaded</div>', # page_info
854
+ None, # processed_image
855
+ "Click 'Process Document' to see extracted content...", # markdown_output
856
+ None, # json_output
857
+ )
858
+
859
+ # Wire up event handlers
860
+ file_input.change(
861
+ handle_file_upload,
862
+ inputs=[file_input],
863
+ outputs=[image_preview, page_info]
864
+ )
865
+
866
+ # The outputs list is now updated to include all components that need to change
867
+ prev_page_btn.click(
868
+ lambda: turn_page("prev"),
869
+ outputs=[image_preview, page_info, markdown_output, processed_image, json_output]
870
+ )
871
+
872
+ next_page_btn.click(
873
+ lambda: turn_page("next"),
874
+ outputs=[image_preview, page_info, markdown_output, processed_image, json_output]
875
+ )
876
+
877
+ process_btn.click(
878
+ process_document,
879
+ inputs=[file_input, max_new_tokens, min_pixels, max_pixels],
880
+ outputs=[processed_image, markdown_output, json_output]
881
+ )
882
+
883
+ # The outputs list for the clear button is now correct
884
+ clear_btn.click(
885
+ clear_all,
886
+ outputs=[
887
+ file_input, image_preview, page_info, processed_image,
888
+ markdown_output, json_output
889
+ ]
890
+ )
891
+
892
+ return demo
893
+
894
+
895
+ if __name__ == "__main__":
896
+ # Create and launch the interface
897
+ demo = create_gradio_interface()
898
+ demo.queue(max_size=10).launch(
899
+ server_name="0.0.0.0",
900
+ server_port=7860,
901
+ share=False,
902
+ debug=True,
903
+ show_error=True
904
+ )