mattbitzesty commited on
Commit
73075a8
·
unverified ·
1 Parent(s): 4888d21

feat(literature): add structured Poucher odour profile parser

Browse files

- Parse Odour classification blocks into explicit top/middle/base lists
- Use Poucher coefficients (1-14 / 15-60 / 61+) as primary classifier
- Tie-break multi-column layouts by header column position
- Generate literature_profiles_poucher.jsonl and attach to formulas

scripts/parse_poucher_profiles.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Poucher structured odour profile parser
2
+
3
+ `parse_poucher_profiles.py` extracts Poucher's `Odour classification` blocks
4
+ into structured volatility profiles:
5
+
6
+ - `top`: materials with Poucher coefficients 1-14
7
+ - `middle`: materials with coefficients 15-60
8
+ - `base`: materials with coefficients 61+
9
+ - `overall`: prose / compounding notes from the page
10
+
11
+ Usage:
12
+
13
+ ```bash
14
+ python scripts/parse_poucher_profiles.py \
15
+ --input /path/to/literature_pages.jsonl \
16
+ --output data/literature_profiles_poucher.jsonl
17
+ ```
18
+
19
+ Generated artifacts (kept out of git; upload to HF dataset repo):
20
+
21
+ - `data/literature_profiles_poucher.jsonl`
22
+ - `data/literature_formulas_poucher_with_profiles.jsonl`
scripts/parse_poucher_profiles.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Parse Poucher "Odour classification" blocks into structured volatility profiles.
5
+
6
+ Poucher pages use a regular layout:
7
+
8
+ Odour classification
9
+ Top notes Middle notes Basic notes
10
+ 1. ... 15. ... 65. ...
11
+
12
+ In the extracted text this can appear as three columns on a single line or as
13
+ stacked headers followed by items. The parser uses Poucher's coefficient ranges
14
+ (1-14 top, 15-60 middle, 61+ basic) as the primary classifier, with column
15
+ position used only as a tie-breaker when headers appear on the same line.
16
+
17
+ Output record:
18
+ {
19
+ "profile_id": "poucher_v2_p{page:04d}_{idx:04d}",
20
+ "source": "...",
21
+ "page": 312,
22
+ "name": "Soap Perfumery: Lily",
23
+ "top": ["Bergamot", "Lemon", ...],
24
+ "middle": ["Jasmine", "Rose", ...],
25
+ "base": ["Sandalwood", "Vetiver", ...],
26
+ "overall": "compounding notes / prose",
27
+ "profile_text": "top: ...; middle: ...; base: ...; overall: ...",
28
+ "raw_text": "..."
29
+ }
30
+ """
31
+
32
+ import json
33
+ import re
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+
38
+ SECTION_LABELS = {
39
+ "top": re.compile(r"\btop\s+notes?\b", re.IGNORECASE),
40
+ "middle": re.compile(r"\bmiddle\s+notes?\b", re.IGNORECASE),
41
+ "base": re.compile(r"\bbasic\s+notes?\b", re.IGNORECASE),
42
+ }
43
+
44
+
45
+ # Fragments that are clearly prose, not odour-material names.
46
+ NOISE_FRAGMENTS = (
47
+ "on this occasion",
48
+ "owing to the",
49
+ "mature for at least",
50
+ "this type is",
51
+ " see the ",
52
+ "monograph on",
53
+ " soap",
54
+ " perfume",
55
+ " formula",
56
+ " no. ",
57
+ "compounding",
58
+ "manufacturing",
59
+ "from the ",
60
+ "that the ",
61
+ "there was",
62
+ "classification of odours",
63
+ "it might be",
64
+ "it is",
65
+ "will be",
66
+ "can be",
67
+ "per cent",
68
+ "the pure substance",
69
+ )
70
+
71
+
72
+ def _is_noise(name: str) -> bool:
73
+ lower = name.lower()
74
+ if any(frag in lower for frag in NOISE_FRAGMENTS):
75
+ return True
76
+ if re.search(r"\b(Soap|Perfume),?\s+no\.\s*\d", name, re.IGNORECASE):
77
+ return True
78
+ return False
79
+
80
+
81
+ def _classify_by_number(num: int) -> str | None:
82
+ if 1 <= num <= 14:
83
+ return "top"
84
+ if 15 <= num <= 60:
85
+ return "middle"
86
+ if num >= 61:
87
+ return "base"
88
+ return None
89
+
90
+
91
+ def _split_line_items(line: str) -> list[tuple[int, str]]:
92
+ """Split a line into one or more (number, material) items."""
93
+ # Find every position where a number begins a new item.
94
+ starts = [(m.start(), m.group(1)) for m in re.finditer(r"\b(\d+)\s*[-.)\s]?\s*[A-Za-z]", line)]
95
+ if not starts:
96
+ return []
97
+ items: list[tuple[int, str]] = []
98
+ for i, (pos, num) in enumerate(starts):
99
+ end = starts[i + 1][0] if i + 1 < len(starts) else len(line)
100
+ raw = line[pos:end]
101
+ m = re.match(r"(\d+)\s*[-.)\s]?\s*(.*)", raw, re.DOTALL)
102
+ if not m:
103
+ continue
104
+ name = m.group(2).strip().strip(".").strip(",").strip()
105
+ if name and len(name) > 1 and not _is_noise(name):
106
+ items.append((int(m.group(1)), name))
107
+ return items
108
+
109
+
110
+ def _extract_items_and_continuations(lines: list[str]) -> list[tuple[int, str]]:
111
+ """Extract (number, material) items, merging continuation lines."""
112
+ items: list[tuple[int, str]] = []
113
+ current: tuple[int, str] | None = None
114
+ for line in lines:
115
+ line = line.strip()
116
+ if not line:
117
+ continue
118
+ # If the line contains a numbered item, flush the previous item and split
119
+ # the line into one or more items (multi-column layout).
120
+ if re.search(r"\b\d+\s*[-.)\s]?\s*[A-Za-z]", line):
121
+ if current and not _is_noise(current[1]):
122
+ items.append(current)
123
+ line_items = _split_line_items(line)
124
+ if line_items:
125
+ current = line_items[-1]
126
+ items.extend(line_items[:-1])
127
+ else:
128
+ current = None
129
+ elif current is not None and line and not re.match(r"\d+", line):
130
+ # Continuation of the previous numbered item.
131
+ cont = line.strip().strip(".").strip(",").strip()
132
+ if cont and not _is_noise(cont):
133
+ current = (current[0], current[1] + " " + cont)
134
+ elif current is not None:
135
+ if not _is_noise(current[1]):
136
+ items.append(current)
137
+ current = None
138
+ if current and not _is_noise(current[1]):
139
+ items.append(current)
140
+ return items
141
+
142
+
143
+ def _extract_page_title(page_text: str) -> str | None:
144
+ """Pull a heading like 'SOAP PERFUMERY: LILY' or 'FLOWER PERFUMES: ROSE'."""
145
+ # Prefer explicit chapter/section headings before the classification.
146
+ for pattern in [
147
+ r"^\s*([A-Z][A-Z\s/,]+):\s*([A-Z][A-Z\s/'’-]+)",
148
+ r"^\s*([A-Z][A-Z\s/,]+)\s+([A-Z][A-Z\s/'’-]+)\s*\n",
149
+ ]:
150
+ m = re.search(pattern, page_text, re.MULTILINE)
151
+ if m:
152
+ return f"{m.group(1).strip().title()}: {m.group(2).strip().title()}"
153
+ return None
154
+
155
+
156
+ def _is_quality_profile(profile: dict[str, Any]) -> bool:
157
+ """Require at least a few items in each section to reduce prose noise."""
158
+ return len(profile.get("top", [])) >= 2 and len(profile.get("middle", [])) >= 2 and len(profile.get("base", [])) >= 2
159
+
160
+
161
+ def _extract_overall(page_text: str) -> str:
162
+ """Capture explanatory prose (Compounding notes + surrounding paragraphs)."""
163
+ m = re.search(r"Odour\s+classification", page_text, re.IGNORECASE)
164
+ if not m:
165
+ return ""
166
+ start = m.start()
167
+ end_m = re.search(
168
+ r"(?:A(?:cacia|lmond|Amber)|C(?:arnation|edar|hypre|ologne|ologne|urd|yclamen)|"
169
+ r"F(?:ern|oug[eè]re)|H(?:eliotrope|erb|yacinth)|Jasmin|"
170
+ r"L(?:avender|ilac|ily)|M(?:ay Blossom|usk)|Narcissus|"
171
+ r"O(?:range Blossom|range-Flower)|Pine Bouquet|"
172
+ r"R(?:ose|ose-Geranium)|Santal|Sweet Pea|Trefle|"
173
+ r"(?:Verbena|Violet))\s+(?:Soap|Perfume),\s*no\.\s*\d+",
174
+ page_text[start:], re.IGNORECASE,
175
+ )
176
+ block = page_text[start : start + end_m.start()] if end_m else page_text[start:]
177
+ # Remove numbered items and header labels to leave only prose.
178
+ prose = re.sub(r"\d+\s*[-.)\s]?\s*[A-Za-z][^\n]*", " ", block, flags=re.IGNORECASE)
179
+ prose = re.sub(
180
+ r"\b(?:Top notes|Middle notes|Basic notes|Odour classification)\b",
181
+ " ",
182
+ prose,
183
+ flags=re.IGNORECASE,
184
+ )
185
+ prose = re.sub(r"\s+", " ", prose).strip()
186
+ return prose[:800]
187
+
188
+
189
+ def _column_positions(header_line: str) -> dict[str, int | None]:
190
+ """Return the approximate start column of each section header on one line."""
191
+ positions: dict[str, int | None] = {}
192
+ for key, label in [("top", "Top"), ("middle", "Middle"), ("base", "Basic")]:
193
+ m = re.search(rf"\b{label}\s+notes?\b", header_line, re.IGNORECASE)
194
+ positions[key] = m.start() if m else None
195
+ return positions
196
+
197
+
198
+ def _multi_header_positions(lines: list[str]) -> dict[str, int]:
199
+ """When headers are stacked on separate lines, record their line indices."""
200
+ positions: dict[str, int] = {}
201
+ for key, rx in SECTION_LABELS.items():
202
+ for i, line in enumerate(lines):
203
+ if rx.search(line):
204
+ positions[key] = i
205
+ break
206
+ return positions
207
+
208
+
209
+ def _parse_one_page(text: str) -> dict[str, Any] | None:
210
+ """Extract the structured classification from a single page's text."""
211
+ has_headers = sum(
212
+ 1 for rx in (SECTION_LABELS["top"], SECTION_LABELS["middle"], SECTION_LABELS["base"])
213
+ if rx.search(text)
214
+ )
215
+ if has_headers < 2:
216
+ return None
217
+
218
+ m = re.search(r"Odour\s+classification", text, re.IGNORECASE)
219
+ if not m:
220
+ return None
221
+ start = m.start()
222
+ end_m = re.search(
223
+ r"\n\s*(?:Compounding\s+notes|"
224
+ r"(?:A(?:cacia|lmond|Amber)|C(?:arnation|edar|hypre|ologne|ologne|urd|yclamen)|"
225
+ r"F(?:ern|oug[eè]re)|H(?:eliotrope|erb|yacinth)|Jasmin|"
226
+ r"L(?:avender|ilac|ily)|M(?:ay Blossom|usk)|Narcissus|"
227
+ r"O(?:range Blossom|range-Flower)|Pine Bouquet|"
228
+ r"R(?:ose|ose-Geranium)|Santal|Sweet Pea|Trefle|"
229
+ r"(?:Verbena|Violet))\s+(?:Soap|Perfume),\s*no\.\s*\d+)",
230
+ text[start:], re.IGNORECASE,
231
+ )
232
+ block = text[start : start + end_m.start()] if end_m else text[start:]
233
+ raw_lines = [ln for ln in block.splitlines()]
234
+
235
+ # Determine whether headers are on a single line or stacked.
236
+ header_line: str | None = None
237
+ for line in raw_lines:
238
+ if sum(bool(rx.search(line)) for rx in SECTION_LABELS.values()) >= 2:
239
+ header_line = line
240
+ break
241
+ single_line_headers = header_line is not None
242
+
243
+ col_pos: dict[str, int | None] = {}
244
+ if single_line_headers:
245
+ col_pos = _column_positions(header_line) # type: ignore[arg-type]
246
+
247
+ # Build ordered column boundaries for single-line header layout.
248
+ ordered: list[tuple[str, int, int | None]] = []
249
+ if single_line_headers:
250
+ sorted_cols = sorted(
251
+ ((k, v) for k, v in col_pos.items() if v is not None),
252
+ key=lambda x: x[1],
253
+ )
254
+ for idx, (key, left) in enumerate(sorted_cols):
255
+ right = sorted_cols[idx + 1][1] if idx + 1 < len(sorted_cols) else None
256
+ ordered.append((key, left, right))
257
+
258
+ # Strip header labels from data lines so they don't create false items.
259
+ data_lines = [
260
+ re.sub(
261
+ r"\b(?:Top notes|Middle notes|Basic notes|Odour classification)\b",
262
+ " ",
263
+ ln,
264
+ flags=re.IGNORECASE,
265
+ )
266
+ for ln in raw_lines
267
+ ]
268
+
269
+ items = _extract_items_and_continuations(data_lines)
270
+
271
+ buckets: dict[str, list[str]] = {"top": [], "middle": [], "base": []}
272
+ for num, name in items:
273
+ # Primary classification by Poucher's coefficient number.
274
+ assigned = _classify_by_number(num)
275
+ # Tie-break using column position if headers are on one line.
276
+ if single_line_headers and assigned:
277
+ # Find the position of this item's leading number in the original raw line.
278
+ for ln in raw_lines:
279
+ nm = re.search(rf"\b{re.escape(str(num))}\b", ln)
280
+ if not nm:
281
+ continue
282
+ pos = nm.start()
283
+ for key, left, right in ordered:
284
+ if right is None:
285
+ if pos >= left - 5:
286
+ assigned = key
287
+ break
288
+ elif left - 5 <= pos < right - 5:
289
+ assigned = key
290
+ break
291
+ break
292
+ if assigned:
293
+ buckets[assigned].append(name)
294
+
295
+ # Drop low-quality / prose-heavy profiles that have no real top/middle/base structure.
296
+ if not _is_quality_profile(buckets):
297
+ return None
298
+
299
+ return {
300
+ "top": buckets["top"],
301
+ "middle": buckets["middle"],
302
+ "base": buckets["base"],
303
+ "overall": _extract_overall(text),
304
+ "raw_text": block.strip()[:2000],
305
+ }
306
+
307
+
308
+ def _build_profile_text(profile: dict[str, Any]) -> str:
309
+ parts = []
310
+ if profile.get("top"):
311
+ parts.append(f"top: {', '.join(profile['top'])}")
312
+ if profile.get("middle"):
313
+ parts.append(f"middle: {', '.join(profile['middle'])}")
314
+ if profile.get("base"):
315
+ parts.append(f"base: {', '.join(profile['base'])}")
316
+ if profile.get("overall"):
317
+ parts.append(f"overall: {profile['overall']}")
318
+ return "; ".join(parts)
319
+
320
+
321
+ def parse_poucher_profiles(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
322
+ profiles: list[dict[str, Any]] = []
323
+ for record in records:
324
+ source = record.get("source", "")
325
+ if "Poucher" not in source:
326
+ continue
327
+ page = record.get("page", 0)
328
+ text = record.get("text", "")
329
+ parsed = _parse_one_page(text)
330
+ if not parsed:
331
+ continue
332
+ title = _extract_page_title(text) or ""
333
+ profile = {
334
+ "profile_id": f"poucher_v2_p{page:04d}_{len(profiles):04d}",
335
+ "source": source,
336
+ "page": page,
337
+ "name": title,
338
+ "top": parsed["top"],
339
+ "middle": parsed["middle"],
340
+ "base": parsed["base"],
341
+ "overall": parsed["overall"],
342
+ "profile_text": _build_profile_text(parsed),
343
+ "raw_text": parsed["raw_text"],
344
+ }
345
+ profiles.append(profile)
346
+ return profiles
347
+
348
+
349
+ def main() -> int:
350
+ import argparse
351
+
352
+ parser = argparse.ArgumentParser(description="Parse Poucher structured odour profiles")
353
+ parser.add_argument("--input", required=True, help="Input JSONL from extract_pdf_text.py")
354
+ parser.add_argument("--output", required=True, help="Output JSONL of profiles")
355
+ args = parser.parse_args()
356
+
357
+ input_path = Path(args.input)
358
+ output_path = Path(args.output)
359
+ output_path.parent.mkdir(parents=True, exist_ok=True)
360
+
361
+ records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
362
+ profiles = parse_poucher_profiles(records)
363
+
364
+ with output_path.open("w", encoding="utf-8") as out:
365
+ for p in profiles:
366
+ out.write(json.dumps(p, ensure_ascii=False) + "\n")
367
+
368
+ print(f"Parsed {len(profiles)} Poucher odour profiles into {output_path}")
369
+ return 0
370
+
371
+
372
+ if __name__ == "__main__":
373
+ raise SystemExit(main())