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