pino-source-code / scripts /parse_poucher.py
mattbitzesty's picture
feat(literature): add trade-name resolver, Poucher/Arctander parsers, and PyMuPDF extraction scripts
0ebf67e unverified
Raw History Blame
5.53 kB
from __future__ import annotations
"""
Targeted parser for Poucher "Perfumes, Cosmetics and Soaps Volume II"
soap/sachet perfume formulas.
Pages 313-360 contain well-structured formulas with material names and parts
per 1000. The text layout from PyMuPDF sometimes wraps the amount and material
onto separate lines. This parser looks for a "Name, no. ####" header, then scans
the following lines for amount/material pairs, allowing either a single line or
two consecutive lines (amount on one, material on the next), and accepts the
block when the cumulative sum reaches ~1000.
"""
import json
import re
from pathlib import Path
from typing import Any
# Header: e.g. "Sweet Pea Soap, no. 1250" or "Rose Soap, no. 1057"
HEADER_RE = re.compile(r"(?i)^([A-Za-z][A-Za-z0-9,\s'/\-()]+)(?:,\s*no\.\s*(\d+))?\s*$")
def _is_header(line: str) -> tuple[str, str | None]:
m = HEADER_RE.match(line.strip())
if not m:
return "", None
return m.group(1).strip(), m.group(2)
def _is_amount(s: str) -> float | None:
s = s.strip()
if s.isdigit():
val = int(s)
if 0 < val <= 5000:
return float(val)
return None
def _is_material(s: str) -> str | None:
s = s.strip()
if len(s) < 3 or s.isdigit():
return None
# Reject section markers and noisy fragments
lower = s.lower()
BAD = ("top notes", "middle notes", "basic notes", "odour classification",
"soap perfumery", "transparent", "no. ", "continued", "floral cacho")
if any(b in lower for b in BAD):
return None
# Clean trailing commas/dots and page numbers like "Benzyl acetate, 233,"
s = re.sub(r",\s*\d+(?:\s*,\s*\d+)*\s*$", "", s).strip()
s = s.strip(".").strip(",")
if len(s) < 3:
return None
return s
def _extract_pair(lines: list[str], idx: int) -> tuple[dict[str, Any] | None, int]:
"""Try to extract one (amount, material) pair starting at idx.
Returns (component, next_idx). May consume 1 or 2 lines.
"""
if idx >= len(lines):
return None, idx
first = lines[idx]
# Single line: "100 Benzyl acetate"
m = re.match(r"(\d+(?:\.\d+)?)\s+([A-Za-z][A-Za-z0-9,\s'/\-()]{2,80})$", first.strip())
if m:
amount = float(m.group(1))
material = _is_material(m.group(2))
if material and 0 < amount <= 5000:
return {"name": material, "amount": amount, "type": "pure"}, idx + 1
# Single line: "Benzyl acetate 100"
m = re.match(r"([A-Za-z][A-Za-z0-9,\s'/\-()]{2,80})\s+(\d+(?:\.\d+)?)$", first.strip())
if m:
material = _is_material(m.group(1))
amount = float(m.group(2))
if material and 0 < amount <= 5000:
return {"name": material, "amount": amount, "type": "pure"}, idx + 1
# Two-line wrap: amount then material
if idx + 1 < len(lines):
amount = _is_amount(first)
material = _is_material(lines[idx + 1])
if amount is not None and material:
return {"name": material, "amount": amount, "type": "pure"}, idx + 2
return None, idx + 1
def parse_poucher_pages(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Parse page records for Poucher-style formulas."""
formulas: list[dict[str, Any]] = []
for record in records:
source = record.get("source", "")
if "Perfumes, Cosmetics and Soaps" not in source or "Volume II" not in source:
continue
page = record.get("page", 0)
if page < 310 or page > 360:
continue
text = record.get("text", "")
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
idx = 0
while idx < len(lines):
name, no = _is_header(lines[idx])
if no:
header = lines[idx]
idx += 1
components: list[dict[str, Any]] = []
while idx < len(lines):
comp, next_idx = _extract_pair(lines, idx)
if comp is None:
break
components.append(comp)
idx = next_idx
total = sum(c["amount"] for c in components)
if len(components) >= 2 and 850 <= total <= 1150:
formulas.append({
"formula_id": f"poucher_v2_p{page:04d}_{len(formulas):04d}",
"name": header,
"source": source,
"page": page,
"components": components,
})
else:
idx += 1
return formulas
def main() -> int:
import argparse
parser = argparse.ArgumentParser(description="Parse Poucher Volume II soap/sachet formulas")
parser.add_argument("--input", required=True, help="Input JSONL from extract_pdf_text.py")
parser.add_argument("--output", required=True, help="Output JSONL")
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()]
formulas = parse_poucher_pages(records)
with output_path.open("w", encoding="utf-8") as out:
for f in formulas:
out.write(json.dumps(f, ensure_ascii=False) + "\n")
print(f"Parsed {len(formulas)} Poucher formulas into {output_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())