mattbitzesty commited on
Commit
08d0ad8
·
unverified ·
1 Parent(s): 45cf13b

feat(semantics): add literature-based odor descriptor vocabulary builder

Browse files
Files changed (1) hide show
  1. src/pino/odor_descriptors.py +208 -0
src/pino/odor_descriptors.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ import re
6
+ from collections import Counter
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ logger = logging.getLogger("pino.odor_descriptors")
11
+
12
+ # Target vocabulary size to align with PIMT output dimension.
13
+ VOCAB_SIZE = 138
14
+
15
+ # Chemical / functional-group terms that are structure, not smell.
16
+ CHEMICAL_TOKENS = {
17
+ "methyl", "ethyl", "propyl", "isopropyl", "butyl", "isobutyl", "amyl", "isoamyl",
18
+ "phenyl", "benzyl", "phenethyl", "cinnamyl", "salicyl", "anisyl", "veratryl",
19
+ "aldehyde", "aldehydic", "ketone", "ester", "acetate", "formate", "propionate",
20
+ "butyrate", "isobutyrate", "valerate", "isovalerate", "benzoate", "salicylate",
21
+ "cinnamate", "anthranilate", "alcohol", "carbinol", "carbinyl", "phenol", "oxide",
22
+ "lactone", "ether", "anhydride", "acid", "acetic", "formic", "benzoic", "cinnamic",
23
+ "hydroxy", "methoxy", "dimethoxy", "trimethyl", "tert", "para", "meta", "ortho",
24
+ "alpha", "beta", "gamma", "delta", "omega", "cis", "trans", "neo", "iso", "sec",
25
+ "di", "tri", "tetra", "mono", "bis", "terpenic", "terpene", "sesquiterpene",
26
+ "hydrocarbon", "aromatic", "aliphatic", "cyclic", "acyclic", "saturated", "unsaturated",
27
+ "molecule", "molecular", "compound", "compounds", "constituents", "composition",
28
+ "solution", "solvent", "concentration", "dilution", "percent", "percentage", "parts",
29
+ "contains", "containing", "component", "components", "mixture", "mixtures", "preparation",
30
+ "synthetic", "nature", "identical", "chemical", "chemically", "organic", "volatile",
31
+ "vapor", "steam", "distillation", "extracted", "extraction", "isolated", "isolation",
32
+ "derivatives", "derivative", "homologue", "homolog", "analogue", "analog",
33
+ }
34
+
35
+ # Prose / grammar terms that carry no scent meaning.
36
+ STOPWORDS = {
37
+ "the", "and", "with", "without", "slightly", "very", "more", "less", "somewhat",
38
+ "moderately", "highly", "extremely", "quite", "rather", "freshly", "freshness",
39
+ "dry", "dried", "powdery", "note", "notes", "odor", "odour", "smell", "smells",
40
+ "scent", "fragrance", "aroma", "character", "like", "type", "hint", "touch",
41
+ "suggestion", "reminiscent", "of", "in", "on", "at", "by", "to", "from", "a", "an",
42
+ "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "do",
43
+ "does", "did", "will", "would", "could", "should", "may", "might", "can", "shall",
44
+ "it", "its", "this", "that", "these", "those", "such", "also", "but", "or", "as",
45
+ "so", "than", "too", "much", "many", "most", "some", "any", "all", "no", "not",
46
+ "only", "just", "even", "still", "yet", "however", "therefore", "thus", "hence",
47
+ "moreover", "furthermore", "nevertheless", "otherwise", "meanwhile", "whereas",
48
+ "although", "though", "while", "because", "since", "until", "unless", "whether",
49
+ "either", "neither", "both", "each", "every", "one", "two", "three", "first",
50
+ "second", "third", "last", "next", "other", "another", "same", "different",
51
+ "similar", "various", "several", "certain", "particular", "specific", "general",
52
+ "overall", "main", "major", "minor", "key", "important", "pronounced", "distinct",
53
+ "definite", "clear", "vague", "faint", "subtle", "delicate", "refined", "crude",
54
+ "raw", "processed", "manufactured", "genuine", "authentic", "real", "true", "false",
55
+ "apparent", "seeming", "usually", "often", "sometimes", "frequently", "rarely",
56
+ "occasionally", "generally", "commonly", "mostly", "partly", "almost", "nearly",
57
+ "approximately", "about", "around", "extremely", "intensely", "strongly", "weakly",
58
+ "highly", "slightly", "very", "too", "so", "such", "rather", "quite", "fairly",
59
+ "pretty", "really", "truly", "actually", "certainly", "probably", "possibly",
60
+ "perhaps", "maybe", "apparently", "seemingly", "evidently", "obviously", "clearly",
61
+ "undoubtedly", "definitely", "absolutely", "relatively", "comparatively", "exceptionally",
62
+ "unusually", "remarkably", "particularly", "especially", "notably", "significantly",
63
+ "considerably", "substantially", "markedly", "noticeably", "distinctly", "sharply",
64
+ "strong", "weak", "powerful", "intense", "mild", "soft", "hard", "sharp", "round",
65
+ "rich", "poor", "full", "light", "heavy", "deep", "high", "low", "fine", "coarse",
66
+ "pure", "impure", "clean", "dirty", "clear", "opaque", "transparent", "cloudy",
67
+ "warm", "cool", "cold", "hot", "tenacious", "fugitive", "volatile", "evanescent",
68
+ "lasting", "lingering", "fading", "receding", "emerging", "developing", "mellowing",
69
+ "ageing", "young", "old", "new", "novel", "normal", "abnormal", "natural", "artificial",
70
+ "which", "following", "follows", "where", "when", "what", "who", "how", "why", "there",
71
+ "here", "then", "now", "again", "once", "twice", "upon", "into", "onto", "up", "down",
72
+ "out", "over", "under", "off", "through", "between", "among", "within", "without",
73
+ "above", "below", "before", "after", "behind", "beyond", "across", "against", "along",
74
+ "around", "beside", "besides", "beyond", "despite", "during", "except", "inside",
75
+ "outside", "toward", "towards", "underneath", "until", "via", "worth", "per",
76
+ }
77
+
78
+
79
+ def _tokenize(text: str) -> list[str]:
80
+ """Extract normalized word tokens from a raw description."""
81
+ text = text.lower()
82
+ # Keep hyphens as word separators, keep letters and numbers.
83
+ tokens = re.findall(r"[a-z0-9]+", text.replace("-", " "))
84
+ return [
85
+ t for t in tokens
86
+ if t and t not in STOPWORDS and t not in CHEMICAL_TOKENS and len(t) > 2
87
+ ]
88
+
89
+
90
+ def _extract_poucher_descriptors(records: list[dict[str, Any]]) -> Counter[str]:
91
+ """Collect descriptors from Poucher structured profiles."""
92
+ counts = Counter[str]()
93
+ for rec in records:
94
+ for key in ("top", "middle", "base"):
95
+ for item in rec.get(key, []):
96
+ # Each item is a raw material like "bergamot oil" or "linalool".
97
+ # Extract simple descriptors (skip "oil", "absolute", etc.).
98
+ for token in _tokenize(item):
99
+ if token in {"oil", "absolute", "resinoid", "concrete", "extract", "otto", "essence"}:
100
+ continue
101
+ counts[token] += 2 # Poucher descriptors are structured; weight higher.
102
+ return counts
103
+
104
+
105
+ def _extract_arctander_descriptors(records: list[dict[str, Any]]) -> Counter[str]:
106
+ """Collect descriptors from Arctander free-text monographs."""
107
+ counts = Counter[str]()
108
+ for rec in records:
109
+ text = rec.get("odor_description") or ""
110
+ if not text:
111
+ continue
112
+ for token in _tokenize(text):
113
+ counts[token] += 1
114
+ return counts
115
+
116
+
117
+ def build_descriptor_vocab(
118
+ poucher_path: str | Path | None,
119
+ arctander_path: str | Path | None,
120
+ vocab_size: int = VOCAB_SIZE,
121
+ extra_terms: list[str] | None = None,
122
+ ) -> list[str]:
123
+ """Build a canonical descriptor vocabulary from available literature sources."""
124
+ counts = Counter[str]()
125
+
126
+ if poucher_path and Path(poucher_path).exists():
127
+ records = [
128
+ json.loads(line) for line in Path(poucher_path).read_text().strip().splitlines()
129
+ ]
130
+ counts.update(_extract_poucher_descriptors(records))
131
+
132
+ if arctander_path and Path(arctander_path).exists():
133
+ records = [
134
+ json.loads(line) for line in Path(arctander_path).read_text().strip().splitlines()
135
+ ]
136
+ counts.update(_extract_arctander_descriptors(records))
137
+
138
+ if extra_terms:
139
+ for term in extra_terms:
140
+ counts[term.lower()] += 3
141
+
142
+ # Drop numeric-only tokens and overly rare terms.
143
+ filtered = {
144
+ term: c
145
+ for term, c in counts.items()
146
+ if not term.isdigit() and c >= 2 and len(term) > 2
147
+ }
148
+
149
+ # Take the most frequent descriptors up to vocab_size.
150
+ most_common = Counter(filtered).most_common(vocab_size)
151
+ vocab = [term for term, _ in most_common]
152
+
153
+ # Pad with generic descriptors if needed, so the model dimension stays fixed.
154
+ pad_descriptors = [
155
+ "citrus", "lemon", "bergamot", "orange", "lime", "grapefruit", "mandarin",
156
+ "floral", "rose", "jasmine", "lily", "ylang", "neroli", "orange blossom",
157
+ "tubereuse", "gardenia", "violet", "iris", "mimosa", "acacia", "hawthorn",
158
+ "woody", "sandalwood", "cedar", "vetiver", "patchouli", "oakmoss", "pine",
159
+ "musk", "amber", "vanilla", "benzoin", "tolu", "labdanum", "styrax",
160
+ "spicy", "cinnamon", "clove", "nutmeg", "pepper", "ginger", "cardamom",
161
+ "herbal", "lavender", "sage", "rosemary", "thyme", "basil", "mint",
162
+ "green", "leafy", "grassy", "galbanum", "tomato leaf", "fig",
163
+ "fruity", "apple", "pear", "peach", "plum", "berry", "tropical", "coconut",
164
+ "aldehydic", "powdery", "mossy", "earthy", "rooty", "leathery", "tobacco",
165
+ "honey", "sweet", "balsamic", "resinous", "incense", "smoky", "burnt",
166
+ "marine", "aquatic", "ozonic", "iodine", "seaweed",
167
+ "animalic", "civet", "castoreum", "musk tonkin", "ambergris",
168
+ "metallic", "camphoraceous", "eucalyptus", "menthol", "medicinal",
169
+ "fatty", "waxy", "lactonic", "coconut", "creamy", "milky",
170
+ "dry", "pungent", "sour", "sulfurous", "rubbery", "plastic",
171
+ "winey", "brandy", "rum", "boozy", "fermented", "yeasty",
172
+ "chocolate", "coffee", "cocoa", "vanilla", "caramel", "toffee",
173
+ "nutty", "almond", "hazelnut", "peanut", "walnut",
174
+ "coconut", "tropical", "pineapple", "banana", "mango", "papaya",
175
+ ]
176
+ for d in pad_descriptors:
177
+ if d not in vocab:
178
+ vocab.append(d)
179
+ if len(vocab) >= vocab_size:
180
+ break
181
+
182
+ return vocab[:vocab_size]
183
+
184
+
185
+ def save_vocab(vocab: list[str], path: str | Path) -> None:
186
+ """Persist the vocabulary as a JSON list."""
187
+ Path(path).write_text(json.dumps(vocab, indent=2, ensure_ascii=False))
188
+
189
+
190
+ def load_vocab(path: str | Path) -> list[str]:
191
+ """Load a previously saved vocabulary."""
192
+ return json.loads(Path(path).read_text())
193
+
194
+
195
+ if __name__ == "__main__":
196
+ import argparse
197
+
198
+ parser = argparse.ArgumentParser(description="Build PINO descriptor vocabulary")
199
+ parser.add_argument("--poucher", default="data/literature_profiles_poucher.jsonl")
200
+ parser.add_argument("--arctander", default="data/arctander_monographs.jsonl")
201
+ parser.add_argument("--output", default="data/odor_descriptor_vocab.json")
202
+ parser.add_argument("--vocab-size", type=int, default=VOCAB_SIZE)
203
+ args = parser.parse_args()
204
+
205
+ vocab = build_descriptor_vocab(args.poucher, args.arctander, args.vocab_size)
206
+ save_vocab(vocab, args.output)
207
+ print(f"Built descriptor vocabulary: {len(vocab)} terms -> {args.output}")
208
+ print("Top 30:", vocab[:30])