File size: 7,062 Bytes
c4e128a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""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,
        }