from __future__ import annotations import base64 import re from email import policy from email.parser import BytesParser from pathlib import Path from typing import Any from flask import current_app from edkb_system.contracts import Block, Context from edkb_system.skills import loader_csv, loader_docx, loader_pdf, ocr from app.services.shipping_notice.export import _storage_root def task_notice_upload_path(task_no: str, filename: str) -> Path: safe_task = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown" name = str(filename or "").strip() or "notice" safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice" return _storage_root() / "notice_uploads" / safe_task / safe_name def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path: path = task_notice_upload_path(task_no, filename) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) return path def _decode_text(data: bytes) -> str: if not data: return "" for enc in ("utf-8", "utf-8-sig", "gb18030", "gbk"): try: return data.decode(enc) except Exception: continue return data.decode("utf-8", errors="ignore") def _html_to_text(html: str) -> str: s = re.sub(r"(?is)<(script|style).*?>.*?", "", html or "") s = re.sub(r"(?is)", "\n", s) s = re.sub(r"(?is)", "\n", s) s = re.sub(r"(?is)<[^>]+>", " ", s) s = re.sub(r"[ \t]+", " ", s) s = re.sub(r"\\n\\s*\\n+", "\n\n", s) return s.strip() def _eml_to_text(data: bytes) -> str: msg = BytesParser(policy=policy.default).parsebytes(data) parts: list[str] = [] subject = str(msg.get("subject") or "").strip() if subject: parts.append(f"Subject: {subject}") if msg.is_multipart(): for part in msg.walk(): if part.is_multipart(): continue ctype = str(part.get_content_type() or "") payload = part.get_payload(decode=True) or b"" if ctype == "text/plain": parts.append(_decode_text(payload).strip()) elif ctype == "text/html": parts.append(_html_to_text(_decode_text(payload)).strip()) else: payload = msg.get_payload(decode=True) or b"" ctype = str(msg.get_content_type() or "") if ctype == "text/html": parts.append(_html_to_text(_decode_text(payload)).strip()) else: parts.append(_decode_text(payload).strip()) return "\n\n".join(x for x in parts if x) def _image_bytes_to_blocks(raw: bytes) -> list[Block]: if not raw: return [] data_uri = "data:image/png;base64," + base64.b64encode(raw).decode("ascii") return [ Block( id="img-1", page=1, type="image", text="", bbox=(0.0, 0.0, 1000.0, 1000.0), meta={"data_uri": data_uri}, ) ] def _blocks_to_text(blocks: list[Block]) -> str: lines: list[str] = [] for b in blocks: if b.type not in {"paragraph", "ocr_text"}: continue txt = str(b.text or "").strip() if not txt: continue if b.type == "ocr_text": if txt.startswith("OCR_TEXT:"): txt = txt[len("OCR_TEXT:") :].strip() txt = re.sub(r"(?m)^\s*-\s*", "", txt).strip() lines.append(txt) text = "\n\n".join(lines) text = re.sub(r"\n{3,}", "\n\n", text).strip() return text def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]: path = Path(file_path) ext = path.suffix.lower().lstrip(".") ctx = Context(file_type=ext) warnings: list[str] = [] if ext in {"txt", "md", "log"}: return _decode_text(path.read_bytes()).strip(), {"warnings": warnings, "file_type": ext} if ext in {"html", "htm"}: return _html_to_text(_decode_text(path.read_bytes())), {"warnings": warnings, "file_type": ext} if ext in {"eml"}: return _eml_to_text(path.read_bytes()), {"warnings": warnings, "file_type": ext} blocks: list[Block] = [] if ext in {"pdf"}: blocks = loader_pdf.run({"file_path": str(path)}, ctx) elif ext in {"docx"}: blocks = loader_docx.run({"file_path": str(path)}, ctx) elif ext in {"csv"}: blocks = loader_csv.run({"file_path": str(path)}, ctx) elif ext in {"png", "jpg", "jpeg", "webp"}: blocks = _image_bytes_to_blocks(path.read_bytes()) else: warnings.append(f"unsupported_file_type:{ext}") if blocks: has_images = any(b.type == "image" for b in blocks) if has_images: blocks = ocr.run(blocks, ctx) text = _blocks_to_text(blocks) return text.strip(), {"warnings": warnings + list(ctx.warnings), "file_type": ext} return "", {"warnings": warnings + list(ctx.warnings), "file_type": ext} def guess_source_type(filename: str) -> str: ext = str(Path(filename or "").suffix or "").lower().lstrip(".") if ext in {"pdf"}: return "pdf" if ext in {"eml"}: return "email" return "manual" def max_notice_chars() -> int: raw = str(current_app.config.get("SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS") or "").strip() try: value = int(raw) if raw else 0 except Exception: value = 0 return value if value > 0 else 200000