Metadata-Version: 2.5
Name: infratex
Version: 1.1.0
Summary: Python SDK for the Infratex document intelligence API
Project-URL: Homepage, https://infratex.io
Project-URL: Documentation, https://docs.infratex.io
Project-URL: Repository, https://github.com/Abransh/infratex-python
Author-email: Infratex <support@infratex.io>
License-Expression: MIT
License-File: LICENSE
Keywords: document,infratex,parsing,pdf,rag
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.8
Requires-Dist: httpx>=0.24.0
Provides-Extra: dev
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Description-Content-Type: text/markdown

# Infratex Python SDK

Official Python client for the [Infratex](https://infratex.io) document intelligence API. Parse PDFs, Word documents, or ordered image batches, build search indexes, retrieve cited context, stream grounded answers, extract structured fields, and receive webhooks when work finishes.

## API parity

Every public endpoint and request parameter in the [API docs](https://docs.infratex.io) is
available from this SDK, and every API error code reaches you in `InfratexError.code`. Each
release lists the API changes it covers in [CHANGELOG.md](CHANGELOG.md), next to the API docs
section each change matches, along with anything not covered yet. The Node.js SDK
(`npm install infratex`) ships the same changes under the same version number.

## Installation

```bash
pip install infratex
```

## Quick start

```python
from infratex import Infratex

client = Infratex(api_key="infratex_sk_...")

# Upload and parse a PDF (waits for parsing by default)
doc = client.documents.upload("report.pdf", method="standard")
print(doc.id, doc.status, doc.page_count)

# Index for retrieval, then wait until it's ready
client.documents.index(doc.id, method="hybrid")

# Stream a cited answer
for event in client.responses.create(
    message="Summarize the key findings with citations.",
    method="hybrid",
    model="fast",
    document_ids=[doc.id],
):
    if event.type == "sources":
        print("Sources:", event.content)
    elif event.type == "text":
        print(event.content, end="")
```

## Authentication

Pass your API key directly or set the `INFRATEX_API_KEY` environment variable. Use a
server-side key (`infratex_sk_...`); keep it out of browser code.

```python
# Explicit
client = Infratex(api_key="infratex_sk_...")

# From environment
import os
os.environ["INFRATEX_API_KEY"] = "infratex_sk_..."
client = Infratex()
```

## Parse methods

| Method | Credits / page | Notes |
|--------|----------------|-------|
| `standard` | 1 | Default. Fast, high-quality Markdown for most documents. |
| `max` | 3 | Figures are marked, captioned, and described. For documents where charts, diagrams, and photos carry meaning. |
| `infratex-phi` | 3 | Proprietary in-house model. Dense tables, financial statements, faithfulness-first OCR. |
| `infratex-gamma` | 1 | Layout-aware OCR. Faithful text and tables at volume, with a bounding box for every region. |
| `standard-ultra-2` | 3 | High-fidelity vision for complex nested tables and chart-heavy reports (API-only). |

Both `documents.upload(...)` and `documents.upload_images(...)` accept any of these
methods and default to `standard`. A method that is temporarily unavailable is rejected
at upload with `InfratexError` (status 503, code `method_unavailable`).

`infratex-gamma` also takes parse `options`, sent as one JSON object, for example
`options={"merge_tables": False, "ignore_labels": ["header", "footer"]}`. The keys and their
defaults are listed in the API docs (Parsing, "Parse options"); other methods answer 422
`invalid_parse_configuration`.

`table_format` (`"otsl"` or `"html"`) sets the table syntax the parser emits; it is
honoured by `max`, `infratex-phi`, `infratex-gamma` and `standard-ultra-2` (`standard`
returns Markdown pipe tables). It is stored with the document: a document parsed as
`otsl` can be read back as either syntax with `documents.markdown(id, table_format=...)`,
one parsed as `html` only as HTML.

`documents.upload(...)` also accepts a Word `.docx`. It is read from the file itself (no
model call) and billed at the `standard` price whatever `method` you send; the document
reports `standard` as its method. Legacy `.doc` and macro-enabled `.docm` files are
rejected with status 415. A PDF that needs a password to open is rejected at upload with
`EncryptedPDFError` (400 `encrypted_pdf`), before any credits are held: remove the password
and upload it again.

If a parse fails, `wait_until_parsed(...)` (and `upload(...)` with the default `wait=True`)
raises `InfratexError` with the document's `error_message`, which says what went wrong and
what to do; a failed document is not charged.

## Resources

### Documents

```python
# Upload a PDF — waits for parsing and returns the markdown-bearing document.
doc = client.documents.upload("report.pdf")
doc = client.documents.upload("report.pdf", method="max", collection_id="col-id")

# Word documents use the same call.
doc = client.documents.upload("contract.docx")

# Table syntax: "otsl" (default) or "html". Stored with the document, not changeable later.
doc = client.documents.upload("report.pdf", method="infratex-gamma", table_format="otsl")

# infratex-gamma parse options, and its per-region bounding boxes once parsed.
doc = client.documents.upload("scan.pdf", method="infratex-gamma", options={"unwarp": True})
for page in client.documents.layout(doc.id):
    for region in page.regions:
        print(page.page, region.label, region.bbox)   # bbox in pixels of a page.width x page.height image

# Upload an ordered image batch as document pages (file order = page order).
images = client.documents.upload_images(["page-1.png", "page-2.png"], method="standard")

# Queue-first if you want to manage the parse lifecycle yourself.
queued = client.documents.upload("report.pdf", wait=False)
doc = client.documents.wait_until_parsed(queued.id)   # or: client.documents.get(queued.id, wait=True)

# Progress while pending or processing (None once parsed or failed): stage is
# "queued", "parsing" or "finishing"; updated_at is refreshed at least every 30 s while it runs.
doc = client.documents.wait_until_parsed(
    queued.id,
    on_progress=lambda p: print(p.stage, p.pages_done, "/", p.pages_total, "attempt", p.attempt, "of", p.max_attempts),
)
progress = client.documents.get(queued.id).progress

# List / get / markdown
docs = client.documents.list(limit=50, offset=0, collection_id="col-id")
print(docs.total)
doc = client.documents.get("doc-id")
md = client.documents.markdown("doc-id")
md = client.documents.markdown("doc-id", table_format="html")   # OTSL tables as <table>
md = client.documents.markdown("doc-id", figure_descriptions=False)   # drop figure <description>s

# Figures cropped from a parsed PDF (any method). The figure block in the markdown
# carries the same src (figures/p12-1.png); bbox is [x1, y1, x2, y2] in PDF points.
for figure in client.documents.list_figures("doc-id"):
    print(figure.page, figure.type, figure.src, figure.bbox)
    client.documents.download_figure("doc-id", figure.name).save(figure.name)   # PNG

# Rename or move between collections
client.documents.update("doc-id", filename="q3-report.pdf")
client.documents.update("doc-id", collection_id="col-id")
client.documents.update("doc-id", remove_collection=True)

# Delete
client.documents.delete("doc-id")

# Index — waits until the method-specific index reaches "indexed".
client.documents.index("doc-id", method="hybrid")

# Queue-first indexing if you want to manage polling yourself.
client.documents.index("doc-id", method="hybrid", wait=False)
indexes = client.documents.list_indexes("doc-id")
index = client.documents.wait_until_indexed("doc-id", method="hybrid")
```

### Searches

Retrieve cited context without generating text. Send one scope: `document_ids` **or**
`collection_id`.

```python
results = client.searches.create(
    query="Find indemnity carve-outs",
    method="hybrid",
    limit=5,
    document_ids=["doc-id"],
)
for hit in results:
    print(hit.document_name, hit.score, hit.content[:160])
```

### Responses (streaming)

Stream answers grounded in indexed documents. Events arrive in order: `sources`,
`thinking` (only when `reasoning=True`), `text` deltas, then `done`.

```python
for event in client.responses.create(
    message="What are the top risks?",
    method="hybrid",
    model="fast",       # "fast" (default) or "pro"
    collection_id="col-id",
    limit=8,
    reasoning=False,
):
    if event.type == "sources":
        sources = event.content
    elif event.type == "text":
        print(event.content, end="")
    elif event.type == "done":
        print("\n--- done ---")
```

```python
# Managed multi-turn thread with persisted scope
conv = client.conversations.create(title="Quarterly Analysis", collection_id="col-id")

for event in client.responses.create(
    message="How does that compare with the previous quarter?",
    method="hybrid",
    model="pro",
    conversation_id=conv.id,   # scope comes from the conversation; omit document_ids/collection_id
):
    if event.type == "text":
        print(event.content, end="")
```

### Extractions

Extract structured fields from a parsed document. Provide inline field definitions, or
reference a `template_id` created in the dashboard — exactly one is required.

```python
run = client.extractions.create(
    "doc-id",
    model="fast",              # "fast" (default) or "pro"
    include_evidence=True,
    inline_fields=[
        {"name": "counterparty", "type": "string", "description": "Legal name of the counterparty"},
        {"name": "effective_date", "type": "date", "description": "Contract effective date"},
        {"name": "termination_fee", "type": "number", "description": "Any explicit termination fee"},
    ],
)

result = client.extractions.wait_until_done(run.id, include_evidence=True)
print(result.result)     # {"counterparty": "...", "effective_date": "...", ...}
print(result.evidence)   # per-field evidence (present because include_evidence=True)

# Reference a dashboard-managed template instead of inline fields
run = client.extractions.create("doc-id", template_id="tpl-id")

# Run every step on Infratex's self-hosted model
run = client.extractions.create("doc-id", template_id="tpl-id", model="infratex-phi")

# Exhaustive mode for list fields where every item matters (footnotes, line items):
# reads every part of the document for array fields, then checks for missed items.
run = client.extractions.create("doc-id", template_id="tpl-id", completeness="exhaustive")

# v2 (beta): "legacy" (default) or "v2". v2 opens per account; check before asking for it.
from infratex import InvalidPipelineError, PipelineNotAvailableError

if client.extractions.list_pipelines().is_available("v2"):
    run = client.extractions.create("doc-id", template_id="tpl-id", pipeline="v2")
try:
    run = client.extractions.create("doc-id", template_id="tpl-id", pipeline="v2")
except PipelineNotAvailableError as e:
    print(e.available_pipelines)   # ["legacy"]: the beta is not open for this account yet
done = client.extractions.wait_until_done(run.id)
print(done.pipeline, done.credits_charged, done.cached)   # the engine that ran, its cost

# Parse and extract in one call (POST /api/v1/extractions): a PDF, .docx or one image.
# wait (0-300 s) holds the request server-side until the run is done or failed.
run = client.extractions.create_from_file(
    "contract.pdf",
    method="standard",
    model="pro",
    inline_fields=[{"name": "counterparty", "type": "string", "description": "Legal name"}],
    wait=180,
)
if run.status not in ("done", "error"):
    run = client.extractions.wait_until_done(run.id)

# Poll with a server-side hold instead of client-side polling
run = client.extractions.get(run.id, wait=60)

# List prior runs, then export tabular results
runs = client.extractions.list("doc-id")
export = client.extractions.export(run.id, format="xlsx")   # or "csv"
export.save("results.xlsx")
```

Field definitions support nested shapes: `type` may be `string`, `number`, `integer`,
`boolean`, `date`, `enum`, `object`, or `array`. Use `enum_values` for `enum`,
`properties` (a list of fields) for `object`, and `items` (a single field) for `array`.
Extraction templates are created and managed in the dashboard. `completeness` is
`"standard"` (default) or `"exhaustive"`; exhaustive runs are slower and bill more tokens,
and the run reports the mode it used in `run.completeness`.

`pipeline` is sent in the request body only when you set it (never as a query parameter).
`"v2"` before the beta is open for your account raises `PipelineNotAvailableError`
(422 `pipeline_not_available`); any other value raises `InvalidPipelineError`
(422 `invalid_pipeline`). Nothing is created or billed when a run is refused. Every finished
run reports the engine that ran in `run.pipeline`, what it charged in `run.credits_charged`,
and whether an earlier identical result was reused at no charge in `run.cached`.

### Collections

```python
col = client.collections.create(name="Q3 Reports")
cols = client.collections.list()
col = client.collections.get("col-id")
client.collections.update("col-id", name="Q4 Reports")
client.collections.delete("col-id")
```

### Conversations

```python
conv = client.conversations.create(title="Analysis", collection_id="col-id")
convs = client.conversations.list()
conv = client.conversations.get("conv-id")   # includes messages
client.conversations.delete("conv-id")
```

### Account & Billing

```python
account = client.account.get()
print(account.tenant["email"], account.tenant["credit_balance_micros"])

settings = client.account.settings()
print(settings.allow_overage, settings.monthly_spend_cap_micros, settings.data_residency)

# Restrict processing to the EU. An API key can turn eu_only on; only the dashboard
# can switch it back to "default" (403 dashboard_only).
client.account.update_settings(data_residency="eu_only")

billing = client.billing.get()
print(billing.balance_micros)

# The credit ledger, newest first: every charge, refund, grant and top-up with the
# balance after it. Amounts are in micro-euros (1 credit = 5,000).
page = client.billing.list_transactions(since="2026-10-01T00:00:00Z", limit=100)  # limit <= 500
for tx in page:
    print(tx.created_at, tx.transaction_type, tx.amount_micros, tx.description)
older = client.billing.list_transactions(before=page.next_before) if page.next_before else None

# Or let the SDK follow next_before for you.
from datetime import datetime, timezone

for tx in client.billing.iter_transactions(since=datetime(2026, 10, 1, tzinfo=timezone.utc)):
    print(tx.source_id, tx.amount_micros)
```

`since` / `until` / `before` take a timezone-aware `datetime` or an ISO 8601 string. A
parse charge carries the document id in `source_id` and the file name and billed pages
in `description` and `metadata`.

### Webhooks

Register an HTTPS endpoint and Infratex POSTs a signed JSON event when a parse, an index
build or an extraction run finishes or fails, instead of you polling.

```python
hook = client.webhooks.create(
    url="https://example.com/infratex",
    events=["document.parsed", "extraction.completed"],   # empty or omitted: every type
    description="production",
)
secret = hook.secret   # shown only here and on rotate_secret(): store it

client.webhooks.list()
client.webhooks.get(hook.id)
client.webhooks.update(hook.id, enabled=False)          # or url=, events=, description=
client.webhooks.test(hook.id)                           # queues a webhook.test event
for delivery in client.webhooks.list_deliveries(hook.id, status="failed", limit=20):
    client.webhooks.retry_delivery(hook.id, delivery.id)
new_secret = client.webhooks.rotate_secret(hook.id).secret
client.webhooks.delete(hook.id)
```

Verify each delivery over the raw request body before trusting it, and deduplicate on the
`Infratex-Event-Id` header (the same on every retry):

```python
from infratex import verify_webhook_signature

# Flask
@app.post("/infratex")
def infratex_webhook():
    if not verify_webhook_signature(SECRET, request.get_data(), request.headers["Infratex-Signature"]):
        abort(400)
    event = request.get_json()
    ...
    return "", 200
```

## Error handling

```python
from infratex import Infratex, InfratexError

client = Infratex(api_key="infratex_sk_...")

try:
    doc = client.documents.get("nonexistent-id")
except InfratexError as e:
    print(e.status_code)  # 404
    print(e.code)         # error code from the API, e.g. "not_found"
    print(str(e))         # human-readable message
    print(e.details)      # extra fields the API sent, if any
    print(e.request_id)   # quote it when you contact support
    print(e.retry_after)  # Retry-After in seconds (429, 409 idempotency_request_in_progress)
```

`InvalidPipelineError` and `PipelineNotAvailableError` (the two extraction `pipeline`
refusals) and `EncryptedPDFError` (a password-protected PDF upload) are subclasses of
`InfratexError`; every other API error code is in `e.code`.

### Retries and idempotency

A request that times out may still have been accepted. To retry a create safely, pass the
same `idempotency_key` on every attempt: within 24 hours the API returns the first response
instead of creating (and billing) the work twice. It is accepted on
`documents.upload(...)`, `documents.upload_images(...)`, `documents.index(...)`,
`extractions.create(...)` and `extractions.create_from_file(...)`.

```python
import time, uuid
import httpx

key = str(uuid.uuid4())   # one key per document, reused on every retry
for attempt in range(5):
    try:
        doc = client.documents.upload("contract.pdf", idempotency_key=key, wait=False)
        break
    except InfratexError as e:
        if e.status_code not in (409, 429, 500, 502, 503, 504):
            raise
        time.sleep(e.retry_after or 2 ** attempt)
    except httpx.TransportError:
        time.sleep(2 ** attempt)
```

## Configuration

```python
client = Infratex(
    api_key="infratex_sk_...",
    base_url="https://api.infratex.io",  # custom base URL
    timeout=300.0,                        # request / poll timeout in seconds
)

# Use as a context manager
with Infratex(api_key="infratex_sk_...") as client:
    doc = client.documents.upload("report.pdf")
```

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest          # tests run against a mocked HTTP transport, no API key needed
mypy            # strict, over infratex/ and tests/
ruff check .
```

## License

MIT
