引擎 API 参考¶
Doctra 引擎的完整 API 文档。
DocResEngine¶
用于文档增强的图像恢复引擎。
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
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 562 563 564 565 566 | |
__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
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 562 563 564 565 566 | |
快速参考¶
DocResEngine¶
from doctra import DocResEngine
# 初始化引擎
engine = DocResEngine(
device: str = None, # "cuda"、"cpu" 或 None 自动检测
use_half_precision: bool = False,
model_path: str = None,
mbd_path: str = None
)
# 恢复单个图像
restored_img, metadata = engine.restore_image(
image: Union[str, np.ndarray, PIL.Image.Image],
task: str = "appearance"
)
# 恢复 PDF
output_path = engine.restore_pdf(
pdf_path: str,
output_path: str = None,
task: str = "appearance",
dpi: int = 200
)
参数参考¶
初始化参数¶
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
device |
str | None | 处理设备:"cuda"、"cpu" 或 None(自动检测) |
use_half_precision |
bool | False | 使用 FP16 以加快 GPU 处理速度 |
model_path |
str | None | 恢复模型的自定义路径 |
mbd_path |
str | None | MBD 模型的自定义路径 |
恢复任务¶
| 任务 | 描述 | 用例 |
|---|---|---|
"appearance" |
一般外观增强 | 大多数文档(默认) |
"dewarping" |
校正透视失真 | 有透视问题的扫描文档 |
"deshadowing" |
去除阴影和光照伪影 | 光照条件差 |
"deblurring" |
减少模糊并提高清晰度 | 运动模糊、对焦问题 |
"binarization" |
转换为黑白 | 干净的文本提取 |
"end2end" |
完整的恢复流程 | 严重退化的文档 |
方法¶
restore_image()¶
恢复单个图像。
参数:
image(str | np.ndarray | PIL.Image.Image):输入图像(路径、numpy 数组或 PIL 图像)task(str):要执行的恢复任务
返回:
restored_img(PIL.Image.Image):恢复的图像metadata(dict):处理元数据,包括任务、设备和时间
示例:
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
restored, meta = engine.restore_image("blurry.jpg", task="deblurring")
print(f"任务:{meta['task']}")
print(f"设备:{meta['device']}")
print(f"时间:{meta['processing_time']:.2f}秒")
# 保存恢复的图像
restored.save("restored.jpg")
restore_pdf()¶
恢复 PDF 文档中的所有页面。
参数:
pdf_path(str):输入 PDF 的路径output_path(str, 可选):输出 PDF 的路径(如果为 None 则自动生成)task(str):要执行的恢复任务dpi(int):处理的分辨率
返回:
output_path(str):恢复的 PDF 的路径
示例:
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"恢复的 PDF 已保存到:{restored_pdf}")
设备选择¶
自动检测¶
显式 GPU¶
显式 CPU¶
检查设备¶
import torch
print(f"CUDA 可用:{torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"GPU:{torch.cuda.get_device_name(0)}")
性能优化¶
半精度¶
在现代 GPU 上使用 FP16 可获得约 2 倍速度:
要求: - 计算能力 7.0+ 的 NVIDIA GPU(Volta 或更新版本) - 示例:RTX 20xx、RTX 30xx、RTX 40xx、A100、V100
批量处理¶
高效处理多个图像:
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
# 处理图像列表
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 考虑¶
| DPI | 质量 | 速度 | 内存 | 最适合 |
|---|---|---|---|---|
| 100 | 低 | 快 | 低 | 快速预览 |
| 150 | 中 | 中 | 中 | 一般用途 |
| 200 | 好 | 慢 | 中 | 默认设置 |
| 300 | 高 | 非常慢 | 高 | 高质量扫描 |
元数据¶
restore_image() 方法返回元数据:
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)
# }
错误处理¶
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
try:
restored, meta = engine.restore_image("document.jpg", "appearance")
except FileNotFoundError:
print("未找到图像")
except RuntimeError as e:
print(f"CUDA 错误:{e}")
# 回退到 CPU
engine = DocResEngine(device="cpu")
restored, meta = engine.restore_image("document.jpg", "appearance")
except Exception as e:
print(f"意外错误:{e}")
与解析器集成¶
DocResEngine 已集成到 EnhancedPDFParser 中:
from doctra import EnhancedPDFParser
# 这内部使用 DocResEngine
parser = EnhancedPDFParser(
use_image_restoration=True,
restoration_task="appearance",
restoration_device="cuda"
)
parser.parse("document.pdf")
对于独立恢复:
from doctra import DocResEngine
# 步骤 1:恢复 PDF
engine = DocResEngine(device="cuda")
enhanced_pdf = engine.restore_pdf(
pdf_path="low_quality.pdf",
output_path="enhanced.pdf",
task="appearance"
)
# 步骤 2:解析增强的 PDF
from doctra import StructuredPDFParser
parser = StructuredPDFParser()
parser.parse(enhanced_pdf)
示例¶
示例 1:去扭曲扫描文档¶
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
# 修复透视失真
restored, meta = engine.restore_image(
"scanned_with_distortion.jpg",
task="dewarping"
)
restored.save("dewarped.jpg")
print(f"处理时间:{meta['processing_time']:.2f}秒")
示例 2:去除阴影¶
from doctra import DocResEngine
engine = DocResEngine(device="cuda")
# 去除阴影伪影
restored, meta = engine.restore_image(
"document_with_shadows.jpg",
task="deshadowing"
)
restored.save("no_shadows.jpg")
示例 3:批量 PDF 恢复¶
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"处理 {filename}...")
engine.restore_pdf(
pdf_path=input_path,
output_path=output_path,
task="appearance",
dpi=200
)