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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 _generate_text_and_confidence_for_crop(
427
+ image: Image.Image,
428
+ max_new_tokens: int = 128,
429
+ temperature: float = 0.1,
430
+ ) -> Tuple[str, float]:
431
+ """Generate text for a cropped region and compute average per-token confidence from model scores.
432
+
433
+ Returns (generated_text, average_confidence_percent).
434
+ """
435
+ try:
436
+ # Prepare a concise extraction prompt for the crop
437
+ messages = [
438
+ {
439
+ "role": "user",
440
+ "content": [
441
+ {"type": "image", "image": image},
442
+ {
443
+ "type": "text",
444
+ "text": "Extract the exact text content from this image region. Output text only without translation or additional words.",
445
+ },
446
+ ],
447
+ }
448
+ ]
449
+
450
+ # Apply chat template
451
+ text = processor.apply_chat_template(
452
+ messages, tokenize=False, add_generation_prompt=True
453
+ )
454
+
455
+ # Process vision information
456
+ image_inputs, video_inputs = process_vision_info(messages)
457
+
458
+ # Prepare inputs
459
+ inputs = processor(
460
+ text=[text],
461
+ images=image_inputs,
462
+ videos=video_inputs,
463
+ padding=True,
464
+ return_tensors="pt",
465
+ )
466
+ inputs = inputs.to(device)
467
+
468
+ # Generate with scores
469
+ with torch.no_grad():
470
+ outputs = model.generate(
471
+ **inputs,
472
+ max_new_tokens=max_new_tokens,
473
+ do_sample=False,
474
+ temperature=temperature,
475
+ output_scores=True,
476
+ return_dict_in_generate=True,
477
+ )
478
+
479
+ sequences = outputs.sequences # [batch, seq_len]
480
+ input_len = inputs.input_ids.shape[1]
481
+ # Trim input prompt ids to isolate generated tokens
482
+ generated_ids = sequences[:, input_len:]
483
+ generated_text = processor.batch_decode(
484
+ generated_ids,
485
+ skip_special_tokens=True,
486
+ clean_up_tokenization_spaces=False,
487
+ )[0].strip()
488
+
489
+ # Compute average probability of chosen tokens
490
+ confidences: List[float] = []
491
+ for step, step_scores in enumerate(outputs.scores or []):
492
+ # step_scores: [batch, vocab]
493
+ probs = torch.nn.functional.softmax(step_scores, dim=-1)
494
+ # token id chosen at this step
495
+ if input_len + step < sequences.shape[1]:
496
+ chosen_ids = sequences[:, input_len + step].unsqueeze(-1)
497
+ chosen_probs = probs.gather(dim=-1, index=chosen_ids) # [batch, 1]
498
+ confidences.append(float(chosen_probs[0, 0].item()))
499
+
500
+ avg_conf_percent = (sum(confidences) / len(confidences) * 100.0) if confidences else 0.0
501
+ return generated_text, avg_conf_percent
502
+ except Exception as e:
503
+ print(f"Error generating crop confidence: {e}")
504
+ traceback.print_exc()
505
+ return "", 0.0
506
+
507
+
508
+ def process_image(
509
+ image: Image.Image,
510
+ min_pixels: Optional[int] = None,
511
+ max_pixels: Optional[int] = None
512
+ ) -> Dict[str, Any]:
513
+ """Process a single image with the specified prompt mode"""
514
+ try:
515
+ # Resize image if needed
516
+ if min_pixels is not None or max_pixels is not None:
517
+ image = fetch_image(image, min_pixels=min_pixels, max_pixels=max_pixels)
518
+
519
+ # Run inference with the default prompt
520
+ raw_output = inference(image, prompt)
521
+
522
+ # Process results based on prompt mode
523
+ result = {
524
+ 'original_image': image,
525
+ 'raw_output': raw_output,
526
+ 'processed_image': image,
527
+ 'layout_result': None,
528
+ 'markdown_content': None
529
+ }
530
+
531
+ # Try to parse JSON and create visualizations (since we're doing layout analysis)
532
+ try:
533
+ # Try to parse JSON output
534
+ layout_data = json.loads(raw_output)
535
+
536
+ # Compute per-region confidence using the model on each cropped region
537
+ for idx, item in enumerate(layout_data):
538
+ try:
539
+ bbox = item.get('bbox', [])
540
+ text_content = item.get('text', '')
541
+ category = item.get('category', '')
542
+ if (not text_content) or category == 'Picture' or not bbox or len(bbox) != 4:
543
+ continue
544
+ x1, y1, x2, y2 = bbox
545
+ x1, y1 = max(0, int(x1)), max(0, int(y1))
546
+ x2, y2 = min(image.width, int(x2)), min(image.height, int(y2))
547
+ if x2 <= x1 or y2 <= y1:
548
+ continue
549
+ crop_img = image.crop((x1, y1, x2, y2))
550
+ # Generate and score text for this crop; we only keep the confidence
551
+ _, region_conf = _generate_text_and_confidence_for_crop(crop_img)
552
+ item['confidence'] = region_conf
553
+ except Exception as e:
554
+ print(f"Error scoring region {idx}: {e}")
555
+ # Leave confidence absent if scoring fails
556
+
557
+ result['layout_result'] = layout_data
558
+
559
+ # Create visualization with bounding boxes
560
+ try:
561
+ processed_image = draw_layout_on_image(image, layout_data)
562
+ result['processed_image'] = processed_image
563
+ except Exception as e:
564
+ print(f"Error drawing layout: {e}")
565
+ result['processed_image'] = image
566
+
567
+ # Generate markdown from layout data
568
+ try:
569
+ markdown_content = layoutjson2md(image, layout_data, text_key='text')
570
+ result['markdown_content'] = markdown_content
571
+ except Exception as e:
572
+ print(f"Error generating markdown: {e}")
573
+ result['markdown_content'] = raw_output
574
+
575
+ except json.JSONDecodeError:
576
+ print("Failed to parse JSON output, using raw output")
577
+ result['markdown_content'] = raw_output
578
+
579
+ return result
580
+
581
+ except Exception as e:
582
+ print(f"Error processing image: {e}")
583
+ traceback.print_exc()
584
+ return {
585
+ 'original_image': image,
586
+ 'raw_output': f"Error processing image: {str(e)}",
587
+ 'processed_image': image,
588
+ 'layout_result': None,
589
+ 'markdown_content': f"Error processing image: {str(e)}"
590
+ }
591
+
592
+
593
+ def load_file_for_preview(file_path: str) -> Tuple[Optional[Image.Image], str]:
594
+ """Load file for preview (supports PDF and images)"""
595
+ global pdf_cache
596
+
597
+ if not file_path or not os.path.exists(file_path):
598
+ return None, "No file selected"
599
+
600
+ file_ext = os.path.splitext(file_path)[1].lower()
601
+
602
+ try:
603
+ if file_ext == '.pdf':
604
+ # Load PDF pages
605
+ images = load_images_from_pdf(file_path)
606
+ if not images:
607
+ return None, "Failed to load PDF"
608
+
609
+ pdf_cache.update({
610
+ "images": images,
611
+ "current_page": 0,
612
+ "total_pages": len(images),
613
+ "file_type": "pdf",
614
+ "is_parsed": False,
615
+ "results": []
616
+ })
617
+
618
+ return images[0], f"Page 1 / {len(images)}"
619
+
620
+ elif file_ext in ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']:
621
+ # Load single image
622
+ image = Image.open(file_path).convert('RGB')
623
+
624
+ pdf_cache.update({
625
+ "images": [image],
626
+ "current_page": 0,
627
+ "total_pages": 1,
628
+ "file_type": "image",
629
+ "is_parsed": False,
630
+ "results": []
631
+ })
632
+
633
+ return image, "Page 1 / 1"
634
+ else:
635
+ return None, f"Unsupported file format: {file_ext}"
636
+
637
+ except Exception as e:
638
+ print(f"Error loading file: {e}")
639
+ return None, f"Error loading file: {str(e)}"
640
+
641
+
642
+ def turn_page(direction: str) -> Tuple[Optional[Image.Image], str, List, Any, Optional[Image.Image], Optional[Dict]]:
643
+ """Navigate through PDF pages and update all relevant outputs."""
644
+ global pdf_cache
645
+
646
+ if not pdf_cache["images"]:
647
+ return None, '<div class="page-info">No file loaded</div>', [], "No results yet", None, None
648
+
649
+ if direction == "prev":
650
+ pdf_cache["current_page"] = max(0, pdf_cache["current_page"] - 1)
651
+ elif direction == "next":
652
+ pdf_cache["current_page"] = min(
653
+ pdf_cache["total_pages"] - 1,
654
+ pdf_cache["current_page"] + 1
655
+ )
656
+
657
+ index = pdf_cache["current_page"]
658
+ current_image_preview = pdf_cache["images"][index]
659
+ page_info_html = f'<div class="page-info">Page {index + 1} / {pdf_cache["total_pages"]}</div>'
660
+
661
+ # Initialize default result values
662
+ markdown_content = "Page not processed yet"
663
+ processed_img = None
664
+ layout_json = None
665
+ ocr_table_data = []
666
+
667
+ # Get results for current page if available
668
+ if (pdf_cache["is_parsed"] and
669
+ index < len(pdf_cache["results"]) and
670
+ pdf_cache["results"][index]):
671
+
672
+ result = pdf_cache["results"][index]
673
+ markdown_content = result.get('markdown_content') or result.get('raw_output', 'No content available')
674
+ processed_img = result.get('processed_image', None) # Get the processed image
675
+ layout_json = result.get('layout_result', None) # Get the layout JSON
676
+
677
+ # Generate OCR table for current page
678
+ if layout_json and result.get('original_image'):
679
+ # Need to import the helper here or move it outside
680
+ import base64
681
+ from io import BytesIO
682
+
683
+ for idx, item in enumerate(layout_json):
684
+ bbox = item.get('bbox', [])
685
+ text = item.get('text', '')
686
+ category = item.get('category', '')
687
+
688
+ if not text or category == 'Picture':
689
+ continue
690
+
691
+ img_html = ""
692
+ if bbox and len(bbox) == 4:
693
+ try:
694
+ x1, y1, x2, y2 = bbox
695
+ orig_img = result['original_image']
696
+ x1, y1 = max(0, int(x1)), max(0, int(y1))
697
+ x2, y2 = min(orig_img.width, int(x2)), min(orig_img.height, int(y2))
698
+
699
+ if x2 > x1 and y2 > y1:
700
+ cropped_img = orig_img.crop((x1, y1, x2, y2))
701
+ buffer = BytesIO()
702
+ cropped_img.save(buffer, format='PNG')
703
+ img_data = base64.b64encode(buffer.getvalue()).decode()
704
+ img_html = f'<img src="data:image/png;base64,{img_data}" style="max-width:200px; max-height:100px; object-fit:contain;" />'
705
+ except Exception as e:
706
+ print(f"Error cropping region {idx}: {e}")
707
+ img_html = f"<div>Region {idx+1}</div>"
708
+ else:
709
+ img_html = f"<div>Region {idx+1}</div>"
710
+
711
+ # Extract confidence from item if available, otherwise N/A
712
+ confidence = item.get('confidence', 'N/A')
713
+ if isinstance(confidence, (int, float)):
714
+ confidence = f"{confidence:.1f}%"
715
+ elif confidence != 'N/A':
716
+ confidence = str(confidence)
717
+
718
+ ocr_table_data.append([img_html, text, confidence])
719
+
720
+ # Check for Arabic text to set RTL property
721
+ if is_arabic_text(markdown_content):
722
+ markdown_update = gr.update(value=markdown_content, rtl=True)
723
+ else:
724
+ markdown_update = markdown_content
725
+
726
+ return current_image_preview, page_info_html, ocr_table_data, markdown_update, processed_img, layout_json
727
+
728
+
729
+ def create_gradio_interface():
730
+ """Create the Gradio interface"""
731
+
732
+ # Custom CSS
733
+ css = """
734
+ .main-container {
735
+ max-width: 1400px;
736
+ margin: 0 auto;
737
+ }
738
+
739
+ .header-text {
740
+ text-align: center;
741
+ color: #2c3e50;
742
+ margin-bottom: 20px;
743
+ }
744
+
745
+ .process-button {
746
+ border: none !important;
747
+ color: white !important;
748
+ font-weight: bold !important;
749
+ }
750
+
751
+ .process-button:hover {
752
+ transform: translateY(-2px) !important;
753
+ box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important;
754
+ }
755
+
756
+ .info-box {
757
+ border: 1px solid #dee2e6;
758
+ border-radius: 8px;
759
+ padding: 15px;
760
+ margin: 10px 0;
761
+ }
762
+
763
+ .page-info {
764
+ text-align: center;
765
+ padding: 8px 16px;
766
+ border-radius: 20px;
767
+ font-weight: bold;
768
+ margin: 10px 0;
769
+ }
770
+
771
+ .model-status {
772
+ padding: 10px;
773
+ border-radius: 8px;
774
+ margin: 10px 0;
775
+ text-align: center;
776
+ font-weight: bold;
777
+ }
778
+
779
+ .status-ready {
780
+ background: #d1edff;
781
+ color: #0c5460;
782
+ border: 1px solid #b8daff;
783
+ }
784
+ """
785
+
786
+ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="Arabic OCR - Document Text Extraction") as demo:
787
+
788
+ # Header
789
+ gr.HTML("""
790
+ <div class="title" style="text-align: center">
791
+ <h1>🔍 Arabic OCR - Professional Document Text Extraction</h1>
792
+ <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
793
+ Advanced AI-powered OCR solution for Arabic documents with high accuracy layout detection and text extraction
794
+ </p>
795
+ </div>
796
+ """)
797
+
798
+ # Main interface
799
+ with gr.Row():
800
+ # Left column - Input and controls
801
+ with gr.Column(scale=1):
802
+
803
+ # File input
804
+ file_input = gr.File(
805
+ label="Upload Image or PDF",
806
+ file_types=[".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".pdf"],
807
+ type="filepath"
808
+ )
809
+
810
+ # Image preview
811
+ image_preview = gr.Image(
812
+ label="Preview",
813
+ type="pil",
814
+ interactive=False,
815
+ height=300
816
+ )
817
+
818
+ # Page navigation for PDFs
819
+ with gr.Row():
820
+ prev_page_btn = gr.Button("◀ Previous", size="md")
821
+ page_info = gr.HTML('<div class="page-info">No file loaded</div>')
822
+ next_page_btn = gr.Button("Next ▶", size="md")
823
+
824
+ # Advanced settings
825
+ with gr.Accordion("Advanced Settings", open=False):
826
+ max_new_tokens = gr.Slider(
827
+ minimum=1000,
828
+ maximum=32000,
829
+ value=24000,
830
+ step=1000,
831
+ label="Max New Tokens",
832
+ info="Maximum number of tokens to generate"
833
+ )
834
+
835
+ min_pixels = gr.Number(
836
+ value=MIN_PIXELS,
837
+ label="Min Pixels",
838
+ info="Minimum image resolution"
839
+ )
840
+
841
+ max_pixels = gr.Number(
842
+ value=MAX_PIXELS,
843
+ label="Max Pixels",
844
+ info="Maximum image resolution"
845
+ )
846
+
847
+ # Process button
848
+ process_btn = gr.Button(
849
+ "🚀 Process Document",
850
+ variant="primary",
851
+ elem_classes=["process-button"],
852
+ size="lg"
853
+ )
854
+
855
+ # Clear button
856
+ clear_btn = gr.Button("🗑️ Clear All", variant="secondary")
857
+
858
+ # Right column - Results
859
+ with gr.Column(scale=2):
860
+
861
+ # Results tabs
862
+ with gr.Tabs():
863
+ # Processed image tab
864
+ with gr.Tab("🖼️ Processed Image"):
865
+ processed_image = gr.Image(
866
+ label="Image with Layout Detection",
867
+ type="pil",
868
+ interactive=False,
869
+ height=500
870
+ )
871
+ # Editable OCR Results Table
872
+ with gr.Tab("📊 OCR Results Table"):
873
+ gr.Markdown("### Editable OCR Results\nReview and edit the extracted text for each detected region")
874
+ ocr_table = gr.Dataframe(
875
+ headers=["Region Image", "Extracted Text", "Confidence"],
876
+ datatype=["html", "str", "str"],
877
+ label="OCR Results",
878
+ interactive=True,
879
+ wrap=True,
880
+ height=500
881
+ )
882
+ # Markdown output tab
883
+ with gr.Tab("📝 Extracted Content"):
884
+ markdown_output = gr.Markdown(
885
+ value="Click 'Process Document' to see extracted content...",
886
+ height=500
887
+ )
888
+ # JSON layout tab
889
+ with gr.Tab("📋 Layout JSON"):
890
+ json_output = gr.JSON(
891
+ label="Layout Analysis Results",
892
+ value=None
893
+ )
894
+
895
+ # Helper function to create OCR table
896
+ def create_ocr_table(image: Image.Image, layout_data: List[Dict]) -> List[List[str]]:
897
+ """Create table data from layout results with cropped images"""
898
+ import base64
899
+ from io import BytesIO
900
+
901
+ if not layout_data:
902
+ return []
903
+
904
+ table_data = []
905
+
906
+ for idx, item in enumerate(layout_data):
907
+ bbox = item.get('bbox', [])
908
+ text = item.get('text', '')
909
+ category = item.get('category', '')
910
+
911
+ # Skip items without text or Picture category
912
+ if not text or category == 'Picture':
913
+ continue
914
+
915
+ # Crop the image region
916
+ img_html = ""
917
+ if bbox and len(bbox) == 4:
918
+ try:
919
+ x1, y1, x2, y2 = bbox
920
+ # Ensure coordinates are within image bounds
921
+ x1, y1 = max(0, int(x1)), max(0, int(y1))
922
+ x2, y2 = min(image.width, int(x2)), min(image.height, int(y2))
923
+
924
+ if x2 > x1 and y2 > y1:
925
+ cropped_img = image.crop((x1, y1, x2, y2))
926
+
927
+ # Convert to base64 for HTML display
928
+ buffer = BytesIO()
929
+ cropped_img.save(buffer, format='PNG')
930
+ img_data = base64.b64encode(buffer.getvalue()).decode()
931
+
932
+ # Create HTML img tag
933
+ img_html = f'<img src="data:image/png;base64,{img_data}" style="max-width:200px; max-height:100px; object-fit:contain;" />'
934
+ except Exception as e:
935
+ print(f"Error cropping region {idx}: {e}")
936
+ img_html = f"<div>Region {idx+1}</div>"
937
+ else:
938
+ img_html = f"<div>Region {idx+1}</div>"
939
+
940
+ # Add confidence score - extract from item if available, otherwise N/A
941
+ confidence = item.get('confidence', 'N/A')
942
+ if isinstance(confidence, (int, float)):
943
+ confidence = f"{confidence:.1f}%"
944
+ elif confidence != 'N/A':
945
+ confidence = str(confidence)
946
+
947
+ # Add row to table
948
+ table_data.append([img_html, text, confidence])
949
+
950
+ return table_data
951
+
952
+ # Event handlers
953
+ def process_document(file_path, max_tokens, min_pix, max_pix):
954
+ """Process the uploaded document"""
955
+ global pdf_cache
956
+
957
+ try:
958
+ if not file_path:
959
+ return None, [], "Please upload a file first.", None
960
+
961
+ if model is None:
962
+ return None, [], "Model not loaded. Please refresh the page and try again.", None
963
+
964
+ # Load and preview file
965
+ image, page_info = load_file_for_preview(file_path)
966
+ if image is None:
967
+ return None, [], page_info, None
968
+
969
+ # Process the image(s)
970
+ if pdf_cache["file_type"] == "pdf":
971
+ # Process all pages for PDF
972
+ all_results = []
973
+ all_markdown = []
974
+
975
+ for i, img in enumerate(pdf_cache["images"]):
976
+ result = process_image(
977
+ img,
978
+ min_pixels=int(min_pix) if min_pix else None,
979
+ max_pixels=int(max_pix) if max_pix else None
980
+ )
981
+ all_results.append(result)
982
+ if result.get('markdown_content'):
983
+ all_markdown.append(f"## Page {i+1}\n\n{result['markdown_content']}")
984
+
985
+ pdf_cache["results"] = all_results
986
+ pdf_cache["is_parsed"] = True
987
+
988
+ # Show results for first page
989
+ first_result = all_results[0]
990
+ combined_markdown = "\n\n---\n\n".join(all_markdown)
991
+
992
+ # Check if the combined markdown contains mostly Arabic text
993
+ if is_arabic_text(combined_markdown):
994
+ markdown_update = gr.update(value=combined_markdown, rtl=True)
995
+ else:
996
+ markdown_update = combined_markdown
997
+
998
+ # Create OCR table for first page
999
+ ocr_table_data = []
1000
+ if first_result['layout_result']:
1001
+ ocr_table_data = create_ocr_table(
1002
+ first_result['original_image'],
1003
+ first_result['layout_result']
1004
+ )
1005
+
1006
+ return (
1007
+ first_result['processed_image'],
1008
+ ocr_table_data,
1009
+ markdown_update,
1010
+ first_result['layout_result']
1011
+ )
1012
+ else:
1013
+ # Process single image
1014
+ result = process_image(
1015
+ image,
1016
+ min_pixels=int(min_pix) if min_pix else None,
1017
+ max_pixels=int(max_pix) if max_pix else None
1018
+ )
1019
+
1020
+ pdf_cache["results"] = [result]
1021
+ pdf_cache["is_parsed"] = True
1022
+
1023
+ # Check if the content contains mostly Arabic text
1024
+ content = result['markdown_content'] or "No content extracted"
1025
+ if is_arabic_text(content):
1026
+ markdown_update = gr.update(value=content, rtl=True)
1027
+ else:
1028
+ markdown_update = content
1029
+
1030
+ # Create OCR table
1031
+ ocr_table_data = []
1032
+ if result['layout_result']:
1033
+ ocr_table_data = create_ocr_table(
1034
+ result['original_image'],
1035
+ result['layout_result']
1036
+ )
1037
+
1038
+ return (
1039
+ result['processed_image'],
1040
+ ocr_table_data,
1041
+ markdown_update,
1042
+ result['layout_result']
1043
+ )
1044
+
1045
+ except Exception as e:
1046
+ error_msg = f"Error processing document: {str(e)}"
1047
+ print(error_msg)
1048
+ traceback.print_exc()
1049
+ return None, [], error_msg, None
1050
+
1051
+ def handle_file_upload(file_path):
1052
+ """Handle file upload and show preview"""
1053
+ if not file_path:
1054
+ return None, "No file loaded"
1055
+
1056
+ image, page_info = load_file_for_preview(file_path)
1057
+ return image, page_info
1058
+
1059
+ def handle_page_turn(direction):
1060
+ """Handle page navigation"""
1061
+ image, page_info, result = turn_page(direction)
1062
+ return image, page_info, result
1063
+
1064
+ def clear_all():
1065
+ """Clear all data and reset interface"""
1066
+ global pdf_cache
1067
+
1068
+ pdf_cache = {
1069
+ "images": [], "current_page": 0, "total_pages": 0,
1070
+ "file_type": None, "is_parsed": False, "results": []
1071
+ }
1072
+
1073
+ return (
1074
+ None, # file_input
1075
+ None, # image_preview
1076
+ '<div class="page-info">No file loaded</div>', # page_info
1077
+ None, # processed_image
1078
+ [], # ocr_table
1079
+ "Click 'Process Document' to see extracted content...", # markdown_output
1080
+ None, # json_output
1081
+ )
1082
+
1083
+ # Wire up event handlers
1084
+ file_input.change(
1085
+ handle_file_upload,
1086
+ inputs=[file_input],
1087
+ outputs=[image_preview, page_info]
1088
+ )
1089
+
1090
+ # The outputs list is now updated to include all components that need to change
1091
+ prev_page_btn.click(
1092
+ lambda: turn_page("prev"),
1093
+ outputs=[image_preview, page_info, ocr_table, markdown_output, processed_image, json_output]
1094
+ )
1095
+
1096
+ next_page_btn.click(
1097
+ lambda: turn_page("next"),
1098
+ outputs=[image_preview, page_info, ocr_table, markdown_output, processed_image, json_output]
1099
+ )
1100
+
1101
+ process_btn.click(
1102
+ process_document,
1103
+ inputs=[file_input, max_new_tokens, min_pixels, max_pixels],
1104
+ outputs=[processed_image, ocr_table, markdown_output, json_output]
1105
+ )
1106
+
1107
+ # The outputs list for the clear button is now correct
1108
+ clear_btn.click(
1109
+ clear_all,
1110
+ outputs=[
1111
+ file_input, image_preview, page_info, processed_image,
1112
+ ocr_table, markdown_output, json_output
1113
+ ]
1114
+ )
1115
+
1116
+ return demo
1117
+
1118
+
1119
+ if __name__ == "__main__":
1120
+ # Create and launch the interface
1121
+ demo = create_gradio_interface()
1122
+ demo.queue(max_size=10).launch(
1123
+ server_name="0.0.0.0",
1124
+ server_port=7860,
1125
+ share=False,
1126
+ debug=True,
1127
+ show_error=True
1128
+ )