linkie-academy commited on
Commit
4d5ce5c
·
1 Parent(s): fbdc47f

Deploy PDF Layout Extractor application

Browse files
Files changed (10) hide show
  1. .dockerignore +25 -0
  2. Dockerfile +45 -0
  3. README.md +51 -5
  4. app.py +296 -0
  5. entrypoint.sh +7 -0
  6. main.py +1309 -0
  7. requirements.txt +13 -0
  8. static/css/styles.css +310 -0
  9. static/js/app.js +482 -0
  10. templates/index.html +183 -0
.dockerignore ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ .Python
6
+ *.so
7
+ *.egg
8
+ *.egg-info
9
+ dist
10
+ build
11
+ .git
12
+ .gitignore
13
+ .vscode
14
+ .idea
15
+ *.md
16
+ !README.md
17
+ pdfs/
18
+ output/
19
+ uploads/
20
+ uv.lock
21
+ .env
22
+ .venv
23
+ venv/
24
+ env/
25
+
Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Python 3.12 slim image as base
2
+ FROM python:3.12-slim
3
+
4
+ # Install system dependencies (as root)
5
+ RUN apt-get update && apt-get install -y \
6
+ build-essential \
7
+ libgl1-mesa-glx \
8
+ libglib2.0-0 \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Create a non-root user (Hugging Face Spaces best practice)
12
+ RUN useradd -m -u 1000 user
13
+ USER user
14
+ ENV PATH="/home/user/.local/bin:$PATH"
15
+
16
+ # Set working directory
17
+ WORKDIR /app
18
+
19
+ # Copy requirements first for better caching
20
+ COPY --chown=user ./requirements.txt requirements.txt
21
+
22
+ # Install Python dependencies
23
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
24
+
25
+ # Copy application files
26
+ COPY --chown=user . /app
27
+
28
+ # Make entrypoint script executable
29
+ RUN chmod +x /app/entrypoint.sh
30
+
31
+ # Create necessary directories
32
+ RUN mkdir -p uploads output
33
+
34
+ # Expose port (Hugging Face Spaces uses 7860)
35
+ EXPOSE 7860
36
+
37
+ # Set environment variables
38
+ ENV FLASK_APP=app.py
39
+ ENV PYTHONUNBUFFERED=1
40
+ ENV PORT=7860
41
+
42
+ # Run the Flask app
43
+ # Hugging Face Spaces expects the app to listen on 0.0.0.0 and port 7860
44
+ CMD ["/app/entrypoint.sh"]
45
+
README.md CHANGED
@@ -1,10 +1,56 @@
1
  ---
2
- title: Volaris Pdf Tool
3
- emoji: 📚
4
- colorFrom: purple
5
- colorTo: red
6
  sdk: docker
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: PDF Layout Extractor
3
+ emoji: 📄
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: docker
7
  pinned: false
8
+ license: mit
9
+ app_port: 7860
10
  ---
11
 
12
+ # PDF Layout Extractor
13
+
14
+ A web application for extracting figures, tables, annotated layouts, and markdown text from scientific PDFs using [DocLayout-YOLO](https://github.com/juliozhao/DocLayout-YOLO).
15
+
16
+ ## Features
17
+
18
+ - **Layout-aware extraction** of figures and tables with YOLO-based detection
19
+ - **Cross-page stitching** for multi-page tables, captions, titles, and body text
20
+ - **Annotated PDF output** with bounding boxes for detected regions
21
+ - **Markdown export** powered by `pymupdf4llm`
22
+ - **Modern Flask Web UI** with dark/light theme support
23
+
24
+ ## Usage
25
+
26
+ 1. Upload one or more PDF files (max 500MB per file)
27
+ 2. Choose extraction mode:
28
+ - **Images Only**: Extract figures and tables with layout detection
29
+ - **Markdown Only**: Extract text content as markdown
30
+ - **Both**: Extract both images and markdown
31
+ 3. Wait for processing to complete
32
+ 4. View and download extracted figures, tables, annotated PDFs, and markdown files
33
+
34
+ ## Technical Details
35
+
36
+ - Built with Flask and DocLayout-YOLO
37
+ - Supports both CPU and GPU processing (GPU recommended for faster processing)
38
+ - Maximum file size: 500MB per PDF
39
+ - Model: DocLayout-YOLO from `juliozhao/DocLayout-YOLO-DocStructBench`
40
+
41
+ ## Output Structure
42
+
43
+ Each processed PDF creates a directory with:
44
+ - `*_content_list.json` - Metadata for extracted figures/tables
45
+ - `*_layout.pdf` - Annotated PDF with layout bounding boxes
46
+ - `*.md` - Markdown export of text content
47
+ - `figures/` - Extracted figure images (PNG)
48
+ - `tables/` - Extracted table images (PNG)
49
+
50
+ ## Model Information
51
+
52
+ This application uses the DocLayout-YOLO model for document layout detection. The model is automatically downloaded from Hugging Face Hub on first use.
53
+
54
+ ## License
55
+
56
+ MIT License
app.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import Dict, List, Optional
6
+ from flask import Flask, render_template, request, jsonify, send_file, send_from_directory
7
+ from werkzeug.utils import secure_filename
8
+ import torch
9
+
10
+ import main as extractor
11
+ from loguru import logger
12
+
13
+ app = Flask(__name__)
14
+ app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024 # 500MB max file size
15
+ app.config['UPLOAD_FOLDER'] = './uploads'
16
+ app.config['OUTPUT_FOLDER'] = './output'
17
+
18
+ # Ensure directories exist
19
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
20
+ os.makedirs(app.config['OUTPUT_FOLDER'], exist_ok=True)
21
+
22
+ # Global model instance
23
+ _model = None
24
+
25
+
26
+ def get_device_info() -> Dict[str, any]:
27
+ """Get information about GPU/CPU availability."""
28
+ cuda_available = torch.cuda.is_available()
29
+ device = "cuda" if cuda_available else "cpu"
30
+
31
+ info = {
32
+ "device": device,
33
+ "cuda_available": cuda_available,
34
+ "device_name": None,
35
+ "device_count": 0,
36
+ }
37
+
38
+ if cuda_available:
39
+ info["device_name"] = torch.cuda.get_device_name(0)
40
+ info["device_count"] = torch.cuda.device_count()
41
+
42
+ return info
43
+
44
+
45
+ def load_model_once():
46
+ """Load the model once and cache it."""
47
+ global _model
48
+ if _model is None:
49
+ logger.info("Loading DocLayout-YOLO model...")
50
+ _model = extractor.get_model()
51
+ logger.info("Model loaded successfully")
52
+ return _model
53
+
54
+
55
+ @app.route('/')
56
+ def index():
57
+ """Main page."""
58
+ device_info = get_device_info()
59
+ return render_template('index.html', device_info=device_info)
60
+
61
+
62
+ @app.route('/api/device-info')
63
+ def device_info():
64
+ """API endpoint to get device information."""
65
+ return jsonify(get_device_info())
66
+
67
+
68
+ @app.route('/api/upload', methods=['POST'])
69
+ def upload_files():
70
+ """Handle multiple PDF file uploads."""
71
+ if 'files[]' not in request.files:
72
+ return jsonify({'error': 'No files provided'}), 400
73
+
74
+ files = request.files.getlist('files[]')
75
+ extraction_mode = request.form.get('extraction_mode', 'images')
76
+ include_images = extraction_mode != 'markdown'
77
+ include_markdown = extraction_mode != 'images'
78
+
79
+ if not files or all(f.filename == '' for f in files):
80
+ return jsonify({'error': 'No files selected'}), 400
81
+
82
+ results = []
83
+
84
+ for file in files:
85
+ if file and file.filename.endswith('.pdf'):
86
+ try:
87
+ # Save uploaded file
88
+ filename = secure_filename(file.filename)
89
+ stem = Path(filename).stem
90
+ upload_path = Path(app.config['UPLOAD_FOLDER']) / filename
91
+ file.save(str(upload_path))
92
+
93
+ # Prepare output directory
94
+ output_dir = Path(app.config['OUTPUT_FOLDER']) / stem
95
+ output_dir.mkdir(parents=True, exist_ok=True)
96
+
97
+ # Copy PDF to output directory
98
+ pdf_path = output_dir / filename
99
+ upload_path.rename(pdf_path)
100
+
101
+ # Process PDF
102
+ extractor.USE_MULTIPROCESSING = False
103
+ logger.info(f"Processing {filename} (images={include_images}, markdown={include_markdown})")
104
+
105
+ if include_images:
106
+ load_model_once()
107
+
108
+ extractor.process_pdf_with_pool(
109
+ pdf_path,
110
+ output_dir,
111
+ pool=None,
112
+ extract_images=include_images,
113
+ extract_markdown=include_markdown,
114
+ )
115
+
116
+ # Collect results
117
+ json_path = output_dir / f"{stem}_content_list.json"
118
+ elements = []
119
+ if include_images and json_path.exists():
120
+ elements = json.loads(json_path.read_text(encoding='utf-8'))
121
+
122
+ annotated_pdf = None
123
+ if include_images:
124
+ candidate_pdf = output_dir / f"{stem}_layout.pdf"
125
+ if candidate_pdf.exists():
126
+ annotated_pdf = str(candidate_pdf.relative_to(app.config['OUTPUT_FOLDER']))
127
+
128
+ markdown_path = None
129
+ if include_markdown:
130
+ candidate_md = output_dir / f"{stem}.md"
131
+ if candidate_md.exists():
132
+ markdown_path = str(candidate_md.relative_to(app.config['OUTPUT_FOLDER']))
133
+
134
+ # Get figure and table counts
135
+ figures = [e for e in elements if e.get('type') == 'figure']
136
+ tables = [e for e in elements if e.get('type') == 'table']
137
+
138
+ results.append({
139
+ 'filename': filename,
140
+ 'stem': stem,
141
+ 'output_dir': str(output_dir.relative_to(app.config['OUTPUT_FOLDER'])),
142
+ 'figures_count': len(figures),
143
+ 'tables_count': len(tables),
144
+ 'elements_count': len(elements),
145
+ 'annotated_pdf': annotated_pdf,
146
+ 'markdown_path': markdown_path,
147
+ 'include_images': include_images,
148
+ 'include_markdown': include_markdown,
149
+ })
150
+
151
+ except Exception as e:
152
+ logger.error(f"Error processing {file.filename}: {e}")
153
+ results.append({
154
+ 'filename': file.filename,
155
+ 'error': str(e)
156
+ })
157
+
158
+ return jsonify({'results': results})
159
+
160
+
161
+ @app.route('/api/pdf-list')
162
+ def pdf_list():
163
+ """Get list of processed PDFs."""
164
+ output_dir = Path(app.config['OUTPUT_FOLDER'])
165
+ pdfs = []
166
+
167
+ for item in output_dir.iterdir():
168
+ if item.is_dir():
169
+ # Check if this directory has processed content
170
+ json_files = list(item.glob('*_content_list.json'))
171
+ md_files = list(item.glob('*.md'))
172
+ pdf_files = list(item.glob('*.pdf'))
173
+
174
+ if json_files or md_files or pdf_files:
175
+ stem = item.name
176
+ pdfs.append({
177
+ 'stem': stem,
178
+ 'output_dir': str(item.relative_to(app.config['OUTPUT_FOLDER'])),
179
+ })
180
+
181
+ return jsonify({'pdfs': pdfs})
182
+
183
+
184
+ @app.route('/api/pdf-details/<path:pdf_stem>')
185
+ def pdf_details(pdf_stem):
186
+ """Get detailed information about a processed PDF."""
187
+ output_dir = Path(app.config['OUTPUT_FOLDER']) / pdf_stem
188
+
189
+ if not output_dir.exists():
190
+ return jsonify({'error': 'PDF not found'}), 404
191
+
192
+ # Load content list
193
+ json_files = list(output_dir.glob('*_content_list.json'))
194
+ elements = []
195
+ if json_files:
196
+ elements = json.loads(json_files[0].read_text(encoding='utf-8'))
197
+
198
+ # Get figures and tables
199
+ figures = [e for e in elements if e.get('type') == 'figure']
200
+ tables = [e for e in elements if e.get('type') == 'table']
201
+
202
+ # Get file paths
203
+ annotated_pdf = None
204
+ pdf_files = list(output_dir.glob('*_layout.pdf'))
205
+ if pdf_files:
206
+ annotated_pdf = str(pdf_files[0].relative_to(app.config['OUTPUT_FOLDER']))
207
+
208
+ markdown_path = None
209
+ md_files = list(output_dir.glob('*.md'))
210
+ if md_files:
211
+ markdown_path = str(md_files[0].relative_to(app.config['OUTPUT_FOLDER']))
212
+
213
+ # Get figure and table images
214
+ figure_dir = output_dir / 'figures'
215
+ table_dir = output_dir / 'tables'
216
+
217
+ figure_images = []
218
+ if figure_dir.exists():
219
+ figure_images = [str(f.relative_to(app.config['OUTPUT_FOLDER']))
220
+ for f in sorted(figure_dir.glob('*.png'))]
221
+
222
+ table_images = []
223
+ if table_dir.exists():
224
+ table_images = [str(t.relative_to(app.config['OUTPUT_FOLDER']))
225
+ for t in sorted(table_dir.glob('*.png'))]
226
+
227
+ return jsonify({
228
+ 'stem': pdf_stem,
229
+ 'figures': figures,
230
+ 'tables': tables,
231
+ 'figures_count': len(figures),
232
+ 'tables_count': len(tables),
233
+ 'elements_count': len(elements),
234
+ 'annotated_pdf': annotated_pdf,
235
+ 'markdown_path': markdown_path,
236
+ 'figure_images': figure_images,
237
+ 'table_images': table_images,
238
+ })
239
+
240
+
241
+ @app.route('/output/<path:filename>')
242
+ def output_file(filename):
243
+ """Serve output files (PDFs, images, markdown)."""
244
+ return send_from_directory(app.config['OUTPUT_FOLDER'], filename)
245
+
246
+
247
+ def _delete_by_stem(stem_raw: str):
248
+ stem = (stem_raw or "").strip()
249
+ if not stem:
250
+ return jsonify({'error': 'Missing stem'}), 400
251
+
252
+ # Resolve output directory safely
253
+ output_root = Path(app.config['OUTPUT_FOLDER']).resolve()
254
+ target_dir = (output_root / stem).resolve()
255
+
256
+ # Prevent path traversal - ensure target is within output_root
257
+ if output_root not in target_dir.parents and target_dir != output_root:
258
+ return jsonify({'error': 'Invalid stem path'}), 400
259
+
260
+ if not target_dir.exists() or not target_dir.is_dir():
261
+ return jsonify({'error': 'Not found'}), 404
262
+
263
+ # Delete the directory
264
+ shutil.rmtree(target_dir, ignore_errors=False)
265
+ logger.info(f"Deleted processed output: {target_dir}")
266
+
267
+ return jsonify({'ok': True, 'deleted': stem})
268
+
269
+
270
+ @app.route('/api/delete', methods=['POST'])
271
+ def delete_pdf():
272
+ """Delete a processed PDF directory by stem (JSON or form body)."""
273
+ try:
274
+ data = request.get_json(silent=True) or {}
275
+ stem = (data.get('stem') or request.form.get('stem') or '').strip()
276
+ return _delete_by_stem(stem)
277
+ except Exception as e:
278
+ logger.error(f"Delete failed: {e}")
279
+ return jsonify({'error': str(e)}), 500
280
+
281
+
282
+ @app.route('/api/delete/<path:stem>', methods=['POST', 'GET'])
283
+ def delete_pdf_by_path(stem: str):
284
+ """Alternate endpoint to delete using URL path, for clients avoiding bodies."""
285
+ try:
286
+ return _delete_by_stem(stem)
287
+ except Exception as e:
288
+ logger.error(f"Delete failed: {e}")
289
+ return jsonify({'error': str(e)}), 500
290
+
291
+
292
+ if __name__ == '__main__':
293
+ port = int(os.environ.get('PORT', 5000))
294
+ app.run(debug=False, host='0.0.0.0', port=port)
295
+
296
+
entrypoint.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+
4
+ # Start Flask application
5
+ # Get port from environment variable or use default 7860
6
+ python -c "import os; port = int(os.environ.get('PORT', 7860)); from app import app; app.run(host='0.0.0.0', port=port, debug=False)"
7
+
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")
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ doclayout-yolo>=0.0.4
2
+ huggingface-hub>=1.1.2
3
+ loguru>=0.7.3
4
+ pillow>=12.0.0
5
+ pymupdf>=1.26.6
6
+ pymupdf-layout>=0.0.15
7
+ pypdfium2>=5.0.0
8
+ pymupdf4llm>=0.1.9
9
+ flask>=3.0.0
10
+ werkzeug>=3.0.0
11
+ torch>=2.0.0
12
+ torchvision>=0.15.0
13
+
static/css/styles.css ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* CSS Variables for Professional Theme */
2
+ :root {
3
+ --primary: #4A5568;
4
+ --primary-dark: #2D3748;
5
+ --accent: #3182CE;
6
+ --accent-dark: #2B6CB0;
7
+ --background-light: #F7FAFC;
8
+ --background-dark: #1A202C;
9
+ --card-bg: #FFFFFF;
10
+ --card-bg-dark: #2D3748;
11
+ --text-primary: #2D3748;
12
+ --text-secondary: #718096;
13
+ --text-invert: #F7FAFC;
14
+ --border-color: #E2E8F0;
15
+ --border-color-dark: #4A5568;
16
+ --shadow-sm: 0 2px 4px rgba(15, 23, 42, 0.05);
17
+ --shadow-md: 0 4px 6px -1px rgba(15, 23, 42, 0.06), 0 2px 4px -1px rgba(15, 23, 42, 0.04);
18
+ --shadow-lg: 0 10px 15px -3px rgba(15, 23, 42, 0.1), 0 4px 6px -2px rgba(15, 23, 42, 0.05);
19
+ --radius-sm: 6px;
20
+ --radius-md: 8px;
21
+ --radius-lg: 12px;
22
+ --transition-base: all 0.25s ease;
23
+ --status-green: #15803d;
24
+ --status-yellow: #a16207;
25
+ --status-red: #b91c1c;
26
+ }
27
+
28
+ [data-theme="dark"] {
29
+ --primary: #CBD5F5;
30
+ --primary-dark: #1A202C;
31
+ --accent: #63B3ED;
32
+ --accent-dark: #4299E1;
33
+ --background-light: var(--background-dark);
34
+ --card-bg: var(--card-bg-dark);
35
+ --text-primary: #EDF2F7;
36
+ --text-secondary: #A0AEC0;
37
+ --text-invert: #0F172A;
38
+ --border-color: #2D3748;
39
+ --status-green: #4ade80;
40
+ --status-yellow: #facc15;
41
+ --status-red: #f87171;
42
+ }
43
+
44
+ body {
45
+ background-color: var(--background-light);
46
+ color: var(--text-primary);
47
+ font-family: "Inter", "Segoe UI", -apple-system, BlinkMacSystemFont, sans-serif;
48
+ transition: background-color 0.3s ease, color 0.3s ease;
49
+ }
50
+
51
+ /* Navbar */
52
+ .bg-primary-custom {
53
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
54
+ }
55
+
56
+ .navbar {
57
+ box-shadow: var(--shadow-sm);
58
+ }
59
+
60
+ /* Cards */
61
+ .card {
62
+ background: var(--card-bg);
63
+ border: 1px solid var(--border-color);
64
+ border-radius: var(--radius-lg);
65
+ box-shadow: var(--shadow-sm);
66
+ transition: var(--transition-base);
67
+ }
68
+
69
+ .card:hover {
70
+ box-shadow: var(--shadow-md);
71
+ }
72
+
73
+ .card-header {
74
+ border-bottom: 1px solid var(--border-color);
75
+ border-radius: var(--radius-lg) var(--radius-lg) 0 0 !important;
76
+ }
77
+
78
+ /* Buttons */
79
+ .btn-primary {
80
+ background: var(--accent);
81
+ border-color: var(--accent);
82
+ color: white;
83
+ transition: var(--transition-base);
84
+ }
85
+
86
+ .btn-primary:hover {
87
+ background: var(--accent-dark);
88
+ border-color: var(--accent-dark);
89
+ box-shadow: var(--shadow-md);
90
+ }
91
+
92
+ .btn-outline-primary {
93
+ border-color: var(--accent);
94
+ color: var(--accent);
95
+ background: transparent;
96
+ }
97
+
98
+ .btn-outline-primary:hover,
99
+ .btn-outline-primary:active,
100
+ .btn-outline-primary:focus {
101
+ background: var(--accent);
102
+ border-color: var(--accent);
103
+ color: white;
104
+ box-shadow: var(--shadow-sm);
105
+ }
106
+
107
+ .btn-check:checked + .btn-outline-primary {
108
+ background: var(--accent);
109
+ border-color: var(--accent);
110
+ color: white;
111
+ }
112
+
113
+ /* Form Controls */
114
+ .form-control,
115
+ .form-select {
116
+ background: var(--card-bg);
117
+ color: var(--text-primary);
118
+ border-color: var(--border-color);
119
+ transition: var(--transition-base);
120
+ }
121
+
122
+ .form-control:focus,
123
+ .form-select:focus {
124
+ background: var(--card-bg);
125
+ color: var(--text-primary);
126
+ border-color: var(--accent);
127
+ box-shadow: 0 0 0 0.2rem rgba(49, 130, 206, 0.15);
128
+ }
129
+
130
+ /* List Group */
131
+ .list-group-item {
132
+ background: var(--card-bg);
133
+ color: var(--text-primary);
134
+ border-color: var(--border-color);
135
+ cursor: pointer;
136
+ transition: var(--transition-base);
137
+ }
138
+
139
+ .list-group-item:hover {
140
+ background: rgba(49, 130, 206, 0.1);
141
+ border-color: var(--accent);
142
+ }
143
+
144
+ .list-group-item.active {
145
+ background: var(--accent);
146
+ border-color: var(--accent);
147
+ color: white;
148
+ }
149
+
150
+ /* Badges */
151
+ .badge {
152
+ padding: 0.5em 0.75em;
153
+ font-weight: 600;
154
+ }
155
+
156
+ .badge.bg-success {
157
+ background-color: var(--status-green) !important;
158
+ }
159
+
160
+ .badge.bg-warning {
161
+ background-color: var(--status-yellow) !important;
162
+ }
163
+
164
+ .badge.bg-danger {
165
+ background-color: var(--status-red) !important;
166
+ }
167
+
168
+ /* Device Status */
169
+ #deviceBadge {
170
+ font-size: 0.9rem;
171
+ padding: 0.4em 0.8em;
172
+ }
173
+
174
+ .badge.bg-success {
175
+ background-color: var(--status-green) !important;
176
+ }
177
+
178
+ .badge.bg-secondary {
179
+ background-color: var(--text-secondary) !important;
180
+ }
181
+
182
+ /* Image Gallery */
183
+ .image-gallery {
184
+ display: grid;
185
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
186
+ gap: 1.5rem;
187
+ margin-top: 1rem;
188
+ }
189
+
190
+ .image-item {
191
+ position: relative;
192
+ border-radius: var(--radius-md);
193
+ overflow: hidden;
194
+ box-shadow: var(--shadow-sm);
195
+ transition: var(--transition-base);
196
+ background: var(--card-bg);
197
+ border: 1px solid var(--border-color);
198
+ }
199
+
200
+ .image-item:hover {
201
+ box-shadow: var(--shadow-lg);
202
+ transform: translateY(-2px);
203
+ }
204
+
205
+ .image-item img {
206
+ width: 100%;
207
+ height: auto;
208
+ display: block;
209
+ }
210
+
211
+ .image-item .image-caption {
212
+ padding: 0.75rem;
213
+ background: var(--card-bg);
214
+ color: var(--text-primary);
215
+ font-size: 0.875rem;
216
+ border-top: 1px solid var(--border-color);
217
+ }
218
+
219
+ /* Stats Cards */
220
+ .stat-card {
221
+ background: var(--card-bg);
222
+ border: 1px solid var(--border-color);
223
+ border-radius: var(--radius-md);
224
+ padding: 1.5rem;
225
+ text-align: center;
226
+ transition: var(--transition-base);
227
+ }
228
+
229
+ .stat-card:hover {
230
+ box-shadow: var(--shadow-md);
231
+ transform: translateY(-2px);
232
+ }
233
+
234
+ .stat-card .stat-value {
235
+ font-size: 2rem;
236
+ font-weight: 700;
237
+ color: var(--accent);
238
+ margin: 0.5rem 0;
239
+ }
240
+
241
+ .stat-card .stat-label {
242
+ color: var(--text-secondary);
243
+ font-size: 0.875rem;
244
+ text-transform: uppercase;
245
+ letter-spacing: 0.5px;
246
+ }
247
+
248
+ /* Loading Spinner */
249
+ .spinner-border {
250
+ width: 2rem;
251
+ height: 2rem;
252
+ }
253
+
254
+ /* Empty State */
255
+ .text-center {
256
+ color: var(--text-secondary);
257
+ }
258
+
259
+ /* Markdown Preview */
260
+ .markdown-preview {
261
+ background: var(--card-bg);
262
+ border: 1px solid var(--border-color);
263
+ border-radius: var(--radius-md);
264
+ padding: 1.5rem;
265
+ max-height: 600px;
266
+ overflow-y: auto;
267
+ font-family: 'Courier New', monospace;
268
+ font-size: 0.9rem;
269
+ line-height: 1.6;
270
+ }
271
+
272
+ /* Download Buttons */
273
+ .download-btn-group {
274
+ display: flex;
275
+ gap: 0.5rem;
276
+ flex-wrap: wrap;
277
+ margin-top: 1rem;
278
+ }
279
+
280
+ /* Responsive */
281
+ @media (max-width: 768px) {
282
+ .image-gallery {
283
+ grid-template-columns: 1fr;
284
+ }
285
+
286
+ .sticky-top {
287
+ position: relative !important;
288
+ }
289
+ }
290
+
291
+ /* Scrollbar Styling */
292
+ ::-webkit-scrollbar {
293
+ width: 8px;
294
+ height: 8px;
295
+ }
296
+
297
+ ::-webkit-scrollbar-track {
298
+ background: var(--background-light);
299
+ }
300
+
301
+ ::-webkit-scrollbar-thumb {
302
+ background: var(--text-secondary);
303
+ border-radius: 4px;
304
+ }
305
+
306
+ ::-webkit-scrollbar-thumb:hover {
307
+ background: var(--accent);
308
+ }
309
+
310
+
static/js/app.js ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Application State
2
+ const AppState = {
3
+ currentPdf: null,
4
+ pdfs: [],
5
+ deviceInfo: null,
6
+ };
7
+
8
+ // Initialize on page load
9
+ document.addEventListener('DOMContentLoaded', function() {
10
+ initializeTheme();
11
+ loadDeviceInfo();
12
+ initializeEventListeners();
13
+ loadPdfList();
14
+ });
15
+
16
+ // Theme Toggle
17
+ function initializeTheme() {
18
+ const savedTheme = localStorage.getItem('theme') || 'light';
19
+ document.body.setAttribute('data-theme', savedTheme);
20
+ updateThemeIcon(savedTheme);
21
+
22
+ document.getElementById('themeToggle').addEventListener('click', function() {
23
+ const currentTheme = document.body.getAttribute('data-theme');
24
+ const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
25
+ document.body.setAttribute('data-theme', newTheme);
26
+ localStorage.setItem('theme', newTheme);
27
+ updateThemeIcon(newTheme);
28
+ });
29
+ }
30
+
31
+ function updateThemeIcon(theme) {
32
+ const icon = document.getElementById('themeIcon');
33
+ if (icon) {
34
+ icon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
35
+ }
36
+ }
37
+
38
+ // Load Device Info
39
+ async function loadDeviceInfo() {
40
+ try {
41
+ const response = await fetch('/api/device-info');
42
+ const data = await response.json();
43
+ AppState.deviceInfo = data;
44
+ updateDeviceStatus(data);
45
+ } catch (error) {
46
+ console.error('Error loading device info:', error);
47
+ updateDeviceStatus({ device: 'unknown', cuda_available: false });
48
+ }
49
+ }
50
+
51
+ function updateDeviceStatus(info) {
52
+ const badge = document.getElementById('deviceBadge');
53
+ const deviceName = document.getElementById('deviceName');
54
+
55
+ if (info.cuda_available) {
56
+ badge.textContent = 'GPU';
57
+ badge.className = 'badge bg-success';
58
+ deviceName.textContent = info.device_name || 'CUDA Device';
59
+ } else {
60
+ badge.textContent = 'CPU';
61
+ badge.className = 'badge bg-secondary';
62
+ deviceName.textContent = 'CPU Processing';
63
+ }
64
+ }
65
+
66
+ // Event Listeners
67
+ function initializeEventListeners() {
68
+ const uploadForm = document.getElementById('uploadForm');
69
+ uploadForm.addEventListener('submit', handleUpload);
70
+ }
71
+
72
+ // Handle File Upload
73
+ async function handleUpload(e) {
74
+ e.preventDefault();
75
+
76
+ const fileInput = document.getElementById('fileInput');
77
+ const files = fileInput.files;
78
+
79
+ if (files.length === 0) {
80
+ alert('Please select at least one PDF file');
81
+ return;
82
+ }
83
+
84
+ const extractionMode = document.querySelector('input[name="extractionMode"]:checked').value;
85
+
86
+ // Show processing section
87
+ document.getElementById('processingSection').style.display = 'block';
88
+ document.getElementById('resultsSection').style.display = 'none';
89
+ document.getElementById('emptyState').style.display = 'none';
90
+
91
+ const formData = new FormData();
92
+ for (let i = 0; i < files.length; i++) {
93
+ formData.append('files[]', files[i]);
94
+ }
95
+ formData.append('extraction_mode', extractionMode);
96
+
97
+ try {
98
+ const response = await fetch('/api/upload', {
99
+ method: 'POST',
100
+ body: formData
101
+ });
102
+
103
+ const data = await response.json();
104
+
105
+ if (data.error) {
106
+ throw new Error(data.error);
107
+ }
108
+
109
+ // Hide processing section
110
+ document.getElementById('processingSection').style.display = 'none';
111
+
112
+ // Reload PDF list and show results
113
+ await loadPdfList();
114
+
115
+ // Show first PDF details if available
116
+ if (data.results && data.results.length > 0) {
117
+ const firstPdf = data.results[0];
118
+ if (!firstPdf.error) {
119
+ showPdfDetails(firstPdf.stem);
120
+ }
121
+ }
122
+
123
+ // Reset form
124
+ fileInput.value = '';
125
+
126
+ } catch (error) {
127
+ console.error('Upload error:', error);
128
+ alert('Error processing files: ' + error.message);
129
+ document.getElementById('processingSection').style.display = 'none';
130
+ }
131
+ }
132
+
133
+ // Load PDF List
134
+ async function loadPdfList() {
135
+ try {
136
+ const response = await fetch('/api/pdf-list');
137
+ const data = await response.json();
138
+ AppState.pdfs = data.pdfs || [];
139
+ renderPdfList();
140
+
141
+ if (AppState.pdfs.length > 0) {
142
+ document.getElementById('resultsSection').style.display = 'block';
143
+ document.getElementById('emptyState').style.display = 'none';
144
+ } else {
145
+ document.getElementById('resultsSection').style.display = 'none';
146
+ document.getElementById('emptyState').style.display = 'block';
147
+ }
148
+ } catch (error) {
149
+ console.error('Error loading PDF list:', error);
150
+ }
151
+ }
152
+
153
+ // Render PDF List
154
+ function renderPdfList() {
155
+ const pdfList = document.getElementById('pdfList');
156
+ pdfList.innerHTML = '';
157
+
158
+ if (AppState.pdfs.length === 0) {
159
+ pdfList.innerHTML = '<div class="text-center text-muted p-3">No PDFs processed yet</div>';
160
+ return;
161
+ }
162
+
163
+ AppState.pdfs.forEach((pdf, index) => {
164
+ const item = document.createElement('div');
165
+ item.className = `list-group-item d-flex align-items-center justify-content-between ${index === 0 && !AppState.currentPdf ? 'active' : ''} ${AppState.currentPdf === pdf.stem ? 'active' : ''}`;
166
+
167
+ const left = document.createElement('a');
168
+ left.href = '#';
169
+ left.className = 'flex-grow-1 text-decoration-none text-reset';
170
+ left.innerHTML = `
171
+ <div class="d-flex w-100 justify-content-between">
172
+ <h6 class="mb-0">
173
+ <i class="fas fa-file-pdf me-2"></i>
174
+ ${pdf.stem}
175
+ </h6>
176
+ </div>
177
+ `;
178
+ left.addEventListener('click', function(e) {
179
+ e.preventDefault();
180
+ // Update active state
181
+ document.querySelectorAll('#pdfList .list-group-item').forEach(i => i.classList.remove('active'));
182
+ item.classList.add('active');
183
+ showPdfDetails(pdf.stem);
184
+ });
185
+
186
+ const delBtn = document.createElement('button');
187
+ delBtn.className = 'btn btn-sm btn-outline-danger ms-3';
188
+ delBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
189
+ delBtn.title = `Delete "${pdf.stem}"`;
190
+ delBtn.addEventListener('click', async (e) => {
191
+ e.preventDefault();
192
+ e.stopPropagation();
193
+ const confirmed = confirm(`Delete processed outputs for "${pdf.stem}"? This cannot be undone.`);
194
+ if (!confirmed) return;
195
+ try {
196
+ // Use form-encoded POST to the body endpoint for widest compatibility
197
+ const resp = await fetch('/api/delete', {
198
+ method: 'POST',
199
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
200
+ body: new URLSearchParams({ stem: pdf.stem }).toString()
201
+ });
202
+ const raw = await resp.text();
203
+ let res;
204
+ try { res = JSON.parse(raw); } catch (_) { res = null; }
205
+ if (!resp.ok || (res && res?.error)) {
206
+ throw new Error((res && res?.error) || raw || 'Delete failed');
207
+ }
208
+ // Refresh list and clear details if we deleted the active item
209
+ if (AppState.currentPdf === pdf.stem) {
210
+ AppState.currentPdf = null;
211
+ const details = document.getElementById('pdfDetails');
212
+ if (details) {
213
+ details.innerHTML = `
214
+ <div class="alert alert-success">
215
+ <i class="fas fa-check-circle me-2"></i>
216
+ Deleted "${pdf.stem}" successfully.
217
+ </div>
218
+ `;
219
+ }
220
+ }
221
+ await loadPdfList();
222
+ } catch (err) {
223
+ console.error('Delete error:', err);
224
+ alert('Failed to delete: ' + (err?.message || err));
225
+ }
226
+ });
227
+
228
+ item.appendChild(left);
229
+ item.appendChild(delBtn);
230
+ pdfList.appendChild(item);
231
+ });
232
+ }
233
+
234
+ // Show PDF Details
235
+ async function showPdfDetails(pdfStem) {
236
+ AppState.currentPdf = pdfStem;
237
+
238
+ // Update active state in list
239
+ document.querySelectorAll('#pdfList .list-group-item').forEach((item, index) => {
240
+ item.classList.remove('active');
241
+ const pdfStemFromItem = AppState.pdfs[index]?.stem;
242
+ if (pdfStemFromItem === pdfStem) {
243
+ item.classList.add('active');
244
+ }
245
+ });
246
+
247
+ try {
248
+ const response = await fetch(`/api/pdf-details/${encodeURIComponent(pdfStem)}`);
249
+ const data = await response.json();
250
+
251
+ if (data.error) {
252
+ throw new Error(data.error);
253
+ }
254
+
255
+ renderPdfDetails(data);
256
+ } catch (error) {
257
+ console.error('Error loading PDF details:', error);
258
+ document.getElementById('pdfDetails').innerHTML = `
259
+ <div class="alert alert-danger">
260
+ <i class="fas fa-exclamation-circle me-2"></i>
261
+ Error loading PDF details: ${error.message}
262
+ </div>
263
+ `;
264
+ }
265
+ }
266
+
267
+ // Render PDF Details
268
+ function renderPdfDetails(data) {
269
+ const container = document.getElementById('pdfDetails');
270
+
271
+ let html = `
272
+ <div class="card shadow-sm mb-4">
273
+ <div class="card-header bg-primary-custom text-white">
274
+ <h5 class="mb-0">
275
+ <i class="fas fa-file-pdf me-2"></i>
276
+ ${data.stem}
277
+ </h5>
278
+ <button class="btn btn-sm btn-danger float-end" id="deletePdfBtn" title="Delete this processed PDF">
279
+ <i class="fas fa-trash-alt me-1"></i> Delete
280
+ </button>
281
+ </div>
282
+ <div class="card-body">
283
+ <div class="row mb-4">
284
+ <div class="col-md-3">
285
+ <div class="stat-card">
286
+ <i class="fas fa-images fa-2x text-primary mb-2"></i>
287
+ <div class="stat-value">${data.figures_count || 0}</div>
288
+ <div class="stat-label">Figures</div>
289
+ </div>
290
+ </div>
291
+ <div class="col-md-3">
292
+ <div class="stat-card">
293
+ <i class="fas fa-table fa-2x text-primary mb-2"></i>
294
+ <div class="stat-value">${data.tables_count || 0}</div>
295
+ <div class="stat-label">Tables</div>
296
+ </div>
297
+ </div>
298
+ <div class="col-md-3">
299
+ <div class="stat-card">
300
+ <i class="fas fa-list fa-2x text-primary mb-2"></i>
301
+ <div class="stat-value">${data.elements_count || 0}</div>
302
+ <div class="stat-label">Total Elements</div>
303
+ </div>
304
+ </div>
305
+ <div class="col-md-3">
306
+ <div class="stat-card">
307
+ <i class="fas fa-microchip fa-2x text-primary mb-2"></i>
308
+ <div class="stat-value">${AppState.deviceInfo?.device === 'cuda' ? 'GPU' : 'CPU'}</div>
309
+ <div class="stat-label">Device</div>
310
+ </div>
311
+ </div>
312
+ </div>
313
+
314
+ <div class="download-btn-group">
315
+ `;
316
+
317
+ if (data.annotated_pdf) {
318
+ html += `
319
+ <a href="/output/${data.annotated_pdf}" class="btn btn-primary" download>
320
+ <i class="fas fa-download me-2"></i>
321
+ Download Annotated PDF
322
+ </a>
323
+ `;
324
+ }
325
+
326
+ if (data.markdown_path) {
327
+ html += `
328
+ <a href="/output/${data.markdown_path}" class="btn btn-outline-primary" download>
329
+ <i class="fas fa-download me-2"></i>
330
+ Download Markdown
331
+ </a>
332
+ `;
333
+ }
334
+
335
+ html += `
336
+ </div>
337
+ </div>
338
+ </div>
339
+ `;
340
+
341
+ // Figures Section
342
+ if (data.figure_images && data.figure_images.length > 0) {
343
+ html += `
344
+ <div class="card shadow-sm mb-4">
345
+ <div class="card-header">
346
+ <h5 class="mb-0">
347
+ <i class="fas fa-images me-2"></i>
348
+ Figures (${data.figure_images.length})
349
+ </h5>
350
+ </div>
351
+ <div class="card-body">
352
+ <div class="image-gallery">
353
+ `;
354
+
355
+ data.figure_images.forEach((imgPath, index) => {
356
+ const figure = data.figures[index] || {};
357
+ html += `
358
+ <div class="image-item">
359
+ <img src="/output/${imgPath}" alt="Figure ${index + 1}" loading="lazy">
360
+ <div class="image-caption">
361
+ <strong>Figure ${index + 1}</strong>
362
+ ${figure.page ? `<br><small class="text-muted">Page ${figure.page}</small>` : ''}
363
+ </div>
364
+ </div>
365
+ `;
366
+ });
367
+
368
+ html += `
369
+ </div>
370
+ </div>
371
+ </div>
372
+ `;
373
+ }
374
+
375
+ // Tables Section
376
+ if (data.table_images && data.table_images.length > 0) {
377
+ html += `
378
+ <div class="card shadow-sm mb-4">
379
+ <div class="card-header">
380
+ <h5 class="mb-0">
381
+ <i class="fas fa-table me-2"></i>
382
+ Tables (${data.table_images.length})
383
+ </h5>
384
+ </div>
385
+ <div class="card-body">
386
+ <div class="image-gallery">
387
+ `;
388
+
389
+ data.table_images.forEach((imgPath, index) => {
390
+ const table = data.tables[index] || {};
391
+ html += `
392
+ <div class="image-item">
393
+ <img src="/output/${imgPath}" alt="Table ${index + 1}" loading="lazy">
394
+ <div class="image-caption">
395
+ <strong>Table ${index + 1}</strong>
396
+ ${table.page ? `<br><small class="text-muted">Page ${table.page}</small>` : ''}
397
+ </div>
398
+ </div>
399
+ `;
400
+ });
401
+
402
+ html += `
403
+ </div>
404
+ </div>
405
+ </div>
406
+ `;
407
+ }
408
+
409
+ // Markdown Preview
410
+ if (data.markdown_path) {
411
+ html += `
412
+ <div class="card shadow-sm">
413
+ <div class="card-header">
414
+ <h5 class="mb-0">
415
+ <i class="fas fa-file-code me-2"></i>
416
+ Markdown Preview
417
+ </h5>
418
+ </div>
419
+ <div class="card-body">
420
+ <div class="markdown-preview" id="markdownPreview">
421
+ Loading markdown...
422
+ </div>
423
+ </div>
424
+ </div>
425
+ `;
426
+ }
427
+
428
+ container.innerHTML = html;
429
+
430
+ // Load markdown preview if available
431
+ if (data.markdown_path) {
432
+ loadMarkdownPreview(data.markdown_path);
433
+ }
434
+
435
+ // Wire delete button
436
+ const deleteBtn = document.getElementById('deletePdfBtn');
437
+ if (deleteBtn) {
438
+ deleteBtn.addEventListener('click', async () => {
439
+ const confirmed = confirm(`Delete processed outputs for "${data.stem}"? This cannot be undone.`);
440
+ if (!confirmed) return;
441
+ try {
442
+ // Use form-encoded POST to the body endpoint for widest compatibility
443
+ const resp = await fetch('/api/delete', {
444
+ method: 'POST',
445
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
446
+ body: new URLSearchParams({ stem: data.stem }).toString()
447
+ });
448
+ const raw = await resp.text();
449
+ let res;
450
+ try { res = JSON.parse(raw); } catch (_) { res = null; }
451
+ if (!resp.ok || (res && res.error)) {
452
+ throw new Error((res && res.error) || raw || 'Delete failed');
453
+ }
454
+ // Refresh list and clear details
455
+ await loadPdfList();
456
+ document.getElementById('pdfDetails').innerHTML = `
457
+ <div class="alert alert-success">
458
+ <i class="fas fa-check-circle me-2"></i>
459
+ Deleted "${data.stem}" successfully.
460
+ </div>
461
+ `;
462
+ AppState.currentPdf = null;
463
+ } catch (err) {
464
+ console.error('Delete error:', err);
465
+ alert('Failed to delete: ' + (err?.message || err));
466
+ }
467
+ });
468
+ }
469
+ }
470
+
471
+ // Load Markdown Preview
472
+ async function loadMarkdownPreview(markdownPath) {
473
+ try {
474
+ const response = await fetch(`/output/${markdownPath}`);
475
+ const text = await response.text();
476
+ document.getElementById('markdownPreview').textContent = text;
477
+ } catch (error) {
478
+ console.error('Error loading markdown:', error);
479
+ document.getElementById('markdownPreview').textContent = 'Error loading markdown content';
480
+ }
481
+ }
482
+
templates/index.html ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>PDF Layout Extractor</title>
7
+
8
+ <!-- Bootstrap 5 CSS -->
9
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
10
+ <!-- Font Awesome -->
11
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
12
+ <!-- Custom CSS -->
13
+ <link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet">
14
+ </head>
15
+ <body data-theme="light">
16
+ <!-- Navigation -->
17
+ <nav class="navbar navbar-expand-lg navbar-dark bg-primary-custom">
18
+ <div class="container-fluid">
19
+ <a class="navbar-brand" href="#">
20
+ <i class="fas fa-file-pdf me-2"></i>
21
+ PDF Layout Extractor
22
+ </a>
23
+ <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
24
+ <span class="navbar-toggler-icon"></span>
25
+ </button>
26
+ <div class="collapse navbar-collapse" id="navbarNav">
27
+ <ul class="navbar-nav ms-auto">
28
+ <li class="nav-item">
29
+ <button class="btn btn-link nav-link text-white" id="themeToggle">
30
+ <i class="fas fa-moon" id="themeIcon"></i>
31
+ </button>
32
+ </li>
33
+ </ul>
34
+ </div>
35
+ </div>
36
+ </nav>
37
+
38
+ <!-- Main Container -->
39
+ <div class="container-fluid mt-4">
40
+ <!-- Device Status Card -->
41
+ <div class="row mb-4">
42
+ <div class="col-12">
43
+ <div class="card shadow-sm">
44
+ <div class="card-body">
45
+ <div class="d-flex justify-content-between align-items-center">
46
+ <div>
47
+ <h5 class="card-title mb-1">
48
+ <i class="fas fa-microchip me-2"></i>
49
+ Processing Device
50
+ </h5>
51
+ <p class="text-muted mb-0" id="deviceStatus">
52
+ <span class="badge bg-secondary" id="deviceBadge">Checking...</span>
53
+ </p>
54
+ </div>
55
+ <div class="text-end">
56
+ <div id="deviceInfo" class="small text-muted">
57
+ <div id="deviceName">-</div>
58
+ </div>
59
+ </div>
60
+ </div>
61
+ </div>
62
+ </div>
63
+ </div>
64
+ </div>
65
+
66
+ <!-- Upload Section -->
67
+ <div class="row mb-4">
68
+ <div class="col-12">
69
+ <div class="card shadow-sm">
70
+ <div class="card-header bg-primary-custom text-white">
71
+ <h5 class="mb-0">
72
+ <i class="fas fa-upload me-2"></i>
73
+ Upload PDFs
74
+ </h5>
75
+ </div>
76
+ <div class="card-body">
77
+ <form id="uploadForm">
78
+ <div class="mb-3">
79
+ <label for="fileInput" class="form-label">Select PDF Files</label>
80
+ <input type="file" class="form-control" id="fileInput"
81
+ accept=".pdf" multiple required>
82
+ <div class="form-text">You can select multiple PDF files at once</div>
83
+ </div>
84
+
85
+ <div class="mb-3">
86
+ <label class="form-label">Extraction Mode</label>
87
+ <div class="btn-group w-100" role="group">
88
+ <input type="radio" class="btn-check" name="extractionMode"
89
+ id="modeImages" value="images" checked>
90
+ <label class="btn btn-outline-primary" for="modeImages">
91
+ <i class="fas fa-images me-2"></i>Images Only
92
+ </label>
93
+
94
+ <input type="radio" class="btn-check" name="extractionMode"
95
+ id="modeMarkdown" value="markdown">
96
+ <label class="btn btn-outline-primary" for="modeMarkdown">
97
+ <i class="fas fa-file-code me-2"></i>Markdown Only
98
+ </label>
99
+
100
+ <input type="radio" class="btn-check" name="extractionMode"
101
+ id="modeBoth" value="both">
102
+ <label class="btn btn-outline-primary" for="modeBoth">
103
+ <i class="fas fa-layer-group me-2"></i>Both
104
+ </label>
105
+ </div>
106
+ </div>
107
+
108
+ <button type="submit" class="btn btn-primary w-100" id="uploadBtn">
109
+ <i class="fas fa-upload me-2"></i>
110
+ Upload and Process
111
+ </button>
112
+ </form>
113
+ </div>
114
+ </div>
115
+ </div>
116
+ </div>
117
+
118
+ <!-- Processing Status -->
119
+ <div class="row mb-4" id="processingSection" style="display: none;">
120
+ <div class="col-12">
121
+ <div class="card shadow-sm">
122
+ <div class="card-body">
123
+ <div class="d-flex align-items-center">
124
+ <div class="spinner-border text-primary me-3" role="status">
125
+ <span class="visually-hidden">Loading...</span>
126
+ </div>
127
+ <div>
128
+ <h6 class="mb-0">Processing PDFs...</h6>
129
+ <small class="text-muted" id="processingStatus">Please wait</small>
130
+ </div>
131
+ </div>
132
+ </div>
133
+ </div>
134
+ </div>
135
+ </div>
136
+
137
+ <!-- Results Section -->
138
+ <div class="row" id="resultsSection" style="display: none;">
139
+ <div class="col-md-4">
140
+ <div class="card shadow-sm sticky-top" style="top: 20px;">
141
+ <div class="card-header bg-primary-custom text-white">
142
+ <h5 class="mb-0">
143
+ <i class="fas fa-list me-2"></i>
144
+ Processed PDFs
145
+ </h5>
146
+ </div>
147
+ <div class="card-body">
148
+ <div class="list-group" id="pdfList">
149
+ <!-- PDF list will be populated here -->
150
+ </div>
151
+ </div>
152
+ </div>
153
+ </div>
154
+
155
+ <div class="col-md-8">
156
+ <div id="pdfDetails">
157
+ <!-- PDF details will be shown here -->
158
+ </div>
159
+ </div>
160
+ </div>
161
+
162
+ <!-- Empty State -->
163
+ <div class="row" id="emptyState">
164
+ <div class="col-12">
165
+ <div class="card shadow-sm">
166
+ <div class="card-body text-center py-5">
167
+ <i class="fas fa-file-pdf fa-3x text-muted mb-3"></i>
168
+ <h5 class="text-muted">No PDFs processed yet</h5>
169
+ <p class="text-muted">Upload PDF files above to get started</p>
170
+ </div>
171
+ </div>
172
+ </div>
173
+ </div>
174
+ </div>
175
+
176
+ <!-- Bootstrap JS -->
177
+ <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
178
+ <!-- Custom JS -->
179
+ <script src="{{ url_for('static', filename='js/app.js') }}"></script>
180
+ </body>
181
+ </html>
182
+
183
+