pino-source-code / scripts /parse_poucher_profiles.py
mattbitzesty's picture
feat(literature): add structured Poucher odour profile parser
73075a8 unverified
Raw History Blame
13.2 kB
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())