mirror of
https://github.com/PaddlePaddle/PaddleOCR.git
synced 2026-11-25 17:29:39 +08:00
refactor(langchain-paddleocr): migrate from HTTP API to PaddleOCR SDK (#18130)
* refactor(langchain-paddleocr): migrate from HTTP API to PaddleOCR SDK * refactor(langchain-paddleocr): update dependencies * refactor(langchain-paddleocr): update unit tests * refactor(langchain-paddleocr): update integration tests * style: fix ruff lint and format * style: fix ruff format for integration test * fix: keep default False for use_doc_orientation_classify and use_doc_unwarping
This commit is contained in:
1 parent
6a8b8f1e32
commit
35a3e07f8f
4 files changed
+137
-305
No files matched your search
@@ -1,116 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Iterable, Iterator
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from typing import Any
|
||||
|
||||
# Bypass model source check to save import time
|
||||
os.environ["PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK"] = "false"
|
||||
|
||||
import requests
|
||||
from langchain_core.document_loaders import BaseLoader
|
||||
from langchain_core.documents import Document
|
||||
from paddlex.inference.serving.schemas.paddleocr_vl import (
|
||||
InferRequest as PaddleOCRVLInferRequest,
|
||||
)
|
||||
from paddlex.inference.serving.schemas.paddleocr_vl import (
|
||||
InferResult as PaddleOCRVLInferResult,
|
||||
)
|
||||
from paddlex.inference.serving.schemas.shared.ocr import (
|
||||
FileType,
|
||||
)
|
||||
from pydantic import SecretStr
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
FileTypeInput = Literal["pdf", "image"] | None
|
||||
|
||||
_IMAGE_EXTENSIONS = {
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".bmp",
|
||||
".tiff",
|
||||
".tif",
|
||||
".webp",
|
||||
}
|
||||
|
||||
_PDF_EXTENSIONS = {".pdf"}
|
||||
_DEFAULT_BASE_URL = "https://paddleocr.aistudio-app.com"
|
||||
|
||||
_PAGES_DELIMITER = "\n\f"
|
||||
|
||||
|
||||
def _snake_to_camel(name: str) -> str:
|
||||
"""Convert snake_case to camelCase."""
|
||||
if not name:
|
||||
return name
|
||||
parts = name.split("_")
|
||||
if len(parts) == 1:
|
||||
return name
|
||||
return parts[0] + "".join(part.capitalize() for part in parts[1:])
|
||||
|
||||
|
||||
def _snake_keys_to_camel(params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Convert a dict with snake_case keys to camelCase, keeping only non-None
|
||||
values."""
|
||||
return {
|
||||
_snake_to_camel(key): value
|
||||
for key, value in params.items()
|
||||
if value is not None
|
||||
}
|
||||
|
||||
|
||||
def _normalize_file_type(file_type: FileTypeInput) -> FileType | None:
|
||||
"""Normalize file type to the numeric format required by the API."""
|
||||
if file_type is None:
|
||||
return None
|
||||
if isinstance(file_type, str):
|
||||
lower = file_type.lower()
|
||||
if lower == "pdf":
|
||||
return 0
|
||||
if lower == "image":
|
||||
return 1
|
||||
msg = f"Invalid `file_type` string: {file_type}. Must be 'pdf' or 'image'."
|
||||
raise ValueError(msg)
|
||||
msg = f"Invalid `file_type` value: {file_type}. Must be 'pdf', 'image', or `None`."
|
||||
raise ValueError(msg)
|
||||
|
||||
|
||||
def _infer_file_type_from_path(path: Path) -> FileType | None:
|
||||
"""
|
||||
Infer file type (PDF or image) from file extension.
|
||||
|
||||
Returns:
|
||||
0 for PDF, 1 for image, or None if the type cannot be determined.
|
||||
"""
|
||||
suffix = path.suffix.lower()
|
||||
if suffix in _PDF_EXTENSIONS:
|
||||
return 0
|
||||
if suffix in _IMAGE_EXTENSIONS:
|
||||
return 1
|
||||
return None
|
||||
|
||||
|
||||
class PaddleOCRVLLoader(BaseLoader):
|
||||
"""Load documents using the PaddleOCR-VL document parsing API."""
|
||||
"""Load documents using the PaddleOCR-VL document parsing API via SDK."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
file_path: str | Iterable[str],
|
||||
*,
|
||||
api_url: str,
|
||||
access_token: SecretStr | None = None,
|
||||
file_type: FileTypeInput = None,
|
||||
base_url: str | None = None,
|
||||
use_doc_orientation_classify: bool | None = False,
|
||||
use_doc_unwarping: bool | None = False,
|
||||
use_layout_detection: bool | None = None,
|
||||
use_chart_recognition: bool | None = None,
|
||||
use_seal_recognition: bool | None = None,
|
||||
use_ocr_for_image_block: bool | None = None,
|
||||
layout_threshold: float | dict[int, float] | None = None,
|
||||
layout_nms: bool | None = None,
|
||||
layout_unclip_ratio: (
|
||||
@@ -119,7 +39,6 @@ class PaddleOCRVLLoader(BaseLoader):
|
||||
layout_merge_bboxes_mode: str | dict[str, float] | None = None,
|
||||
layout_shape_mode: str | None = None,
|
||||
prompt_label: str | None = None,
|
||||
format_block_content: bool | None = None,
|
||||
repetition_penalty: float | None = None,
|
||||
temperature: float | None = None,
|
||||
top_p: float | None = None,
|
||||
@@ -127,15 +46,12 @@ class PaddleOCRVLLoader(BaseLoader):
|
||||
max_pixels: int | None = None,
|
||||
max_new_tokens: int | None = None,
|
||||
merge_layout_blocks: bool | None = None,
|
||||
markdown_ignore_labels: list[str] | None = None,
|
||||
vlm_extra_args: dict[str, Any] | None = None,
|
||||
prettify_markdown: bool | None = None,
|
||||
show_formula_number: bool | None = None,
|
||||
restructure_pages: bool | None = None,
|
||||
merge_tables: bool | None = None,
|
||||
relevel_titles: bool | None = None,
|
||||
visualize: bool | None = None,
|
||||
additional_params: dict[str, Any] | None = None,
|
||||
timeout: int = 300,
|
||||
) -> None:
|
||||
"""Initialize the PaddleOCR-VL loader.
|
||||
@@ -143,27 +59,22 @@ class PaddleOCRVLLoader(BaseLoader):
|
||||
Args:
|
||||
file_path: Single path/URL or an iterable of paths/URLs to PDF or
|
||||
image files.
|
||||
api_url: URL of the PaddleOCR-VL API endpoint.
|
||||
access_token: Optional access token as ``SecretStr``. If ``None``, the value
|
||||
from the ``PADDLEOCR_ACCESS_TOKEN`` environment variable will be used,
|
||||
if present.
|
||||
file_type: File type hint. ``"pdf"`` for PDFs, ``"image"`` for images,
|
||||
or ``None`` to infer from the file extension.
|
||||
from the ``PADDLEOCR_ACCESS_TOKEN`` environment variable will be used.
|
||||
base_url: Base URL of the PaddleOCR API service. Defaults to the official
|
||||
service. Most users do not need to set this.
|
||||
use_doc_orientation_classify: Whether to enable document orientation
|
||||
classification.
|
||||
use_doc_unwarping: Whether to enable document unwarping.
|
||||
use_layout_detection: Whether to enable layout detection.
|
||||
use_chart_recognition: Whether to enable chart recognition.
|
||||
use_seal_recognition: Whether to enable seal recognition.
|
||||
use_ocr_for_image_block: Whether to run OCR on image blocks.
|
||||
layout_threshold: Layout detection threshold (float or page-specific dict).
|
||||
layout_threshold: Layout detection threshold.
|
||||
layout_nms: Whether to apply non-maximum suppression for layout detection.
|
||||
layout_unclip_ratio: Layout unclip ratio (float, (min, max) tuple, or dict).
|
||||
layout_unclip_ratio: Layout unclip ratio.
|
||||
layout_merge_bboxes_mode: Mode for merging layout bounding boxes.
|
||||
layout_shape_mode: Layout shape mode.
|
||||
prompt_label: Prompt label for the VLM (for example, ``"ocr"`` or
|
||||
``"table"``).
|
||||
format_block_content: Whether to format block content.
|
||||
prompt_label: Prompt label for the VLM.
|
||||
repetition_penalty: Repetition penalty for VLM sampling.
|
||||
temperature: Temperature for VLM sampling.
|
||||
top_p: Top-p sampling value for VLM.
|
||||
@@ -171,17 +82,13 @@ class PaddleOCRVLLoader(BaseLoader):
|
||||
max_pixels: Maximum number of pixels allowed in preprocessing.
|
||||
max_new_tokens: Maximum number of tokens generated by the VLM.
|
||||
merge_layout_blocks: Whether to merge layout blocks across columns.
|
||||
markdown_ignore_labels: Layout labels to ignore when generating Markdown.
|
||||
vlm_extra_args: Additional configuration parameters for the VLM.
|
||||
prettify_markdown: Whether to prettify the Markdown output.
|
||||
show_formula_number: Whether to include formula numbers in Markdown.
|
||||
restructure_pages: Whether to restructure results across pages.
|
||||
merge_tables: Whether to merge tables across pages.
|
||||
relevel_titles: Whether to relevel titles.
|
||||
visualize: Whether to include visualization results.
|
||||
additional_params: Additional parameters to pass directly to the API
|
||||
(keys are treated as snake_case and converted to camelCase).
|
||||
timeout: Request timeout in seconds.
|
||||
timeout: Poll timeout in seconds.
|
||||
"""
|
||||
self._file_paths = (
|
||||
file_path
|
||||
@@ -189,148 +96,100 @@ class PaddleOCRVLLoader(BaseLoader):
|
||||
else [file_path]
|
||||
)
|
||||
|
||||
self.api_url = api_url
|
||||
self.timeout = timeout
|
||||
|
||||
if access_token is None:
|
||||
env_value = os.getenv("PADDLEOCR_ACCESS_TOKEN")
|
||||
self.access_token = SecretStr(env_value) if env_value else None
|
||||
self._token = env_value
|
||||
else:
|
||||
self.access_token = access_token
|
||||
self._token = access_token.get_secret_value()
|
||||
|
||||
self.file_type = _normalize_file_type(file_type)
|
||||
self._base_url = base_url or _DEFAULT_BASE_URL
|
||||
self._timeout = timeout
|
||||
|
||||
base_params: dict[str, Any] = {
|
||||
"use_doc_orientation_classify": use_doc_orientation_classify,
|
||||
"use_doc_unwarping": use_doc_unwarping,
|
||||
"use_layout_detection": use_layout_detection,
|
||||
"use_chart_recognition": use_chart_recognition,
|
||||
"use_seal_recognition": use_seal_recognition,
|
||||
"use_ocr_for_image_block": use_ocr_for_image_block,
|
||||
"layout_threshold": layout_threshold,
|
||||
"layout_nms": layout_nms,
|
||||
"layout_unclip_ratio": layout_unclip_ratio,
|
||||
"layout_merge_bboxes_mode": layout_merge_bboxes_mode,
|
||||
"layout_shape_mode": layout_shape_mode,
|
||||
"prompt_label": prompt_label,
|
||||
"format_block_content": format_block_content,
|
||||
"repetition_penalty": repetition_penalty,
|
||||
"temperature": temperature,
|
||||
"top_p": top_p,
|
||||
"min_pixels": min_pixels,
|
||||
"max_pixels": max_pixels,
|
||||
"max_new_tokens": max_new_tokens,
|
||||
"merge_layout_blocks": merge_layout_blocks,
|
||||
"markdown_ignore_labels": markdown_ignore_labels,
|
||||
"vlm_extra_args": vlm_extra_args,
|
||||
"prettify_markdown": prettify_markdown,
|
||||
"show_formula_number": show_formula_number,
|
||||
"restructure_pages": restructure_pages,
|
||||
"merge_tables": merge_tables,
|
||||
"relevel_titles": relevel_titles,
|
||||
"visualize": visualize,
|
||||
from paddleocr import PaddleOCRVLOptions
|
||||
|
||||
options_kwargs: dict[str, Any] = {
|
||||
key: val
|
||||
for key, val in {
|
||||
"use_doc_orientation_classify": use_doc_orientation_classify,
|
||||
"use_doc_unwarping": use_doc_unwarping,
|
||||
"use_layout_detection": use_layout_detection,
|
||||
"use_chart_recognition": use_chart_recognition,
|
||||
"use_seal_recognition": use_seal_recognition,
|
||||
"layout_threshold": layout_threshold,
|
||||
"layout_nms": layout_nms,
|
||||
"layout_unclip_ratio": layout_unclip_ratio,
|
||||
"layout_merge_bboxes_mode": layout_merge_bboxes_mode,
|
||||
"layout_shape_mode": layout_shape_mode,
|
||||
"prompt_label": prompt_label,
|
||||
"repetition_penalty": repetition_penalty,
|
||||
"temperature": temperature,
|
||||
"top_p": top_p,
|
||||
"min_pixels": min_pixels,
|
||||
"max_pixels": max_pixels,
|
||||
"max_new_tokens": max_new_tokens,
|
||||
"merge_layout_blocks": merge_layout_blocks,
|
||||
"prettify_markdown": prettify_markdown,
|
||||
"show_formula_number": show_formula_number,
|
||||
"restructure_pages": restructure_pages,
|
||||
"merge_tables": merge_tables,
|
||||
"relevel_titles": relevel_titles,
|
||||
"visualize": visualize,
|
||||
}.items()
|
||||
if val is not None
|
||||
}
|
||||
|
||||
# Convert all known service parameters from snake_case to camelCase.
|
||||
service_params = _snake_keys_to_camel(base_params)
|
||||
self._options = PaddleOCRVLOptions(**options_kwargs) if options_kwargs else None
|
||||
|
||||
if additional_params:
|
||||
for key, value in additional_params.items():
|
||||
if value is None:
|
||||
continue
|
||||
service_params[key] = value
|
||||
def _is_url(self, path: str) -> bool:
|
||||
"""Check if the path is a URL."""
|
||||
return path.startswith(("http://", "https://"))
|
||||
|
||||
self._service_params = service_params
|
||||
def _process_file(self, file_path: str) -> tuple[str, dict[str, Any]]:
|
||||
"""Process a single file through the SDK and return text + raw result."""
|
||||
from paddleocr import PaddleOCRClient
|
||||
|
||||
def _read_file_bytes(self, path: Path) -> str:
|
||||
"""Read file content from a local path."""
|
||||
try:
|
||||
data = path.read_bytes()
|
||||
except OSError as exc:
|
||||
msg = f"Failed to read file from path '{path}': {exc}"
|
||||
raise ValueError(msg) from exc
|
||||
return base64.b64encode(data).decode("ascii")
|
||||
with PaddleOCRClient(
|
||||
token=self._token,
|
||||
base_url=self._base_url,
|
||||
client_platform="langchain",
|
||||
poll_timeout=self._timeout,
|
||||
) as client:
|
||||
if self._is_url(file_path):
|
||||
result = client.parse_document(
|
||||
file_url=file_path,
|
||||
options=self._options,
|
||||
)
|
||||
else:
|
||||
local_path = Path(file_path)
|
||||
if not local_path.exists():
|
||||
msg = f"File not found: '{file_path}'"
|
||||
raise ValueError(msg)
|
||||
result = client.parse_document(
|
||||
file_path=str(local_path),
|
||||
options=self._options,
|
||||
)
|
||||
|
||||
def _call_api(self, data: str, file_type: FileType) -> tuple[str, dict[str, Any]]:
|
||||
"""Call the PaddleOCR-VL API and return extracted text and raw response."""
|
||||
|
||||
request_data: dict[str, Any] = {
|
||||
"file": data,
|
||||
"fileType": file_type,
|
||||
}
|
||||
request_data.update(self._service_params)
|
||||
|
||||
try:
|
||||
request_model = PaddleOCRVLInferRequest(**request_data)
|
||||
request_payload = request_model.model_dump(exclude_none=True)
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
msg = f"Invalid request parameters for PaddleOCR-VL: {exc}"
|
||||
raise ValueError(msg) from exc
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Client-Platform": "langchain",
|
||||
}
|
||||
if self.access_token is not None:
|
||||
headers["Authorization"] = f"token {self.access_token.get_secret_value()}"
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
self.api_url,
|
||||
json=request_payload,
|
||||
headers=headers,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
except requests.RequestException as exc:
|
||||
msg = f"Failed to call PaddleOCR-VL API: {exc}"
|
||||
raise ValueError(msg) from exc
|
||||
|
||||
try:
|
||||
response_data: dict[str, Any] = response.json()
|
||||
except ValueError as exc: # pragma: no cover - defensive
|
||||
msg = f"Invalid JSON response from PaddleOCR-VL API: {exc}"
|
||||
raise ValueError(msg) from exc
|
||||
|
||||
if "result" not in response_data:
|
||||
msg = "Response from PaddleOCR-VL API is missing the 'result' field."
|
||||
raise ValueError(msg)
|
||||
|
||||
try:
|
||||
result = PaddleOCRVLInferResult(**response_data["result"])
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
msg = f"Invalid response format from PaddleOCR-VL API: {exc}"
|
||||
raise ValueError(msg) from exc
|
||||
|
||||
text_parts = [
|
||||
layout_result.markdown.text
|
||||
for layout_result in result.layoutParsingResults
|
||||
if layout_result.markdown and layout_result.markdown.text
|
||||
]
|
||||
text_parts = [page.markdown_text for page in result.pages if page.markdown_text]
|
||||
text = _PAGES_DELIMITER.join(text_parts)
|
||||
|
||||
return text, response_data
|
||||
raw_response = {
|
||||
"job_id": result.job_id,
|
||||
"pages": [
|
||||
{
|
||||
"markdown_text": page.markdown_text,
|
||||
"markdown_images": page.markdown_images,
|
||||
"output_images": page.output_images,
|
||||
}
|
||||
for page in result.pages
|
||||
],
|
||||
}
|
||||
|
||||
return text, raw_response
|
||||
|
||||
def lazy_load(self) -> Iterator[Document]:
|
||||
"""Lazily load documents from the configured file paths."""
|
||||
for file_path in self._file_paths:
|
||||
if self.file_type is not None:
|
||||
file_type = self.file_type
|
||||
else:
|
||||
file_type = None
|
||||
|
||||
if file_path.startswith(("http://", "https://")):
|
||||
data = file_path
|
||||
else:
|
||||
data = self._read_file_bytes(Path(file_path))
|
||||
if file_type is None:
|
||||
inferred = _infer_file_type_from_path(Path(file_path))
|
||||
if inferred is None:
|
||||
msg = f"Could not determine file type for '{file_path}'."
|
||||
raise ValueError(msg)
|
||||
file_type = inferred
|
||||
|
||||
text, raw_response = self._call_api(data, file_type)
|
||||
text, raw_response = self._process_file(file_path)
|
||||
|
||||
if not text:
|
||||
logger.warning(
|
||||
|
||||
@@ -4,17 +4,15 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "langchain-paddleocr"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
description = "An integration package connecting PaddleOCR and LangChain"
|
||||
authors = []
|
||||
readme = "README.md"
|
||||
license = { text = "Apache License 2.0" }
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"paddleocr>=3.4.0,<3.5.0",
|
||||
"paddlex[serving]>=3.4.1,<3.5.0",
|
||||
"paddleocr>=3.6.0",
|
||||
"langchain-core>=1.2.5,<2.0.0",
|
||||
"requests>=2.32.5",
|
||||
"pydantic>=2.0.0,<3.0.0",
|
||||
]
|
||||
|
||||
@@ -38,10 +36,7 @@ test = [
|
||||
"pytest-asyncio>=0.21.0,<1.0.0",
|
||||
"pytest-retry>=1.7.0,<2.0.0",
|
||||
"pytest-socket>=0.7.0,<1.0.0",
|
||||
"numpy>=1.26.4; python_version<'3.13'",
|
||||
"numpy>=2.1.0; python_version>='3.13'",
|
||||
"langchain-tests>=1.1.2,<2.0.0",
|
||||
"protobuf>=4.25.0,<7.0.0",
|
||||
]
|
||||
test_integration = [
|
||||
"pytest>=8.4.0,<9.0.0",
|
||||
@@ -112,7 +107,7 @@ strict = true
|
||||
disallow_untyped_defs = true
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = ["paddleocr.*", "paddlex.*"]
|
||||
module = ["paddleocr.*"]
|
||||
ignore_missing_imports = true
|
||||
|
||||
# TODO: activate for 'strict' checking
|
||||
|
||||
+6
-8
@@ -14,17 +14,15 @@ def test_paddleocr_vl_loader_live_integration() -> None:
|
||||
|
||||
This test requires the following environment variables to be set:
|
||||
|
||||
- ``PADDLEOCR_VL_API_URL``: The PaddleOCR-VL HTTP endpoint.
|
||||
- ``PADDLEOCR_ACCESS_TOKEN``: Access token for the endpoint.
|
||||
- ``PADDLEOCR_BASE_URL`` (optional): Override the default base URL.
|
||||
"""
|
||||
api_url = os.getenv("PADDLEOCR_VL_API_URL")
|
||||
access_token = os.getenv("PADDLEOCR_ACCESS_TOKEN")
|
||||
|
||||
if not api_url or not access_token:
|
||||
pytest.skip(
|
||||
"PADDLEOCR_VL_API_URL and PADDLEOCR_ACCESS_TOKEN must be"
|
||||
" set for integration tests."
|
||||
)
|
||||
if not access_token:
|
||||
pytest.skip("PADDLEOCR_ACCESS_TOKEN must be set for integration tests.")
|
||||
|
||||
base_url = os.getenv("PADDLEOCR_BASE_URL")
|
||||
|
||||
tests_dir = Path(__file__).resolve().parents[2]
|
||||
sample_paths = [
|
||||
@@ -34,8 +32,8 @@ def test_paddleocr_vl_loader_live_integration() -> None:
|
||||
|
||||
loader = PaddleOCRVLLoader(
|
||||
file_path=sample_paths,
|
||||
api_url=api_url,
|
||||
access_token=SecretStr(access_token),
|
||||
base_url=base_url,
|
||||
)
|
||||
|
||||
docs = list(loader.lazy_load())
|
||||
|
||||
@@ -7,76 +7,56 @@ import pytest
|
||||
from langchain_paddleocr import PaddleOCRVLLoader
|
||||
|
||||
|
||||
def test_snake_to_camel_conversion_and_additional_params(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Ensure that snake_case parameters and additional_params are converted to
|
||||
camelCase."""
|
||||
|
||||
captured_service_params: dict[str, Any] = {}
|
||||
|
||||
# Patch the loader to expose internal _service_params for inspection.
|
||||
original_init = PaddleOCRVLLoader.__init__
|
||||
|
||||
def _wrapped_init(self: PaddleOCRVLLoader, *args: Any, **kwargs: Any) -> None:
|
||||
original_init(self, *args, **kwargs)
|
||||
nonlocal captured_service_params
|
||||
captured_service_params = getattr(self, "_service_params")
|
||||
|
||||
monkeypatch.setattr(PaddleOCRVLLoader, "__init__", _wrapped_init)
|
||||
|
||||
_ = PaddleOCRVLLoader(
|
||||
def test_default_base_url() -> None:
|
||||
"""Ensure default base_url is set when not provided."""
|
||||
loader = PaddleOCRVLLoader(
|
||||
file_path="dummy.pdf",
|
||||
api_url="http://example.com",
|
||||
use_doc_orientation_classify=True,
|
||||
layout_unclip_ratio=(0.1, 0.9),
|
||||
prompt_label="ocr",
|
||||
additional_params={"customOption": 1, "anotherFlag": True},
|
||||
access_token=None,
|
||||
)
|
||||
|
||||
# Keys from constructor
|
||||
assert captured_service_params["useDocOrientationClassify"] is True
|
||||
assert captured_service_params["layoutUnclipRatio"] == (0.1, 0.9)
|
||||
assert captured_service_params["promptLabel"] == "ocr"
|
||||
|
||||
# Keys from additional_params
|
||||
assert captured_service_params["customOption"] == 1
|
||||
assert captured_service_params["anotherFlag"] is True
|
||||
assert loader._base_url == "https://paddleocr.aistudio-app.com"
|
||||
|
||||
|
||||
def test_file_type_normalization_and_inference(
|
||||
tmp_path_factory: pytest.TempdirFactory,
|
||||
) -> None:
|
||||
"""Ensure file_type normalization and type inference from file extension
|
||||
work as expected."""
|
||||
pdf_file = tmp_path_factory.mktemp("pdf") / "sample.pdf"
|
||||
pdf_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
pdf_file.write_bytes(b"%PDF-1.4")
|
||||
|
||||
image_file = tmp_path_factory.mktemp("img") / "sample.png"
|
||||
image_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
image_file.write_bytes(b"\x89PNG\r\n\x1a\n")
|
||||
|
||||
loader_pdf_hint = PaddleOCRVLLoader(
|
||||
file_path=str(pdf_file),
|
||||
api_url="http://example.com",
|
||||
file_type="pdf",
|
||||
def test_custom_base_url() -> None:
|
||||
"""Ensure custom base_url is respected."""
|
||||
loader = PaddleOCRVLLoader(
|
||||
file_path="dummy.pdf",
|
||||
base_url="https://custom.example.com",
|
||||
)
|
||||
assert loader_pdf_hint.file_type == 0
|
||||
assert loader._base_url == "https://custom.example.com"
|
||||
|
||||
loader_image_hint = PaddleOCRVLLoader(
|
||||
file_path=str(image_file),
|
||||
api_url="http://example.com",
|
||||
file_type="image",
|
||||
|
||||
def test_access_token_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Ensure token is read from environment variable."""
|
||||
monkeypatch.setenv("PADDLEOCR_ACCESS_TOKEN", "env-token")
|
||||
loader = PaddleOCRVLLoader(file_path="dummy.pdf")
|
||||
assert loader._token == "env-token"
|
||||
|
||||
|
||||
def test_options_are_built_correctly() -> None:
|
||||
"""Ensure options with non-None values are passed to PaddleOCRVLOptions."""
|
||||
loader = PaddleOCRVLLoader(
|
||||
file_path="dummy.pdf",
|
||||
use_layout_detection=True,
|
||||
temperature=0.7,
|
||||
top_p=0.9,
|
||||
)
|
||||
assert loader_image_hint.file_type == 1
|
||||
assert loader._options is not None
|
||||
assert loader._options.use_layout_detection is True
|
||||
assert loader._options.temperature == 0.7
|
||||
assert loader._options.top_p == 0.9
|
||||
|
||||
|
||||
def test_lazy_load_raises_for_unreadable_file() -> None:
|
||||
"""Ensure lazy_load raises when a file cannot be read."""
|
||||
def test_options_none_when_no_params() -> None:
|
||||
"""Ensure options is None when no OCR params are provided."""
|
||||
loader = PaddleOCRVLLoader(file_path="dummy.pdf")
|
||||
assert loader._options is None
|
||||
|
||||
|
||||
def test_lazy_load_raises_for_missing_file() -> None:
|
||||
"""Ensure lazy_load raises when a local file does not exist."""
|
||||
loader = PaddleOCRVLLoader(
|
||||
file_path="nonexistent-file.pdf",
|
||||
api_url="http://example.com",
|
||||
access_token=None,
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
with pytest.raises(ValueError, match="File not found"):
|
||||
list(loader.lazy_load())
|
||||
Reference in new issue
Block a user