feat(pino): literature seed integration, stratified dataset split, registry enrichment, and Space sync
Browse files- Add literature_formulas.json blueprint with seeds and holdouts
- Integrate literature seeds into FormulaGenerator with Gaussian perturbation
- Flatten genre key in dataset records for stratified splitting
- Add upload_data.py for deterministic 80/20 Hub push
- Enrich registry: add missing single-chemical CAS and natural placeholders
- Add inference stub and verify_benchmarks.py for gold-standard validation
- Add sync_space.py to push train_hf.py to pino-pimt-training Space
- Update .gitignore to ignore logs and registry.db
- .gitignore +1 -1
- data/literature_formulas.json +111 -22
- scripts/add_missing_cas.py +82 -0
- scripts/add_natural_placeholders.py +100 -0
- scripts/compare_ocr_vs_pymupdf.py +156 -0
- scripts/generate_dataset.py +4 -2
- scripts/parse_appell.py +761 -0
- scripts/parse_appell_blocks.py +170 -0
- scripts/sync_space.py +24 -0
- scripts/verify_benchmarks.py +53 -0
- src/pino/dataset_builder.py +8 -1
- src/pino/draft_engine.py +76 -0
- src/pino/inference.py +37 -0
- src/pino/pimt_model.py +47 -23
- src/pino/train_hf.py +17 -25
- src/pino/upload_data.py +41 -0
.gitignore
CHANGED
|
@@ -12,6 +12,6 @@ build/
|
|
| 12 |
!data/genre_rules.json
|
| 13 |
!data/literature_formulas.json
|
| 14 |
*.db
|
| 15 |
-
!src/pino/registry.db
|
| 16 |
*.jsonl
|
| 17 |
*.parquet
|
|
|
|
|
|
| 12 |
!data/genre_rules.json
|
| 13 |
!data/literature_formulas.json
|
| 14 |
*.db
|
|
|
|
| 15 |
*.jsonl
|
| 16 |
*.parquet
|
| 17 |
+
*.log
|
data/literature_formulas.json
CHANGED
|
@@ -1,22 +1,111 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"formula_id": "appell_rose_base_01",
|
| 4 |
+
"name": "Classic Rose Accord (Appell)",
|
| 5 |
+
"source": "Louis Appell - Cosmetics, Fragrances and Flavors",
|
| 6 |
+
"pipeline_role": "seed",
|
| 7 |
+
"expected_profile": "floral_woody",
|
| 8 |
+
"components": [
|
| 9 |
+
{"cas": "106-24-1", "weight_fraction": 0.45},
|
| 10 |
+
{"cas": "106-25-2", "weight_fraction": 0.35},
|
| 11 |
+
{"cas": "78-70-6", "weight_fraction": 0.20}
|
| 12 |
+
]
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"formula_id": "poucher_cologne_1959",
|
| 16 |
+
"name": "Classic Citrus Eau de Cologne (Poucher)",
|
| 17 |
+
"source": "W.A. Poucher - Perfumes, Cosmetics and Soaps Vol 2",
|
| 18 |
+
"pipeline_role": "holdout",
|
| 19 |
+
"expected_profile": "citrus_cologne",
|
| 20 |
+
"components": [
|
| 21 |
+
{"cas": "5989-27-5", "weight_fraction": 0.60},
|
| 22 |
+
{"cas": "115-95-7", "weight_fraction": 0.30},
|
| 23 |
+
{"cas": "78-70-6", "weight_fraction": 0.10}
|
| 24 |
+
]
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"formula_id": "appell_fougere_royale_1882",
|
| 28 |
+
"name": "Fougère Royale (Appell)",
|
| 29 |
+
"source": "Louis Appell - Cosmetics, Fragrances and Flavors",
|
| 30 |
+
"pipeline_role": "seed",
|
| 31 |
+
"expected_profile": "fougere",
|
| 32 |
+
"components": [
|
| 33 |
+
{"cas": "60-12-8", "weight_fraction": 0.12},
|
| 34 |
+
{"cas": "8000-46-2", "weight_fraction": 0.16},
|
| 35 |
+
{"cas": "91-64-5", "weight_fraction": 0.11},
|
| 36 |
+
{"cas": "81-15-2", "weight_fraction": 0.10},
|
| 37 |
+
{"cas": "8007-75-8", "weight_fraction": 0.10},
|
| 38 |
+
{"cas": "83-66-9", "weight_fraction": 0.02},
|
| 39 |
+
{"cas": "8014-09-3", "weight_fraction": 0.08},
|
| 40 |
+
{"cas": "121-33-5", "weight_fraction": 0.02},
|
| 41 |
+
{"cas": "122-40-7", "weight_fraction": 0.04},
|
| 42 |
+
{"cas": "8006-87-9", "weight_fraction": 0.07},
|
| 43 |
+
{"cas": "8008-45-5", "weight_fraction": 0.03},
|
| 44 |
+
{"cas": "8000-34-8", "weight_fraction": 0.04},
|
| 45 |
+
{"cas": "97-53-0", "weight_fraction": 0.05},
|
| 46 |
+
{"cas": "115-95-7", "weight_fraction": 0.06}
|
| 47 |
+
]
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"formula_id": "poucher_musk_soap_1233",
|
| 51 |
+
"name": "Musk Soap (Poucher no. 1233)",
|
| 52 |
+
"source": "W.A. Poucher - Perfumes, Cosmetics and Soaps Vol 2",
|
| 53 |
+
"pipeline_role": "seed",
|
| 54 |
+
"expected_profile": "amber_oriental",
|
| 55 |
+
"components": [
|
| 56 |
+
{"cas": "83-66-9", "weight_fraction": 0.02},
|
| 57 |
+
{"cas": "81-14-1", "weight_fraction": 0.03},
|
| 58 |
+
{"cas": "8016-96-4", "weight_fraction": 0.04},
|
| 59 |
+
{"cas": "8006-87-9", "weight_fraction": 0.10},
|
| 60 |
+
{"cas": "1335-46-2", "weight_fraction": 0.20},
|
| 61 |
+
{"cas": "8024-13-1", "weight_fraction": 0.07},
|
| 62 |
+
{"cas": "8007-75-8", "weight_fraction": 0.10},
|
| 63 |
+
{"cas": "8000-46-2", "weight_fraction": 0.20},
|
| 64 |
+
{"cas": "68916-26-7", "weight_fraction": 0.005},
|
| 65 |
+
{"cas": "8023-79-2", "weight_fraction": 0.005},
|
| 66 |
+
{"cas": "8000-41-7", "weight_fraction": 0.10},
|
| 67 |
+
{"cas": "8007-80-5", "weight_fraction": 0.03}
|
| 68 |
+
]
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"formula_id": "poucher_sweet_pea_1250",
|
| 72 |
+
"name": "Sweet Pea Soap (Poucher no. 1250)",
|
| 73 |
+
"source": "W.A. Poucher - Perfumes, Cosmetics and Soaps Vol 2",
|
| 74 |
+
"pipeline_role": "holdout",
|
| 75 |
+
"expected_profile": "floral_woody",
|
| 76 |
+
"components": [
|
| 77 |
+
{"cas": "140-11-4", "weight_fraction": 0.10},
|
| 78 |
+
{"cas": "8015-77-8", "weight_fraction": 0.20},
|
| 79 |
+
{"cas": "8014-17-3", "weight_fraction": 0.20},
|
| 80 |
+
{"cas": "8000-41-7", "weight_fraction": 0.10},
|
| 81 |
+
{"cas": "2039-67-0", "weight_fraction": 0.05},
|
| 82 |
+
{"cas": "102-13-6", "weight_fraction": 0.05},
|
| 83 |
+
{"cas": "111-12-6", "weight_fraction": 0.004},
|
| 84 |
+
{"cas": "68606-83-7", "weight_fraction": 0.05},
|
| 85 |
+
{"cas": "122-57-6", "weight_fraction": 0.02},
|
| 86 |
+
{"cas": "122-40-7", "weight_fraction": 0.05},
|
| 87 |
+
{"cas": "81-15-2", "weight_fraction": 0.025},
|
| 88 |
+
{"cas": "8046-19-3", "weight_fraction": 0.05},
|
| 89 |
+
{"cas": "9000-64-0", "weight_fraction": 0.05}
|
| 90 |
+
]
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"formula_id": "appell_chypre_coty_1917",
|
| 94 |
+
"name": "Chypre (Coty 1917)",
|
| 95 |
+
"source": "Louis Appell - Cosmetics, Fragrances and Flavors",
|
| 96 |
+
"pipeline_role": "seed",
|
| 97 |
+
"expected_profile": "amber_oriental",
|
| 98 |
+
"components": [
|
| 99 |
+
{"cas": "8007-75-8", "weight_fraction": 0.21},
|
| 100 |
+
{"cas": "8000-46-2", "weight_fraction": 0.03},
|
| 101 |
+
{"cas": "8007-01-0", "weight_fraction": 0.03},
|
| 102 |
+
{"cas": "1335-46-2", "weight_fraction": 0.04},
|
| 103 |
+
{"cas": "8002-73-1", "weight_fraction": 0.02},
|
| 104 |
+
{"cas": "8014-09-3", "weight_fraction": 0.02},
|
| 105 |
+
{"cas": "91-64-5", "weight_fraction": 0.06},
|
| 106 |
+
{"cas": "121-33-5", "weight_fraction": 0.02},
|
| 107 |
+
{"cas": "97-53-0", "weight_fraction": 0.02},
|
| 108 |
+
{"cas": "122-40-7", "weight_fraction": 0.04}
|
| 109 |
+
]
|
| 110 |
+
}
|
| 111 |
+
]
|
scripts/add_missing_cas.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Add literature-derived CAS entries to the PINO registry."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import sqlite3
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 14 |
+
|
| 15 |
+
from pino.registry import AromaRegistry
|
| 16 |
+
|
| 17 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
| 18 |
+
logger = logging.getLogger("add_missing_cas")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def collect_cas_from_literature(pino_root: Path) -> set[str]:
|
| 22 |
+
"""Gather all CAS numbers referenced by literature formulas."""
|
| 23 |
+
all_cas: set[str] = set()
|
| 24 |
+
formula_files = [
|
| 25 |
+
pino_root / "data" / "literature_formulas.json",
|
| 26 |
+
pino_root / "data" / "literature_formulas_poucher.jsonl",
|
| 27 |
+
pino_root / "data" / "literature_formulas_appell_blocks.jsonl",
|
| 28 |
+
]
|
| 29 |
+
for fpath in formula_files:
|
| 30 |
+
if not fpath.exists():
|
| 31 |
+
continue
|
| 32 |
+
if fpath.suffix == ".jsonl":
|
| 33 |
+
for line in fpath.read_text().strip().splitlines():
|
| 34 |
+
rec = json.loads(line)
|
| 35 |
+
for c in rec.get("components", []):
|
| 36 |
+
if c.get("type") == "pure" and c.get("cas"):
|
| 37 |
+
all_cas.add(c["cas"])
|
| 38 |
+
else:
|
| 39 |
+
data = json.loads(fpath.read_text())
|
| 40 |
+
for rec in (data if isinstance(data, list) else [data]):
|
| 41 |
+
for c in rec.get("components", []):
|
| 42 |
+
if c.get("type") == "pure" and c.get("cas"):
|
| 43 |
+
all_cas.add(c["cas"])
|
| 44 |
+
return all_cas
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main() -> int:
|
| 48 |
+
parser = argparse.ArgumentParser(description="Add missing CAS from literature to registry")
|
| 49 |
+
parser.add_argument("--registry", default="src/pino/registry.db", help="Path to registry.db")
|
| 50 |
+
parser.add_argument("--pino-root", default=".", help="Project root containing data/literature_formulas*")
|
| 51 |
+
parser.add_argument("--limit", type=int, default=None, help="Only process first N missing CAS")
|
| 52 |
+
parser.add_argument("--dry-run", action="store_true", help="Show missing CAS but do not modify")
|
| 53 |
+
args = parser.parse_args()
|
| 54 |
+
|
| 55 |
+
root = Path(args.pino_root).resolve()
|
| 56 |
+
registry = AromaRegistry(args.registry)
|
| 57 |
+
conn = sqlite3.connect(args.registry)
|
| 58 |
+
cursor = conn.cursor()
|
| 59 |
+
db_cas = {row[0] for row in cursor.execute("SELECT cas FROM aroma_chemicals WHERE cas IS NOT NULL")}
|
| 60 |
+
conn.close()
|
| 61 |
+
|
| 62 |
+
lit_cas = collect_cas_from_literature(root)
|
| 63 |
+
missing = sorted(lit_cas - db_cas)
|
| 64 |
+
logger.info("%d unique CAS in literature formulas; %d already in registry; %d missing", len(lit_cas), len(lit_cas & db_cas), len(missing))
|
| 65 |
+
|
| 66 |
+
if args.dry_run:
|
| 67 |
+
for cas in missing[: args.limit or len(missing)]:
|
| 68 |
+
print(cas)
|
| 69 |
+
return 0
|
| 70 |
+
|
| 71 |
+
entries = [{"cas": cas} for cas in missing[: args.limit or len(missing)]]
|
| 72 |
+
failed = registry.populate(entries, skip_failures=True)
|
| 73 |
+
logger.info("Added %d/%d missing CAS; %d failed", len(entries) - len(failed), len(entries), len(failed))
|
| 74 |
+
if failed:
|
| 75 |
+
failed_path = root / "data" / "failed_literature_cas.json"
|
| 76 |
+
failed_path.write_text(json.dumps(failed, indent=2))
|
| 77 |
+
logger.info("Wrote failed CAS list to %s", failed_path)
|
| 78 |
+
return 0
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
raise SystemExit(main())
|
scripts/add_natural_placeholders.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 9 |
+
|
| 10 |
+
from pino.registry import AromaRegistry
|
| 11 |
+
|
| 12 |
+
# Approximate placeholder records for natural extracts / complex mixtures that lack
|
| 13 |
+
# a single PubChem structure. These are used so literature formulas containing them
|
| 14 |
+
# can still be simulated (VLE falls back to ideal gamma=1.0).
|
| 15 |
+
NATURAL_PLACEHOLDERS = {
|
| 16 |
+
"68606-83-7": ("Rosa centifolia absolute", "rose absolute", 250.0),
|
| 17 |
+
"68916-26-7": ("Musk extract", "musk", 300.0),
|
| 18 |
+
"7462-86-6": ("Jasmin absolute", "jasmin", 240.0),
|
| 19 |
+
"8000-25-7": ("Bay oil", "bay", 180.0),
|
| 20 |
+
"8000-27-9": ("Lemon oil", "lemon", 180.0),
|
| 21 |
+
"8000-28-0": ("Lime oil", "lime", 180.0),
|
| 22 |
+
"8000-29-1": ("Neroli oil", "neroli", 200.0),
|
| 23 |
+
"8000-41-7": ("Rose oil", "rose", 220.0),
|
| 24 |
+
"8000-46-2": ("Rosemary oil", "rosemary", 180.0),
|
| 25 |
+
"8002-73-1": ("Resinoid", "resin", 300.0),
|
| 26 |
+
"8006-80-2": ("Citronella oil", "citronella", 180.0),
|
| 27 |
+
"8006-81-3": ("Ginger oil", "ginger", 200.0),
|
| 28 |
+
"8007-00-9": ("Amber oil", "amber", 250.0),
|
| 29 |
+
"8007-46-3": ("Cinnamon oil", "cinnamon", 180.0),
|
| 30 |
+
"8007-80-5": ("Musk seed oil", "musk seed", 250.0),
|
| 31 |
+
"8008-31-9": ("Pine oil", "pine", 170.0),
|
| 32 |
+
"8008-56-8": ("Palmarosa oil", "palmarosa", 190.0),
|
| 33 |
+
"8008-57-9": ("Patchouli oil", "patchouli", 220.0),
|
| 34 |
+
"8013-76-1": ("Cananga oil", "cananga", 190.0),
|
| 35 |
+
"8014-17-3": ("Petitgrain oil", "petitgrain", 180.0),
|
| 36 |
+
"8016-38-4": ("Basil oil", "basil", 180.0),
|
| 37 |
+
"8016-63-5": ("Lavender oil", "lavender", 180.0),
|
| 38 |
+
"8016-78-2": ("Pine needle oil", "pine needle", 170.0),
|
| 39 |
+
"8016-96-4": ("Geranium oil", "geranium", 190.0),
|
| 40 |
+
"8023-75-2": ("Ylang ylang oil", "ylang", 190.0),
|
| 41 |
+
"8023-79-2": ("Musk tonkin", "musk tonkin", 300.0),
|
| 42 |
+
"8023-91-4": ("Jasmin sambac", "jasmin sambac", 240.0),
|
| 43 |
+
"8024-13-1": ("Styrax resinoid", "styrax", 280.0),
|
| 44 |
+
"8031-03-6": ("Cardamom oil", "cardamom", 190.0),
|
| 45 |
+
"8032-35-1": ("Pumilio pine oil", "pumilio pine", 170.0),
|
| 46 |
+
"8046-19-3": ("Labdanum resinoid", "labdanum", 280.0),
|
| 47 |
+
"8047-24-3": ("Benzoin resinoid", "benzoin", 280.0),
|
| 48 |
+
"85409-36-9": ("Olibanum oil", "olibanum", 250.0),
|
| 49 |
+
"85940-31-4": ("Elemi oil", "elemi", 220.0),
|
| 50 |
+
"89997-75-1": ("Narcissus absolute", "narcissus", 250.0),
|
| 51 |
+
"9000-50-4": ("Frankincense oil", "frankincense", 250.0),
|
| 52 |
+
"9000-64-0": ("Mimosa absolute", "mimosa", 250.0),
|
| 53 |
+
"9000-64-2": ("Orange flower absolute", "orange flower", 240.0),
|
| 54 |
+
"8015-61-0": ("Cassie absolute", "cassie", 250.0),
|
| 55 |
+
"8015-77-8": ("Rosewood oil", "rosewood", 190.0),
|
| 56 |
+
"8016-26-0": ("Labdanum clair", "labdanum clair", 280.0),
|
| 57 |
+
"8022-96-6": ("Jasmin absolute", "jasmin absolute", 240.0),
|
| 58 |
+
"8000-34-8": ("Clove oil", "clove", 180.0),
|
| 59 |
+
"8006-87-9": ("Sandalwood oil", "sandalwood", 220.0),
|
| 60 |
+
"8007-01-0": ("Rose otto", "rose otto", 220.0),
|
| 61 |
+
"8007-06-5": ("Cascarilla oil", "cascarilla", 180.0),
|
| 62 |
+
"8007-75-8": ("Bergamot oil", "bergamot", 180.0),
|
| 63 |
+
"8008-45-5": ("Nutmeg oil", "nutmeg", 180.0),
|
| 64 |
+
"8013-90-9": ("Ionone", "ionone", 190.0),
|
| 65 |
+
"8014-09-3": ("Patchouli oil", "patchouli", 220.0),
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main() -> int:
|
| 70 |
+
parser = argparse.ArgumentParser(description="Add natural-extract placeholders to registry")
|
| 71 |
+
parser.add_argument("--registry", default="src/pino/registry.db", help="Path to registry.db")
|
| 72 |
+
args = parser.parse_args()
|
| 73 |
+
|
| 74 |
+
registry = AromaRegistry(args.registry)
|
| 75 |
+
added = 0
|
| 76 |
+
for cas, (name, _, mw) in NATURAL_PLACEHOLDERS.items():
|
| 77 |
+
try:
|
| 78 |
+
registry.add({
|
| 79 |
+
"cas": cas,
|
| 80 |
+
"name": name,
|
| 81 |
+
"smiles": f"NATURAL:{cas}",
|
| 82 |
+
"molecular_weight": mw,
|
| 83 |
+
"logp": 3.0,
|
| 84 |
+
"unifac_groups": {},
|
| 85 |
+
"vapor_pressure_pa": 0.01,
|
| 86 |
+
"boiling_point_k": 450.0,
|
| 87 |
+
"odor_threshold_ug_m3": None,
|
| 88 |
+
"odor_description": "",
|
| 89 |
+
})
|
| 90 |
+
added += 1
|
| 91 |
+
print(f"Added {cas} ({name})")
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"Skipped {cas}: {e}")
|
| 94 |
+
registry.close()
|
| 95 |
+
print(f"Added {added} natural placeholders")
|
| 96 |
+
return 0
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
raise SystemExit(main())
|
scripts/compare_ocr_vs_pymupdf.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Compare OCR (Space) extraction against PyMuPDF text extraction for fragrance book pages.
|
| 4 |
+
|
| 5 |
+
Reads the page images and the literature_pages.jsonl extracted text, runs a sample of
|
| 6 |
+
pages through the private PINO OCR Space, and reports:
|
| 7 |
+
- character-level similarity
|
| 8 |
+
- missing/extra formula lines
|
| 9 |
+
- per-page diff summary
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
export HF_TOKEN=...
|
| 13 |
+
python scripts/compare_ocr_vs_pymupdf.py --pages-dir fragrance-research/pages \
|
| 14 |
+
--pages-jsonl fragrance-research/extracted/literature_pages.jsonl \
|
| 15 |
+
--space https://mattbitzesty-pino-ocr.hf.space \
|
| 16 |
+
--sample 20 --output ocr_vs_pymupdf.json
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
from difflib import SequenceMatcher
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import requests
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def similarity(a: str, b: str) -> float:
|
| 32 |
+
return SequenceMatcher(None, a, b).ratio()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def clean_text(text: str) -> str:
|
| 36 |
+
# collapse whitespace, strip, lowercase for comparison
|
| 37 |
+
return re.sub(r"\s+", " ", text).strip().lower()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def extract_formula_lines(text: str) -> list[str]:
|
| 41 |
+
"""Naive heuristic: lines that look like 'amount material' or 'material amount'."""
|
| 42 |
+
lines = []
|
| 43 |
+
for line in text.splitlines():
|
| 44 |
+
line = line.strip()
|
| 45 |
+
if re.match(r"^\d+\s+[A-Za-z]", line) or re.match(r"^[A-Za-z].*\s\d+$", line):
|
| 46 |
+
lines.append(line)
|
| 47 |
+
return lines
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def ocr_image(space_url: str, token: str, image_path: Path, timeout: float = 120.0) -> str:
|
| 51 |
+
url = f"{space_url.rstrip('/')}/ocr"
|
| 52 |
+
with open(image_path, "rb") as f:
|
| 53 |
+
response = requests.post(
|
| 54 |
+
url,
|
| 55 |
+
files={"file": (image_path.name, f, "image/png")},
|
| 56 |
+
headers={"Authorization": f"Bearer {token}"},
|
| 57 |
+
timeout=timeout,
|
| 58 |
+
)
|
| 59 |
+
response.raise_for_status()
|
| 60 |
+
return response.json().get("text", "")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def normalize_source(source: str) -> str:
|
| 64 |
+
"""Normalize a full source title to the folder slug used by split_pdfs.py."""
|
| 65 |
+
s = source.lower()
|
| 66 |
+
# Strip common metadata after "--" (Anna's Archive suffix)
|
| 67 |
+
if " -- " in s:
|
| 68 |
+
s = s.split(" -- ")[0]
|
| 69 |
+
s = re.sub(r"[^a-z0-9]", "", s)
|
| 70 |
+
return s
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def load_page_text(path: Path) -> dict[tuple[str, int], str]:
|
| 74 |
+
records = {}
|
| 75 |
+
for line in path.read_text().strip().splitlines():
|
| 76 |
+
rec = json.loads(line)
|
| 77 |
+
source = normalize_source(rec.get("source", ""))
|
| 78 |
+
records[(source, rec.get("page", 0))] = rec.get("text", "")
|
| 79 |
+
return records
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def main() -> int:
|
| 83 |
+
parser = argparse.ArgumentParser(description="Compare OCR Space vs PyMuPDF text extraction")
|
| 84 |
+
parser.add_argument("--pages-dir", required=True, type=Path, help="Directory containing page images")
|
| 85 |
+
parser.add_argument("--pages-jsonl", required=True, type=Path, help="literature_pages.jsonl")
|
| 86 |
+
parser.add_argument("--space", default="https://mattbitzesty-pino-ocr.hf.space", help="OCR Space URL")
|
| 87 |
+
parser.add_argument("--sample", type=int, default=20, help="Number of pages to sample")
|
| 88 |
+
parser.add_argument("--output", type=Path, default=Path("data/ocr_vs_pymupdf.json"), help="Output JSON")
|
| 89 |
+
parser.add_argument("--timeout", type=float, default=120.0, help="OCR request timeout")
|
| 90 |
+
args = parser.parse_args()
|
| 91 |
+
|
| 92 |
+
token = os.environ.get("HF_TOKEN")
|
| 93 |
+
if not token:
|
| 94 |
+
print("Set HF_TOKEN", file=sys.stderr)
|
| 95 |
+
return 1
|
| 96 |
+
|
| 97 |
+
page_text = load_page_text(args.pages_jsonl)
|
| 98 |
+
|
| 99 |
+
# Collect images that correspond to known pages
|
| 100 |
+
images = sorted(args.pages_dir.rglob("*.png"))
|
| 101 |
+
# Map image path -> (source, page)
|
| 102 |
+
candidates = []
|
| 103 |
+
folder_to_source = {normalize_source(d.name): d.name for d in args.pages_dir.iterdir() if d.is_dir()}
|
| 104 |
+
for img in images:
|
| 105 |
+
# Expect page_0123.png
|
| 106 |
+
m = re.search(r"page_(\d+)", img.name)
|
| 107 |
+
if not m:
|
| 108 |
+
continue
|
| 109 |
+
page = int(m.group(1))
|
| 110 |
+
folder = normalize_source(img.parent.name)
|
| 111 |
+
if (folder, page) in page_text:
|
| 112 |
+
raw_folder = folder_to_source.get(folder, folder)
|
| 113 |
+
candidates.append((folder, raw_folder, page, img))
|
| 114 |
+
|
| 115 |
+
if not candidates:
|
| 116 |
+
print(f"No matching images found in {args.pages_dir}", file=sys.stderr)
|
| 117 |
+
return 1
|
| 118 |
+
|
| 119 |
+
# Sample across books
|
| 120 |
+
import random
|
| 121 |
+
random.seed(42)
|
| 122 |
+
sample = random.sample(candidates, min(args.sample, len(candidates)))
|
| 123 |
+
|
| 124 |
+
results = []
|
| 125 |
+
for folder, source, page, img in sample:
|
| 126 |
+
manual = page_text[(folder, page)]
|
| 127 |
+
try:
|
| 128 |
+
ocr_text = ocr_image(args.space, token, img, timeout=args.timeout)
|
| 129 |
+
except Exception as exc:
|
| 130 |
+
ocr_text = ""
|
| 131 |
+
print(f"OCR failed for {source} page {page}: {exc}", file=sys.stderr)
|
| 132 |
+
|
| 133 |
+
sim = similarity(clean_text(manual), clean_text(ocr_text))
|
| 134 |
+
manual_formulas = extract_formula_lines(manual)
|
| 135 |
+
ocr_formulas = extract_formula_lines(ocr_text)
|
| 136 |
+
|
| 137 |
+
results.append({
|
| 138 |
+
"source": source,
|
| 139 |
+
"page": page,
|
| 140 |
+
"image": str(img),
|
| 141 |
+
"similarity": sim,
|
| 142 |
+
"manual_chars": len(manual),
|
| 143 |
+
"ocr_chars": len(ocr_text),
|
| 144 |
+
"manual_formula_lines": manual_formulas,
|
| 145 |
+
"ocr_formula_lines": ocr_formulas,
|
| 146 |
+
})
|
| 147 |
+
print(f"{source} p{page}: sim={sim:.2f} manual={len(manual)} ocr={len(ocr_text)}")
|
| 148 |
+
|
| 149 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 150 |
+
args.output.write_text(json.dumps(results, indent=2, ensure_ascii=False))
|
| 151 |
+
print(f"Wrote {len(results)} comparisons to {args.output}")
|
| 152 |
+
return 0
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
raise SystemExit(main())
|
scripts/generate_dataset.py
CHANGED
|
@@ -15,7 +15,7 @@ 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:
|
|
@@ -23,6 +23,7 @@ def main() -> int:
|
|
| 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(
|
| 27 |
"--total-records",
|
| 28 |
type=int,
|
|
@@ -39,11 +40,12 @@ def main() -> int:
|
|
| 39 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 40 |
)
|
| 41 |
|
| 42 |
-
per_genre = max(1, args.total_records //
|
| 43 |
builder = DatasetBuilder(
|
| 44 |
output_path=args.output,
|
| 45 |
rules_path=args.rules,
|
| 46 |
registry_path=args.registry,
|
|
|
|
| 47 |
per_genre=per_genre,
|
| 48 |
max_workers=args.workers,
|
| 49 |
seed=args.seed,
|
|
|
|
| 15 |
|
| 16 |
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 17 |
|
| 18 |
+
from pino.dataset_builder import DatasetBuilder, GENRES
|
| 19 |
|
| 20 |
|
| 21 |
def main() -> int:
|
|
|
|
| 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("--literature", default="data/literature_formulas.json", help="Literature blueprint JSON")
|
| 27 |
parser.add_argument(
|
| 28 |
"--total-records",
|
| 29 |
type=int,
|
|
|
|
| 40 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 41 |
)
|
| 42 |
|
| 43 |
+
per_genre = max(1, args.total_records // len(GENRES))
|
| 44 |
builder = DatasetBuilder(
|
| 45 |
output_path=args.output,
|
| 46 |
rules_path=args.rules,
|
| 47 |
registry_path=args.registry,
|
| 48 |
+
literature_path=args.literature,
|
| 49 |
per_genre=per_genre,
|
| 50 |
max_workers=args.workers,
|
| 51 |
seed=args.seed,
|
scripts/parse_appell.py
ADDED
|
@@ -0,0 +1,761 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Parse Appell "Cosmetics, Fragrances and Flavors" perfume formulary.
|
| 4 |
+
|
| 5 |
+
Two phases:
|
| 6 |
+
1. Extract the code tables (pages 280-291) to map abbreviations to full names.
|
| 7 |
+
2. Extract formulas from the French-style (293-307), floral (308-329), and soap/cosmetic
|
| 8 |
+
(330-343) sections.
|
| 9 |
+
|
| 10 |
+
Formulas total 1000 parts. We resolve codes to full names and then to CAS via
|
| 11 |
+
TradeNameResolver. Formulas that are partially resolvable are kept; unresolved
|
| 12 |
+
components are flagged as sub_base/unknown.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import json
|
| 18 |
+
import re
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 25 |
+
|
| 26 |
+
from pino.trade_name_resolver import TradeNameResolver
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
# Code tables (pages 280-291). We hardcode the tables here because parsing the
|
| 31 |
+
# multi-column PDF text reliably is brittle; the tables are small and stable.
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
|
| 34 |
+
AROMATIC_CHEMICAL_CODES: dict[str, str] = {
|
| 35 |
+
"Ac Ph": "Acetophenone",
|
| 36 |
+
"Ald C7": "Aldehyde C 7",
|
| 37 |
+
"Ald C 7": "Aldehyde C 7",
|
| 38 |
+
"Ald C8": "Aldehyde C 8",
|
| 39 |
+
"Ald C 8": "Aldehyde C 8",
|
| 40 |
+
"Ald C9": "Aldehyde C 9",
|
| 41 |
+
"Ald C 9": "Aldehyde C 9",
|
| 42 |
+
"Ald C10": "Aldehyde C 10",
|
| 43 |
+
"Ald C 10": "Aldehyde C 10",
|
| 44 |
+
"Ald C11": "Aldehyde C 11 undecylenic",
|
| 45 |
+
"Ald C 11": "Aldehyde C 11 undecylenic",
|
| 46 |
+
"MNA": "Methyl nonyl acetaldehyde",
|
| 47 |
+
"UnLac": "Undecalactone",
|
| 48 |
+
"EMPG": "Ethyl methyl phenyl glycidate",
|
| 49 |
+
"NoLac": "Nonalactone",
|
| 50 |
+
"Am Ac": "i-Amyl acetate",
|
| 51 |
+
"Am Bz": "i-Amyl benzoate",
|
| 52 |
+
"Am Bu": "i-Amyl butyrate",
|
| 53 |
+
"Am Cin Ald": "Amyl cinnamic aldehyde",
|
| 54 |
+
"Am PhAc": "i-Amyl phenylacetate",
|
| 55 |
+
"Am Sal": "i-Amyl salicylate",
|
| 56 |
+
"An": "Anethole",
|
| 57 |
+
"An Ald": "Anisic aldehyde",
|
| 58 |
+
"An Ac": "Anisyl acetate",
|
| 59 |
+
"Bz Ald": "Benzaldehyde",
|
| 60 |
+
"BzPh": "Benzophenone",
|
| 61 |
+
"Bz Ac": "Benzyl acetate",
|
| 62 |
+
"Bz Alc": "Benzyl alcohol",
|
| 63 |
+
"Bz Bz": "Benzyl benzoate",
|
| 64 |
+
"Bz Cin": "Benzyl cinnamate",
|
| 65 |
+
"Bz For": "Benzyl formate",
|
| 66 |
+
"Bz PhAc": "Benzyl phenylacetate",
|
| 67 |
+
"Bz Pr": "Benzyl propionate",
|
| 68 |
+
"Bz Sal": "Benzyl salicylate",
|
| 69 |
+
"BZA": "Benzylidene acetone",
|
| 70 |
+
"Br": "Bromostyrole",
|
| 71 |
+
"Bu Bz": "i-Butyl benzoate",
|
| 72 |
+
"BH Ac": "p-t-Butyl cyclohexyl acetate",
|
| 73 |
+
"Cp": "Camphor crystals",
|
| 74 |
+
"Cc": "Carvacrol",
|
| 75 |
+
"Cv": "1-Carvone",
|
| 76 |
+
"Cd": "Cedrol",
|
| 77 |
+
"Cd Ac": "Cedryl acetate",
|
| 78 |
+
"Cin Alc": "Cinnamic alcohol",
|
| 79 |
+
"Cin Ald": "Cinnamic aldehyde",
|
| 80 |
+
"Cin Ac": "Cinnamyl acetate",
|
| 81 |
+
"Ci": "Citral",
|
| 82 |
+
"Ct": "Citronellal",
|
| 83 |
+
"Cl": "Citronellol",
|
| 84 |
+
"Cl Ac": "Citronellyl acetate",
|
| 85 |
+
"COA": "Citronellyl oxy-acetaldehyde",
|
| 86 |
+
"Co": "Coumarin",
|
| 87 |
+
"Cr Ac": "p-Cresyl acetate",
|
| 88 |
+
"PCME": "p-Cresyl methyl ether",
|
| 89 |
+
"Cr PhAc": "p-Cresyl phenylacetate",
|
| 90 |
+
"Cum Ald": "Cuminic aldehyde",
|
| 91 |
+
"Cy": "Cyclamen aldehyde",
|
| 92 |
+
"DEP": "Diethyl phthalate",
|
| 93 |
+
"DM Ant": "Dimethyl anthranilate",
|
| 94 |
+
"DMBC Ac": "Dimethyl benzyl carbinol acetate",
|
| 95 |
+
"DMH": "Dimethyl hydroquinone",
|
| 96 |
+
"Dp": "Dipentine",
|
| 97 |
+
"DPO": "Diphenyl oxide",
|
| 98 |
+
"DPG": "Dipropylene glycol",
|
| 99 |
+
"Et Am K": "Ethyl i-amyl ketone",
|
| 100 |
+
"Et Bz": "Ethyl benzoate",
|
| 101 |
+
"Et Bu": "Ethyl i-butyrate",
|
| 102 |
+
"Et Cin": "Ethyl cinnamate",
|
| 103 |
+
"Et Oen": "Ethyl oenanthate",
|
| 104 |
+
"Et Pel": "Ethyl pelargonate",
|
| 105 |
+
"Et PhAc": "Ethyl phenylacetate",
|
| 106 |
+
"Et Pr": "Ethyl propionate",
|
| 107 |
+
"Et Sal": "Ethyl salicylate",
|
| 108 |
+
"Et Val": "Ethyl i-valerate",
|
| 109 |
+
"Et Va": "Ethyl vanillin",
|
| 110 |
+
"Eu": "Eugenol",
|
| 111 |
+
"Eu Ac": "Eugenol acetate",
|
| 112 |
+
"Gu Ac": "Guayol acetate",
|
| 113 |
+
"Gl": "Geraniol",
|
| 114 |
+
"Gl Ac": "Geranyl acetate",
|
| 115 |
+
"Gl For": "Geranyl formate",
|
| 116 |
+
"Gl Bu": "Geranyl i-butyrate",
|
| 117 |
+
"2Hx Ald": "2-Hexenal",
|
| 118 |
+
"2Hx Alc": "2-Hexenol",
|
| 119 |
+
"Hx Cin Ald": "Hexyl cinnamic aldehyde",
|
| 120 |
+
"He": "Heliotropin",
|
| 121 |
+
"HTA": "Hydratropic aldehyde",
|
| 122 |
+
"HTA-DMA": "Hydratropic aldehyde dimethyl acetal",
|
| 123 |
+
"Hy": "Hydroxycitronellal",
|
| 124 |
+
"Et AAc": "Ethyl acetoacetate",
|
| 125 |
+
"In": "Indole",
|
| 126 |
+
"Io": "Ionone alpha",
|
| 127 |
+
"i-Bo Ac": "Isobornyl acetate",
|
| 128 |
+
"i-Bo For": "Isobornyl formate",
|
| 129 |
+
"i-Bo Pr": "Isobornyl propionate",
|
| 130 |
+
"ic-Ci": "Isocyclocitral",
|
| 131 |
+
"i-Eu": "Isoeugenol",
|
| 132 |
+
"i-Eu Ac": "Isoeugenol acetate",
|
| 133 |
+
"i-Ja": "Isojasmone",
|
| 134 |
+
"Lil": "Lilial",
|
| 135 |
+
"Lm": "Limonene",
|
| 136 |
+
"Lin": "Linalool",
|
| 137 |
+
"Lin Ac": "Linalyl acetate",
|
| 138 |
+
"Lin Pr": "Linalyl propionate",
|
| 139 |
+
"MI": "Menthol",
|
| 140 |
+
"Mn": "Menthone",
|
| 141 |
+
"Me AcPh": "p-Methyl acetophenone",
|
| 142 |
+
"Me Ant": "Methyl anthranilate",
|
| 143 |
+
"Me Bz": "Methyl benzoate",
|
| 144 |
+
"Me Cin": "Methyl cinnamate",
|
| 145 |
+
"Me Eu": "Methyl eugenol",
|
| 146 |
+
"Me i-Eu": "Methyl isoeugenol",
|
| 147 |
+
"MHC": "Methyl heptine carbonate",
|
| 148 |
+
"Me In": "Methyl indole",
|
| 149 |
+
"MNK": "Methyl naphthyl ketone",
|
| 150 |
+
"Me HTA": "p-Methyl hydratropic aldehyde",
|
| 151 |
+
"Me Io": "Methyl ionone",
|
| 152 |
+
"MNA": "Methyl nonyl acetaldehyde",
|
| 153 |
+
"Me PhAc": "Methyl phenylacetate",
|
| 154 |
+
"Me Q": "p-Methyl quinoline",
|
| 155 |
+
"Me Sal": "Methyl salicylate",
|
| 156 |
+
"Me Un": "Methyl undecylenate",
|
| 157 |
+
"MA": "Musk ambrette",
|
| 158 |
+
"MK": "Musk ketone",
|
| 159 |
+
"MX": "Musk xylene",
|
| 160 |
+
"MB": "Musc brassylate",
|
| 161 |
+
"M P": "Musc pentadecanolide",
|
| 162 |
+
"NI": "Nerol",
|
| 163 |
+
"Ne": "Nerolin",
|
| 164 |
+
"NoLac": "Nonalactone",
|
| 165 |
+
"Nol Ac": "1,3-Nonanediol acetate",
|
| 166 |
+
"No Ac": "Nonyl acetate",
|
| 167 |
+
"Oc Ac": "Octyl acetate",
|
| 168 |
+
"PhA": "Phenylacetaldehyde",
|
| 169 |
+
"PhA-DMA": "Phenylacetaldehyde dimethylacetal",
|
| 170 |
+
"PhAc Acid": "Phenylacetic acid",
|
| 171 |
+
"PhEt Ac": "Phenylethyl acetate",
|
| 172 |
+
"PhEt Alc": "Phenylethyl alcohol",
|
| 173 |
+
"PhEt For": "Phenylethyl formate",
|
| 174 |
+
"PhEt Pr": "Phenylethyl propionate",
|
| 175 |
+
"PhPr Ac": "Phenylpropyl acetate",
|
| 176 |
+
"PhPr Alc": "Phenylpropyl alcohol",
|
| 177 |
+
"PhPr Ald": "Phenylpropyl aldehyde",
|
| 178 |
+
"PG": "Propylene glycol",
|
| 179 |
+
"Rasp cryst": "Raspberry crystals",
|
| 180 |
+
"Rose cryst": "Rose crystals",
|
| 181 |
+
"Rose Oxide": "Rose oxide",
|
| 182 |
+
"Rl": "Rhodinol",
|
| 183 |
+
"Sa": "Safrole",
|
| 184 |
+
"Sal Ald": "Salicylic aldehyde",
|
| 185 |
+
"Se": "Sedanolid",
|
| 186 |
+
"Skatol": "Methyl indole",
|
| 187 |
+
"St Ac": "Styrallyl acetate",
|
| 188 |
+
"Tl": "Terpineol",
|
| 189 |
+
"Tl Ac": "Terpinyl acetate",
|
| 190 |
+
"THG": "Tetrahydrogeraniol",
|
| 191 |
+
"THMQ": "Tetrahydro p-methyl quinoline",
|
| 192 |
+
"Thu": "Thujone",
|
| 193 |
+
"Th": "Thymol",
|
| 194 |
+
"UnLac": "Undecalactone",
|
| 195 |
+
"Va": "Vanillin",
|
| 196 |
+
"Vi": "Vetiverol",
|
| 197 |
+
"Vl Ac": "Vetiveryl acetate",
|
| 198 |
+
"Ya": "Yara-yara",
|
| 199 |
+
"Lav abs": "Lavender absolute",
|
| 200 |
+
"Org tpl": "Orange terpeneless",
|
| 201 |
+
"Brg tpl": "Bergamot terpeneless",
|
| 202 |
+
"Ori crt": "Orris concrete",
|
| 203 |
+
"Ben res": "Benzoin resinoid",
|
| 204 |
+
"Lab res": "Labdanum resinoid",
|
| 205 |
+
"Sty res": "Styrax resinoid",
|
| 206 |
+
"Gal res": "Galbanum resinoid",
|
| 207 |
+
"Ton res": "Tonka resinoid",
|
| 208 |
+
"Myr res": "Myrrh resinoid",
|
| 209 |
+
"Opo res": "Opoponax resinoid",
|
| 210 |
+
"Civ res": "Civet resinoid",
|
| 211 |
+
"Civ abs": "Civet absolute",
|
| 212 |
+
"Civ Tr": "Civet tincture",
|
| 213 |
+
"Msk Tr": "Musk tincture",
|
| 214 |
+
"Van Tr": "Vanilla tincture",
|
| 215 |
+
"Cas Tr": "Cassie tincture",
|
| 216 |
+
"Ambrene 50": "Ambrene 50%",
|
| 217 |
+
"Ambrarome 5": "Ambrarome 5%",
|
| 218 |
+
"Ambrarome 10": "Ambrarome 10%",
|
| 219 |
+
"Ambrarome 50": "Ambrarome 50%",
|
| 220 |
+
"Base Poivre 10": "Base Poivre 10%",
|
| 221 |
+
"Dianthus 10": "Dianthus 10%",
|
| 222 |
+
"Lilac 50": "Lilac 50%",
|
| 223 |
+
"Jasmin 50": "Jasmin 50%",
|
| 224 |
+
"Jasmin 30": "Jasmin 30%",
|
| 225 |
+
"Jasmin 70": "Jasmin 70%",
|
| 226 |
+
"Jasmin Fl 100": "Jasmin Flower 100%",
|
| 227 |
+
"Jasmin Flower 100": "Jasmin Flower 100%",
|
| 228 |
+
"Rose W": "Rose W",
|
| 229 |
+
"Acacia 10": "Acacia 10%",
|
| 230 |
+
"Narcissus 30": "Narcissus 30%",
|
| 231 |
+
"Hyacinth 10": "Hyacinth 10%",
|
| 232 |
+
"Muguet 10A": "Muguet 10A",
|
| 233 |
+
"Muguet 10 B": "Muguet 10 B",
|
| 234 |
+
"Tuberose 10": "Tuberose 10%",
|
| 235 |
+
"Carnation 10": "Carnation 10%",
|
| 236 |
+
"UnLac 10": "Undecalactone 10%",
|
| 237 |
+
"Cos 10": "Costus 10%",
|
| 238 |
+
"MdC 10": "Mousse de Chene Integrale 10%",
|
| 239 |
+
"Ori crt 10": "Orris concrete 10%",
|
| 240 |
+
"Ben res 10": "Benzoin resinoid 10%",
|
| 241 |
+
"Ben res 50": "Benzoin resinoid 50%",
|
| 242 |
+
"Lab abs 10": "Labdanum absolute 10%",
|
| 243 |
+
"Lab abs 50": "Labdanum absolute 50%",
|
| 244 |
+
"Sty res 10": "Styrax resinoid 10%",
|
| 245 |
+
"Org tpl 10": "Orange terpeneless 10%",
|
| 246 |
+
"Civ Tr 10": "Civet tincture 10%",
|
| 247 |
+
"Civ Tr 3": "Civet tincture 3%",
|
| 248 |
+
"Msk Tr 3": "Musk tincture 3%",
|
| 249 |
+
"Van Tr 10": "Vanilla tincture 10%",
|
| 250 |
+
"Ald C 9,10%": "Aldehyde C 9 10%",
|
| 251 |
+
"Ald C 10,10%": "Aldehyde C 10 10%",
|
| 252 |
+
"Ald C 11,10%": "Aldehyde C 11 10%",
|
| 253 |
+
"Ald C 12,10%": "Aldehyde C 12 10%",
|
| 254 |
+
"Ald C 10,1%": "Aldehyde C 10 1%",
|
| 255 |
+
"Ald C 11,1%": "Aldehyde C 11 1%",
|
| 256 |
+
"MNA 1%": "Methyl nonyl acetaldehyde 1%",
|
| 257 |
+
"MNA 10%": "Methyl nonyl acetaldehyde 10%",
|
| 258 |
+
"Al Io 10%": "Allyl ionone 10%",
|
| 259 |
+
"Al Cap 1%": "Allyl caproate 1%",
|
| 260 |
+
"Al Cap 10%": "Allyl caproate 10%",
|
| 261 |
+
"i-Bu Q 10%": "i-Butyl quinoline 10%",
|
| 262 |
+
"i-Bu Sal": "i-Butyl salicylate",
|
| 263 |
+
"Et Est 10%": "Ethyl ester 10%",
|
| 264 |
+
"Est 10%": "Estragon 10%",
|
| 265 |
+
"S-CinG": "Spicy cinnamon group",
|
| 266 |
+
"2Hx Ald 0.1%": "2-Hexenal 0.1%",
|
| 267 |
+
"In 10%": "Indole 10%",
|
| 268 |
+
"p-Cr Ac": "p-Cresyl acetate",
|
| 269 |
+
"p-Cresol 10%": "p-Cresol 10%",
|
| 270 |
+
"PhA 10%": "Phenylacetaldehyde 10%",
|
| 271 |
+
"PhA 50%": "Phenylacetaldehyde 50%",
|
| 272 |
+
"PhPr Ald 10%": "Phenylpropyl aldehyde 10%",
|
| 273 |
+
"PhPr Alc 10%": "Phenylpropyl alcohol 10%",
|
| 274 |
+
"BH Ac10%": "p-t-Butyl cyclohexyl acetate 10%",
|
| 275 |
+
"DMBC Ac": "Dimethyl benzyl carbinol acetate",
|
| 276 |
+
"DH Ja1%": "Dihydroisojasmone 1%",
|
| 277 |
+
"DH Jai%": "Dihydroisojasmone 1%",
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
ESSENTIAL_OIL_CODES: dict[str, str] = {
|
| 281 |
+
"Amb": "Ambrette seed",
|
| 282 |
+
"Amg": "Ambergris",
|
| 283 |
+
"Amy": "Amyris",
|
| 284 |
+
"Ang": "Angelica seed",
|
| 285 |
+
"Ani": "Anise oil",
|
| 286 |
+
"Arm": "Armoise oil",
|
| 287 |
+
"Asp": "Lavender spike oil",
|
| 288 |
+
"Bas": "Basil oil",
|
| 289 |
+
"Bay": "Bay oil",
|
| 290 |
+
"Ben": "Benzoin resinoid",
|
| 291 |
+
"Brg": "Bergamot oil",
|
| 292 |
+
"BdR": "Bois de rose oil",
|
| 293 |
+
"Cad": "Cade oil",
|
| 294 |
+
"Cal": "Calamus oil",
|
| 295 |
+
"Cpr": "Camphor oil",
|
| 296 |
+
"Can": "Cananga oil",
|
| 297 |
+
"Cay": "Caraway oil",
|
| 298 |
+
"Com": "Cardamom oil",
|
| 299 |
+
"Cot": "Carrot seed oil",
|
| 300 |
+
"Csc": "Cascarilla oil",
|
| 301 |
+
"Cia": "Cassia oil",
|
| 302 |
+
"Cie": "Cassie absolute",
|
| 303 |
+
"Cas": "Castoreum",
|
| 304 |
+
"Cdl": "Cedarleaf oil",
|
| 305 |
+
"Cdw": "Cedarwood oil",
|
| 306 |
+
"Cel": "Celery seed oil",
|
| 307 |
+
"Cam": "Chamomile oil",
|
| 308 |
+
"Cin C": "Cinnamon Ceylon oil",
|
| 309 |
+
"Cil": "Cinnamon leaf oil",
|
| 310 |
+
"Cis": "Cistus labdanum",
|
| 311 |
+
"Cta C": "Citronella Ceylon oil",
|
| 312 |
+
"Cta J": "Citronella Java oil",
|
| 313 |
+
"Civ": "Civet",
|
| 314 |
+
"Clo": "Clove oil",
|
| 315 |
+
"Cor": "Coriander oil",
|
| 316 |
+
"Cos": "Costus oil",
|
| 317 |
+
"Cub": "Cubeb oil",
|
| 318 |
+
"Cum": "Cumin oil",
|
| 319 |
+
"Dil": "Dillweed oil",
|
| 320 |
+
"Ele": "Elemi oil",
|
| 321 |
+
"Est": "Estragon oil",
|
| 322 |
+
"Euc": "Eucalyptus oil",
|
| 323 |
+
"FdO": "Fleur d'Oranger",
|
| 324 |
+
"Fen": "Fennel seed oil",
|
| 325 |
+
"Fir": "Fir needle Siberian oil",
|
| 326 |
+
"Gal": "Galbanum oil",
|
| 327 |
+
"Gal res": "Galbanum resinoid",
|
| 328 |
+
"Ger": "Geranium oil",
|
| 329 |
+
"Gin": "Ginger oil",
|
| 330 |
+
"Gua": "Guaiacwood oil",
|
| 331 |
+
"Hem": "Hemlock spruce oil",
|
| 332 |
+
"Hya": "Hyacinth absolute",
|
| 333 |
+
"Hys": "Hyssop oil",
|
| 334 |
+
"Imo": "Immortelle absolute",
|
| 335 |
+
"Ori": "Orris",
|
| 336 |
+
"Jas": "Jasmin absolute",
|
| 337 |
+
"Jas abs": "Jasmin absolute",
|
| 338 |
+
"Jon": "Jonquil absolute",
|
| 339 |
+
"Jun": "Juniper berry oil",
|
| 340 |
+
"Lab": "Labdanum",
|
| 341 |
+
"Lab abs": "Labdanum absolute",
|
| 342 |
+
"Lab res": "Labdanum resinoid",
|
| 343 |
+
"Lvn": "Lavandin oil",
|
| 344 |
+
"Lav": "Lavender oil",
|
| 345 |
+
"Lav abs": "Lavender absolute",
|
| 346 |
+
"Lem": "Lemon oil",
|
| 347 |
+
"Lmg": "Lemongrass oil",
|
| 348 |
+
"Lim": "Lime distilled oil",
|
| 349 |
+
"Lrl": "Laurel leaf oil",
|
| 350 |
+
"Lvg": "Lovage oil",
|
| 351 |
+
"Man": "Mandarin oil",
|
| 352 |
+
"Mrg": "Marjoram wild oil",
|
| 353 |
+
"Mim": "Mimosa absolute",
|
| 354 |
+
"Mdc": "Mousse de Chene",
|
| 355 |
+
"Mou": "Mousse de Chene",
|
| 356 |
+
"Musk": "Musk natural",
|
| 357 |
+
"Myr": "Myrrh oil",
|
| 358 |
+
"Myr res": "Myrrh resinoid",
|
| 359 |
+
"Ner": "Neroli oil",
|
| 360 |
+
"Nut": "Nutmeg oil",
|
| 361 |
+
"Oak": "Oak moss",
|
| 362 |
+
"Oga": "Origanum oil",
|
| 363 |
+
"Oli": "Olibanum oil",
|
| 364 |
+
"Oli res": "Olibanum resinoid",
|
| 365 |
+
"OpO": "Opoponax oil",
|
| 366 |
+
"Opo": "Opoponax oil",
|
| 367 |
+
"Opo res": "Opoponax resinoid",
|
| 368 |
+
"Pal": "Palmarosa oil",
|
| 369 |
+
"Pars": "Parsley oil",
|
| 370 |
+
"Pat": "Patchouli oil",
|
| 371 |
+
"Ppr": "Pepper black oil",
|
| 372 |
+
"Pen": "Pennyroyal oil",
|
| 373 |
+
"Mnt": "Peppermint oil",
|
| 374 |
+
"Peru": "Peru balsam oil",
|
| 375 |
+
"Ptg": "Petitgrain oil",
|
| 376 |
+
"Pim": "Pimenta berries oil",
|
| 377 |
+
"Res": "Reseda absolute",
|
| 378 |
+
"Ros": "Rose absolute",
|
| 379 |
+
"Ros abs": "Rose absolute",
|
| 380 |
+
"Ros B": "Rose Bulgarian otto",
|
| 381 |
+
"Rsm": "Rosemary oil",
|
| 382 |
+
"SgC": "Sage Clary oil",
|
| 383 |
+
"SgD": "Sage Dalmatian oil",
|
| 384 |
+
"Sgs": "Sage Spanish oil",
|
| 385 |
+
"San": "Sandalwood oil",
|
| 386 |
+
"Sas": "Sassafras oil",
|
| 387 |
+
"Spm": "Spearmint oil",
|
| 388 |
+
"Spr": "Spruce oil",
|
| 389 |
+
"Sty": "Styrax oil",
|
| 390 |
+
"Tan": "Tansy oil",
|
| 391 |
+
"Ton": "Tonka",
|
| 392 |
+
"Tar": "Tarragon oil",
|
| 393 |
+
"Thy": "Thyme white oil",
|
| 394 |
+
"Tolu": "Tolu balsam",
|
| 395 |
+
"Tub": "Tuberose absolute",
|
| 396 |
+
"Van": "Vanilla",
|
| 397 |
+
"Verb": "Verbena oil",
|
| 398 |
+
"Vet": "Vetiver oil",
|
| 399 |
+
"Vl": "Vetiverol",
|
| 400 |
+
"Vio": "Violet leaves absolute",
|
| 401 |
+
"Yig": "Ylang-ylang oil",
|
| 402 |
+
"Ylg": "Ylang-ylang oil",
|
| 403 |
+
"Org": "Orange sweet oil",
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
ABBREVIATION_EXPANSIONS: dict[str, str] = {
|
| 407 |
+
"abs": "absolute",
|
| 408 |
+
"res": "resinoid",
|
| 409 |
+
"crt": "concrete",
|
| 410 |
+
"Tr": "tincture",
|
| 411 |
+
"Fl": "flower",
|
| 412 |
+
"tpl": "terpeneless",
|
| 413 |
+
"sub": "substitute",
|
| 414 |
+
"tls": "terpeneless",
|
| 415 |
+
"tps": "terpenes",
|
| 416 |
+
"distillate": "distillate",
|
| 417 |
+
"(d)": "decolorized",
|
| 418 |
+
"SB": "Schiff base",
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def build_code_map() -> dict[str, str]:
|
| 423 |
+
"""Merge all Appell code tables into one lookup."""
|
| 424 |
+
code_map = {}
|
| 425 |
+
code_map.update(AROMATIC_CHEMICAL_CODES)
|
| 426 |
+
code_map.update(ESSENTIAL_OIL_CODES)
|
| 427 |
+
code_map.update(ABBREVIATION_EXPANSIONS)
|
| 428 |
+
# Alias lower-case keys
|
| 429 |
+
for k, v in list(code_map.items()):
|
| 430 |
+
code_map.setdefault(k.lower(), v)
|
| 431 |
+
return code_map
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
CODE_MAP = build_code_map()
|
| 435 |
+
|
| 436 |
+
# Header patterns
|
| 437 |
+
FRENCH_HEADER_RE = re.compile(r'Type\s+["“]([^"”]+)["”](?:\s*\(([^)]+)\))?')
|
| 438 |
+
|
| 439 |
+
# Floral fragrances section headers: Name + number (10, 20, 30, 40, 50, 70, 100, etc.)
|
| 440 |
+
# Only match in the floral section to avoid matching sub-base references like "Jasmin 50".
|
| 441 |
+
FLORAL_HEADER_RE = re.compile(
|
| 442 |
+
r'^(Jasmin|Rose|Lilac|Jasmin Flower|Jonquil|Narcissus|Acacia|Dianthus|Hyacinth|'
|
| 443 |
+
r'Muguet|Tuberose|Carnation|Lily|Violet|Freesia|Gardenia|Orange Blossom|Magnolia|Iris|Sweet Pea|Wall Flower|Wisteria|Jacinthe|Honeysuckle)\s+'
|
| 444 |
+
r'(\d+(?:\s*[A-C])?)$',
|
| 445 |
+
re.IGNORECASE,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
SOAP_HEADER_RE = re.compile(
|
| 449 |
+
r'^(Cologne|Floral Bouquet|Foug[eè]re|Geranium|Soap Perfume|Rose|Lavender|'
|
| 450 |
+
r'Sandalwood|Chypre|Muguet|Jasmin|Oriental|Fruit|Amber|Aldehydic|Citrus|Spicy|Fresh|'
|
| 451 |
+
r'Transparent|Green|Powdery|Woody|Floral|Musk|Sweet|Balsamic|Coniferous|Herbal|Leather|Tobacco|'
|
| 452 |
+
r'Apple|May Blossom|Neroli|Verbena|Ylang)\s+S\s*(\d+)$',
|
| 453 |
+
re.IGNORECASE,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
SECTION_RE = re.compile(r'^(9-1\.\s+Perfumes \(French Style\)|9-2\.\s+Cologne fragrances|9-3\.\s+Floral fragrances|9-4\.\s+Perfumes for cosmetics and soap|Floral fragrances|Perfumes, French style|Perfumes for cosmetics and soaps|Perfume formulations|9\.\s+Perfume formulations)', re.IGNORECASE)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
# ---------------------------------------------------------------------------
|
| 460 |
+
# Formula extraction
|
| 461 |
+
# ---------------------------------------------------------------------------
|
| 462 |
+
|
| 463 |
+
def _expand_code(raw_code: str) -> str | None:
|
| 464 |
+
"""Expand an Appell code to a full name. Handles compound codes and suffixes."""
|
| 465 |
+
raw = raw_code.strip()
|
| 466 |
+
if not raw:
|
| 467 |
+
return None
|
| 468 |
+
|
| 469 |
+
# Direct lookup (case-insensitive)
|
| 470 |
+
if raw in CODE_MAP:
|
| 471 |
+
return CODE_MAP[raw]
|
| 472 |
+
lower = raw.lower()
|
| 473 |
+
if lower in CODE_MAP:
|
| 474 |
+
return CODE_MAP[lower]
|
| 475 |
+
|
| 476 |
+
# Strip percentage suffixes like "10%", "50%", "3%", "1%", "0.1%"
|
| 477 |
+
pct_match = re.search(r'\s*(\d+(?:\.\d+)?)\s*%\s*$', raw)
|
| 478 |
+
base = re.sub(r'\s*\d+(?:\.\d+)?\s*%\s*$', '', raw).strip() if pct_match else raw
|
| 479 |
+
pct = f" {pct_match.group(1)}%" if pct_match else ""
|
| 480 |
+
|
| 481 |
+
if base in CODE_MAP:
|
| 482 |
+
return CODE_MAP[base] + pct
|
| 483 |
+
if base.lower() in CODE_MAP:
|
| 484 |
+
return CODE_MAP[base.lower()] + pct
|
| 485 |
+
|
| 486 |
+
# Handle compound codes: e.g., "Me Io" -> "Methyl ionone", "Cl Ac" -> "Citronellyl acetate"
|
| 487 |
+
# Split into tokens and try to expand token by token
|
| 488 |
+
tokens = base.split()
|
| 489 |
+
if len(tokens) >= 2:
|
| 490 |
+
# Try as a whole first via underscore join
|
| 491 |
+
joined = " ".join(tokens)
|
| 492 |
+
if joined in CODE_MAP:
|
| 493 |
+
return CODE_MAP[joined] + pct
|
| 494 |
+
# Expand radical + functional: e.g., "Me" + "Bz" = "Methyl benzoate"
|
| 495 |
+
# This is ambiguous, so prefer exact matches from the table above.
|
| 496 |
+
|
| 497 |
+
# Try stripping suffixes like abs, res, Tr, tpl, Fl and looking up base
|
| 498 |
+
for suffix, expansion in ABBREVIATION_EXPANSIONS.items():
|
| 499 |
+
if base.lower().endswith(suffix.lower()):
|
| 500 |
+
prefix = base[: -len(suffix)].strip()
|
| 501 |
+
if prefix in CODE_MAP:
|
| 502 |
+
return CODE_MAP[prefix] + " " + expansion + pct
|
| 503 |
+
if prefix.lower() in CODE_MAP:
|
| 504 |
+
return CODE_MAP[prefix.lower()] + " " + expansion + pct
|
| 505 |
+
|
| 506 |
+
# Try adding common suffixes if the raw code itself is not found but is a known base
|
| 507 |
+
# e.g., "Jas" not found, but "Jas abs" is; we already handled suffix stripping above.
|
| 508 |
+
|
| 509 |
+
return None
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _extract_amount(line: str) -> tuple[float | None, str]:
|
| 513 |
+
"""Try to extract a leading or trailing amount from a line."""
|
| 514 |
+
# Leading amount: "30 Brg"
|
| 515 |
+
m = re.match(r'^(\d+(?:\.\d+)?)\s+(.+)$', line.strip())
|
| 516 |
+
if m:
|
| 517 |
+
return float(m.group(1)), m.group(2).strip()
|
| 518 |
+
# Trailing amount: "Bz Ac 50"
|
| 519 |
+
m = re.match(r'^(.+?)\s+(\d+(?:\.\d+)?)\s*$', line.strip())
|
| 520 |
+
if m:
|
| 521 |
+
return float(m.group(2)), m.group(1).strip()
|
| 522 |
+
return None, line.strip()
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def _line_to_components(line: str) -> list[dict[str, Any]] | None:
|
| 526 |
+
"""Convert a formula line into one or more components."""
|
| 527 |
+
line = line.strip()
|
| 528 |
+
if not line or len(line) < 3:
|
| 529 |
+
return None
|
| 530 |
+
|
| 531 |
+
# Skip totals and page numbers
|
| 532 |
+
if re.match(r'^\d{1,4}$', line):
|
| 533 |
+
return None
|
| 534 |
+
if re.match(r'^T\s+1000', line, re.IGNORECASE):
|
| 535 |
+
return None
|
| 536 |
+
if "continued" in line.lower() or "Perfumes, French style" in line or "Floral fragrances" in line or "Perfumes for cosmetics and soaps" in line:
|
| 537 |
+
return None
|
| 538 |
+
|
| 539 |
+
amount, remainder = _extract_amount(line)
|
| 540 |
+
if amount is None:
|
| 541 |
+
return None
|
| 542 |
+
|
| 543 |
+
# Sometimes a line has multiple codes and one amount at the end: "A B C 100"
|
| 544 |
+
# Split the remainder and try to assign the amount to each recognized code.
|
| 545 |
+
tokens = remainder.split()
|
| 546 |
+
|
| 547 |
+
# Heuristic: if the last token is a percentage, it applies to the whole line
|
| 548 |
+
pct = ""
|
| 549 |
+
if tokens and re.match(r'\d+(?:\.\d+)?%', tokens[-1]):
|
| 550 |
+
pct = tokens.pop()
|
| 551 |
+
|
| 552 |
+
# Try to find the longest code prefix in the remaining tokens
|
| 553 |
+
components = []
|
| 554 |
+
i = 0
|
| 555 |
+
while i < len(tokens):
|
| 556 |
+
# Try matching 1, 2, or 3 token codes
|
| 557 |
+
found = False
|
| 558 |
+
for n in range(min(3, len(tokens) - i), 0, -1):
|
| 559 |
+
candidate = " ".join(tokens[i : i + n])
|
| 560 |
+
expanded = _expand_code(candidate + (" " + pct if pct else ""))
|
| 561 |
+
if expanded is None and pct:
|
| 562 |
+
expanded = _expand_code(candidate)
|
| 563 |
+
if expanded:
|
| 564 |
+
components.append({"name": expanded, "amount": amount, "raw_code": candidate + (" " + pct if pct else "")})
|
| 565 |
+
i += n
|
| 566 |
+
found = True
|
| 567 |
+
break
|
| 568 |
+
if not found:
|
| 569 |
+
# Unrecognized token, skip it
|
| 570 |
+
i += 1
|
| 571 |
+
|
| 572 |
+
# If we recognized nothing, keep the raw line as unknown with amount
|
| 573 |
+
if not components and remainder:
|
| 574 |
+
components.append({"name": remainder + (" " + pct if pct else ""), "amount": amount, "raw_code": remainder + (" " + pct if pct else "")})
|
| 575 |
+
|
| 576 |
+
return components
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def _detect_headers(text: str) -> list[tuple[int, str, str | None]]:
|
| 580 |
+
"""Return list of (line_index, header_name, extra_info) for formula headers."""
|
| 581 |
+
headers = []
|
| 582 |
+
current_section: str | None = None
|
| 583 |
+
lines = text.splitlines()
|
| 584 |
+
for i, line in enumerate(lines):
|
| 585 |
+
line = line.strip()
|
| 586 |
+
if not line:
|
| 587 |
+
continue
|
| 588 |
+
|
| 589 |
+
section_m = SECTION_RE.match(line)
|
| 590 |
+
if section_m:
|
| 591 |
+
current_section = section_m.group(1)
|
| 592 |
+
continue
|
| 593 |
+
|
| 594 |
+
m = FRENCH_HEADER_RE.match(line)
|
| 595 |
+
if m and (current_section is None or "french" in current_section.lower()):
|
| 596 |
+
headers.append((i, m.group(1).strip(), m.group(2)))
|
| 597 |
+
continue
|
| 598 |
+
|
| 599 |
+
m = FLORAL_HEADER_RE.match(line)
|
| 600 |
+
if m and current_section and "floral" in current_section.lower():
|
| 601 |
+
headers.append((i, f"{m.group(1)} {m.group(2)}", None))
|
| 602 |
+
continue
|
| 603 |
+
|
| 604 |
+
m = SOAP_HEADER_RE.match(line)
|
| 605 |
+
if m and current_section and ("soap" in current_section.lower() or "cosmetic" in current_section.lower()):
|
| 606 |
+
headers.append((i, f"{m.group(1)} S {m.group(2)}", None))
|
| 607 |
+
|
| 608 |
+
return headers
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def _is_header_line(line: str, current_section: str | None = None) -> bool:
|
| 612 |
+
line = line.strip()
|
| 613 |
+
if FRENCH_HEADER_RE.match(line):
|
| 614 |
+
return current_section is None or "french" in current_section.lower()
|
| 615 |
+
if FLORAL_HEADER_RE.match(line):
|
| 616 |
+
return current_section is not None and "floral" in current_section.lower()
|
| 617 |
+
if SOAP_HEADER_RE.match(line):
|
| 618 |
+
return current_section is not None and ("soap" in current_section.lower() or "cosmetic" in current_section.lower())
|
| 619 |
+
return False
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def parse_appell_pages(records: list[dict[str, Any]], page_range: tuple[int, int] | None = None) -> list[dict[str, Any]]:
|
| 623 |
+
"""Parse Appell pages into formula entries."""
|
| 624 |
+
formulas = []
|
| 625 |
+
current_section: str | None = None
|
| 626 |
+
for record in records:
|
| 627 |
+
source = record.get("source", "")
|
| 628 |
+
if not source.startswith("Cosmetics"):
|
| 629 |
+
continue
|
| 630 |
+
page = record.get("page", 0)
|
| 631 |
+
if page_range and not (page_range[0] <= page <= page_range[1]):
|
| 632 |
+
continue
|
| 633 |
+
text = record.get("text", "")
|
| 634 |
+
# Update section from this page before parsing headers
|
| 635 |
+
for line in text.splitlines():
|
| 636 |
+
s = SECTION_RE.match(line.strip())
|
| 637 |
+
if s:
|
| 638 |
+
current_section = s.group(1)
|
| 639 |
+
headers = _detect_headers(text)
|
| 640 |
+
lines = text.splitlines()
|
| 641 |
+
|
| 642 |
+
for idx, (line_idx, header, extra) in enumerate(headers):
|
| 643 |
+
header_section = current_section
|
| 644 |
+
if header_section is None:
|
| 645 |
+
for ln in range(0, line_idx):
|
| 646 |
+
s = SECTION_RE.match(lines[ln].strip())
|
| 647 |
+
if s:
|
| 648 |
+
header_section = s.group(1)
|
| 649 |
+
end_idx = headers[idx + 1][0] if idx + 1 < len(headers) else len(lines)
|
| 650 |
+
components = []
|
| 651 |
+
for ln in range(line_idx + 1, end_idx):
|
| 652 |
+
raw_line = lines[ln].strip()
|
| 653 |
+
if not raw_line or _is_header_line(raw_line, header_section):
|
| 654 |
+
continue
|
| 655 |
+
comps = _line_to_components(raw_line)
|
| 656 |
+
if comps:
|
| 657 |
+
components.extend(comps)
|
| 658 |
+
|
| 659 |
+
total = sum(c["amount"] for c in components)
|
| 660 |
+
# Appell formulas total 1000 parts; reject obvious fragments
|
| 661 |
+
if total < 500 or total > 1500:
|
| 662 |
+
continue
|
| 663 |
+
if len(components) < 3:
|
| 664 |
+
continue
|
| 665 |
+
|
| 666 |
+
formulas.append({
|
| 667 |
+
"formula_id": f"appell_p{page:04d}_{len(formulas):04d}",
|
| 668 |
+
"name": header,
|
| 669 |
+
"source": source,
|
| 670 |
+
"page": page,
|
| 671 |
+
"extra": extra,
|
| 672 |
+
"components": components,
|
| 673 |
+
"raw_basis_sum": total,
|
| 674 |
+
})
|
| 675 |
+
|
| 676 |
+
return formulas
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def resolve_appell_formulas(raw_formulas: list[dict[str, Any]], resolver: TradeNameResolver | None = None) -> list[dict[str, Any]]:
|
| 680 |
+
"""Resolve Appell formula components to CAS using TradeNameResolver."""
|
| 681 |
+
if resolver is None:
|
| 682 |
+
resolver = TradeNameResolver()
|
| 683 |
+
|
| 684 |
+
resolved_formulas = []
|
| 685 |
+
for raw in raw_formulas:
|
| 686 |
+
components = []
|
| 687 |
+
for c in raw["components"]:
|
| 688 |
+
name = c["name"]
|
| 689 |
+
cas = resolver.resolve(name)
|
| 690 |
+
if cas:
|
| 691 |
+
components.append({"cas": cas, "amount": c["amount"], "type": "pure", "raw_name": name})
|
| 692 |
+
else:
|
| 693 |
+
components.append({"name": name, "amount": c["amount"], "type": "unknown", "raw_code": c.get("raw_code", name)})
|
| 694 |
+
|
| 695 |
+
if all(c["type"] == "unknown" for c in components):
|
| 696 |
+
continue
|
| 697 |
+
|
| 698 |
+
total = sum(c["amount"] for c in components)
|
| 699 |
+
if total <= 0:
|
| 700 |
+
continue
|
| 701 |
+
|
| 702 |
+
normalized = []
|
| 703 |
+
for c in components:
|
| 704 |
+
entry = {"amount": round(c["amount"] / total, 6)}
|
| 705 |
+
if c["type"] == "unknown":
|
| 706 |
+
entry["type"] = "sub_base"
|
| 707 |
+
entry["name"] = c["name"]
|
| 708 |
+
else:
|
| 709 |
+
entry["type"] = "pure"
|
| 710 |
+
entry["cas"] = c["cas"]
|
| 711 |
+
normalized.append(entry)
|
| 712 |
+
|
| 713 |
+
resolved_formulas.append({
|
| 714 |
+
"formula_id": raw["formula_id"],
|
| 715 |
+
"name": raw["name"],
|
| 716 |
+
"source": raw["source"],
|
| 717 |
+
"page": raw["page"],
|
| 718 |
+
"extra": raw.get("extra"),
|
| 719 |
+
"raw_basis_sum": total,
|
| 720 |
+
"components": normalized,
|
| 721 |
+
})
|
| 722 |
+
|
| 723 |
+
return resolved_formulas
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def main() -> int:
|
| 727 |
+
parser = argparse.ArgumentParser(description="Parse Appell perfume formulary")
|
| 728 |
+
parser.add_argument("--input", required=True, help="Input literature_pages.jsonl")
|
| 729 |
+
parser.add_argument("--output", required=True, help="Output JSONL of resolved formulas")
|
| 730 |
+
parser.add_argument("--raw-output", help="Optional raw parsed formulas JSONL")
|
| 731 |
+
parser.add_argument("--start-page", type=int, default=293, help="First Appell formula page")
|
| 732 |
+
parser.add_argument("--end-page", type=int, default=343, help="Last Appell formula page")
|
| 733 |
+
args = parser.parse_args()
|
| 734 |
+
|
| 735 |
+
input_path = Path(args.input)
|
| 736 |
+
output_path = Path(args.output)
|
| 737 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 738 |
+
|
| 739 |
+
records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
|
| 740 |
+
raw_formulas = parse_appell_pages(records, page_range=(args.start_page, args.end_page))
|
| 741 |
+
|
| 742 |
+
if args.raw_output:
|
| 743 |
+
raw_path = Path(args.raw_output)
|
| 744 |
+
raw_path.parent.mkdir(parents=True, exist_ok=True)
|
| 745 |
+
with raw_path.open("w", encoding="utf-8") as out:
|
| 746 |
+
for f in raw_formulas:
|
| 747 |
+
out.write(json.dumps(f, ensure_ascii=False) + "\n")
|
| 748 |
+
print(f"Wrote {len(raw_formulas)} raw Appell formulas to {raw_path}")
|
| 749 |
+
|
| 750 |
+
resolved = resolve_appell_formulas(raw_formulas)
|
| 751 |
+
|
| 752 |
+
with output_path.open("w", encoding="utf-8") as out:
|
| 753 |
+
for f in resolved:
|
| 754 |
+
out.write(json.dumps(f, ensure_ascii=False) + "\n")
|
| 755 |
+
|
| 756 |
+
print(f"Resolved {len(resolved)}/{len(raw_formulas)} Appell formulas to {output_path}")
|
| 757 |
+
return 0
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
if __name__ == "__main__":
|
| 761 |
+
raise SystemExit(main())
|
scripts/parse_appell_blocks.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
# Allow importing parse_appell as a module from the same directory
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 12 |
+
import parse_appell as appell
|
| 13 |
+
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 15 |
+
from pino.trade_name_resolver import TradeNameResolver
|
| 16 |
+
|
| 17 |
+
import fitz
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _block_sort_key(block: tuple) -> tuple[float, float]:
|
| 21 |
+
"""Sort blocks by top-y then left-x for reading order."""
|
| 22 |
+
x0, y0, _, _ = block[:4]
|
| 23 |
+
return (y0, x0)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _is_header_block(text: str) -> tuple[str, str | None] | None:
|
| 27 |
+
"""Return (header_name, extra) if the block is a formula header."""
|
| 28 |
+
text = text.strip()
|
| 29 |
+
if not text:
|
| 30 |
+
return None
|
| 31 |
+
m = appell.FRENCH_HEADER_RE.search(text)
|
| 32 |
+
if m:
|
| 33 |
+
return (m.group(1).strip(), m.group(2))
|
| 34 |
+
m = appell.FLORAL_HEADER_RE.match(text)
|
| 35 |
+
if m:
|
| 36 |
+
return (f"{m.group(1)} {m.group(2)}", None)
|
| 37 |
+
m = appell.SOAP_HEADER_RE.match(text)
|
| 38 |
+
if m:
|
| 39 |
+
return (f"{m.group(1)} S {m.group(2)}", None)
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _block_lines_to_components(block_text: str) -> list[dict[str, Any]]:
|
| 44 |
+
"""Parse all amount+code lines within a block."""
|
| 45 |
+
components = []
|
| 46 |
+
for line in block_text.splitlines():
|
| 47 |
+
line = line.strip()
|
| 48 |
+
if not line or len(line) < 3:
|
| 49 |
+
continue
|
| 50 |
+
# Skip totals, page numbers, and section headers
|
| 51 |
+
if re.match(r'^\d{1,4}$', line):
|
| 52 |
+
continue
|
| 53 |
+
if re.match(r'^T\s+1000', line, re.IGNORECASE):
|
| 54 |
+
continue
|
| 55 |
+
if "continued" in line.lower():
|
| 56 |
+
continue
|
| 57 |
+
comps = appell._line_to_components(line)
|
| 58 |
+
if comps:
|
| 59 |
+
components.extend(comps)
|
| 60 |
+
return components
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _detect_page_section(blocks: list[tuple]) -> str | None:
|
| 64 |
+
"""Find the current section heading from the page blocks."""
|
| 65 |
+
for block in blocks:
|
| 66 |
+
text = block[4].strip()
|
| 67 |
+
m = appell.SECTION_RE.match(text)
|
| 68 |
+
if m:
|
| 69 |
+
return m.group(1)
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def parse_appell_blocks(
|
| 74 |
+
pdf_path: Path,
|
| 75 |
+
page_range: tuple[int, int],
|
| 76 |
+
) -> list[dict[str, Any]]:
|
| 77 |
+
"""Parse Appell formula pages using PyMuPDF text blocks (preserves columns)."""
|
| 78 |
+
doc = fitz.open(pdf_path)
|
| 79 |
+
formulas: list[dict[str, Any]] = []
|
| 80 |
+
current_section: str | None = None
|
| 81 |
+
|
| 82 |
+
for page_idx in range(page_range[0] - 1, page_range[1]):
|
| 83 |
+
if page_idx >= len(doc):
|
| 84 |
+
continue
|
| 85 |
+
page = doc[page_idx]
|
| 86 |
+
blocks = page.get_text("blocks")
|
| 87 |
+
blocks = sorted(blocks, key=_block_sort_key)
|
| 88 |
+
page_section = _detect_page_section(blocks) or current_section
|
| 89 |
+
current_section = page_section
|
| 90 |
+
|
| 91 |
+
current_header: tuple[str, str | None] | None = None
|
| 92 |
+
current_components: list[dict[str, Any]] = []
|
| 93 |
+
|
| 94 |
+
def flush_formula() -> None:
|
| 95 |
+
if not current_header or not current_components:
|
| 96 |
+
return
|
| 97 |
+
total = sum(c["amount"] for c in current_components)
|
| 98 |
+
if total < 500 or total > 1500 or len(current_components) < 3:
|
| 99 |
+
return
|
| 100 |
+
formulas.append({
|
| 101 |
+
"formula_id": f"appell_p{page_idx + 1:04d}_{len(formulas):04d}",
|
| 102 |
+
"name": current_header[0],
|
| 103 |
+
"source": "Louis Appell - Cosmetics, Fragrances and Flavors",
|
| 104 |
+
"page": page_idx + 1,
|
| 105 |
+
"extra": current_header[1],
|
| 106 |
+
"components": current_components,
|
| 107 |
+
"raw_basis_sum": total,
|
| 108 |
+
})
|
| 109 |
+
|
| 110 |
+
for block in blocks:
|
| 111 |
+
text = block[4].strip()
|
| 112 |
+
if not text:
|
| 113 |
+
continue
|
| 114 |
+
# Update section if this block is a section heading
|
| 115 |
+
s = appell.SECTION_RE.match(text)
|
| 116 |
+
if s:
|
| 117 |
+
current_section = s.group(1)
|
| 118 |
+
continue
|
| 119 |
+
|
| 120 |
+
header = _is_header_block(text)
|
| 121 |
+
if header:
|
| 122 |
+
flush_formula()
|
| 123 |
+
current_header = header
|
| 124 |
+
current_components = []
|
| 125 |
+
continue
|
| 126 |
+
|
| 127 |
+
if current_header is None:
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
comps = _block_lines_to_components(text)
|
| 131 |
+
if comps:
|
| 132 |
+
current_components.extend(comps)
|
| 133 |
+
|
| 134 |
+
flush_formula()
|
| 135 |
+
|
| 136 |
+
doc.close()
|
| 137 |
+
return formulas
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def main() -> int:
|
| 141 |
+
parser = argparse.ArgumentParser(description="Block-aware Appell formula parser")
|
| 142 |
+
parser.add_argument("--pdf", required=True, type=Path, help="Appell PDF path")
|
| 143 |
+
parser.add_argument("--output", required=True, type=Path, help="Output resolved JSONL")
|
| 144 |
+
parser.add_argument("--raw-output", type=Path, help="Optional raw parsed JSONL")
|
| 145 |
+
parser.add_argument("--start-page", type=int, default=293, help="First formula page")
|
| 146 |
+
parser.add_argument("--end-page", type=int, default=343, help="Last formula page")
|
| 147 |
+
args = parser.parse_args()
|
| 148 |
+
|
| 149 |
+
raw_formulas = parse_appell_blocks(args.pdf, (args.start_page, args.end_page))
|
| 150 |
+
|
| 151 |
+
if args.raw_output:
|
| 152 |
+
args.raw_output.parent.mkdir(parents=True, exist_ok=True)
|
| 153 |
+
with args.raw_output.open("w", encoding="utf-8") as out:
|
| 154 |
+
for f in raw_formulas:
|
| 155 |
+
out.write(json.dumps(f, ensure_ascii=False) + "\n")
|
| 156 |
+
print(f"Wrote {len(raw_formulas)} raw block formulas to {args.raw_output}")
|
| 157 |
+
|
| 158 |
+
resolved = appell.resolve_appell_formulas(raw_formulas)
|
| 159 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 160 |
+
with args.output.open("w", encoding="utf-8") as out:
|
| 161 |
+
for f in resolved:
|
| 162 |
+
out.write(json.dumps(f, ensure_ascii=False) + "\n")
|
| 163 |
+
|
| 164 |
+
print(f"Resolved {len(resolved)}/{len(raw_formulas)} block formulas to {args.output}")
|
| 165 |
+
return 0
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
raise SystemExit(main())
|
| 170 |
+
|
scripts/sync_space.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from huggingface_hub import HfApi
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def push_training_code_to_space() -> None:
|
| 9 |
+
"""Upload the local train_hf.py to the remote pino-pimt-training Space."""
|
| 10 |
+
token = os.environ.get("HF_TOKEN")
|
| 11 |
+
api = HfApi(token=token)
|
| 12 |
+
|
| 13 |
+
print("Pushing updated train_hf.py to the cloud Space...")
|
| 14 |
+
api.upload_file(
|
| 15 |
+
path_or_fileobj="src/pino/train_hf.py",
|
| 16 |
+
path_in_repo="train_hf.py",
|
| 17 |
+
repo_id="mattbitzesty/pino-pimt-training",
|
| 18 |
+
repo_type="space",
|
| 19 |
+
)
|
| 20 |
+
print("Cloud Space synchronized successfully.")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
push_training_code_to_space()
|
scripts/verify_benchmarks.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 10 |
+
|
| 11 |
+
from pino.inference import FragranceInferenceEngine
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def run_gold_standard_validation(model_path: str, blueprint_path: str) -> dict[str, Any]:
|
| 15 |
+
"""Run hidden literature holdouts through the trained PINO pipeline."""
|
| 16 |
+
engine = FragranceInferenceEngine(model_path=model_path)
|
| 17 |
+
|
| 18 |
+
blueprint = json.loads(Path(blueprint_path).read_text())
|
| 19 |
+
holdouts = [f for f in blueprint if f.get("pipeline_role") == "holdout"]
|
| 20 |
+
|
| 21 |
+
print("====== RUNNING HUMAN LITERATURE ALIGNMENT EXAM ======")
|
| 22 |
+
results = []
|
| 23 |
+
for formula in holdouts:
|
| 24 |
+
predictions = engine.run_full_pipeline(formula["components"])
|
| 25 |
+
top_predicted_notes = predictions.get("pyramid", {}).get("top", [])
|
| 26 |
+
|
| 27 |
+
print(f"\nFormula: {formula['name']}")
|
| 28 |
+
print(f"Expected: {formula.get('expected_profile', 'N/A')} | Predicted Top: {top_predicted_notes}")
|
| 29 |
+
results.append({
|
| 30 |
+
"formula_id": formula["formula_id"],
|
| 31 |
+
"name": formula["name"],
|
| 32 |
+
"expected_profile": formula.get("expected_profile"),
|
| 33 |
+
"predicted_top": top_predicted_notes,
|
| 34 |
+
})
|
| 35 |
+
|
| 36 |
+
return {"holdouts_evaluated": len(results), "results": results}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main() -> int:
|
| 40 |
+
parser = argparse.ArgumentParser(description="Validate trained PINO against literature holdouts")
|
| 41 |
+
parser.add_argument("--model-path", default="./models/pino_cloud_weights", help="Path to trained model weights")
|
| 42 |
+
parser.add_argument("--blueprint", default="data/literature_formulas.json", help="Literature blueprint JSON")
|
| 43 |
+
parser.add_argument("--output", default="data/literature_validation_results.json", help="Output JSON path")
|
| 44 |
+
args = parser.parse_args()
|
| 45 |
+
|
| 46 |
+
summary = run_gold_standard_validation(args.model_path, args.blueprint)
|
| 47 |
+
Path(args.output).write_text(json.dumps(summary, indent=2))
|
| 48 |
+
print(f"\nWrote validation results to {args.output}")
|
| 49 |
+
return 0
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
raise SystemExit(main())
|
src/pino/dataset_builder.py
CHANGED
|
@@ -25,6 +25,7 @@ def _get_worker_generator(
|
|
| 25 |
genre: str,
|
| 26 |
rules_path: Path,
|
| 27 |
registry_path: Path,
|
|
|
|
| 28 |
base_seed: int,
|
| 29 |
) -> FormulaGenerator:
|
| 30 |
"""Return a thread-local FormulaGenerator for this genre."""
|
|
@@ -35,6 +36,7 @@ def _get_worker_generator(
|
|
| 35 |
genre=genre,
|
| 36 |
rules_path=rules_path,
|
| 37 |
registry_path=registry_path,
|
|
|
|
| 38 |
seed=base_seed + hash(genre) + thread_id,
|
| 39 |
min_k=5,
|
| 40 |
max_k=20,
|
|
@@ -63,6 +65,7 @@ class DatasetBuilder:
|
|
| 63 |
output_path: str | Path,
|
| 64 |
rules_path: str | Path,
|
| 65 |
registry_path: str | Path,
|
|
|
|
| 66 |
per_genre: int = 1000,
|
| 67 |
max_workers: int = 16,
|
| 68 |
seed: int = 2026,
|
|
@@ -71,6 +74,7 @@ class DatasetBuilder:
|
|
| 71 |
self.output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 72 |
self.rules_path = Path(rules_path)
|
| 73 |
self.registry_path = Path(registry_path)
|
|
|
|
| 74 |
self.per_genre = per_genre
|
| 75 |
self.max_workers = max_workers
|
| 76 |
self.seed = seed
|
|
@@ -83,7 +87,7 @@ class DatasetBuilder:
|
|
| 83 |
def _task(self, idx: int, genre: str) -> dict[str, Any] | None:
|
| 84 |
"""Generate and verify a single formula in a worker thread."""
|
| 85 |
generator = _get_worker_generator(
|
| 86 |
-
genre, self.rules_path, self.registry_path, self.seed
|
| 87 |
)
|
| 88 |
formula, formula_id = generator.generate(idx=idx)
|
| 89 |
|
|
@@ -103,6 +107,7 @@ class DatasetBuilder:
|
|
| 103 |
return {
|
| 104 |
"status": result.get("status"),
|
| 105 |
"formula_id": formula_id,
|
|
|
|
| 106 |
"metadata": {
|
| 107 |
"generation_strategy": genre,
|
| 108 |
"active_components_count": len(formula) - 1, # exclude solvent
|
|
@@ -233,6 +238,7 @@ if __name__ == "__main__":
|
|
| 233 |
parser.add_argument("--output", default="data/synthetic_dataset_v2.jsonl")
|
| 234 |
parser.add_argument("--rules", default="data/genre_rules.json")
|
| 235 |
parser.add_argument("--registry", default="src/pino/registry.db")
|
|
|
|
| 236 |
parser.add_argument("--per-genre", type=int, default=1000)
|
| 237 |
parser.add_argument("--workers", type=int, default=4)
|
| 238 |
parser.add_argument("--seed", type=int, default=2026)
|
|
@@ -247,6 +253,7 @@ if __name__ == "__main__":
|
|
| 247 |
output_path=args.output,
|
| 248 |
rules_path=args.rules,
|
| 249 |
registry_path=args.registry,
|
|
|
|
| 250 |
per_genre=args.per_genre,
|
| 251 |
max_workers=args.workers,
|
| 252 |
seed=args.seed,
|
|
|
|
| 25 |
genre: str,
|
| 26 |
rules_path: Path,
|
| 27 |
registry_path: Path,
|
| 28 |
+
literature_path: Path,
|
| 29 |
base_seed: int,
|
| 30 |
) -> FormulaGenerator:
|
| 31 |
"""Return a thread-local FormulaGenerator for this genre."""
|
|
|
|
| 36 |
genre=genre,
|
| 37 |
rules_path=rules_path,
|
| 38 |
registry_path=registry_path,
|
| 39 |
+
literature_path=literature_path,
|
| 40 |
seed=base_seed + hash(genre) + thread_id,
|
| 41 |
min_k=5,
|
| 42 |
max_k=20,
|
|
|
|
| 65 |
output_path: str | Path,
|
| 66 |
rules_path: str | Path,
|
| 67 |
registry_path: str | Path,
|
| 68 |
+
literature_path: str | Path,
|
| 69 |
per_genre: int = 1000,
|
| 70 |
max_workers: int = 16,
|
| 71 |
seed: int = 2026,
|
|
|
|
| 74 |
self.output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 75 |
self.rules_path = Path(rules_path)
|
| 76 |
self.registry_path = Path(registry_path)
|
| 77 |
+
self.literature_path = Path(literature_path)
|
| 78 |
self.per_genre = per_genre
|
| 79 |
self.max_workers = max_workers
|
| 80 |
self.seed = seed
|
|
|
|
| 87 |
def _task(self, idx: int, genre: str) -> dict[str, Any] | None:
|
| 88 |
"""Generate and verify a single formula in a worker thread."""
|
| 89 |
generator = _get_worker_generator(
|
| 90 |
+
genre, self.rules_path, self.registry_path, self.literature_path, self.seed
|
| 91 |
)
|
| 92 |
formula, formula_id = generator.generate(idx=idx)
|
| 93 |
|
|
|
|
| 107 |
return {
|
| 108 |
"status": result.get("status"),
|
| 109 |
"formula_id": formula_id,
|
| 110 |
+
"genre": genre,
|
| 111 |
"metadata": {
|
| 112 |
"generation_strategy": genre,
|
| 113 |
"active_components_count": len(formula) - 1, # exclude solvent
|
|
|
|
| 238 |
parser.add_argument("--output", default="data/synthetic_dataset_v2.jsonl")
|
| 239 |
parser.add_argument("--rules", default="data/genre_rules.json")
|
| 240 |
parser.add_argument("--registry", default="src/pino/registry.db")
|
| 241 |
+
parser.add_argument("--literature", default="data/literature_formulas.json")
|
| 242 |
parser.add_argument("--per-genre", type=int, default=1000)
|
| 243 |
parser.add_argument("--workers", type=int, default=4)
|
| 244 |
parser.add_argument("--seed", type=int, default=2026)
|
|
|
|
| 253 |
output_path=args.output,
|
| 254 |
rules_path=args.rules,
|
| 255 |
registry_path=args.registry,
|
| 256 |
+
literature_path=args.literature,
|
| 257 |
per_genre=args.per_genre,
|
| 258 |
max_workers=args.workers,
|
| 259 |
seed=args.seed,
|
src/pino/draft_engine.py
CHANGED
|
@@ -28,9 +28,12 @@ class FormulaGenerator:
|
|
| 28 |
genre: str,
|
| 29 |
rules_path: str | Path,
|
| 30 |
registry_path: str | Path | None = None,
|
|
|
|
| 31 |
seed: int | None = None,
|
| 32 |
min_k: int = 5,
|
| 33 |
max_k: int = 25,
|
|
|
|
|
|
|
| 34 |
) -> None:
|
| 35 |
self.genre = genre
|
| 36 |
self.rules_path = Path(rules_path)
|
|
@@ -38,6 +41,8 @@ class FormulaGenerator:
|
|
| 38 |
self.rng = random.Random(seed)
|
| 39 |
self.min_k = min_k
|
| 40 |
self.max_k = max_k
|
|
|
|
|
|
|
| 41 |
|
| 42 |
self.rules = json.loads(self.rules_path.read_text())
|
| 43 |
if genre not in self.rules["genres"] and genre != "uniform":
|
|
@@ -49,6 +54,7 @@ class FormulaGenerator:
|
|
| 49 |
self.compounds = self._load_compounds()
|
| 50 |
self.tiers = self._classify_tiers()
|
| 51 |
self.active_pool = self._build_active_pool()
|
|
|
|
| 52 |
|
| 53 |
def _load_compounds(self) -> dict[str, dict[str, Any]]:
|
| 54 |
"""Load all active aroma compounds from the registry."""
|
|
@@ -110,6 +116,47 @@ class FormulaGenerator:
|
|
| 110 |
pool.update(self.tiers.get(tier, []))
|
| 111 |
return [cas for cas in pool if self.compounds[cas]["max_weight_fraction"] > 0.0]
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
def _genre_formula_id(self, idx: int) -> str:
|
| 114 |
prefix = self.genre[:4].lower()
|
| 115 |
return f"gen_{prefix}_{idx:04d}"
|
|
@@ -125,6 +172,22 @@ class FormulaGenerator:
|
|
| 125 |
solvent_max = self.rules.get("solvent_max", 0.95)
|
| 126 |
|
| 127 |
for _ in range(100):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
if self.genre == "uniform" or self.genre_rules.get("uniform"):
|
| 129 |
k = self.rng.randint(self.min_k, min(self.max_k, len(self.active_pool)))
|
| 130 |
selected = self.rng.sample(self.active_pool, k)
|
|
@@ -156,6 +219,19 @@ class FormulaGenerator:
|
|
| 156 |
formula.append({"cas": cas, "weight_fraction": w})
|
| 157 |
return formula
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
def _select_with_tier_constraints(self) -> list[str]:
|
| 160 |
"""Pick aroma compounds that can physically satisfy the genre tier-mass rules."""
|
| 161 |
default_max = self.rules["default_max_weight"]
|
|
|
|
| 28 |
genre: str,
|
| 29 |
rules_path: str | Path,
|
| 30 |
registry_path: str | Path | None = None,
|
| 31 |
+
literature_path: str | Path | None = None,
|
| 32 |
seed: int | None = None,
|
| 33 |
min_k: int = 5,
|
| 34 |
max_k: int = 25,
|
| 35 |
+
seed_prob: float = 0.30,
|
| 36 |
+
seed_perturbation: float = 0.05,
|
| 37 |
) -> None:
|
| 38 |
self.genre = genre
|
| 39 |
self.rules_path = Path(rules_path)
|
|
|
|
| 41 |
self.rng = random.Random(seed)
|
| 42 |
self.min_k = min_k
|
| 43 |
self.max_k = max_k
|
| 44 |
+
self.seed_prob = seed_prob
|
| 45 |
+
self.seed_perturbation = seed_perturbation
|
| 46 |
|
| 47 |
self.rules = json.loads(self.rules_path.read_text())
|
| 48 |
if genre not in self.rules["genres"] and genre != "uniform":
|
|
|
|
| 54 |
self.compounds = self._load_compounds()
|
| 55 |
self.tiers = self._classify_tiers()
|
| 56 |
self.active_pool = self._build_active_pool()
|
| 57 |
+
self.seeds = self._load_literature_seeds(literature_path)
|
| 58 |
|
| 59 |
def _load_compounds(self) -> dict[str, dict[str, Any]]:
|
| 60 |
"""Load all active aroma compounds from the registry."""
|
|
|
|
| 116 |
pool.update(self.tiers.get(tier, []))
|
| 117 |
return [cas for cas in pool if self.compounds[cas]["max_weight_fraction"] > 0.0]
|
| 118 |
|
| 119 |
+
def _load_literature_seeds(self, literature_path: str | Path | None) -> list[dict[str, Any]]:
|
| 120 |
+
"""Load literature formulas that are marked as seeds for this genre."""
|
| 121 |
+
if literature_path is None:
|
| 122 |
+
return []
|
| 123 |
+
path = Path(literature_path)
|
| 124 |
+
if not path.exists():
|
| 125 |
+
logger.warning("Literature blueprint not found: %s", path)
|
| 126 |
+
return []
|
| 127 |
+
try:
|
| 128 |
+
formulas = json.loads(path.read_text())
|
| 129 |
+
except Exception as exc:
|
| 130 |
+
logger.warning("Failed to parse literature blueprint: %s", exc)
|
| 131 |
+
return []
|
| 132 |
+
seeds = []
|
| 133 |
+
for f in formulas:
|
| 134 |
+
if f.get("pipeline_role") != "seed":
|
| 135 |
+
continue
|
| 136 |
+
if f.get("expected_profile") != self.genre:
|
| 137 |
+
continue
|
| 138 |
+
components = [c for c in f.get("components", []) if c.get("cas") and c.get("weight_fraction") is not None]
|
| 139 |
+
if not components:
|
| 140 |
+
continue
|
| 141 |
+
# Validate every CAS is present in the registry and pool.
|
| 142 |
+
if any(c["cas"] not in self.compounds for c in components):
|
| 143 |
+
continue
|
| 144 |
+
seeds.append({"formula_id": f.get("formula_id"), "name": f.get("name"), "components": components})
|
| 145 |
+
if seeds:
|
| 146 |
+
logger.info("Loaded %d literature seeds for genre %s", len(seeds), self.genre)
|
| 147 |
+
return seeds
|
| 148 |
+
|
| 149 |
+
def _perturb_seed(self, seed_components: list[dict[str, Any]]) -> dict[str, float]:
|
| 150 |
+
"""Apply Gaussian noise to seed weights, clip, and renormalize to a unit simplex."""
|
| 151 |
+
weights: dict[str, float] = {}
|
| 152 |
+
for c in seed_components:
|
| 153 |
+
noise = self.rng.gauss(0, self.seed_perturbation)
|
| 154 |
+
weights[c["cas"]] = max(0.0, c["weight_fraction"] + noise)
|
| 155 |
+
total = sum(weights.values())
|
| 156 |
+
if total <= 0.0:
|
| 157 |
+
return weights
|
| 158 |
+
return {cas: w / total for cas, w in weights.items()}
|
| 159 |
+
|
| 160 |
def _genre_formula_id(self, idx: int) -> str:
|
| 161 |
prefix = self.genre[:4].lower()
|
| 162 |
return f"gen_{prefix}_{idx:04d}"
|
|
|
|
| 172 |
solvent_max = self.rules.get("solvent_max", 0.95)
|
| 173 |
|
| 174 |
for _ in range(100):
|
| 175 |
+
# Literature-seed path: with seed_prob, perturb a seed formula for this genre.
|
| 176 |
+
if self.seeds and self.rng.random() < self.seed_prob:
|
| 177 |
+
seed = self.rng.choice(self.seeds)
|
| 178 |
+
weights = self._perturb_seed(seed["components"])
|
| 179 |
+
if weights:
|
| 180 |
+
# Ensure weights respect compound-specific maxima and IFRA limits.
|
| 181 |
+
weights = self._clip_weights_to_limits(weights)
|
| 182 |
+
target_aroma = self.rng.uniform(1.0 - solvent_max, 1.0 - solvent_min)
|
| 183 |
+
scaled = self._project_weights(weights, target_aroma)
|
| 184 |
+
solvent_share = 1.0 - sum(scaled.values())
|
| 185 |
+
formula = [{"cas": self.solvent_cas, "weight_fraction": solvent_share}]
|
| 186 |
+
for cas, w in scaled.items():
|
| 187 |
+
if w > 0:
|
| 188 |
+
formula.append({"cas": cas, "weight_fraction": w})
|
| 189 |
+
return formula
|
| 190 |
+
|
| 191 |
if self.genre == "uniform" or self.genre_rules.get("uniform"):
|
| 192 |
k = self.rng.randint(self.min_k, min(self.max_k, len(self.active_pool)))
|
| 193 |
selected = self.rng.sample(self.active_pool, k)
|
|
|
|
| 219 |
formula.append({"cas": cas, "weight_fraction": w})
|
| 220 |
return formula
|
| 221 |
|
| 222 |
+
def _clip_weights_to_limits(self, weights: dict[str, float]) -> dict[str, float]:
|
| 223 |
+
"""Clip each weight to [min_weight_fraction, max_weight_fraction] and renormalize."""
|
| 224 |
+
clipped: dict[str, float] = {}
|
| 225 |
+
for cas, w in weights.items():
|
| 226 |
+
meta = self.compounds.get(cas, {})
|
| 227 |
+
min_w = float(meta.get("min_weight_fraction", 0.001))
|
| 228 |
+
max_w = float(meta.get("max_weight_fraction", 1.0))
|
| 229 |
+
clipped[cas] = max(min_w, min(w, max_w))
|
| 230 |
+
total = sum(clipped.values())
|
| 231 |
+
if total <= 0.0:
|
| 232 |
+
return clipped
|
| 233 |
+
return {cas: w / total for cas, w in clipped.items()}
|
| 234 |
+
|
| 235 |
def _select_with_tier_constraints(self) -> list[str]:
|
| 236 |
"""Pick aroma compounds that can physically satisfy the genre tier-mass rules."""
|
| 237 |
default_max = self.rules["default_max_weight"]
|
src/pino/inference.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FragranceInferenceEngine:
|
| 8 |
+
"""
|
| 9 |
+
Stub inference engine for the PINO fragrance pipeline.
|
| 10 |
+
|
| 11 |
+
Loads a model path placeholder and returns a fixed prediction schema that
|
| 12 |
+
matches the contract expected by `scripts/verify_benchmarks.py`. Once the
|
| 13 |
+
cloud model is trained, this stub will be replaced by the real weight load
|
| 14 |
+
and forward pass.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, model_path: str) -> None:
|
| 18 |
+
self.model_path = model_path
|
| 19 |
+
print(f"Initializing FragranceInferenceEngine with weights from: {model_path}")
|
| 20 |
+
|
| 21 |
+
def run_full_pipeline(self, components: list) -> dict:
|
| 22 |
+
"""
|
| 23 |
+
Stub executing the exact evaluation contract. Accepts ingredient lists,
|
| 24 |
+
mocks VLE + Transformer forward passes, and returns formatted arrays.
|
| 25 |
+
"""
|
| 26 |
+
return {
|
| 27 |
+
"pyramid": {
|
| 28 |
+
"top": ["Citrus", "Fresh", "Bergamot"],
|
| 29 |
+
"heart": ["Floral", "Rose"],
|
| 30 |
+
"base": ["Woody", "Musk"],
|
| 31 |
+
},
|
| 32 |
+
"raw_predictions": {
|
| 33 |
+
"subjective_logits": [0.85, 0.12, 0.05, 0.01, 0.01, 0.01, 0.01],
|
| 34 |
+
"objective_trajectory_shape": [1, 49, 138],
|
| 35 |
+
},
|
| 36 |
+
"review_text": "Mocked validation profile: High volatile top-note distribution detected.",
|
| 37 |
+
}
|
src/pino/pimt_model.py
CHANGED
|
@@ -28,38 +28,48 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 28 |
|
| 29 |
def __init__(
|
| 30 |
self,
|
| 31 |
-
data_path: str | Path = DEFAULT_DATASET,
|
|
|
|
| 32 |
max_ingredients: int = 32,
|
| 33 |
embedding_dim: int = 138,
|
| 34 |
state_dim: int = 4,
|
| 35 |
use_embedding_fallback: bool = True,
|
| 36 |
label_noise: bool = True,
|
| 37 |
) -> None:
|
| 38 |
-
self.data_path = Path(data_path)
|
|
|
|
| 39 |
self.max_ingredients = max_ingredients
|
| 40 |
self.embedding_dim = embedding_dim
|
| 41 |
self.state_dim = state_dim
|
| 42 |
self.embedding_engine = OlfactoryEmbeddingEngine(use_fallback=use_embedding_fallback)
|
| 43 |
self.label_noise = label_noise
|
| 44 |
self._index_offsets: list[int] = []
|
| 45 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
def _build_index(self) -> None:
|
| 48 |
"""Build a byte-offset index so the dataset can be randomly accessed."""
|
| 49 |
offset = 0
|
| 50 |
-
with self.data_path.open("r") as f:
|
| 51 |
for line in f:
|
| 52 |
self._index_offsets.append(offset)
|
| 53 |
offset += len(line.encode("utf-8"))
|
| 54 |
logger.info("Indexed %d trajectory records from %s", len(self._index_offsets), self.data_path)
|
| 55 |
|
| 56 |
def __len__(self) -> int:
|
| 57 |
-
return len(self._index_offsets)
|
| 58 |
|
| 59 |
def __getitem__(self, idx: int) -> dict[str, Any]:
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
if "formula" not in record or "trajectory" not in record:
|
| 65 |
raise IndexError(f"Record {idx} is not a formulation sample")
|
|
@@ -186,24 +196,38 @@ class PhysicsInformedMixtureTransformer(torch.nn.Module):
|
|
| 186 |
)
|
| 187 |
self.encoder = torch.nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
|
| 188 |
|
| 189 |
-
def forward(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
"""
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
|
|
|
|
|
|
| 195 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
gated = self.gating(tokens, states) # (B, T, S, E)
|
| 197 |
-
b, t, s,
|
| 198 |
x = self.input_proj(gated) # (B, T, S, H)
|
| 199 |
-
|
| 200 |
-
# Transformer expects (B, S, H); process each timestep independently.
|
| 201 |
x = x.reshape(b * t, s, self.hidden_dim)
|
| 202 |
-
|
| 203 |
-
# src_key_padding_mask is (B, S); repeat for each timestep so shape is (B*T, S).
|
| 204 |
-
mask_bt = src_key_padding_mask.unsqueeze(1).expand(-1, t, -1).reshape(b * t, s)
|
| 205 |
-
x = self.encoder(x, src_key_padding_mask=mask_bt)
|
| 206 |
-
else:
|
| 207 |
-
x = self.encoder(x)
|
| 208 |
x = x.reshape(b, t, s, self.hidden_dim)
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def __init__(
|
| 30 |
self,
|
| 31 |
+
data_path: str | Path | None = DEFAULT_DATASET,
|
| 32 |
+
records: list[dict[str, Any]] | None = None,
|
| 33 |
max_ingredients: int = 32,
|
| 34 |
embedding_dim: int = 138,
|
| 35 |
state_dim: int = 4,
|
| 36 |
use_embedding_fallback: bool = True,
|
| 37 |
label_noise: bool = True,
|
| 38 |
) -> None:
|
| 39 |
+
self.data_path = Path(data_path) if data_path else None
|
| 40 |
+
self.records = records
|
| 41 |
self.max_ingredients = max_ingredients
|
| 42 |
self.embedding_dim = embedding_dim
|
| 43 |
self.state_dim = state_dim
|
| 44 |
self.embedding_engine = OlfactoryEmbeddingEngine(use_fallback=use_embedding_fallback)
|
| 45 |
self.label_noise = label_noise
|
| 46 |
self._index_offsets: list[int] = []
|
| 47 |
+
if self.records is None:
|
| 48 |
+
if self.data_path is None:
|
| 49 |
+
raise ValueError("Either data_path or records must be provided")
|
| 50 |
+
self._build_index()
|
| 51 |
+
else:
|
| 52 |
+
logger.info("Using %d in-memory trajectory records", len(self.records))
|
| 53 |
|
| 54 |
def _build_index(self) -> None:
|
| 55 |
"""Build a byte-offset index so the dataset can be randomly accessed."""
|
| 56 |
offset = 0
|
| 57 |
+
with self.data_path.open("r") as f: # type: ignore[union-att]
|
| 58 |
for line in f:
|
| 59 |
self._index_offsets.append(offset)
|
| 60 |
offset += len(line.encode("utf-8"))
|
| 61 |
logger.info("Indexed %d trajectory records from %s", len(self._index_offsets), self.data_path)
|
| 62 |
|
| 63 |
def __len__(self) -> int:
|
| 64 |
+
return len(self._index_offsets) if self.records is None else len(self.records)
|
| 65 |
|
| 66 |
def __getitem__(self, idx: int) -> dict[str, Any]:
|
| 67 |
+
if self.records is not None:
|
| 68 |
+
record = self.records[idx]
|
| 69 |
+
else:
|
| 70 |
+
with self.data_path.open("r") as f: # type: ignore[union-att]
|
| 71 |
+
f.seek(self._index_offsets[idx])
|
| 72 |
+
record = json.loads(f.readline())
|
| 73 |
|
| 74 |
if "formula" not in record or "trajectory" not in record:
|
| 75 |
raise IndexError(f"Record {idx} is not a formulation sample")
|
|
|
|
| 196 |
)
|
| 197 |
self.encoder = torch.nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
|
| 198 |
|
| 199 |
+
def forward(
|
| 200 |
+
self,
|
| 201 |
+
input_vectors: torch.Tensor,
|
| 202 |
+
labels: torch.Tensor | None = None,
|
| 203 |
+
) -> dict[str, torch.Tensor]:
|
| 204 |
"""
|
| 205 |
+
HF-compatible forward: accept a fused input and optional labels.
|
| 206 |
+
|
| 207 |
+
input_vectors: (B, T, S, E+state_dim) concatenated token + physics tensor
|
| 208 |
+
labels: optional (B, T, E) objective targets or (B, 7) subjective targets
|
| 209 |
+
Returns: {"loss": total_loss, "logits": logits} when labels provided,
|
| 210 |
+
otherwise {"logits": logits}
|
| 211 |
"""
|
| 212 |
+
e = self.embedding_dim
|
| 213 |
+
tokens = input_vectors[..., :e]
|
| 214 |
+
states = input_vectors[..., e:]
|
| 215 |
+
|
| 216 |
gated = self.gating(tokens, states) # (B, T, S, E)
|
| 217 |
+
b, t, s, _ = gated.shape
|
| 218 |
x = self.input_proj(gated) # (B, T, S, H)
|
|
|
|
|
|
|
| 219 |
x = x.reshape(b * t, s, self.hidden_dim)
|
| 220 |
+
x = self.encoder(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
x = x.reshape(b, t, s, self.hidden_dim)
|
| 222 |
+
|
| 223 |
+
# Mean pool over tokens for a simple pooled representation.
|
| 224 |
+
pooled = x.mean(dim=2) # (B, T, H)
|
| 225 |
+
|
| 226 |
+
logits = torch.nn.functional.linear(pooled, torch.randn(138, self.hidden_dim)) # placeholder objective head
|
| 227 |
+
logits = logits[:, :1, :].expand(-1, t, -1) # (B, T, 138)
|
| 228 |
+
|
| 229 |
+
if labels is not None:
|
| 230 |
+
loss = torch.nn.functional.mse_loss(logits, labels)
|
| 231 |
+
return {"loss": loss, "logits": logits}
|
| 232 |
+
|
| 233 |
+
return {"logits": logits}
|
src/pino/train_hf.py
CHANGED
|
@@ -6,6 +6,7 @@ from pathlib import Path
|
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
import torch
|
|
|
|
| 9 |
from huggingface_hub import hf_hub_download
|
| 10 |
from transformers import Trainer, TrainingArguments
|
| 11 |
|
|
@@ -58,27 +59,14 @@ def main() -> None:
|
|
| 58 |
np.random.seed(seed)
|
| 59 |
random.seed(seed)
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
dataset = FragranceTrajectoryDataset(
|
| 71 |
-
data_path=dataset_path,
|
| 72 |
-
use_embedding_fallback=True,
|
| 73 |
-
)
|
| 74 |
-
total = len(dataset)
|
| 75 |
-
train_len = int(0.8 * total)
|
| 76 |
-
val_len = int(0.1 * total)
|
| 77 |
-
test_len = total - train_len - val_len
|
| 78 |
-
train_ds, val_ds, _ = torch.utils.data.random_split(
|
| 79 |
-
dataset, [train_len, val_len, test_len],
|
| 80 |
-
generator=torch.Generator().manual_seed(seed),
|
| 81 |
-
)
|
| 82 |
|
| 83 |
config = PIMTConfig(
|
| 84 |
embedding_dim=138,
|
|
@@ -92,13 +80,14 @@ def main() -> None:
|
|
| 92 |
model = PhysicsInformedMixtureTransformer(config)
|
| 93 |
|
| 94 |
training_args = TrainingArguments(
|
| 95 |
-
output_dir="./models/
|
|
|
|
| 96 |
do_train=True,
|
| 97 |
do_eval=True,
|
| 98 |
-
|
| 99 |
num_train_epochs=5,
|
| 100 |
-
per_device_train_batch_size=
|
| 101 |
-
per_device_eval_batch_size=
|
| 102 |
fp16=True,
|
| 103 |
gradient_accumulation_steps=4,
|
| 104 |
dataloader_num_workers=2,
|
|
@@ -112,6 +101,9 @@ def main() -> None:
|
|
| 112 |
disable_tqdm=False,
|
| 113 |
seed=seed,
|
| 114 |
remove_unused_columns=False,
|
|
|
|
|
|
|
|
|
|
| 115 |
)
|
| 116 |
|
| 117 |
trainer = Trainer(
|
|
|
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
import torch
|
| 9 |
+
from datasets import load_dataset
|
| 10 |
from huggingface_hub import hf_hub_download
|
| 11 |
from transformers import Trainer, TrainingArguments
|
| 12 |
|
|
|
|
| 59 |
np.random.seed(seed)
|
| 60 |
random.seed(seed)
|
| 61 |
|
| 62 |
+
# Load the verified stratified partitions from the Hugging Face Hub.
|
| 63 |
+
logger.info("Loading PINO synthetic dataset from Hugging Face Hub")
|
| 64 |
+
hub_dataset = load_dataset("mattbitzesty/pino-synthetic-dataset")
|
| 65 |
+
train_records = list(hub_dataset["train"])
|
| 66 |
+
val_records = list(hub_dataset["validation"])
|
| 67 |
+
|
| 68 |
+
train_ds = FragranceTrajectoryDataset(records=train_records, use_embedding_fallback=True)
|
| 69 |
+
val_ds = FragranceTrajectoryDataset(records=val_records, use_embedding_fallback=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
config = PIMTConfig(
|
| 72 |
embedding_dim=138,
|
|
|
|
| 80 |
model = PhysicsInformedMixtureTransformer(config)
|
| 81 |
|
| 82 |
training_args = TrainingArguments(
|
| 83 |
+
output_dir="./models/pino_cloud_weights",
|
| 84 |
+
overwrite_output_dir=True,
|
| 85 |
do_train=True,
|
| 86 |
do_eval=True,
|
| 87 |
+
evaluation_strategy="epoch",
|
| 88 |
num_train_epochs=5,
|
| 89 |
+
per_device_train_batch_size=32,
|
| 90 |
+
per_device_eval_batch_size=32,
|
| 91 |
fp16=True,
|
| 92 |
gradient_accumulation_steps=4,
|
| 93 |
dataloader_num_workers=2,
|
|
|
|
| 101 |
disable_tqdm=False,
|
| 102 |
seed=seed,
|
| 103 |
remove_unused_columns=False,
|
| 104 |
+
push_to_hub=True,
|
| 105 |
+
hub_model_id="mattbitzesty/pino-pimt",
|
| 106 |
+
hub_strategy="end",
|
| 107 |
)
|
| 108 |
|
| 109 |
trainer = Trainer(
|
src/pino/upload_data.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from datasets import DatasetDict, load_dataset
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def split_and_upload_dataset(jsonl_path: str, repo_id: str) -> None:
|
| 9 |
+
"""
|
| 10 |
+
Load a production JSONL corpus, perform a deterministic 80/20 stratified
|
| 11 |
+
train/validation split by the 'genre' column, and push the resulting
|
| 12 |
+
DatasetDict to the Hugging Face Hub.
|
| 13 |
+
"""
|
| 14 |
+
print(f"Loading raw production corpus from {jsonl_path}...")
|
| 15 |
+
raw_dataset = load_dataset("json", data_files=jsonl_path, split="train")
|
| 16 |
+
|
| 17 |
+
print("Executing stratified 80/20 train/validation split...")
|
| 18 |
+
split_data = raw_dataset.train_test_split(
|
| 19 |
+
test_size=0.2,
|
| 20 |
+
stratify_by_column="genre",
|
| 21 |
+
seed=42,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
dataset_dict = DatasetDict({
|
| 25 |
+
"train": split_data["train"],
|
| 26 |
+
"validation": split_data["test"],
|
| 27 |
+
})
|
| 28 |
+
|
| 29 |
+
print(f"Train rows: {len(dataset_dict['train'])} | Validation rows: {len(dataset_dict['validation'])}")
|
| 30 |
+
|
| 31 |
+
token = os.environ.get("HF_TOKEN")
|
| 32 |
+
print(f"Uploading unified DatasetDict to HF Hub: {repo_id}...")
|
| 33 |
+
dataset_dict.push_to_hub(repo_id, private=True, token=token)
|
| 34 |
+
print("Dataset sync complete. Training partitions are fully live.")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if __name__ == "__main__":
|
| 38 |
+
split_and_upload_dataset(
|
| 39 |
+
jsonl_path="data/synthetic_dataset_v2.jsonl",
|
| 40 |
+
repo_id="mattbitzesty/pino-synthetic-dataset",
|
| 41 |
+
)
|