mattbitzesty commited on
Commit
5c9c324
·
1 Parent(s): fd5ba83

feat(scraper): TGSC enrichment with mmHg->Pa conversion and priority registry updates

Browse files

- Add src/pino/scraper.py with requests + Camoufox modes

- Add scripts/enrich_registry.py for targeted priority CAS enrichment

- Add scripts/generate_dataset.py wrapper for 5k dataset generation

- Add data/genre_rules.json for dataset builder

- Add odor_description column to registry schema

- Enrich priority materials (limonene, linalool, citral, geraniol, coumarin, vanillin, musks, woods, etc.)

.gitignore CHANGED
@@ -8,8 +8,8 @@ build/
8
  *.whl
9
  .pytest_cache/
10
  *.json
11
- !.gitkeep
12
  !data/design_brief.json
 
13
  *.db
14
  !src/pino/registry.db
15
  *.jsonl
 
8
  *.whl
9
  .pytest_cache/
10
  *.json
 
11
  !data/design_brief.json
12
+ !data/genre_rules.json
13
  *.db
14
  !src/pino/registry.db
15
  *.jsonl
data/genre_rules.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "genres": {
3
+ "citrus_cologne": {
4
+ "required_tiers": ["top"],
5
+ "min_top_mass": 0.35,
6
+ "max_top_mass": 0.65,
7
+ "min_heart_mass": 0.15,
8
+ "min_base_mass": 0.05
9
+ },
10
+ "fougere": {
11
+ "required_tiers": ["top", "heart"],
12
+ "min_top_mass": 0.15,
13
+ "max_top_mass": 0.35,
14
+ "min_heart_mass": 0.35,
15
+ "min_base_mass": 0.15
16
+ },
17
+ "floral_woody": {
18
+ "required_tiers": ["heart", "base"],
19
+ "min_top_mass": 0.10,
20
+ "max_top_mass": 0.30,
21
+ "min_heart_mass": 0.30,
22
+ "min_base_mass": 0.20
23
+ },
24
+ "amber_oriental": {
25
+ "required_tiers": ["base"],
26
+ "min_top_mass": 0.05,
27
+ "max_top_mass": 0.20,
28
+ "min_heart_mass": 0.20,
29
+ "min_base_mass": 0.40
30
+ },
31
+ "wildcard": {
32
+ "uniform": true
33
+ }
34
+ },
35
+ "solvent_cas": "64-17-5",
36
+ "solvent_min": 0.50,
37
+ "solvent_max": 0.90,
38
+ "default_min_weight": 0.005,
39
+ "default_max_weight": 0.25,
40
+ "prohibited_cas": [
41
+ "80-54-6",
42
+ "83-66-9",
43
+ "81-15-2",
44
+ "89-68-9",
45
+ "92-48-8",
46
+ "143-50-0"
47
+ ],
48
+ "tier_cutoffs": {
49
+ "top": { "max_mw": 160 },
50
+ "base": { "min_mw": 210 }
51
+ }
52
+ }
scripts/enrich_registry.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Targeted TGSC enrichment of the PINO aroma registry.
5
+
6
+ Processes a priority subset of single-chemical fragrance materials, fetches their
7
+ TGSC data sheets, and writes the extracted boiling point, vapor pressure
8
+ (mmHg -> Pa), and odor description back into the SQLite registry.
9
+ """
10
+
11
+ import argparse
12
+ import logging
13
+ import re
14
+ import sys
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
19
+
20
+ from camoufox.sync_api import Camoufox
21
+ from pino.registry import AromaRegistry
22
+ from pino.scraper import search_tgsc, parse_tgsc_page_camofox
23
+
24
+ logging.basicConfig(
25
+ level=logging.INFO,
26
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
27
+ )
28
+ logger = logging.getLogger("enrich_registry")
29
+
30
+
31
+ # Priority palette covering top, heart, and base notes. These are the materials
32
+ # that most strongly influence the VLE dry-down and the optimizer's search space.
33
+ PRIORITY_CAS = [
34
+ "5989-27-5", # d-Limonene (citrus top)
35
+ "78-70-6", # Linalool (floral/citrus top-heart)
36
+ "5392-40-5", # Citral (lemon/citrus top)
37
+ "106-24-1", # Geraniol (rosy floral heart)
38
+ "106-25-2", # Nerol (citrus-rose heart)
39
+ "115-95-7", # Linalyl acetate (bergamot/citrus top)
40
+ "80-56-8", # alpha-Pinene (pine/citrus top)
41
+ "99-85-4", # Gamma-terpinene (citrus peel)
42
+ "91-64-5", # Coumarin (sweet hay base)
43
+ "121-33-5", # Vanillin (sweet gourmand base)
44
+ "105-95-3", # Ethylene brassylate (musk base)
45
+ "77-53-2", # Cedrol (cedarwood base)
46
+ "87-44-5", # Caryophyllene (spicy woody heart)
47
+ "97-53-0", # Eugenol (spicy clove heart)
48
+ "119-36-8", # Methyl salicylate (wintergreen top)
49
+ "118-58-1", # Benzyl salicylate (floral musk base)
50
+ "1222-05-5", # Galaxolide (musk base)
51
+ "21145-77-7", # Tonalid (musk base)
52
+ "4602-84-0", # Farnesol (floral woody base)
53
+ "7212-44-4", # Nerolidol (woody floral base)
54
+ "104-67-6", # Gamma-undecalactone (peach lactone base)
55
+ "120-57-0", # Anisaldehyde (anise top)
56
+ "124-13-0", # Octanal (citrus aldehyde top)
57
+ "112-31-2", # Decanal (waxy aldehyde top)
58
+ "140-11-4", # Benzyl acetate (jasmin floral heart)
59
+ "141-12-8", # Linalyl acetate (duplicate alias)
60
+ "24851-98-7", # Methyl dihydrojasmonate (jasmine heart)
61
+ "127-51-5", # alpha-Isomethyl ionone (powdery floral heart)
62
+ "14901-07-6", # Gamma-methyl ionone (floral heart)
63
+ "16409-43-1", # Cashmeran (woody musk base)
64
+ "33704-61-9", # Cashmeran (alternative) - skipped, duplicate
65
+ ]
66
+
67
+
68
+ def _is_single_chemical(cas: str) -> bool:
69
+ """Natural oils and absolutes have 8000/9000 CAS prefixes; skip them."""
70
+ return not re.match(r"^(8\d{3}|9\d{3})", cas)
71
+
72
+
73
+ def enrich_priority(
74
+ registry: AromaRegistry,
75
+ priority: list[str],
76
+ limit: int | None = None,
77
+ ) -> dict[str, Any]:
78
+ """
79
+ Enrich a priority list of CAS entries from TGSC.
80
+
81
+ Returns a summary dict with counts and the list of updated records.
82
+ """
83
+ rows = registry._conn.execute(
84
+ "SELECT cas, name FROM aroma_chemicals WHERE cas IN ("
85
+ + ",".join("?" * len(priority))
86
+ + ") ORDER BY cas",
87
+ tuple(priority),
88
+ ).fetchall()
89
+
90
+ if limit is not None:
91
+ rows = rows[:limit]
92
+
93
+ logger.info("Enriching %d priority materials from TGSC", len(rows))
94
+
95
+ enriched: list[dict[str, Any]] = []
96
+ skipped = 0
97
+ failed = 0
98
+
99
+ with Camoufox(headless=True) as browser:
100
+ for cas, name in rows:
101
+ if not _is_single_chemical(cas):
102
+ skipped += 1
103
+ continue
104
+
105
+ try:
106
+ candidates = search_tgsc(name, browser=browser)
107
+ except Exception as exc:
108
+ logger.warning("Search failed for %s (%s): %s", cas, name, exc)
109
+ failed += 1
110
+ continue
111
+
112
+ if not candidates:
113
+ logger.warning("No TGSC results for %s (%s)", cas, name)
114
+ failed += 1
115
+ continue
116
+
117
+ scraped = None
118
+ for candidate in candidates:
119
+ try:
120
+ scraped = parse_tgsc_page_camofox(candidate["url"], browser=browser)
121
+ except Exception as exc:
122
+ logger.debug("Scrape failed for %s: %s", candidate["url"], exc)
123
+ continue
124
+ if scraped.get("vapor_pressure_pa") is not None:
125
+ scraped["url"] = candidate["url"]
126
+ scraped["name"] = candidate["name"]
127
+ break
128
+
129
+ if scraped is None or scraped.get("vapor_pressure_pa") is None:
130
+ failed += 1
131
+ continue
132
+
133
+ registry._conn.execute(
134
+ """
135
+ UPDATE aroma_chemicals
136
+ SET boiling_point_k = COALESCE(?, boiling_point_k),
137
+ vapor_pressure_pa = COALESCE(?, vapor_pressure_pa),
138
+ odor_description = COALESCE(?, odor_description)
139
+ WHERE cas = ?
140
+ """,
141
+ (
142
+ scraped.get("boiling_point_k"),
143
+ scraped.get("vapor_pressure_pa"),
144
+ scraped.get("odor_description", ""),
145
+ cas,
146
+ ),
147
+ )
148
+ registry._conn.commit()
149
+ enriched.append({"cas": cas, "name": name, **scraped})
150
+ logger.info(
151
+ "Enriched %s (%s): VP=%.4f Pa, BP=%.2f K, odor=%r",
152
+ cas,
153
+ name,
154
+ scraped["vapor_pressure_pa"],
155
+ scraped["boiling_point_k"] or 0.0,
156
+ scraped.get("odor_description", "")[:60],
157
+ )
158
+
159
+ return {
160
+ "enriched": len(enriched),
161
+ "skipped": skipped,
162
+ "failed": failed,
163
+ "records": enriched,
164
+ }
165
+
166
+
167
+ def main() -> int:
168
+ parser = argparse.ArgumentParser(description="Targeted TGSC registry enrichment")
169
+ parser.add_argument(
170
+ "--registry",
171
+ default="src/pino/registry.db",
172
+ help="Path to the SQLite aroma registry",
173
+ )
174
+ parser.add_argument(
175
+ "--limit",
176
+ type=int,
177
+ default=None,
178
+ help="Process only the first N priority materials",
179
+ )
180
+ parser.add_argument(
181
+ "--priority",
182
+ default=None,
183
+ help="Comma-separated list of CAS numbers to enrich instead of the default priority list",
184
+ )
185
+ parser.add_argument(
186
+ "--log-level",
187
+ default="INFO",
188
+ help="Logging level",
189
+ )
190
+ args = parser.parse_args()
191
+
192
+ logging.getLogger().setLevel(getattr(logging, args.log_level.upper(), logging.INFO))
193
+
194
+ registry = AromaRegistry(args.registry)
195
+ priority = [c.strip() for c in args.priority.split(",")] if args.priority else PRIORITY_CAS
196
+
197
+ summary = enrich_priority(registry, priority, limit=args.limit)
198
+ print(summary)
199
+ return 0
200
+
201
+
202
+ if __name__ == "__main__":
203
+ raise SystemExit(main())
scripts/generate_dataset.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ Dataset generation wrapper for PINO.
5
+
6
+ Runs the multi-threaded dataset builder and writes a 5,000-row synthetic
7
+ formulation corpus to data/synthetic_dataset_v2.jsonl. Intended for background
8
+ execution via nohup.
9
+ """
10
+
11
+ import argparse
12
+ import logging
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
17
+
18
+ from pino.dataset_builder import DatasetBuilder
19
+
20
+
21
+ def main() -> int:
22
+ parser = argparse.ArgumentParser(description="Generate PINO synthetic dataset v2")
23
+ parser.add_argument("--output", default="data/synthetic_dataset_v2.jsonl", help="Output JSONL path")
24
+ parser.add_argument("--rules", default="data/genre_rules.json", help="Genre rules JSON")
25
+ parser.add_argument("--registry", default="src/pino/registry.db", help="SQLite registry path")
26
+ parser.add_argument("--per-genre", type=int, default=1000, help="Samples per genre")
27
+ parser.add_argument("--workers", type=int, default=4, help="Thread workers")
28
+ parser.add_argument("--seed", type=int, default=2026, help="Random seed")
29
+ parser.add_argument("--log-level", default="INFO", help="Logging level")
30
+ args = parser.parse_args()
31
+
32
+ logging.basicConfig(
33
+ level=getattr(logging, args.log_level.upper(), logging.INFO),
34
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
35
+ )
36
+
37
+ builder = DatasetBuilder(
38
+ output_path=args.output,
39
+ rules_path=args.rules,
40
+ registry_path=args.registry,
41
+ per_genre=args.per_genre,
42
+ max_workers=args.workers,
43
+ seed=args.seed,
44
+ )
45
+ card = builder.build()
46
+ print(card)
47
+ return 0
48
+
49
+
50
+ if __name__ == "__main__":
51
+ raise SystemExit(main())
src/pino/registry.py CHANGED
@@ -54,10 +54,17 @@ class AromaRegistry:
54
  vapor_pressure_pa REAL,
55
  odor_threshold_ug_m3 REAL,
56
  logp REAL,
 
57
  unifac_groups TEXT
58
  )
59
  """
60
  )
 
 
 
 
 
 
61
  self._conn.execute(
62
  "CREATE INDEX IF NOT EXISTS idx_name ON aroma_chemicals(name)"
63
  )
@@ -135,8 +142,8 @@ class AromaRegistry:
135
  """
136
  INSERT OR REPLACE INTO aroma_chemicals
137
  (cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa,
138
- odor_threshold_ug_m3, logp, unifac_groups)
139
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
140
  """,
141
  (
142
  record["cas"],
@@ -147,6 +154,7 @@ class AromaRegistry:
147
  record.get("vapor_pressure_pa"),
148
  record.get("odor_threshold_ug_m3"),
149
  record.get("logp"),
 
150
  json.dumps(record.get("unifac_groups", {}), sort_keys=True),
151
  ),
152
  )
 
54
  vapor_pressure_pa REAL,
55
  odor_threshold_ug_m3 REAL,
56
  logp REAL,
57
+ odor_description TEXT,
58
  unifac_groups TEXT
59
  )
60
  """
61
  )
62
+ # Migrate older registries that were created without odor_description.
63
+ try:
64
+ self._conn.execute("ALTER TABLE aroma_chemicals ADD COLUMN odor_description TEXT")
65
+ self._conn.commit()
66
+ except sqlite3.OperationalError:
67
+ pass # Column already exists
68
  self._conn.execute(
69
  "CREATE INDEX IF NOT EXISTS idx_name ON aroma_chemicals(name)"
70
  )
 
142
  """
143
  INSERT OR REPLACE INTO aroma_chemicals
144
  (cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa,
145
+ odor_threshold_ug_m3, logp, odor_description, unifac_groups)
146
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
147
  """,
148
  (
149
  record["cas"],
 
154
  record.get("vapor_pressure_pa"),
155
  record.get("odor_threshold_ug_m3"),
156
  record.get("logp"),
157
+ record.get("odor_description", ""),
158
  json.dumps(record.get("unifac_groups", {}), sort_keys=True),
159
  ),
160
  )
src/pino/scraper.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """
4
+ TGSC (The Good Scents Company) material scraper.
5
+
6
+ This module fetches raw material HTML pages from TGSC and extracts the
7
+ properties we need for realistic physics:
8
+ - Boiling point (K)
9
+ - Vapor pressure (mmHg -> Pa)
10
+ - Odor description string
11
+
12
+ The parser is intentionally regex-driven against the page text because TGSC
13
+ pages are legacy hand-written HTML without stable semantic markup. Callers can
14
+ pass either a URL, a raw HTML string, or a Camoufox page object.
15
+ """
16
+
17
+ import logging
18
+ import re
19
+ from typing import Any
20
+
21
+ try:
22
+ from camoufox.sync_api import Camoufox
23
+ except Exception: # pragma: no cover - optional dependency for stealth mode
24
+ Camoufox = None
25
+
26
+ import requests
27
+ from bs4 import BeautifulSoup
28
+
29
+ logger = logging.getLogger("pino.scraper")
30
+
31
+ # Conversion factor: 1 mmHg = 133.3224 Pa (exact definition used in PINO).
32
+ MMHG_TO_PA = 133.3224
33
+
34
+ # Default room temperature for boiling-point conversions if only Celsius is given.
35
+ ROOM_TEMP_K = 298.15
36
+
37
+
38
+ def _kelvin_from_string(text: str) -> float | None:
39
+ """Try to extract a temperature in Kelvin or Celsius from free text."""
40
+ # Celsius: 123.45 °C / 123.45 C
41
+ c_match = re.search(r"([\d\.]+)\s*°?C", text)
42
+ if c_match:
43
+ c = float(c_match.group(1))
44
+ return c + 273.15
45
+ # Kelvin: 123.45 K
46
+ k_match = re.search(r"([\d\.]+)\s*K\b", text)
47
+ if k_match:
48
+ return float(k_match.group(1))
49
+ return None
50
+
51
+
52
+ def _extract_boiling_point(page_text: str) -> float | None:
53
+ """
54
+ Extract boiling point from page text.
55
+
56
+ TGSC usually labels this as "Boiling Point:" followed by a temperature range.
57
+ We take the midpoint of the range.
58
+ """
59
+ # Look for a labelled boiling point line, e.g. "Boiling Point: 176.00 to 177.00 °C. @ 760.00 mm Hg"
60
+ bp_match = re.search(
61
+ r"Boiling Point:\s*([\d\.]+)\s*(?:to\s+([\d\.]+))?\s*°?C",
62
+ page_text,
63
+ re.IGNORECASE,
64
+ )
65
+ if bp_match:
66
+ low = float(bp_match.group(1))
67
+ high = float(bp_match.group(2)) if bp_match.group(2) else low
68
+ return (low + high) / 2.0 + 273.15
69
+ # Fallback: any phrase like "bp 123.45 °C".
70
+ fallback = re.search(r"\bb\.?p\.?\s*([\d\.]+)\s*°?C", page_text, re.IGNORECASE)
71
+ if fallback:
72
+ return float(fallback.group(1)) + 273.15
73
+ return None
74
+
75
+
76
+ def _extract_vapor_pressure(page_text: str) -> float | None:
77
+ """
78
+ Extract vapor pressure in mmHg and convert to Pascals.
79
+
80
+ TGSC labels this as "Vapor Pressure: 0.003000 mmHg @ 25.00 °C. (est)".
81
+ We always convert the mmHg value to Pa using MMHG_TO_PA.
82
+ """
83
+ vp_match = re.search(
84
+ r"Vapor Pressure:\s*([\d\.]+)\s*mmHg", page_text, re.IGNORECASE
85
+ )
86
+ if vp_match:
87
+ vp_mmhg = float(vp_match.group(1))
88
+ return vp_mmhg * MMHG_TO_PA
89
+ return None
90
+
91
+
92
+ def _extract_odor_description(page_text: str) -> str:
93
+ """
94
+ Extract the odor description keyword string.
95
+
96
+ TGSC labels this as "Odor Description: ...". We capture the remainder of the
97
+ line and strip the trailing attribution/reference text.
98
+ """
99
+ odor_match = re.search(
100
+ r"Odor Description:\s*at\s+\d+(?:\.\d+)?\s*\%\.\s*([^\n\r]+)",
101
+ page_text,
102
+ re.IGNORECASE,
103
+ )
104
+ if odor_match:
105
+ return odor_match.group(1).strip().split(" ")[0].strip()
106
+ odor_match = re.search(
107
+ r"Odor Description:\s*([^\n\r]+)", page_text, re.IGNORECASE
108
+ )
109
+ if odor_match:
110
+ return odor_match.group(1).strip().split(" ")[0].strip()
111
+ odor_match = re.search(r"Odor:\s*([^\n\r]+)", page_text, re.IGNORECASE)
112
+ if odor_match:
113
+ return odor_match.group(1).strip().split(" ")[0].strip()
114
+ return ""
115
+
116
+
117
+ def parse_tgsc_html(html: str) -> dict[str, Any]:
118
+ """Parse a TGSC raw material HTML string and return extracted properties."""
119
+ soup = BeautifulSoup(html, "html.parser")
120
+ page_text = soup.get_text(" ", strip=True)
121
+
122
+ bp_k = _extract_boiling_point(page_text)
123
+ vp_pa = _extract_vapor_pressure(page_text)
124
+ odor_desc = _extract_odor_description(page_text)
125
+
126
+ return {
127
+ "boiling_point_k": bp_k,
128
+ "vapor_pressure_pa": vp_pa,
129
+ "odor_description": odor_desc,
130
+ }
131
+
132
+
133
+ def parse_tgsc_page_requests(url: str, timeout: float = 30.0) -> dict[str, Any]:
134
+ """
135
+ Fetch a TGSC raw material URL with plain requests and parse its properties.
136
+ """
137
+ try:
138
+ response = requests.get(
139
+ url,
140
+ headers={"User-Agent": "Mozilla/5.0"},
141
+ timeout=timeout,
142
+ )
143
+ response.raise_for_status()
144
+ except Exception as exc:
145
+ logger.warning("Failed to fetch TGSC page %s: %s", url, exc)
146
+ return {
147
+ "boiling_point_k": None,
148
+ "vapor_pressure_pa": None,
149
+ "odor_description": "",
150
+ "error": str(exc),
151
+ }
152
+
153
+ return parse_tgsc_html(response.text)
154
+
155
+
156
+ def parse_tgsc_page_camofox(url: str, browser: Any | None = None) -> dict[str, Any]:
157
+ """
158
+ Fetch a TGSC raw material URL using Camoufox for stealth and parse properties.
159
+
160
+ If a browser instance is provided, it will be reused; otherwise a temporary
161
+ Camoufox browser is created and closed.
162
+ """
163
+ if Camoufox is None:
164
+ raise RuntimeError("Camoufox is not installed")
165
+
166
+ close_browser = False
167
+ if browser is None:
168
+ browser = Camoufox(headless=True).__enter__()
169
+ close_browser = True
170
+
171
+ try:
172
+ context = browser.new_context(no_viewport=True)
173
+ page = context.new_page()
174
+ page.goto(url, wait_until="networkidle")
175
+ html = page.content()
176
+ return parse_tgsc_html(html)
177
+ except Exception as exc:
178
+ logger.warning("Camoufox failed to fetch TGSC page %s: %s", url, exc)
179
+ return {
180
+ "boiling_point_k": None,
181
+ "vapor_pressure_pa": None,
182
+ "odor_description": "",
183
+ "error": str(exc),
184
+ }
185
+ finally:
186
+ if close_browser and browser is not None:
187
+ browser.close()
188
+
189
+
190
+ def parse_tgsc_page(
191
+ url: str,
192
+ *,
193
+ use_camofox: bool = True,
194
+ timeout: float = 30.0,
195
+ ) -> dict[str, Any]:
196
+ """
197
+ Fetch a TGSC raw material URL and parse its properties.
198
+
199
+ Parameters
200
+ ----------
201
+ url: str
202
+ TGSC data page URL (e.g., https://www.thegoodscentscompany.com/data/rw1007831.html).
203
+ use_camofox: bool
204
+ If True, use Camoufox for stealth; otherwise plain requests.
205
+ timeout: float
206
+ Request timeout for plain requests mode.
207
+
208
+ Returns
209
+ -------
210
+ dict with boiling_point_k, vapor_pressure_pa, odor_description, and optionally error.
211
+ """
212
+ if use_camofox:
213
+ return parse_tgsc_page_camofox(url)
214
+ return parse_tgsc_page_requests(url, timeout=timeout)
215
+
216
+
217
+ def mmhg_to_pa(mmhg: float) -> float:
218
+ """Public helper for the strict mmHg -> Pa conversion."""
219
+ return mmhg * MMHG_TO_PA
220
+
221
+
222
+ def search_tgsc(
223
+ query: str,
224
+ browser: Any | None = None,
225
+ ) -> list[dict[str, str]]:
226
+ """
227
+ Search TGSC for materials by name and return candidate data page URLs.
228
+
229
+ Returns a list of {"name": str, "url": str} records.
230
+ """
231
+ if Camoufox is None:
232
+ raise RuntimeError("Camoufox is not installed")
233
+
234
+ close_browser = False
235
+ if browser is None:
236
+ browser = Camoufox(headless=True).__enter__()
237
+ close_browser = True
238
+
239
+ results: list[dict[str, str]] = []
240
+ try:
241
+ context = browser.new_context(no_viewport=True)
242
+ page = context.new_page()
243
+ page.goto("https://www.thegoodscentscompany.com/search.php", wait_until="networkidle")
244
+ page.fill('input[name="qName"]', query)
245
+ page.click('input[type="Image"]')
246
+ page.wait_for_load_state("networkidle")
247
+ html = page.content()
248
+ soup = BeautifulSoup(html, "html.parser")
249
+ seen: set[str] = set()
250
+ for tr in soup.find_all("tr"):
251
+ a = tr.find("a", onclick=True)
252
+ if a and "openMainWindow" in a.get("onclick", ""):
253
+ m = re.search(r"openMainWindow\('([^']+)'\)", a["onclick"])
254
+ if not m:
255
+ continue
256
+ path = m.group(1)
257
+ if path.startswith("/"):
258
+ url = f"https://www.thegoodscentscompany.com{path}"
259
+ else:
260
+ url = f"https://www.thegoodscentscompany.com/{path}"
261
+ if url in seen:
262
+ continue
263
+ seen.add(url)
264
+ name = a.get_text(strip=True)
265
+ prefix = ""
266
+ prefix_td = tr.find("td", class_="lstw9")
267
+ if prefix_td:
268
+ prefix = prefix_td.get_text(strip=True)
269
+ results.append({"name": f"{prefix} {name}".strip(), "url": url})
270
+ finally:
271
+ if close_browser and browser is not None:
272
+ browser.close()
273
+
274
+ return results
275
+
276
+
277
+ if __name__ == "__main__":
278
+ import sys
279
+
280
+ if len(sys.argv) < 2:
281
+ print("Usage: python -m pino.scraper <tgsc-url>")
282
+ sys.exit(1)
283
+
284
+ result = parse_tgsc_page(sys.argv[1])
285
+ print(result)