Spaces:
Sleeping
Sleeping
update
Browse files- .gitignore +14 -0
- .python-version +1 -0
- README.md +125 -7
- app.py +295 -0
- main.py +1309 -0
- modal_app.py +112 -0
- pdf_extractor_gui.py +624 -0
- pyproject.toml +20 -0
- run_flask_gpu.py +48 -0
- static/css/styles.css +310 -0
- static/js/app.js +482 -0
- templates/index.html +183 -0
- uv.lock +0 -0
.gitignore
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python-generated files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[oc]
|
| 4 |
+
build/
|
| 5 |
+
dist/
|
| 6 |
+
wheels/
|
| 7 |
+
*.egg-info
|
| 8 |
+
|
| 9 |
+
# Virtual environments
|
| 10 |
+
.venv
|
| 11 |
+
pdfs/*
|
| 12 |
+
/output4
|
| 13 |
+
/output
|
| 14 |
+
/uploads
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.12
|
README.md
CHANGED
|
@@ -1,10 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PDF Layout Extraction Companion
|
| 2 |
+
|
| 3 |
+
A streamlined workflow for extracting figures, tables, annotated layouts, and markdown text from scientific PDFs using [DocLayout-YOLO](https://github.com/juliozhao/DocLayout-YOLO), PyMuPDF, and Flask. The project exposes a command-line pipeline (`main.py`) and a modern Flask web UI (`app.py`).
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Features
|
| 8 |
+
- **Layout-aware extraction** of figures and tables with YOLO-based detection
|
| 9 |
+
- **Cross-page stitching** for multi-page tables, captions, titles, and body text
|
| 10 |
+
- **Annotated PDF output** with bounding boxes for detected regions
|
| 11 |
+
- **Markdown export** powered by `pymupdf4llm` / `pymupdf-layout`
|
| 12 |
+
- **Flask Web UI** with modern design, dark/light theme, GPU/CPU status, and individual PDF viewing
|
| 13 |
+
- Unified `output/<PDF stem>/` directory structure for CLI + UI runs
|
| 14 |
+
|
| 15 |
---
|
| 16 |
+
|
| 17 |
+
## Requirements
|
| 18 |
+
- Python 3.12+
|
| 19 |
+
- [uv](https://docs.astral.sh/uv/latest/) (recommended) or `pip`
|
| 20 |
+
- GPU optional (DocLayout-YOLO runs on CPU as well)
|
| 21 |
+
|
| 22 |
+
Install dependencies:
|
| 23 |
+
```bash
|
| 24 |
+
uv pip install
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
> If you prefer a virtualenv, create/activate it first, then run `uv pip install` inside.
|
| 28 |
+
|
| 29 |
---
|
| 30 |
|
| 31 |
+
## Quick Start
|
| 32 |
+
|
| 33 |
+
### Command Line Pipeline
|
| 34 |
+
Process all PDFs in `./pdfs` and write outputs to `./output/<PDF stem>/`:
|
| 35 |
+
```bash
|
| 36 |
+
uv run python main.py
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Each subdirectory contains:
|
| 40 |
+
- `* _content_list.json` – metadata for extracted figures/tables
|
| 41 |
+
- `*_layout.pdf` – annotated PDF with layout boxes
|
| 42 |
+
- `*.md` – markdown export (if `pymupdf4llm` is installed)
|
| 43 |
+
- `figures/` & `tables/` – cropped PNGs with stitched captions/titles
|
| 44 |
+
|
| 45 |
+
### Flask Web App (Recommended)
|
| 46 |
+
Launch the modern Flask web interface locally:
|
| 47 |
+
```bash
|
| 48 |
+
python run_flask_gpu.py
|
| 49 |
+
```
|
| 50 |
+
Then open your browser to `http://localhost:5000`
|
| 51 |
+
|
| 52 |
+
**Features:**
|
| 53 |
+
- Clean, modern UI with dark/light theme support
|
| 54 |
+
- Multiple PDF upload and processing
|
| 55 |
+
- Individual PDF output viewing with sidebar navigation
|
| 56 |
+
- Real-time GPU/CPU status display
|
| 57 |
+
- Image gallery for figures and tables
|
| 58 |
+
- Markdown preview and download
|
| 59 |
+
- Responsive design for mobile and desktop
|
| 60 |
+
|
| 61 |
+
All Flask app runs also write into `./output/<PDF stem>/` using the same structure as the CLI.
|
| 62 |
+
|
| 63 |
+
### Deploy to Modal.com (Cloud with GPU)
|
| 64 |
+
Deploy your Flask app online with GPU support using Modal:
|
| 65 |
+
```bash
|
| 66 |
+
# Install Modal CLI
|
| 67 |
+
pip install modal
|
| 68 |
+
|
| 69 |
+
# Authenticate with Modal
|
| 70 |
+
modal token new
|
| 71 |
+
|
| 72 |
+
# Deploy to Modal
|
| 73 |
+
modal deploy modal_app.py
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
See [MODAL_DEPLOYMENT.md](MODAL_DEPLOYMENT.md) for detailed instructions.
|
| 77 |
+
|
| 78 |
+
**Benefits:**
|
| 79 |
+
- GPU support (T4, A10G, or A100)
|
| 80 |
+
- Pay-per-use pricing
|
| 81 |
+
- Automatic HTTPS
|
| 82 |
+
- Auto-scaling
|
| 83 |
+
- Global deployment
|
| 84 |
+
|
| 85 |
+
---
|
| 86 |
+
|
| 87 |
+
## Configuration Highlights
|
| 88 |
+
- **Detection model:** DocLayout-YOLO (`doclayout_yolo_docstructbench_imgsz1024.pt`)
|
| 89 |
+
- **Detection thresholds:** configurable in `main.py`
|
| 90 |
+
- **Layout stitching:** tables, captions, titles, body text
|
| 91 |
+
- **Markdown extraction:** defaults to enabled (`pymupdf4llm.to_markdown`); falls back gracefully if the package is missing
|
| 92 |
+
- **Output directory:** `./output` (configurable near the bottom of `main.py`)
|
| 93 |
+
|
| 94 |
+
---
|
| 95 |
+
|
| 96 |
+
## File Overview
|
| 97 |
+
| Path | Description |
|
| 98 |
+
|------|-------------|
|
| 99 |
+
| `main.py` | CLI pipeline for batch PDF processing |
|
| 100 |
+
| `app.py` | Flask web application (recommended UI) |
|
| 101 |
+
| `run_flask_gpu.py` | Local Flask runner with GPU support |
|
| 102 |
+
| `modal_app.py` | Modal.com deployment configuration (cloud GPU) |
|
| 103 |
+
| `MODAL_DEPLOYMENT.md` | Modal.com deployment guide |
|
| 104 |
+
| `templates/` | Flask HTML templates |
|
| 105 |
+
| `static/` | Flask static files (CSS, JS) |
|
| 106 |
+
| `pdfs/` | Source PDFs (gitignored) |
|
| 107 |
+
| `output/` | Generated outputs per PDF |
|
| 108 |
+
| `pyproject.toml` | Project metadata & dependency list |
|
| 109 |
+
| `uv.lock` | Locked dependency versions (auto-maintained by `uv`) |
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
## Troubleshooting
|
| 114 |
+
- **`ModuleNotFoundError: pymupdf4llm`** – install it via `uv pip install pymupdf4llm` (already listed in `pyproject.toml`).
|
| 115 |
+
- **Slow performance** – ensure GPU CUDA drivers are available or reduce concurrency by toggling `USE_MULTIPROCESSING` in `main.py`.
|
| 116 |
+
- **Large outputs** – clean the `output/` directory before reruns to avoid confusing duplicates.
|
| 117 |
+
|
| 118 |
+
For additional logging, set `LOG_LEVEL` or edit the `logger` configuration in `main.py`.
|
| 119 |
+
|
| 120 |
+
---
|
| 121 |
+
|
| 122 |
+
## Acknowledgements
|
| 123 |
+
- [DocLayout-YOLO](https://github.com/juliozhao/DocLayout-YOLO)
|
| 124 |
+
- [PyMuPDF](https://pymupdf.readthedocs.io/)
|
| 125 |
+
- [PyMuPDF4LLM](https://github.com/pymupdf/RAG/blob/main/pymupdf4llm.md)
|
| 126 |
+
- [Flask](https://flask.palletsprojects.com/)
|
| 127 |
+
|
| 128 |
+
Happy extracting! 🎉
|
app.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
app.run(debug=True, host='0.0.0.0', port=5000)
|
| 294 |
+
|
| 295 |
+
|
main.py
ADDED
|
@@ -0,0 +1,1309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|
modal_app.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Modal deployment configuration for PDF Layout Extractor Flask app.
|
| 3 |
+
Deploy with: modal deploy modal_app.py
|
| 4 |
+
"""
|
| 5 |
+
import modal
|
| 6 |
+
|
| 7 |
+
# Create a Modal image with GPU support and all dependencies
|
| 8 |
+
image = (
|
| 9 |
+
modal.Image.debian_slim(python_version="3.12")
|
| 10 |
+
.apt_install(
|
| 11 |
+
"build-essential",
|
| 12 |
+
"gcc",
|
| 13 |
+
"g++",
|
| 14 |
+
"libgl1",
|
| 15 |
+
"libglib2.0-0", # Required for cv2 (provides libgthread-2.0.so.0)
|
| 16 |
+
"libsm6", # Required for cv2
|
| 17 |
+
"libxext6", # Required for cv2
|
| 18 |
+
"libxrender-dev", # Required for cv2
|
| 19 |
+
"libgomp1", # Required for cv2
|
| 20 |
+
"libffi-dev",
|
| 21 |
+
"libjpeg62-turbo-dev",
|
| 22 |
+
"zlib1g-dev",
|
| 23 |
+
"netcat-openbsd",
|
| 24 |
+
)
|
| 25 |
+
.pip_install(
|
| 26 |
+
"torch>=2.0.0",
|
| 27 |
+
"torchvision>=0.15.0",
|
| 28 |
+
"doclayout-yolo>=0.0.4",
|
| 29 |
+
"huggingface-hub>=1.1.2",
|
| 30 |
+
"loguru>=0.7.3",
|
| 31 |
+
"pillow>=12.0.0",
|
| 32 |
+
"pymupdf>=1.26.6",
|
| 33 |
+
"pymupdf-layout>=0.0.15",
|
| 34 |
+
"pypdfium2>=5.0.0",
|
| 35 |
+
"pymupdf4llm>=0.1.9",
|
| 36 |
+
"flask>=3.0.0",
|
| 37 |
+
"fastapi>=0.109.0", # Required for Modal web endpoints
|
| 38 |
+
"werkzeug>=3.0.0",
|
| 39 |
+
"gunicorn>=21.2.0",
|
| 40 |
+
"asgiref>=3.7.0", # For WSGI-to-ASGI conversion
|
| 41 |
+
)
|
| 42 |
+
.run_commands(
|
| 43 |
+
"mkdir -p /app/uploads /app/output /app/static /app/templates"
|
| 44 |
+
)
|
| 45 |
+
# Copy application files directly into the image
|
| 46 |
+
.add_local_dir("static", remote_path="/app/static")
|
| 47 |
+
.add_local_dir("templates", remote_path="/app/templates")
|
| 48 |
+
.add_local_file("app.py", remote_path="/app/app.py")
|
| 49 |
+
.add_local_file("main.py", remote_path="/app/main.py")
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Create the Modal app
|
| 53 |
+
app = modal.App("pdf-layout-extractor", image=image)
|
| 54 |
+
|
| 55 |
+
# GPU configuration - using T4 for cheapest option (~$0.50/hour while active)
|
| 56 |
+
# For no GPU (CPU only), set gpu=None (much cheaper but slower)
|
| 57 |
+
# Valid options: "T4", "A10G", "A100", or None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@app.function(
|
| 61 |
+
image=image,
|
| 62 |
+
gpu="T4", # Cheapest GPU option (~$0.50/hour while active)
|
| 63 |
+
secrets=[
|
| 64 |
+
# Add any secrets here if needed (e.g., HUGGINGFACE_TOKEN)
|
| 65 |
+
# modal.Secret.from_name("huggingface-secret"),
|
| 66 |
+
],
|
| 67 |
+
timeout=3600, # 1 hour timeout for long PDF processing
|
| 68 |
+
max_containers=10, # Handle up to 10 concurrent requests
|
| 69 |
+
)
|
| 70 |
+
@modal.asgi_app()
|
| 71 |
+
def flask_app():
|
| 72 |
+
"""
|
| 73 |
+
Expose the Flask app as an ASGI application for Modal.
|
| 74 |
+
Flask is WSGI, so we convert it to ASGI using a wrapper.
|
| 75 |
+
"""
|
| 76 |
+
import sys
|
| 77 |
+
import os
|
| 78 |
+
from pathlib import Path
|
| 79 |
+
|
| 80 |
+
# Set working directory
|
| 81 |
+
os.chdir("/app")
|
| 82 |
+
sys.path.insert(0, "/app")
|
| 83 |
+
|
| 84 |
+
# Import Flask app
|
| 85 |
+
from app import app as flask_app_instance
|
| 86 |
+
|
| 87 |
+
# Convert Flask WSGI app to ASGI for Modal
|
| 88 |
+
# Using asgiref's WSGI-to-ASGI adapter
|
| 89 |
+
from asgiref.wsgi import WsgiToAsgi
|
| 90 |
+
|
| 91 |
+
asgi_app = WsgiToAsgi(flask_app_instance)
|
| 92 |
+
return asgi_app
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# Alternative: Deploy as a web endpoint with automatic HTTPS
|
| 96 |
+
@app.function(
|
| 97 |
+
image=image,
|
| 98 |
+
gpu="T4",
|
| 99 |
+
timeout=3600,
|
| 100 |
+
max_containers=10,
|
| 101 |
+
)
|
| 102 |
+
@modal.fastapi_endpoint(method="GET", label="pdf-extractor")
|
| 103 |
+
def health():
|
| 104 |
+
"""Health check endpoint."""
|
| 105 |
+
return {"status": "ok", "service": "pdf-layout-extractor"}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
# For local testing with Modal dev server:
|
| 110 |
+
# Run: modal serve modal_app.py
|
| 111 |
+
pass
|
| 112 |
+
|
pdf_extractor_gui.py
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import cv2
|
| 6 |
+
import fitz # PyMuPDF
|
| 7 |
+
import pytesseract
|
| 8 |
+
import numpy as np
|
| 9 |
+
from typing import List, Dict, Tuple, Optional
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import tempfile
|
| 14 |
+
import zipfile
|
| 15 |
+
import io
|
| 16 |
+
|
| 17 |
+
class PDFExtractor:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
# Configuration (same as original)
|
| 20 |
+
self.config = {
|
| 21 |
+
'dpi': 400,
|
| 22 |
+
'min_area_ratio': 0.02,
|
| 23 |
+
'max_area_ratio': 0.96,
|
| 24 |
+
'min_width_px': 200,
|
| 25 |
+
'min_height_px': 220,
|
| 26 |
+
'inset_px': 6,
|
| 27 |
+
'stitch': {
|
| 28 |
+
'y_tol': 60,
|
| 29 |
+
'h_tol': 120,
|
| 30 |
+
'x_tol': 60,
|
| 31 |
+
'w_tol': 120,
|
| 32 |
+
},
|
| 33 |
+
'caption_regex': r"^\s*(?:Figure|Fig\.?|Panel|Table)\s*[\dA-Za-z\-\.]*",
|
| 34 |
+
'ocr_lang': 'eng',
|
| 35 |
+
'rotate_on_demand': False,
|
| 36 |
+
'debug_mode': False,
|
| 37 |
+
'max_caption_search_pages_ahead': 1,
|
| 38 |
+
}
|
| 39 |
+
self.setup_tesseract()
|
| 40 |
+
|
| 41 |
+
def setup_tesseract(self):
|
| 42 |
+
"""Try to find Tesseract executable"""
|
| 43 |
+
possible_paths = [
|
| 44 |
+
r'C:\Program Files\Tesseract-OCR\tesseract.exe',
|
| 45 |
+
r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe',
|
| 46 |
+
'/usr/bin/tesseract',
|
| 47 |
+
'/usr/local/bin/tesseract',
|
| 48 |
+
'tesseract' # If in PATH
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
for path in possible_paths:
|
| 52 |
+
try:
|
| 53 |
+
if os.path.exists(path) or path == 'tesseract':
|
| 54 |
+
pytesseract.pytesseract.tesseract_cmd = path
|
| 55 |
+
# Test if it works
|
| 56 |
+
test_img = np.ones((50, 50, 3), dtype=np.uint8) * 255
|
| 57 |
+
pytesseract.image_to_string(test_img)
|
| 58 |
+
return True
|
| 59 |
+
except:
|
| 60 |
+
continue
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
def process_single_pdf(self, pdf_path: str, out_dir: str):
|
| 64 |
+
"""Process a single PDF file (adapted from original code)"""
|
| 65 |
+
if not os.path.isfile(pdf_path):
|
| 66 |
+
raise FileNotFoundError(f"PDF not found: {pdf_path}")
|
| 67 |
+
|
| 68 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
doc = fitz.open(pdf_path)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
raise Exception(f"Error opening PDF: {e}")
|
| 74 |
+
|
| 75 |
+
detections_by_page = []
|
| 76 |
+
total_pages = len(doc)
|
| 77 |
+
|
| 78 |
+
# Progress tracking for Streamlit
|
| 79 |
+
if hasattr(self, 'progress_callback'):
|
| 80 |
+
self.progress_callback(f"Analyzing {total_pages} pages...")
|
| 81 |
+
|
| 82 |
+
for pno, page in enumerate(doc):
|
| 83 |
+
img = self.render_page_to_bgr(page, self.config['dpi'])
|
| 84 |
+
boxes, _ = self.detect_boxes_on_image(
|
| 85 |
+
img,
|
| 86 |
+
min_area_ratio=self.config['min_area_ratio'],
|
| 87 |
+
max_area_ratio=self.config['max_area_ratio'],
|
| 88 |
+
min_w=self.config['min_width_px'],
|
| 89 |
+
min_h=self.config['min_height_px'],
|
| 90 |
+
inset_px=self.config['inset_px'],
|
| 91 |
+
debug_overlay=self.config['debug_mode'],
|
| 92 |
+
)
|
| 93 |
+
for b in boxes:
|
| 94 |
+
b['page'] = pno
|
| 95 |
+
detections_by_page.append(boxes)
|
| 96 |
+
if hasattr(self, 'progress_callback'):
|
| 97 |
+
self.progress_callback(f" - Page {pno+1}: {len(boxes)} region(s)")
|
| 98 |
+
|
| 99 |
+
doc.close()
|
| 100 |
+
|
| 101 |
+
self.classify_boxes_with_ocr(detections_by_page, self.config['ocr_lang'])
|
| 102 |
+
figures = self.stitch_split_figures(detections_by_page)
|
| 103 |
+
self.save_results(figures, detections_by_page, out_dir)
|
| 104 |
+
|
| 105 |
+
# Original algorithm methods (adapted for the class)
|
| 106 |
+
def render_page_to_bgr(self, page: fitz.Page, dpi: int) -> np.ndarray:
|
| 107 |
+
mat = fitz.Matrix(dpi / 72.0, dpi / 72.0)
|
| 108 |
+
pix = page.get_pixmap(matrix=mat, alpha=False)
|
| 109 |
+
img_bytes = pix.tobytes("png")
|
| 110 |
+
arr = np.frombuffer(img_bytes, np.uint8)
|
| 111 |
+
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
| 112 |
+
return img
|
| 113 |
+
|
| 114 |
+
def detect_boxes_on_image(self, img: np.ndarray, min_area_ratio: float, max_area_ratio: float,
|
| 115 |
+
min_w: int, min_h: int, inset_px: int, debug_overlay: bool = False
|
| 116 |
+
) -> Tuple[List[Dict], Optional[np.ndarray]]:
|
| 117 |
+
H, W = img.shape[:2]
|
| 118 |
+
page_area = W * H
|
| 119 |
+
|
| 120 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 121 |
+
bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
|
| 122 |
+
cv2.THRESH_BINARY_INV, 21, 12)
|
| 123 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
|
| 124 |
+
closed = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel, iterations=2)
|
| 125 |
+
|
| 126 |
+
contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 127 |
+
|
| 128 |
+
boxes: List[Dict] = []
|
| 129 |
+
|
| 130 |
+
for cnt in contours:
|
| 131 |
+
peri = cv2.arcLength(cnt, True)
|
| 132 |
+
if peri < 80:
|
| 133 |
+
continue
|
| 134 |
+
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
|
| 135 |
+
x, y, w, h = cv2.boundingRect(approx)
|
| 136 |
+
|
| 137 |
+
if w < min_w or h < min_h:
|
| 138 |
+
continue
|
| 139 |
+
area = w * h
|
| 140 |
+
area_ratio = area / page_area
|
| 141 |
+
if not (min_area_ratio <= area_ratio <= max_area_ratio):
|
| 142 |
+
continue
|
| 143 |
+
if (w / (h + 1e-6) > 12) or (h / (w + 1e-6) > 12):
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
mask = np.zeros((H, W), dtype=np.uint8)
|
| 147 |
+
cv2.drawContours(mask, [approx], -1, 255, -1)
|
| 148 |
+
|
| 149 |
+
def edge_present(slice_arr: np.ndarray) -> bool:
|
| 150 |
+
if slice_arr.size == 0:
|
| 151 |
+
return False
|
| 152 |
+
return (np.mean(slice_arr) > 20)
|
| 153 |
+
|
| 154 |
+
edge_thickness = 8
|
| 155 |
+
top_slice = mask[y:y+edge_thickness, x:x+w] if y+edge_thickness < H else mask[y:H, x:x+w]
|
| 156 |
+
bottom_slice = mask[max(0, y+h-edge_thickness):y+h, x:x+w]
|
| 157 |
+
left_slice = mask[y:y+h, x:x+edge_thickness] if x+edge_thickness < W else mask[y:y+h, x:W]
|
| 158 |
+
right_slice = mask[y:y+h, max(0, x+w-edge_thickness):x+w]
|
| 159 |
+
|
| 160 |
+
top_edge = edge_present(top_slice)
|
| 161 |
+
bottom_edge = edge_present(bottom_slice)
|
| 162 |
+
left_edge = edge_present(left_slice)
|
| 163 |
+
right_edge = edge_present(right_slice)
|
| 164 |
+
|
| 165 |
+
open_sides = []
|
| 166 |
+
if not top_edge: open_sides.append("top")
|
| 167 |
+
if not bottom_edge: open_sides.append("bottom")
|
| 168 |
+
if not left_edge: open_sides.append("left")
|
| 169 |
+
if not right_edge: open_sides.append("right")
|
| 170 |
+
|
| 171 |
+
x1 = max(0, x + inset_px)
|
| 172 |
+
y1 = max(0, y + inset_px)
|
| 173 |
+
x2 = min(W, x + w - inset_px)
|
| 174 |
+
y2 = min(H, y + h - inset_px)
|
| 175 |
+
if x2 <= x1 or y2 <= y1:
|
| 176 |
+
continue
|
| 177 |
+
crop = img[y1:y2, x1:x2].copy()
|
| 178 |
+
|
| 179 |
+
box = {
|
| 180 |
+
'coords': (x, y, w, h),
|
| 181 |
+
'image': crop,
|
| 182 |
+
'open_sides': open_sides,
|
| 183 |
+
'area_ratio': float(area_ratio),
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
boxes.append(box)
|
| 187 |
+
|
| 188 |
+
boxes.sort(key=lambda b: (b['coords'][1], b['coords'][0]))
|
| 189 |
+
return boxes, None
|
| 190 |
+
|
| 191 |
+
def ocr_text(self, image: np.ndarray, lang: str) -> str:
|
| 192 |
+
try:
|
| 193 |
+
txt = pytesseract.image_to_string(image, lang=lang)
|
| 194 |
+
except Exception:
|
| 195 |
+
txt = ""
|
| 196 |
+
return (txt or "").strip()
|
| 197 |
+
|
| 198 |
+
def classify_boxes_with_ocr(self, detections_by_page: List[List[Dict]], lang: str) -> None:
|
| 199 |
+
caption_re = re.compile(self.config['caption_regex'], re.IGNORECASE)
|
| 200 |
+
|
| 201 |
+
jobs = []
|
| 202 |
+
with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as ex:
|
| 203 |
+
for p_idx, page_boxes in enumerate(detections_by_page):
|
| 204 |
+
for b_idx, box in enumerate(page_boxes):
|
| 205 |
+
jobs.append(((p_idx, b_idx), ex.submit(self.ocr_text, box['image'], lang)))
|
| 206 |
+
|
| 207 |
+
for (p_idx, b_idx), fut in jobs:
|
| 208 |
+
text = fut.result() or ""
|
| 209 |
+
box = detections_by_page[p_idx][b_idx]
|
| 210 |
+
if caption_re.match(text):
|
| 211 |
+
box['type'] = 'caption'
|
| 212 |
+
box['text'] = text
|
| 213 |
+
else:
|
| 214 |
+
box['type'] = 'figure'
|
| 215 |
+
box['text'] = text
|
| 216 |
+
|
| 217 |
+
def stitch_split_figures(self, detections_by_page: List[List[Dict]]) -> List[Dict]:
|
| 218 |
+
# Mark boxes with IDs and stitch flags
|
| 219 |
+
for p_idx, page_boxes in enumerate(detections_by_page):
|
| 220 |
+
for b_idx, box in enumerate(page_boxes):
|
| 221 |
+
box['id'] = f"p{p_idx+1}_b{b_idx+1}"
|
| 222 |
+
box['used_for_stitch'] = False
|
| 223 |
+
|
| 224 |
+
figures: List[Dict] = []
|
| 225 |
+
|
| 226 |
+
for p_idx, page_boxes in enumerate(detections_by_page):
|
| 227 |
+
for b_idx, box in enumerate(page_boxes):
|
| 228 |
+
if box.get('type') == 'caption':
|
| 229 |
+
continue
|
| 230 |
+
if box['used_for_stitch']:
|
| 231 |
+
continue
|
| 232 |
+
|
| 233 |
+
cur_img = box['image']
|
| 234 |
+
cur_coords = box['coords']
|
| 235 |
+
pages = [p_idx]
|
| 236 |
+
bbox_refs = [(p_idx, b_idx)]
|
| 237 |
+
box['used_for_stitch'] = True
|
| 238 |
+
|
| 239 |
+
np_idx = p_idx + 1
|
| 240 |
+
candidate = None
|
| 241 |
+
if np_idx < len(detections_by_page):
|
| 242 |
+
for nb_idx, nb in enumerate(detections_by_page[np_idx]):
|
| 243 |
+
if nb.get('type') == 'caption' or nb['used_for_stitch']:
|
| 244 |
+
continue
|
| 245 |
+
x, y, w, h = cur_coords
|
| 246 |
+
nx, ny, nw, nh = nb['coords']
|
| 247 |
+
|
| 248 |
+
if abs(x - nx) < 50 and abs((x+w) - (nx+nw)) < 50:
|
| 249 |
+
candidate = (np_idx, nb_idx, nb, 'vertical')
|
| 250 |
+
break
|
| 251 |
+
if abs(y - ny) < 50 and abs((y+h) - (ny+nh)) < 50:
|
| 252 |
+
candidate = (np_idx, nb_idx, nb, 'horizontal')
|
| 253 |
+
break
|
| 254 |
+
|
| 255 |
+
if candidate:
|
| 256 |
+
np_idx, nb_idx, nb, stitch_type = candidate
|
| 257 |
+
nb['used_for_stitch'] = True
|
| 258 |
+
pages.append(np_idx)
|
| 259 |
+
bbox_refs.append((np_idx, nb_idx))
|
| 260 |
+
|
| 261 |
+
if stitch_type == 'vertical':
|
| 262 |
+
w_max = max(cur_img.shape[1], nb['image'].shape[1])
|
| 263 |
+
|
| 264 |
+
def pad_to_width(img, target_w):
|
| 265 |
+
pad_w = target_w - img.shape[1]
|
| 266 |
+
if pad_w <= 0:
|
| 267 |
+
return img
|
| 268 |
+
return np.pad(img, ((0,0),(0,pad_w),(0,0)),
|
| 269 |
+
mode="constant", constant_values=255)
|
| 270 |
+
|
| 271 |
+
cur_img = pad_to_width(cur_img, w_max)
|
| 272 |
+
nb_img = pad_to_width(nb['image'], w_max)
|
| 273 |
+
cur_img = np.vstack([cur_img, nb_img])
|
| 274 |
+
|
| 275 |
+
x1 = min(cur_coords[0], nb['coords'][0])
|
| 276 |
+
y1 = min(cur_coords[1], nb['coords'][1])
|
| 277 |
+
x2 = max(cur_coords[0]+cur_coords[2], nb['coords'][0]+nb['coords'][2])
|
| 278 |
+
y2 = max(cur_coords[1]+cur_coords[3], nb['coords'][1]+nb['coords'][3])
|
| 279 |
+
cur_coords = (x1, y1, x2-x1, y2-y1)
|
| 280 |
+
|
| 281 |
+
else: # horizontal
|
| 282 |
+
h_max = max(cur_img.shape[0], nb['image'].shape[0])
|
| 283 |
+
|
| 284 |
+
def pad_to_height(img, target_h):
|
| 285 |
+
pad_h = target_h - img.shape[0]
|
| 286 |
+
if pad_h <= 0:
|
| 287 |
+
return img
|
| 288 |
+
return np.pad(img, ((0,pad_h),(0,0),(0,0)),
|
| 289 |
+
mode="constant", constant_values=255)
|
| 290 |
+
|
| 291 |
+
cur_img = pad_to_height(cur_img, h_max)
|
| 292 |
+
nb_img = pad_to_height(nb['image'], h_max)
|
| 293 |
+
cur_img = np.hstack([cur_img, nb_img])
|
| 294 |
+
|
| 295 |
+
x1 = min(cur_coords[0], nb['coords'][0])
|
| 296 |
+
y1 = min(cur_coords[1], nb['coords'][1])
|
| 297 |
+
x2 = max(cur_coords[0]+cur_coords[2], nb['coords'][0]+nb['coords'][2])
|
| 298 |
+
y2 = max(cur_coords[1]+cur_coords[3], nb['coords'][1]+nb['coords'][3])
|
| 299 |
+
cur_coords = (x1, y1, x2-x1, y2-y1)
|
| 300 |
+
|
| 301 |
+
figures.append({
|
| 302 |
+
'id': f"f{len(figures)+1:03d}",
|
| 303 |
+
'pages': pages,
|
| 304 |
+
'image': cur_img,
|
| 305 |
+
'bbox_refs': bbox_refs,
|
| 306 |
+
'base_page': pages[0],
|
| 307 |
+
'coords_hint': cur_coords,
|
| 308 |
+
})
|
| 309 |
+
|
| 310 |
+
return figures
|
| 311 |
+
|
| 312 |
+
def pick_best_caption_for_figure(self, fig: Dict, detections_by_page: List[List[Dict]],
|
| 313 |
+
used_caption_ids: set) -> Optional[Tuple[int, int, Dict]]:
|
| 314 |
+
base_p = fig['base_page']
|
| 315 |
+
x, y, w, h = fig['coords_hint']
|
| 316 |
+
|
| 317 |
+
max_ahead = self.config['max_caption_search_pages_ahead']
|
| 318 |
+
candidates = []
|
| 319 |
+
for p in range(base_p, min(base_p + 1 + max_ahead, len(detections_by_page))):
|
| 320 |
+
for b_idx, box in enumerate(detections_by_page[p]):
|
| 321 |
+
if box.get('type') != 'caption':
|
| 322 |
+
continue
|
| 323 |
+
if box.get('caption_used_id'):
|
| 324 |
+
continue
|
| 325 |
+
bx, by, bw, bh = box['coords']
|
| 326 |
+
same_page = (p == base_p)
|
| 327 |
+
after_figure = (not same_page) or (by >= y)
|
| 328 |
+
if not after_figure:
|
| 329 |
+
continue
|
| 330 |
+
vdist = abs((by) - (y + h)) if same_page else 0
|
| 331 |
+
wdiff = abs(bw - w)
|
| 332 |
+
score = vdist + 0.5 * wdiff
|
| 333 |
+
candidates.append((score, p, b_idx, box))
|
| 334 |
+
|
| 335 |
+
if not candidates:
|
| 336 |
+
return None
|
| 337 |
+
candidates.sort(key=lambda t: t[0])
|
| 338 |
+
for _, p, b_idx, box in candidates:
|
| 339 |
+
box_id = (p, b_idx)
|
| 340 |
+
if box_id not in used_caption_ids:
|
| 341 |
+
return (p, b_idx, box)
|
| 342 |
+
return None
|
| 343 |
+
|
| 344 |
+
def rotate_if_needed(self, img: np.ndarray) -> np.ndarray:
|
| 345 |
+
if not self.config['rotate_on_demand']:
|
| 346 |
+
return img
|
| 347 |
+
h, w = img.shape[:2]
|
| 348 |
+
if h > w * 1.2:
|
| 349 |
+
return cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
|
| 350 |
+
return img
|
| 351 |
+
|
| 352 |
+
def save_results(self, figures: List[Dict], detections_by_page: List[List[Dict]], out_dir: str) -> None:
|
| 353 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 354 |
+
used_captions = set()
|
| 355 |
+
saved = 0
|
| 356 |
+
|
| 357 |
+
for fig in figures:
|
| 358 |
+
cap = self.pick_best_caption_for_figure(fig, detections_by_page, used_captions)
|
| 359 |
+
if cap is not None:
|
| 360 |
+
p, b_idx, cap_box = cap
|
| 361 |
+
used_captions.add((p, b_idx))
|
| 362 |
+
fig_img = fig['image']
|
| 363 |
+
cap_img = cap_box['image']
|
| 364 |
+
if cap_img.shape[1] != fig_img.shape[1]:
|
| 365 |
+
new_h = int(cap_img.shape[0] * (fig_img.shape[1] / cap_img.shape[1]))
|
| 366 |
+
cap_img = cv2.resize(cap_img, (fig_img.shape[1], new_h))
|
| 367 |
+
stitched = cv2.vconcat([fig_img, cap_img])
|
| 368 |
+
stitched = self.rotate_if_needed(stitched)
|
| 369 |
+
fname = f"figure_with_caption_{fig['id']}.png"
|
| 370 |
+
cv2.imwrite(os.path.join(out_dir, fname), stitched)
|
| 371 |
+
saved += 1
|
| 372 |
+
else:
|
| 373 |
+
fig_img = self.rotate_if_needed(fig['image'])
|
| 374 |
+
fname = f"figure_{fig['id']}.png"
|
| 375 |
+
cv2.imwrite(os.path.join(out_dir, fname), fig_img)
|
| 376 |
+
saved += 1
|
| 377 |
+
|
| 378 |
+
cap_count = 0
|
| 379 |
+
for p_idx, page_boxes in enumerate(detections_by_page):
|
| 380 |
+
for b_idx, box in enumerate(page_boxes):
|
| 381 |
+
if box.get('type') == 'caption' and (p_idx, b_idx) not in used_captions:
|
| 382 |
+
cap_count += 1
|
| 383 |
+
cv2.imwrite(os.path.join(out_dir, f"standalone_caption_{cap_count:03d}.png"), box['image'])
|
| 384 |
+
|
| 385 |
+
if hasattr(self, 'progress_callback'):
|
| 386 |
+
self.progress_callback(f"Saved {saved} figure image(s) (+ any standalone captions) to: {out_dir}")
|
| 387 |
+
|
| 388 |
+
def main():
|
| 389 |
+
st.set_page_config(
|
| 390 |
+
page_title="PDF Figure Extractor",
|
| 391 |
+
page_icon="📄",
|
| 392 |
+
layout="wide"
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
# Custom CSS for better styling
|
| 396 |
+
st.markdown("""
|
| 397 |
+
<style>
|
| 398 |
+
.main-title {
|
| 399 |
+
font-size: 2.5rem;
|
| 400 |
+
font-weight: bold;
|
| 401 |
+
color: #1f77b4;
|
| 402 |
+
text-align: center;
|
| 403 |
+
margin-bottom: 2rem;
|
| 404 |
+
}
|
| 405 |
+
.section-title {
|
| 406 |
+
font-size: 1.5rem;
|
| 407 |
+
font-weight: bold;
|
| 408 |
+
margin-top: 1.5rem;
|
| 409 |
+
margin-bottom: 1rem;
|
| 410 |
+
}
|
| 411 |
+
.success-box {
|
| 412 |
+
padding: 1rem;
|
| 413 |
+
background-color: #d4edda;
|
| 414 |
+
border-left: 5px solid #28a745;
|
| 415 |
+
margin: 1rem 0;
|
| 416 |
+
}
|
| 417 |
+
.error-box {
|
| 418 |
+
padding: 1rem;
|
| 419 |
+
background-color: #f8d7da;
|
| 420 |
+
border-left: 5px solid #dc3545;
|
| 421 |
+
margin: 1rem 0;
|
| 422 |
+
}
|
| 423 |
+
.info-box {
|
| 424 |
+
padding: 1rem;
|
| 425 |
+
background-color: #d1ecf1;
|
| 426 |
+
border-left: 5px solid #17a2b8;
|
| 427 |
+
margin: 1rem 0;
|
| 428 |
+
}
|
| 429 |
+
</style>
|
| 430 |
+
""", unsafe_allow_html=True)
|
| 431 |
+
|
| 432 |
+
# Title
|
| 433 |
+
st.markdown('<h1 class="main-title">📄 PDF Figure Extractor</h1>', unsafe_allow_html=True)
|
| 434 |
+
st.markdown("---")
|
| 435 |
+
|
| 436 |
+
# Initialize extractor in session state
|
| 437 |
+
if 'extractor' not in st.session_state:
|
| 438 |
+
st.session_state.extractor = PDFExtractor()
|
| 439 |
+
tesseract_found = st.session_state.extractor.setup_tesseract()
|
| 440 |
+
if not tesseract_found:
|
| 441 |
+
st.info("ℹ️ **Tesseract OCR not detected.** "
|
| 442 |
+
"Caption detection will be limited. "
|
| 443 |
+
"For local development, install Tesseract from: "
|
| 444 |
+
"https://github.com/UB-Mannheim/tesseract/wiki")
|
| 445 |
+
|
| 446 |
+
# Sidebar for settings
|
| 447 |
+
with st.sidebar:
|
| 448 |
+
st.header("⚙️ Settings")
|
| 449 |
+
|
| 450 |
+
dpi = st.slider(
|
| 451 |
+
"Image Quality (DPI)",
|
| 452 |
+
min_value=150,
|
| 453 |
+
max_value=600,
|
| 454 |
+
value=400,
|
| 455 |
+
step=50,
|
| 456 |
+
help="Higher DPI means better quality but slower processing"
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
rotate_images = st.checkbox(
|
| 460 |
+
"Auto-rotate tall images",
|
| 461 |
+
value=False,
|
| 462 |
+
help="Automatically rotate images that are taller than they are wide"
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
st.markdown("---")
|
| 466 |
+
st.markdown("### About")
|
| 467 |
+
st.markdown("""
|
| 468 |
+
This tool extracts figures and captions from PDF files using:
|
| 469 |
+
- **Computer Vision** for figure detection
|
| 470 |
+
- **OCR** for caption recognition
|
| 471 |
+
- **Smart Stitching** for multi-page figures
|
| 472 |
+
""")
|
| 473 |
+
|
| 474 |
+
# Main content
|
| 475 |
+
col1, col2 = st.columns([2, 1])
|
| 476 |
+
|
| 477 |
+
with col1:
|
| 478 |
+
st.markdown('<h3 class="section-title">1️⃣ Upload PDF Files</h3>', unsafe_allow_html=True)
|
| 479 |
+
uploaded_files = st.file_uploader(
|
| 480 |
+
"Choose PDF files",
|
| 481 |
+
type=['pdf'],
|
| 482 |
+
accept_multiple_files=True,
|
| 483 |
+
help="Select one or more PDF files to extract figures from"
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
if uploaded_files:
|
| 487 |
+
st.success(f"✅ {len(uploaded_files)} PDF file(s) selected")
|
| 488 |
+
for i, file in enumerate(uploaded_files, 1):
|
| 489 |
+
st.text(f" {i}. {file.name}")
|
| 490 |
+
else:
|
| 491 |
+
# Show welcome message when no files uploaded
|
| 492 |
+
st.info("""
|
| 493 |
+
👋 **Welcome!** Upload your PDF files to get started.
|
| 494 |
+
|
| 495 |
+
This tool will:
|
| 496 |
+
- 🔍 Detect figures, charts, and diagrams
|
| 497 |
+
- 📝 Extract and match captions
|
| 498 |
+
- 🔄 Stitch multi-page figures
|
| 499 |
+
- 💾 Package everything for easy download
|
| 500 |
+
""")
|
| 501 |
+
|
| 502 |
+
with col2:
|
| 503 |
+
st.markdown('<h3 class="section-title">2️⃣ Process</h3>', unsafe_allow_html=True)
|
| 504 |
+
|
| 505 |
+
process_button = st.button(
|
| 506 |
+
"🚀 Extract Figures",
|
| 507 |
+
type="primary",
|
| 508 |
+
disabled=not uploaded_files,
|
| 509 |
+
use_container_width=True
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
# Processing section
|
| 513 |
+
if process_button and uploaded_files:
|
| 514 |
+
st.markdown("---")
|
| 515 |
+
st.markdown('<h3 class="section-title">📊 Processing Status</h3>', unsafe_allow_html=True)
|
| 516 |
+
|
| 517 |
+
# Update config
|
| 518 |
+
st.session_state.extractor.config['dpi'] = dpi
|
| 519 |
+
st.session_state.extractor.config['rotate_on_demand'] = rotate_images
|
| 520 |
+
|
| 521 |
+
# Progress tracking
|
| 522 |
+
progress_bar = st.progress(0)
|
| 523 |
+
status_text = st.empty()
|
| 524 |
+
|
| 525 |
+
def log_callback(message):
|
| 526 |
+
pass # Silent processing
|
| 527 |
+
|
| 528 |
+
st.session_state.extractor.progress_callback = log_callback
|
| 529 |
+
|
| 530 |
+
# Create temporary directory for output
|
| 531 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 532 |
+
total_files = len(uploaded_files)
|
| 533 |
+
all_results = []
|
| 534 |
+
|
| 535 |
+
for i, uploaded_file in enumerate(uploaded_files):
|
| 536 |
+
# Update progress
|
| 537 |
+
progress = i / total_files
|
| 538 |
+
progress_bar.progress(progress)
|
| 539 |
+
status_text.markdown(f"**Processing:** {uploaded_file.name} ({i+1}/{total_files})")
|
| 540 |
+
|
| 541 |
+
# Save uploaded file temporarily
|
| 542 |
+
temp_pdf_path = os.path.join(temp_dir, uploaded_file.name)
|
| 543 |
+
with open(temp_pdf_path, 'wb') as f:
|
| 544 |
+
f.write(uploaded_file.getbuffer())
|
| 545 |
+
|
| 546 |
+
# Create output directory for this PDF
|
| 547 |
+
pdf_name = os.path.splitext(uploaded_file.name)[0]
|
| 548 |
+
out_dir = os.path.join(temp_dir, pdf_name)
|
| 549 |
+
|
| 550 |
+
try:
|
| 551 |
+
st.session_state.extractor.process_single_pdf(temp_pdf_path, out_dir)
|
| 552 |
+
|
| 553 |
+
# Collect results
|
| 554 |
+
if os.path.exists(out_dir):
|
| 555 |
+
for filename in os.listdir(out_dir):
|
| 556 |
+
if filename.endswith('.png'):
|
| 557 |
+
filepath = os.path.join(out_dir, filename)
|
| 558 |
+
all_results.append((pdf_name, filename, filepath))
|
| 559 |
+
|
| 560 |
+
except Exception as e:
|
| 561 |
+
st.error(f"Error processing {uploaded_file.name}: {str(e)}")
|
| 562 |
+
|
| 563 |
+
# Complete progress
|
| 564 |
+
progress_bar.progress(1.0)
|
| 565 |
+
status_text.markdown("**✅ Processing completed!**")
|
| 566 |
+
|
| 567 |
+
# Display results
|
| 568 |
+
if all_results:
|
| 569 |
+
st.markdown("---")
|
| 570 |
+
st.markdown('<h3 class="section-title">🎉 Extraction Results</h3>', unsafe_allow_html=True)
|
| 571 |
+
st.success(f"Successfully extracted {len(all_results)} figure(s) from {total_files} PDF(s)")
|
| 572 |
+
|
| 573 |
+
# Group by PDF
|
| 574 |
+
results_by_pdf = {}
|
| 575 |
+
for pdf_name, filename, filepath in all_results:
|
| 576 |
+
if pdf_name not in results_by_pdf:
|
| 577 |
+
results_by_pdf[pdf_name] = []
|
| 578 |
+
results_by_pdf[pdf_name].append((filename, filepath))
|
| 579 |
+
|
| 580 |
+
# Display results by PDF with auto-expanded previews
|
| 581 |
+
for pdf_name, files in results_by_pdf.items():
|
| 582 |
+
st.markdown(f"### 📄 {pdf_name} ({len(files)} figures)")
|
| 583 |
+
|
| 584 |
+
# Display images in columns
|
| 585 |
+
cols = st.columns(3)
|
| 586 |
+
for idx, (filename, filepath) in enumerate(files):
|
| 587 |
+
with cols[idx % 3]:
|
| 588 |
+
st.image(filepath, caption=filename, use_container_width=True)
|
| 589 |
+
|
| 590 |
+
# Create download button for all results (placed after previews)
|
| 591 |
+
st.markdown("---")
|
| 592 |
+
zip_buffer = io.BytesIO()
|
| 593 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 594 |
+
for pdf_name, filename, filepath in all_results:
|
| 595 |
+
arcname = f"{pdf_name}/{filename}"
|
| 596 |
+
zip_file.write(filepath, arcname)
|
| 597 |
+
|
| 598 |
+
zip_buffer.seek(0)
|
| 599 |
+
st.download_button(
|
| 600 |
+
label="📥 Download All Figures (ZIP)",
|
| 601 |
+
data=zip_buffer,
|
| 602 |
+
file_name="extracted_figures.zip",
|
| 603 |
+
mime="application/zip",
|
| 604 |
+
use_container_width=True,
|
| 605 |
+
type="primary"
|
| 606 |
+
)
|
| 607 |
+
else:
|
| 608 |
+
st.warning("No figures were extracted. The PDFs may not contain detectable figures.")
|
| 609 |
+
|
| 610 |
+
# Footer
|
| 611 |
+
st.markdown("---")
|
| 612 |
+
st.markdown(
|
| 613 |
+
"""
|
| 614 |
+
<div style='text-align: center; color: #666; padding: 2rem 0;'>
|
| 615 |
+
<p>Made with ❤️ using Streamlit |
|
| 616 |
+
<a href='https://github.com' target='_blank'>GitHub</a> |
|
| 617 |
+
Need help? Check the processing log for details</p>
|
| 618 |
+
</div>
|
| 619 |
+
""",
|
| 620 |
+
unsafe_allow_html=True
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
if __name__ == "__main__":
|
| 624 |
+
main()
|
pyproject.toml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "pdf-minor-allegations"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Add your description here"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.12"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"doclayout-yolo>=0.0.4",
|
| 9 |
+
"huggingface-hub>=1.1.2",
|
| 10 |
+
"loguru>=0.7.3",
|
| 11 |
+
"pillow>=12.0.0",
|
| 12 |
+
"pymupdf>=1.26.6",
|
| 13 |
+
"pymupdf-layout>=0.0.15",
|
| 14 |
+
"pypdfium2>=5.0.0",
|
| 15 |
+
"pymupdf4llm>=0.1.9",
|
| 16 |
+
"flask>=3.0.0",
|
| 17 |
+
"werkzeug>=3.0.0",
|
| 18 |
+
"torch>=2.0.0",
|
| 19 |
+
"torchvision>=0.15.0",
|
| 20 |
+
]
|
run_flask_gpu.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
Startup script that ensures CUDA PyTorch is installed before running Flask app.
|
| 4 |
+
"""
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
def ensure_cuda_torch():
|
| 10 |
+
"""Ensure CUDA-enabled PyTorch is installed."""
|
| 11 |
+
try:
|
| 12 |
+
import torch
|
| 13 |
+
if torch.cuda.is_available():
|
| 14 |
+
print(f"✓ CUDA available: {torch.cuda.get_device_name(0)}")
|
| 15 |
+
return True
|
| 16 |
+
else:
|
| 17 |
+
print("⚠ CUDA not available in current PyTorch installation")
|
| 18 |
+
print("Installing CUDA-enabled PyTorch...")
|
| 19 |
+
subprocess.run([
|
| 20 |
+
sys.executable, "-m", "pip", "install",
|
| 21 |
+
"torch", "torchvision",
|
| 22 |
+
"--index-url", "https://download.pytorch.org/whl/cu121",
|
| 23 |
+
"--upgrade"
|
| 24 |
+
], check=True)
|
| 25 |
+
# Re-import to check
|
| 26 |
+
import importlib
|
| 27 |
+
importlib.reload(torch)
|
| 28 |
+
if torch.cuda.is_available():
|
| 29 |
+
print(f"✓ CUDA now available: {torch.cuda.get_device_name(0)}")
|
| 30 |
+
return True
|
| 31 |
+
else:
|
| 32 |
+
print("⚠ Still no CUDA after installation. Using CPU mode.")
|
| 33 |
+
return False
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print(f"Error checking CUDA: {e}")
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
if __name__ == '__main__':
|
| 39 |
+
print("Checking GPU availability...")
|
| 40 |
+
ensure_cuda_torch()
|
| 41 |
+
|
| 42 |
+
print("\nStarting PDF Layout Extractor Flask App...")
|
| 43 |
+
print("Open your browser to http://localhost:5000\n")
|
| 44 |
+
|
| 45 |
+
from app import app
|
| 46 |
+
# Disable reloader to avoid environment discrepancies in child process
|
| 47 |
+
app.run(debug=False, use_reloader=False, host='0.0.0.0', port=5000)
|
| 48 |
+
|
static/css/styles.css
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/[email protected]/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/[email protected]/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 |
+
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|