File size: 8,960 Bytes
e1ecd91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
Utilities to ingest uploaded legal documents into persistent storage.
"""

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from datetime import datetime, date
from io import BytesIO
from typing import BinaryIO, Dict, Optional
from pathlib import Path
import re

from django.conf import settings
from django.core.files.base import ContentFile
from django.db import transaction
from django.utils import timezone

from hue_portal.core.models import (
    LegalDocument,
    LegalSection,
    LegalDocumentImage,
    IngestionJob,
)
from hue_portal.core.etl.legal_document_loader import load_legal_document
from hue_portal.core.tasks import process_ingestion_job


@dataclass
class LegalIngestionResult:
    document: LegalDocument
    created: bool
    sections_count: int
    images_count: int


def _parse_date(value: Optional[str | date]) -> Optional[date]:
    if isinstance(value, date):
        return value
    if not value:
        return None
    for fmt in ("%Y-%m-%d", "%d/%m/%Y"):
        try:
            return datetime.strptime(value, fmt).date()
        except ValueError:
            continue
    return None


def _sha256(data: bytes) -> str:
    digest = hashlib.sha256()
    digest.update(data)
    return digest.hexdigest()


def _normalize_text(text: str) -> str:
    cleaned = re.sub(r"\s+", "", text or "")
    return cleaned.lower()


DOC_TYPE_KEYWORDS = {
    "decision": ["quyết định"],
    "circular": ["thông tư"],
    "guideline": ["hướng dẫn"],
    "plan": ["kế hoạch"],
}


def _auto_fill_metadata(
    *, text: str, title: str, issued_by: str, issued_at: Optional[date], doc_type: str
) -> tuple[str, str, Optional[date], str]:
    head = (text or "")[:2000]
    if not issued_by:
        match = re.search(r"(BỘ\s+[A-ZÂĂÊÔƠƯ\s]+|ỦY BAN\s+NHÂN DÂN\s+[^\n]+)", head, re.IGNORECASE)
        if match:
            issued_by = match.group(0).strip()

    if not issued_at:
        match = re.search(
            r"(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})", head,
        )
        if match:
            day, month, year = match.groups()
            issued_at = _parse_date(f"{year}-{int(month):02d}-{int(day):02d}")
        else:
            match = re.search(
                r"ngày\s+(\d{1,2})\s+tháng\s+(\d{1,2})\s+năm\s+(\d{4})",
                head,
                re.IGNORECASE,
            )
            if match:
                day, month, year = match.groups()
                issued_at = _parse_date(f"{year}-{int(month):02d}-{int(day):02d}")

    if doc_type == "other":
        lower = head.lower()
        for dtype, keywords in DOC_TYPE_KEYWORDS.items():
            if any(keyword in lower for keyword in keywords):
                doc_type = dtype
                break

    if not title or title == (DOC_TYPE_KEYWORDS.get(doc_type, [title])[0] if doc_type != "other" else ""):
        match = re.search(r"(QUYẾT ĐỊNH|THÔNG TƯ|HƯỚNG DẪN|KẾ HOẠCH)[^\n]+", head, re.IGNORECASE)
        if match:
            title = match.group(0).strip().title()

    return title, issued_by, issued_at, doc_type


def ingest_uploaded_document(
    *,
    file_obj: BinaryIO,
    filename: str,
    metadata: Dict,
) -> LegalIngestionResult:
    """
    Ingest uploaded PDF/DOCX file, storing raw file, sections, and extracted images.

    Args:
        file_obj: Binary file-like object positioned at start.
        filename: Original filename.
        metadata: dict containing code, title, doc_type, summary, issued_by, issued_at, source_url, extra_metadata.
    """
    code = metadata.get("code", "").strip()
    if not code:
        raise ValueError("Document code is required.")

    title = metadata.get("title") or code
    doc_type = metadata.get("doc_type", "other")
    issued_at = _parse_date(metadata.get("issued_at"))
    summary = metadata.get("summary", "")
    issued_by = metadata.get("issued_by", "")
    source_url = metadata.get("source_url", "")
    extra_metadata = metadata.get("metadata") or {}

    file_bytes = file_obj.read()
    if hasattr(file_obj, "seek"):
        file_obj.seek(0)
    checksum = _sha256(file_bytes)
    mime_type = metadata.get("mime_type") or getattr(file_obj, "content_type", "")
    size = len(file_bytes)

    extracted = load_legal_document(BytesIO(file_bytes), filename=filename)
    title, issued_by, issued_at, doc_type = _auto_fill_metadata(
        text=extracted.text, title=title, issued_by=issued_by, issued_at=issued_at, doc_type=doc_type
    )
    normalized_text = _normalize_text(extracted.text)
    content_checksum = _sha256(normalized_text.encode("utf-8"))

    duplicate = (
        LegalDocument.objects.filter(content_checksum=content_checksum)
        .exclude(code=code)
        .first()
    )
    if duplicate:
        raise ValueError(f"Nội dung trùng với văn bản hiện có: {duplicate.code}")

    with transaction.atomic():
        doc, created = LegalDocument.objects.get_or_create(
            code=code,
            defaults={
                "title": title,
                "doc_type": doc_type,
                "summary": summary,
                "issued_by": issued_by,
                "issued_at": issued_at,
                "source_url": source_url,
                "metadata": extra_metadata,
            },
        )

        # Update metadata if document already existed (keep latest info)
        doc.title = title
        doc.doc_type = doc_type
        doc.summary = summary
        doc.issued_by = issued_by
        doc.issued_at = issued_at
        doc.source_url = source_url
        doc.metadata = extra_metadata
        doc.page_count = extracted.page_count
        doc.raw_text = extracted.text
        doc.raw_text_ocr = extracted.ocr_text or ""
        doc.file_checksum = checksum
        doc.content_checksum = content_checksum
        doc.file_size = size
        doc.mime_type = mime_type
        doc.original_filename = filename
        doc.updated_at = timezone.now()

        # Save binary file
        content = ContentFile(file_bytes)
        storage_name = f"{code}/{filename}"
        doc.uploaded_file.save(storage_name, content, save=False)
        doc.source_file = doc.uploaded_file.name
        doc.save()

        # Replace sections
        doc.sections.all().delete()
        sections = []
        for idx, section in enumerate(extracted.sections, start=1):
            sections.append(
                LegalSection(
                    document=doc,
                    section_code=section.code,
                    section_title=section.title,
                    level=section.level,
                    order=idx,
                    content=section.content,
                    excerpt=section.content[:400],
                    page_start=section.page_start,
                    page_end=section.page_end,
                    is_ocr=section.is_ocr,
                    metadata=section.metadata or {},
                )
            )
        LegalSection.objects.bulk_create(sections, batch_size=200)

        # Replace images
        doc.images.all().delete()
        images = []
        for idx, image in enumerate(extracted.images, start=1):
            image_content = ContentFile(image.data)
            image_name = f"{code}/img_{idx}.{image.extension}"
            img_instance = LegalDocumentImage(
                document=doc,
                page_number=image.page_number,
                description=image.description,
                width=image.width,
                height=image.height,
                checksum=_sha256(image.data),
            )
            img_instance.image.save(image_name, image_content, save=False)
            images.append(img_instance)
        LegalDocumentImage.objects.bulk_create(images, batch_size=100)

    return LegalIngestionResult(
        document=doc,
        created=created,
        sections_count=len(sections),
        images_count=len(images),
    )


def enqueue_ingestion_job(*, file_obj, filename: str, metadata: Dict) -> IngestionJob:
    """
    Persist uploaded file to a temporary job folder and enqueue Celery processing.
    """

    job = IngestionJob.objects.create(
        code=metadata.get("code", ""),
        filename=filename,
        metadata=metadata,
        status=IngestionJob.STATUS_PENDING,
    )

    temp_dir = Path(settings.MEDIA_ROOT) / "ingestion_jobs" / str(job.id)
    temp_dir.mkdir(parents=True, exist_ok=True)
    temp_path = temp_dir / filename

    if hasattr(file_obj, "seek"):
        file_obj.seek(0)
    if hasattr(file_obj, "chunks"):
        with temp_path.open("wb") as dest:
            for chunk in file_obj.chunks():
                dest.write(chunk)
    else:
        data = file_obj.read()
        with temp_path.open("wb") as dest:
            dest.write(data)

    job.storage_path = str(temp_path)
    job.save(update_fields=["storage_path"])
    process_ingestion_job.delay(str(job.id))
    return job