File size: 5,732 Bytes
31ee18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any

# Allow importing parse_appell as a module from the same directory
sys.path.insert(0, str(Path(__file__).parent))
import parse_appell as appell

sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from pino.trade_name_resolver import TradeNameResolver

import fitz


def _block_sort_key(block: tuple) -> tuple[float, float]:
    """Sort blocks by top-y then left-x for reading order."""
    x0, y0, _, _ = block[:4]
    return (y0, x0)


def _is_header_block(text: str) -> tuple[str, str | None] | None:
    """Return (header_name, extra) if the block is a formula header."""
    text = text.strip()
    if not text:
        return None
    m = appell.FRENCH_HEADER_RE.search(text)
    if m:
        return (m.group(1).strip(), m.group(2))
    m = appell.FLORAL_HEADER_RE.match(text)
    if m:
        return (f"{m.group(1)} {m.group(2)}", None)
    m = appell.SOAP_HEADER_RE.match(text)
    if m:
        return (f"{m.group(1)} S {m.group(2)}", None)
    return None


def _block_lines_to_components(block_text: str) -> list[dict[str, Any]]:
    """Parse all amount+code lines within a block."""
    components = []
    for line in block_text.splitlines():
        line = line.strip()
        if not line or len(line) < 3:
            continue
        # Skip totals, page numbers, and section headers
        if re.match(r'^\d{1,4}$', line):
            continue
        if re.match(r'^T\s+1000', line, re.IGNORECASE):
            continue
        if "continued" in line.lower():
            continue
        comps = appell._line_to_components(line)
        if comps:
            components.extend(comps)
    return components


def _detect_page_section(blocks: list[tuple]) -> str | None:
    """Find the current section heading from the page blocks."""
    for block in blocks:
        text = block[4].strip()
        m = appell.SECTION_RE.match(text)
        if m:
            return m.group(1)
    return None


def parse_appell_blocks(
    pdf_path: Path,
    page_range: tuple[int, int],
) -> list[dict[str, Any]]:
    """Parse Appell formula pages using PyMuPDF text blocks (preserves columns)."""
    doc = fitz.open(pdf_path)
    formulas: list[dict[str, Any]] = []
    current_section: str | None = None

    for page_idx in range(page_range[0] - 1, page_range[1]):
        if page_idx >= len(doc):
            continue
        page = doc[page_idx]
        blocks = page.get_text("blocks")
        blocks = sorted(blocks, key=_block_sort_key)
        page_section = _detect_page_section(blocks) or current_section
        current_section = page_section

        current_header: tuple[str, str | None] | None = None
        current_components: list[dict[str, Any]] = []

        def flush_formula() -> None:
            if not current_header or not current_components:
                return
            total = sum(c["amount"] for c in current_components)
            if total < 500 or total > 1500 or len(current_components) < 3:
                return
            formulas.append({
                "formula_id": f"appell_p{page_idx + 1:04d}_{len(formulas):04d}",
                "name": current_header[0],
                "source": "Louis Appell - Cosmetics, Fragrances and Flavors",
                "page": page_idx + 1,
                "extra": current_header[1],
                "components": current_components,
                "raw_basis_sum": total,
            })

        for block in blocks:
            text = block[4].strip()
            if not text:
                continue
            # Update section if this block is a section heading
            s = appell.SECTION_RE.match(text)
            if s:
                current_section = s.group(1)
                continue

            header = _is_header_block(text)
            if header:
                flush_formula()
                current_header = header
                current_components = []
                continue

            if current_header is None:
                continue

            comps = _block_lines_to_components(text)
            if comps:
                current_components.extend(comps)

        flush_formula()

    doc.close()
    return formulas


def main() -> int:
    parser = argparse.ArgumentParser(description="Block-aware Appell formula parser")
    parser.add_argument("--pdf", required=True, type=Path, help="Appell PDF path")
    parser.add_argument("--output", required=True, type=Path, help="Output resolved JSONL")
    parser.add_argument("--raw-output", type=Path, help="Optional raw parsed JSONL")
    parser.add_argument("--start-page", type=int, default=293, help="First formula page")
    parser.add_argument("--end-page", type=int, default=343, help="Last formula page")
    args = parser.parse_args()

    raw_formulas = parse_appell_blocks(args.pdf, (args.start_page, args.end_page))

    if args.raw_output:
        args.raw_output.parent.mkdir(parents=True, exist_ok=True)
        with args.raw_output.open("w", encoding="utf-8") as out:
            for f in raw_formulas:
                out.write(json.dumps(f, ensure_ascii=False) + "\n")
        print(f"Wrote {len(raw_formulas)} raw block formulas to {args.raw_output}")

    resolved = appell.resolve_appell_formulas(raw_formulas)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("w", encoding="utf-8") as out:
        for f in resolved:
            out.write(json.dumps(f, ensure_ascii=False) + "\n")

    print(f"Resolved {len(resolved)}/{len(raw_formulas)} block formulas to {args.output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())