docql 0.1.0__py3-none-any.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.
- docql/__init__.py +57 -0
- docql/_client.py +213 -0
- docql/_constants.py +56 -0
- docql/_errors.py +106 -0
- docql/_request.py +266 -0
- docql/_response.py +185 -0
- docql/_version.py +15 -0
- docql/py.typed +0 -0
- docql-0.1.0.dist-info/METADATA +184 -0
- docql-0.1.0.dist-info/RECORD +12 -0
- docql-0.1.0.dist-info/WHEEL +4 -0
- docql-0.1.0.dist-info/licenses/LICENSE +202 -0
docql/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Python client for the DocQL document-extraction API."""
|
|
2
|
+
|
|
3
|
+
from docql._client import DocQL
|
|
4
|
+
from docql._constants import (
|
|
5
|
+
MODE_FAST,
|
|
6
|
+
MODE_STANDARD,
|
|
7
|
+
REASON_BODY_NOT_JSON,
|
|
8
|
+
REASON_CORRUPTED_FILE,
|
|
9
|
+
REASON_DOCUMENT_EXCEEDS_TIME_BUDGET,
|
|
10
|
+
REASON_INVALID_API_KEY,
|
|
11
|
+
REASON_INVALID_PARAMS,
|
|
12
|
+
REASON_MISSING_BODY_FIELD,
|
|
13
|
+
REASON_MISSING_FILE_PART,
|
|
14
|
+
REASON_MISSING_QUERY_OR_PROMPT,
|
|
15
|
+
REASON_SERVICE_OVERLOADED,
|
|
16
|
+
REASON_UNSUPPORTED_FILE_TYPE,
|
|
17
|
+
REASON_UNSUPPORTED_MEDIA_TYPE,
|
|
18
|
+
REASON_UPLOAD_TOO_LARGE,
|
|
19
|
+
REASON_UPSTREAM_AUTH_FAILED,
|
|
20
|
+
REASON_UPSTREAM_UNAVAILABLE,
|
|
21
|
+
Mode,
|
|
22
|
+
)
|
|
23
|
+
from docql._errors import (
|
|
24
|
+
DocQLConnectionError,
|
|
25
|
+
DocQLError,
|
|
26
|
+
DocQLException,
|
|
27
|
+
DocQLTimeoutError,
|
|
28
|
+
)
|
|
29
|
+
from docql._response import QueryResult
|
|
30
|
+
from docql._version import __version__
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"DocQL",
|
|
34
|
+
"DocQLConnectionError",
|
|
35
|
+
"DocQLError",
|
|
36
|
+
"DocQLException",
|
|
37
|
+
"DocQLTimeoutError",
|
|
38
|
+
"MODE_FAST",
|
|
39
|
+
"MODE_STANDARD",
|
|
40
|
+
"Mode",
|
|
41
|
+
"QueryResult",
|
|
42
|
+
"REASON_BODY_NOT_JSON",
|
|
43
|
+
"REASON_CORRUPTED_FILE",
|
|
44
|
+
"REASON_DOCUMENT_EXCEEDS_TIME_BUDGET",
|
|
45
|
+
"REASON_INVALID_API_KEY",
|
|
46
|
+
"REASON_INVALID_PARAMS",
|
|
47
|
+
"REASON_MISSING_BODY_FIELD",
|
|
48
|
+
"REASON_MISSING_FILE_PART",
|
|
49
|
+
"REASON_MISSING_QUERY_OR_PROMPT",
|
|
50
|
+
"REASON_SERVICE_OVERLOADED",
|
|
51
|
+
"REASON_UNSUPPORTED_FILE_TYPE",
|
|
52
|
+
"REASON_UNSUPPORTED_MEDIA_TYPE",
|
|
53
|
+
"REASON_UPLOAD_TOO_LARGE",
|
|
54
|
+
"REASON_UPSTREAM_AUTH_FAILED",
|
|
55
|
+
"REASON_UPSTREAM_UNAVAILABLE",
|
|
56
|
+
"__version__",
|
|
57
|
+
]
|
docql/_client.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""The DocQL client: config resolution, per-request send, error mapping."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
from types import TracebackType
|
|
6
|
+
from typing import BinaryIO, Self
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from docql._constants import (
|
|
11
|
+
CONNECT_TIMEOUT,
|
|
12
|
+
DEFAULT_API_URL,
|
|
13
|
+
DEFAULT_TIMEOUT,
|
|
14
|
+
ENV_API_KEY,
|
|
15
|
+
ENV_API_URL,
|
|
16
|
+
ERROR_BODY_READ_LIMIT,
|
|
17
|
+
MAX_UPLOAD_BYTES,
|
|
18
|
+
QUERY_PATH,
|
|
19
|
+
)
|
|
20
|
+
from docql._errors import DocQLConnectionError, DocQLTimeoutError
|
|
21
|
+
from docql._request import Upload, _ShortReadError, prepare_upload
|
|
22
|
+
from docql._response import QueryResult, decode_error, parse_result
|
|
23
|
+
from docql._version import __version__
|
|
24
|
+
|
|
25
|
+
# h11/httpcore failures (a raw h11.LocalProtocolError is not an httpx type)
|
|
26
|
+
# are re-mapped by module origin so the undeclared h11 dependency is never
|
|
27
|
+
# imported (research Pitfall 1).
|
|
28
|
+
_INTERNAL_MODULE_ROOTS = ("h11", "httpcore")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _read_error_body(response: httpx.Response) -> bytes:
|
|
32
|
+
"""Read at most ``ERROR_BODY_READ_LIMIT`` bytes of a non-2xx body (T-11-12).
|
|
33
|
+
|
|
34
|
+
Slicing each chunk keeps the bound even when a transport yields chunks
|
|
35
|
+
larger than the limit; the caller closes the response right after.
|
|
36
|
+
"""
|
|
37
|
+
parts: list[bytes] = []
|
|
38
|
+
remaining = ERROR_BODY_READ_LIMIT
|
|
39
|
+
for chunk in response.iter_bytes():
|
|
40
|
+
if len(chunk) >= remaining:
|
|
41
|
+
parts.append(chunk[:remaining])
|
|
42
|
+
break
|
|
43
|
+
parts.append(chunk)
|
|
44
|
+
remaining -= len(chunk)
|
|
45
|
+
return b"".join(parts)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class DocQL:
|
|
49
|
+
"""Client for the DocQL document-extraction API.
|
|
50
|
+
|
|
51
|
+
Keyword-only construction (D-01): ``api_key`` then ``DOCQL_API_KEY``;
|
|
52
|
+
``api_url`` then ``DOCQL_API_URL`` (empty treated as unset) then the
|
|
53
|
+
production default. The key travels on each request, never as a client
|
|
54
|
+
default, and redirects are never followed, so it cannot leave the
|
|
55
|
+
configured host.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
*,
|
|
61
|
+
api_key: str | None = None,
|
|
62
|
+
api_url: str | None = None,
|
|
63
|
+
timeout: float | httpx.Timeout = DEFAULT_TIMEOUT,
|
|
64
|
+
http_client: httpx.Client | None = None,
|
|
65
|
+
) -> None:
|
|
66
|
+
key = api_key if api_key is not None else os.environ.get(ENV_API_KEY)
|
|
67
|
+
if key is None or not key.strip():
|
|
68
|
+
raise ValueError(
|
|
69
|
+
"DocQL API key missing: pass api_key= or set the "
|
|
70
|
+
f"{ENV_API_KEY} environment variable"
|
|
71
|
+
)
|
|
72
|
+
self._api_key = key
|
|
73
|
+
|
|
74
|
+
if api_url is not None:
|
|
75
|
+
url = api_url
|
|
76
|
+
else:
|
|
77
|
+
env_url = os.environ.get(ENV_API_URL, "")
|
|
78
|
+
url = env_url.strip() or DEFAULT_API_URL
|
|
79
|
+
if not url.lower().startswith(("http://", "https://")):
|
|
80
|
+
raise ValueError(
|
|
81
|
+
"DocQL api_url must be an http:// or https:// URL: pass "
|
|
82
|
+
f"api_url= or set {ENV_API_URL} (got {url!r})"
|
|
83
|
+
)
|
|
84
|
+
try:
|
|
85
|
+
httpx.URL(url)
|
|
86
|
+
except httpx.InvalidURL as exc:
|
|
87
|
+
raise ValueError(
|
|
88
|
+
"DocQL api_url is not a URL httpx can parse: pass api_url= "
|
|
89
|
+
f"or set {ENV_API_URL} (got {url!r})"
|
|
90
|
+
) from exc
|
|
91
|
+
self._api_url = url.rstrip("/")
|
|
92
|
+
|
|
93
|
+
if isinstance(timeout, httpx.Timeout):
|
|
94
|
+
self._timeout = timeout
|
|
95
|
+
elif isinstance(timeout, (int, float)) and not isinstance(timeout, bool):
|
|
96
|
+
# D-02 float form: read/write/pool = the float, connect stays 10 s.
|
|
97
|
+
self._timeout = httpx.Timeout(float(timeout), connect=CONNECT_TIMEOUT)
|
|
98
|
+
else:
|
|
99
|
+
raise TypeError(
|
|
100
|
+
"timeout must be a float (seconds) or an httpx.Timeout, "
|
|
101
|
+
f"not {type(timeout).__name__!r}"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
if http_client is not None:
|
|
105
|
+
self._client = http_client
|
|
106
|
+
self._owns_client = False
|
|
107
|
+
else:
|
|
108
|
+
self._client = httpx.Client(timeout=DEFAULT_TIMEOUT)
|
|
109
|
+
self._owns_client = True
|
|
110
|
+
|
|
111
|
+
def _scrub(self, text: str) -> str:
|
|
112
|
+
"""Keep the API key out of every message this client builds."""
|
|
113
|
+
return text.replace(self._api_key, "***")
|
|
114
|
+
|
|
115
|
+
def _connection_message(self, exc: Exception, upload: Upload) -> str:
|
|
116
|
+
if isinstance(exc, _ShortReadError):
|
|
117
|
+
text = f"the file changed size during upload: {exc}"
|
|
118
|
+
else:
|
|
119
|
+
text = f"connection to {self._api_url} failed: {type(exc).__name__}"
|
|
120
|
+
if upload.file_size is not None and upload.file_size > MAX_UPLOAD_BYTES:
|
|
121
|
+
text += f" (the upload is {upload.file_size} bytes; the API rejects files over 25 MiB)"
|
|
122
|
+
return self._scrub(text)
|
|
123
|
+
|
|
124
|
+
def query_document(
|
|
125
|
+
self,
|
|
126
|
+
file: str | os.PathLike[str] | bytes | BinaryIO,
|
|
127
|
+
*,
|
|
128
|
+
query: str | None = None,
|
|
129
|
+
prompt: str | None = None,
|
|
130
|
+
mode: str | None = None,
|
|
131
|
+
filename: str | None = None,
|
|
132
|
+
) -> QueryResult:
|
|
133
|
+
"""Upload one document and answer its extraction result (D-03/D-04).
|
|
134
|
+
|
|
135
|
+
``file`` is a path (``str`` or ``os.PathLike``), raw ``bytes``, or a
|
|
136
|
+
binary file object read from its current position and never closed
|
|
137
|
+
(D-13/D-16).
|
|
138
|
+
"""
|
|
139
|
+
with prepare_upload(
|
|
140
|
+
file, query=query, prompt=prompt, mode=mode, filename=filename
|
|
141
|
+
) as upload:
|
|
142
|
+
headers: dict[str, str] = {
|
|
143
|
+
"X-API-Key": self._api_key,
|
|
144
|
+
"Content-Type": upload.content_type,
|
|
145
|
+
"User-Agent": (
|
|
146
|
+
f"docql-python/{__version__} "
|
|
147
|
+
f"(python {platform.python_version()}; httpx {httpx.__version__})"
|
|
148
|
+
),
|
|
149
|
+
}
|
|
150
|
+
if upload.content_length is not None:
|
|
151
|
+
headers["Content-Length"] = str(upload.content_length)
|
|
152
|
+
request = self._client.build_request(
|
|
153
|
+
"POST",
|
|
154
|
+
self._api_url + QUERY_PATH,
|
|
155
|
+
content=upload.iter_bytes(),
|
|
156
|
+
headers=headers,
|
|
157
|
+
timeout=self._timeout,
|
|
158
|
+
)
|
|
159
|
+
# build_request merges an injected client's default headers; drop
|
|
160
|
+
# the forbidden ones so tenant headers never leave the process
|
|
161
|
+
# (T-11-05). The key stays a per-request header only.
|
|
162
|
+
for header_name in list(request.headers.keys()):
|
|
163
|
+
lowered = header_name.lower()
|
|
164
|
+
if lowered == "x-request-id" or lowered.startswith("x-docql-"):
|
|
165
|
+
del request.headers[header_name]
|
|
166
|
+
# One boundary around the send AND the body read (D-09): a timeout
|
|
167
|
+
# or transport failure raised while streaming the response body is
|
|
168
|
+
# mapped exactly like a send failure, so no httpx or h11 exception
|
|
169
|
+
# ever reaches the caller. Nothing here retries: calls are paid.
|
|
170
|
+
response: httpx.Response | None = None
|
|
171
|
+
body: bytes
|
|
172
|
+
try:
|
|
173
|
+
response = self._client.send(request, follow_redirects=False, stream=True)
|
|
174
|
+
body = (
|
|
175
|
+
response.read()
|
|
176
|
+
if 200 <= response.status_code < 300
|
|
177
|
+
else _read_error_body(response)
|
|
178
|
+
)
|
|
179
|
+
except httpx.TimeoutException as exc:
|
|
180
|
+
raise DocQLTimeoutError(
|
|
181
|
+
self._scrub(f"DocQL request timed out after {self._timeout}")
|
|
182
|
+
) from exc
|
|
183
|
+
except (_ShortReadError, httpx.RequestError) as exc:
|
|
184
|
+
raise DocQLConnectionError(self._connection_message(exc, upload)) from exc
|
|
185
|
+
except Exception as exc:
|
|
186
|
+
if type(exc).__module__.split(".", 1)[0] in _INTERNAL_MODULE_ROOTS:
|
|
187
|
+
raise DocQLConnectionError(self._connection_message(exc, upload)) from exc
|
|
188
|
+
raise
|
|
189
|
+
finally:
|
|
190
|
+
if response is not None:
|
|
191
|
+
response.close()
|
|
192
|
+
if 200 <= response.status_code < 300:
|
|
193
|
+
return parse_result(response.status_code, response.headers, body, self._api_key)
|
|
194
|
+
raise decode_error(response.status_code, response.headers, body, self._api_key)
|
|
195
|
+
|
|
196
|
+
def close(self) -> None:
|
|
197
|
+
"""Close the httpx client the SDK created; an injected one stays open (D-06)."""
|
|
198
|
+
if self._owns_client:
|
|
199
|
+
self._client.close()
|
|
200
|
+
|
|
201
|
+
def __enter__(self) -> Self:
|
|
202
|
+
return self
|
|
203
|
+
|
|
204
|
+
def __exit__(
|
|
205
|
+
self,
|
|
206
|
+
exc_type: type[BaseException] | None,
|
|
207
|
+
exc: BaseException | None,
|
|
208
|
+
tb: TracebackType | None,
|
|
209
|
+
) -> None:
|
|
210
|
+
self.close()
|
|
211
|
+
|
|
212
|
+
def __repr__(self) -> str:
|
|
213
|
+
return f"DocQL(api_url={self._api_url!r})"
|
docql/_constants.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Shared constants for the DocQL client."""
|
|
2
|
+
|
|
3
|
+
from typing import Final, Literal
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
DEFAULT_API_URL: Final[str] = "https://api-docql.finoniq.com"
|
|
8
|
+
ENV_API_KEY: Final[str] = "DOCQL_API_KEY"
|
|
9
|
+
ENV_API_URL: Final[str] = "DOCQL_API_URL"
|
|
10
|
+
QUERY_PATH: Final[str] = "/v1/query-document"
|
|
11
|
+
|
|
12
|
+
# Extraction modes (D-05): plain module-level constants plus a Literal alias.
|
|
13
|
+
# ``mode`` itself stays an open ``str`` everywhere — unknown values pass through
|
|
14
|
+
# for the server to validate.
|
|
15
|
+
MODE_FAST: Final[str] = "fast"
|
|
16
|
+
MODE_STANDARD: Final[str] = "standard"
|
|
17
|
+
Mode = Literal["fast", "standard"]
|
|
18
|
+
|
|
19
|
+
# Largest chunk one upload yields, keeping large files out of memory (T-11-09).
|
|
20
|
+
CHUNK_SIZE: Final[int] = 65536
|
|
21
|
+
|
|
22
|
+
# One timeout ladder for every request (D-02): 660 s read/write/pool over the
|
|
23
|
+
# engine's 540 s standard ceiling, 10 s connect.
|
|
24
|
+
CONNECT_TIMEOUT: Final[float] = 10.0
|
|
25
|
+
DEFAULT_TIMEOUT: Final[httpx.Timeout] = httpx.Timeout(660.0, connect=10.0)
|
|
26
|
+
|
|
27
|
+
# Kept characters of a non-2xx response body stored on DocQLError (D-11).
|
|
28
|
+
ERROR_BODY_KEEP_CHARS: Final[int] = 2048
|
|
29
|
+
|
|
30
|
+
# A non-2xx body is streamed and discarded after this many bytes, so a
|
|
31
|
+
# misbehaving proxy cannot exhaust memory (T-11-12).
|
|
32
|
+
ERROR_BODY_READ_LIMIT: Final[int] = 65536
|
|
33
|
+
|
|
34
|
+
# The API's upload ceiling; over this, transport failures gain a size hint
|
|
35
|
+
# because an early RST may have discarded the 413 (research Pitfall 4).
|
|
36
|
+
MAX_UPLOAD_BYTES: Final[int] = 26_214_400
|
|
37
|
+
|
|
38
|
+
# Reason constants (D-05): exactly the 14 the stub's REASON_TEXTS plus the
|
|
39
|
+
# gateway's ERROR_CLASSES produce, which equals the non-null reasons of the
|
|
40
|
+
# vendored contract/sdk-cases.json. The engine's wider class table stays
|
|
41
|
+
# reachable through the open ``reason: str``; adding constants later is
|
|
42
|
+
# backward compatible, removing them is not.
|
|
43
|
+
REASON_INVALID_API_KEY: Final[str] = "invalid_api_key"
|
|
44
|
+
REASON_UPLOAD_TOO_LARGE: Final[str] = "upload_too_large"
|
|
45
|
+
REASON_UNSUPPORTED_MEDIA_TYPE: Final[str] = "unsupported_media_type"
|
|
46
|
+
REASON_MISSING_FILE_PART: Final[str] = "missing_file_part"
|
|
47
|
+
REASON_MISSING_BODY_FIELD: Final[str] = "missing_body_field"
|
|
48
|
+
REASON_BODY_NOT_JSON: Final[str] = "body_not_json"
|
|
49
|
+
REASON_MISSING_QUERY_OR_PROMPT: Final[str] = "missing_query_or_prompt"
|
|
50
|
+
REASON_INVALID_PARAMS: Final[str] = "invalid_params"
|
|
51
|
+
REASON_UNSUPPORTED_FILE_TYPE: Final[str] = "unsupported_file_type"
|
|
52
|
+
REASON_CORRUPTED_FILE: Final[str] = "corrupted_file"
|
|
53
|
+
REASON_DOCUMENT_EXCEEDS_TIME_BUDGET: Final[str] = "document_exceeds_time_budget"
|
|
54
|
+
REASON_SERVICE_OVERLOADED: Final[str] = "service_overloaded"
|
|
55
|
+
REASON_UPSTREAM_UNAVAILABLE: Final[str] = "upstream_unavailable"
|
|
56
|
+
REASON_UPSTREAM_AUTH_FAILED: Final[str] = "upstream_auth_failed"
|
docql/_errors.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Exception tree for the DocQL client (D-09/D-11/D-12).
|
|
2
|
+
|
|
3
|
+
DocQLException(Exception)
|
|
4
|
+
├── DocQLError # the server answered non-2xx
|
|
5
|
+
└── DocQLConnectionError # no response: connect, TLS, reset, early RST
|
|
6
|
+
└── DocQLTimeoutError
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
_SNIPPET_MAX_CHARS = 200
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _snippet(body: str) -> str:
|
|
16
|
+
collapsed = " ".join(body.split())
|
|
17
|
+
if not collapsed:
|
|
18
|
+
return "(empty body)"
|
|
19
|
+
return collapsed[:_SNIPPET_MAX_CHARS]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DocQLException(Exception):
|
|
23
|
+
"""Base class for every exception the DocQL client raises."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DocQLError(DocQLException):
|
|
27
|
+
"""The DocQL API answered with a non-2xx status (D-11/D-12).
|
|
28
|
+
|
|
29
|
+
Neither :func:`str` nor :func:`repr` ever contains anything beyond the
|
|
30
|
+
stored fields, and ``body`` is scrubbed by the decoder before it is
|
|
31
|
+
stored, so no form leaks the API key.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
status: int,
|
|
38
|
+
reason: str | None,
|
|
39
|
+
request_id: str | None,
|
|
40
|
+
retry_after: int | None,
|
|
41
|
+
retryable: bool,
|
|
42
|
+
message: str | None,
|
|
43
|
+
body: str,
|
|
44
|
+
) -> None:
|
|
45
|
+
super().__init__()
|
|
46
|
+
self.status = status
|
|
47
|
+
self.reason = reason
|
|
48
|
+
self.request_id = request_id
|
|
49
|
+
self.retry_after = retry_after
|
|
50
|
+
self.retryable = retryable
|
|
51
|
+
self.message = message
|
|
52
|
+
self.body = body
|
|
53
|
+
|
|
54
|
+
def __str__(self) -> str:
|
|
55
|
+
if self.reason is not None:
|
|
56
|
+
text = f"{self.status} {self.reason}"
|
|
57
|
+
if self.message is not None:
|
|
58
|
+
text = f"{text}: {self.message}"
|
|
59
|
+
extras = []
|
|
60
|
+
if self.request_id is not None:
|
|
61
|
+
extras.append(f"request_id={self.request_id}")
|
|
62
|
+
if self.retry_after is not None:
|
|
63
|
+
extras.append(f"retry_after={self.retry_after}s")
|
|
64
|
+
if extras:
|
|
65
|
+
text = f"{text} ({', '.join(extras)})"
|
|
66
|
+
return text
|
|
67
|
+
text = f"{self.status} (non-DocQL response): {_snippet(self.body)}"
|
|
68
|
+
if self.request_id is not None:
|
|
69
|
+
text = f"{text} (request_id={self.request_id})"
|
|
70
|
+
return text
|
|
71
|
+
|
|
72
|
+
def __repr__(self) -> str:
|
|
73
|
+
return (
|
|
74
|
+
f"{type(self).__name__}(status={self.status!r}, "
|
|
75
|
+
f"reason={self.reason!r}, request_id={self.request_id!r})"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def __reduce__(self) -> tuple[Callable[[dict[str, Any]], "DocQLError"], tuple[dict[str, Any]]]:
|
|
79
|
+
# Keyword-only __init__ does not pickle by default; rebuild through a
|
|
80
|
+
# module-level callable so pickle.loads(pickle.dumps(err)) round-trips.
|
|
81
|
+
return _rebuild_docql_error, (
|
|
82
|
+
{
|
|
83
|
+
"status": self.status,
|
|
84
|
+
"reason": self.reason,
|
|
85
|
+
"request_id": self.request_id,
|
|
86
|
+
"retry_after": self.retry_after,
|
|
87
|
+
"retryable": self.retryable,
|
|
88
|
+
"message": self.message,
|
|
89
|
+
"body": self.body,
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _rebuild_docql_error(fields: dict[str, Any]) -> DocQLError:
|
|
95
|
+
return DocQLError(**fields)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class DocQLConnectionError(DocQLException):
|
|
99
|
+
"""No DocQL response arrived: connect, TLS, reset or early connection close."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, message: str) -> None:
|
|
102
|
+
super().__init__(message)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class DocQLTimeoutError(DocQLConnectionError):
|
|
106
|
+
"""The DocQL request timed out. The call may still have been billed."""
|
docql/_request.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Transport-independent multipart request building.
|
|
2
|
+
|
|
3
|
+
The wire format is byte-exact with the golden fixtures (D-01..D-03 of the
|
|
4
|
+
shared contract): part order ``file`` then ``body``, only the double quote,
|
|
5
|
+
CR and LF escaped in the filename, compact canonical UTF-8 JSON for the body
|
|
6
|
+
part, CRLF line endings everywhere.
|
|
7
|
+
|
|
8
|
+
httpx's own multipart encoder is deliberately not used: it emits ``data``
|
|
9
|
+
fields before ``files``, escapes a different character set and rewinds the
|
|
10
|
+
caller's file object. The framing here is built by hand; everything stateful
|
|
11
|
+
(TLS, pooling, timeouts) stays in the transport.
|
|
12
|
+
|
|
13
|
+
File inputs (D-13): ``str`` and ``os.PathLike`` mean a path, ``bytes`` mean
|
|
14
|
+
contents, any other object is a binary file object only when its ``read()``
|
|
15
|
+
returns ``bytes``. A caller's file object is read from its current position
|
|
16
|
+
and never closed (D-16); a file the SDK opened from a path is closed by
|
|
17
|
+
:class:`Upload`. Validation completes before a path is opened or a byte is
|
|
18
|
+
sent.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import builtins
|
|
22
|
+
import io
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import secrets
|
|
26
|
+
from collections.abc import Iterator
|
|
27
|
+
from types import TracebackType
|
|
28
|
+
from typing import BinaryIO, Self
|
|
29
|
+
|
|
30
|
+
from docql._constants import CHUNK_SIZE
|
|
31
|
+
|
|
32
|
+
TYPE_ERROR_TEXT = "file must be a path (str or os.PathLike), bytes, or a binary file object"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _ShortReadError(Exception):
|
|
36
|
+
"""A measured file yielded fewer bytes than its declared length."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def new_boundary() -> str:
|
|
40
|
+
"""Return a fresh random multipart boundary (tests monkeypatch this)."""
|
|
41
|
+
return secrets.token_hex(16)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def escape_filename(name: str) -> str:
|
|
45
|
+
"""Escape only ``"``, CR and LF in a form filename (D-02 of the contract)."""
|
|
46
|
+
return name.replace('"', "%22").replace("\r", "%0D").replace("\n", "%0A")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def body_json(query: str | None, prompt: str | None, mode: str | None) -> bytes:
|
|
50
|
+
"""Encode the body part JSON: query or prompt first, params only when set."""
|
|
51
|
+
doc: dict[str, object] = {}
|
|
52
|
+
if query is not None:
|
|
53
|
+
doc["query"] = query
|
|
54
|
+
if prompt is not None:
|
|
55
|
+
doc["prompt"] = prompt
|
|
56
|
+
if mode is not None:
|
|
57
|
+
doc["params"] = {"mode": mode}
|
|
58
|
+
return json.dumps(doc, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def frame(filename: str, body: bytes, boundary: str) -> tuple[bytes, bytes]:
|
|
62
|
+
"""Return the (preamble, epilogue) framing around the file bytes."""
|
|
63
|
+
preamble = (
|
|
64
|
+
f"--{boundary}\r\n"
|
|
65
|
+
f'Content-Disposition: form-data; name="file"; '
|
|
66
|
+
f'filename="{escape_filename(filename)}"\r\n'
|
|
67
|
+
"Content-Type: application/octet-stream\r\n\r\n"
|
|
68
|
+
).encode()
|
|
69
|
+
epilogue = (
|
|
70
|
+
(f'\r\n--{boundary}\r\nContent-Disposition: form-data; name="body"\r\n\r\n').encode()
|
|
71
|
+
+ body
|
|
72
|
+
+ f"\r\n--{boundary}--\r\n".encode()
|
|
73
|
+
)
|
|
74
|
+
return preamble, epilogue
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def open(path: str) -> BinaryIO:
|
|
78
|
+
"""Open a path for binary reading (a seam tests wrap to track closes)."""
|
|
79
|
+
# builtins.open because this module-level name IS the seam under test.
|
|
80
|
+
return builtins.open(path, "rb")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _is_binary_stream(obj: object) -> bool:
|
|
84
|
+
"""True for a readable binary file object (D-15): callable read() returning bytes."""
|
|
85
|
+
if isinstance(obj, io.TextIOBase):
|
|
86
|
+
return False
|
|
87
|
+
read = getattr(obj, "read", None)
|
|
88
|
+
if not callable(read):
|
|
89
|
+
return False
|
|
90
|
+
try:
|
|
91
|
+
probe = read(0)
|
|
92
|
+
except Exception:
|
|
93
|
+
return False
|
|
94
|
+
return isinstance(probe, bytes)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _remaining_length(stream: BinaryIO) -> int | None:
|
|
98
|
+
"""Bytes left in a caller's file object, or None when unmeasurable.
|
|
99
|
+
|
|
100
|
+
The object is only ever moved relative to its own current position
|
|
101
|
+
(D-16): one tell, one seek to the end and one seek back.
|
|
102
|
+
io.UnsupportedOperation subclasses OSError and ValueError, so catching
|
|
103
|
+
those two covers it.
|
|
104
|
+
"""
|
|
105
|
+
try:
|
|
106
|
+
seekable = getattr(stream, "seekable", None)
|
|
107
|
+
if seekable is not None and not seekable():
|
|
108
|
+
return None
|
|
109
|
+
pos = stream.tell()
|
|
110
|
+
end = stream.seek(0, os.SEEK_END)
|
|
111
|
+
stream.seek(pos)
|
|
112
|
+
except (AttributeError, OSError, ValueError):
|
|
113
|
+
return None
|
|
114
|
+
if not isinstance(end, int):
|
|
115
|
+
return None
|
|
116
|
+
return end - pos
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Upload:
|
|
120
|
+
"""A framed multipart upload, streamable as request content (D-09 wire rules).
|
|
121
|
+
|
|
122
|
+
``content_length`` is the exact byte count ``iter_bytes`` yields when the
|
|
123
|
+
file length is known, so the transport sends a ``Content-Length`` header
|
|
124
|
+
and never chunked framing; ``None`` means the length could not be
|
|
125
|
+
measured and the transport falls back to chunked encoding.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def __init__(
|
|
129
|
+
self,
|
|
130
|
+
filename: str,
|
|
131
|
+
body: bytes,
|
|
132
|
+
boundary: str,
|
|
133
|
+
source: bytes | BinaryIO,
|
|
134
|
+
file_size: int | None,
|
|
135
|
+
own_file: BinaryIO | None,
|
|
136
|
+
) -> None:
|
|
137
|
+
self._preamble, self._epilogue = frame(filename, body, boundary)
|
|
138
|
+
self._source = source
|
|
139
|
+
self._file_size = file_size
|
|
140
|
+
self._own_file = own_file
|
|
141
|
+
self.content_type = f"multipart/form-data; boundary={boundary}"
|
|
142
|
+
self.content_length: int | None = (
|
|
143
|
+
len(self._preamble) + file_size + len(self._epilogue) if file_size is not None else None
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def file_size(self) -> int | None:
|
|
148
|
+
"""The measured file length, when known (framing excluded)."""
|
|
149
|
+
return self._file_size
|
|
150
|
+
|
|
151
|
+
def iter_bytes(self) -> Iterator[bytes]:
|
|
152
|
+
"""Yield the preamble, the file bytes in bounded chunks, the epilogue."""
|
|
153
|
+
yield self._preamble
|
|
154
|
+
source = self._source
|
|
155
|
+
if isinstance(source, bytes):
|
|
156
|
+
for start in range(0, len(source), CHUNK_SIZE):
|
|
157
|
+
yield source[start : start + CHUNK_SIZE]
|
|
158
|
+
elif self._file_size is not None:
|
|
159
|
+
# Read exactly the measured length: a file that grew never
|
|
160
|
+
# over-sends, and one that shrank raises instead of undersending.
|
|
161
|
+
left = self._file_size
|
|
162
|
+
while left > 0:
|
|
163
|
+
chunk = source.read(min(CHUNK_SIZE, left))
|
|
164
|
+
if not chunk:
|
|
165
|
+
raise _ShortReadError(
|
|
166
|
+
f"short read: {left} of {self._file_size} measured bytes missing"
|
|
167
|
+
)
|
|
168
|
+
part = chunk[:left]
|
|
169
|
+
yield part
|
|
170
|
+
left -= len(part)
|
|
171
|
+
else:
|
|
172
|
+
while True:
|
|
173
|
+
chunk = source.read(CHUNK_SIZE)
|
|
174
|
+
if not chunk:
|
|
175
|
+
break
|
|
176
|
+
yield chunk
|
|
177
|
+
yield self._epilogue
|
|
178
|
+
|
|
179
|
+
def close(self) -> None:
|
|
180
|
+
"""Close a file the SDK opened from a path; never a caller's object (D-16)."""
|
|
181
|
+
if self._own_file is not None:
|
|
182
|
+
self._own_file.close()
|
|
183
|
+
|
|
184
|
+
def __enter__(self) -> Self:
|
|
185
|
+
return self
|
|
186
|
+
|
|
187
|
+
def __exit__(
|
|
188
|
+
self,
|
|
189
|
+
exc_type: type[BaseException] | None,
|
|
190
|
+
exc: BaseException | None,
|
|
191
|
+
tb: TracebackType | None,
|
|
192
|
+
) -> None:
|
|
193
|
+
self.close()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def prepare_upload(
|
|
197
|
+
file: str | os.PathLike[str] | bytes | BinaryIO,
|
|
198
|
+
*,
|
|
199
|
+
query: str | None,
|
|
200
|
+
prompt: str | None,
|
|
201
|
+
mode: str | None,
|
|
202
|
+
filename: str | None,
|
|
203
|
+
) -> Upload:
|
|
204
|
+
"""Validate the call, resolve the input kind and frame the upload (D-13..D-17).
|
|
205
|
+
|
|
206
|
+
The filename rule (D-14): explicit ``filename`` wins verbatim, then a
|
|
207
|
+
path's basename, then the basename of a ``str`` ``.name``; anything else
|
|
208
|
+
needs ``filename=`` and there is no default filename. Every rule is
|
|
209
|
+
checked before a path is opened or a byte is sent.
|
|
210
|
+
"""
|
|
211
|
+
if (query is None) == (prompt is None):
|
|
212
|
+
raise ValueError("pass exactly one of query= or prompt=")
|
|
213
|
+
|
|
214
|
+
path: str | None = None
|
|
215
|
+
contents: bytes | None = None
|
|
216
|
+
stream: BinaryIO | None = None
|
|
217
|
+
if isinstance(file, os.PathLike):
|
|
218
|
+
fspath = os.fspath(file)
|
|
219
|
+
if isinstance(fspath, bytes):
|
|
220
|
+
raise TypeError("a bytes path is not supported: pass a str path or os.PathLike[str]")
|
|
221
|
+
path = fspath
|
|
222
|
+
elif isinstance(file, str):
|
|
223
|
+
path = file
|
|
224
|
+
elif isinstance(file, bytes):
|
|
225
|
+
contents = file
|
|
226
|
+
elif isinstance(file, (bytearray, memoryview)):
|
|
227
|
+
raise TypeError(f"pass bytes for the file contents, not {type(file).__name__!r}")
|
|
228
|
+
elif _is_binary_stream(file):
|
|
229
|
+
stream = file
|
|
230
|
+
else:
|
|
231
|
+
raise TypeError(TYPE_ERROR_TEXT)
|
|
232
|
+
|
|
233
|
+
if filename is not None:
|
|
234
|
+
part_name = filename
|
|
235
|
+
elif path is not None:
|
|
236
|
+
part_name = os.path.basename(path)
|
|
237
|
+
elif stream is not None:
|
|
238
|
+
object_name = getattr(stream, "name", None)
|
|
239
|
+
if isinstance(object_name, str):
|
|
240
|
+
part_name = os.path.basename(object_name)
|
|
241
|
+
else:
|
|
242
|
+
raise ValueError(
|
|
243
|
+
"a file object without a str .name needs filename= to name the file part"
|
|
244
|
+
)
|
|
245
|
+
else:
|
|
246
|
+
raise ValueError("bytes input needs filename= to name the file part")
|
|
247
|
+
|
|
248
|
+
source: bytes | BinaryIO
|
|
249
|
+
own_file: BinaryIO | None = None
|
|
250
|
+
file_size: int | None
|
|
251
|
+
if path is not None:
|
|
252
|
+
opened = open(path)
|
|
253
|
+
own_file = opened
|
|
254
|
+
file_size = os.fstat(opened.fileno()).st_size
|
|
255
|
+
source = opened
|
|
256
|
+
elif contents is not None:
|
|
257
|
+
file_size = len(contents)
|
|
258
|
+
source = contents
|
|
259
|
+
else:
|
|
260
|
+
assert stream is not None
|
|
261
|
+
source = stream
|
|
262
|
+
file_size = _remaining_length(stream)
|
|
263
|
+
|
|
264
|
+
return Upload(
|
|
265
|
+
part_name, body_json(query, prompt, mode), new_boundary(), source, file_size, own_file
|
|
266
|
+
)
|
docql/_response.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Transport-independent response decoding (D-04, D-10..D-12).
|
|
2
|
+
|
|
3
|
+
Both functions take ``(status, headers, body_bytes)`` so the same decode path
|
|
4
|
+
serves the sync client, raw contract replays and a future async client.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from email.utils import parsedate_to_datetime
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from docql._constants import ERROR_BODY_KEEP_CHARS
|
|
16
|
+
from docql._errors import DocQLError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class QueryResult:
|
|
21
|
+
"""A successful query answer (D-04). Unknown fields pass through."""
|
|
22
|
+
|
|
23
|
+
data: dict[str, Any]
|
|
24
|
+
request_id: str
|
|
25
|
+
page_count: int | None
|
|
26
|
+
pages_ocr: int | None
|
|
27
|
+
metadata: dict[str, Any]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _header(headers: Mapping[str, str], name: str) -> str | None:
|
|
31
|
+
for key, value in headers.items():
|
|
32
|
+
if key.lower() == name:
|
|
33
|
+
return value
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _int_or_none(value: Any) -> int | None:
|
|
38
|
+
# bool is an int subclass; the contract counts exact integers only.
|
|
39
|
+
return value if type(value) is int else None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _scrub_and_truncate(text: str, api_key: str) -> str:
|
|
43
|
+
"""Replace every occurrence of the key, then keep the first chars (D-11).
|
|
44
|
+
|
|
45
|
+
Scrubbing before truncating means a key straddling the cut can never
|
|
46
|
+
survive as a fragment.
|
|
47
|
+
"""
|
|
48
|
+
if api_key:
|
|
49
|
+
text = text.replace(api_key, "***")
|
|
50
|
+
return text[:ERROR_BODY_KEEP_CHARS]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse_retry_after(value: str | None, now: datetime | None = None) -> int | None:
|
|
54
|
+
"""``Retry-After`` as whole seconds, or None when absent/unparsable.
|
|
55
|
+
|
|
56
|
+
Delta-seconds pass through as an int. An HTTP-date is converted to the
|
|
57
|
+
seconds from ``now`` (default: current UTC time) rounded up with
|
|
58
|
+
:func:`math.ceil` and clamped at 0, so a date in the past means "retry
|
|
59
|
+
now" rather than a negative sleep.
|
|
60
|
+
"""
|
|
61
|
+
if value is None:
|
|
62
|
+
return None
|
|
63
|
+
text = value.strip()
|
|
64
|
+
if text.isascii() and text.isdigit():
|
|
65
|
+
return int(text)
|
|
66
|
+
try:
|
|
67
|
+
parsed = parsedate_to_datetime(text)
|
|
68
|
+
except (TypeError, ValueError, IndexError):
|
|
69
|
+
return None
|
|
70
|
+
if parsed.tzinfo is None:
|
|
71
|
+
# An RFC 5322 "-0000" zone means "unknown local time"; assume UTC.
|
|
72
|
+
parsed = parsed.replace(tzinfo=UTC)
|
|
73
|
+
reference = now if now is not None else datetime.now(UTC)
|
|
74
|
+
if reference.tzinfo is None:
|
|
75
|
+
reference = reference.replace(tzinfo=UTC)
|
|
76
|
+
return max(0, math.ceil((parsed - reference).total_seconds()))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _unusable_result(
|
|
80
|
+
status: int,
|
|
81
|
+
headers: Mapping[str, str],
|
|
82
|
+
body: bytes,
|
|
83
|
+
api_key: str,
|
|
84
|
+
message: str,
|
|
85
|
+
) -> DocQLError:
|
|
86
|
+
"""The error for a 2xx body the SDK cannot decode (research OQ 3/4)."""
|
|
87
|
+
return DocQLError(
|
|
88
|
+
status=status,
|
|
89
|
+
reason=None,
|
|
90
|
+
request_id=_header(headers, "x-request-id"),
|
|
91
|
+
retry_after=None,
|
|
92
|
+
retryable=False,
|
|
93
|
+
message=message,
|
|
94
|
+
body=_scrub_and_truncate(body.decode("utf-8", "replace"), api_key),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def parse_result(
|
|
99
|
+
status: int,
|
|
100
|
+
headers: Mapping[str, str],
|
|
101
|
+
body: bytes,
|
|
102
|
+
api_key: str,
|
|
103
|
+
) -> QueryResult:
|
|
104
|
+
"""Decode a 2xx DocQL envelope into a :class:`QueryResult`.
|
|
105
|
+
|
|
106
|
+
A body that is not a JSON object, or whose ``data`` is present, non-null
|
|
107
|
+
and not an object, is unusable: it raises :class:`DocQLError` naming the
|
|
108
|
+
problem instead of silently answering with empty data. ``api_key`` scrubs
|
|
109
|
+
the body stored on that error, symmetric with :func:`decode_error`.
|
|
110
|
+
"""
|
|
111
|
+
try:
|
|
112
|
+
doc: Any = json.loads(body)
|
|
113
|
+
except ValueError:
|
|
114
|
+
doc = None
|
|
115
|
+
if not isinstance(doc, dict):
|
|
116
|
+
raise _unusable_result(status, headers, body, api_key, "unexpected non-JSON response")
|
|
117
|
+
if "data" in doc and doc["data"] is not None and not isinstance(doc["data"], dict):
|
|
118
|
+
raise _unusable_result(
|
|
119
|
+
status, headers, body, api_key, "unexpected response: data is not a JSON object"
|
|
120
|
+
)
|
|
121
|
+
data = doc.get("data")
|
|
122
|
+
if not isinstance(data, dict):
|
|
123
|
+
data = {}
|
|
124
|
+
metadata = doc.get("metadata")
|
|
125
|
+
if not isinstance(metadata, dict):
|
|
126
|
+
metadata = {}
|
|
127
|
+
request_id = metadata.get("request_id")
|
|
128
|
+
if not isinstance(request_id, str):
|
|
129
|
+
request_id = _header(headers, "x-request-id") or ""
|
|
130
|
+
return QueryResult(
|
|
131
|
+
data=data,
|
|
132
|
+
request_id=request_id,
|
|
133
|
+
page_count=_int_or_none(metadata.get("page_count")),
|
|
134
|
+
pages_ocr=_int_or_none(metadata.get("pages_ocr")),
|
|
135
|
+
metadata=metadata,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def decode_error(
|
|
140
|
+
status: int,
|
|
141
|
+
headers: Mapping[str, str],
|
|
142
|
+
body: bytes,
|
|
143
|
+
api_key: str,
|
|
144
|
+
) -> DocQLError:
|
|
145
|
+
"""Decode a non-2xx response into a :class:`DocQLError`.
|
|
146
|
+
|
|
147
|
+
Classification is by status, never by body shape. An envelope is present
|
|
148
|
+
only when the JSON body is a dict whose ``metadata`` is a dict with a str
|
|
149
|
+
``reason``. Neither the stored ``body`` nor ``message`` ever contains the
|
|
150
|
+
API key, even when the server echoes it back.
|
|
151
|
+
"""
|
|
152
|
+
reason: str | None = None
|
|
153
|
+
message: str | None = None
|
|
154
|
+
request_id: str | None = None
|
|
155
|
+
try:
|
|
156
|
+
doc: Any = json.loads(body)
|
|
157
|
+
except ValueError:
|
|
158
|
+
doc = None
|
|
159
|
+
if isinstance(doc, dict):
|
|
160
|
+
metadata = doc.get("metadata")
|
|
161
|
+
if isinstance(metadata, dict) and isinstance(metadata.get("reason"), str):
|
|
162
|
+
reason = metadata["reason"]
|
|
163
|
+
error_info = doc.get("error_info")
|
|
164
|
+
if isinstance(error_info, str):
|
|
165
|
+
message = error_info
|
|
166
|
+
raw_id = metadata.get("request_id")
|
|
167
|
+
if isinstance(raw_id, str):
|
|
168
|
+
request_id = raw_id
|
|
169
|
+
if request_id is None:
|
|
170
|
+
request_id = _header(headers, "x-request-id")
|
|
171
|
+
|
|
172
|
+
retry_after = parse_retry_after(_header(headers, "retry-after"))
|
|
173
|
+
|
|
174
|
+
if message is not None and api_key:
|
|
175
|
+
message = message.replace(api_key, "***")
|
|
176
|
+
|
|
177
|
+
return DocQLError(
|
|
178
|
+
status=status,
|
|
179
|
+
reason=reason,
|
|
180
|
+
request_id=request_id,
|
|
181
|
+
retry_after=retry_after,
|
|
182
|
+
retryable=status in (429, 503),
|
|
183
|
+
message=message,
|
|
184
|
+
body=_scrub_and_truncate(body.decode("utf-8", "replace"), api_key),
|
|
185
|
+
)
|
docql/_version.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Package version, read from installed metadata (D-08).
|
|
2
|
+
|
|
3
|
+
The version is never a hand-edited constant: an installed distribution answers
|
|
4
|
+
through importlib.metadata, and a source checkout without metadata falls back
|
|
5
|
+
to a clearly non-release string.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
9
|
+
|
|
10
|
+
__version__: str
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
__version__ = version("docql")
|
|
14
|
+
except PackageNotFoundError: # pragma: no cover - source checkout without metadata
|
|
15
|
+
__version__ = "0+unknown"
|
docql/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: docql
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the DocQL document-extraction API
|
|
5
|
+
Author: Finoniq
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Typing :: Typed
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Dist: httpx>=0.27,<1
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Project-URL: Homepage, https://github.com/finoniq/docql-python
|
|
18
|
+
Project-URL: Repository, https://github.com/finoniq/docql-python
|
|
19
|
+
Project-URL: Issues, https://github.com/finoniq/docql-python/issues
|
|
20
|
+
Project-URL: Changelog, https://github.com/finoniq/docql-python/releases
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# DocQL Python SDK
|
|
24
|
+
|
|
25
|
+
A Python client for the DocQL document-extraction API (`POST /v1/query-document`).
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pip install docql
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Requirements
|
|
34
|
+
|
|
35
|
+
- Python 3.11 or newer
|
|
36
|
+
- httpx `>=0.27,<1` (installed with the SDK)
|
|
37
|
+
|
|
38
|
+
## Quickstart
|
|
39
|
+
|
|
40
|
+
Set `DOCQL_API_KEY`, and set `DOCQL_API_URL` to the API origin you were given — the production endpoint `https://api-docql.finoniq.com` is not live yet.
|
|
41
|
+
|
|
42
|
+
<!-- docql:quickstart:start -->
|
|
43
|
+
```python
|
|
44
|
+
from docql import DocQL
|
|
45
|
+
|
|
46
|
+
with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
47
|
+
result = client.query_document("invoice.pdf", query="{ invoice_number total_amount }")
|
|
48
|
+
print(result.request_id, result.page_count)
|
|
49
|
+
print(result.data)
|
|
50
|
+
```
|
|
51
|
+
<!-- docql:quickstart:end -->
|
|
52
|
+
|
|
53
|
+
The query uses DocQL's brace-and-field syntax; pass `prompt=` instead for a
|
|
54
|
+
natural-language instruction. A call takes exactly one of `query` or `prompt`.
|
|
55
|
+
|
|
56
|
+
## Configuration
|
|
57
|
+
|
|
58
|
+
| Keyword | Env variable | Default | Notes |
|
|
59
|
+
| --- | --- | --- | --- |
|
|
60
|
+
| `api_key` | `DOCQL_API_KEY` | none | required; `ValueError` at construction when neither is set |
|
|
61
|
+
| `api_url` | `DOCQL_API_URL` | `https://api-docql.finoniq.com` | trailing `/` ignored; `http://` allowed for local stacks; the default is not live yet |
|
|
62
|
+
| `timeout` | — | 660 s read / 10 s connect | a number sets read/write/pool; an `httpx.Timeout` gives full control; applied to every request, even with an injected client |
|
|
63
|
+
| `http_client` | — | none | an injected `httpx.Client` is never closed by the SDK; the SDK still sets its own timeout per request and never follows redirects |
|
|
64
|
+
|
|
65
|
+
Keyword arguments win over the environment variables. A missing key raises
|
|
66
|
+
`ValueError` before any upload.
|
|
67
|
+
|
|
68
|
+
**Local stacks behind Caddy `tls internal`:** the local CA is private and httpx
|
|
69
|
+
does not trust it. Export the root certificate path in `SSL_CERT_FILE`, or
|
|
70
|
+
inject a client that trusts it explicitly:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import ssl
|
|
74
|
+
|
|
75
|
+
import httpx
|
|
76
|
+
from docql import DocQL
|
|
77
|
+
|
|
78
|
+
client = DocQL(http_client=httpx.Client(verify=ssl.create_default_context(cafile="root.crt")))
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Pass an `ssl.SSLContext`, not a path string — httpx 0.28 deprecates
|
|
82
|
+
`verify="<path>"`. Never disable certificate verification.
|
|
83
|
+
|
|
84
|
+
## Files
|
|
85
|
+
|
|
86
|
+
`query_document` accepts a path (`str` or `os.PathLike`), raw `bytes`, or a
|
|
87
|
+
binary file object:
|
|
88
|
+
|
|
89
|
+
- The filename rule: an explicit `filename=` is sent verbatim; otherwise a path
|
|
90
|
+
uses its basename; otherwise a file object uses the basename of its `.name`.
|
|
91
|
+
`bytes` and unnamed streams need `filename=` — there is no default filename.
|
|
92
|
+
- A file object is read from its current position and never closed. A file the
|
|
93
|
+
SDK opened from a path is closed by the SDK.
|
|
94
|
+
- There are no client-side type or size checks — the server is the authority.
|
|
95
|
+
- A stream whose length cannot be measured is sent chunked; an oversized one
|
|
96
|
+
may answer `503` instead of `413`. The API rejects files over 25 MiB.
|
|
97
|
+
|
|
98
|
+
## Modes
|
|
99
|
+
|
|
100
|
+
`docql.MODE_FAST` and `docql.MODE_STANDARD` name the two processing modes.
|
|
101
|
+
`mode` is passed through and validated by the server; omitting it means the
|
|
102
|
+
server default.
|
|
103
|
+
|
|
104
|
+
## Errors
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
DocQLException
|
|
108
|
+
├── DocQLError # the server answered non-2xx
|
|
109
|
+
└── DocQLConnectionError # no response arrived
|
|
110
|
+
└── DocQLTimeoutError # the request timed out
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`DocQLError` carries `status`, `reason`, `request_id`, `retry_after`,
|
|
114
|
+
`retryable`, `message` (the envelope's `error_info`) and `body` (the response
|
|
115
|
+
text, truncated to about 2 KB). Every reason below is also exported as a
|
|
116
|
+
`docql.REASON_*` constant (`invalid_api_key` is
|
|
117
|
+
`docql.REASON_INVALID_API_KEY`).
|
|
118
|
+
|
|
119
|
+
| Status | Reason | What to do |
|
|
120
|
+
| --- | --- | --- |
|
|
121
|
+
| 401 | `invalid_api_key` | the key is wrong or revoked — check `DOCQL_API_KEY` or issue a new key |
|
|
122
|
+
| 413 | `upload_too_large` | the file exceeds the API limit (25 MiB) — shrink or split it |
|
|
123
|
+
| 415 | `unsupported_media_type` | the request was not multipart/form-data — send it through `query_document` |
|
|
124
|
+
| 422 | `missing_file_part` | the multipart body has no file part |
|
|
125
|
+
| 422 | `missing_body_field` | the multipart body has no `body` form field |
|
|
126
|
+
| 422 | `body_not_json` | the `body` form field is not valid JSON |
|
|
127
|
+
| 422 | `missing_query_or_prompt` | pass exactly one of `query=` or `prompt=` |
|
|
128
|
+
| 422 | `invalid_params` | check the parameters — for example an unknown `mode` |
|
|
129
|
+
| 422 | `unsupported_file_type` | the API does not accept this file type |
|
|
130
|
+
| 422 | `corrupted_file` | the file could not be parsed |
|
|
131
|
+
| 422 | `document_exceeds_time_budget` | the document is too large for the mode — try `docql.MODE_STANDARD` or split it |
|
|
132
|
+
| 429 | `service_overloaded` | retryable — wait `retry_after` seconds and retry |
|
|
133
|
+
| 502 | `upstream_auth_failed` | not retryable — quote `request_id` when contacting support |
|
|
134
|
+
| 503 | `upstream_unavailable` | retryable — wait `retry_after` seconds and retry |
|
|
135
|
+
| any | any other reason | read `message`; only 429 and 503 set `retryable` |
|
|
136
|
+
| any | `reason` is `None` | a non-DocQL response: a framework 404/405 means a wrong `api_url`; an empty 5xx or an HTML 524 from an edge means the call may still have been processed |
|
|
137
|
+
|
|
138
|
+
## Retrying
|
|
139
|
+
|
|
140
|
+
The SDK never retries — every call is billed. Retry yourself, only on
|
|
141
|
+
`retryable` errors, sleeping `retry_after` when the server sent one and a
|
|
142
|
+
capped exponential backoff otherwise:
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
import time
|
|
146
|
+
|
|
147
|
+
from docql import DocQL, DocQLError
|
|
148
|
+
|
|
149
|
+
client = DocQL()
|
|
150
|
+
attempt = 0
|
|
151
|
+
while True:
|
|
152
|
+
try:
|
|
153
|
+
result = client.query_document("invoice.pdf", query="{ invoice_number total_amount }")
|
|
154
|
+
break
|
|
155
|
+
except DocQLError as err:
|
|
156
|
+
attempt += 1
|
|
157
|
+
if not err.retryable or attempt >= 5:
|
|
158
|
+
raise
|
|
159
|
+
time.sleep(err.retry_after if err.retry_after is not None else min(2**attempt, 30))
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Timeouts and billing
|
|
163
|
+
|
|
164
|
+
Usage is metered in pages. A timed-out call may still have been billed — the
|
|
165
|
+
server may finish the work after the client gave up. For the same reason,
|
|
166
|
+
502/504/524 answers are not `retryable`: only 429 and 503 are, because those
|
|
167
|
+
two mean the request was not processed.
|
|
168
|
+
|
|
169
|
+
## Versioning
|
|
170
|
+
|
|
171
|
+
The SDK follows [Semantic Versioning](https://semver.org/). While the major
|
|
172
|
+
version is 0, a minor release may change the API; pin `docql>=0.1,<0.2` until
|
|
173
|
+
1.0.
|
|
174
|
+
|
|
175
|
+
## Support
|
|
176
|
+
|
|
177
|
+
When asking for help, quote the `request_id` — `result.request_id` on success,
|
|
178
|
+
`err.request_id` on a `DocQLError`. Never share your API key, and never paste a
|
|
179
|
+
full exception dump: a chained exception can hold the request headers. Report
|
|
180
|
+
security issues through [SECURITY.md](SECURITY.md).
|
|
181
|
+
|
|
182
|
+
## License
|
|
183
|
+
|
|
184
|
+
Apache-2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
docql/__init__.py,sha256=Sj42mnRBemiy3rygydGi9VG_7XMSgxeDJQVXii_SzK0,1482
|
|
2
|
+
docql/_client.py,sha256=xJXjq2R42UE08tXXJwur9TF13Y1FAD7VNHc_jeayRVQ,8448
|
|
3
|
+
docql/_constants.py,sha256=CSNm6D37-wNPDnGsdTzFBUmvI06kw_iDrU7w967sAco,2619
|
|
4
|
+
docql/_errors.py,sha256=QfOAtdTAAmjRrA_viuwrbcK-hfvhwMRs-oUPvro9QKU,3425
|
|
5
|
+
docql/_request.py,sha256=yIbUQ4pRNtis2tPo-1_5xQ15D2W_JknxDbJU8Dm6zaY,9348
|
|
6
|
+
docql/_response.py,sha256=a6KB6EWZlsuQERTkE7xaUMf4RhXOziRhrOWU1gClK6s,6094
|
|
7
|
+
docql/_version.py,sha256=XkD1Ht9FOPaYUD_PJ0jIT_7r4abTpsdjsjqRmzM_PvU,487
|
|
8
|
+
docql/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
docql-0.1.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
|
|
10
|
+
docql-0.1.0.dist-info/WHEEL,sha256=3iQx15CyXwGi4dbygedzA4M5T1eqO_SjwdPfUmqt2Cw,81
|
|
11
|
+
docql-0.1.0.dist-info/METADATA,sha256=3IaaiaC1Uli1x7zWv3crrzlNi4yAAUVbyxvR0sgNGhs,7429
|
|
12
|
+
docql-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|