puffinparse 0.2.0__cp310-abi3-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- puffinparse/__init__.py +141 -0
- puffinparse/_core.pyd +0 -0
- puffinparse/_core.pyi +62 -0
- puffinparse/exceptions.py +143 -0
- puffinparse/jobs.py +298 -0
- puffinparse/main.py +1139 -0
- puffinparse/py.typed +0 -0
- puffinparse/types.py +482 -0
- puffinparse-0.2.0.data/scripts/puffinparse.exe +0 -0
- puffinparse-0.2.0.dist-info/METADATA +753 -0
- puffinparse-0.2.0.dist-info/RECORD +16 -0
- puffinparse-0.2.0.dist-info/WHEEL +4 -0
- puffinparse-0.2.0.dist-info/licenses/LICENSE +21 -0
- puffinparse-0.2.0.dist-info/licenses/THIRD_PARTY_LICENSES.txt +48987 -0
- puffinparse-0.2.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +412 -0
- puffinparse-0.2.0.dist-info/sboms/puffinparse-python.cyclonedx.json +6731 -0
puffinparse/__init__.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""PuffinParse: one API for every OCR / document-parsing provider.
|
|
2
|
+
|
|
3
|
+
Three modes, one shape each — switch providers by changing one string:
|
|
4
|
+
|
|
5
|
+
>>> import puffinparse
|
|
6
|
+
>>> doc = puffinparse.parse("invoice.pdf", model="reducto/standard") # markdown + blocks
|
|
7
|
+
>>> print(doc.markdown, doc.usage.pages, doc.cost_usd)
|
|
8
|
+
>>> text = puffinparse.ocr("scan.png", model="llamaparse/fast") # plain text + boxes
|
|
9
|
+
>>> print(text.text, len(text.pages[0].lines))
|
|
10
|
+
>>> data = puffinparse.extract("invoice.pdf", schema, model="...") # JSON from a schema
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from . import _core
|
|
16
|
+
from .exceptions import (
|
|
17
|
+
AuthenticationError,
|
|
18
|
+
BadRequestError,
|
|
19
|
+
InputError,
|
|
20
|
+
NetworkError,
|
|
21
|
+
ProviderError,
|
|
22
|
+
PuffinParseError,
|
|
23
|
+
RateLimitError,
|
|
24
|
+
TimeoutError,
|
|
25
|
+
UnsupportedModelError,
|
|
26
|
+
)
|
|
27
|
+
from .jobs import (
|
|
28
|
+
JobResult,
|
|
29
|
+
ahandle_webhook,
|
|
30
|
+
aretrieve,
|
|
31
|
+
asubmit,
|
|
32
|
+
handle_webhook,
|
|
33
|
+
retrieve,
|
|
34
|
+
submit,
|
|
35
|
+
)
|
|
36
|
+
from .main import (
|
|
37
|
+
Router,
|
|
38
|
+
aextract,
|
|
39
|
+
aocr,
|
|
40
|
+
aparse,
|
|
41
|
+
estimate_cost,
|
|
42
|
+
extract,
|
|
43
|
+
failure_callback,
|
|
44
|
+
init_logging,
|
|
45
|
+
list_models,
|
|
46
|
+
markdown_to_text,
|
|
47
|
+
modes,
|
|
48
|
+
normalize_text,
|
|
49
|
+
ocr,
|
|
50
|
+
output_formats,
|
|
51
|
+
parse,
|
|
52
|
+
pricing,
|
|
53
|
+
providers,
|
|
54
|
+
reset_pricing,
|
|
55
|
+
resolve_model,
|
|
56
|
+
score,
|
|
57
|
+
set_pricing,
|
|
58
|
+
success_callback,
|
|
59
|
+
)
|
|
60
|
+
from .types import (
|
|
61
|
+
MODES,
|
|
62
|
+
BBox,
|
|
63
|
+
Block,
|
|
64
|
+
BlockType,
|
|
65
|
+
Citation,
|
|
66
|
+
ExtractResponse,
|
|
67
|
+
FieldInfo,
|
|
68
|
+
Job,
|
|
69
|
+
Line,
|
|
70
|
+
Metrics,
|
|
71
|
+
Mode,
|
|
72
|
+
Page,
|
|
73
|
+
ParseResponse,
|
|
74
|
+
Response,
|
|
75
|
+
TextPage,
|
|
76
|
+
TextResponse,
|
|
77
|
+
Usage,
|
|
78
|
+
Word,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
__version__: str = str(_core.__version__)
|
|
82
|
+
|
|
83
|
+
__all__ = [
|
|
84
|
+
"MODES",
|
|
85
|
+
"AuthenticationError",
|
|
86
|
+
"BBox",
|
|
87
|
+
"BadRequestError",
|
|
88
|
+
"Block",
|
|
89
|
+
"BlockType",
|
|
90
|
+
"Citation",
|
|
91
|
+
"ExtractResponse",
|
|
92
|
+
"FieldInfo",
|
|
93
|
+
"InputError",
|
|
94
|
+
"Job",
|
|
95
|
+
"JobResult",
|
|
96
|
+
"Line",
|
|
97
|
+
"Metrics",
|
|
98
|
+
"Mode",
|
|
99
|
+
"NetworkError",
|
|
100
|
+
"Page",
|
|
101
|
+
"ParseResponse",
|
|
102
|
+
"ProviderError",
|
|
103
|
+
"PuffinParseError",
|
|
104
|
+
"RateLimitError",
|
|
105
|
+
"Response",
|
|
106
|
+
"Router",
|
|
107
|
+
"TextPage",
|
|
108
|
+
"TextResponse",
|
|
109
|
+
"TimeoutError",
|
|
110
|
+
"UnsupportedModelError",
|
|
111
|
+
"Usage",
|
|
112
|
+
"Word",
|
|
113
|
+
"__version__",
|
|
114
|
+
"aextract",
|
|
115
|
+
"ahandle_webhook",
|
|
116
|
+
"aocr",
|
|
117
|
+
"aparse",
|
|
118
|
+
"aretrieve",
|
|
119
|
+
"asubmit",
|
|
120
|
+
"estimate_cost",
|
|
121
|
+
"extract",
|
|
122
|
+
"failure_callback",
|
|
123
|
+
"handle_webhook",
|
|
124
|
+
"init_logging",
|
|
125
|
+
"list_models",
|
|
126
|
+
"markdown_to_text",
|
|
127
|
+
"modes",
|
|
128
|
+
"normalize_text",
|
|
129
|
+
"ocr",
|
|
130
|
+
"output_formats",
|
|
131
|
+
"parse",
|
|
132
|
+
"pricing",
|
|
133
|
+
"providers",
|
|
134
|
+
"reset_pricing",
|
|
135
|
+
"resolve_model",
|
|
136
|
+
"retrieve",
|
|
137
|
+
"score",
|
|
138
|
+
"set_pricing",
|
|
139
|
+
"submit",
|
|
140
|
+
"success_callback",
|
|
141
|
+
]
|
puffinparse/_core.pyd
ADDED
|
Binary file
|
puffinparse/_core.pyi
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Type stubs for the Rust extension module."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
__version__: str
|
|
6
|
+
|
|
7
|
+
class CoreError(Exception): ...
|
|
8
|
+
|
|
9
|
+
class Router:
|
|
10
|
+
def __init__(
|
|
11
|
+
self,
|
|
12
|
+
models: list[str],
|
|
13
|
+
mode: str = "parse",
|
|
14
|
+
strategy: str = "ordered",
|
|
15
|
+
fallback_on: Optional[list[str]] = None,
|
|
16
|
+
) -> None: ...
|
|
17
|
+
def models(self) -> list[str]: ...
|
|
18
|
+
def mode(self) -> str: ...
|
|
19
|
+
def plan(self) -> list[str]: ...
|
|
20
|
+
def parse(self, request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
21
|
+
async def aparse(self, request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
22
|
+
def ocr(self, request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
23
|
+
async def aocr(self, request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
24
|
+
def extract(self, request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
25
|
+
async def aextract(self, request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
26
|
+
def stats(self) -> dict[str, dict[str, Any]]: ...
|
|
27
|
+
|
|
28
|
+
def parse(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
29
|
+
async def aparse(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
30
|
+
def ocr(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
31
|
+
async def aocr(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
32
|
+
def extract(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
33
|
+
async def aextract(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
34
|
+
def submit(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
35
|
+
async def asubmit(request: dict[str, Any], data: Optional[bytes] = None) -> dict[str, Any]: ...
|
|
36
|
+
def retrieve(job: dict[str, Any], options: Optional[dict[str, Any]] = None) -> dict[str, Any]: ...
|
|
37
|
+
async def aretrieve(job: dict[str, Any], options: Optional[dict[str, Any]] = None) -> dict[str, Any]: ...
|
|
38
|
+
def parse_webhook(model: str, payload: Any) -> dict[str, Any]: ...
|
|
39
|
+
def output_formats() -> list[str]: ...
|
|
40
|
+
def validate_output_format(format: str) -> str: ...
|
|
41
|
+
def render_parse(response: dict[str, Any], format: str) -> dict[str, Any]: ...
|
|
42
|
+
def render_extract(response: dict[str, Any], format: str) -> dict[str, Any]: ...
|
|
43
|
+
def list_models(mode: Optional[str] = None) -> list[str]: ...
|
|
44
|
+
def modes() -> list[str]: ...
|
|
45
|
+
def providers() -> list[dict[str, Any]]: ...
|
|
46
|
+
def pricing() -> dict[str, dict[str, Any]]: ...
|
|
47
|
+
def set_pricing(prices: dict[str, float], mode: str = "parse") -> None: ...
|
|
48
|
+
def reset_pricing() -> None: ...
|
|
49
|
+
def estimate_cost(model: str, mode: str, pages: int) -> Optional[float]: ...
|
|
50
|
+
def resolve_model(model: str, mode: Optional[str] = None) -> str: ...
|
|
51
|
+
def score(
|
|
52
|
+
prediction: str,
|
|
53
|
+
truth: str,
|
|
54
|
+
case_insensitive: bool = True,
|
|
55
|
+
strip_markdown: bool = True,
|
|
56
|
+
strip_punctuation: bool = False,
|
|
57
|
+
) -> dict[str, Any]: ...
|
|
58
|
+
def normalize_text(
|
|
59
|
+
text: str, case_insensitive: bool = True, strip_markdown: bool = True, strip_punctuation: bool = False
|
|
60
|
+
) -> str: ...
|
|
61
|
+
def markdown_to_text(md: str) -> str: ...
|
|
62
|
+
def init_logging(level: str) -> None: ...
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Exception hierarchy. Every error raised by PuffinParse derives from :class:`PuffinParseError`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PuffinParseError(Exception):
|
|
10
|
+
"""Base class for all PuffinParse errors."""
|
|
11
|
+
|
|
12
|
+
kind: str = "error"
|
|
13
|
+
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
message: str,
|
|
17
|
+
*,
|
|
18
|
+
provider: Optional[str] = None,
|
|
19
|
+
status_code: Optional[int] = None,
|
|
20
|
+
job_id: Optional[str] = None,
|
|
21
|
+
retryable: bool = False,
|
|
22
|
+
) -> None:
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.message = message
|
|
25
|
+
self.provider = provider
|
|
26
|
+
self.status_code = status_code
|
|
27
|
+
self.job_id = job_id
|
|
28
|
+
self.retryable = retryable
|
|
29
|
+
|
|
30
|
+
def __str__(self) -> str:
|
|
31
|
+
parts = [self.kind]
|
|
32
|
+
if self.provider:
|
|
33
|
+
parts.append(f"[{self.provider}]")
|
|
34
|
+
s = " ".join(parts) + f": {self.message}"
|
|
35
|
+
if self.status_code is not None:
|
|
36
|
+
s += f" (HTTP {self.status_code})"
|
|
37
|
+
if self.job_id:
|
|
38
|
+
s += f" [job {self.job_id}]"
|
|
39
|
+
return s
|
|
40
|
+
|
|
41
|
+
def to_dict(self) -> dict[str, Any]:
|
|
42
|
+
return {
|
|
43
|
+
"kind": self.kind,
|
|
44
|
+
"message": self.message,
|
|
45
|
+
"provider": self.provider,
|
|
46
|
+
"status_code": self.status_code,
|
|
47
|
+
"job_id": self.job_id,
|
|
48
|
+
"retryable": self.retryable,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AuthenticationError(PuffinParseError):
|
|
53
|
+
"""401/403 from the provider, or no API key configured."""
|
|
54
|
+
|
|
55
|
+
kind = "authentication_error"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class RateLimitError(PuffinParseError):
|
|
59
|
+
"""429 from the provider after retries were exhausted."""
|
|
60
|
+
|
|
61
|
+
kind = "rate_limit_error"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class BadRequestError(PuffinParseError):
|
|
65
|
+
"""The provider rejected the request (4xx other than auth / rate limit)."""
|
|
66
|
+
|
|
67
|
+
kind = "bad_request_error"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ProviderError(PuffinParseError):
|
|
71
|
+
"""5xx, malformed provider payload, or a job that ended in a failed state."""
|
|
72
|
+
|
|
73
|
+
kind = "provider_error"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TimeoutError(PuffinParseError):
|
|
77
|
+
"""The overall deadline (upload + polling + download) was exceeded."""
|
|
78
|
+
|
|
79
|
+
kind = "timeout_error"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class UnsupportedModelError(PuffinParseError):
|
|
83
|
+
"""Unknown provider or model string."""
|
|
84
|
+
|
|
85
|
+
kind = "unsupported_model_error"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class InputError(PuffinParseError):
|
|
89
|
+
"""Unreadable input, bytes without a filename, empty body, ..."""
|
|
90
|
+
|
|
91
|
+
kind = "input_error"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class NetworkError(PuffinParseError):
|
|
95
|
+
"""Network / TLS / DNS failure after retries."""
|
|
96
|
+
|
|
97
|
+
kind = "network_error"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_KIND_TO_CLASS: dict[str, type[PuffinParseError]] = {
|
|
101
|
+
"authentication": AuthenticationError,
|
|
102
|
+
"rate_limit": RateLimitError,
|
|
103
|
+
"bad_request": BadRequestError,
|
|
104
|
+
"provider": ProviderError,
|
|
105
|
+
"timeout": TimeoutError,
|
|
106
|
+
"unsupported_model": UnsupportedModelError,
|
|
107
|
+
"input": InputError,
|
|
108
|
+
"network": NetworkError,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def from_core(exc: BaseException) -> PuffinParseError:
|
|
113
|
+
"""Convert a ``puffinparse._core.CoreError`` (JSON payload) into a typed exception."""
|
|
114
|
+
payload: Any = exc.args[0] if exc.args else ""
|
|
115
|
+
data: dict[str, Any]
|
|
116
|
+
try:
|
|
117
|
+
data = json.loads(payload) if isinstance(payload, str) else {}
|
|
118
|
+
except ValueError:
|
|
119
|
+
data = {}
|
|
120
|
+
if not isinstance(data, dict) or "kind" not in data:
|
|
121
|
+
return ProviderError(str(payload))
|
|
122
|
+
cls = _KIND_TO_CLASS.get(str(data.get("kind")), ProviderError)
|
|
123
|
+
return cls(
|
|
124
|
+
str(data.get("message", "")),
|
|
125
|
+
provider=data.get("provider"),
|
|
126
|
+
status_code=data.get("status_code"),
|
|
127
|
+
job_id=data.get("job_id"),
|
|
128
|
+
retryable=bool(data.get("retryable", False)),
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
__all__ = [
|
|
133
|
+
"AuthenticationError",
|
|
134
|
+
"BadRequestError",
|
|
135
|
+
"InputError",
|
|
136
|
+
"NetworkError",
|
|
137
|
+
"ProviderError",
|
|
138
|
+
"PuffinParseError",
|
|
139
|
+
"RateLimitError",
|
|
140
|
+
"TimeoutError",
|
|
141
|
+
"UnsupportedModelError",
|
|
142
|
+
"from_core",
|
|
143
|
+
]
|
puffinparse/jobs.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Asynchronous jobs: submit a ``parse`` now, collect the result later.
|
|
2
|
+
|
|
3
|
+
:func:`puffinparse.parse` waits for the provider (polling job-queue providers for you). For long
|
|
4
|
+
documents, large batches or webhook-driven pipelines, split the call in two instead:
|
|
5
|
+
|
|
6
|
+
>>> job = puffinparse.submit("200-pages.pdf", model="reducto/standard",
|
|
7
|
+
... webhook_url="https://example.com/hooks/puffinparse")
|
|
8
|
+
>>> store(job.to_dict()) # a Job never contains an API key
|
|
9
|
+
>>> result = puffinparse.retrieve(job) # Job (still running) or ParseResponse
|
|
10
|
+
>>> # ... or, in the webhook handler:
|
|
11
|
+
>>> result = puffinparse.handle_webhook(request.json(), model="reducto")
|
|
12
|
+
|
|
13
|
+
Supported by the providers with a job queue: ``reducto``, ``extend``, ``llamaparse``,
|
|
14
|
+
``opendocrouter`` (which has no webhooks). A failed job raises the same typed exceptions as
|
|
15
|
+
:func:`puffinparse.parse`.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
from typing import Any, Literal, Optional, Union
|
|
22
|
+
|
|
23
|
+
from . import _core
|
|
24
|
+
from .main import (
|
|
25
|
+
DocumentLike,
|
|
26
|
+
_afail,
|
|
27
|
+
_build_request,
|
|
28
|
+
_fail,
|
|
29
|
+
_finish,
|
|
30
|
+
_run_callbacks_async,
|
|
31
|
+
success_callback,
|
|
32
|
+
)
|
|
33
|
+
from .types import Job, ParseResponse
|
|
34
|
+
|
|
35
|
+
#: What :func:`retrieve` and :func:`handle_webhook` return: the job while it is still running,
|
|
36
|
+
#: the unified response once it is done.
|
|
37
|
+
JobResult = Union[Job, ParseResponse]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _submit_request(
|
|
41
|
+
input: DocumentLike,
|
|
42
|
+
model: str,
|
|
43
|
+
webhook_url: Optional[str],
|
|
44
|
+
kwargs: dict[str, Any],
|
|
45
|
+
) -> tuple[dict[str, Any], Optional[bytes]]:
|
|
46
|
+
req, data = _build_request(input, model, **kwargs)
|
|
47
|
+
if webhook_url is not None:
|
|
48
|
+
req["webhook_url"] = webhook_url
|
|
49
|
+
return req, data
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _options(
|
|
53
|
+
api_key: Optional[str], base_url: Optional[str], timeout: float, max_retries: int
|
|
54
|
+
) -> dict[str, Any]:
|
|
55
|
+
opts: dict[str, Any] = {"timeout_secs": float(timeout), "max_retries": int(max_retries)}
|
|
56
|
+
if api_key is not None:
|
|
57
|
+
opts["api_key"] = api_key
|
|
58
|
+
if base_url is not None:
|
|
59
|
+
opts["base_url"] = base_url
|
|
60
|
+
return opts
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _job_result(job: Job, status: dict[str, Any]) -> JobResult:
|
|
64
|
+
if status.get("status") == "succeeded":
|
|
65
|
+
return ParseResponse.from_dict(status["result"])
|
|
66
|
+
return job
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def submit(
|
|
70
|
+
input: DocumentLike,
|
|
71
|
+
model: str = "reducto",
|
|
72
|
+
*,
|
|
73
|
+
webhook_url: Optional[str] = None,
|
|
74
|
+
filename: Optional[str] = None,
|
|
75
|
+
pages: Optional[str] = None,
|
|
76
|
+
language: Optional[str] = None,
|
|
77
|
+
output: Literal["markdown", "text"] = "markdown",
|
|
78
|
+
provider_options: Optional[dict[str, Any]] = None,
|
|
79
|
+
include_raw: bool = False,
|
|
80
|
+
timeout: float = 300.0,
|
|
81
|
+
max_retries: int = 2,
|
|
82
|
+
api_key: Optional[str] = None,
|
|
83
|
+
base_url: Optional[str] = None,
|
|
84
|
+
metadata: Optional[dict[str, Any]] = None,
|
|
85
|
+
) -> Job:
|
|
86
|
+
"""Upload a document and start a ``parse`` job without waiting for it.
|
|
87
|
+
|
|
88
|
+
Takes the same arguments as :func:`puffinparse.parse` (``timeout`` covers the upload and the
|
|
89
|
+
submission only), plus:
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
webhook_url: Ask the provider to POST to this URL when the job finishes — Reducto
|
|
93
|
+
``async.webhook`` (direct mode), LlamaParse ``webhook_url``. Extend has no per-job
|
|
94
|
+
webhook (register an endpoint in Extend instead); passing one raises
|
|
95
|
+
:class:`~puffinparse.InputError`.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
A :class:`~puffinparse.types.Job` to pass to :func:`retrieve`.
|
|
99
|
+
"""
|
|
100
|
+
req, data = _submit_request(
|
|
101
|
+
input,
|
|
102
|
+
model,
|
|
103
|
+
webhook_url,
|
|
104
|
+
{
|
|
105
|
+
"output": output,
|
|
106
|
+
"filename": filename,
|
|
107
|
+
"pages": pages,
|
|
108
|
+
"language": language,
|
|
109
|
+
"provider_options": provider_options,
|
|
110
|
+
"include_raw": include_raw,
|
|
111
|
+
"timeout": timeout,
|
|
112
|
+
"max_retries": max_retries,
|
|
113
|
+
"api_key": api_key,
|
|
114
|
+
"base_url": base_url,
|
|
115
|
+
"metadata": metadata,
|
|
116
|
+
},
|
|
117
|
+
)
|
|
118
|
+
try:
|
|
119
|
+
return Job.from_dict(_core.submit(req, data))
|
|
120
|
+
except _core.CoreError as e:
|
|
121
|
+
raise _fail(e, mode="parse") from None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def asubmit(
|
|
125
|
+
input: DocumentLike,
|
|
126
|
+
model: str = "reducto",
|
|
127
|
+
*,
|
|
128
|
+
webhook_url: Optional[str] = None,
|
|
129
|
+
filename: Optional[str] = None,
|
|
130
|
+
pages: Optional[str] = None,
|
|
131
|
+
language: Optional[str] = None,
|
|
132
|
+
output: Literal["markdown", "text"] = "markdown",
|
|
133
|
+
provider_options: Optional[dict[str, Any]] = None,
|
|
134
|
+
include_raw: bool = False,
|
|
135
|
+
timeout: float = 300.0,
|
|
136
|
+
max_retries: int = 2,
|
|
137
|
+
api_key: Optional[str] = None,
|
|
138
|
+
base_url: Optional[str] = None,
|
|
139
|
+
metadata: Optional[dict[str, Any]] = None,
|
|
140
|
+
) -> Job:
|
|
141
|
+
"""Async version of :func:`submit`."""
|
|
142
|
+
req, data = _submit_request(
|
|
143
|
+
input,
|
|
144
|
+
model,
|
|
145
|
+
webhook_url,
|
|
146
|
+
{
|
|
147
|
+
"output": output,
|
|
148
|
+
"filename": filename,
|
|
149
|
+
"pages": pages,
|
|
150
|
+
"language": language,
|
|
151
|
+
"provider_options": provider_options,
|
|
152
|
+
"include_raw": include_raw,
|
|
153
|
+
"timeout": timeout,
|
|
154
|
+
"max_retries": max_retries,
|
|
155
|
+
"api_key": api_key,
|
|
156
|
+
"base_url": base_url,
|
|
157
|
+
"metadata": metadata,
|
|
158
|
+
},
|
|
159
|
+
)
|
|
160
|
+
try:
|
|
161
|
+
return Job.from_dict(await _core.asubmit(req, data))
|
|
162
|
+
except _core.CoreError as e:
|
|
163
|
+
raise await _afail(e, mode="parse") from None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def retrieve(
|
|
167
|
+
job: Job,
|
|
168
|
+
*,
|
|
169
|
+
api_key: Optional[str] = None,
|
|
170
|
+
base_url: Optional[str] = None,
|
|
171
|
+
timeout: float = 120.0,
|
|
172
|
+
max_retries: int = 2,
|
|
173
|
+
) -> JobResult:
|
|
174
|
+
"""Check a submitted job once.
|
|
175
|
+
|
|
176
|
+
Returns the same :class:`~puffinparse.types.Job` while the provider is still working, or the
|
|
177
|
+
:class:`~puffinparse.types.ParseResponse` (normalised exactly like :func:`puffinparse.parse`) once it
|
|
178
|
+
is done. A job the provider reports as failed raises the matching typed exception, with
|
|
179
|
+
``job_id`` set. Credentials come from the environment unless ``api_key`` is given; the base
|
|
180
|
+
URL defaults to the one used at submit time.
|
|
181
|
+
"""
|
|
182
|
+
try:
|
|
183
|
+
status = _core.retrieve(job.to_dict(), _options(api_key, base_url, timeout, max_retries))
|
|
184
|
+
except _core.CoreError as e:
|
|
185
|
+
raise _fail(e, mode="parse") from None
|
|
186
|
+
result = _job_result(job, status)
|
|
187
|
+
return _finish(result) if isinstance(result, ParseResponse) else result
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
async def aretrieve(
|
|
191
|
+
job: Job,
|
|
192
|
+
*,
|
|
193
|
+
api_key: Optional[str] = None,
|
|
194
|
+
base_url: Optional[str] = None,
|
|
195
|
+
timeout: float = 120.0,
|
|
196
|
+
max_retries: int = 2,
|
|
197
|
+
) -> JobResult:
|
|
198
|
+
"""Async version of :func:`retrieve`."""
|
|
199
|
+
try:
|
|
200
|
+
status = await _core.aretrieve(job.to_dict(), _options(api_key, base_url, timeout, max_retries))
|
|
201
|
+
except _core.CoreError as e:
|
|
202
|
+
raise await _afail(e, mode="parse") from None
|
|
203
|
+
result = _job_result(job, status)
|
|
204
|
+
if isinstance(result, ParseResponse):
|
|
205
|
+
await _run_callbacks_async(success_callback, result)
|
|
206
|
+
return result
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _webhook_event(payload: dict[str, Any], model: str) -> tuple[Optional[Job], dict[str, Any]]:
|
|
210
|
+
"""Parse a webhook body with the core; raise a typed error on an unreadable body."""
|
|
211
|
+
event = _core.parse_webhook(model, payload)
|
|
212
|
+
job = Job.from_dict(event["job"]) if event.get("job") else None
|
|
213
|
+
return job, event["status"]
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def handle_webhook(
|
|
217
|
+
payload: dict[str, Any],
|
|
218
|
+
model: str = "reducto",
|
|
219
|
+
*,
|
|
220
|
+
api_key: Optional[str] = None,
|
|
221
|
+
base_url: Optional[str] = None,
|
|
222
|
+
timeout: float = 120.0,
|
|
223
|
+
max_retries: int = 2,
|
|
224
|
+
) -> JobResult:
|
|
225
|
+
"""Turn the JSON body a provider POSTed to your webhook into a :class:`Job` or a result.
|
|
226
|
+
|
|
227
|
+
``model`` names the provider (``"reducto"``, ``"extend"``, ``"llamaparse"``) or one of its
|
|
228
|
+
models. Bodies that carry the whole result (LlamaParse's ``webhook_url`` push) are normalised
|
|
229
|
+
directly; bodies that only name a finished job (Reducto, Extend, LlamaCloud events) trigger
|
|
230
|
+
one :func:`retrieve`. A body reporting a failure raises the matching typed exception. Verify
|
|
231
|
+
the provider's signature (Extend, LlamaCloud) or your own secret *before* calling this.
|
|
232
|
+
"""
|
|
233
|
+
try:
|
|
234
|
+
job, status = _webhook_event(payload, model)
|
|
235
|
+
except _core.CoreError as e:
|
|
236
|
+
raise _fail(e, mode="parse") from None
|
|
237
|
+
state = status.get("status")
|
|
238
|
+
if state == "failed":
|
|
239
|
+
raise _fail(_core.CoreError(json.dumps(status["result"])), mode="parse")
|
|
240
|
+
if state == "succeeded":
|
|
241
|
+
return _finish(ParseResponse.from_dict(status["result"]))
|
|
242
|
+
if job is None:
|
|
243
|
+
raise _fail(_core.CoreError(json.dumps(_no_job_error())), mode="parse")
|
|
244
|
+
if state == "finished":
|
|
245
|
+
return retrieve(job, api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
|
|
246
|
+
return job
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
async def ahandle_webhook(
|
|
250
|
+
payload: dict[str, Any],
|
|
251
|
+
model: str = "reducto",
|
|
252
|
+
*,
|
|
253
|
+
api_key: Optional[str] = None,
|
|
254
|
+
base_url: Optional[str] = None,
|
|
255
|
+
timeout: float = 120.0,
|
|
256
|
+
max_retries: int = 2,
|
|
257
|
+
) -> JobResult:
|
|
258
|
+
"""Async version of :func:`handle_webhook`."""
|
|
259
|
+
try:
|
|
260
|
+
job, status = _webhook_event(payload, model)
|
|
261
|
+
except _core.CoreError as e:
|
|
262
|
+
raise await _afail(e, mode="parse") from None
|
|
263
|
+
state = status.get("status")
|
|
264
|
+
if state == "failed":
|
|
265
|
+
raise await _afail(_core.CoreError(json.dumps(status["result"])), mode="parse")
|
|
266
|
+
if state == "succeeded":
|
|
267
|
+
resp = ParseResponse.from_dict(status["result"])
|
|
268
|
+
await _run_callbacks_async(success_callback, resp)
|
|
269
|
+
return resp
|
|
270
|
+
if job is None:
|
|
271
|
+
raise await _afail(_core.CoreError(json.dumps(_no_job_error())), mode="parse")
|
|
272
|
+
if state == "finished":
|
|
273
|
+
return await aretrieve(
|
|
274
|
+
job, api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries
|
|
275
|
+
)
|
|
276
|
+
return job
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _no_job_error() -> dict[str, Any]:
|
|
280
|
+
return {
|
|
281
|
+
"kind": "input",
|
|
282
|
+
"message": "webhook payload names no job id",
|
|
283
|
+
"provider": None,
|
|
284
|
+
"status_code": None,
|
|
285
|
+
"job_id": None,
|
|
286
|
+
"retryable": False,
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
__all__ = [
|
|
291
|
+
"JobResult",
|
|
292
|
+
"ahandle_webhook",
|
|
293
|
+
"aretrieve",
|
|
294
|
+
"asubmit",
|
|
295
|
+
"handle_webhook",
|
|
296
|
+
"retrieve",
|
|
297
|
+
"submit",
|
|
298
|
+
]
|