mattbitzesty commited on
Commit
0ebf67e
·
unverified ·
1 Parent(s): fbfc939

feat(literature): add trade-name resolver, Poucher/Arctander parsers, and PyMuPDF extraction scripts

Browse files
scripts/extract_pdf_text.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Extract text from every page of a fragrance literature PDF using PyMuPDF.
5
+
6
+ Outputs a JSONL file where each line is:
7
+ {"source": "filename", "page": 1, "text": "..."}
8
+ """
9
+
10
+ import argparse
11
+ import json
12
+ import logging
13
+ from pathlib import Path
14
+
15
+ import fitz
16
+
17
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
18
+ logger = logging.getLogger("extract_pdf_text")
19
+
20
+
21
+ def extract_text_from_pdf(pdf_path: Path) -> list[dict[str, str]]:
22
+ doc = fitz.open(str(pdf_path))
23
+ records = []
24
+ for i in range(len(doc)):
25
+ page = doc.load_page(i)
26
+ text = page.get_text()
27
+ records.append({
28
+ "source": pdf_path.stem,
29
+ "page": i + 1,
30
+ "text": text,
31
+ })
32
+ doc.close()
33
+ return records
34
+
35
+
36
+ def main() -> int:
37
+ parser = argparse.ArgumentParser(description="Extract text from PDF pages")
38
+ parser.add_argument("--input", required=True, help="PDF file or directory of PDFs")
39
+ parser.add_argument("--output", required=True, help="Output JSONL path")
40
+ args = parser.parse_args()
41
+
42
+ input_path = Path(args.input)
43
+ output_path = Path(args.output)
44
+ output_path.parent.mkdir(parents=True, exist_ok=True)
45
+
46
+ if input_path.is_dir():
47
+ pdf_files = sorted(input_path.glob("*.pdf"))
48
+ else:
49
+ pdf_files = [input_path]
50
+
51
+ with output_path.open("w", encoding="utf-8") as out:
52
+ for pdf_file in pdf_files:
53
+ logger.info("Extracting %s", pdf_file.name)
54
+ records = extract_text_from_pdf(pdf_file)
55
+ for record in records:
56
+ out.write(json.dumps(record, ensure_ascii=False) + "\n")
57
+
58
+ logger.info("Done: %s", output_path)
59
+ return 0
60
+
61
+
62
+ if __name__ == "__main__":
63
+ raise SystemExit(main())
scripts/parse_arctander.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Parse Arctander "Perfume and Flavor Chemicals" monographs from extracted text.
5
+
6
+ Arctander entries have a regular structure:
7
+ <number>:
8
+ <NAME> [<synonyms>]
9
+ <empirical formula>
10
+ <description of appearance, odor, taste, uses, production>
11
+
12
+ We extract:
13
+ - name, synonyms, cas (if known from cross-reference)
14
+ - empirical_formula, molecular_weight
15
+ - odor_description, taste_description
16
+ - physical_notes (B.P., Sp.Gr., color, solubility)
17
+ - usage_notes (perfumery/flavor uses)
18
+ - source_page
19
+ """
20
+
21
+ import json
22
+ import logging
23
+ import re
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
28
+ logger = logging.getLogger("parse_arctander")
29
+
30
+
31
+ def _extract_number_and_name(block: str) -> tuple[int, str, str]:
32
+ """Parse the leading '123:' monograph number and name."""
33
+ m = re.match(r"(\d+):\s*\n?\s*([^\n]+(?:\n[^\n]+){0,5})", block, re.DOTALL)
34
+ if not m:
35
+ return 0, "", ""
36
+ raw = m.group(2).strip()
37
+ # Name is the first ALL-CAPS or Title-Case line; synonyms follow after a period.
38
+ lines = [l.strip() for l in raw.splitlines() if l.strip()]
39
+ name = lines[0] if lines else ""
40
+ synonyms = " ".join(lines[1:]) if len(lines) > 1 else ""
41
+ return int(m.group(1)), name, synonyms
42
+
43
+
44
+ def _extract_formula_and_weight(block: str) -> tuple[str | None, float | None]:
45
+ """Find empirical formula and molecular weight from the block."""
46
+ # Look for patterns like C10H12O2 = 164.20
47
+ m = re.search(r"([C][^\s=]{0,40}[H][^\s=]{0,40})\s*=\s*([\d\.]+)", block)
48
+ if m:
49
+ formula = m.group(1).strip()
50
+ try:
51
+ weight = float(m.group(2))
52
+ except ValueError:
53
+ weight = None
54
+ return formula, weight
55
+ # Fallback: molecular weight line like "M.W. 164.20"
56
+ m = re.search(r"M\.?W\.?\s*=?\s*([\d\.]+)", block, re.IGNORECASE)
57
+ if m:
58
+ return None, float(m.group(1))
59
+ return None, None
60
+
61
+
62
+ def _extract_bullet_notes(block: str) -> dict[str, str]:
63
+ """Pull out physical properties and odor/taste notes from the description."""
64
+ notes: dict[str, str] = {}
65
+ for label, key in [
66
+ ("B\.P\.", "boiling_point"),
67
+ ("Sp\.Gr\.", "specific_gravity"),
68
+ ("color", "color"),
69
+ ("odor", "odor"),
70
+ ("taste", "taste"),
71
+ ]:
72
+ m = re.search(rf"{label}\s*[^\.\n]{{0,10}}[\.\:]\s*([^\.\n]{{5,200}})", block, re.IGNORECASE)
73
+ if m:
74
+ notes[key] = m.group(1).strip()
75
+ return notes
76
+
77
+
78
+ def parse_arctander_pages(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
79
+ """Parse a list of page records into monograph entries."""
80
+ monographs: list[dict[str, Any]] = []
81
+ for record in records:
82
+ text = record.get("text", "")
83
+ source = record.get("source", "")
84
+ page = record.get("page", 0)
85
+ # Split by monograph numbers followed by a colon and newline
86
+ blocks = re.split(r"(?=\n\s*\d+:\s*\n)", "\n" + text)
87
+ for block in blocks:
88
+ block = block.strip()
89
+ if not block:
90
+ continue
91
+ number, name, synonyms = _extract_number_and_name(block)
92
+ if not name or number == 0:
93
+ continue
94
+ formula, mw = _extract_formula_and_weight(block)
95
+ notes = _extract_bullet_notes(block)
96
+ monographs.append({
97
+ "monograph_number": number,
98
+ "name": name,
99
+ "synonyms": synonyms,
100
+ "empirical_formula": formula,
101
+ "molecular_weight": mw,
102
+ "odor_description": notes.get("odor", ""),
103
+ "taste_description": notes.get("taste", ""),
104
+ "physical_notes": notes,
105
+ "raw_text": block[:3000],
106
+ "source": source,
107
+ "page": page,
108
+ })
109
+ return monographs
110
+
111
+
112
+ def main() -> int:
113
+ parser = argparse.ArgumentParser(description="Parse Arctander monographs from extracted text")
114
+ parser.add_argument("--input", required=True, help="Input JSONL from extract_pdf_text.py")
115
+ parser.add_argument("--output", required=True, help="Output JSONL of parsed monographs")
116
+ args = parser.parse_args()
117
+
118
+ input_path = Path(args.input)
119
+ output_path = Path(args.output)
120
+ output_path.parent.mkdir(parents=True, exist_ok=True)
121
+
122
+ records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
123
+ arctander_records = [r for r in records if "Arctander" in r.get("source", "")]
124
+ monographs = parse_arctander_pages(arctander_records)
125
+
126
+ with output_path.open("w", encoding="utf-8") as out:
127
+ for mono in monographs:
128
+ out.write(json.dumps(mono, ensure_ascii=False) + "\n")
129
+
130
+ logger.info("Parsed %d monographs from Arctander", len(monographs))
131
+ return 0
132
+
133
+
134
+ if __name__ == "__main__":
135
+ import argparse
136
+ raise SystemExit(main())
scripts/parse_poucher.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Targeted parser for Poucher "Perfumes, Cosmetics and Soaps Volume II"
5
+ soap/sachet perfume formulas.
6
+
7
+ Pages 313-360 contain well-structured formulas with material names and parts
8
+ per 1000. The text layout from PyMuPDF sometimes wraps the amount and material
9
+ onto separate lines. This parser looks for a "Name, no. ####" header, then scans
10
+ the following lines for amount/material pairs, allowing either a single line or
11
+ two consecutive lines (amount on one, material on the next), and accepts the
12
+ block when the cumulative sum reaches ~1000.
13
+ """
14
+
15
+ import json
16
+ import re
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+
21
+ # Header: e.g. "Sweet Pea Soap, no. 1250" or "Rose Soap, no. 1057"
22
+ HEADER_RE = re.compile(r"(?i)^([A-Za-z][A-Za-z0-9,\s'/\-()]+)(?:,\s*no\.\s*(\d+))?\s*$")
23
+
24
+
25
+ def _is_header(line: str) -> tuple[str, str | None]:
26
+ m = HEADER_RE.match(line.strip())
27
+ if not m:
28
+ return "", None
29
+ return m.group(1).strip(), m.group(2)
30
+
31
+
32
+ def _is_amount(s: str) -> float | None:
33
+ s = s.strip()
34
+ if s.isdigit():
35
+ val = int(s)
36
+ if 0 < val <= 5000:
37
+ return float(val)
38
+ return None
39
+
40
+
41
+ def _is_material(s: str) -> str | None:
42
+ s = s.strip()
43
+ if len(s) < 3 or s.isdigit():
44
+ return None
45
+ # Reject section markers and noisy fragments
46
+ lower = s.lower()
47
+ BAD = ("top notes", "middle notes", "basic notes", "odour classification",
48
+ "soap perfumery", "transparent", "no. ", "continued", "floral cacho")
49
+ if any(b in lower for b in BAD):
50
+ return None
51
+ # Clean trailing commas/dots and page numbers like "Benzyl acetate, 233,"
52
+ s = re.sub(r",\s*\d+(?:\s*,\s*\d+)*\s*$", "", s).strip()
53
+ s = s.strip(".").strip(",")
54
+ if len(s) < 3:
55
+ return None
56
+ return s
57
+
58
+
59
+ def _extract_pair(lines: list[str], idx: int) -> tuple[dict[str, Any] | None, int]:
60
+ """Try to extract one (amount, material) pair starting at idx.
61
+
62
+ Returns (component, next_idx). May consume 1 or 2 lines.
63
+ """
64
+ if idx >= len(lines):
65
+ return None, idx
66
+ first = lines[idx]
67
+ # Single line: "100 Benzyl acetate"
68
+ m = re.match(r"(\d+(?:\.\d+)?)\s+([A-Za-z][A-Za-z0-9,\s'/\-()]{2,80})$", first.strip())
69
+ if m:
70
+ amount = float(m.group(1))
71
+ material = _is_material(m.group(2))
72
+ if material and 0 < amount <= 5000:
73
+ return {"name": material, "amount": amount, "type": "pure"}, idx + 1
74
+ # Single line: "Benzyl acetate 100"
75
+ m = re.match(r"([A-Za-z][A-Za-z0-9,\s'/\-()]{2,80})\s+(\d+(?:\.\d+)?)$", first.strip())
76
+ if m:
77
+ material = _is_material(m.group(1))
78
+ amount = float(m.group(2))
79
+ if material and 0 < amount <= 5000:
80
+ return {"name": material, "amount": amount, "type": "pure"}, idx + 1
81
+ # Two-line wrap: amount then material
82
+ if idx + 1 < len(lines):
83
+ amount = _is_amount(first)
84
+ material = _is_material(lines[idx + 1])
85
+ if amount is not None and material:
86
+ return {"name": material, "amount": amount, "type": "pure"}, idx + 2
87
+ return None, idx + 1
88
+
89
+
90
+ def parse_poucher_pages(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
91
+ """Parse page records for Poucher-style formulas."""
92
+ formulas: list[dict[str, Any]] = []
93
+ for record in records:
94
+ source = record.get("source", "")
95
+ if "Perfumes, Cosmetics and Soaps" not in source or "Volume II" not in source:
96
+ continue
97
+ page = record.get("page", 0)
98
+ if page < 310 or page > 360:
99
+ continue
100
+ text = record.get("text", "")
101
+ lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
102
+
103
+ idx = 0
104
+ while idx < len(lines):
105
+ name, no = _is_header(lines[idx])
106
+ if no:
107
+ header = lines[idx]
108
+ idx += 1
109
+ components: list[dict[str, Any]] = []
110
+ while idx < len(lines):
111
+ comp, next_idx = _extract_pair(lines, idx)
112
+ if comp is None:
113
+ break
114
+ components.append(comp)
115
+ idx = next_idx
116
+ total = sum(c["amount"] for c in components)
117
+ if len(components) >= 2 and 850 <= total <= 1150:
118
+ formulas.append({
119
+ "formula_id": f"poucher_v2_p{page:04d}_{len(formulas):04d}",
120
+ "name": header,
121
+ "source": source,
122
+ "page": page,
123
+ "components": components,
124
+ })
125
+ else:
126
+ idx += 1
127
+ return formulas
128
+
129
+
130
+ def main() -> int:
131
+ import argparse
132
+ parser = argparse.ArgumentParser(description="Parse Poucher Volume II soap/sachet formulas")
133
+ parser.add_argument("--input", required=True, help="Input JSONL from extract_pdf_text.py")
134
+ parser.add_argument("--output", required=True, help="Output JSONL")
135
+ args = parser.parse_args()
136
+
137
+ input_path = Path(args.input)
138
+ output_path = Path(args.output)
139
+ output_path.parent.mkdir(parents=True, exist_ok=True)
140
+
141
+ records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
142
+ formulas = parse_poucher_pages(records)
143
+
144
+ with output_path.open("w", encoding="utf-8") as out:
145
+ for f in formulas:
146
+ out.write(json.dumps(f, ensure_ascii=False) + "\n")
147
+
148
+ print(f"Parsed {len(formulas)} Poucher formulas into {output_path}")
149
+ return 0
150
+
151
+
152
+ if __name__ == "__main__":
153
+ raise SystemExit(main())
scripts/parse_recipe_books.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Parse fragrance accord skeletons and formula tables from Calkin & Jellinek,
5
+ Poucher, and Appell.
6
+
7
+ These books list multi-component formulations with rough percentages. The parser
8
+ detects lines that look like:
9
+
10
+ Bergamot oil 20
11
+ Petitgrain oil 10
12
+ Musk ketone 5
13
+ Ethanol 65
14
+
15
+ and extracts named ingredients plus numerical amounts. It also detects section
16
+ headers like "Eau de Cologne" or "Chypre" as formula names.
17
+
18
+ Post-processing filters out index entries and cosmetic emulsion bases, keeping
19
+ only plausible fragrance formulas whose amounts sum to a common basis (100, 200,
20
+ 500, or 1000 parts).
21
+ """
22
+
23
+ import json
24
+ import logging
25
+ import re
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
30
+ logger = logging.getLogger("parse_recipe_books")
31
+
32
+
33
+ # Lines that often mark a new formula/accord name.
34
+ FORMULA_HEADER_RE = re.compile(
35
+ r"(?i)(?:no\.\s*\d+|formula|recipes?|compound|type|accord|skeleton|eau de|cologne|chypre|fougere|oriental|amber|moss|rose|jasmine|musk|soap|sachet|tobacco|cachou|flavour|flavor)\s*[\-:]?\s*(.+)?"
36
+ )
37
+
38
+ # Formula header with "Name, no. 1234" pattern (Poucher-style).
39
+ POUCHER_HEADER_RE = re.compile(r"(?i)^([A-Za-z][A-Za-z0-9\s,\-]+(?:no\.\s*\d+)?)\s*$")
40
+
41
+ # A line with a material name and a trailing number (possibly with decimal).
42
+ INGREDIENT_LINE_RE = re.compile(
43
+ r"^([A-Za-z][A-Za-z0-9\-/\s,%().]{3,80}?)(?:\s{2,}|\t|\.{2,})\s*(\d+(?:\.\d+)?)\s*(?:g|kg|ml|parts?| drops?|%|percent)?$",
44
+ re.IGNORECASE,
45
+ )
46
+
47
+ # Also allow comma-separated "Material, 10" within the text.
48
+ COMMA_RE = re.compile(
49
+ r"^([A-Za-z][A-Za-z0-9\-/\s,%().]{3,60})[,\s]+(\d+(?:\.\d+)?)\s*(?:g|kg|ml|parts?|drops?|%|percent)?$",
50
+ re.IGNORECASE,
51
+ )
52
+
53
+ # Index entries look like "Name, 123" or "Name 123" where 123 is a page number (>100).
54
+ INDEX_RE = re.compile(r"[,\s]+(\d+(?:\s*,\s*\d+)*\s*)$")
55
+
56
+ # Words that flag a cosmetic/rubbish entry rather than a fragrance material.
57
+ NON_FRAGRANCE_WORDS = {
58
+ "tween", "natrosol", "carbopol", "triethanolamine", "stearic", "cetyl", "oleyl",
59
+ "glyceryl", "monostearate", "petrolatum", "mineral oil", "vaseline", "lanolin",
60
+ "sorbitol", "propylene glycol", "butylene glycol", "ethanol", "water", "deionized",
61
+ "preservative", "colour", "color", "dye", "titanium", "zinc oxide", "kaolin", "talc",
62
+ "ref.", "page", "no.", "chapter", "index", "introduction", "bibliography", "appendix",
63
+ "table", "figure", "see also", "perfume", "fragrance", "flavor", "cosmetic", "toilet",
64
+ "soap", "cologne", "eau de", "abstract", "summary", "contents", "ml", "grams", "kg",
65
+ }
66
+
67
+
68
+ def _is_header_line(line: str) -> bool:
69
+ stripped = line.strip()
70
+ if bool(FORMULA_HEADER_RE.match(stripped)) and len(stripped) < 80:
71
+ return True
72
+ if POUCHER_HEADER_RE.match(stripped) and "no." in stripped.lower():
73
+ return True
74
+ return False
75
+
76
+
77
+ def _looks_like_index_entry(name: str, amount: float) -> bool:
78
+ """Page numbers in indices are typically >100 and follow the name."""
79
+ if amount > 100 and INDEX_RE.search(name):
80
+ return True
81
+ # Large numbers in the thousands are almost certainly page numbers.
82
+ if amount > 1000:
83
+ return True
84
+ return False
85
+
86
+
87
+ def _looks_like_material(name: str) -> bool:
88
+ """Reject cosmetic excipients and obvious index fragments."""
89
+ lower = name.lower()
90
+ for bad in NON_FRAGRANCE_WORDS:
91
+ if bad in lower:
92
+ return False
93
+ # Must contain at least one alphabetic word of reasonable length.
94
+ words = [w for w in re.findall(r"[a-zA-Z]+", name) if len(w) > 2]
95
+ return len(words) > 0
96
+
97
+
98
+ def _parse_amount_line(line: str) -> tuple[str, float] | None:
99
+ line = line.strip()
100
+ if not line or len(line) < 5:
101
+ return None
102
+ for pattern in (INGREDIENT_LINE_RE, COMMA_RE):
103
+ m = pattern.match(line)
104
+ if m:
105
+ name = m.group(1).strip().strip(".")
106
+ amount = float(m.group(2))
107
+ if amount <= 0 or amount > 10000:
108
+ return None
109
+ return name, amount
110
+ return None
111
+
112
+
113
+ def _is_valid_formula(components: list[dict[str, Any]]) -> bool:
114
+ """
115
+ A valid fragrance formula has 2-20 material lines, amounts summing to a
116
+ common basis within tolerance, and no obvious index/cosmetic entries.
117
+ """
118
+ if len(components) < 2 or len(components) > 20:
119
+ return False
120
+ total = sum(c["amount"] for c in components)
121
+ # Common raw bases: 100, 200, 500, 1000 parts/grams. Allow 10% tolerance.
122
+ valid_basis = any(abs(total - basis) / basis <= 0.12 for basis in (100, 200, 500, 1000))
123
+ if not valid_basis:
124
+ return False
125
+ # Reject if any component looks like an index or non-fragrance material.
126
+ for c in components:
127
+ if not _looks_like_material(c["name"]):
128
+ return False
129
+ if _looks_like_index_entry(c["name"], c["amount"]):
130
+ return False
131
+ return True
132
+
133
+
134
+ def parse_recipe_pages(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
135
+ """Parse page records into candidate formula blocks."""
136
+ formulas: list[dict[str, Any]] = []
137
+ for record in records:
138
+ text = record.get("text", "")
139
+ source = record.get("source", "")
140
+ page = record.get("page", 0)
141
+ lines = text.splitlines()
142
+ current_formula: dict[str, Any] | None = None
143
+
144
+ for line in lines:
145
+ stripped = line.strip()
146
+ if not stripped:
147
+ # Blank line may end a formula block.
148
+ if current_formula and _is_valid_formula(current_formula.get("components", [])):
149
+ formulas.append(current_formula)
150
+ current_formula = None
151
+ continue
152
+
153
+ if _is_header_line(stripped) and (current_formula is None or len(current_formula.get("components", [])) < 2):
154
+ current_formula = {
155
+ "formula_id": f"{source.replace(' ', '_')[:40]}_p{page:04d}_{len(formulas):04d}",
156
+ "name": stripped,
157
+ "source": source,
158
+ "page": page,
159
+ "components": [],
160
+ }
161
+ continue
162
+
163
+ parsed = _parse_amount_line(stripped)
164
+ if parsed:
165
+ name, amount = parsed
166
+ if current_formula is None:
167
+ current_formula = {
168
+ "formula_id": f"{source.replace(' ', '_')[:40]}_p{page:04d}_{len(formulas):04d}",
169
+ "name": f"Detected formula p{page}",
170
+ "source": source,
171
+ "page": page,
172
+ "components": [],
173
+ }
174
+ current_formula["components"].append({"name": name, "amount": amount, "type": "pure"})
175
+
176
+ if current_formula and _is_valid_formula(current_formula.get("components", [])):
177
+ formulas.append(current_formula)
178
+
179
+ return formulas
180
+
181
+
182
+ def main() -> int:
183
+ parser = argparse.ArgumentParser(description="Parse recipe/accord books from extracted text")
184
+ parser.add_argument("--input", required=True, help="Input JSONL from extract_pdf_text.py")
185
+ parser.add_argument("--output", required=True, help="Output JSONL of candidate formulas")
186
+ args = parser.parse_args()
187
+
188
+ input_path = Path(args.input)
189
+ output_path = Path(args.output)
190
+ output_path.parent.mkdir(parents=True, exist_ok=True)
191
+
192
+ records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
193
+ # Exclude Arctander from this parser; target Calkin, Poucher, Appell, Sell.
194
+ target_records = [r for r in records if "Arctander" not in r.get("source", "")]
195
+ formulas = parse_recipe_pages(target_records)
196
+
197
+ with output_path.open("w", encoding="utf-8") as out:
198
+ for f in formulas:
199
+ out.write(json.dumps(f, ensure_ascii=False) + "\n")
200
+
201
+ logger.info("Parsed %d candidate formulas from recipe books", len(formulas))
202
+ return 0
203
+
204
+
205
+ if __name__ == "__main__":
206
+ import argparse
207
+ raise SystemExit(main())
src/pino/__init__.py CHANGED
@@ -1,5 +1,5 @@
1
  from __future__ import annotations
2
 
3
- from pino import models, structures, verifier, vle, evaporation
4
-
5
- __all__ = ["models", "structures", "verifier", "vle", "evaporation"]
 
1
  from __future__ import annotations
2
 
3
+ # Package marker: avoid eager imports of heavy/optional dependencies.
4
+ # Submodules are imported on demand by callers.
5
+ __all__ = []
src/pino/ocr_client.py CHANGED
@@ -36,13 +36,30 @@ def upload_file(file_path: str | Path, token: str | None = None) -> dict[str, An
36
  return data
37
 
38
 
39
- def call_ocr(file_data: dict[str, Any], endpoint: str = "v2", token: str | None = None) -> str:
40
  """Call the OCR endpoint and return the event_id to poll."""
41
  url = f"{SPACE_API}/call/{endpoint}"
42
  headers = {"Content-Type": "application/json"}
43
  if token:
44
  headers["Authorization"] = f"Bearer {token}"
45
- payload = {"data": [file_data]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  response = requests.post(url, json=payload, headers=headers, timeout=60)
47
  response.raise_for_status()
48
  data = response.json()
@@ -50,39 +67,48 @@ def call_ocr(file_data: dict[str, Any], endpoint: str = "v2", token: str | None
50
  return str(data["event_id"])
51
 
52
 
53
- def poll_result(event_id: str, token: str | None = None, timeout: float = 120.0) -> dict[str, Any]:
54
- """Poll the result endpoint until completion or timeout."""
55
- url = f"{SPACE_API}/call/{event_id}"
 
 
 
 
56
  headers = {}
57
  if token:
58
  headers["Authorization"] = f"Bearer {token}"
59
  deadline = time.time() + timeout
 
60
  while time.time() < deadline:
61
- response = requests.get(url, headers=headers, timeout=30)
62
  response.raise_for_status()
63
- # The endpoint returns Server-Sent Events or JSON depending on state.
64
  for line in response.text.splitlines():
65
  line = line.strip()
66
- if not line:
 
 
 
 
67
  continue
68
- if line.startswith("data:"):
69
- try:
70
- payload = json.loads(line[5:].strip())
71
- except json.JSONDecodeError:
72
- continue
73
- if isinstance(payload, dict):
74
- return payload
75
- if isinstance(payload, list) and len(payload) > 0:
76
- return {"result": payload}
77
- time.sleep(2.0)
78
  raise TimeoutError(f"OCR polling timed out for event_id {event_id}")
79
 
80
 
81
  def extract_text(file_path: str | Path, token: str | None = None) -> str:
82
  """End-to-end: upload a file, run OCR, and return the extracted text."""
83
  file_data = upload_file(file_path, token=token)
84
- event_id = call_ocr(file_data, token=token)
85
- result = poll_result(event_id, token=token)
86
  # The OCR result is typically a list of strings or a single string.
87
  if isinstance(result, dict) and "result" in result:
88
  data = result["result"]
 
36
  return data
37
 
38
 
39
+ def call_ocr(file_data: dict[str, Any], endpoint: str = "run_ocr", token: str | None = None) -> str:
40
  """Call the OCR endpoint and return the event_id to poll."""
41
  url = f"{SPACE_API}/call/{endpoint}"
42
  headers = {"Content-Type": "application/json"}
43
  if token:
44
  headers["Authorization"] = f"Bearer {token}"
45
+
46
+ # Ensure file_data is a proper Gradio FileData dict.
47
+ if isinstance(file_data, str):
48
+ file_payload = {
49
+ "path": file_data,
50
+ "url": None,
51
+ "size": None,
52
+ "orig_name": None,
53
+ "mime_type": None,
54
+ "is_stream": False,
55
+ "meta": {"_type": "gradio.FileData"},
56
+ }
57
+ else:
58
+ file_payload = dict(file_data)
59
+ if "meta" not in file_payload:
60
+ file_payload["meta"] = {"_type": "gradio.FileData"}
61
+
62
+ payload = {"data": [file_payload, "gundam", "document parsing"]}
63
  response = requests.post(url, json=payload, headers=headers, timeout=60)
64
  response.raise_for_status()
65
  data = response.json()
 
67
  return str(data["event_id"])
68
 
69
 
70
+ def poll_result(event_id: str, endpoint: str = "run_ocr", token: str | None = None, timeout: float = 180.0) -> dict[str, Any]:
71
+ """Poll the result endpoint until completion or timeout.
72
+
73
+ Gradio streaming endpoints emit Server-Sent Events. We accumulate ``text``
74
+ chunks until ``done`` is true, then return the concatenated result.
75
+ """
76
+ url = f"{SPACE_API}/call/{endpoint}/{event_id}"
77
  headers = {}
78
  if token:
79
  headers["Authorization"] = f"Bearer {token}"
80
  deadline = time.time() + timeout
81
+ collected_text_parts: list[str] = []
82
  while time.time() < deadline:
83
+ response = requests.get(url, headers=headers, timeout=60)
84
  response.raise_for_status()
85
+ done = False
86
  for line in response.text.splitlines():
87
  line = line.strip()
88
+ if not line or not line.startswith("data:"):
89
+ continue
90
+ try:
91
+ payload = json.loads(line[5:].strip())
92
+ except json.JSONDecodeError:
93
  continue
94
+ if isinstance(payload, dict):
95
+ if payload.get("text"):
96
+ collected_text_parts.append(str(payload["text"]))
97
+ if payload.get("done"):
98
+ done = True
99
+ elif isinstance(payload, list) and len(payload) > 0:
100
+ return {"result": payload}
101
+ if done:
102
+ return {"result": "".join(collected_text_parts)}
103
+ time.sleep(1.0)
104
  raise TimeoutError(f"OCR polling timed out for event_id {event_id}")
105
 
106
 
107
  def extract_text(file_path: str | Path, token: str | None = None) -> str:
108
  """End-to-end: upload a file, run OCR, and return the extracted text."""
109
  file_data = upload_file(file_path, token=token)
110
+ event_id = call_ocr(file_data, endpoint="run_ocr", token=token)
111
+ result = poll_result(event_id, endpoint="run_ocr", token=token)
112
  # The OCR result is typically a list of strings or a single string.
113
  if isinstance(result, dict) and "result" in result:
114
  data = result["result"]
src/pino/trade_name_resolver.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Resolve common fragrance trade names to CAS numbers for literature formula ingestion.
5
+
6
+ Primary source: local SQLite registry (aroma_chemicals).
7
+ Fallback: hardcoded mapping for trade names and naturals that the registry may not include.
8
+ """
9
+
10
+ import re
11
+ import sqlite3
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from rapidfuzz import fuzz, process
16
+
17
+
18
+ TRADE_TO_CAS: dict[str, str] = {
19
+ # Common trade / natural names
20
+ "rosewood": "8015-77-8",
21
+ "rosewood oil": "8015-77-8",
22
+ "bois de rose oil": "8015-77-8",
23
+ "bergamot": "8007-75-8",
24
+ "bergamot oil": "8007-75-8",
25
+ "santal": "8006-87-9",
26
+ "sandalwood": "8006-87-9",
27
+ "sandalwood oil": "8006-87-9",
28
+ "santalwood oil": "8006-87-9",
29
+ "cedarwood": "8000-27-9",
30
+ "cedarwood oil": "8000-27-9",
31
+ "cedarwood oil, virginia": "8000-27-9",
32
+ "lavender": "8000-28-0",
33
+ "lavender oil": "8000-28-0",
34
+ "lavender flowers": "8000-28-0",
35
+ "lavender, spike": "8016-78-2",
36
+ "spike lavender": "8016-78-2",
37
+ "lavender oil, m.b": "8000-28-0",
38
+ "lavender oil, french": "8000-28-0",
39
+ "lavender oil, english": "8000-28-0",
40
+ "lavandin": "93455-97-1",
41
+ "geranium": "8000-46-2",
42
+ "geranium oil": "8000-46-2",
43
+ "geranium, bourbon": "8000-46-2",
44
+ "geranium oil, bourbon": "8000-46-2",
45
+ "geranium oil, algerian": "8000-46-2",
46
+ "geranium, algerian": "8000-46-2",
47
+ "rose otto": "8007-01-0",
48
+ "rose absolute": "8007-01-0",
49
+ "rose petals": "8007-01-0",
50
+ "rose geranium oil": "8000-46-2",
51
+ "rose geranium oil, french": "8000-46-2",
52
+ "phenylethyl alcohol": "60-12-8",
53
+ "phenyl ethyl alcohol": "60-12-8",
54
+ "phenyl ethyl acetate": "103-45-7",
55
+ "benzyl acetate": "140-11-4",
56
+ "iso-butyl phenylacetate": "102-13-6",
57
+ "isobutyl phenylacetate": "102-13-6",
58
+ "methyl heptine carbonate": "111-12-6",
59
+ "methyl heptin carbonate": "111-12-6",
60
+ "methyl nonyl acetaldehyde": "112-12-9",
61
+ "aldehyde c 11": "112-44-7",
62
+ "aldehyde c 12": "112-54-9",
63
+ "aldehyde c 8": "124-13-0",
64
+ "aldehyde c 10": "112-31-2",
65
+ "aldehyde c 12": "112-54-9",
66
+ "ald c 8": "124-13-0",
67
+ "ald c 10": "112-31-2",
68
+ "ald c 11": "112-44-7",
69
+ "ald c 12": "112-54-9",
70
+ "amyl cinnamic aldehyde": "122-40-7",
71
+ "amyl salicylate": "2050-08-0",
72
+ "anisic aldehyde": "123-11-5",
73
+ "bromstyrole": "2039-67-0",
74
+ "bromstyrol": "2039-67-0",
75
+ "cananga": "68606-83-7",
76
+ "cananga oil": "68606-83-7",
77
+ "ylang-ylang oil": "8006-81-3",
78
+ "ylang-ylang oil, bourbon": "8006-81-3",
79
+ "cassia": "8007-80-5",
80
+ "cassia oil": "8007-80-5",
81
+ "ceylon cinnamon": "8007-80-5",
82
+ "cinnamon ceylon": "8007-80-5",
83
+ "clove": "8000-34-8",
84
+ "clove oil": "8000-34-8",
85
+ "clove bud oil": "8000-34-8",
86
+ "patchouli": "8014-09-3",
87
+ "patchouli oil": "8014-09-3",
88
+ "patchouli leaves": "8014-09-3",
89
+ "patchouli oil, english": "8014-09-3",
90
+ "vetivert": "8016-96-4",
91
+ "vetivert oil": "8016-96-4",
92
+ "vetivert roots": "8016-96-4",
93
+ "vetiver": "8016-96-4",
94
+ "vetiver oil": "8016-96-4",
95
+ "oakmoss": "9000-50-4",
96
+ "oakmoss absolute": "9000-50-4",
97
+ "oakmoss absolute, green": "9000-50-4",
98
+ "mousse de saxe": "",
99
+ "tonka beans": "9000-65-5",
100
+ "tonka absolute": "9000-65-5",
101
+ "coumarin": "91-64-5",
102
+ "vanillin": "121-33-5",
103
+ "heliotropin": "120-57-0",
104
+ "piperonal": "120-57-0",
105
+ "musk ambrette": "83-66-9",
106
+ "musk ketone": "81-14-1",
107
+ "musk xylene": "81-15-2",
108
+ "musk xylol": "81-15-2",
109
+ "musk residues": "",
110
+ "musk tincture, 3 per cent": "",
111
+ "civet extract, 3 per cent": "68916-26-7",
112
+ "civet absolute": "68916-26-7",
113
+ "civet": "68916-26-7",
114
+ "ambergris extract, 3 per cent": "9000-64-2",
115
+ "ambergris": "9000-64-2",
116
+ "ambre": "",
117
+ "ambrene": "",
118
+ "ambroxan": "6790-58-5",
119
+ "siam benzoin": "9000-64-0",
120
+ "benzoin resin": "9000-64-0",
121
+ "benzoin tincture, 10 per cent": "9000-64-0",
122
+ "peru balsam": "8007-00-9",
123
+ "peru balsam oil": "8007-00-9",
124
+ "peru balsam": "8007-00-9",
125
+ "tolu balsam": "9000-64-0",
126
+ "tolu balsam oil": "9000-64-0",
127
+ "styrax resin": "8046-19-3",
128
+ "styrax absolute": "8046-19-3",
129
+ "liquidambar resin": "8024-13-1",
130
+ "olibanum resin": "8050-07-5",
131
+ "frankincense": "8050-07-5",
132
+ "opopanax": "8023-89-0",
133
+ "myrrh": "9000-45-9",
134
+ "galbanum resin": "8023-91-4",
135
+ "galbanum oil": "8023-91-4",
136
+ "orris": "8002-73-1",
137
+ "orris root": "8002-73-1",
138
+ "orris concrete": "8002-73-1",
139
+ "orris oil": "8002-73-1",
140
+ "orris oil, concrete": "8002-73-1",
141
+ "orris resin": "8002-73-1",
142
+ "tincture of orris": "8002-73-1",
143
+ "tincture of vanilla": "8047-24-3",
144
+ "vanilla essence, 10 per cent": "8047-24-3",
145
+ "tincture of tonka": "9000-65-5",
146
+ "tincture of benzoin": "9000-64-0",
147
+ "tincture of tolu, 10 per cent": "9000-64-0",
148
+ "jasmine absolute": "8022-96-6",
149
+ "jasmin absolute": "8022-96-6",
150
+ "jasmine": "8022-96-6",
151
+ "jasmin": "8022-96-6",
152
+ "jasmine compound": "8022-96-6",
153
+ "jasmin compound": "8022-96-6",
154
+ "jasmin, compound": "8022-96-6",
155
+ "neroli oil": "8016-38-4",
156
+ "neroli oil, bigarade": "8016-38-4",
157
+ "orange blossom absolute": "8016-38-4",
158
+ "orange oil, sweet": "8008-57-9",
159
+ "sweet orange oil": "8008-57-9",
160
+ "sweet orange oil, 10 fold": "8008-57-9",
161
+ "lemon oil": "8008-56-8",
162
+ "lemon": "8008-56-8",
163
+ "mandarin oil": "8008-31-9",
164
+ "petitgrain": "8014-17-3",
165
+ "petitgrain para": "8014-17-3",
166
+ "petitgrain oil": "8014-17-3",
167
+ "petitgrain oil, french": "8014-17-3",
168
+ "petitgrain para": "8014-17-3",
169
+ "bergamot": "8007-75-8",
170
+ "citronella, java": "8000-29-1",
171
+ "citronella, ceylon": "89997-75-1",
172
+ "ceylon citronella": "89997-75-1",
173
+ "lemongrass": "8007-02-1",
174
+ "citral": "5392-40-5",
175
+ "geraniol, java": "106-24-1",
176
+ "geraniol": "106-24-1",
177
+ "geranyl acetate": "105-87-3",
178
+ "geranyl formate": "105-86-2",
179
+ "linalool": "78-70-6",
180
+ "linalyl acetate": "115-95-7",
181
+ "citronellol": "106-22-9",
182
+ "ionone": "8013-90-9",
183
+ "methyl ionone": "1335-46-2",
184
+ "ionone beta": "14901-07-6",
185
+ "isoeugenol": "97-54-1",
186
+ "iso-eugenol": "97-54-1",
187
+ "benzyl iso-eugenol": "120-11-6",
188
+ "eugenol": "97-53-0",
189
+ "methyl anthranilate": "134-20-3",
190
+ "dimethyl anthranilate": "606-09-1",
191
+ "paracresyl acetate": "140-39-6",
192
+ "p-cresyl acetate": "140-39-6",
193
+ "amyl valerianate": "2173-56-0",
194
+ "amyl valerate": "2173-56-0",
195
+ "ethyl acetate": "141-78-6",
196
+ "ethyl malonate": "105-53-3",
197
+ "ethyl benzoate": "93-89-0",
198
+ "ethyl butyrate": "105-54-4",
199
+ "ethyl oenanthate": "123-66-0",
200
+ "ethyl heptanoate": "123-66-0",
201
+ "geranyl butyrate": "106-29-6",
202
+ "acetaldehyde": "75-07-0",
203
+ "chloroform": "67-66-3",
204
+ " bornyl acetate": "76-49-3",
205
+ "borneol": "507-70-0",
206
+ "camphor": "76-22-2",
207
+ "fir needle, siberian": "8021-29-2",
208
+ "fir needle siberian": "8021-29-2",
209
+ "sassafras": "8006-80-2",
210
+ "sassafras oil": "8006-80-2",
211
+ "thyme, red": "8007-46-3",
212
+ "thyme oil": "8007-46-3",
213
+ "thyme oil, red": "8007-46-3",
214
+ "eucalyptus oil": "8000-48-4",
215
+ "rosemary oil": "8000-25-7",
216
+ "peppermint oil": "8006-90-4",
217
+ "spearmint oil": "8008-79-5",
218
+ "caraway": "85940-31-4",
219
+ "caraway oil": "85940-31-4",
220
+ "anise": "8007-70-3",
221
+ "anise oil": "8007-70-3",
222
+ "star anise": "8007-70-3",
223
+ "fennel, sweet": "8006-84-6",
224
+ "sweet fennel": "8006-84-6",
225
+ "bitter almond": "8013-76-1",
226
+ "almond oil, bitter s.a.p": "8013-76-1",
227
+ "almond oil, bitter s.a.p.": "8013-76-1",
228
+ "benzaldehyde": "100-52-7",
229
+ "cinnamon bark oil": "8015-91-6",
230
+ "cinnamon oil": "8007-80-5",
231
+ "cinnamon oil, ceylon": "8007-80-5",
232
+ "cassia oil": "8007-80-5",
233
+ "nutmeg": "8008-45-5",
234
+ "pimento": "8006-77-7",
235
+ "allspice": "8006-77-7",
236
+ "clove stem oil": "8000-34-8",
237
+ "clove leaf oil": "8000-34-8",
238
+ "mace": "8007-12-3",
239
+ "cedarleaf oil": "8006-80-2",
240
+ "cade oil": "8011-10-3",
241
+ "birch tar": "84012-40-2",
242
+ "guaiac wood": "8016-23-7",
243
+ "guaiacwood oil": "8016-23-7",
244
+ "rose ether": "141-12-8",
245
+ "rhodinol": "6812-78-8",
246
+ "dimethyl benzyl carbinol": "100-86-7",
247
+ "phenyl ethyl dimethyl carbinol": "100-86-7",
248
+ "hedione": "24851-98-7",
249
+ "methyl dihydrojasmonate": "24851-98-7",
250
+ "iso e super": "54464-57-2",
251
+ "iso e super": "54464-57-2",
252
+ "ambroxan": "6790-58-5",
253
+ "ambrox": "6790-58-5",
254
+ "galaxolide": "1222-05-5",
255
+ "tibetine": "",
256
+ "terpineol": "8000-41-7",
257
+ "terpineol, alpha": "98-55-5",
258
+ "hydroxy citronellal": "107-75-5",
259
+ "cyclamen aldehyde": "103-95-7",
260
+ "indole": "120-72-9",
261
+ "terebene": "8032-35-1",
262
+ "benzylidene acetone": "122-57-6",
263
+ "musk extract, 3 per cent": "",
264
+ "phenylethyl valerianate": "7462-86-6",
265
+ "rhodinyl valerianate": "85409-36-9",
266
+ "cascarilla oil": "8007-06-5",
267
+ "nutmeg oil": "8008-45-5",
268
+ "musk tincture, 3 per cent": "",
269
+ "dimethyl hydroquinone": "150-78-7",
270
+ "labdanum clair": "8016-26-0",
271
+ "castoreum extract, 3 per cent": "8023-79-2",
272
+ "clary sage, concrete": "8016-63-5",
273
+ "clary sage concrete": "8016-63-5",
274
+ "castoreum absolute": "8023-79-2",
275
+ "castoreum": "8023-79-2",
276
+ "mimosa absolute": "8031-03-6",
277
+ "cassie absolute": "8015-61-0",
278
+ "tuberose compound": "",
279
+ "orange blossom compound": "",
280
+ "apple blossom b": "",
281
+ "fougere b": "",
282
+ "muguet": "",
283
+ "narcissus": "8023-75-2",
284
+ "lily": "9000-40-2",
285
+ "lily of the valley": "",
286
+ "violet leaves absolute": "8024-08-6",
287
+ "violet leaf absolute": "8024-08-6",
288
+ "hawthorn": "",
289
+ "sweet pea": "",
290
+ "trefle": "",
291
+ "tretle": "",
292
+ "transparent": "",
293
+ "pine bouquet": "",
294
+ "shaving stick": "",
295
+ "flake": "",
296
+ "apple base": "",
297
+ "chypre": "",
298
+ "heliotrope": "",
299
+ "carnation": "",
300
+ "rose": "",
301
+ "violet": "",
302
+ "musk": "",
303
+ "fougere": "",
304
+ "amber": "",
305
+ "oriental": "",
306
+ "orange blossom": "8016-38-4",
307
+ # Solvents / carriers not used in fragrance concentrate, skip
308
+ "ethanol": "",
309
+ "alcohol": "",
310
+ "sd alcohol 38 f": "",
311
+ "tincture of vanilla": "8047-24-3",
312
+ "tincture of benzoin": "9000-64-0",
313
+ "tincture of tonka": "9000-65-5",
314
+ "tincture of orris": "8002-73-1",
315
+ "tincture of tolu": "9000-64-0",
316
+ "musk tincture, 3 per cent": "",
317
+ "civet extract, 3 per cent": "68916-26-7",
318
+ "ambergris extract, 3 per cent": "9000-64-2",
319
+ }
320
+
321
+
322
+ class TradeNameResolver:
323
+ def __init__(self, registry_db: Path | str = "/home/hermes/pino/src/pino/registry.db"):
324
+ self.registry: dict[str, str] = {}
325
+ self.aliases: dict[str, str] = {}
326
+ self._load_registry(registry_db)
327
+ self._build_alias_index()
328
+
329
+ def _load_registry(self, registry_db: Path | str) -> None:
330
+ conn = sqlite3.connect(str(registry_db))
331
+ conn.row_factory = sqlite3.Row
332
+ cur = conn.cursor()
333
+ try:
334
+ cur.execute("SELECT cas, name FROM aroma_chemicals")
335
+ for row in cur.fetchall():
336
+ cas = row["cas"]
337
+ if not cas:
338
+ continue
339
+ key = row["name"]
340
+ if key:
341
+ self.registry[key.lower()] = cas
342
+ finally:
343
+ conn.close()
344
+
345
+ def _build_alias_index(self) -> None:
346
+ for name, cas in TRADE_TO_CAS.items():
347
+ self.aliases[name.lower()] = cas
348
+ # Also index stripped version without "oil"
349
+ simple = name.lower().replace(" oil", "").strip()
350
+ if simple and simple != name.lower():
351
+ self.aliases.setdefault(simple, cas)
352
+
353
+ def resolve(self, name: str, threshold: float = 80.0) -> str | None:
354
+ """Return a CAS number for a trade name, or None if unresolved."""
355
+ key = name.lower().strip().strip(".")
356
+ if key in self.aliases:
357
+ return self.aliases[key] or None
358
+ if key in self.registry:
359
+ return self.registry[key]
360
+ # Fuzzy match against registry keys
361
+ match = process.extractOne(key, self.registry.keys(), scorer=fuzz.token_sort_ratio)
362
+ if match and match[1] >= threshold:
363
+ return self.registry[match[0]]
364
+ # Fuzzy match against aliases
365
+ match = process.extractOne(key, self.aliases.keys(), scorer=fuzz.token_sort_ratio)
366
+ if match and match[1] >= threshold:
367
+ return self.aliases[match[0]] or None
368
+ return None
369
+
370
+
371
+ def clean_literature_formula(raw: dict[str, Any]) -> dict[str, Any] | None:
372
+ """Convert a raw parsed formula into a normalized literature formula entry."""
373
+ resolver = TradeNameResolver()
374
+ components: list[dict[str, Any]] = []
375
+ for c in raw.get("components", []):
376
+ name = c["name"]
377
+ cas = resolver.resolve(name)
378
+ if cas:
379
+ components.append({"cas": cas, "amount": c["amount"], "type": "pure"})
380
+ else:
381
+ components.append({"name": name, "amount": c["amount"], "type": "unknown"})
382
+
383
+ if all(c["type"] == "unknown" for c in components):
384
+ return None
385
+
386
+ total = sum(c["amount"] for c in components)
387
+ if total <= 0:
388
+ return None
389
+
390
+ normalized = []
391
+ for c in components:
392
+ entry = dict(c)
393
+ entry["amount"] = round(c["amount"] / total, 6)
394
+ if entry["type"] == "unknown":
395
+ entry["type"] = "sub_base" # treat unresolved trade names as accord sub-bases
396
+ normalized.append(entry)
397
+
398
+ return {
399
+ "formula_id": raw["formula_id"],
400
+ "name": raw["name"],
401
+ "source": raw.get("source", ""),
402
+ "page": raw.get("page", 0),
403
+ "raw_basis_sum": total,
404
+ "components": normalized,
405
+ }
406
+
407
+
408
+ if __name__ == "__main__":
409
+ import json, argparse
410
+ parser = argparse.ArgumentParser()
411
+ parser.add_argument("--input", required=True)
412
+ parser.add_argument("--output", required=True)
413
+ args = parser.parse_args()
414
+ in_path = Path(args.input)
415
+ out_path = Path(args.output)
416
+ out_path.parent.mkdir(parents=True, exist_ok=True)
417
+ raw_formulas = [json.loads(line) for line in in_path.read_text().strip().splitlines()]
418
+ clean = [f for f in (clean_literature_formula(r) for r in raw_formulas) if f]
419
+ with out_path.open("w", encoding="utf-8") as f:
420
+ for entry in clean:
421
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
422
+ print(f"Resolved {len(clean)}/{len(raw_formulas)} formulas")