mattbitzesty commited on
Commit
eaf6535
·
unverified ·
1 Parent(s): 0c18170

feat(ingest): TGSC demo formula scraper + odor cache

Browse files

- Add scripts/ingest_tgsc.py for fetching TGSC demonstration formulas,
parsing ingredient tables, normalizing weights, and mapping names to
registry CAS via overrides and fuzzy matching.
- Capture narrative descriptions and per-ingredient TGSC links that were
previously dropped by the scraper.
- Add TGSC ingredient-page odor enrichment with persistent on-disk cache
(scripts/build_tgsc_odor_cache.py) so ingest is resumable.
- Add --enrich-tgsc-odor and --lookup-external flags to the ingest CLI.
- Add requests, beautifulsoup4, and openai to project dependencies.

pyproject.toml CHANGED
@@ -21,6 +21,9 @@ dependencies = [
21
  "tensorboard>=2.15",
22
  "matplotlib>=3.8",
23
  "umap-learn>=0.5",
 
 
 
24
  ]
25
 
26
  [project.optional-dependencies]
 
21
  "tensorboard>=2.15",
22
  "matplotlib>=3.8",
23
  "umap-learn>=0.5",
24
+ "requests>=2.31",
25
+ "beautifulsoup4>=4.12",
26
+ "openai>=1.0",
27
  ]
28
 
29
  [project.optional-dependencies]
scripts/build_tgsc_odor_cache.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """One-off builder for TGSC ingredient odor cache.
3
+
4
+ Fetches organoleptic descriptors for every unique TGSC ingredient link found
5
+ in a TGSC demo formula dataset and persists them to data/tgsc_odor_cache.json.
6
+ Subsequent ingest_tgsc.py runs use this cache and complete instantly.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib.util
12
+ import json
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+
17
+ import requests
18
+ from bs4 import BeautifulSoup
19
+
20
+ src = Path(__file__).parent.parent / "src"
21
+ if str(src) not in sys.path:
22
+ sys.path.insert(0, str(src))
23
+
24
+ _INGEST_PATH = Path(__file__).parent / "ingest_tgsc.py"
25
+ _ingest_spec = importlib.util.spec_from_file_location("ingest_tgsc", _INGEST_PATH)
26
+ assert _ingest_spec and _ingest_spec.loader
27
+ _ingest_module = importlib.util.module_from_spec(_ingest_spec)
28
+ sys.modules["ingest_tgsc"] = _ingest_module
29
+ _ingest_spec.loader.exec_module(_ingest_module)
30
+
31
+ _absolute_tgsc_url = _ingest_module._absolute_tgsc_url
32
+ _load_tgsc_odor_cache = _ingest_module._load_tgsc_odor_cache
33
+ _save_tgsc_odor_cache = _ingest_module._save_tgsc_odor_cache
34
+ _is_known_header = _ingest_module._is_known_header
35
+
36
+
37
+ def _fetch(link: str) -> dict:
38
+ result = {
39
+ "url": link,
40
+ "odor_type": [],
41
+ "odor_descriptions": [],
42
+ "flavor_type": [],
43
+ "taste_descriptions": [],
44
+ "vapor_pressure_pa": None,
45
+ "error": None,
46
+ }
47
+ try:
48
+ resp = requests.get(link, headers={"User-Agent": "PinoDataIngest/1.0"}, timeout=20)
49
+ resp.raise_for_status()
50
+ except Exception as exc:
51
+ result["error"] = str(exc)
52
+ return result
53
+
54
+ soup = BeautifulSoup(resp.text, "html.parser")
55
+ page_text = soup.get_text("\n")
56
+ lines = [l.strip() for l in page_text.splitlines() if l.strip()]
57
+
58
+ i = 0
59
+ while i < len(lines):
60
+ line = lines[i]
61
+ low = line.lower()
62
+
63
+ if low.startswith("odor type:"):
64
+ j = i + 1
65
+ while j < len(lines) and not _is_known_header(lines[j]):
66
+ result["odor_type"].append(lines[j])
67
+ j += 1
68
+ i = j
69
+ continue
70
+
71
+ if low.startswith("odor description:"):
72
+ j = i + 1
73
+ while j < len(lines) and not _is_known_header(lines[j]):
74
+ result["odor_descriptions"].append(lines[j])
75
+ j += 1
76
+ i = j
77
+ continue
78
+
79
+ if low.startswith("flavor type:"):
80
+ j = i + 1
81
+ while j < len(lines) and not _is_known_header(lines[j]):
82
+ result["flavor_type"].append(lines[j])
83
+ j += 1
84
+ i = j
85
+ continue
86
+
87
+ if low.startswith("taste description:"):
88
+ j = i + 1
89
+ while j < len(lines) and not _is_known_header(lines[j]):
90
+ result["taste_descriptions"].append(lines[j])
91
+ j += 1
92
+ i = j
93
+ continue
94
+
95
+ i += 1
96
+
97
+ # Vapor pressure: look for "Vapor Pressure: X Pa (Y mm Hg)"
98
+ for line in lines:
99
+ if "vapor pressure" in line.lower():
100
+ m = __import__("re").search(r"([0-9.]+)\s*Pa", line)
101
+ if m:
102
+ result["vapor_pressure_pa"] = float(m.group(1))
103
+ break
104
+
105
+ return result
106
+
107
+
108
+ def main() -> int:
109
+ data_path = Path(__file__).parent.parent / "data" / "tgsc_demo_formulas_v2.jsonl"
110
+ if not data_path.exists():
111
+ print(f"Dataset not found: {data_path}")
112
+ return 1
113
+
114
+ records = [json.loads(line) for line in data_path.open()]
115
+ links: set[str] = set()
116
+ for rec in records:
117
+ for item in rec.get("formula", []):
118
+ link = item.get("link")
119
+ abs_url = _absolute_tgsc_url(link)
120
+ if abs_url:
121
+ links.add(abs_url)
122
+
123
+ print(f"Unique TGSC ingredient links to fetch: {len(links)}")
124
+
125
+ cache = _load_tgsc_odor_cache()
126
+ print(f"Already cached: {len(cache)}")
127
+
128
+ todo = [l for l in links if l not in cache]
129
+ print(f"To fetch: {len(todo)}")
130
+
131
+ for idx, link in enumerate(todo, 1):
132
+ cache[link] = _fetch(link)
133
+ if idx % 50 == 0:
134
+ _save_tgsc_odor_cache(cache)
135
+ print(f"Fetched {idx}/{len(todo)}; cache size: {len(cache)}")
136
+ time.sleep(0.2)
137
+
138
+ _save_tgsc_odor_cache(cache)
139
+ print(f"Done. Cache size: {len(cache)}")
140
+ return 0
141
+
142
+
143
+ if __name__ == "__main__":
144
+ raise SystemExit(main())
scripts/ingest_tgsc.py ADDED
@@ -0,0 +1,1216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Scrape, clean, and map The Good Scents Company demo formulas into PINO format.
3
+
4
+ Usage:
5
+ export ZAI_API_KEY="..."
6
+ PYTHONPATH=src python scripts/ingest_tgsc.py [--label] [--limit N]
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import re
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import requests
19
+ from bs4 import BeautifulSoup, Tag
20
+
21
+ from pino.registry import AromaRegistry
22
+ from pino.thermo.naturals import NATURAL_PROFILES
23
+
24
+
25
+ # TGSC pages known to contain demo formulas (discovered via probing and web search).
26
+ KNOWN_DEMO_PAGES = [
27
+ 1001492, 1002631, 1002632, 1002641, 1002651, 1002652, 1002671, 1003981, 1006041,
28
+ 1009771, 1012432, 1013351, 1015111, 1015272, 1018851, 1020191, 1020271, 1029341,
29
+ 1036291, 1059381, 1061001, 1103321, 1105542, 1109231, 1113201, 1424291, 1433011,
30
+ 1542791, 1544211, 1690071,
31
+ ]
32
+
33
+ SOLVENT_CAS = "25265-71-8" # DPG proxy
34
+
35
+
36
+ # TGSC-specific name overrides for things that do not match the AromaRegistry.
37
+ TGSC_NAME_OVERRIDES: dict[str, str] = {
38
+ "dipg": "25265-71-8",
39
+ "dpg": "25265-71-8",
40
+ "cade oil in dpg": "NATURAL:8013-10-3",
41
+ "portugal": "8007-75-8",
42
+ "fixolide": "54982-83-1",
43
+ "thibetolide": "7779-50-2",
44
+ "kephalis": "54464-57-2",
45
+ "givescone": "28940-11-6",
46
+ "bacdanol": "28219-60-5",
47
+ "ambroxan": "3738-00-9",
48
+ "ambrox": "3738-00-9",
49
+ "ambrettolide": "7779-50-2",
50
+ "agrume": "94201-04-2",
51
+ "agrumex hc": "94201-04-2",
52
+ "isoraldeine 40": "8013-90-9",
53
+ "isoraldeine": "8013-90-9",
54
+ "green acetate": "3681-71-8",
55
+ "lilial": "80-54-6",
56
+ "helional": "1205-17-0",
57
+ "helional a": "1205-17-0",
58
+ "hedione": "24851-98-7",
59
+ "ebanol": "81786-73-4",
60
+ "gardenol": "68133-79-9",
61
+ "maltol": "118-71-8",
62
+ "ethyl maltol": "4940-11-8",
63
+ "cashmeran": "33704-61-9",
64
+ "cetalox": "109291-46-5",
65
+ "ambroxdiol": "132153-74-9",
66
+ "javanol": "198404-98-7",
67
+ "sandalore": "65113-99-5",
68
+ "polysantol": "66068-84-6",
69
+ "firsantal": "196109-17-8",
70
+ "liffarome": "18368-95-1",
71
+ "florhydral": "125109-85-5",
72
+ "triplal": "68039-49-6",
73
+ "vertocitral": "54830-99-8",
74
+ "undecavertol": "81782-77-6",
75
+ "muguet aldehyde": "18368-95-1",
76
+ "cortylande": "105-91-5",
77
+ "cassis": "617-54-9",
78
+ "rhoisal": "36306-87-3",
79
+ "maitone": "470-90-6",
80
+ "sulfurol": "137-00-8",
81
+ "cis-3-hexenyl acetate": "3681-71-8",
82
+ "hexyl acetate": "142-92-7",
83
+ "styrallyl acetate": "93-92-5",
84
+ "freskomenthe": "87061-04-9",
85
+ "methyl benzoate": "93-58-3",
86
+ "ethyl benzoate": "93-89-0",
87
+ "phenyl ethyl alcohol": "60-12-8",
88
+ "phenylethyl alcohol": "60-12-8",
89
+ "phenethylol": "60-12-8",
90
+ "phenyl ethyl acetate": "103-45-7",
91
+ "phenethyl acetate": "103-45-7",
92
+ "para-anisyl alcohol": "105-13-5",
93
+ "para-anisaldehyde": "123-11-5",
94
+ "para-anisyl acetate": "140-39-6",
95
+ "para-tolyl aldehyde": "104-87-0",
96
+ "para-cresyl methyl ether": "104-93-8",
97
+ "methyl cinnamate": "103-26-4",
98
+ "ethyl cinnamate": "4192-77-2",
99
+ "cinnamic alcohol": "104-54-1",
100
+ "cinnamic aldehyde": "104-55-2",
101
+ "cinnamaldehyde": "104-55-2",
102
+ "cinnamyl acetate": "21040-45-9",
103
+ "cinnamyl alcohol": "104-54-1",
104
+ "eugenol": "97-53-0",
105
+ "isoeugenol": "97-54-1",
106
+ "methyl eugenol": "93-15-2",
107
+ "ethyl eugenol": "2785-89-9",
108
+ "vanillin": "121-33-5",
109
+ "ethyl vanillin": "121-32-4",
110
+ "coumarin": "91-64-5",
111
+ "heliotropin": "120-57-0",
112
+ "piperonal": "120-57-0",
113
+ "musk ketone": "81-14-1",
114
+ "musk xylol": "81-15-2",
115
+ "galaxolide": "1222-05-5",
116
+ "tonalid": "1506-02-1",
117
+ "celestolide": "13171-00-1",
118
+ "pharmlactone": "104-67-6",
119
+ "exaltolide": "106-02-5",
120
+ "habanolide": "111879-80-2",
121
+ "ambrettol": "124-07-2",
122
+ "jasmal": "18871-14-2",
123
+ "jasmonyl": "106-02-5",
124
+ "nerolidol": "142-50-7",
125
+ "farnesol": "4602-84-0",
126
+ "geraniol": "106-24-1",
127
+ "nerol": "106-25-2",
128
+ "linalool": "78-70-6",
129
+ "linalol": "78-70-6",
130
+ "ethyl linalool": "39255-35-5",
131
+ "dihydro myrcenol": "18479-58-8",
132
+ "dihydromyrcenol": "18479-58-8",
133
+ "citronellol": "106-22-9",
134
+ "rhodinol": "141-25-3",
135
+ "geranyl acetate": "164-09-4",
136
+ "geranyl butyrate": "106-29-6",
137
+ "geranyl isobutyrate": "2345-24-6",
138
+ "linalyl acetate": "115-95-7",
139
+ "citronellyl acetate": "150-84-5",
140
+ "isoamyl salicylate": "87-20-7",
141
+ "benzyl salicylate": "118-58-1",
142
+ "hexyl salicylate": "6259-76-3",
143
+ "methyl salicylate": "119-36-8",
144
+ "ethyl salicylate": "118-61-6",
145
+ "alpha-terpineol": "98-55-5",
146
+ "terpineol": "8000-41-7",
147
+ "terpineol alpha": "98-55-5",
148
+ "lyral": "31906-04-4",
149
+ "cyclamen aldehyde": "103-95-7",
150
+ "mandarin oil": "8008-31-9",
151
+ "florol": "63500-71-0",
152
+ "evernyl": "4707-47-3",
153
+ "undecalactone gamma": "104-67-6",
154
+ "gamma undecalactone": "104-67-6",
155
+ "allyl heptanoate": "142-19-8",
156
+ "raspberry ketone": "5471-51-2",
157
+ "melonal": "106-72-9",
158
+ "tropional": "68039-49-6",
159
+ "allyl cyclohexyl propionate": "2705-87-5",
160
+ "fructone": "68555-63-5",
161
+ "phenoxyethyl isobutyrate": "103-48-0",
162
+ "lavandin oil": "8022-15-9",
163
+ "ambrofix": "6790-58-5",
164
+ "manzanate": "39255-32-2",
165
+ "veramoss": "90028-68-5",
166
+ "coranol": "406093-69-4",
167
+ "muscenone": "82356-51-2",
168
+ "cosmone": "32768-82-8",
169
+ "vertofix": "54464-57-2",
170
+ "verdox": "54464-57-2",
171
+ "iso e super": "54464-57-2",
172
+ "vertocitral": "54830-99-8",
173
+ "woodynol": "66068-84-6",
174
+ "synambrane": "26446-35-5",
175
+ "habanolide": "111879-80-2",
176
+ "javanol": "198404-98-7",
177
+ "sandalore": "65113-99-5",
178
+ "polysantol": "66068-84-6",
179
+ "firsantal": "196109-17-8",
180
+ "ebanol": "81786-73-4",
181
+ "bacdanol": "28219-60-5",
182
+ "jasmal": "18871-14-2",
183
+ "jasmonyl": "106-02-5",
184
+ "ambroxan": "3738-00-9",
185
+ "ambrox": "3738-00-9",
186
+ "cetalox": "109291-46-5",
187
+ "ambroxdiol": "132153-74-9",
188
+ "cashmeran": "33704-61-9",
189
+ "fixolide": "54982-83-1",
190
+ "thibetolide": "7779-50-2",
191
+ "kephalis": "54464-57-2",
192
+ "givescone": "28940-11-6",
193
+ "gardenol": "68133-79-9",
194
+ "liffarome": "18368-95-1",
195
+ "florhydral": "125109-85-5",
196
+ "triplal": "68039-49-6",
197
+ "undecavertol": "81782-77-6",
198
+ "muguet aldehyde": "18368-95-1",
199
+ "cortylande": "105-91-5",
200
+ "cassis": "617-54-9",
201
+ "rhoisal": "36306-87-3",
202
+ "maitone": "470-90-6",
203
+ "sulfurol": "137-00-8",
204
+ "cis-3-hexenyl acetate": "3681-71-8",
205
+ "hexyl acetate": "142-92-7",
206
+ "styrallyl acetate": "93-92-5",
207
+ "freskomenthe": "87061-04-9",
208
+ "methyl benzoate": "93-58-3",
209
+ "ethyl benzoate": "93-89-0",
210
+ "tomato leaf absolute": "90131-24-1",
211
+ "ethyl butyrate": "105-54-4",
212
+ "ethyl acetate": "141-78-6",
213
+ "ethyl acetoacetate": "141-97-9",
214
+ "strawberry glycidate 1": "unknown",
215
+ "aldehyde c-6": "66-25-1",
216
+ "aldehyde c-8": "124-13-0",
217
+ "aldehyde c-9": "112-31-2",
218
+ "aldehyde c-10": "112-31-2",
219
+ "aldehyde c-11 undecylenic": "112-45-8",
220
+ "aldehyde c-12 lauric": "112-54-9",
221
+ "aldehyde c-12 mna": "110-41-8",
222
+ "aldehyde c-14": "104-67-6",
223
+ "aldehyde c-16": "77-83-8",
224
+ "aldehyde c-18": "104-67-6",
225
+ "aldehyde iso c-11": "8016-83-3",
226
+ "methyl octine carbonate": "111-80-8",
227
+ "methyl heptine carbonate": "111-12-6",
228
+ "dimethyl anthranilate": "85-74-5",
229
+ "methyl anthranilate": "134-20-3",
230
+ "ethyl anthranilate": "87-25-2",
231
+ "gamma-decalactone": "706-14-9",
232
+ "gamma-undecalactone": "104-67-6",
233
+ "delta-undecalactone": "706-14-9",
234
+ "cyclogalbanate": "68912-13-0",
235
+ "alpha-damascone": "43052-87-5",
236
+ "beta-damascone": "35044-57-6",
237
+ "delta-damascone": "57378-72-0",
238
+ "alpha-ionone": "127-41-3",
239
+ "beta-ionone": "14901-07-6",
240
+ "alpha-isomethyl ionone": "127-51-5",
241
+ "methyl ionone": "1335-46-2",
242
+ "dihydro-beta-ionone": "13720-12-2",
243
+ "alpha-hexyl cinnamaldehyde": "101-86-0",
244
+ "alpha-amyl cinnamaldehyde": "122-40-7",
245
+ "amyl cinnamaldehyde": "122-40-7",
246
+ "hexyl cinnamaldehyde": "101-86-0",
247
+ "mandarin aldehyde": "540-18-1",
248
+ "2,3,5-trimethyl pyrazine": "14667-55-1",
249
+ "2-acetyl pyrazine": "22047-25-2",
250
+ "ethyl pyrazine": "13925-00-3",
251
+ "isobutyraldehyde": "78-84-2",
252
+ "isovaleraldehyde": "590-86-3",
253
+ "phenyl acetaldehyde": "122-78-1",
254
+ "phenylacetaldehyde": "122-78-1",
255
+ "acetal r": "68133-13-1",
256
+ "acetate pa": "142-92-7",
257
+ "allyl amyl glycolate": "67634-20-2",
258
+ "allyl caproate": "123-68-2",
259
+ "ethyl caprylate": "106-32-1",
260
+ "ethyl oenanthate": "123-66-0",
261
+ "3-phenyl propyl alcohol": "122-97-4",
262
+ "3-phenyl propyl acetate": "122-72-5",
263
+ "dextro-limonene": "5989-27-5",
264
+ "laevo-carvone": "6485-40-1",
265
+ "carvone": "99-49-0",
266
+ "rose oxide": "16409-43-1",
267
+ "buchu leaf oil": "8013-43-0",
268
+ "nutmeg oil": "8008-45-5",
269
+ "bay leaf oil": "8006-78-8",
270
+ "ginger root oil": "8007-08-7",
271
+ "clove bud oil": "8000-34-8",
272
+ "ylang ylang oil": "8006-81-3",
273
+ "cedarwood oil virginia": "8000-27-9",
274
+ "cedarwood oil virginia brown": "8000-27-9",
275
+ "cedarwood oil atlas": "8000-27-9",
276
+ "lemon oil": "NATURAL:8008-56-8",
277
+ "orange oil": "NATURAL:8008-57-9",
278
+ "lime oil distilled mexico": "NATURAL:8008-26-2",
279
+ "bergamot oil bergaptene reduced": "NATURAL:8007-35-0",
280
+ "petitgrain oil": "NATURAL:8014-17-3",
281
+ "lavender oil": "NATURAL:8000-28-0",
282
+ "geranium oil": "NATURAL:8000-46-2",
283
+ "guaiacwood oil": "NATURAL:8016-23-7",
284
+ "carrot seed oil": "8015-88-1",
285
+ "pimento berry oil": "8006-39-1",
286
+ "chamomile flower oil morocco": "8015-92-7",
287
+ "armoise oil": "8023-88-9",
288
+ "immortelle flower resinoid": "90131-24-1",
289
+ "rose absolute bulgaria": "NATURAL:8007-01-0",
290
+ "orris rhizome concrete": "90045-43-5",
291
+ "ambrarome absolute": "8023-83-4",
292
+ "cade oil": "8013-10-3",
293
+ "galbanum oil": "8023-91-4",
294
+ "tomato leaf absolute": "unknown",
295
+ "hay absolute": "8023-91-4",
296
+ "tobacco absolute": "8037-19-0",
297
+ "labdanum absolute": "8016-26-0",
298
+ "opoponax resinoid": "NATURAL:9000-78-6",
299
+ "myrrh resinoid": "NATURAL:8016-37-3",
300
+ "benzoin siam resinoid": "NATURAL:9000-05-9",
301
+ "styrax resinoid": "8046-42-0",
302
+ "peru balsam": "8007-00-9",
303
+ "tolu balsam": "9000-64-0",
304
+ "elemi resinoid": "8023-89-0",
305
+ "olibanum resinoid": "8016-36-2",
306
+ "frankincense oil": "8016-36-2",
307
+ "rum ether": "unknown",
308
+ "dimethyl benzyl carbinyl acetate": "151-05-3",
309
+ "dimethyl benzyl carbinyl butyrate": "10094-34-5",
310
+ "dimethyl benzyl carbinol": "100-86-7",
311
+ "ethyl 1,3-dioxolan-2-yl-2-methyl acetate": "unknown",
312
+ "methyl cedryl ketone": "32388-55-9",
313
+ "verdyl acetate": "80-26-2",
314
+ "iso e super": "54464-57-2",
315
+ "2-methyl-7-tert.butyl-1,4-dioxaspiro[4,5]decane": "unknown",
316
+ "1,3-dioxolane": "unknown",
317
+ "benzyl alcohol": "100-51-6",
318
+ "benzyl acetate": "140-11-4",
319
+ "benzyl benzoate": "120-51-4",
320
+ "phenyl acetaldehyde": "122-78-1",
321
+ "phenethyl alcohol": "60-12-8",
322
+ }
323
+
324
+
325
+ def _normalize_name(name: str) -> str:
326
+ """Lowercase, strip extra whitespace, remove trailing punctuation."""
327
+ name = name.lower().strip()
328
+ name = re.sub(r"[\s]+", " ", name)
329
+ name = re.sub(r"[,.;]+$", "", name)
330
+ return name
331
+
332
+
333
+ def build_tgsc_mapping(registry: AromaRegistry) -> dict[str, str]:
334
+ """Build a lower-cased name -> CAS/NATURAL:* mapping from registry, profiles, and overrides."""
335
+ mapping: dict[str, str] = {}
336
+
337
+ # 1. Registry names first.
338
+ for rec in registry.all_records().values():
339
+ rname = rec.get("name", "")
340
+ cas = rec.get("cas", "")
341
+ if rname and cas and not cas.startswith("SMILES:"):
342
+ mapping[_normalize_name(rname)] = cas
343
+
344
+ # 2. Natural profiles override/add aliases.
345
+ for token, profile in NATURAL_PROFILES.items():
346
+ mapping[_normalize_name(profile["name"])] = token
347
+ for suffix in [" oil", " absolute", " resinoid"]:
348
+ if profile["name"].lower().endswith(suffix):
349
+ mapping[profile["name"].lower().replace(suffix, "")] = token
350
+ mapping[profile["name"].lower().replace(suffix, "") + suffix] = token
351
+
352
+ # 3. TGSC-specific overrides take highest precedence.
353
+ for raw, cas in TGSC_NAME_OVERRIDES.items():
354
+ mapping[_normalize_name(raw)] = cas
355
+
356
+ return mapping
357
+
358
+
359
+ def map_ingredient(name: str, mapping: dict[str, str]) -> str | None:
360
+ """Map a TGSC ingredient name to a CAS or NATURAL:* token. Returns None if unresolved."""
361
+ norm = _normalize_name(name)
362
+
363
+ if norm in mapping:
364
+ return mapping[norm]
365
+
366
+ # Strip trailing parenthetical qualifiers like (Firmenich), (Givaudan), 70% min., etc.
367
+ stripped = re.sub(r"\s*\([^)]*\)\s*$", "", norm).strip()
368
+ if stripped and stripped != norm and stripped in mapping:
369
+ return mapping[stripped]
370
+
371
+ # Strip common suffixes that indicate dilution, base, or synth versions.
372
+ for suffix in [" base", " synth", " synthetic", " natural", " 10%", " 20%", " 50%"]:
373
+ if stripped.endswith(suffix):
374
+ cand = stripped[: -len(suffix)].strip()
375
+ if cand in mapping:
376
+ return mapping[cand]
377
+
378
+ for prefix in ["synthetic ", "natural ", "pure ", "concentrated ", "concentrate "]:
379
+ if norm.startswith(prefix):
380
+ cand = norm[len(prefix):].strip()
381
+ if cand in mapping:
382
+ return mapping[cand]
383
+
384
+ # Fuzzy match is dangerous: "lavender aldehyde" would match "lavender oil".
385
+ # Only use it as a last resort and require the whole ingredient name to be
386
+ # contained in a dictionary key (not the other way around).
387
+ for key, cas in mapping.items():
388
+ if key.startswith("NATURAL:"):
389
+ continue
390
+ if key in norm:
391
+ return cas
392
+
393
+ return None
394
+
395
+
396
+ def _parse_table_formula(table: Tag) -> dict[str, Any] | None:
397
+ """Parse a single demo formula from a TGSC table element.
398
+
399
+ TGSC uses classes dmow1..dmow8 on table cells. Rows may be wrapped in
400
+ <tbody> on some pages, so callers must pass a table that already contains
401
+ all relevant rows.
402
+ """
403
+ rows = table.find_all("tr")
404
+ title = None
405
+ source = None
406
+ application = None
407
+ description_lines: list[str] = []
408
+ notes: list[str] = []
409
+ ingredients = []
410
+
411
+ for row in rows:
412
+ cells = [c.get_text(strip=True) for c in row.find_all(["td", "th"])]
413
+ if not cells:
414
+ continue
415
+ classes = [c.get("class") for c in row.find_all(["td", "th"])]
416
+ flat_classes = [cls for sub in classes if sub for cls in sub]
417
+
418
+ if "dmow1" in flat_classes:
419
+ title = cells[0] if cells else None
420
+ elif "dmow2" in flat_classes or "dmow3" in flat_classes:
421
+ text = cells[0] if cells else ""
422
+ if not text:
423
+ continue
424
+ low = text.lower()
425
+ # dmow2 is usually the source/citation; on newer pages it may contain a
426
+ # short descriptive paragraph. dmow3 is usually the application.
427
+ is_citation = bool(re.search(r"patent\s*[0-9,]+", text, re.I)) or \
428
+ bool(re.search(r"pg\.\s*\d+", text, re.I)) or \
429
+ bool(re.search(r"\b(19|20)\d{2}\b", text)) or \
430
+ "cosmetic, fragrances and flavors" in low or \
431
+ "novox" in low or \
432
+ "bedoukian" in low or \
433
+ "firmenich" in low or \
434
+ "iff" in low or \
435
+ "symrise" in low
436
+ is_application = low.startswith("application:")
437
+
438
+ if is_application:
439
+ application = text
440
+ elif is_citation and not source:
441
+ source = text
442
+ else:
443
+ description_lines.append(text)
444
+ elif "dmow8" in flat_classes:
445
+ text = cells[0] if cells else ""
446
+ if text and text not in notes:
447
+ notes.append(text)
448
+ elif "dmow5" in flat_classes and "dmow6" in flat_classes:
449
+ weight_text = cells[0] if len(cells) > 0 else ""
450
+ name_text = cells[1] if len(cells) > 1 else ""
451
+ try:
452
+ weight = float(weight_text.replace(",", ""))
453
+ except ValueError:
454
+ continue
455
+ if not name_text or "total" in name_text.lower():
456
+ continue
457
+ dilution_match = re.search(r"(\d+)%\s*$", name_text)
458
+ dilution = float(dilution_match.group(1)) / 100.0 if dilution_match else 1.0
459
+ name = re.sub(r"\s+\d+%\s*$", "", name_text).strip()
460
+ link = None
461
+ a_tag = row.find("a")
462
+ if a_tag and isinstance(a_tag, Tag):
463
+ link = a_tag.get("href")
464
+ ingredients.append({"name": name, "weight": weight, "dilution": dilution, "link": link})
465
+ elif "dmow7" in flat_classes:
466
+ # dmow7 is sometimes used for an ingredient in a second column layout;
467
+ # treat it the same as dmow6.
468
+ weight_text = cells[0] if len(cells) > 0 else ""
469
+ name_text = cells[1] if len(cells) > 1 else ""
470
+ try:
471
+ weight = float(weight_text.replace(",", ""))
472
+ except ValueError:
473
+ continue
474
+ if not name_text or "total" in name_text.lower():
475
+ continue
476
+ dilution_match = re.search(r"(\d+)%\s*$", name_text)
477
+ dilution = float(dilution_match.group(1)) / 100.0 if dilution_match else 1.0
478
+ name = re.sub(r"\s+\d+%\s*$", "", name_text).strip()
479
+ link = None
480
+ a_tag = row.find("a")
481
+ if a_tag and isinstance(a_tag, Tag):
482
+ link = a_tag.get("href")
483
+ ingredients.append({"name": name, "weight": weight, "dilution": dilution, "link": link})
484
+ elif len(cells) == 1 and cells[0]:
485
+ # Catch-all for descriptive paragraphs that don't have a known class.
486
+ text = cells[0]
487
+ if not text.lower().startswith("total") and text not in description_lines:
488
+ description_lines.append(text)
489
+
490
+ if not title or not ingredients:
491
+ return None
492
+
493
+ # Build a formula-level description from the captured dmow2/dmow3/free-form lines.
494
+ description = " ".join(description_lines).strip()
495
+
496
+ return {
497
+ "meta": {
498
+ "title": title,
499
+ "source": source,
500
+ "application": application,
501
+ "notes": [n for n in notes if n],
502
+ "description": description or None,
503
+ },
504
+ "ingredients": ingredients,
505
+ }
506
+
507
+
508
+ def scrape_tgsc_page(demo_id: int) -> list[dict[str, Any]]:
509
+ """Scrape a TGSC demo page and return all formula blocks found on it."""
510
+ url = f"https://www.thegoodscentscompany.com/demos/dm{demo_id}.html"
511
+ try:
512
+ response = requests.get(url, headers={"User-Agent": "PinoDataIngest/1.0"}, timeout=20)
513
+ except requests.RequestException as exc:
514
+ print(f"{demo_id}: request error {exc}")
515
+ return []
516
+
517
+ if response.status_code != 200:
518
+ return []
519
+
520
+ soup = BeautifulSoup(response.text, "html.parser")
521
+ table = soup.find("table", id="tableList5")
522
+ if not table or not isinstance(table, Tag):
523
+ return []
524
+
525
+ formulas = []
526
+ current_rows: list[Tag] = []
527
+ for row in table.find_all("tr"):
528
+ # Skip the nested table header row used on some pages.
529
+ cells = row.find_all(["td", "th"])
530
+ classes = [c.get("class") for c in cells]
531
+ flat_classes = [cls for sub in classes if sub for cls in sub]
532
+ if "subcomp" in flat_classes:
533
+ continue
534
+ if "dmow1" in flat_classes and current_rows:
535
+ tmp = BeautifulSoup("<table></table>", "html.parser")
536
+ tbl = tmp.find("table")
537
+ for r in current_rows:
538
+ tbl.append(r)
539
+ parsed = _parse_table_formula(tbl)
540
+ if parsed:
541
+ parsed["meta"]["url"] = url
542
+ parsed["meta"]["demo_id"] = demo_id
543
+ formulas.append(parsed)
544
+ current_rows = [row]
545
+ else:
546
+ current_rows.append(row)
547
+
548
+ if current_rows:
549
+ tmp = BeautifulSoup("<table></table>", "html.parser")
550
+ tbl = tmp.find("table")
551
+ for r in current_rows:
552
+ tbl.append(r)
553
+ parsed = _parse_table_formula(tbl)
554
+ if parsed:
555
+ parsed["meta"]["url"] = url
556
+ parsed["meta"]["demo_id"] = demo_id
557
+ formulas.append(parsed)
558
+
559
+ return formulas
560
+
561
+
562
+ def derive_heuristic_labels(formula: dict[str, Any], title: str, application: str | None) -> dict[str, Any]:
563
+ """Derive heuristic scent labels from title, application, and ingredient names."""
564
+ title_lower = title.lower()
565
+ app_lower = (application or "").lower()
566
+ text = f"{title_lower} {app_lower}"
567
+
568
+ labels = {
569
+ "seasonality": {"spring": 0.0, "summer": 0.0, "autumn": 0.0, "winter": 0.0},
570
+ "gender": 0.0,
571
+ "wearability": {"day": 0.0, "night": 0.0},
572
+ "categories": {
573
+ "citrus": 0.0, "floral": 0.0, "oriental": 0.0, "woody": 0.0,
574
+ "fougere": 0.0, "chypre": 0.0, "gourmand": 0.0, "green": 0.0,
575
+ "fruity": 0.0, "spicy": 0.0, "musk": 0.0,
576
+ },
577
+ "notes": [],
578
+ }
579
+
580
+ keyword_rules = [
581
+ ("citrus", ["citrus", "bergamot", "lemon", "lime", "orange", "mandarin", "grapefruit", "hesperidic"]),
582
+ ("floral", ["floral", "flower", "rose", "jasmine", "jasmin", "lily", "ylang", "tuberose", "muguet", "lilac", "violet", "neroli", "fleur", "bloom", "blossom"]),
583
+ ("oriental", ["oriental", "amber", "vanilla", "balsamic", "resin", "incense", "myrrh", "opoponax", "benzoin", "tonka"]),
584
+ ("woody", ["woody", "sandalwood", "cedar", "patchouli", "vetiver", "vetivert", "guaiac", "oakmoss", "cashmeran", "iso e super"]),
585
+ ("fougere", ["fougere", "fougère", "lavender", "coumarin", "oakmoss"]),
586
+ ("chypre", ["chypre", "oakmoss", "bergamot", "patchouli", "labdanum"]),
587
+ ("gourmand", ["gourmand", "chocolate", "vanilla", "caramel", "coffee", "honey", "maltol", "ethyl maltol", "butterscotch", "cherry", "fruity"]),
588
+ ("green", ["green", "galbanum", "leaf", "stemone", "fresh"]),
589
+ ("fruity", ["fruity", "fruit", "apple", "pear", "peach", "berry", "strawberry", "raspberry", "plum", "apricot", "lychee", "guava", "mango"]),
590
+ ("spicy", ["spicy", "spice", "cinnamon", "cassia", "clove", "nutmeg", "pimento", "pepper", "cardamom", "ginger", "chai"]),
591
+ ("musk", ["musk", "ambrette", "ambroxan", "ambrox", "musk ketone", "galaxolide"]),
592
+ ]
593
+ for cat, keywords in keyword_rules:
594
+ if any(kw in text for kw in keywords):
595
+ labels["categories"][cat] += 1.0
596
+
597
+ season_rules = [
598
+ ("winter", ["winter", "christmas", "amber", "balsamic", "oriental spice"]),
599
+ ("autumn", ["autumn", "fall", "chypre", "patchouli", "smoke", "smoky", "leather", "tobacco"]),
600
+ ("spring", ["spring", "lilac", "lily of the valley", "green floral", "fresh floral"]),
601
+ ("summer", ["summer", "marine", "aquatic", "ocean", "cologne", "hesperidic"]),
602
+ ]
603
+ for season, keywords in season_rules:
604
+ if any(kw in text for kw in keywords):
605
+ labels["seasonality"][season] += 1.0
606
+ if any(w in text for w in ["citrus", "bergamot", "lemon", "lime", "orange"]):
607
+ labels["seasonality"]["summer"] += 0.3
608
+ if any(w in text for w in ["woody", "spicy", "cinnamon", "clove"]):
609
+ labels["seasonality"]["autumn"] += 0.3
610
+ labels["seasonality"]["winter"] += 0.2
611
+
612
+ if any(w in text for w in ["feminine", "women", "woman", "lady", "floral", "rose", "jasmine"]):
613
+ labels["gender"] -= 0.5
614
+ if any(w in text for w in ["masculine", "men", "man", "male", "fougere", "barbershop", "tobacco", "leather"]):
615
+ labels["gender"] += 0.5
616
+
617
+ if any(w in text for w in ["night", "evening", "extrait", "oriental", "amber", "musk", "leather"]):
618
+ labels["wearability"]["night"] += 1.0
619
+ if any(w in text for w in ["day", "morning", "fresh", "citrus", "light", "shower gel", "shampoo"]):
620
+ labels["wearability"]["day"] += 1.0
621
+
622
+ ing_text = " ".join(ing["name"].lower() for ing in formula["ingredients"])
623
+ for cat, keywords in keyword_rules:
624
+ if any(kw in ing_text for kw in keywords):
625
+ labels["categories"][cat] += 0.3
626
+
627
+ def softmax_dict(d: dict[str, float]) -> dict[str, float]:
628
+ import math
629
+ exp = {k: math.exp(v) for k, v in d.items()}
630
+ total = sum(exp.values())
631
+ return {k: v / total for k, v in exp.items()} if total > 0 else d
632
+
633
+ labels["seasonality"] = softmax_dict(labels["seasonality"])
634
+ labels["wearability"] = softmax_dict(labels["wearability"])
635
+ labels["categories"] = softmax_dict(labels["categories"])
636
+ labels["gender"] = max(-1.0, min(1.0, labels["gender"]))
637
+ return labels
638
+
639
+
640
+ def _tgsc_odor_cache_path() -> Path:
641
+ return Path(__file__).parent.parent / "data" / "tgsc_odor_cache.json"
642
+
643
+
644
+ def _load_tgsc_odor_cache() -> dict[str, dict[str, Any]]:
645
+ path = _tgsc_odor_cache_path()
646
+ if path.exists():
647
+ try:
648
+ with open(path, "r", encoding="utf-8") as f:
649
+ return json.load(f)
650
+ except Exception:
651
+ pass
652
+ return {}
653
+
654
+
655
+ def _save_tgsc_odor_cache(cache: dict[str, dict[str, Any]]) -> None:
656
+ path = _tgsc_odor_cache_path()
657
+ path.parent.mkdir(parents=True, exist_ok=True)
658
+ with open(path, "w", encoding="utf-8") as f:
659
+ json.dump(cache, f, ensure_ascii=False, indent=2)
660
+
661
+
662
+ # In-memory cache loaded lazily.
663
+ _TGSC_ODOR_CACHE: dict[str, dict[str, Any]] = {}
664
+
665
+
666
+ def _absolute_tgsc_url(href: str | None) -> str | None:
667
+ if not href:
668
+ return None
669
+ if href.startswith("http"):
670
+ return href
671
+ return "https://www.thegoodscentscompany.com" + href
672
+
673
+
674
+ def fetch_tgsc_ingredient_odor(link: str) -> dict[str, Any]:
675
+ """Fetch a TGSC ingredient page and extract odor/flavor descriptors and vapor pressure."""
676
+ global _TGSC_ODOR_CACHE
677
+ if not _TGSC_ODOR_CACHE:
678
+ _TGSC_ODOR_CACHE = _load_tgsc_odor_cache()
679
+
680
+ if link in _TGSC_ODOR_CACHE:
681
+ return _TGSC_ODOR_CACHE[link]
682
+
683
+ result: dict[str, Any] = {
684
+ "odor_type": [],
685
+ "odor_descriptions": [],
686
+ "flavor_type": [],
687
+ "taste_descriptions": [],
688
+ "vapor_pressure_pa": None,
689
+ "error": None,
690
+ }
691
+
692
+ try:
693
+ resp = requests.get(link, headers={"User-Agent": "PinoDataIngest/1.0"}, timeout=20)
694
+ resp.raise_for_status()
695
+ except Exception as exc:
696
+ result["error"] = str(exc)
697
+ _TGSC_ODOR_CACHE[link] = result
698
+ return result
699
+
700
+ soup = BeautifulSoup(resp.text, "html.parser")
701
+ page_text = soup.get_text("\n")
702
+ lines = [l.strip() for l in page_text.splitlines() if l.strip()]
703
+
704
+ # Extract odor/flavor sections.
705
+ i = 0
706
+ while i < len(lines):
707
+ line = lines[i]
708
+ low = line.lower()
709
+
710
+ if low.startswith("odor type:"):
711
+ # Next lines are odor type keywords until another known header.
712
+ j = i + 1
713
+ while j < len(lines) and not _is_known_header(lines[j]):
714
+ line = lines[j]
715
+ if not _should_skip_tgsc_line(line):
716
+ result["odor_type"].append(line)
717
+ j += 1
718
+ i = j
719
+ continue
720
+
721
+ if low.startswith("odor description:"):
722
+ # Capture actual descriptor lines; stop at attribution/section headers.
723
+ j = i + 1
724
+ while j < len(lines) and not _is_known_header(lines[j]):
725
+ line = lines[j]
726
+ if not _should_skip_tgsc_line(line):
727
+ result["odor_descriptions"].append(line)
728
+ j += 1
729
+ i = j
730
+ continue
731
+
732
+ if low.startswith("flavor type:"):
733
+ j = i + 1
734
+ while j < len(lines) and not _is_known_header(lines[j]):
735
+ line = lines[j]
736
+ if not _should_skip_tgsc_line(line):
737
+ result["flavor_type"].append(line)
738
+ j += 1
739
+ i = j
740
+ continue
741
+
742
+ if low.startswith("taste description:"):
743
+ j = i + 1
744
+ while j < len(lines) and not _is_known_header(lines[j]):
745
+ line = lines[j]
746
+ if not _should_skip_tgsc_line(line):
747
+ result["taste_descriptions"].append(line)
748
+ j += 1
749
+ i = j
750
+ continue
751
+
752
+ # Vapor pressure is often in the Properties section.
753
+ if "vapor pressure" in low and "mm" in low:
754
+ match = re.search(r"([0-9.]+)\s*mm\s*Hg", line, re.I)
755
+ if match:
756
+ result["vapor_pressure_pa"] = float(match.group(1)) * 133.3224
757
+
758
+ i += 1
759
+
760
+ _TGSC_ODOR_CACHE[link] = result
761
+ return result
762
+
763
+
764
+ def _is_known_header(line: str) -> bool:
765
+ low = line.lower()
766
+ return any(
767
+ low.startswith(h)
768
+ for h in [
769
+ "odor type:",
770
+ "odor description:",
771
+ "odor strength:",
772
+ "substantivity:",
773
+ "flavor type:",
774
+ "taste description:",
775
+ "cosmetic information:",
776
+ "us / eu / fda",
777
+ "google scholar:",
778
+ "perfumer and flavorist:",
779
+ "rifm fragrance",
780
+ "epi system:",
781
+ "safety",
782
+ "suppliers",
783
+ "physical properties:",
784
+ "for odor",
785
+ "for flavor",
786
+ "references",
787
+ ]
788
+ )
789
+
790
+
791
+ _SKIP_TGSC_LINES = {
792
+ "luebke, william", "tgsc,", "odor sample from", "international flavors & fragrances",
793
+ "firmenich", "givaudan", "symrise", "takasago", "mane", "robertet", "berje", "inc",
794
+ "odor strength", "substantivity", "recommend smelling", "at 100.00 %",
795
+ "odor and/or flavor descriptions from others", "sample from", "descriptions from others",
796
+ "if found", "google scholar", "perfumer and flavorist", "rifm fragrance", "epi system",
797
+ }
798
+
799
+
800
+ def _should_skip_tgsc_line(line: str) -> bool:
801
+ low = line.lower()
802
+ if not low:
803
+ return True
804
+ # Pure concentration / attribution noise.
805
+ if low.startswith("at ") and "%" in low and len(low.split()) < 10:
806
+ return True
807
+ # Duration lines like "364 hour(s) at 10.00 % in dipropylene glycol".
808
+ if re.match(r"^\d+\s+hour\(s\)", low):
809
+ return True
810
+ if any(skip in low for skip in _SKIP_TGSC_LINES):
811
+ return True
812
+ # Drop standalone years like "(1992)" or "© 2020" or plain numbers like "1981".
813
+ if re.match(r"^\(?\d{4}\)?$|^©\s*\d{4}$", line.strip()):
814
+ return True
815
+ # Drop short lines that are not descriptors (single word without scent terms).
816
+ if len(low.split()) <= 1:
817
+ if low not in {
818
+ "fruity", "floral", "woody", "green", "sweet", "citrus", "spicy",
819
+ "musky", "powdery", "balsamic", "amber", "herbal", "earthy", "fresh",
820
+ }:
821
+ return True
822
+ return False
823
+
824
+
825
+ def aggregate_odor_profile(formula: list[dict[str, Any]]) -> dict[str, Any]:
826
+ """Build a formula-level scent profile by aggregating ingredient TGSC odor data."""
827
+ profile: dict[str, Any] = {
828
+ "ingredient_odor_types": {},
829
+ "ingredient_odor_descriptions": {},
830
+ "formula_odor_words": [],
831
+ "ingredients_with_odor_data": 0,
832
+ "ingredients_without_odor_data": 0,
833
+ }
834
+
835
+ for item in formula:
836
+ link = item.get("link")
837
+ if not link:
838
+ profile["ingredients_without_odor_data"] += 1
839
+ continue
840
+ absolute = _absolute_tgsc_url(link)
841
+ if not absolute:
842
+ profile["ingredients_without_odor_data"] += 1
843
+ continue
844
+ odor = fetch_tgsc_ingredient_odor(absolute)
845
+ if odor.get("error"):
846
+ profile["ingredients_without_odor_data"] += 1
847
+ continue
848
+
849
+ profile["ingredients_with_odor_data"] += 1
850
+ profile["ingredient_odor_types"][item["cas"]] = odor.get("odor_type", [])
851
+ profile["ingredient_odor_descriptions"][item["cas"]] = odor.get("odor_descriptions", [])
852
+
853
+ # Aggregate words from odor descriptions, weighted by formula fraction.
854
+ weight = item.get("weight_fraction", 0.0)
855
+ stopwords = {
856
+ "and", "with", "from", "odor", "type", "description", "flavor", "taste",
857
+ "aroma", "smell", "note", "notes", "the", "for", "use", "used", "this",
858
+ "that", "are", "is", "to", "of", "in", "a", "an", "at", "very", "slightly",
859
+ "somewhat", "characteristic", "pleasant", "unpleasant", "dry", "soft",
860
+ "strong", "weak", "moderate", "fresh", "green", "white", "yellow", "red",
861
+ "brown", "black", "color", "colors", "its", "sample", "others", "descriptions",
862
+ "and/or", "high", "low", "medium", "luebke", "william", "tgsc", "berje", "inc",
863
+ }
864
+ for desc in odor.get("odor_descriptions", []):
865
+ # Skip lines that are clearly not descriptors.
866
+ if _should_skip_tgsc_line(desc):
867
+ continue
868
+ # Clean and tokenize descriptors; drop concentration and attribution lines.
869
+ clean = re.sub(r"at\s+[0-9.\-]+\s*(%|ppm)", "", desc, flags=re.I)
870
+ clean = re.sub(r"[().,;:]+", " ", clean)
871
+ clean = re.sub(r"Mosciano.*$", "", clean, flags=re.I)
872
+ words = [w.strip().lower() for w in clean.split() if len(w) > 2 and w.strip().lower() not in stopwords]
873
+ for w in words:
874
+ profile["formula_odor_words"].append((w, weight))
875
+
876
+ # Weighted word frequencies.
877
+ word_scores: dict[str, float] = {}
878
+ for w, weight in profile["formula_odor_words"]:
879
+ word_scores[w] = word_scores.get(w, 0.0) + weight
880
+ profile["formula_odor_words"] = sorted(word_scores.items(), key=lambda x: x[1], reverse=True)[:50]
881
+
882
+ # Periodically persist cache so an interruption can be resumed.
883
+ if len(_TGSC_ODOR_CACHE) % 50 == 0:
884
+ _save_tgsc_odor_cache(_TGSC_ODOR_CACHE)
885
+
886
+ return profile
887
+
888
+
889
+ def _fetch_fragrantica_notes(url: str) -> dict[str, Any]:
890
+ """Extract all notes from a Fragrantica perfume page."""
891
+ result: dict[str, Any] = {"url": url, "notes": [], "notes_by_section": {}, "error": None}
892
+ try:
893
+ resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=20)
894
+ resp.raise_for_status()
895
+ except Exception as exc:
896
+ result["error"] = str(exc)
897
+ return result
898
+
899
+ soup = BeautifulSoup(resp.text, "html.parser")
900
+ # Notes are in <a class="pyramid-note-link"> tags.
901
+ note_links = soup.find_all("a", class_="pyramid-note-link")
902
+ result["notes"] = sorted({a.get_text(strip=True) for a in note_links if a.get_text(strip=True)})
903
+
904
+ # Try to associate notes with top/heart/base sections by inspecting parent containers.
905
+ section_keywords = {
906
+ "top": ["top notes", "top note"],
907
+ "heart": ["middle notes", "heart notes", "middle note", "heart note"],
908
+ "base": ["base notes", "base note"],
909
+ }
910
+ for section, keywords in section_keywords.items():
911
+ section_notes = set()
912
+ # Look for headers that mention the section.
913
+ for header in soup.find_all(["h2", "h3", "h4", "span", "div"]):
914
+ text = header.get_text(" ", strip=True).lower()
915
+ if any(kw in text for kw in keywords):
916
+ # Collect all pyramid-note-link tags in the same parent container.
917
+ parent = header
918
+ for _ in range(5): # search up to 5 levels up
919
+ if not parent:
920
+ break
921
+ notes = parent.find_all("a", class_="pyramid-note-link")
922
+ if notes:
923
+ section_notes.update(a.get_text(strip=True) for a in notes)
924
+ break
925
+ parent = parent.parent
926
+ if section_notes:
927
+ result["notes_by_section"][section] = sorted(section_notes)
928
+
929
+ return result
930
+
931
+
932
+ def _search_fragrantica_page(query: str) -> str | None:
933
+ """Use a lightweight web search to find a Fragrantica perfume page for a query."""
934
+ # Try DuckDuckGo HTML first.
935
+ search_url = "https://html.duckduckgo.com/html/"
936
+ try:
937
+ resp = requests.post(search_url, data={"q": f"site:fragrantica.com/perfume/ {query}"}, headers={"User-Agent": "Mozilla/5.0"}, timeout=20)
938
+ if resp.status_code == 200:
939
+ soup = BeautifulSoup(resp.text, "html.parser")
940
+ for a in soup.find_all("a", class_="result__a"):
941
+ href = a.get("href")
942
+ if href and "fragrantica.com/perfume/" in href and not href.endswith("/perfume/"):
943
+ return href
944
+ except Exception:
945
+ pass
946
+
947
+ # Fallback to Bing (no API key needed; may be blocked).
948
+ try:
949
+ resp = requests.get(
950
+ "https://www.bing.com/search",
951
+ params={"q": f"site:fragrantica.com/perfume/ {query}"},
952
+ headers={"User-Agent": "Mozilla/5.0"},
953
+ timeout=20,
954
+ )
955
+ if resp.status_code == 200:
956
+ soup = BeautifulSoup(resp.text, "html.parser")
957
+ for a in soup.find_all("a", href=re.compile(r"fragrantica\.com/perfume/")):
958
+ href = a.get("href")
959
+ if href and "fragrantica.com/perfume/" in href:
960
+ return href
961
+ except Exception:
962
+ pass
963
+
964
+ return None
965
+
966
+
967
+ def lookup_external_formula_notes(title: str) -> dict[str, Any] | None:
968
+ """Try to find a Fragrantica/Basenotes page for a formula name and extract notes."""
969
+ # Skip generic accord names that are unlikely to match a perfume page.
970
+ generic_words = {"accord", "perfume", "fragrance", "base", "composition", "formula"}
971
+ if sum(1 for w in generic_words if w in title.lower()) >= 2:
972
+ return None
973
+
974
+ url = _search_fragrantica_page(title)
975
+ if url:
976
+ return {"source": "fragrantica", "title": title, **(_fetch_fragrantica_notes(url))}
977
+ return None
978
+
979
+
980
+ # Optional: simple search for Basenotes (same structure as Fragrantica URLs).
981
+ _BASENOTES_URL_RE = re.compile(r"basenotes\.net/perfumes/[^\s\"]+")
982
+
983
+
984
+ def lookup_external_formula_notes_batch(
985
+ records: list[dict[str, Any]],
986
+ delay: float = 1.0,
987
+ ) -> list[dict[str, Any]]:
988
+ """Look up external perfume notes for records whose titles might match a perfume."""
989
+ for rec in records:
990
+ title = rec["source"]["title"]
991
+ external = lookup_external_formula_notes(title)
992
+ if external:
993
+ rec["external_notes"] = external
994
+ time.sleep(delay)
995
+ return records
996
+
997
+
998
+ def label_with_zai(records: list[dict[str, Any]], api_key: str, batch_size: int = 10) -> list[dict[str, Any]]:
999
+ """Enrich records with LLM-derived olfactory labels using Z.AI (OpenAI-compatible)."""
1000
+ try:
1001
+ from openai import OpenAI
1002
+ except ImportError as exc:
1003
+ raise RuntimeError("openai package is required for Z.AI labeling") from exc
1004
+
1005
+ client = OpenAI(api_key=api_key, base_url="https://api.z.ai/api/coding/paas/v4/")
1006
+ system_prompt = (
1007
+ "You are a perfumery expert. Given a fragrance formula name, source, application, "
1008
+ "and a list of ingredients with relative weights, output a JSON object with exactly these keys:\n"
1009
+ "- seasonality: object with spring, summer, autumn, winter (probabilities summing to 1.0)\n"
1010
+ "- gender: float between -1.0 (strongly feminine) and +1.0 (strongly masculine)\n"
1011
+ "- wearability: object with day and night (probabilities summing to 1.0)\n"
1012
+ "- categories: object with citrus, floral, oriental, woody, fougere, chypre, gourmand, green, fruity, spicy, musk (probabilities summing to 1.0)\n"
1013
+ "- notes: list of 3-7 short olfactory descriptor strings (e.g., 'bergamot', 'vanilla', 'smoky', 'jasmine')\n"
1014
+ "Return only valid JSON, no markdown, no explanation."
1015
+ )
1016
+
1017
+ labeled = []
1018
+ for i in range(0, len(records), batch_size):
1019
+ batch = records[i:i + batch_size]
1020
+ for rec in batch:
1021
+ prompt = (
1022
+ f"Title: {rec['source']['title']}\n"
1023
+ f"Source: {rec['source'].get('source') or 'N/A'}\n"
1024
+ f"Application: {rec['source'].get('application') or 'N/A'}\n"
1025
+ f"Notes: {', '.join(rec['source'].get('notes', [])) or 'N/A'}\n"
1026
+ f"Ingredients (weight fraction):\n"
1027
+ )
1028
+ for item in rec["formula"][:40]:
1029
+ prompt += f"- {item['name']} ({item['weight_fraction']:.4f})\n"
1030
+ try:
1031
+ resp = client.chat.completions.create(
1032
+ model="glm-5.2",
1033
+ messages=[
1034
+ {"role": "system", "content": system_prompt},
1035
+ {"role": "user", "content": prompt},
1036
+ ],
1037
+ temperature=0.2,
1038
+ max_tokens=600,
1039
+ )
1040
+ content = resp.choices[0].message.content
1041
+ # Strip markdown fences if present.
1042
+ content = re.sub(r"^```json\s*|\s*```$", "", content.strip())
1043
+ rec["labels"] = json.loads(content)
1044
+ rec["labels_ai"] = True
1045
+ except Exception as exc:
1046
+ print(f"Z.AI labeling failed for {rec['id']}: {exc}")
1047
+ rec.setdefault("labels", {}).setdefault("ai_error", str(exc))
1048
+ rec["labels_ai"] = False
1049
+ labeled.extend(batch)
1050
+ time.sleep(0.5)
1051
+ return labeled
1052
+
1053
+
1054
+ def convert_to_pino_record(formula: dict[str, Any], mapping: dict[str, str]) -> dict[str, Any] | None:
1055
+ """Convert a parsed TGSC formula into a PINO hierarchical recipe record."""
1056
+ formula_items = []
1057
+ unresolved = []
1058
+ total_mass = 0.0
1059
+
1060
+ # Collect links per (name, cas) so we can enrich later with TGSC odor data.
1061
+ links_by_identity: dict[tuple[str, str], str] = {}
1062
+
1063
+ for ing in formula["ingredients"]:
1064
+ name = ing["name"]
1065
+ raw_weight = ing["weight"]
1066
+ dilution = ing["dilution"]
1067
+ cas_or_token = map_ingredient(name, mapping)
1068
+
1069
+ if not cas_or_token or cas_or_token == "unknown":
1070
+ unresolved.append(name)
1071
+ continue
1072
+
1073
+ active_weight = raw_weight * dilution
1074
+ solvent_weight = raw_weight * (1.0 - dilution)
1075
+
1076
+ formula_items.append({"cas": cas_or_token, "name": name, "weight": active_weight, "link": ing.get("link")})
1077
+ total_mass += active_weight
1078
+
1079
+ if ing.get("link"):
1080
+ links_by_identity[(name, cas_or_token)] = ing["link"]
1081
+
1082
+ if solvent_weight > 0:
1083
+ formula_items.append({"cas": SOLVENT_CAS, "name": "solvent (DPG)", "weight": solvent_weight, "link": None})
1084
+ total_mass += solvent_weight
1085
+
1086
+ if not formula_items:
1087
+ return None
1088
+
1089
+ aggregated: dict[str, dict[str, Any]] = {}
1090
+ for item in formula_items:
1091
+ cas = item["cas"]
1092
+ if cas not in aggregated:
1093
+ aggregated[cas] = {"cas": cas, "name": item["name"], "weight": 0.0, "link": item.get("link")}
1094
+ aggregated[cas]["weight"] += item["weight"]
1095
+ if item.get("link") and not aggregated[cas].get("link"):
1096
+ aggregated[cas]["link"] = item["link"]
1097
+ formula_items = list(aggregated.values())
1098
+
1099
+ for item in formula_items:
1100
+ item["weight_fraction"] = item["weight"] / total_mass
1101
+ del item["weight"]
1102
+
1103
+ labels = derive_heuristic_labels(formula, formula["meta"]["title"], formula["meta"].get("application"))
1104
+
1105
+ return {
1106
+ "id": f"tgsc_{formula['meta']['demo_id']}_{re.sub(r'[^a-z0-9]+', '_', formula['meta']['title'].lower()).strip('_')}",
1107
+ "source": formula["meta"],
1108
+ "formula": formula_items,
1109
+ "labels": labels,
1110
+ "labels_ai": False,
1111
+ "unresolved": unresolved,
1112
+ }
1113
+
1114
+
1115
+ def ingest_all(
1116
+ output_path: Path,
1117
+ demo_ids: list[int] | None = None,
1118
+ delay: float = 0.3,
1119
+ zai_api_key: str | None = None,
1120
+ zai_limit: int | None = None,
1121
+ enrich_tgsc_odor: bool = False,
1122
+ lookup_external: bool = False,
1123
+ external_delay: float = 1.0,
1124
+ ) -> dict[str, Any]:
1125
+ """Scrape all known TGSC demo pages, map them, and write a JSON-L dataset."""
1126
+ demo_ids = demo_ids or KNOWN_DEMO_PAGES
1127
+ registry = AromaRegistry()
1128
+ mapping = build_tgsc_mapping(registry)
1129
+
1130
+ records = []
1131
+ stats = {"pages": 0, "formulas": 0, "resolved": 0, "unresolved_names": set()}
1132
+
1133
+ for demo_id in demo_ids:
1134
+ formulas = scrape_tgsc_page(demo_id)
1135
+ stats["pages"] += 1
1136
+ for formula in formulas:
1137
+ stats["formulas"] += 1
1138
+ record = convert_to_pino_record(formula, mapping)
1139
+ if not record:
1140
+ continue
1141
+ stats["resolved"] += 1
1142
+ stats["unresolved_names"].update(record["unresolved"])
1143
+ records.append(record)
1144
+ time.sleep(delay)
1145
+
1146
+ # Deduplicate by normalized title (case and punctuation insensitive).
1147
+ seen_titles = set()
1148
+ deduped = []
1149
+ for rec in records:
1150
+ title = re.sub(r"[^a-z0-9]+", "", rec["source"]["title"].lower())
1151
+ if title in seen_titles:
1152
+ continue
1153
+ seen_titles.add(title)
1154
+ deduped.append(rec)
1155
+ records = deduped
1156
+
1157
+ # Optional TGSC ingredient-page odor enrichment.
1158
+ if enrich_tgsc_odor:
1159
+ print(f"Enriching {len(records)} records with TGSC ingredient odor profiles...")
1160
+ for rec in records:
1161
+ rec["tgsc_odor_profile"] = aggregate_odor_profile(rec["formula"])
1162
+ _save_tgsc_odor_cache(_TGSC_ODOR_CACHE)
1163
+ print(f"Saved TGSC odor cache: {len(_TGSC_ODOR_CACHE)} unique ingredient pages")
1164
+
1165
+ # Optional external note lookup.
1166
+ if lookup_external:
1167
+ print(f"Looking up external perfume notes for {len(records)} records...")
1168
+ records = lookup_external_formula_notes_batch(records, delay=external_delay)
1169
+ matched = sum(1 for rec in records if rec.get("external_notes"))
1170
+ print(f"External matches: {matched}/{len(records)}")
1171
+
1172
+ # Optional AI labeling.
1173
+ if zai_api_key:
1174
+ target = records[:zai_limit] if zai_limit else records
1175
+ print(f"Labeling {len(target)} records with Z.AI...")
1176
+ target = label_with_zai(target, zai_api_key)
1177
+
1178
+ output_path.parent.mkdir(parents=True, exist_ok=True)
1179
+ with output_path.open("w", encoding="utf-8") as f:
1180
+ for rec in records:
1181
+ f.write(json.dumps(rec, ensure_ascii=False, separators=(",", ":")) + "\n")
1182
+
1183
+ stats["unresolved_names"] = sorted(stats["unresolved_names"])
1184
+ stats["n_records"] = len(records)
1185
+ return stats
1186
+
1187
+
1188
+ if __name__ == "__main__":
1189
+ parser = argparse.ArgumentParser(description="Ingest TGSC demo formulas into PINO format")
1190
+ parser.add_argument("--output", type=Path, default=Path("data/tgsc_demo_formulas.jsonl"))
1191
+ parser.add_argument("--label", action="store_true", help="Use Z.AI to enrich labels")
1192
+ parser.add_argument("--limit", type=int, help="Limit Z.AI labeling to N records")
1193
+ parser.add_argument("--enrich-tgsc-odor", action="store_true", help="Fetch and aggregate TGSC ingredient-page odor descriptions")
1194
+ parser.add_argument("--lookup-external", action="store_true", help="Look up formula names on Fragrantica/Basenotes for additional notes")
1195
+ parser.add_argument("--external-delay", type=float, default=1.0, help="Delay between external lookups (seconds)")
1196
+ args = parser.parse_args()
1197
+
1198
+ zai_key = None
1199
+ if args.label:
1200
+ zai_key = zai_key or __import__("os").environ.get("ZAI_API_KEY")
1201
+ if not zai_key:
1202
+ raise SystemExit("ZAI_API_KEY environment variable is required for --label")
1203
+
1204
+ stats = ingest_all(
1205
+ args.output,
1206
+ zai_api_key=zai_key,
1207
+ zai_limit=args.limit,
1208
+ enrich_tgsc_odor=args.enrich_tgsc_odor,
1209
+ lookup_external=args.lookup_external,
1210
+ external_delay=args.external_delay,
1211
+ )
1212
+ print(f"Wrote {stats['n_records']} records to {args.output}")
1213
+ print(f"Pages scanned: {stats['pages']}, formulas found: {stats['formulas']}, resolved: {stats['resolved']}")
1214
+ print(f"Unresolved unique names: {len(stats['unresolved_names'])}")
1215
+ for name in stats["unresolved_names"][:20]:
1216
+ print(f" - {name}")