File size: 13,243 Bytes
73075a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
from __future__ import annotations

"""
Parse Poucher "Odour classification" blocks into structured volatility profiles.

Poucher pages use a regular layout:

    Odour classification
    Top notes    Middle notes    Basic notes
    1. ...       15. ...         65. ...

In the extracted text this can appear as three columns on a single line or as
stacked headers followed by items. The parser uses Poucher's coefficient ranges
(1-14 top, 15-60 middle, 61+ basic) as the primary classifier, with column
position used only as a tie-breaker when headers appear on the same line.

Output record:
{
    "profile_id": "poucher_v2_p{page:04d}_{idx:04d}",
    "source": "...",
    "page": 312,
    "name": "Soap Perfumery: Lily",
    "top": ["Bergamot", "Lemon", ...],
    "middle": ["Jasmine", "Rose", ...],
    "base": ["Sandalwood", "Vetiver", ...],
    "overall": "compounding notes / prose",
    "profile_text": "top: ...; middle: ...; base: ...; overall: ...",
    "raw_text": "..."
}
"""

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


SECTION_LABELS = {
    "top": re.compile(r"\btop\s+notes?\b", re.IGNORECASE),
    "middle": re.compile(r"\bmiddle\s+notes?\b", re.IGNORECASE),
    "base": re.compile(r"\bbasic\s+notes?\b", re.IGNORECASE),
}


# Fragments that are clearly prose, not odour-material names.
NOISE_FRAGMENTS = (
    "on this occasion",
    "owing to the",
    "mature for at least",
    "this type is",
    " see the ",
    "monograph on",
    " soap",
    " perfume",
    " formula",
    " no. ",
    "compounding",
    "manufacturing",
    "from the ",
    "that the ",
    "there was",
    "classification of odours",
    "it might be",
    "it is",
    "will be",
    "can be",
    "per cent",
    "the pure substance",
)


def _is_noise(name: str) -> bool:
    lower = name.lower()
    if any(frag in lower for frag in NOISE_FRAGMENTS):
        return True
    if re.search(r"\b(Soap|Perfume),?\s+no\.\s*\d", name, re.IGNORECASE):
        return True
    return False


def _classify_by_number(num: int) -> str | None:
    if 1 <= num <= 14:
        return "top"
    if 15 <= num <= 60:
        return "middle"
    if num >= 61:
        return "base"
    return None


def _split_line_items(line: str) -> list[tuple[int, str]]:
    """Split a line into one or more (number, material) items."""
    # Find every position where a number begins a new item.
    starts = [(m.start(), m.group(1)) for m in re.finditer(r"\b(\d+)\s*[-.)\s]?\s*[A-Za-z]", line)]
    if not starts:
        return []
    items: list[tuple[int, str]] = []
    for i, (pos, num) in enumerate(starts):
        end = starts[i + 1][0] if i + 1 < len(starts) else len(line)
        raw = line[pos:end]
        m = re.match(r"(\d+)\s*[-.)\s]?\s*(.*)", raw, re.DOTALL)
        if not m:
            continue
        name = m.group(2).strip().strip(".").strip(",").strip()
        if name and len(name) > 1 and not _is_noise(name):
            items.append((int(m.group(1)), name))
    return items


def _extract_items_and_continuations(lines: list[str]) -> list[tuple[int, str]]:
    """Extract (number, material) items, merging continuation lines."""
    items: list[tuple[int, str]] = []
    current: tuple[int, str] | None = None
    for line in lines:
        line = line.strip()
        if not line:
            continue
        # If the line contains a numbered item, flush the previous item and split
        # the line into one or more items (multi-column layout).
        if re.search(r"\b\d+\s*[-.)\s]?\s*[A-Za-z]", line):
            if current and not _is_noise(current[1]):
                items.append(current)
            line_items = _split_line_items(line)
            if line_items:
                current = line_items[-1]
                items.extend(line_items[:-1])
            else:
                current = None
        elif current is not None and line and not re.match(r"\d+", line):
            # Continuation of the previous numbered item.
            cont = line.strip().strip(".").strip(",").strip()
            if cont and not _is_noise(cont):
                current = (current[0], current[1] + " " + cont)
        elif current is not None:
            if not _is_noise(current[1]):
                items.append(current)
            current = None
    if current and not _is_noise(current[1]):
        items.append(current)
    return items


def _extract_page_title(page_text: str) -> str | None:
    """Pull a heading like 'SOAP PERFUMERY: LILY' or 'FLOWER PERFUMES: ROSE'."""
    # Prefer explicit chapter/section headings before the classification.
    for pattern in [
        r"^\s*([A-Z][A-Z\s/,]+):\s*([A-Z][A-Z\s/'’-]+)",
        r"^\s*([A-Z][A-Z\s/,]+)\s+([A-Z][A-Z\s/'’-]+)\s*\n",
    ]:
        m = re.search(pattern, page_text, re.MULTILINE)
        if m:
            return f"{m.group(1).strip().title()}: {m.group(2).strip().title()}"
    return None


def _is_quality_profile(profile: dict[str, Any]) -> bool:
    """Require at least a few items in each section to reduce prose noise."""
    return len(profile.get("top", [])) >= 2 and len(profile.get("middle", [])) >= 2 and len(profile.get("base", [])) >= 2


def _extract_overall(page_text: str) -> str:
    """Capture explanatory prose (Compounding notes + surrounding paragraphs)."""
    m = re.search(r"Odour\s+classification", page_text, re.IGNORECASE)
    if not m:
        return ""
    start = m.start()
    end_m = re.search(
        r"(?:A(?:cacia|lmond|Amber)|C(?:arnation|edar|hypre|ologne|ologne|urd|yclamen)|"
        r"F(?:ern|oug[eè]re)|H(?:eliotrope|erb|yacinth)|Jasmin|"
        r"L(?:avender|ilac|ily)|M(?:ay Blossom|usk)|Narcissus|"
        r"O(?:range Blossom|range-Flower)|Pine Bouquet|"
        r"R(?:ose|ose-Geranium)|Santal|Sweet Pea|Trefle|"
        r"(?:Verbena|Violet))\s+(?:Soap|Perfume),\s*no\.\s*\d+",
        page_text[start:], re.IGNORECASE,
    )
    block = page_text[start : start + end_m.start()] if end_m else page_text[start:]
    # Remove numbered items and header labels to leave only prose.
    prose = re.sub(r"\d+\s*[-.)\s]?\s*[A-Za-z][^\n]*", " ", block, flags=re.IGNORECASE)
    prose = re.sub(
        r"\b(?:Top notes|Middle notes|Basic notes|Odour classification)\b",
        " ",
        prose,
        flags=re.IGNORECASE,
    )
    prose = re.sub(r"\s+", " ", prose).strip()
    return prose[:800]


def _column_positions(header_line: str) -> dict[str, int | None]:
    """Return the approximate start column of each section header on one line."""
    positions: dict[str, int | None] = {}
    for key, label in [("top", "Top"), ("middle", "Middle"), ("base", "Basic")]:
        m = re.search(rf"\b{label}\s+notes?\b", header_line, re.IGNORECASE)
        positions[key] = m.start() if m else None
    return positions


def _multi_header_positions(lines: list[str]) -> dict[str, int]:
    """When headers are stacked on separate lines, record their line indices."""
    positions: dict[str, int] = {}
    for key, rx in SECTION_LABELS.items():
        for i, line in enumerate(lines):
            if rx.search(line):
                positions[key] = i
                break
    return positions


def _parse_one_page(text: str) -> dict[str, Any] | None:
    """Extract the structured classification from a single page's text."""
    has_headers = sum(
        1 for rx in (SECTION_LABELS["top"], SECTION_LABELS["middle"], SECTION_LABELS["base"])
        if rx.search(text)
    )
    if has_headers < 2:
        return None

    m = re.search(r"Odour\s+classification", text, re.IGNORECASE)
    if not m:
        return None
    start = m.start()
    end_m = re.search(
        r"\n\s*(?:Compounding\s+notes|"
        r"(?:A(?:cacia|lmond|Amber)|C(?:arnation|edar|hypre|ologne|ologne|urd|yclamen)|"
        r"F(?:ern|oug[eè]re)|H(?:eliotrope|erb|yacinth)|Jasmin|"
        r"L(?:avender|ilac|ily)|M(?:ay Blossom|usk)|Narcissus|"
        r"O(?:range Blossom|range-Flower)|Pine Bouquet|"
        r"R(?:ose|ose-Geranium)|Santal|Sweet Pea|Trefle|"
        r"(?:Verbena|Violet))\s+(?:Soap|Perfume),\s*no\.\s*\d+)",
        text[start:], re.IGNORECASE,
    )
    block = text[start : start + end_m.start()] if end_m else text[start:]
    raw_lines = [ln for ln in block.splitlines()]

    # Determine whether headers are on a single line or stacked.
    header_line: str | None = None
    for line in raw_lines:
        if sum(bool(rx.search(line)) for rx in SECTION_LABELS.values()) >= 2:
            header_line = line
            break
    single_line_headers = header_line is not None

    col_pos: dict[str, int | None] = {}
    if single_line_headers:
        col_pos = _column_positions(header_line)  # type: ignore[arg-type]

    # Build ordered column boundaries for single-line header layout.
    ordered: list[tuple[str, int, int | None]] = []
    if single_line_headers:
        sorted_cols = sorted(
            ((k, v) for k, v in col_pos.items() if v is not None),
            key=lambda x: x[1],
        )
        for idx, (key, left) in enumerate(sorted_cols):
            right = sorted_cols[idx + 1][1] if idx + 1 < len(sorted_cols) else None
            ordered.append((key, left, right))

    # Strip header labels from data lines so they don't create false items.
    data_lines = [
        re.sub(
            r"\b(?:Top notes|Middle notes|Basic notes|Odour classification)\b",
            " ",
            ln,
            flags=re.IGNORECASE,
        )
        for ln in raw_lines
    ]

    items = _extract_items_and_continuations(data_lines)

    buckets: dict[str, list[str]] = {"top": [], "middle": [], "base": []}
    for num, name in items:
        # Primary classification by Poucher's coefficient number.
        assigned = _classify_by_number(num)
        # Tie-break using column position if headers are on one line.
        if single_line_headers and assigned:
            # Find the position of this item's leading number in the original raw line.
            for ln in raw_lines:
                nm = re.search(rf"\b{re.escape(str(num))}\b", ln)
                if not nm:
                    continue
                pos = nm.start()
                for key, left, right in ordered:
                    if right is None:
                        if pos >= left - 5:
                            assigned = key
                            break
                    elif left - 5 <= pos < right - 5:
                        assigned = key
                        break
                break
        if assigned:
            buckets[assigned].append(name)

    # Drop low-quality / prose-heavy profiles that have no real top/middle/base structure.
    if not _is_quality_profile(buckets):
        return None

    return {
        "top": buckets["top"],
        "middle": buckets["middle"],
        "base": buckets["base"],
        "overall": _extract_overall(text),
        "raw_text": block.strip()[:2000],
    }


def _build_profile_text(profile: dict[str, Any]) -> str:
    parts = []
    if profile.get("top"):
        parts.append(f"top: {', '.join(profile['top'])}")
    if profile.get("middle"):
        parts.append(f"middle: {', '.join(profile['middle'])}")
    if profile.get("base"):
        parts.append(f"base: {', '.join(profile['base'])}")
    if profile.get("overall"):
        parts.append(f"overall: {profile['overall']}")
    return "; ".join(parts)


def parse_poucher_profiles(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
    profiles: list[dict[str, Any]] = []
    for record in records:
        source = record.get("source", "")
        if "Poucher" not in source:
            continue
        page = record.get("page", 0)
        text = record.get("text", "")
        parsed = _parse_one_page(text)
        if not parsed:
            continue
        title = _extract_page_title(text) or ""
        profile = {
            "profile_id": f"poucher_v2_p{page:04d}_{len(profiles):04d}",
            "source": source,
            "page": page,
            "name": title,
            "top": parsed["top"],
            "middle": parsed["middle"],
            "base": parsed["base"],
            "overall": parsed["overall"],
            "profile_text": _build_profile_text(parsed),
            "raw_text": parsed["raw_text"],
        }
        profiles.append(profile)
    return profiles


def main() -> int:
    import argparse

    parser = argparse.ArgumentParser(description="Parse Poucher structured odour profiles")
    parser.add_argument("--input", required=True, help="Input JSONL from extract_pdf_text.py")
    parser.add_argument("--output", required=True, help="Output JSONL of profiles")
    args = parser.parse_args()

    input_path = Path(args.input)
    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
    profiles = parse_poucher_profiles(records)

    with output_path.open("w", encoding="utf-8") as out:
        for p in profiles:
            out.write(json.dumps(p, ensure_ascii=False) + "\n")

    print(f"Parsed {len(profiles)} Poucher odour profiles into {output_path}")
    return 0


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