saifisvibin commited on
Commit
fd2b9fb
Β·
verified Β·
1 Parent(s): 93b8ce2

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +845 -0
  2. main.py +1309 -0
  3. packages.txt +0 -0
  4. requirements.txt +16 -0
app.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ import shutil
5
+ import threading
6
+ import uuid
7
+ import time
8
+ import multiprocessing
9
+ from pathlib import Path
10
+ from typing import Dict, List, Optional, Any
11
+ from enum import Enum
12
+ from contextlib import asynccontextmanager
13
+
14
+ from fastapi import FastAPI, Request, File, UploadFile, Form, BackgroundTasks, HTTPException
15
+ from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
16
+ from fastapi.staticfiles import StaticFiles
17
+ from fastapi.middleware.cors import CORSMiddleware
18
+ from pydantic import BaseModel, Field
19
+ import re
20
+ import gradio as gr
21
+ # from werkzeug.utils import secure_filename # Removed dependency
22
+ import torch
23
+
24
+ import main as extractor
25
+ from loguru import logger
26
+
27
+ # --------------------------------------------------------------------------------
28
+ # CONFIGURATION
29
+ # --------------------------------------------------------------------------------
30
+
31
+ MAX_CONTENT_LENGTH = 500 * 1024 * 1024 # Not strictly enforced by FastAPI by default, but good to know
32
+ UPLOAD_FOLDER = Path('./uploads')
33
+ OUTPUT_FOLDER = Path('./output')
34
+
35
+ UPLOAD_FOLDER.mkdir(parents=True, exist_ok=True)
36
+ OUTPUT_FOLDER.mkdir(parents=True, exist_ok=True)
37
+
38
+ # Global model instance
39
+ _model = None
40
+ _progress_tracker: Dict[str, Dict] = {}
41
+ _progress_lock = threading.RLock()
42
+ # Global process pool
43
+ _pool = None
44
+
45
+
46
+ def secure_filename(filename: str) -> str:
47
+ """
48
+ Sanitize filename to prevent directory traversal and special chars.
49
+ Simplistic implementation to replace werkzeug.
50
+ """
51
+ filename = Path(filename).name
52
+ # Keep only alphanumeric, dots, hyphens, and underscores
53
+ filename = re.sub(r'[^a-zA-Z0-9_.-]', '_', filename)
54
+ return filename
55
+
56
+
57
+ def get_device_info() -> Dict[str, Any]:
58
+ """Get information about GPU/CPU availability."""
59
+ cuda_available = torch.cuda.is_available()
60
+ device = "cuda" if cuda_available else "cpu"
61
+
62
+ info = {
63
+ "device": device,
64
+ "cuda_available": cuda_available,
65
+ "device_name": None,
66
+ "device_count": 0,
67
+ }
68
+
69
+ if cuda_available:
70
+ info["device_name"] = torch.cuda.get_device_name(0)
71
+ info["device_count"] = torch.cuda.device_count()
72
+
73
+ return info
74
+
75
+ def load_model_once():
76
+ """Load the model once and cache it."""
77
+ global _model
78
+ if _model is None:
79
+ logger.info("Loading DocLayout-YOLO model...")
80
+ _model = extractor.get_model()
81
+ logger.info("Model loaded successfully")
82
+ return _model
83
+
84
+ @asynccontextmanager
85
+ async def lifespan(app: FastAPI):
86
+ """
87
+ Life span context manager for startup and shutdown events.
88
+ Initializes the multiprocessing pool for non-blocking CPU tasks.
89
+ """
90
+ global _pool
91
+ logger.info("Starting up PDF Layout Extractor...")
92
+
93
+ # Configure multiprocessing for PyTorch/CUDA
94
+ try:
95
+ multiprocessing.set_start_method('spawn', force=True)
96
+ except RuntimeError:
97
+ pass # Already set
98
+
99
+ # Initialize worker pool
100
+ try:
101
+ workers = max(1, multiprocessing.cpu_count() - 1)
102
+ # Check available memory/device for safe concurrency?
103
+ # For now rely on CPU count.
104
+ # Note: If CUDA is used, we must be careful with VRAM.
105
+ # main.py handles lazy loading in workers.
106
+ logger.info(f"Initializing background process pool with {workers} workers...")
107
+ _pool = multiprocessing.Pool(processes=workers, initializer=extractor.init_worker)
108
+ except Exception as e:
109
+ logger.error(f"Failed to initialize pool: {e}")
110
+ # non-fatal, will fallback to serial?
111
+ # actually if pool is None, app might error if we rely on it.
112
+ # But we'll handle it.
113
+ pass
114
+
115
+ yield
116
+
117
+ # Shutdown
118
+ logger.info("Shutting down PDF Layout Extractor...")
119
+ if _pool:
120
+ _pool.close()
121
+ _pool.join()
122
+
123
+ app = FastAPI(
124
+ title="PDF Layout Extractor API",
125
+ description="A polished API for extracting layout information (text, tables, figures) from PDFs using DocLayout-YOLO.",
126
+ version="1.0.0",
127
+ lifespan=lifespan
128
+ )
129
+
130
+ # Enable CORS
131
+ app.add_middleware(
132
+ CORSMiddleware,
133
+ allow_origins=["*"],
134
+ allow_credentials=True,
135
+ allow_methods=["*"],
136
+ allow_headers=["*"],
137
+ )
138
+
139
+ # Mount Static Files
140
+ # Mount Output as Static for easy access to generated images/PDFs
141
+ app.mount("/output", StaticFiles(directory="output"), name="output")
142
+
143
+
144
+ # --------------------------------------------------------------------------------
145
+ # Pydantic Models for Response Documentation
146
+ # --------------------------------------------------------------------------------
147
+
148
+ class DeviceInfo(BaseModel):
149
+ device: str = Field(..., description="Compute device being used (e.g., 'cuda' or 'cpu').")
150
+ cuda_available: bool = Field(..., description="Whether CUDA GPU acceleration is available.")
151
+ device_name: Optional[str] = Field(None, description="Name of the GPU if available.")
152
+ device_count: int = Field(..., description="Number of GPU devices detected.")
153
+
154
+ class TaskStartResponse(BaseModel):
155
+ task_id: str = Field(..., description="Unique identifier for the background processing task.")
156
+ message: str = Field(..., description="Status message confirming start.")
157
+ total_files: int = Field(..., description="Number of PDF files accepted for processing.")
158
+
159
+ class ProcessingResult(BaseModel):
160
+ filename: str = Field(..., description="Name of the processed file.")
161
+ stem: Optional[str] = Field(None, description="Filename without extension.")
162
+ output_dir: Optional[str] = Field(None, description="Relative path to the output directory.")
163
+ figures_count: Optional[int] = Field(0, description="Total figures detected.")
164
+ tables_count: Optional[int] = Field(0, description="Total tables detected.")
165
+ elements_count: Optional[int] = Field(0, description="Total layout elements (text, tables, figures).")
166
+ annotated_pdf: Optional[str] = Field(None, description="Path to the PDF with layout bounding boxes drawn.")
167
+ markdown_path: Optional[str] = Field(None, description="Path to the extracted markdown file.")
168
+ # Extended URLs
169
+ annotated_pdf_url: Optional[str] = Field(None, description="Full URL to access the annotated PDF.")
170
+ markdown_url: Optional[str] = Field(None, description="Full URL to access the extracted markdown.")
171
+ figure_urls: Optional[List[Dict[str, Any]]] = Field(None, description="List of URLs for extracted figure images.")
172
+ table_urls: Optional[List[Dict[str, Any]]] = Field(None, description="List of URLs for extracted table images.")
173
+ error: Optional[str] = Field(None, description="Error message if processing failed.")
174
+
175
+ class ExtractionMode(str, Enum):
176
+ images = "images"
177
+ markdown = "markdown"
178
+ both = "both"
179
+
180
+ class ProgressResponse(BaseModel):
181
+ status: str = Field(..., description="Current status of the task (e.g., 'processing', 'completed').")
182
+ progress: int = Field(..., description="Overall progress percentage (0-100).")
183
+ message: str = Field(..., description="Current status message.")
184
+ results: List[ProcessingResult] = Field([], description="List of results for processed files.")
185
+ file_progress: Optional[Dict[str, int]] = Field(None, description="Progress percentage per file.")
186
+
187
+ class PDFInfo(BaseModel):
188
+ stem: str = Field(..., description="Unique identifier/stem of the PDF.")
189
+ output_dir: str = Field(..., description="Directory where results are stored.")
190
+
191
+ class PDFListResponse(BaseModel):
192
+ pdfs: List[PDFInfo] = Field(..., description="List of processed PDFs available on the server.")
193
+
194
+ # --------------------------------------------------------------------------------
195
+ # Helper Functions
196
+ # --------------------------------------------------------------------------------
197
+
198
+ def _update_task_progress(task_id: str, filename: str, file_progress: int, message: str):
199
+ """Update progress for a specific file and calculate overall progress."""
200
+ with _progress_lock:
201
+ if task_id not in _progress_tracker:
202
+ return
203
+
204
+ # Update file-specific progress
205
+ if 'file_progress' not in _progress_tracker[task_id]:
206
+ _progress_tracker[task_id]['file_progress'] = {}
207
+ _progress_tracker[task_id]['file_progress'][filename] = file_progress
208
+
209
+ # Calculate overall progress (average of all files)
210
+ file_progresses = _progress_tracker[task_id]['file_progress']
211
+ if file_progresses:
212
+ total_progress = sum(file_progresses.values()) / len(file_progresses)
213
+ _progress_tracker[task_id]['progress'] = int(total_progress)
214
+
215
+ _progress_tracker[task_id]['message'] = message
216
+
217
+ def process_file_background_task(task_id: str, file_data: bytes, filename: str, extraction_mode: str):
218
+ """
219
+ Process a single file in the background (runs in a thread pool inside FastAPI/Starlette).
220
+ Note: For heavy CPU/GPU tasks, prefer running in a separate process or queue (like Celery),
221
+ but consistent with the request to 'use FastAPI' and the previous design, this is fine
222
+ since `fastapi.BackgroundTasks` runs in a thread pool.
223
+ """
224
+ filename = secure_filename(filename)
225
+
226
+ try:
227
+ _update_task_progress(task_id, filename, 5, f'Processing {filename}...')
228
+
229
+ stem = Path(filename).stem
230
+ include_images = extraction_mode != 'markdown'
231
+ include_markdown = extraction_mode != 'images'
232
+
233
+ # Ensure upload directory exists
234
+ upload_dir = UPLOAD_FOLDER
235
+ upload_path = upload_dir / filename
236
+ upload_path.write_bytes(file_data)
237
+
238
+ _update_task_progress(task_id, filename, 15, f'Saved {filename}, preparing output...')
239
+
240
+ # Prepare output directory
241
+ output_dir = OUTPUT_FOLDER / stem
242
+ output_dir.mkdir(parents=True, exist_ok=True)
243
+
244
+ # Copy PDF to output directory
245
+ pdf_path = output_dir / filename
246
+ # shutil.copy caused permissions issues in some envs, renaming/moving is safer if fresh upload
247
+ # But here we might want to keep the original in uploads?
248
+ # The original code did `upload_path.rename(pdf_path)`, so let's stick to that semantics:
249
+ # Move from temp upload to output dir
250
+ if pdf_path.exists():
251
+ pdf_path.unlink()
252
+ upload_path.rename(pdf_path)
253
+
254
+ _update_task_progress(task_id, filename, 25, f'Loading model and processing {filename}...')
255
+
256
+ # Process PDF
257
+ # Enable multiprocessing to release GIL and avoid blocking the event loop
258
+ extractor.USE_MULTIPROCESSING = True
259
+ logger.info(f"Processing {filename} (images={include_images}, markdown={include_markdown})")
260
+
261
+ # Note: When using a pool, we don't strictly need to load the model in THIS process
262
+ # unless we fallback to serial.
263
+ # But 'init_worker' loaded it in workers.
264
+
265
+ _update_task_progress(task_id, filename, 30, f'Extracting content from {filename}...')
266
+
267
+ # Use the global pool
268
+ # If _pool is None (initialization failed), main.py will fallback to serial (blocking this thread, but working)
269
+ extractor.process_pdf_with_pool(
270
+ pdf_path,
271
+ output_dir,
272
+ pool=_pool,
273
+ extract_images=include_images,
274
+ extract_markdown=include_markdown,
275
+ )
276
+
277
+ _update_task_progress(task_id, filename, 85, f'Collecting results for {filename}...')
278
+
279
+ # Collect results
280
+ json_path = output_dir / f"{stem}_content_list.json"
281
+ elements = []
282
+ if include_images and json_path.exists():
283
+ text_content = json_path.read_text(encoding='utf-8')
284
+ if text_content.strip():
285
+ elements = json.loads(text_content)
286
+
287
+ annotated_pdf = None
288
+ if include_images:
289
+ candidate_pdf = output_dir / f"{stem}_layout.pdf"
290
+ if candidate_pdf.exists():
291
+ annotated_pdf = str(candidate_pdf.relative_to(OUTPUT_FOLDER))
292
+
293
+ markdown_path = None
294
+ if include_markdown:
295
+ candidate_md = output_dir / f"{stem}.md"
296
+ if candidate_md.exists():
297
+ markdown_path = str(candidate_md.relative_to(OUTPUT_FOLDER))
298
+
299
+ figures = [e for e in elements if e.get('type') == 'figure']
300
+ tables = [e for e in elements if e.get('type') == 'table']
301
+
302
+ result = {
303
+ 'filename': filename,
304
+ 'stem': stem,
305
+ 'output_dir': str(output_dir.relative_to(OUTPUT_FOLDER)),
306
+ 'figures_count': len(figures),
307
+ 'tables_count': len(tables),
308
+ 'elements_count': len(elements),
309
+ 'annotated_pdf': annotated_pdf,
310
+ 'markdown_path': markdown_path,
311
+ 'include_images': include_images,
312
+ 'include_markdown': include_markdown,
313
+ }
314
+
315
+ with _progress_lock:
316
+ if 'file_progress' not in _progress_tracker[task_id]:
317
+ _progress_tracker[task_id]['file_progress'] = {}
318
+ _progress_tracker[task_id]['file_progress'][filename] = 100
319
+
320
+ # Recalculate total
321
+ file_progresses = _progress_tracker[task_id]['file_progress']
322
+ if file_progresses:
323
+ total_prog = sum(file_progresses.values()) / len(file_progresses)
324
+ _progress_tracker[task_id]['progress'] = int(total_prog)
325
+
326
+ _progress_tracker[task_id]['results'].append(result)
327
+ _progress_tracker[task_id]['message'] = f'Completed processing {filename}'
328
+
329
+ # Check completion
330
+ total_files = _progress_tracker[task_id].get('total_files', 1)
331
+ completed_count = len([r for r in _progress_tracker[task_id]['results'] if 'error' not in r])
332
+ error_count = len([r for r in _progress_tracker[task_id]['results'] if 'error' in r])
333
+
334
+ if completed_count + error_count >= total_files:
335
+ _progress_tracker[task_id]['status'] = 'completed'
336
+ _progress_tracker[task_id]['progress'] = 100
337
+ _progress_tracker[task_id]['message'] = f'All {total_files} file(s) processed.'
338
+
339
+ except Exception as e:
340
+ logger.error(f"Error processing {filename}: {e}")
341
+ import traceback
342
+ logger.error(traceback.format_exc())
343
+ with _progress_lock:
344
+ _progress_tracker[task_id]['results'].append({
345
+ 'filename': filename,
346
+ 'error': str(e)
347
+ })
348
+ # Check if this was the last file
349
+ total_files = _progress_tracker[task_id].get('total_files', 1)
350
+ if len(_progress_tracker[task_id]['results']) >= total_files:
351
+ _progress_tracker[task_id]['status'] = 'completed' # Mark done even if error, so frontend stops polling
352
+ _progress_tracker[task_id]['message'] = f'Finished with errors.'
353
+
354
+
355
+ # --------------------------------------------------------------------------------
356
+ # Routes
357
+ # --------------------------------------------------------------------------------
358
+
359
+ @app.get("/api/docs", response_class=HTMLResponse, tags=["UI"], include_in_schema=False)
360
+ async def api_docs_redirect():
361
+ """Redirect legacy /api/docs to Swagger UI."""
362
+ return HTMLResponse(
363
+ """
364
+ <html>
365
+ <head>
366
+ <meta http-equiv="refresh" content="0; url=/docs" />
367
+ </head>
368
+ <body>
369
+ <p>Redirecting to <a href="/docs">/docs</a>...</p>
370
+ </body>
371
+ </html>
372
+ """
373
+ )
374
+
375
+
376
+ @app.get("/api/device-info", response_model=DeviceInfo, tags=["System"])
377
+ async def device_info_endpoint():
378
+ """Get information about the processing device (CPU/GPU)."""
379
+ return get_device_info()
380
+
381
+
382
+ @app.post("/api/upload", response_model=TaskStartResponse, tags=["Processing"])
383
+ async def upload_files(
384
+ background_tasks: BackgroundTasks,
385
+ files: List[UploadFile] = File(...),
386
+ extraction_mode: ExtractionMode = Form(ExtractionMode.images, description="Select extraction mode: 'images' (figures/tables), 'markdown' (text), or 'both'.")
387
+ ):
388
+ """
389
+ Upload one or more PDF files for background processing.
390
+ """
391
+ if not files:
392
+ raise HTTPException(status_code=400, detail="No files provided")
393
+
394
+ pdf_files = [f for f in files if f.filename.lower().endswith('.pdf')]
395
+ if not pdf_files:
396
+ raise HTTPException(status_code=400, detail="No valid PDF files selected")
397
+
398
+ task_id = str(uuid.uuid4())
399
+
400
+ with _progress_lock:
401
+ _progress_tracker[task_id] = {
402
+ 'status': 'processing',
403
+ 'progress': 0,
404
+ 'message': 'Starting upload...',
405
+ 'results': [],
406
+ 'total_files': len(pdf_files)
407
+ }
408
+
409
+ # Read files into memory to pass to background task (UploadFile is a stream)
410
+ # Be careful with RAM here for huge files. If too big, save to temp disk first.
411
+ # Given the original code read into RAM, we'll do the same for consistency but simpler.
412
+ for file in pdf_files:
413
+ content = await file.read()
414
+ background_tasks.add_task(
415
+ process_file_background_task,
416
+ task_id,
417
+ content,
418
+ file.filename,
419
+ extraction_mode
420
+ )
421
+
422
+ return {
423
+ "task_id": task_id,
424
+ "message": "Processing started",
425
+ "total_files": len(pdf_files)
426
+ }
427
+
428
+
429
+ @app.get("/api/progress/{task_id}", response_model=ProgressResponse, tags=["Processing"])
430
+ async def get_progress(task_id: str, request: Request):
431
+ """Check the progress of a processing task."""
432
+ with _progress_lock:
433
+ progress = _progress_tracker.get(task_id)
434
+ if not progress:
435
+ raise HTTPException(status_code=404, detail="Task not found")
436
+
437
+ # Deep copy to modify for response (adding URLs) without changing state
438
+ # Or just build the response object.
439
+ # Since we are adding computed URLs, we shouldn't modify the stored state every time.
440
+ response_data = progress.copy()
441
+
442
+ # Use request.base_url for absolute URLs
443
+ base_url = str(request.base_url).rstrip('/')
444
+ if 'hf.space' in base_url or request.headers.get("x-forwarded-proto") == "https":
445
+ base_url = base_url.replace("http://", "https://")
446
+
447
+ # Process results to add URLs
448
+ results_with_urls = []
449
+ for res in response_data.get('results', []):
450
+ res_copy = res.copy()
451
+
452
+ # Helper to make url
453
+ def make_url(rel_path):
454
+ if not rel_path: return None
455
+ # Clean windows paths to forward slashes for URLs
456
+ clean_path = str(rel_path).replace('\\', '/')
457
+ return f"{base_url}/output/{clean_path}"
458
+
459
+ res_copy['annotated_pdf_url'] = make_url(res.get('annotated_pdf'))
460
+ res_copy['markdown_url'] = make_url(res.get('markdown_path'))
461
+
462
+ # Figures and Tables URLs need to be discovered from disk if not stored
463
+ # The original code loaded JSON every time. That's a bit heavy but ensures freshness.
464
+ # Let's try to do it if stem is present.
465
+ stem = res.get('stem')
466
+ if stem:
467
+ output_dir = OUTPUT_FOLDER / stem
468
+ if output_dir.exists():
469
+ json_files = list(output_dir.glob('*_content_list.json'))
470
+ if json_files:
471
+ try:
472
+ elements = json.loads(json_files[0].read_text(encoding='utf-8'))
473
+ figures = [e for e in elements if e.get('type') == 'figure']
474
+ tables = [e for e in elements if e.get('type') == 'table']
475
+
476
+ fig_urls = []
477
+ for fig in figures:
478
+ if fig.get('image_path'):
479
+ path = Path(fig['image_path']) # relative to unique output folder usually?
480
+ # Actually in main.py it saves relative to out_dir
481
+ # so image_path is like "figures/page_1_fig_0.png"
482
+ # We need relative to "output" folder for URL
483
+ # output_dir is "output/stem_timestamp"
484
+ # so full path is "output/stem_timestamp/figures/..."
485
+ # The URL mount is /output/ -> output/
486
+
487
+ # "image_path" in JSON is relative to the specific STEM folder (implied by main.py logic)
488
+ # Wait, main.py says: "image_path": str(path_template.relative_to(out_dir))
489
+ # So yes, it is "figures/..."
490
+
491
+ full_rel_path = f"{stem}/{fig['image_path']}"
492
+ fig_urls.append({
493
+ "page": fig.get('page'),
494
+ "url": make_url(full_rel_path),
495
+ "path": full_rel_path
496
+ })
497
+ res_copy['figure_urls'] = fig_urls
498
+
499
+ tab_urls = []
500
+ for tab in tables:
501
+ if tab.get('image_path'):
502
+ full_rel_path = f"{stem}/{tab['image_path']}"
503
+ tab_urls.append({
504
+ "page": tab.get('page'),
505
+ "url": make_url(full_rel_path),
506
+ "path": full_rel_path
507
+ })
508
+ res_copy['table_urls'] = tab_urls
509
+
510
+ except Exception as e:
511
+ logger.error(f"Error reading details for {stem}: {e}")
512
+
513
+ results_with_urls.append(res_copy)
514
+
515
+ response_data['results'] = results_with_urls
516
+ return response_data
517
+
518
+
519
+ @app.get("/api/pdf-list", response_model=PDFListResponse, tags=["Retrieval"])
520
+ async def pdf_list():
521
+ """List previously processed PDFs."""
522
+ output_dir = OUTPUT_FOLDER
523
+ pdfs = []
524
+
525
+ if output_dir.exists():
526
+ for item in output_dir.iterdir():
527
+ if item.is_dir():
528
+ # Check for indicators of success
529
+ if list(item.glob('*_content_list.json')) or list(item.glob('*.md')):
530
+ pdfs.append({
531
+ 'stem': item.name,
532
+ 'output_dir': item.name # returning the name as relative dir
533
+ })
534
+ return {'pdfs': pdfs}
535
+
536
+
537
+ @app.get("/api/pdf-details/{pdf_stem}", tags=["Retrieval"])
538
+ async def pdf_details(pdf_stem: str, request: Request):
539
+ """Get detailed information about a processed PDF."""
540
+ output_dir = OUTPUT_FOLDER / pdf_stem
541
+
542
+ if not output_dir.exists():
543
+ raise HTTPException(status_code=404, detail="PDF not found")
544
+
545
+ base_url = str(request.base_url).rstrip('/')
546
+ if 'hf.space' in base_url or request.headers.get("x-forwarded-proto") == "https":
547
+ base_url = base_url.replace("http://", "https://")
548
+
549
+ def make_url(rel_path):
550
+ if not rel_path: return None
551
+ clean_path = str(rel_path).replace('\\', '/')
552
+ return f"{base_url}/output/{clean_path}"
553
+
554
+ # Load content list
555
+ json_files = list(output_dir.glob('*_content_list.json'))
556
+ elements = []
557
+ if json_files:
558
+ elements = json.loads(json_files[0].read_text(encoding='utf-8'))
559
+
560
+ figures = [e for e in elements if e.get('type') == 'figure']
561
+ tables = [e for e in elements if e.get('type') == 'table']
562
+
563
+ # PDF Layout
564
+ annotated_pdf = None
565
+ pdf_files = list(output_dir.glob('*_layout.pdf'))
566
+ if pdf_files:
567
+ annotated_pdf = f"{pdf_stem}/{pdf_files[0].name}"
568
+
569
+ # Markdown
570
+ markdown_path = None
571
+ md_files = list(output_dir.glob('*.md'))
572
+ if md_files:
573
+ markdown_path = f"{pdf_stem}/{md_files[0].name}"
574
+
575
+ # Image lists
576
+ figure_images = []
577
+ fig_dir = output_dir / 'figures'
578
+ if fig_dir.exists():
579
+ figure_images = [f"{pdf_stem}/figures/{f.name}" for f in sorted(fig_dir.glob('*.png'))]
580
+
581
+ table_images = []
582
+ tab_dir = output_dir / 'tables'
583
+ if tab_dir.exists():
584
+ table_images = [f"{pdf_stem}/tables/{f.name}" for f in sorted(tab_dir.glob('*.png'))]
585
+
586
+ return {
587
+ 'stem': pdf_stem,
588
+ 'figures': figures,
589
+ 'tables': tables,
590
+ 'figures_count': len(figures),
591
+ 'tables_count': len(tables),
592
+ 'elements_count': len(elements),
593
+ 'annotated_pdf': annotated_pdf,
594
+ 'markdown_path': markdown_path,
595
+ 'figure_images': figure_images,
596
+ 'table_images': table_images,
597
+ 'urls': {
598
+ 'annotated_pdf': make_url(annotated_pdf),
599
+ 'markdown': make_url(markdown_path),
600
+ 'figures': [make_url(img) for img in figure_images],
601
+ 'tables': [make_url(img) for img in table_images],
602
+ }
603
+ }
604
+
605
+
606
+ @app.post("/api/predict", tags=["Legacy"], include_in_schema=True)
607
+ async def predict(
608
+ file: UploadFile = File(...),
609
+ request: Request = None
610
+ ):
611
+ """
612
+ Direct API endpoint for extracting text/tables/figures from a single PDF.
613
+ Waits for completion and returns JSON result.
614
+ """
615
+ if not file.filename.lower().endswith('.pdf'):
616
+ raise HTTPException(status_code=400, detail="Invalid file type. Please upload a PDF.")
617
+
618
+ # Create unique output directory
619
+ filename = secure_filename(file.filename)
620
+ stem = Path(filename).stem
621
+ unique_id = f"{stem}_{int(time.time())}"
622
+ output_dir = OUTPUT_FOLDER / unique_id
623
+ output_dir.mkdir(parents=True, exist_ok=True)
624
+
625
+ # Save file
626
+ pdf_path = output_dir / filename
627
+ content = await file.read()
628
+ pdf_path.write_bytes(content)
629
+
630
+ try:
631
+ # Load model logic (sync call to stay simple for this endpoint)
632
+ load_model_once()
633
+ extractor.USE_MULTIPROCESSING = False
634
+
635
+ # Process
636
+ extractor.process_pdf_with_pool(
637
+ pdf_path,
638
+ output_dir,
639
+ pool=None,
640
+ extract_images=True,
641
+ extract_markdown=True,
642
+ )
643
+
644
+ # Build Result
645
+ base_url = str(request.base_url).rstrip('/')
646
+ if 'hf.space' in base_url or request.headers.get("x-forwarded-proto") == "https":
647
+ base_url = base_url.replace("http://", "https://")
648
+
649
+ def make_url(rel_path):
650
+ return f"{base_url}/output/{unique_id}/{rel_path}"
651
+
652
+ result = {
653
+ "status": "success",
654
+ "filename": filename,
655
+ "text": "",
656
+ "tables": [],
657
+ "figures": [],
658
+ "summary": {}
659
+ }
660
+
661
+ # Text
662
+ md_path = output_dir / f"{stem}.md"
663
+ if md_path.exists():
664
+ result['text'] = md_path.read_text(encoding='utf-8')
665
+
666
+ # JSON content
667
+ json_path = output_dir / f"{stem}_content_list.json"
668
+ if json_path.exists():
669
+ elements = json.loads(json_path.read_text(encoding='utf-8'))
670
+
671
+ figures = [e for e in elements if e.get('type') == 'figure']
672
+ result['figures'] = [{
673
+ **fig,
674
+ 'image_url': make_url(fig.get('image_path')) if fig.get('image_path') else None
675
+ } for fig in figures]
676
+
677
+ tables = [e for e in elements if e.get('type') == 'table']
678
+ result['tables'] = [{
679
+ **tab,
680
+ 'image_url': make_url(tab.get('image_path')) if tab.get('image_path') else None
681
+ } for tab in tables]
682
+
683
+ result['summary'] = {
684
+ 'figures_count': len(figures),
685
+ 'tables_count': len(tables),
686
+ 'elements_count': len(elements)
687
+ }
688
+
689
+ return result
690
+
691
+ except Exception as e:
692
+ logger.error(f"Error in predict: {e}")
693
+ import traceback
694
+ logger.error(traceback.format_exc())
695
+ raise HTTPException(status_code=500, detail=str(e))
696
+
697
+
698
+ @app.post("/api/delete", tags=["Processing"])
699
+ async def delete_pdf(stem: str = Form(...)):
700
+ """Delete a processed PDF and its output directory."""
701
+ if not stem:
702
+ raise HTTPException(status_code=400, detail="Missing stem")
703
+
704
+ # Resolve output directory safely
705
+ output_root = OUTPUT_FOLDER.resolve()
706
+ target_dir = (output_root / stem).resolve()
707
+
708
+ # Prevent path traversal
709
+ if output_root not in target_dir.parents and target_dir != output_root:
710
+ raise HTTPException(status_code=400, detail="Invalid stem path")
711
+
712
+ if not target_dir.exists() or not target_dir.is_dir():
713
+ raise HTTPException(status_code=404, detail="Not found")
714
+
715
+ try:
716
+ shutil.rmtree(target_dir)
717
+ return {"status": "success", "message": f"Deleted {stem}"}
718
+ except Exception as e:
719
+ # Try to fix read-only files (common on Windows)
720
+ try:
721
+ import stat
722
+ def on_rm_error(func, path, exc_info):
723
+ os.chmod(path, stat.S_IWRITE)
724
+ func(path)
725
+ shutil.rmtree(target_dir, onerror=on_rm_error)
726
+ return {"status": "success", "message": f"Deleted {stem}"}
727
+ except Exception as e2:
728
+ logger.error(f"Error deleting {stem}: {e2}")
729
+ raise HTTPException(status_code=500, detail=f"Failed to delete: {str(e2)}")
730
+
731
+
732
+ raise HTTPException(status_code=500, detail=f"Failed to delete: {str(e2)}")
733
+
734
+
735
+ # --------------------------------------------------------------------------------
736
+ # Gradio Interface
737
+ # --------------------------------------------------------------------------------
738
+
739
+ def gradio_process(pdf_file, mode_str):
740
+ """
741
+ Wrapper for Gradio to call the extractor logic.
742
+ """
743
+ if pdf_file is None:
744
+ return None, None, None, "No file uploaded."
745
+
746
+ try:
747
+ # Create unique directory
748
+ filename = secure_filename(Path(pdf_file.name).name)
749
+ stem = Path(filename).stem
750
+ unique_id = f"{stem}_{int(time.time())}"
751
+ output_dir = OUTPUT_FOLDER / unique_id
752
+ output_dir.mkdir(parents=True, exist_ok=True)
753
+
754
+ # Copy file
755
+ dest_path = output_dir / filename
756
+ shutil.copy(pdf_file.name, dest_path)
757
+
758
+ # Determine flags
759
+ include_images = (mode_str != "markdown")
760
+ include_markdown = (mode_str != "images")
761
+
762
+ # Process (sync for Gradio simplicity, or use utils)
763
+ # We need to load model if not loaded
764
+ load_model_once()
765
+ extractor.USE_MULTIPROCESSING = False # Gradio usually runs in thread
766
+
767
+ extractor.process_pdf_with_pool(
768
+ dest_path,
769
+ output_dir,
770
+ pool=None,
771
+ extract_images=include_images,
772
+ extract_markdown=include_markdown
773
+ )
774
+
775
+ # Collect outputs
776
+ md_text = ""
777
+ md_path = output_dir / f"{stem}.md"
778
+ if md_path.exists():
779
+ md_text = md_path.read_text(encoding='utf-8')
780
+
781
+ annotated_pdf = None
782
+ pdf_layout_path = output_dir / f"{stem}_layout.pdf"
783
+ if pdf_layout_path.exists():
784
+ annotated_pdf = str(pdf_layout_path)
785
+
786
+ gallery = []
787
+ if include_images:
788
+ fig_dir = output_dir / 'figures'
789
+ if fig_dir.exists():
790
+ gallery.extend([str(p) for p in fig_dir.glob('*.png')])
791
+ tab_dir = output_dir / 'tables'
792
+ if tab_dir.exists():
793
+ gallery.extend([str(p) for p in tab_dir.glob('*.png')])
794
+
795
+ return md_text, gallery, annotated_pdf, f"Processed {filename} successfully."
796
+
797
+ except Exception as e:
798
+ logger.error(f"Gradio Error: {e}")
799
+ return str(e), None, None, f"Error: {e}"
800
+
801
+ # Define Gradio App
802
+ with gr.Blocks(title="PDF Layout Extractor") as demo:
803
+ gr.Markdown("# PDF Layout Extractor")
804
+ gr.Markdown("Upload a PDF to extract text (Markdown), figures, tables, and visualization.")
805
+
806
+ with gr.Row():
807
+ with gr.Column():
808
+ input_pdf = gr.File(label="Upload PDF", file_types=[".pdf"])
809
+ mode_input = gr.Radio(["both", "images", "markdown"], label="Extraction Mode", value="both")
810
+ process_btn = gr.Button("Extract Layout", variant="primary")
811
+
812
+ with gr.Column():
813
+ status_msg = gr.Textbox(label="Status", interactive=False)
814
+ output_md = gr.Code(label="Extracted Simple Markdown", language="markdown")
815
+
816
+ with gr.Row():
817
+ output_pdf = gr.File(label="Annotated PDF Layout")
818
+ output_gallery = gr.Gallery(label="Extracted Images (Figures/Tables)")
819
+
820
+ process_btn.click(
821
+ fn=gradio_process,
822
+ inputs=[input_pdf, mode_input],
823
+ outputs=[output_md, output_gallery, output_pdf, status_msg]
824
+ )
825
+
826
+
827
+ # Mount Gradio to FastAPI
828
+ # We mount it at the root "/" to replace the old index.html,
829
+ # OR we can mount it at "/gradio" and keep the old UI.
830
+ # The user said "switch to gradio", implying replacement or primary usage.
831
+ # HF Spaces expects the app at root.
832
+ # But we have specific API endpoints.
833
+ # Let's mount Gradio at "/" and move the custom API docs to "/docs" (already there).
834
+ # Wait, if we mount at "/", it might shadow "/api" if not careful?
835
+ # No, FastAPI routing takes precedence if defined before mounting, usually.
836
+ # But `gr.mount_gradio_app` documentation says it mounts a sub-app.
837
+ # If path="", it mounts at root.
838
+ # Let's mount at "/" but ensure API routes work.
839
+ # Actually, `mount_gradio_app` handles this gracefully if we pass the `app`.
840
+
841
+ app = gr.mount_gradio_app(app, demo, path="/")
842
+
843
+ if __name__ == "__main__":
844
+ import uvicorn
845
+ uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
main.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import signal
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import List, Dict, Tuple, Optional, Sequence, Set, Any
7
+ from multiprocessing import Pool, cpu_count
8
+ from functools import partial
9
+
10
+ import fitz # PyMuPDF (Still needed for drawing output PDF)
11
+ import pypdfium2 as pdfium
12
+ import torch
13
+ from doclayout_yolo import YOLOv10
14
+ from huggingface_hub import hf_hub_download
15
+ from loguru import logger
16
+ from PIL import Image
17
+ import numpy as np
18
+
19
+ try:
20
+ import pymupdf4llm # type: ignore
21
+ except ImportError: # pragma: no cover - optional dependency
22
+ pymupdf4llm = None # type: ignore
23
+
24
+ # ----------------------------------------------------------------------
25
+ # CONFIGURATION
26
+ # ----------------------------------------------------------------------
27
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
28
+
29
+ # Model options
30
+ MODEL_SIZE = 1024
31
+ REPO_ID = "juliozhao/DocLayout-YOLO-DocStructBench"
32
+ WEIGHTS_FILE = f"doclayout_yolo_docstructbench_imgsz{MODEL_SIZE}.pt"
33
+
34
+ # Detection settings
35
+ CONF_THRESHOLD = 0.25
36
+
37
+ # Multiprocessing settings
38
+ NUM_WORKERS = None # None = auto (cpu_count - 1), or set to specific number like 4
39
+ USE_MULTIPROCESSING = True # Set to False to disable parallel processing entirely
40
+
41
+ # ----------------------------------------------------------------------
42
+ # Color map for the layout classes
43
+ # ----------------------------------------------------------------------
44
+ CLASS_COLORS = {
45
+ "text": (0, 128, 0), # Dark Green
46
+ "title": (192, 0, 0), # Dark Red
47
+ "figure": (0, 0, 192), # Dark Blue
48
+ "table": (218, 165, 32), # Goldenrod (Dark Yellow)
49
+ "list": (128, 0, 128), # Purple
50
+ "header": (0, 128, 128), # Teal
51
+ "footer": (100, 100, 100), # Dark Gray
52
+ "figure_caption": (0, 0, 128), # Navy
53
+ "table_caption": (139, 69, 19), # Saddle Brown
54
+ "table_footnote": (128, 0, 128), # Purple
55
+ }
56
+
57
+ # Global model instance (will be None in worker processes until loaded)
58
+ _model = None
59
+ _shutdown_requested = False
60
+
61
+ # ----------------------------------------------------------------------
62
+ # Signal handler for graceful shutdown
63
+ # ----------------------------------------------------------------------
64
+ def signal_handler(signum, frame):
65
+ """Handle interrupt signals gracefully."""
66
+ global _shutdown_requested
67
+ if not _shutdown_requested:
68
+ _shutdown_requested = True
69
+ logger.warning("\n⚠️ Interrupt received! Finishing current page and shutting down gracefully...")
70
+ logger.warning("Press Ctrl+C again to force quit (may leave incomplete files)")
71
+ else:
72
+ logger.error("\n❌ Force quit requested. Exiting immediately.")
73
+ sys.exit(1)
74
+
75
+ def setup_signal_handlers():
76
+ """Setup signal handlers for graceful shutdown."""
77
+ signal.signal(signal.SIGINT, signal_handler)
78
+ signal.signal(signal.SIGTERM, signal_handler)
79
+
80
+ # ----------------------------------------------------------------------
81
+ # Model loader function
82
+ # ----------------------------------------------------------------------
83
+ def get_model():
84
+ """Lazy load the model (only once per process)."""
85
+ global _model
86
+ if _model is None:
87
+ weights_path = hf_hub_download(repo_id=REPO_ID, filename=WEIGHTS_FILE)
88
+ _model = YOLOv10(weights_path)
89
+ logger.info(f"βœ“ Model loaded in worker process (PID: {os.getpid()})")
90
+ return _model
91
+
92
+ # ----------------------------------------------------------------------
93
+ # Worker initialization function
94
+ # ----------------------------------------------------------------------
95
+ def init_worker():
96
+ """Initialize worker process - loads model once at startup."""
97
+ try:
98
+ get_model()
99
+ logger.success(f"Worker {os.getpid()} ready")
100
+ except Exception as e:
101
+ logger.error(f"Failed to initialize worker {os.getpid()}: {e}")
102
+ raise
103
+
104
+ # ----------------------------------------------------------------------
105
+ # Run layout detection on a single page image (YOLO)
106
+ # ----------------------------------------------------------------------
107
+ def detect_page(pil_img: Image.Image) -> List[dict]:
108
+ """Detect layout elements using YOLO model."""
109
+ model = get_model() # Will return already-loaded model in worker
110
+ img_cv = np.array(pil_img)
111
+ results = model.predict(
112
+ img_cv,
113
+ imgsz=MODEL_SIZE,
114
+ conf=CONF_THRESHOLD,
115
+ device=DEVICE,
116
+ verbose=False
117
+ )
118
+ dets = []
119
+ for i, box in enumerate(results[0].boxes):
120
+ cls_id = int(box.cls.item())
121
+ name = results[0].names[cls_id]
122
+ conf = float(box.conf.item())
123
+ x0, y0, x1, y1 = box.xyxy[0].cpu().numpy().tolist()
124
+ dets.append({
125
+ "name": name,
126
+ "bbox": [x0, y0, x1, y1],
127
+ "conf": conf,
128
+ "source": "yolo",
129
+ "index": i
130
+ })
131
+ return dets
132
+
133
+ # ----------------------------------------------------------------------
134
+ # Crop & save figure/table regions (with captions)
135
+ # ----------------------------------------------------------------------
136
+ def get_union_box(box1: List[float], box2: List[float]) -> List[float]:
137
+ """Get the bounding box enclosing two boxes."""
138
+ x0 = min(box1[0], box2[0])
139
+ y0 = min(box1[1], box2[1])
140
+ x1 = max(box1[2], box2[2])
141
+ y1 = max(box1[3], box2[3])
142
+ return [x0, y0, x1, y1]
143
+
144
+ def collect_caption_elements(
145
+ element: Dict,
146
+ all_dets: List[Dict],
147
+ target_name: str,
148
+ max_vertical_gap: float = 60.0,
149
+ min_overlap: float = 0.25,
150
+ ) -> List[Dict]:
151
+ """
152
+ Collect contiguous caption detections directly below a figure/table.
153
+ """
154
+ base_box = element["bbox"]
155
+ base_bottom = base_box[3]
156
+ selected: List[Dict] = []
157
+ last_bottom = base_bottom
158
+
159
+ relevant = [
160
+ d for d in all_dets
161
+ if d["name"] == target_name and d["bbox"][1] >= base_bottom - 5
162
+ ]
163
+
164
+ relevant.sort(key=lambda d: d["bbox"][1])
165
+
166
+ for cand in relevant:
167
+ cand_box = cand["bbox"]
168
+ top = cand_box[1]
169
+ if selected and top - last_bottom > max_vertical_gap:
170
+ break
171
+
172
+ if selected:
173
+ overlap = _horizontal_overlap_ratio(selected[-1]["bbox"], cand_box)
174
+ else:
175
+ overlap = _horizontal_overlap_ratio(base_box, cand_box)
176
+
177
+ if overlap < min_overlap:
178
+ continue
179
+
180
+ selected.append(cand)
181
+ last_bottom = cand_box[3]
182
+
183
+ return selected
184
+
185
+
186
+ def collect_title_and_text_segments(
187
+ element: Dict,
188
+ all_dets: List[Dict],
189
+ processed_indices: Set[int],
190
+ settings: Optional[Dict[str, float]] = None,
191
+ ) -> Tuple[List[Dict], List[Dict]]:
192
+ """
193
+ Locate a title below the element and any contiguous text blocks directly beneath it.
194
+ """
195
+ if settings is None:
196
+ settings = TITLE_TEXT_ASSOCIATION
197
+
198
+ if not element.get("bbox"):
199
+ return [], []
200
+
201
+ figure_box = element["bbox"]
202
+ figure_bottom = figure_box[3]
203
+
204
+ candidates = [
205
+ d for d in all_dets
206
+ if d.get("bbox") and d["index"] not in processed_indices
207
+ ]
208
+ candidates.sort(key=lambda d: d["bbox"][1])
209
+
210
+ titles: List[Dict] = []
211
+ texts: List[Dict] = []
212
+
213
+ for idx, det in enumerate(candidates):
214
+ if det["name"] != "title":
215
+ continue
216
+
217
+ title_box = det["bbox"]
218
+ if title_box[1] < figure_bottom - 5:
219
+ continue
220
+
221
+ vertical_gap = title_box[1] - figure_bottom
222
+ if vertical_gap > settings["max_title_gap"]:
223
+ break
224
+
225
+ overlap = _horizontal_overlap_ratio(figure_box, title_box)
226
+ if overlap < settings["min_overlap"]:
227
+ continue
228
+
229
+ titles.append(det)
230
+ last_bottom = title_box[3]
231
+
232
+ for follower in candidates[idx + 1 :]:
233
+ if follower["name"] == "title":
234
+ break
235
+ if follower["name"] != "text":
236
+ continue
237
+ text_box = follower["bbox"]
238
+ if text_box[1] < title_box[1]:
239
+ continue
240
+
241
+ gap = text_box[1] - last_bottom
242
+ if gap > settings["max_text_gap"]:
243
+ break
244
+
245
+ if _horizontal_overlap_ratio(title_box, text_box) < settings["min_overlap"]:
246
+ continue
247
+
248
+ texts.append(follower)
249
+ last_bottom = text_box[3]
250
+
251
+ break
252
+
253
+ return titles, texts
254
+
255
+
256
+ def save_layout_elements(pil_img: Image.Image, page_num: int,
257
+ dets: List[dict], out_dir: Path) -> List[dict]:
258
+ """Save figure and table crops, merging captions."""
259
+ fig_dir = out_dir / "figures"
260
+ tab_dir = out_dir / "tables"
261
+ os.makedirs(fig_dir, exist_ok=True)
262
+ os.makedirs(tab_dir, exist_ok=True)
263
+
264
+ infos = []
265
+ fig_count = 0
266
+ tab_count = 0
267
+
268
+ processed_indices = set()
269
+
270
+ for i, d in enumerate(dets):
271
+ if d["index"] in processed_indices:
272
+ continue
273
+
274
+ name = d["name"].lower()
275
+ final_box = d["bbox"]
276
+ caption_segments: List[Dict] = []
277
+ title_segments: List[Dict] = []
278
+ text_segments: List[Dict] = []
279
+
280
+ if name == "figure":
281
+ elem_type = "figure"
282
+ path_template = fig_dir / f"page_{page_num + 1}_fig_{fig_count}.png"
283
+ fig_count += 1
284
+ caption_segments = collect_caption_elements(d, dets, "figure_caption")
285
+ for cap in caption_segments:
286
+ final_box = get_union_box(final_box, cap["bbox"])
287
+ processed_indices.add(cap["index"])
288
+ title_segments, text_segments = collect_title_and_text_segments(
289
+ d, dets, processed_indices
290
+ )
291
+ for seg in title_segments + text_segments:
292
+ final_box = get_union_box(final_box, seg["bbox"])
293
+ processed_indices.add(seg["index"])
294
+
295
+ elif name == "table":
296
+ elem_type = "table"
297
+ path_template = tab_dir / f"page_{page_num + 1}_tab_{tab_count}.png"
298
+ tab_count += 1
299
+ caption_segments = collect_caption_elements(d, dets, "table_caption")
300
+ for cap in caption_segments:
301
+ final_box = get_union_box(final_box, cap["bbox"])
302
+ processed_indices.add(cap["index"])
303
+ else:
304
+ continue
305
+
306
+ x0, y0, x1, y1 = map(int, final_box)
307
+ crop = pil_img.crop((x0, y0, x1, y1))
308
+
309
+ if crop.mode == "CMYK":
310
+ crop = crop.convert("RGB")
311
+
312
+ crop.save(path_template)
313
+
314
+ info_data = {
315
+ "type": elem_type,
316
+ "page": page_num + 1,
317
+ "bbox_pixels": final_box,
318
+ "conf": d["conf"],
319
+ "source": d.get("source", "yolo"),
320
+ "image_path": str(path_template.relative_to(out_dir)),
321
+ "width": int(x1 - x0),
322
+ "height": int(y1 - y0),
323
+ "page_width": pil_img.width,
324
+ "page_height": pil_img.height,
325
+ }
326
+ if caption_segments:
327
+ info_data["captions"] = [
328
+ {
329
+ "bbox": cap["bbox"],
330
+ "conf": cap.get("conf"),
331
+ "index": cap["index"],
332
+ "source": cap.get("source"),
333
+ "page": page_num + 1,
334
+ }
335
+ for cap in caption_segments
336
+ ]
337
+ if title_segments:
338
+ info_data["titles"] = [
339
+ {
340
+ "bbox": seg["bbox"],
341
+ "conf": seg.get("conf"),
342
+ "index": seg["index"],
343
+ "source": seg.get("source"),
344
+ "page": page_num + 1,
345
+ }
346
+ for seg in title_segments
347
+ ]
348
+ if text_segments:
349
+ info_data["texts"] = [
350
+ {
351
+ "bbox": seg["bbox"],
352
+ "conf": seg.get("conf"),
353
+ "index": seg["index"],
354
+ "source": seg.get("source"),
355
+ "page": page_num + 1,
356
+ }
357
+ for seg in text_segments
358
+ ]
359
+
360
+ infos.append(info_data)
361
+
362
+ return infos
363
+
364
+
365
+ TABLE_STITCH_TOLERANCES = {
366
+ "x_tol": 60,
367
+ "y_tol": 60,
368
+ "width_tol": 120,
369
+ "height_tol": 120,
370
+ }
371
+
372
+ CROSS_PAGE_CAPTION_THRESHOLDS = {
373
+ "max_top_ratio": 0.35,
374
+ "max_top_pixels": 220,
375
+ "x_tol": 120,
376
+ "width_tol": 200,
377
+ "min_overlap": 0.05,
378
+ }
379
+
380
+ TITLE_TEXT_ASSOCIATION = {
381
+ "max_title_gap": 220,
382
+ "max_text_gap": 160,
383
+ "min_overlap": 0.2,
384
+ }
385
+
386
+
387
+ def _horizontal_overlap_ratio(box1: List[float], box2: List[float]) -> float:
388
+ """Compute horizontal overlap ratio between two bounding boxes."""
389
+ x_left = max(box1[0], box2[0])
390
+ x_right = min(box1[2], box2[2])
391
+ overlap = max(0.0, x_right - x_left)
392
+ if overlap <= 0:
393
+ return 0.0
394
+ width_union = max(box1[2], box2[2]) - min(box1[0], box2[0])
395
+ if width_union <= 0:
396
+ return 0.0
397
+ return overlap / width_union
398
+
399
+
400
+ def _bbox_to_rect(bbox: List[float]) -> Tuple[int, int, int, int]:
401
+ """Convert [x0, y0, x1, y1] into (x, y, w, h)."""
402
+ x0, y0, x1, y1 = bbox
403
+ return int(x0), int(y0), int(x1 - x0), int(y1 - y0)
404
+
405
+
406
+ def _open_table_image(elem: Dict, out_dir: Path) -> Optional[Image.Image]:
407
+ """Open a table image relative to the output directory."""
408
+ image_path = out_dir / elem["image_path"]
409
+ if not image_path.exists():
410
+ logger.warning(f"Missing table crop for stitching: {image_path}")
411
+ return None
412
+ img = Image.open(image_path)
413
+ if img.mode != "RGB":
414
+ img = img.convert("RGB")
415
+ return img
416
+
417
+
418
+ def _pad_width(img: Image.Image, target_width: int) -> Image.Image:
419
+ if img.width >= target_width:
420
+ return img
421
+ canvas = Image.new("RGB", (target_width, img.height), color=(255, 255, 255))
422
+ canvas.paste(img, (0, 0))
423
+ return canvas
424
+
425
+
426
+ def _pad_height(img: Image.Image, target_height: int) -> Image.Image:
427
+ if img.height >= target_height:
428
+ return img
429
+ canvas = Image.new("RGB", (img.width, target_height), color=(255, 255, 255))
430
+ canvas.paste(img, (0, 0))
431
+ return canvas
432
+
433
+
434
+ def _append_segment_image(
435
+ base_img: Image.Image,
436
+ segment_img: Image.Image,
437
+ resize_to_base: bool = False,
438
+ ) -> Image.Image:
439
+ """Append segment image below base image with optional width alignment."""
440
+ if base_img.mode != "RGB":
441
+ base_img = base_img.convert("RGB")
442
+ if segment_img.mode != "RGB":
443
+ segment_img = segment_img.convert("RGB")
444
+
445
+ if resize_to_base and segment_img.width > 0 and base_img.width > 0:
446
+ segment_img = segment_img.resize(
447
+ (
448
+ base_img.width,
449
+ max(1, int(segment_img.height * (base_img.width / segment_img.width))),
450
+ ),
451
+ Image.Resampling.LANCZOS,
452
+ )
453
+
454
+ target_width = max(base_img.width, segment_img.width)
455
+ base_img = _pad_width(base_img, target_width)
456
+ segment_img = _pad_width(segment_img, target_width)
457
+
458
+ stitched = Image.new(
459
+ "RGB",
460
+ (target_width, base_img.height + segment_img.height),
461
+ color=(255, 255, 255),
462
+ )
463
+ stitched.paste(base_img, (0, 0))
464
+ stitched.paste(segment_img, (0, base_img.height))
465
+ return stitched
466
+
467
+
468
+ def _render_pdf_page(
469
+ pdf_doc: pdfium.PdfDocument,
470
+ page_index: int,
471
+ scale: float,
472
+ cache: Dict[int, Image.Image],
473
+ ) -> Optional[Image.Image]:
474
+ """Render a PDF page to a PIL image with caching."""
475
+ if page_index in cache:
476
+ return cache[page_index]
477
+
478
+ try:
479
+ page = pdf_doc[page_index]
480
+ bitmap = page.render(scale=scale)
481
+ pil_img = bitmap.to_pil()
482
+ page.close()
483
+ except Exception as exc:
484
+ logger.error(f"Failed to render page {page_index + 1} for caption stitching: {exc}")
485
+ return None
486
+
487
+ cache[page_index] = pil_img
488
+ return pil_img
489
+
490
+
491
+ def _crop_pdf_region(
492
+ page_img: Optional[Image.Image], bbox: List[float]
493
+ ) -> Optional[Image.Image]:
494
+ """Crop a region from a rendered PDF page."""
495
+ if page_img is None:
496
+ return None
497
+
498
+ x0, y0, x1, y1 = map(int, bbox)
499
+ x0 = max(0, x0)
500
+ y0 = max(0, y0)
501
+ x1 = min(page_img.width, max(x0 + 1, x1))
502
+ y1 = min(page_img.height, max(y0 + 1, y1))
503
+
504
+ if x0 >= x1 or y0 >= y1:
505
+ return None
506
+
507
+ crop = page_img.crop((x0, y0, x1, y1))
508
+ if crop.mode == "CMYK":
509
+ crop = crop.convert("RGB")
510
+ return crop
511
+
512
+
513
+ def write_markdown_document(pdf_path: Path, out_dir: Path) -> Optional[Path]:
514
+ """
515
+ Extract markdown text from a PDF using PyMuPDF4LLM and write it to disk.
516
+ """
517
+ if pymupdf4llm is None:
518
+ logger.warning(
519
+ "Skipping markdown extraction for %s because pymupdf4llm is not installed.",
520
+ pdf_path.name,
521
+ )
522
+ return None
523
+
524
+ try:
525
+ markdown_content = pymupdf4llm.to_markdown(str(pdf_path))
526
+ except Exception as exc:
527
+ logger.error(f" Failed to create markdown for {pdf_path.name}: {exc}")
528
+ return None
529
+
530
+ if isinstance(markdown_content, list):
531
+ markdown_content = "\n\n".join(
532
+ part for part in markdown_content if isinstance(part, str)
533
+ )
534
+
535
+ if not isinstance(markdown_content, str):
536
+ logger.error(
537
+ f" Unexpected markdown output type {type(markdown_content)} for {pdf_path.name}"
538
+ )
539
+ return None
540
+
541
+ markdown_content = markdown_content.strip()
542
+ if not markdown_content:
543
+ logger.warning(f" No textual content extracted from {pdf_path.name}")
544
+ return None
545
+
546
+ if not markdown_content.endswith("\n"):
547
+ markdown_content += "\n"
548
+
549
+ md_path = out_dir / f"{pdf_path.stem}.md"
550
+ md_path.write_text(markdown_content, encoding="utf-8")
551
+ logger.info(f" Saved markdown to {md_path.name}")
552
+ return md_path
553
+
554
+
555
+ def _collect_text_under_title_cross_page(
556
+ title_det: Dict,
557
+ sorted_dets: List[Dict],
558
+ start_idx: int,
559
+ page_idx: int,
560
+ used_indices: Set[Tuple[int, int]],
561
+ settings: Optional[Dict[str, float]] = None,
562
+ ) -> List[Dict]:
563
+ """Collect text elements directly below a title on the next page."""
564
+ if settings is None:
565
+ settings = TITLE_TEXT_ASSOCIATION
566
+ texts: List[Dict] = []
567
+ title_box = title_det["bbox"]
568
+ last_bottom = title_box[3]
569
+
570
+ for follower in sorted_dets[start_idx + 1 :]:
571
+ det_index = follower.get("index")
572
+ if det_index is None or (page_idx, det_index) in used_indices:
573
+ continue
574
+
575
+ if follower["name"] == "title":
576
+ break
577
+
578
+ if follower["name"] != "text":
579
+ continue
580
+
581
+ text_box = follower["bbox"]
582
+ if text_box[1] < title_box[1]:
583
+ continue
584
+
585
+ gap = text_box[1] - last_bottom
586
+ if gap > settings["max_text_gap"]:
587
+ break
588
+
589
+ if _horizontal_overlap_ratio(title_box, text_box) < settings["min_overlap"]:
590
+ continue
591
+
592
+ texts.append(follower)
593
+ last_bottom = text_box[3]
594
+
595
+ return texts
596
+
597
+
598
+ def attach_cross_page_figure_captions(
599
+ elements: List[Dict],
600
+ all_dets: Sequence[Optional[List[Dict[str, Any]]]],
601
+ pdf_bytes: bytes,
602
+ out_dir: Path,
603
+ scale: float,
604
+ ) -> List[Dict]:
605
+ """
606
+ If a figure caption appears on the next page, stitch it to the prior figure.
607
+ """
608
+ figures = [elem for elem in elements if elem.get("type") == "figure"]
609
+ if not figures or not all_dets:
610
+ return elements
611
+
612
+ try:
613
+ pdf_doc = pdfium.PdfDocument(pdf_bytes)
614
+ except Exception as exc:
615
+ logger.error(f"Unable to reopen PDF for figure caption stitching: {exc}")
616
+ return elements
617
+
618
+ page_cache: Dict[int, Image.Image] = {}
619
+ used_following_ids: Set[Tuple[int, int]] = set()
620
+
621
+ # Mark existing caption/title/text detections as used
622
+ for elem in figures:
623
+ for key in ("captions", "titles", "texts"):
624
+ for seg in elem.get(key, []) or []:
625
+ idx = seg.get("index")
626
+ page_no = seg.get("page")
627
+ if idx is None or page_no is None:
628
+ continue
629
+ used_following_ids.add((page_no - 1, idx))
630
+
631
+ for elem in figures:
632
+ page_no = elem.get("page")
633
+ bbox = elem.get("bbox_pixels")
634
+ if page_no is None or bbox is None:
635
+ continue
636
+
637
+ current_idx = page_no - 1
638
+ next_idx = current_idx + 1
639
+ if next_idx >= len(all_dets):
640
+ continue
641
+
642
+ next_dets = all_dets[next_idx]
643
+ if not next_dets:
644
+ continue
645
+
646
+ fig_width = bbox[2] - bbox[0]
647
+ page_img = _render_pdf_page(pdf_doc, next_idx, scale, page_cache)
648
+ if page_img is None:
649
+ continue
650
+
651
+ next_page_height = page_img.height
652
+ max_top_allowed = min(
653
+ CROSS_PAGE_CAPTION_THRESHOLDS["max_top_pixels"],
654
+ int(next_page_height * CROSS_PAGE_CAPTION_THRESHOLDS["max_top_ratio"]),
655
+ )
656
+
657
+ sorted_next = sorted(
658
+ [det for det in next_dets if det.get("bbox")],
659
+ key=lambda det: det["bbox"][1],
660
+ )
661
+
662
+ caption_candidate: Optional[Tuple[Dict, int]] = None
663
+ caption_candidates = []
664
+ for det in sorted_next:
665
+ if det.get("name") != "figure_caption":
666
+ continue
667
+ det_index = det.get("index")
668
+ if det_index is None or (next_idx, det_index) in used_following_ids:
669
+ continue
670
+
671
+ det_bbox = det.get("bbox")
672
+ if not det_bbox or det_bbox[1] > max_top_allowed:
673
+ continue
674
+
675
+ overlap = _horizontal_overlap_ratio(bbox, det_bbox)
676
+ x_diff = abs(bbox[0] - det_bbox[0])
677
+ width_diff = abs((bbox[2] - bbox[0]) - (det_bbox[2] - det_bbox[0]))
678
+
679
+ if overlap < CROSS_PAGE_CAPTION_THRESHOLDS["min_overlap"]:
680
+ if (
681
+ x_diff > CROSS_PAGE_CAPTION_THRESHOLDS["x_tol"]
682
+ or width_diff > CROSS_PAGE_CAPTION_THRESHOLDS["width_tol"]
683
+ ):
684
+ continue
685
+
686
+ score = width_diff + 0.5 * x_diff
687
+ caption_candidates.append((score, det, det_index))
688
+
689
+ if caption_candidates:
690
+ caption_candidates.sort(key=lambda item: item[0])
691
+ _, best_det, best_index = caption_candidates[0]
692
+ caption_candidate = (best_det, best_index)
693
+
694
+ title_candidate: Optional[Tuple[Dict, int]] = None
695
+ title_texts: List[Dict] = []
696
+ for idx_sorted, det in enumerate(sorted_next):
697
+ if det.get("name") != "title":
698
+ continue
699
+ det_index = det.get("index")
700
+ if det_index is None or (next_idx, det_index) in used_following_ids:
701
+ continue
702
+
703
+ det_bbox = det.get("bbox")
704
+ if not det_bbox or det_bbox[1] > max_top_allowed:
705
+ continue
706
+
707
+ overlap = _horizontal_overlap_ratio(bbox, det_bbox)
708
+ x_diff = abs(bbox[0] - det_bbox[0])
709
+ if (
710
+ overlap < TITLE_TEXT_ASSOCIATION["min_overlap"]
711
+ and x_diff > CROSS_PAGE_CAPTION_THRESHOLDS["x_tol"]
712
+ ):
713
+ continue
714
+
715
+ title_candidate = (det, det_index)
716
+ title_texts = _collect_text_under_title_cross_page(
717
+ det, sorted_next, idx_sorted, next_idx, used_following_ids
718
+ )
719
+ break
720
+
721
+ if not caption_candidate and not title_candidate and not title_texts:
722
+ continue
723
+
724
+ figure_path = out_dir / elem["image_path"]
725
+ if not figure_path.exists():
726
+ continue
727
+
728
+ figure_img = Image.open(figure_path)
729
+ if figure_img.mode == "CMYK":
730
+ figure_img = figure_img.convert("RGB")
731
+
732
+ segments_added = False
733
+
734
+ if caption_candidate:
735
+ cap_det, cap_index = caption_candidate
736
+ caption_crop = _crop_pdf_region(page_img, cap_det["bbox"])
737
+ if caption_crop is not None:
738
+ figure_img = _append_segment_image(
739
+ figure_img, caption_crop, resize_to_base=True
740
+ )
741
+ elem.setdefault("captions", [])
742
+ elem["captions"].append(
743
+ {
744
+ "bbox": cap_det["bbox"],
745
+ "conf": cap_det.get("conf"),
746
+ "index": cap_index,
747
+ "source": cap_det.get("source"),
748
+ "page": next_idx + 1,
749
+ }
750
+ )
751
+ used_following_ids.add((next_idx, cap_index))
752
+ segments_added = True
753
+
754
+ if title_candidate:
755
+ title_det, title_index = title_candidate
756
+ title_crop = _crop_pdf_region(page_img, title_det["bbox"])
757
+ if title_crop is not None:
758
+ figure_img = _append_segment_image(figure_img, title_crop)
759
+ elem.setdefault("titles", [])
760
+ elem["titles"].append(
761
+ {
762
+ "bbox": title_det["bbox"],
763
+ "conf": title_det.get("conf"),
764
+ "index": title_index,
765
+ "source": title_det.get("source"),
766
+ "page": next_idx + 1,
767
+ }
768
+ )
769
+ used_following_ids.add((next_idx, title_index))
770
+ segments_added = True
771
+
772
+ for text_det in title_texts:
773
+ text_index = text_det.get("index")
774
+ text_crop = _crop_pdf_region(page_img, text_det["bbox"])
775
+ if text_crop is None:
776
+ continue
777
+ figure_img = _append_segment_image(figure_img, text_crop)
778
+ elem.setdefault("texts", [])
779
+ elem["texts"].append(
780
+ {
781
+ "bbox": text_det["bbox"],
782
+ "conf": text_det.get("conf"),
783
+ "index": text_index,
784
+ "source": text_det.get("source"),
785
+ "page": next_idx + 1,
786
+ }
787
+ )
788
+ if text_index is not None:
789
+ used_following_ids.add((next_idx, text_index))
790
+ segments_added = True
791
+
792
+ if not segments_added:
793
+ continue
794
+
795
+ figure_img.save(figure_path)
796
+ elem["width"] = figure_img.width
797
+ elem["height"] = figure_img.height
798
+
799
+ span = elem.get("page_span")
800
+ if span:
801
+ if next_idx + 1 not in span:
802
+ span.append(next_idx + 1)
803
+ else:
804
+ base_page = elem.get("page")
805
+ new_span = [page for page in (base_page, next_idx + 1) if page is not None]
806
+ elem["page_span"] = new_span
807
+
808
+ pdf_doc.close()
809
+ return elements
810
+
811
+
812
+ def _stitch_table_pair(
813
+ base_elem: Dict,
814
+ candidate_elem: Dict,
815
+ out_dir: Path,
816
+ merge_index: int,
817
+ stitch_type: str,
818
+ ) -> Optional[Dict]:
819
+ """Stitch two table crops either vertically or horizontally."""
820
+ base_img = _open_table_image(base_elem, out_dir)
821
+ candidate_img = _open_table_image(candidate_elem, out_dir)
822
+ if base_img is None or candidate_img is None:
823
+ return None
824
+
825
+ tables_dir = out_dir / "tables"
826
+ tables_dir.mkdir(parents=True, exist_ok=True)
827
+
828
+ if stitch_type == "vertical":
829
+ target_width = max(base_img.width, candidate_img.width)
830
+ base_img = _pad_width(base_img, target_width)
831
+ candidate_img = _pad_width(candidate_img, target_width)
832
+ merged_height = base_img.height + candidate_img.height
833
+ stitched = Image.new("RGB", (target_width, merged_height), color=(255, 255, 255))
834
+ stitched.paste(base_img, (0, 0))
835
+ stitched.paste(candidate_img, (0, base_img.height))
836
+ else:
837
+ target_height = max(base_img.height, candidate_img.height)
838
+ base_img = _pad_height(base_img, target_height)
839
+ candidate_img = _pad_height(candidate_img, target_height)
840
+ merged_width = base_img.width + candidate_img.width
841
+ stitched = Image.new("RGB", (merged_width, target_height), color=(255, 255, 255))
842
+ stitched.paste(base_img, (0, 0))
843
+ stitched.paste(candidate_img, (base_img.width, 0))
844
+
845
+ merged_name = (
846
+ f"page_{base_elem['page']}_to_{candidate_elem['page']}_"
847
+ f"table_merged_{merge_index}.png"
848
+ )
849
+ merged_path = tables_dir / merged_name
850
+ stitched.save(merged_path)
851
+
852
+ # Remove original partial crops to avoid duplicates
853
+ (out_dir / base_elem["image_path"]).unlink(missing_ok=True)
854
+ (out_dir / candidate_elem["image_path"]).unlink(missing_ok=True)
855
+
856
+ new_bbox = [
857
+ min(base_elem["bbox_pixels"][0], candidate_elem["bbox_pixels"][0]),
858
+ min(base_elem["bbox_pixels"][1], candidate_elem["bbox_pixels"][1]),
859
+ max(base_elem["bbox_pixels"][2], candidate_elem["bbox_pixels"][2]),
860
+ max(base_elem["bbox_pixels"][3], candidate_elem["bbox_pixels"][3]),
861
+ ]
862
+
863
+ merged_elem = base_elem.copy()
864
+ merged_elem["page_span"] = [base_elem["page"], candidate_elem["page"]]
865
+ merged_elem["box_refs"] = [
866
+ {"page": base_elem["page"], "image_path": base_elem["image_path"]},
867
+ {"page": candidate_elem["page"], "image_path": candidate_elem["image_path"]},
868
+ ]
869
+ merged_elem["bbox_pixels"] = new_bbox
870
+ merged_elem["image_path"] = str(merged_path.relative_to(out_dir))
871
+ merged_elem["width"] = stitched.width
872
+ merged_elem["height"] = stitched.height
873
+ merged_elem["page_height"] = stitched.height
874
+ merged_elem["conf"] = min(
875
+ base_elem.get("conf", 1.0), candidate_elem.get("conf", 1.0)
876
+ )
877
+ return merged_elem
878
+
879
+
880
+ def merge_spanning_tables(elements: List[Dict], out_dir: Path) -> List[Dict]:
881
+ """
882
+ Stitch table crops that continue across adjacent pages using the heuristic
883
+ from the legacy OpenCV-based extractor.
884
+ """
885
+ if not elements:
886
+ return elements
887
+
888
+ tables_by_page: Dict[int, List[Dict]] = {}
889
+ non_tables: List[Dict] = []
890
+
891
+ for elem in elements:
892
+ if elem.get("type") != "table":
893
+ non_tables.append(elem)
894
+ continue
895
+ page = elem.get("page")
896
+ if not isinstance(page, int):
897
+ non_tables.append(elem)
898
+ continue
899
+ tables_by_page.setdefault(page, []).append(elem)
900
+
901
+ merged_results: List[Dict] = []
902
+ used_next: Dict[int, set[int]] = {}
903
+ merge_counter = 0
904
+
905
+ for page in sorted(tables_by_page.keys()):
906
+ current_tables = tables_by_page.get(page, [])
907
+ next_page_tables = tables_by_page.get(page + 1, [])
908
+ next_used_indices = used_next.get(page + 1, set())
909
+ current_used_indices = used_next.get(page, set())
910
+
911
+ for idx_current, table_elem in enumerate(current_tables):
912
+ if idx_current in current_used_indices:
913
+ continue
914
+
915
+ if not next_page_tables:
916
+ merged_results.append(table_elem)
917
+ continue
918
+
919
+ x, y, w, h = _bbox_to_rect(table_elem["bbox_pixels"])
920
+ matched = False
921
+
922
+ for idx, candidate in enumerate(next_page_tables):
923
+ if idx in next_used_indices:
924
+ continue
925
+ if candidate.get("type") != "table":
926
+ continue
927
+
928
+ cx, cy, cw, ch = _bbox_to_rect(candidate["bbox_pixels"])
929
+
930
+ vertical_match = (
931
+ abs(x - cx) <= TABLE_STITCH_TOLERANCES["x_tol"]
932
+ and abs((x + w) - (cx + cw)) <= TABLE_STITCH_TOLERANCES["width_tol"]
933
+ )
934
+ horizontal_match = (
935
+ abs(y - cy) <= TABLE_STITCH_TOLERANCES["y_tol"]
936
+ and abs((y + h) - (cy + ch))
937
+ <= TABLE_STITCH_TOLERANCES["height_tol"]
938
+ )
939
+
940
+ stitch_type = "vertical" if vertical_match else None
941
+ if not stitch_type and horizontal_match:
942
+ stitch_type = "horizontal"
943
+
944
+ if not stitch_type:
945
+ continue
946
+
947
+ merge_counter += 1
948
+ merged_elem = _stitch_table_pair(
949
+ table_elem, candidate, out_dir, merge_counter, stitch_type
950
+ )
951
+ if merged_elem is None:
952
+ continue
953
+
954
+ merged_results.append(merged_elem)
955
+ next_used_indices.add(idx)
956
+ matched = True
957
+ break
958
+
959
+ if not matched:
960
+ merged_results.append(table_elem)
961
+
962
+ used_next[page + 1] = next_used_indices
963
+
964
+ merged_results.extend(non_tables)
965
+ return merged_results
966
+
967
+
968
+
969
+ # ----------------------------------------------------------------------
970
+ # Draw layout boxes on the original PDF
971
+ # ----------------------------------------------------------------------
972
+ def draw_layout_pdf(pdf_bytes: bytes, all_dets: List[List[dict]],
973
+ scale: float, out_path: Path):
974
+ """Annotate PDF with semi-transparent bounding boxes and labels."""
975
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
976
+
977
+ for page_no, dets in enumerate(all_dets):
978
+ page = doc[page_no]
979
+
980
+ for d in dets:
981
+ rgb = CLASS_COLORS.get(d["name"], (0, 0, 0))
982
+ rect = fitz.Rect([c / scale for c in d["bbox"]])
983
+
984
+ border_color = [c / 255 for c in rgb]
985
+ fill_color = [c / 255 for c in rgb]
986
+ fill_opacity = 0.15
987
+ border_width = 1.5
988
+
989
+ page.draw_rect(
990
+ rect,
991
+ color=border_color,
992
+ fill=fill_color,
993
+ width=border_width,
994
+ overlay=True,
995
+ fill_opacity=fill_opacity
996
+ )
997
+
998
+ label = f"{d['name']} {d['conf']:.2f}"
999
+ if d.get("source"):
1000
+ label += f" [{d['source'][0].upper()}]"
1001
+
1002
+ text_bg = fitz.Rect(rect.x0, rect.y0 - 10, rect.x0 + 60, rect.y0)
1003
+ page.draw_rect(text_bg, color=None, fill=(1, 1, 1, 0.6), overlay=True)
1004
+
1005
+ page.insert_text(
1006
+ (rect.x0 + 2, rect.y0 - 8),
1007
+ label,
1008
+ fontsize=6.5,
1009
+ color=border_color,
1010
+ overlay=True
1011
+ )
1012
+
1013
+ doc.save(str(out_path))
1014
+ doc.close()
1015
+
1016
+ # ----------------------------------------------------------------------
1017
+ # Process a single PDF Page (for parallel execution)
1018
+ # ----------------------------------------------------------------------
1019
+ def process_page(task_data: Tuple[int, bytes, float, Path, str]) -> Optional[Tuple[int, List[dict], List[dict]]]:
1020
+ """
1021
+ Process a single page of a PDF in a worker process.
1022
+ Returns: (page_number, detections, elements) or None on failure
1023
+ """
1024
+ pno, pdf_bytes, scale, out_dir, pdf_name = task_data
1025
+
1026
+ if _shutdown_requested:
1027
+ return None
1028
+
1029
+ pdf_pdfium = None
1030
+ try:
1031
+ pdf_pdfium = pdfium.PdfDocument(pdf_bytes)
1032
+
1033
+ page = pdf_pdfium[pno]
1034
+ bitmap = page.render(scale=scale)
1035
+ pil = bitmap.to_pil()
1036
+
1037
+ dets = detect_page(pil)
1038
+ elements = save_layout_elements(pil, pno, dets, out_dir)
1039
+
1040
+ page_figures = len([d for d in dets if d['name'] == 'figure'])
1041
+ page_tables = len([d for d in dets if d['name'] == 'table'])
1042
+ logger.info(f" [{pdf_name}] Page {pno + 1}: {page_figures} figs, {page_tables} tables")
1043
+
1044
+ page.close()
1045
+ pdf_pdfium.close()
1046
+
1047
+ return (pno, dets, elements)
1048
+
1049
+ except Exception as e:
1050
+ logger.error(f"Failed to process page {pno + 1} of {pdf_name}: {e}")
1051
+ if pdf_pdfium:
1052
+ pdf_pdfium.close()
1053
+ return None
1054
+
1055
+ # ----------------------------------------------------------------------
1056
+ # Process a full PDF using the persistent worker pool
1057
+ # ----------------------------------------------------------------------
1058
+ def process_pdf_with_pool(
1059
+ pdf_path: Path,
1060
+ out_dir: Path,
1061
+ pool: Optional[Pool] = None,
1062
+ *,
1063
+ extract_images: bool = True,
1064
+ extract_markdown: bool = True,
1065
+ ):
1066
+ """
1067
+ Main processing pipeline for a PDF file.
1068
+ If pool is provided, uses it. Otherwise processes serially.
1069
+ """
1070
+
1071
+ if _shutdown_requested:
1072
+ logger.warning(f"Skipping {pdf_path.name} due to shutdown request")
1073
+ return
1074
+
1075
+ stem = pdf_path.stem
1076
+ logger.info(f"Processing {pdf_path.name}")
1077
+
1078
+ pdf_bytes = pdf_path.read_bytes()
1079
+
1080
+ doc = None
1081
+ try:
1082
+ doc = pdfium.PdfDocument(pdf_bytes)
1083
+ page_count = len(doc)
1084
+ except Exception as e:
1085
+ logger.error(f"Failed to open PDF {pdf_path.name}: {e}. Skipping.")
1086
+ return
1087
+ finally:
1088
+ if doc is not None:
1089
+ doc.close()
1090
+
1091
+ scale = 2.0
1092
+ all_elements: List[Dict] = []
1093
+ filtered_dets: List[List[dict]] = []
1094
+
1095
+ if extract_images:
1096
+ all_dets: List[Optional[List[dict]]] = [None] * page_count
1097
+
1098
+ if pool is not None and USE_MULTIPROCESSING:
1099
+ logger.info(f" Using worker pool for {page_count} pages...")
1100
+
1101
+ tasks = [
1102
+ (pno, pdf_bytes, scale, out_dir, pdf_path.name)
1103
+ for pno in range(page_count)
1104
+ ]
1105
+
1106
+ try:
1107
+ results = pool.map(process_page, tasks)
1108
+
1109
+ for res in results:
1110
+ if res:
1111
+ pno, dets, elements = res
1112
+ all_dets[pno] = dets
1113
+ all_elements.extend(elements)
1114
+
1115
+ except KeyboardInterrupt:
1116
+ logger.warning("Processing interrupted during parallel execution")
1117
+ raise
1118
+
1119
+ else:
1120
+ logger.info("Using serial processing...")
1121
+
1122
+ try:
1123
+ pdf_pdfium = pdfium.PdfDocument(pdf_bytes)
1124
+
1125
+ for pno in range(page_count):
1126
+ if _shutdown_requested:
1127
+ logger.warning(
1128
+ f"Stopping at page {pno + 1}/{page_count} due to shutdown request"
1129
+ )
1130
+ break
1131
+
1132
+ try:
1133
+ logger.info(f" Processing page {pno + 1}/{page_count}")
1134
+
1135
+ page = pdf_pdfium[pno]
1136
+ bitmap = page.render(scale=scale)
1137
+ pil = bitmap.to_pil()
1138
+
1139
+ dets = detect_page(pil)
1140
+ all_dets[pno] = dets
1141
+
1142
+ elements = save_layout_elements(pil, pno, dets, out_dir)
1143
+ all_elements.extend(elements)
1144
+
1145
+ page_figures = len([d for d in dets if d["name"] == "figure"])
1146
+ page_tables = len([d for d in dets if d["name"] == "table"])
1147
+ logger.info(
1148
+ f" Found {page_figures} figures and {page_tables} tables"
1149
+ )
1150
+
1151
+ page.close()
1152
+
1153
+ except Exception as e:
1154
+ logger.error(f"Failed to process page {pno + 1}: {e}. Skipping page.")
1155
+
1156
+ pdf_pdfium.close()
1157
+
1158
+ except Exception as e:
1159
+ logger.error(f"Fatal error processing {pdf_path.name}: {e}")
1160
+ if "pdf_pdfium" in locals() and pdf_pdfium:
1161
+ pdf_pdfium.close()
1162
+ return
1163
+
1164
+ dets_per_page: List[Optional[List[Dict[str, Any]]]] = [
1165
+ det if det is not None else None for det in all_dets
1166
+ ]
1167
+
1168
+ filtered_dets = [d for d in all_dets if d is not None]
1169
+
1170
+ if all_elements:
1171
+ all_elements = merge_spanning_tables(all_elements, out_dir)
1172
+ all_elements = attach_cross_page_figure_captions(
1173
+ all_elements, dets_per_page, pdf_bytes, out_dir, scale
1174
+ )
1175
+
1176
+ if all_elements:
1177
+ content_list_path = out_dir / f"{stem}_content_list.json"
1178
+ with open(content_list_path, "w", encoding="utf-8") as f:
1179
+ json.dump(all_elements, f, ensure_ascii=False, indent=4)
1180
+ logger.info(f" Saved {len(all_elements)} elements to JSON")
1181
+
1182
+ if filtered_dets:
1183
+ draw_layout_pdf(
1184
+ pdf_bytes, filtered_dets, scale, out_dir / f"{stem}_layout.pdf"
1185
+ )
1186
+ logger.info(" Generated annotated PDF")
1187
+ else:
1188
+ logger.warning(f"No detections found for {stem}. Skipping layout PDF.")
1189
+
1190
+ else:
1191
+ logger.info(" Image extraction skipped per configuration.")
1192
+
1193
+ markdown_path = None
1194
+ if extract_markdown:
1195
+ markdown_path = write_markdown_document(pdf_path, out_dir)
1196
+ if markdown_path is None:
1197
+ logger.warning(f" Markdown extraction yielded no content for {stem}.")
1198
+
1199
+ if _shutdown_requested:
1200
+ logger.warning(f"⚠️ Partial results saved for {stem} β†’ {out_dir}")
1201
+ else:
1202
+ if extract_images:
1203
+ logger.success(
1204
+ f"βœ“ {stem} β†’ {out_dir} ({len(all_elements)} elements extracted)"
1205
+ )
1206
+ else:
1207
+ logger.success(f"βœ“ {stem} β†’ {out_dir} (image extraction skipped)")
1208
+
1209
+ # ----------------------------------------------------------------------
1210
+ # Main
1211
+ # ----------------------------------------------------------------------
1212
+ if __name__ == "__main__":
1213
+ # Important for multiprocessing on Windows/macOS
1214
+ torch.multiprocessing.set_start_method('spawn', force=True)
1215
+
1216
+ # Setup signal handlers for graceful shutdown
1217
+ setup_signal_handlers()
1218
+
1219
+ INPUT_DIR = Path("./pdfs")
1220
+ OUTPUT_DIR = Path("./output")
1221
+
1222
+ os.makedirs(INPUT_DIR, exist_ok=True)
1223
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
1224
+
1225
+ pdf_files = list(INPUT_DIR.glob("*.pdf"))
1226
+ if not pdf_files:
1227
+ logger.warning("No PDF files found in ./pdfs")
1228
+ logger.info("Please add PDF files to the ./pdfs directory")
1229
+ logger.info("The script will exit gracefully. No errors occurred.")
1230
+ sys.exit(0)
1231
+
1232
+ logger.info(f"Found {len(pdf_files)} PDF file(s) to process")
1233
+ logger.info(f"Settings: MODEL_SIZE={MODEL_SIZE}, CONF={CONF_THRESHOLD}")
1234
+
1235
+ # Determine worker count
1236
+ total_cpus = cpu_count()
1237
+ if NUM_WORKERS is None:
1238
+ num_workers = max(1, total_cpus - 1)
1239
+ else:
1240
+ num_workers = max(1, min(NUM_WORKERS, total_cpus))
1241
+
1242
+ # Decide whether to use multiprocessing
1243
+ use_pool = USE_MULTIPROCESSING and DEVICE == "cpu" and total_cpus >= 4
1244
+
1245
+ if use_pool:
1246
+ logger.info(f"πŸš€ Creating persistent worker pool with {num_workers} workers...")
1247
+ else:
1248
+ if not USE_MULTIPROCESSING:
1249
+ logger.info("Multiprocessing disabled by configuration")
1250
+ elif DEVICE != "cpu":
1251
+ logger.info(f"Using serial GPU processing (device: {DEVICE})")
1252
+ else:
1253
+ logger.info(f"Using serial CPU processing (CPU count {total_cpus} too low)")
1254
+
1255
+ pool = None
1256
+ try:
1257
+ # Create persistent pool ONCE for all PDFs
1258
+ if use_pool:
1259
+ pool = Pool(processes=num_workers, initializer=init_worker)
1260
+ logger.success(f"βœ“ Worker pool ready with {num_workers} workers\n")
1261
+ else:
1262
+ # Load model in main process for serial execution
1263
+ logger.info("Initializing model in main process...")
1264
+ get_model()
1265
+ logger.success(f"βœ“ Model loaded (device: {DEVICE})\n")
1266
+
1267
+ # Process all PDFs using the same pool
1268
+ for i, pdf_path in enumerate(pdf_files, 1):
1269
+ if _shutdown_requested:
1270
+ logger.warning(f"\nShutdown requested. Processed {i-1}/{len(pdf_files)} files.")
1271
+ break
1272
+
1273
+ logger.info(f"\n{'='*60}")
1274
+ logger.info(f"πŸ“„ File {i}/{len(pdf_files)}: {pdf_path.name}")
1275
+ logger.info(f"{'='*60}")
1276
+
1277
+ sub_out = OUTPUT_DIR / pdf_path.stem
1278
+ os.makedirs(sub_out, exist_ok=True)
1279
+
1280
+ try:
1281
+ process_pdf_with_pool(pdf_path, sub_out, pool)
1282
+ except KeyboardInterrupt:
1283
+ logger.warning(f"\nInterrupted while processing {pdf_path.name}")
1284
+ break
1285
+ except Exception as e:
1286
+ logger.error(f"Error processing {pdf_path.name}: {e}")
1287
+ if _shutdown_requested:
1288
+ break
1289
+ logger.info("Continuing with next file...")
1290
+ continue
1291
+
1292
+ if _shutdown_requested:
1293
+ logger.warning(f"\n⚠️ Processing interrupted. Partial results saved in {OUTPUT_DIR}")
1294
+ else:
1295
+ logger.success(f"\n✨ All done! Results are in {OUTPUT_DIR}")
1296
+
1297
+ except KeyboardInterrupt:
1298
+ logger.error("\n❌ Processing interrupted by user")
1299
+ sys.exit(1)
1300
+ except Exception as e:
1301
+ logger.error(f"\n❌ Fatal error: {e}")
1302
+ sys.exit(1)
1303
+ finally:
1304
+ # Clean up pool if it exists
1305
+ if pool is not None:
1306
+ logger.info("\n🧹 Shutting down worker pool...")
1307
+ pool.close()
1308
+ pool.join()
1309
+ logger.success("βœ“ Worker pool closed cleanly")
packages.txt ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles>=23.2.1
2
+ fastapi>=0.109.0
3
+ gradio>=4.0.0
4
+ huggingface-hub>=0.20.0
5
+ jinja2>=3.1.3
6
+ loguru>=0.7.2
7
+ numpy<2.0.0
8
+ pillow>=10.2.0
9
+ pymupdf>=1.23.0
10
+ pymupdf4llm>=0.0.1
11
+ pypdfium2>=4.26.0
12
+ python-multipart>=0.0.9
13
+ torch>=2.0.0
14
+ torchvision>=0.15.0
15
+ uvicorn>=0.27.0
16
+ doclayout-yolo>=0.0.2