darachhat
feat: build production-ready Khmer Document Corpus v0.2.0 with Typer CLI, PyMuPDF, Polars, and DI architecture
c4e128a
Raw
History Blame Contribute Delete
7.06 kB
"""Core Pydantic v2 document models."""
from __future__ import annotations
from enum import StrEnum
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, field_validator, model_validator
# ──────────────────────────────────────────────────────────────────────────────
# Enums
# ──────────────────────────────────────────────────────────────────────────────
class Language(StrEnum):
"""ISO 639-1 language codes supported by the corpus."""
km = "km"
en = "en"
mixed = "mixed"
unknown = "unknown"
class Category(StrEnum):
"""Document category taxonomy."""
government_report = "government_report"
government_form = "government_form"
law = "law"
gazette = "gazette"
book = "book"
research_paper = "research_paper"
manual = "manual"
annual_report = "annual_report"
financial_report = "financial_report"
certificate = "certificate"
contract = "contract"
invoice = "invoice"
receipt = "receipt"
newspaper = "newspaper"
magazine = "magazine"
presentation = "presentation"
other = "other"
class DeduplicationStrategy(StrEnum):
sha256 = "sha256"
simhash = "simhash"
both = "both"
# ──────────────────────────────────────────────────────────────────────────────
# Sub-models
# ──────────────────────────────────────────────────────────────────────────────
class PageMeta(BaseModel):
"""Per-page metadata extracted from a PDF."""
page_number: int = Field(..., ge=1, description="1-indexed page number")
width_pt: float = Field(..., gt=0, description="Page width in points")
height_pt: float = Field(..., gt=0, description="Page height in points")
text_char_count: int = Field(default=0, ge=0)
image_count: int = Field(default=0, ge=0)
has_text_layer: bool = False
class ValidationResult(BaseModel):
"""Result of schema + content validation for a document."""
is_valid: bool
errors: list[str] = Field(default_factory=list)
warnings: list[str] = Field(default_factory=list)
@property
def has_warnings(self) -> bool:
return len(self.warnings) > 0
# ──────────────────────────────────────────────────────────────────────────────
# Core Model
# ──────────────────────────────────────────────────────────────────────────────
class DocumentMeta(BaseModel):
"""Complete metadata for a single corpus document."""
model_config = {"use_enum_values": True}
# Identity
id: UUID = Field(default_factory=uuid4, description="Unique document UUID")
filename: str = Field(..., min_length=1, description="PDF filename (no path)")
# Classification
language: Language = Language.unknown
category: Category = Category.other
# Dimensions
pages: int = Field(..., ge=1, description="Total page count")
file_size_bytes: int = Field(..., ge=0, description="Raw PDF file size in bytes")
# Content flags
native_pdf: bool = Field(False, description="True if text is embedded in the PDF")
scanned: bool = Field(False, description="True if the PDF requires OCR")
has_tables: bool = False
has_images: bool = False
has_header: bool = False
has_footer: bool = False
# Deduplication
sha256: str | None = Field(None, description="SHA-256 hex digest of raw file bytes")
simhash: int | None = Field(None, description="SimHash fingerprint of extracted text")
# Provenance
source: str | None = Field(None, description="Source URL or institution name")
license: str | None = Field(None, description="Original document license")
# Paths (relative to corpus root)
pdf_path: str | None = None
preview_path: str | None = Field(None, description="Path to the preview image folder")
# Per-page detail (optional, not always populated)
pages_meta: list[PageMeta] = Field(default_factory=list)
# ── Validators ────────────────────────────────────────────────────────────
@field_validator("filename")
@classmethod
def filename_must_be_pdf(cls, v: str) -> str:
if not v.lower().endswith(".pdf"):
raise ValueError(f"filename must end with .pdf, got: {v!r}")
return v
@field_validator("sha256")
@classmethod
def sha256_format(cls, v: str | None) -> str | None:
if v is not None and len(v) != 64:
raise ValueError("sha256 must be a 64-character hex string")
return v
@model_validator(mode="after")
def pages_meta_length(self) -> DocumentMeta:
if self.pages_meta and len(self.pages_meta) != self.pages:
raise ValueError(
f"pages_meta has {len(self.pages_meta)} entries but pages={self.pages}"
)
return self
# ── Helpers ───────────────────────────────────────────────────────────────
@property
def file_size_kb(self) -> float:
return self.file_size_bytes / 1024
@property
def file_size_mb(self) -> float:
return self.file_size_bytes / (1024 * 1024)
def to_flat_dict(self) -> dict[str, object]:
"""Return a flat dict suitable for a Polars row (no nested objects)."""
return {
"id": str(self.id),
"filename": self.filename,
"language": self.language,
"category": self.category,
"pages": self.pages,
"file_size_bytes": self.file_size_bytes,
"native_pdf": self.native_pdf,
"scanned": self.scanned,
"has_tables": self.has_tables,
"has_images": self.has_images,
"has_header": self.has_header,
"has_footer": self.has_footer,
"sha256": self.sha256,
"simhash": self.simhash,
"source": self.source,
"license": self.license,
"pdf_path": self.pdf_path,
"preview_path": self.preview_path,
}