Spaces:
Sleeping

File size: 2,454 Bytes
efff1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""Typed configuration, sourced from environment variables."""

from __future__ import annotations

from functools import lru_cache

from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Runtime configuration.

    All values can be overridden with the ``DOCX_`` environment prefix, e.g.
    ``DOCX_MAX_UPLOAD_MB=25``.
    """

    model_config = SettingsConfigDict(
        env_prefix="DOCX_", env_file=".env", extra="ignore"
    )

    # --- model ---
    # NOTE: impira/layoutlm-invoices is licensed CC-BY-NC-SA-4.0 (non-commercial).
    # impira/layoutlm-document-qa is MIT and safe for commercial use.
    model_id: str = "impira/layoutlm-invoices"
    device: str = "cpu"
    torch_threads: int = Field(default=4, ge=1, le=64)

    # --- extraction behaviour ---
    # Answers below this confidence are reported as `low_confidence` rather
    # than silently returned as fact.
    confidence_threshold: float = Field(default=0.5, ge=0.0, le=1.0)
    # Maximum pages processed per document. LayoutLM's effective context is
    # ~512 tokens, so deep multi-page scans are truncated anyway.
    max_pages: int = Field(default=3, ge=1, le=50)
    # Keys per batched forward pass. Measured sweet spot on CPU; see BENCHMARK.md.
    batch_size: int = Field(default=8, ge=1, le=64)
    # How many keys one request may ask for.
    max_keys: int = Field(default=64, ge=1, le=512)
    max_key_length: int = Field(default=200, ge=1, le=2000)

    # --- resource limits ---
    max_upload_mb: int = Field(default=25, ge=1, le=500)
    request_timeout_s: float = Field(default=60.0, gt=0)
    # Rendered-page pixel budget; guards against decompression bombs where a
    # small file expands to a huge bitmap.
    max_render_pixels: int = Field(default=40_000_000, ge=1_000_000)

    # --- caching ---
    # Parsed text+boxes are cached by content hash so repeated keys against the
    # same document do not re-run OCR/parsing.
    parse_cache_size: int = Field(default=128, ge=0, le=10_000)

    # --- concurrency ---
    # Torch is not thread-safe for concurrent forward passes on one module
    # without a lock; the engine serialises model access and relies on
    # batching for throughput.
    max_concurrency: int = Field(default=4, ge=1, le=64)

    log_level: str = "INFO"
    log_json: bool = True


@lru_cache(maxsize=1)
def get_settings() -> Settings:
    return Settings()