Engines API Reference¶
Complete API documentation for Doctra engines.
DocResEngine¶
Image restoration engine for document enhancement.
doctra.engines.image_restoration.DocResEngine
¶
DocRes Image Restoration Engine
A wrapper around DocRes inference functionality for easy integration with Doctra's document processing pipeline.
Source code in doctra/engines/image_restoration/docres_engine.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
|
__init__(device=None, use_half_precision=True, model_path=None, mbd_path=None)
¶
Initialize DocRes Engine
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
Optional[str]
|
Device to run on ('cuda', 'cpu', or None for auto-detect) |
None
|
use_half_precision
|
bool
|
Whether to use half precision for inference |
True
|
model_path
|
Optional[str]
|
Path to DocRes model checkpoint (optional, defaults to Hugging Face Hub) |
None
|
mbd_path
|
Optional[str]
|
Path to MBD model checkpoint (optional, defaults to Hugging Face Hub) |
None
|
Source code in doctra/engines/image_restoration/docres_engine.py
batch_restore(images, task='appearance', save_prompts=False)
¶
Restore multiple images in batch
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
List[Union[str, ndarray]]
|
List of image paths or numpy arrays |
required |
task
|
str
|
Restoration task to perform |
'appearance'
|
save_prompts
|
bool
|
Whether to save intermediate prompts |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[Optional[ndarray], Dict[str, Any]]]
|
List of (restored_image, metadata) tuples |
Source code in doctra/engines/image_restoration/docres_engine.py
get_supported_tasks()
¶
is_available()
¶
restore_image(image, task='appearance', save_prompts=False)
¶
Restore a single image using DocRes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
Union[str, ndarray]
|
Path to image file or numpy array |
required |
task
|
str
|
Restoration task to perform |
'appearance'
|
save_prompts
|
bool
|
Whether to save intermediate prompts |
False
|
Returns:
Type | Description |
---|---|
Tuple[ndarray, Dict[str, Any]]
|
Tuple of (restored_image, metadata) |
Source code in doctra/engines/image_restoration/docres_engine.py
restore_pdf(pdf_path, output_path=None, task='appearance', dpi=200)
¶
Restore an entire PDF document using DocRes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pdf_path
|
str
|
Path to the input PDF file |
required |
output_path
|
str | None
|
Path for the enhanced PDF (if None, auto-generates) |
None
|
task
|
str
|
DocRes restoration task (default: "appearance") |
'appearance'
|
dpi
|
int
|
DPI for PDF rendering (default: 200) |
200
|
Returns:
Type | Description |
---|---|
str | None
|
Path to the enhanced PDF or None if failed |
Source code in doctra/engines/image_restoration/docres_engine.py
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
|
Quick Reference¶
DocResEngine¶
from doctra import DocResEngine
# Initialize engine
engine = DocResEngine(
device: str = None, # "cuda", "cpu", or None for auto-detect
use_half_precision: bool = False,
model_path: str = None,
mbd_path: str = None
)
# Restore single image
restored_img, metadata = engine.restore_image(
image: Union[str, np.ndarray, PIL.Image.Image],
task: str = "appearance"
)
# Restore PDF
output_path = engine.restore_pdf(
pdf_path: str,
output_path: str = None,
task: str = "appearance",
dpi: int = 200
)
Parameter Reference¶
Initialization Parameters¶
Parameter | Type | Default | Description |
---|---|---|---|
device |
str | None | Processing device: "cuda", "cpu", or None (auto-detect) |
use_half_precision |
bool | False | Use FP16 for faster GPU processing |
model_path |
str | None | Custom path to restoration model |
mbd_path |
str | None | Custom path to MBD model |
Restoration Tasks¶
Task | Description | Use Case |
---|---|---|
"appearance" |
General appearance enhancement | Most documents (default) |
"dewarping" |
Correct perspective distortion | Scanned with perspective issues |
"deshadowing" |
Remove shadows and lighting artifacts | Poor lighting conditions |
"deblurring" |
Reduce blur and improve sharpness | Motion blur, focus issues |
"binarization" |
Convert to black and white | Clean text extraction |
"end2end" |
Complete restoration pipeline | Severely degraded documents |
Methods¶
restore_image()¶
Restore a single image.
Parameters:
image
(str | np.ndarray | PIL.Image.Image): Input image (path, numpy array, or PIL Image)task
(str): Restoration task to perform
Returns:
restored_img
(PIL.Image.Image): Restored imagemetadata
(dict): Processing metadata including task, device, and timing
Example:
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
restored, meta = engine.restore_image("blurry.jpg", task="deblurring")
print(f"Task: {meta['task']}")
print(f"Device: {meta['device']}")
print(f"Time: {meta['processing_time']:.2f}s")
# Save restored image
restored.save("restored.jpg")
restore_pdf()¶
Restore all pages in a PDF document.
Parameters:
pdf_path
(str): Path to input PDFoutput_path
(str, optional): Path for output PDF (auto-generated if None)task
(str): Restoration task to performdpi
(int): Resolution for processing
Returns:
output_path
(str): Path to the restored PDF
Example:
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
restored_pdf = engine.restore_pdf(
pdf_path="low_quality.pdf",
output_path="enhanced.pdf",
task="appearance",
dpi=300
)
print(f"Restored PDF saved to: {restored_pdf}")
Device Selection¶
Auto-Detection¶
Explicit GPU¶
Explicit CPU¶
Check Device¶
import torch
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"GPU: {torch.cuda.get_device_name(0)}")
Performance Optimization¶
Half Precision¶
Use FP16 for ~2x speed on modern GPUs:
Requirements: - NVIDIA GPU with compute capability 7.0+ (Volta or newer) - Examples: RTX 20xx, RTX 30xx, RTX 40xx, A100, V100
Batch Processing¶
Process multiple images efficiently:
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
# Process image list
images = ["doc1.jpg", "doc2.jpg", "doc3.jpg"]
restored_images = []
for img_path in images:
restored, _ = engine.restore_image(img_path, task="appearance")
restored_images.append(restored)
restored.save(f"restored_{img_path}")
DPI Considerations¶
DPI | Quality | Speed | Memory | Best For |
---|---|---|---|---|
100 | Low | Fast | Low | Quick previews |
150 | Medium | Medium | Medium | General use |
200 | Good | Slow | Medium | Default setting |
300 | High | Very Slow | High | High-quality scans |
Metadata¶
The restore_image()
method returns metadata:
restored, metadata = engine.restore_image("doc.jpg", "appearance")
print(metadata)
# {
# 'task': 'appearance',
# 'device': 'cuda',
# 'processing_time': 1.23,
# 'input_size': (1920, 1080),
# 'output_size': (1920, 1080)
# }
Error Handling¶
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
try:
restored, meta = engine.restore_image("document.jpg", "appearance")
except FileNotFoundError:
print("Image not found")
except RuntimeError as e:
print(f"CUDA error: {e}")
# Fall back to CPU
engine = DocResEngine(device="cpu")
restored, meta = engine.restore_image("document.jpg", "appearance")
except Exception as e:
print(f"Unexpected error: {e}")
Integration with Parsers¶
DocResEngine is integrated into EnhancedPDFParser:
from doctra import EnhancedPDFParser
# This internally uses DocResEngine
parser = EnhancedPDFParser(
use_image_restoration=True,
restoration_task="appearance",
restoration_device="cuda"
)
parser.parse("document.pdf")
For standalone restoration:
from doctra import DocResEngine
# Step 1: Restore PDF
engine = DocResEngine(device="cuda")
enhanced_pdf = engine.restore_pdf(
pdf_path="low_quality.pdf",
output_path="enhanced.pdf",
task="appearance"
)
# Step 2: Parse enhanced PDF
from doctra import StructuredPDFParser
parser = StructuredPDFParser()
parser.parse(enhanced_pdf)
Examples¶
Example 1: Dewarp Scanned Document¶
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
# Fix perspective distortion
restored, meta = engine.restore_image(
"scanned_with_distortion.jpg",
task="dewarping"
)
restored.save("dewarped.jpg")
print(f"Processed in {meta['processing_time']:.2f}s")
Example 2: Remove Shadows¶
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
# Remove shadow artifacts
restored, meta = engine.restore_image(
"document_with_shadows.jpg",
task="deshadowing"
)
restored.save("no_shadows.jpg")
Example 3: Batch PDF Restoration¶
import os
from doctra import DocResEngine
engine = DocResEngine(device="cuda", use_half_precision=True)
pdf_dir = "input_pdfs"
output_dir = "restored_pdfs"
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(pdf_dir):
if filename.endswith(".pdf"):
input_path = os.path.join(pdf_dir, filename)
output_path = os.path.join(output_dir, f"restored_{filename}")
print(f"Processing {filename}...")
engine.restore_pdf(
pdf_path=input_path,
output_path=output_path,
task="appearance",
dpi=200
)
See Also¶
- Enhanced Parser - Using restoration with parsing
- Core Concepts - Understanding image restoration
- Examples - Advanced usage patterns