-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
2172 lines (1892 loc) Β· 105 KB
/
Copy pathapp.py
File metadata and controls
2172 lines (1892 loc) Β· 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
app.py β serving layer for the flavor workbench (demo).
Run:
pip install fastapi "uvicorn[standard]" pydantic # plus the SETUP.md env
uvicorn app:app --host 0.0.0.0 --port 8000
Then open http://<r620-ip>:8000/
Endpoints:
GET / -> the workbench UI (workbench.html)
POST /api/predict -> {smiles|name} -> full flavor read (predict.predict)
POST /api/neighbors -> {smiles|name, k} -> substitution search (predict.substitute)
Both endpoints delegate to predict.py β one source of truth for the flavor read AND
the substitution search (Tanimoto/Morgan nearest-neighbor over the labeled molecules;
runnable today, no aroma model required). Auth / per-seat is stubbed (single open
instance) for the demo; deployment puts this behind login + per-user history, and the
prediction core doesn't change.
"""
import contextlib
import math
import threading
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
from pathlib import Path
import predict as P # the unified flavor read + substitution search
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from rdkit import Chem
app = FastAPI(title="Flavor Workbench (demo)")
# --- warming-up gate -------------------------------------------------------------------------
# Model heads load on a background thread (predict._load_all_models) so uvicorn binds instantly.
# Until they're ready we serve a friendly self-refreshing page (HTML nav) / a clean 503 (API),
# instead of the old ~34 s startup 502. /api/status and /healthz stay open so the page can poll.
_WARMING_OPEN = {"/api/status", "/healthz", "/favicon.ico"}
_WARMING_HTML = """<!doctype html><html lang=en><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1"><title>Flavormancer β warming up</title>
<link rel=icon type=image/png href="/static/favicon.png">
<meta http-equiv=refresh content=15>
<style>
@font-face{font-family:'Cinzel Decorative';src:url('/static/wordmark.ttf') format('truetype');font-weight:700;font-display:swap}
@font-face{font-family:'Grenze Gotisch';src:url('/static/headerfont.ttf') format('truetype');font-weight:700;font-display:swap}
:root{--brand-1:#8A6BE0;--brand-2:#2BC4C4;--accent:#E0913C;--cream:#D9AB74;--ink:#0B0F14;--muted:#9BA6B0}
*{box-sizing:border-box}html,body{margin:0;height:100%}
body{background:radial-gradient(1200px 640px at 50% -12%,#161d29,#080B10 62%);color:var(--cream);
font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;display:flex;align-items:center;justify-content:center;padding:24px}
.box{max-width:460px;width:100%;text-align:center}
header{display:flex;flex-direction:column;align-items:center;gap:6px;margin-bottom:6px}
header img{width:54px;height:54px;object-fit:contain;filter:drop-shadow(0 2px 8px rgba(0,0,0,.5))}
.wordmark{font-family:'Grenze Gotisch','Cinzel Decorative',Georgia,serif;font-size:38px;line-height:1;
letter-spacing:.02em;background:linear-gradient(100deg,#8A6BE0,#4E84C8 46%,#2BC4C4);-webkit-background-clip:text;
background-clip:text;color:transparent;margin:2px 0 0}
.tagline{font-family:'Cinzel Decorative',Georgia,serif;font-size:12.5px;letter-spacing:.05em;color:var(--muted)}
.flask{width:150px;height:150px;margin:14px auto 6px;display:block}
.loader-ring{transform-origin:70px 70px;animation:ringspin 1.15s linear infinite}
@keyframes ringspin{to{transform:rotate(360deg)}}
.bub{opacity:0;transform-box:fill-box;transform-origin:center;animation:bub 1.7s ease-in infinite}
.b1{animation-delay:0s}.b2{animation-delay:.5s}.b3{animation-delay:.9s}.b4{animation-delay:1.3s}
@keyframes bub{0%{opacity:0;transform:translateY(6px) scale(.4)}20%{opacity:.9}100%{opacity:0;transform:translateY(-18px) scale(.95)}}
.wisp{stroke-dasharray:5 9;transform-box:fill-box;transform-origin:bottom;animation:wisp 2.2s linear infinite,wispRise 3.4s ease-in-out infinite}
.w1{opacity:.85;animation-delay:0s,0s}.w2{opacity:.6;animation-delay:.5s,.4s}
.w3{opacity:.55;animation-delay:1s,.9s}.w4{opacity:.5;animation-delay:1.5s,1.3s}
@keyframes wisp{to{stroke-dashoffset:-28}}
@keyframes wispRise{0%,100%{transform:translateY(2px) scaleY(.96)}50%{transform:translateY(-2px) scaleY(1.02)}}
h1{font-family:'Cinzel Decorative',Georgia,serif;font-size:18px;letter-spacing:.06em;color:var(--cream);margin:2px 0 4px}
.sub{color:var(--muted);font-size:13px;margin:0 0 20px}
.bar{height:10px;border-radius:6px;background:#141b26;overflow:hidden;border:1px solid #2a3644}
.fill{height:100%;width:0;border-radius:6px;background:linear-gradient(90deg,var(--brand-1),var(--brand-2));transition:width .5s ease}
.stat{display:flex;justify-content:space-between;margin-top:10px;font-size:12.5px;color:var(--muted);font-variant-numeric:tabular-nums}
.cantrip{margin-top:18px;min-height:1.2em;font-family:'Cinzel Decorative',Georgia,serif;font-size:12.5px;color:var(--brand-2);opacity:.9}
@media(prefers-reduced-motion:reduce){.loader-ring,.bub,.wisp{animation:none}}
</style></head><body>
<div class=box>
<header>
<img src="/static/logo.png" alt="">
<div class=wordmark>Flavormancer</div>
<div class=tagline>taste & aroma prediction from chemical structure</div>
</header>
<svg class=flask viewBox="0 0 140 140" aria-hidden=true>
<defs><linearGradient id=g x1=0 y1=0 x2=1 y2=1><stop offset=0 stop-color=#7C5CBF /><stop offset=1 stop-color=#2BC4C4 /></linearGradient></defs>
<circle cx=70 cy=70 r=62 fill=none stroke="url(#g)" stroke-width=3 opacity=.55 />
<circle class=loader-ring cx=70 cy=70 r=62 fill=none stroke="url(#g)" stroke-width=3 stroke-linecap=round stroke-dasharray="80 320"/>
<path d="M58 44 h24 v14 l16 34 a6 6 0 0 1 -5.5 8.4 h-45 a6 6 0 0 1 -5.5 -8.4 l16 -34 z" fill="rgba(43,196,196,.10)" stroke="url(#g)" stroke-width=3 stroke-linejoin=round/>
<path d="M56 44 h28" stroke="url(#g)" stroke-width=3.4 stroke-linecap=round/>
<path d="M50.5 74 L89.5 74 L98 92 a6 6 0 0 1 -5.5 8.4 h-45 a6 6 0 0 1 -5.5 -8.4 Z" fill="url(#g)" opacity=.72 />
<circle class="bub b1" cx=64 cy=90 r=2.4 fill=#EAF6F4 /><circle class="bub b2" cx=73 cy=93 r=1.8 fill=#EAF6F4 />
<circle class="bub b3" cx=77 cy=87 r=2.1 fill=#EAF6F4 /><circle class="bub b4" cx=68 cy=95 r=1.5 fill=#EAF6F4 />
<g fill=none stroke-linecap=round>
<path class="wisp w1" d="M69 72 C63 64 75 58 69 50 C63 43 77 36 70 28 C65 22 73 16 69 9" stroke=#D9AB74 stroke-width=2.4 />
<path class="wisp w2" d="M63 71 C57 64 69 59 62 52 C56 46 66 40 62 33 C59 28 64 24 62 19" stroke=#2BC4C4 stroke-width=2 />
<path class="wisp w3" d="M76 71 C82 64 70 59 77 52 C83 46 73 41 77 34 C79 30 75 26 77 22" stroke=#8A6BE0 stroke-width=2 />
<path class="wisp w4" d="M70 73 C66 68 74 63 70 57 C67 52 72 48 70 43" stroke=#D9AB74 stroke-width=1.7 />
</g>
</svg>
<h1>Warming the cauldronβ¦</h1>
<p class=sub>Summoning the flavor & aroma heads into memory. This happens once, at startup.</p>
<div class=bar><div class=fill id=fill></div></div>
<div class=stat><span id=count>Loading modelsβ¦</span><span id=eta></span></div>
<div class=cantrip id=cantrip>Stoking the athanorβ¦</div>
</div>
<script>
var CANTRIPS=['Stoking the athanorβ¦','Unrolling the aroma grimoireβ¦','Awakening the descriptor headsβ¦',
'Charging the olfactory runesβ¦','Tempering the taste enginesβ¦','Aligning the flavor latticeβ¦','Distilling first essencesβ¦'];
var ci=0;setInterval(function(){ci=(ci+1)%CANTRIPS.length;document.getElementById('cantrip').textContent=CANTRIPS[ci];},5000);
function poll(){
fetch('/api/status',{cache:'no-store'}).then(function(r){return r.json();}).then(function(s){
if(s.ready){location.reload();return;}
var t=s.total||0,l=s.loaded||0,pct=t?Math.round(l/t*100):0;
document.getElementById('fill').style.width=pct+'%';
document.getElementById('count').textContent=t?(l+' / '+t+' heads summoned'):'Discovering headsβ¦';
var eta='';
if(l>0&&t>l&&s.elapsed){var per=s.elapsed/l;eta='~'+Math.max(1,Math.round(per*(t-l)))+'s remaining';}
document.getElementById('eta').textContent=eta;
}).catch(function(){}).finally(function(){setTimeout(poll,1000);});
}
poll();
</script></body></html>"""
@app.get("/api/status")
def api_status():
"""Model-load progress for the warming-up page (loaded/total heads, phase, ready, elapsed)."""
return P.load_status()
@app.get("/healthz")
def healthz():
"""Liveness/readiness for systemd + proxies: ok once the process is up, ready once models load."""
return {"ok": True, "ready": P.MODELS_READY.is_set()}
@app.get("/api/heads")
@lru_cache(maxsize=1)
def api_heads():
"""The full head catalog grouped by category (taste / aroma / mouthfeel / safety) with AUROC β
for the modal Heads card and the library category pickers."""
return P.head_catalog()
@app.middleware("http")
async def _warming_gate(request: Request, call_next):
_p = request.url.path
# /static/* stays open so the warming page's own fonts/logo/favicon load while models warm
if not P.MODELS_READY.is_set() and _p not in _WARMING_OPEN and not _p.startswith("/static/"):
wants_html = request.method == "GET" and (
request.url.path == "/" or "text/html" in request.headers.get("accept", ""))
if wants_html:
return HTMLResponse(_WARMING_HTML, status_code=503, headers={"Retry-After": "5"})
return JSONResponse({"warming": True, **P.load_status()}, status_code=503,
headers={"Retry-After": "5"})
return await call_next(request)
def _load_name2smiles():
"""Local name -> SMILES index (instant, offline) so library/demo ingredients resolve without a
PubChem round-trip. Built from master_enrichment.parquet (~8k named molecules) + the suggest
CSV. Only genuinely-unknown names fall through to live PubChem in _resolve()."""
idx = {}
with contextlib.suppress(Exception): # table absent / no pandas; live lookup still covers it
import pandas as pd
df = pd.read_parquet(P.artifact("master_enrichment.parquet"))
for nm, smi in zip(df["name"], df["smiles"]):
if isinstance(nm, str) and isinstance(smi, str) and nm.strip() and smi.strip():
idx.setdefault(nm.strip().lower(), smi)
with contextlib.suppress(Exception): # no suggest file; fine
import csv
with open(P.artifact("flavor_volatiles.csv"), encoding="utf-8") as fh:
for r in csv.DictReader(fh):
if r.get("name") and r.get("smiles"):
idx.setdefault(r["name"].strip().lower(), r["smiles"])
return idx
_NAME2SMILES = _load_name2smiles()
@lru_cache(maxsize=8192)
def _resolve(text: str):
"""Accept a SMILES or a compound name; return canonical SMILES or None. Memoized. Tries a
local name index first (instant, offline) so library/demo molecules never touch the network;
only unknown names hit PubChem live (~1-2 s), which is why caching + the index matter."""
text = (text or "").strip()
if Chem.MolFromSmiles(text):
return text
hit = _NAME2SMILES.get(text.lower())
if hit and Chem.MolFromSmiles(hit):
return hit
with contextlib.suppress(Exception):
import pubchempy as pcp
hits = pcp.get_compounds(text, "name")
if hits and hits[0].canonical_smiles:
return hits[0].canonical_smiles
return None
def _svg(smi, w=320, h=220):
"""2D structure SVG; None if drawing is unavailable (headless box w/o libXrender)."""
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is None:
return None
try:
from rdkit.Chem.Draw import rdMolDraw2D
d = rdMolDraw2D.MolDraw2DSVG(w, h)
d.DrawMolecule(mol)
d.FinishDrawing()
return d.GetDrawingText()
except Exception: # noqa: BLE001 β missing X11 libs etc.; degrade gracefully
return None
def _load_name_table():
"""inchikey-skeleton -> (common, IUPAC) from the precomputed enrichment table, so the
whole labeled set resolves instantly and offline. Empty until build_properties.py has
written name columns; live PubChem stays the fallback for anything not in the table."""
try:
import pandas as pd
df = pd.read_parquet(P.artifact("properties.parquet"))
if "common_name" not in df.columns:
return {}
out = {}
for ik, c, u in zip(df["inchikey"], df["common_name"], df["iupac_name"]):
if isinstance(ik, str) and (isinstance(c, str) or isinstance(u, str)):
out[ik.split("-")[0]] = (c if isinstance(c, str) else None,
u if isinstance(u, str) else None)
return out
except Exception: # noqa: BLE001 β no table / no pandas; just fall back to live lookups
return {}
def _merge_iupac_backfill(table):
"""Fold in IUPAC names that build_iupac_backfill.py recovered from PubChem for molecules
the main properties crawl missed (skeleton -> keep any common name, add the IUPAC)."""
try:
import pandas as pd
bf = pd.read_parquet(P.artifact("iupac_backfill.parquet"))
except Exception: # noqa: BLE001 β backfill not built; nothing to merge
return table
for skel, u in zip(bf["inchikey_skel"], bf["iupac_name"]):
if isinstance(skel, str) and isinstance(u, str) and u:
common = table.get(skel, (None, None))[0]
table[skel] = (common, u)
return table
_NAME_TABLE = _merge_iupac_backfill(_load_name_table())
@lru_cache(maxsize=8192)
def _names(smi):
"""(common, IUPAC) names β from the precomputed table first (instant), else live PubChem."""
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is not None:
hit = _NAME_TABLE.get(Chem.MolToInchiKey(mol).split("-")[0])
if hit:
return hit
import json
import urllib.parse
import urllib.request
url = ("https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/"
f"{urllib.parse.quote(smi)}/property/Title,IUPACName/JSON")
try:
with urllib.request.urlopen(url, timeout=4) as r:
p = json.load(r)["PropertyTable"]["Properties"][0]
return p.get("Title"), p.get("IUPACName")
except Exception: # noqa: BLE001 β not found / timeout / throttled
return None, None
def _name_local(smi):
"""Common name from the precomputed table ONLY (instant, no network) β for hot loops like
the Formulation Studio's candidate ranking, where a live PubChem call per candidate would
stall the request. Returns None for molecules not in the table (they're simply skipped)."""
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is None:
return None
hit = _NAME_TABLE.get(Chem.MolToInchiKey(mol).split("-")[0])
return hit[0] if hit else None
class Query(BaseModel):
smiles: str
k: int = 50 # a generous cap; neighbors/substitutes return every match above a similarity floor
# (up to k), so the UI scrolls the qualifying set instead of a fixed short list
@app.post("/api/predict")
def api_predict(q: Query):
smi = _resolve(q.smiles)
if not smi:
return {"error": f"Couldn't resolve '{q.smiles}' to a structure. "
f"Enter a valid SMILES or a recognized compound name."}
out = P.predict(smi, include_aroma=True)
out["flavor_tags"] = _read_tags(smi, out)
out["references"] = _references(smi)
return out
def _load_spectra():
"""inchikey-skeleton -> [available spectra types] from spectra.parquet (build_spectra.py):
public-domain PubChem availability metadata. Empty until the crawl has run."""
try:
import pandas as pd
df = pd.read_parquet(P.artifact("spectra.parquet"))
labels = [("has_ms", "MS"), ("has_ir", "IR"), ("has_nmr", "NMR"),
("has_uv", "UV"), ("has_raman", "Raman")]
out = {}
for _, r in df.iterrows():
ik = r.get("inchikey")
if isinstance(ik, str):
out[ik.split("-")[0]] = [lab for col, lab in labels if bool(r.get(col))]
return out
except Exception: # noqa: BLE001 β not crawled yet
return {}
_SPECTRA = _load_spectra()
def _spectra_flags(inchikey):
return _SPECTRA.get(inchikey.split("-")[0], [])
def _references(smi):
"""Deep links to the authoritative public pages for this molecule β where the spectra
(IR / MS / UV / NMR), GC retention indices, and full literature live. We LINK rather than
host: PubChem is public domain, but NIST WebBook data is licensed for individual use only,
so redistribution isn't clean β a hyperlink always is."""
import urllib.parse
mol = Chem.MolFromSmiles(smi)
if mol is None:
return []
ik = Chem.MolToInchiKey(mol)
have = _spectra_flags(ik) # which spectra PubChem actually has (public-domain availability metadata)
note = ("PubChem has " + " Β· ".join(have) if have else "identity, properties, spectra")
refs = [{"label": "PubChem", "note": note,
"url": f"https://pubchem.ncbi.nlm.nih.gov/#query={urllib.parse.quote(ik)}",
"spectra": have}]
with contextlib.suppress(Exception): # InChI generation can fail on odd valences
inchi = Chem.MolToInchi(mol)
if inchi:
refs.append({"label": "NIST WebBook", "note": "IR / MS spectra, GC retention index",
"url": "https://webbook.nist.gov/cgi/cbook.cgi?InChI="
+ urllib.parse.quote(inchi) + "&Units=SI"})
return refs
def _read_tags(smi, out):
"""Plain-folk 'what is this?' tags for the read: the tastes it carries, the aroma notes it
reads as, and any everyday flavor it's the character molecule of (banana, saffronβ¦). So a
non-chemist sees 'banana Β· fruity Β· sweet' at a glance instead of only probabilities."""
tastes = [t for t in ("sweet", "bitter", "umami")
if isinstance(out.get(t), (int, float)) and out[t] >= 0.5]
if out.get("sour"):
tastes.append("sour")
if out.get("salty"):
tastes.append("salty")
aromas = [d["odor"] for d in _aroma_tags(smi)] # documented-or-confident aroma notes
mol = Chem.MolFromSmiles(smi)
flavors = []
if mol is not None:
flavors = _FLAVOR_BY_SKEL.get(Chem.MolToInchiKey(mol).split("-")[0], [])
# a word can be BOTH a curated flavor and an aroma descriptor (coconut, banana, citrusβ¦) β
# show it once, as the richer flavor tag; also don't repeat a taste as an aroma
seen = set(flavors) | set(tastes)
aromas = [a for a in aromas if a not in seen]
return {"tastes": tastes, "aromas": aromas[:6], "flavors": flavors}
def _aroma_tags(smi, k=3):
"""A few aroma descriptor tags for a molecule: keyword-derived from documented HSDB odor
when the molecule is in the corpus (source 'found'), else the model's confident predictions."""
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is None:
return []
rec = _ODOR_TABLE.get(Chem.MolToInchiKey(mol).split("-")[0])
if rec and rec.get("odor"):
with contextlib.suppress(Exception): # vocab module missing; fall through to predicted
from build_aroma_dataset import tag as _odor_tag
found = sorted(_odor_tag(rec["odor"]))[:k]
if found:
return [{"odor": t, "source": "found"} for t in found]
pa = P.predict_aroma(smi)
return [{"odor": d["odor"], "source": "predicted"}
for d in pa.get("descriptors", []) if d.get("confident")][:k]
def _aroma_tags_cheap(smi, precomputed, k=3):
"""Same as _aroma_tags β documented HSDB odor first ('found') β but for the PREDICTED
fallback it reuses aromas already computed in the substitution index instead of re-running
the 24 heads. Identical result to _aroma_tags, without the per-molecule model cost."""
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is not None:
rec = _ODOR_TABLE.get(Chem.MolToInchiKey(mol).split("-")[0])
if rec and rec.get("odor"):
with contextlib.suppress(Exception): # vocab module missing; fall through to predicted
from build_aroma_dataset import tag as _odor_tag
found = sorted(_odor_tag(rec["odor"]))[:k]
if found:
return [{"odor": t, "source": "found"} for t in found]
return [{"odor": a, "source": "predicted"} for a in (precomputed or [])][:k]
@app.post("/api/neighbors")
def api_neighbors(q: Query):
smi = _resolve(q.smiles)
if not smi:
return {"neighbors": []}
res = P.substitute(smi, k=q.k, min_similarity=0.30) # every structural look-alike above the floor
for n in res.get("neighbors", []): # enrich each candidate: structure + names + aroma + GRAS
n["svg"] = _svg(n["smiles"], 132, 96)
nm = _names(n["smiles"])
n["name"], n["iupac"] = nm[0], nm[1]
# documented odor first (fast lookup); predicted fallback reuses the index's precomputed
# aromas so the heads never re-run (was ~1.3s x k). Same result as _aroma_tags.
n["aroma"] = _aroma_tags_cheap(n["smiles"], n.pop("aromas", []))
_m = Chem.MolFromSmiles(n["smiles"])
n["gras"] = bool(_m is not None and Chem.MolToInchiKey(_m).split("-")[0] in P._GRAS)
return res
@app.post("/api/substitutes")
def api_substitutes(q: Query):
"""Profile-based substitutes: molecules whose predicted taste+aroma head scores line up
closest with the query β the taste/smell-alikes (vs /api/neighbors' structural look-alikes)."""
smi = _resolve(q.smiles)
if not smi:
return {"substitutes": []}
res = P.substitutes(smi, k=q.k, min_match=0.45) # every taste/aroma-alike above the floor
for n in res.get("substitutes", []): # same enrichment as neighbors: structure + names + aroma + GRAS
n["svg"] = _svg(n["smiles"], 132, 96)
nm = _names(n["smiles"])
n["name"], n["iupac"] = nm[0], nm[1]
n["aroma"] = _aroma_tags_cheap(n["smiles"], n.pop("aromas", []))
_m = Chem.MolFromSmiles(n["smiles"])
n["gras"] = bool(_m is not None and Chem.MolToInchiKey(_m).split("-")[0] in P._GRAS)
return res
@app.post("/api/precomputed")
def api_precomputed(q: Query):
"""Fast check: is this molecule's profile already in the index (instant read) or does it need a
fresh 178-head compute? Lets the UI show a 'conjuring a fresh reading' note for novel molecules."""
smi = _resolve(q.smiles)
return {"precomputed": bool(smi and P.is_precomputed(smi))}
@app.post("/api/names")
def api_names(q: Query):
"""Common (PubChem Title) + IUPAC names for the queried molecule."""
raw = (q.smiles or "").strip()
smi = _resolve(raw)
common, iupac = _names(smi) if smi else (None, None)
# If the user searched by NAME (not a SMILES), that IS the best common name β PubChem's
# Title for a flattened structure is often the systematic name (e.g. "cinnamaldehyde"
# resolves to Title "3-Phenylprop-2-Enal"), which then looks like the IUPAC name repeated.
if smi and raw and Chem.MolFromSmiles(raw) is None:
common = raw[:1].upper() + raw[1:]
return {"common": common, "iupac": iupac, "smiles": smi, "formula": _formula(smi)}
def _formula(smi):
"""Hill-system molecular formula (e.g. C9H16O2) β a compact 4th identifier alongside
common / IUPAC / SMILES. None for an unparseable SMILES."""
from rdkit.Chem import rdMolDescriptors
m = Chem.MolFromSmiles(smi) if smi else None
return rdMolDescriptors.CalcMolFormula(m) if m is not None else None
@app.post("/api/structure")
def api_structure(q: Query):
"""2D structure depiction (SVG); {svg: None} if drawing is unavailable."""
return {"svg": _svg(_resolve(q.smiles))}
@app.post("/api/structure3d")
def api_structure3d(q: Query):
"""3D conformer as an SDF mol block β RDKit ETKDG embed + MMFF optimize. Rendered
interactively in the browser (3Dmol.js). {molblock: None} if a 3D embed isn't possible."""
smi = _resolve(q.smiles)
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is None:
return {"molblock": None}
try:
from rdkit.Chem import AllChem
mol = Chem.AddHs(mol)
params = AllChem.ETKDGv3()
params.randomSeed = 42 # deterministic conformer
if AllChem.EmbedMolecule(mol, params) != 0 and AllChem.EmbedMolecule(mol, AllChem.ETKDG()) != 0:
return {"molblock": None} # embedding failed (e.g. tricky cage/macrocycle)
with contextlib.suppress(Exception): # no MMFF params for some atoms; unoptimized still fine
AllChem.MMFFOptimizeMolecule(mol)
return {"molblock": Chem.MolToMolBlock(mol)}
except Exception: # noqa: BLE001 β RDKit build without embedding etc.; degrade gracefully
return {"molblock": None}
@app.post("/api/stereoisomers")
def api_stereoisomers(q: Query):
"""Every stereoisomer of the queried molecule β all R/S centers AND E/Z double bonds β each
as a card: stereo label, structure SVG, name, and any ISOMER-SPECIFIC documented odor/taste
(keyed by full InChIKey, so R-carvone spearmint vs S-carvone caraway show through where
PubChem records them). The trained models are achiral, so the *difference* is documented, not
predicted β this makes that difference explorable instead of hidden."""
smi = _resolve(q.smiles)
if not smi:
return {"isomers": []}
isos = P.stereoisomers(smi)
for it in isos:
it["svg"] = _svg(it["smiles"], 150, 108)
it["name"] = (_names(it["smiles"]) or (None, None))[0]
doc = _documented_by_full(it["inchikey"])
if doc.get("odor"):
it["odor"] = doc["odor"]
if doc.get("taste"):
it["taste"] = doc["taste"]
n_doc = sum(1 for it in isos if it.get("odor") or it.get("taste"))
return {"isomers": isos, "n": len(isos), "n_documented": n_doc}
@app.get("/static/{fname}")
def _static(fname: str):
"""Serve vendored static assets (3Dmol.js, the logo) locally so the demo is self-contained."""
from fastapi import HTTPException
from fastapi.responses import FileResponse
p = Path("static") / Path(fname).name # basename only β no path traversal
if p.exists():
return FileResponse(str(p))
raise HTTPException(status_code=404)
_TASTE_RGB = {"sweet": (232, 169, 74), "bitter": (168, 138, 224), "umami": (224, 128, 94),
"sour": (191, 210, 78), "salty": (99, 166, 224), "tasteless": (184, 192, 198)}
@app.get("/api/card")
def api_card(q: str = "", dl: int = 0):
"""A branded, shareable 'flavor card' PNG for a molecule β structure + the read + the
share URL. Self-contained (RDKit draws the structure, Pillow composes)."""
from fastapi import HTTPException
from fastapi.responses import Response
smi = _resolve(q)
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is None:
raise HTTPException(status_code=404)
out = P.predict(smi, include_aroma=False)
tags = _read_tags(smi, out)
common, iupac = _names(smi)
name = common or (q[:1].upper() + q[1:] if q else smi)
import io
from PIL import Image, ImageDraw, ImageFont
from rdkit.Chem.Draw import rdMolDraw2D
def font(path, size):
try:
return ImageFont.truetype(path, size)
except Exception: # noqa: BLE001 β font file missing; fall back to default
return ImageFont.load_default()
DJ = "/usr/share/fonts/truetype/dejavu/"
f_title = font("static/headerfont.ttf", 46)
f_tag = font("static/wordmark.ttf", 17)
f_name = font(DJ + "DejaVuSans-Bold.ttf", 34)
f_body = font(DJ + "DejaVuSans.ttf", 17)
f_mono = font(DJ + "DejaVuSansMono.ttf", 15)
f_pill = font(DJ + "DejaVuSans-Bold.ttf", 16)
f_lab = font(DJ + "DejaVuSans-Bold.ttf", 15)
f_cell = font(DJ + "DejaVuSans.ttf", 12)
W = 1200
x = 508 # right column (upper band)
ink, muted, cream, teal = (231, 237, 234), (148, 162, 169), (217, 171, 116), (43, 196, 196)
# ---- the FULL readout: all 6 taste heads + all 24 aroma heads (nothing truncated) ----
taste_src = {"sweet": out.get("sweet"), "bitter": out.get("bitter"), "umami": out.get("umami"),
"sour": out.get("sour_predicted"), "salty": out.get("salty_predicted"),
"tasteless": out.get("tasteless")}
taste_cells = sorted(((t, float(v) if isinstance(v, (int, float)) else 0.0)
for t, v in taste_src.items()), key=lambda kv: -kv[1])
# The card is a shareable SNAPSHOT β a PNG can't scroll, and there are 190 heads. So: the 6
# tastes ALWAYS render (a complete, fixed row you can compare across cards), while aroma,
# mouthfeel and safety show only what actually FIRES, capped. The labels say "N of M" so a
# reader knows they're seeing the firing subset, not the whole model.
AROMA_CAP = 18 # 3 rows of 6 β keeps the card readable
pa = P.predict_aroma(smi)
# rank by score but decide "fired" from the head's OWN calibrated threshold, which
# predict_aroma already applied β re-thresholding at a flat 0.5 here would disagree with the
# modal for exactly the thin heads that needed calibrating
_descs = sorted(pa.get("descriptors", []), key=lambda d: -d["score"])
_all_aroma = [(d["odor"], d["score"]) for d in _descs]
_fired = [(d["odor"], d["score"]) for d in _descs if d.get("confident")]
aroma_cells = (_fired or _all_aroma[:3])[:AROMA_CAP] # nothing firing -> top 3, never a blank card
aroma_total, aroma_fired = len(_all_aroma), len(_fired)
_mol = Chem.MolFromSmiles(smi)
mouth_cells = [(d["sensation"], d["score"])
for d in (P.predict_mouthfeel(_mol).get("descriptors", []) if _mol else [])
if d.get("confident")]
tox_cells = [(a["assay"], a["probability"])
for a in ((out.get("safety") or {}).get("tox_screen") or {}).get("assays", [])
if (a.get("probability") or 0) >= 0.5]
pill_items = ([(fl, cream) for fl in tags.get("flavors", [])[:3]]
+ [(t, _TASTE_RGB.get(t, teal)) for t in tags.get("tastes", [])]
+ [(a, teal) for a in tags.get("aromas", [])[:6]])
# ---- measure pill wrapping (right column) to know where the full-width grid starts ----
scratch = ImageDraw.Draw(Image.new("RGB", (10, 10)))
py = 306
px = x
for text, _c in pill_items:
w = scratch.textlength(text, font=f_pill)
if px + w + 22 > W - 40:
px, py = x, py + 40
px += w + 30
pills_bottom = py + 40
# ---- full-width readout grid: 6 columns; TASTE row (6) then AROMA rows (24 = 4 x 6) ----
GX0, COLS, ROW_H = 40, 6, 40
colw = (W - 80) / COLS
grid_top = max(500, pills_bottom + 14)
taste_row_y = grid_top + 22
aroma_label_y = taste_row_y + ROW_H + 12
aroma_grid_y = aroma_label_y + 22
aroma_rows = (len(aroma_cells) + COLS - 1) // COLS
content_bottom = aroma_grid_y + aroma_rows * ROW_H
# mouthfeel + safety only take space when something actually fires
mouth_label_y = content_bottom + 12 if mouth_cells else None
mouth_row_y = (mouth_label_y + 22) if mouth_cells else None
if mouth_cells:
content_bottom = mouth_row_y + ((len(mouth_cells) + COLS - 1) // COLS) * ROW_H
tox_label_y = content_bottom + 12 if tox_cells else None
tox_row_y = (tox_label_y + 22) if tox_cells else None
if tox_cells:
content_bottom = tox_row_y + ((len(tox_cells) + COLS - 1) // COLS) * ROW_H
H = max(560, content_bottom + 56)
img = Image.new("RGB", (W, H), (15, 19, 25))
dr = ImageDraw.Draw(img)
# corner aura
for cx, cy, col in [(0, 0, (138, 107, 224)), (W, H, (43, 196, 196))]:
glow = Image.new("RGB", (W, H), (15, 19, 25))
gd = ImageDraw.Draw(glow)
gd.ellipse([cx - 380, cy - 320, cx + 380, cy + 320], fill=col)
img = Image.blend(img, glow, 0.06)
dr = ImageDraw.Draw(img)
# header
with contextlib.suppress(Exception):
emblem = Image.open("static/logo.png").convert("RGBA").resize((58, 58))
img.paste(emblem, (40, 30), emblem)
dr.text((110, 30), "Flavormancer", font=f_title, fill=ink)
dr.text((112, 82), "taste & aroma from chemical structure", font=f_tag, fill=cream)
dr.line([40, 122, W - 40, 122], fill=(42, 50, 60), width=1)
# structure panel (white) β sits in the upper band, above the grid
panel_bottom = grid_top - 14
dr.rounded_rectangle([40, 150, 470, panel_bottom], radius=14, fill=(245, 247, 245))
struct_h = min(340, panel_bottom - 172)
d2 = rdMolDraw2D.MolDraw2DCairo(410, struct_h)
d2.drawOptions().padding = 0.12
d2.DrawMolecule(mol)
d2.FinishDrawing()
struct = Image.open(io.BytesIO(d2.GetDrawingText())).convert("RGBA")
img.paste(struct, (50, 150 + (panel_bottom - 150 - struct_h) // 2), struct)
# right column β name / IUPAC / SMILES + READS AS pills
dr.text((x, 158), name[:34], font=f_name, fill=ink)
if iupac and iupac.lower() != name.lower():
dr.text((x, 206), ("IUPAC " + iupac)[:64], font=f_body, fill=muted)
dr.text((x, 232), smi[:58], font=f_mono, fill=muted)
dr.text((x, 254), "formula " + (_formula(smi) or ""), font=f_mono, fill=muted)
dr.text((x, 282), "READS AS", font=f_lab, fill=muted)
px, py = x, 306
for text, c in pill_items:
w = dr.textlength(text, font=f_pill)
if px + w + 22 > W - 40:
px, py = x, py + 40
dr.rounded_rectangle([px, py, px + w + 22, py + 30], radius=15, outline=c, width=2)
dr.text((px + 11, py + 6), text, font=f_pill, fill=c)
px += w + 30
# a compact meter cell in the grid: label, %, and a mini bar
def cell(col, cy, label, v, color):
cx = GX0 + int(col * colw)
inner = int(colw) - 12
ptxt = f"{round(v * 100)}%"
pw = dr.textlength(ptxt, font=f_cell)
lab = label
while lab and dr.textlength(lab, font=f_cell) > inner - pw - 8:
lab = lab[:-1]
dr.text((cx, cy), lab, font=f_cell, fill=ink)
dr.text((cx + inner - pw, cy), ptxt, font=f_cell, fill=muted)
dr.rounded_rectangle([cx, cy + 17, cx + inner, cy + 24], radius=3, fill=(36, 44, 53))
if v > 0:
dr.rounded_rectangle([cx, cy + 17, cx + max(2, int(inner * v)), cy + 24], radius=3, fill=color)
# TASTE MODEL β all 6 heads across one row
dr.text((GX0, grid_top), "TASTE MODEL Β· all 6 heads", font=f_lab, fill=muted)
for i, (t, v) in enumerate(taste_cells):
cell(i, taste_row_y, t, v, _TASTE_RGB.get(t, teal))
# AROMA MODEL β only the heads that fire, capped; label states the subset honestly
_shown = len(aroma_cells)
_alab = (f"AROMA MODEL Β· {_shown} of {aroma_total} heads firing"
+ (f" (top {_shown} shown)" if aroma_fired > _shown else "")
if aroma_fired else f"AROMA MODEL Β· none of {aroma_total} heads firing Β· strongest {_shown}")
dr.text((GX0, aroma_label_y), _alab, font=f_lab, fill=muted)
for i, (a, v) in enumerate(aroma_cells):
cell(i % COLS, aroma_grid_y + (i // COLS) * ROW_H, a, v, teal)
# MOUTHFEEL β trigeminal sensations, only what fires
if mouth_cells:
dr.text((GX0, mouth_label_y), f"MOUTHFEEL Β· {len(mouth_cells)} of 5 sensations firing",
font=f_lab, fill=muted)
for i, (m, v) in enumerate(mouth_cells):
cell(i % COLS, mouth_row_y + (i // COLS) * ROW_H, m, v, cream)
# SAFETY β Tox21 assays, only when flagged; caution-only, never a determination
if tox_cells:
dr.text((GX0, tox_label_y), f"SAFETY Β· {len(tox_cells)} Tox21 assay(s) flagged β caution-only, "
"indicative in-vitro activity, NOT a toxicity determination", font=f_lab, fill=muted)
for i, (a, v) in enumerate(tox_cells):
cell(i % COLS, tox_row_y + (i // COLS) * ROW_H, a, v, (192, 85, 58))
# footer
fy = H - 54
dr.line([40, fy, W - 40, fy], fill=(42, 50, 60), width=1)
share = "flavormancer.echelonts.net/?q=" + (common or q or smi)
dr.text((40, fy + 14), share, font=f_mono, fill=teal)
tw = dr.textlength("before you pour", font=f_tag)
dr.text((W - 40 - tw, fy + 12), "before you pour", font=f_tag, fill=cream)
buf = io.BytesIO()
img.save(buf, "PNG")
data = buf.getvalue()
fn = "".join(ch for ch in (common or "molecule") if ch.isalnum() or ch in "-_") or "molecule"
headers = {"Content-Disposition": f'attachment; filename="flavormancer-{fn}.png"'} if dl else {}
return Response(content=data, media_type="image/png", headers=headers)
class RecipeIngredient(BaseModel):
name: str = ""
smiles: str = ""
ppm: float | None = None
carries: list[str] = []
volatility: str = ""
dose_basis: str = ""
class RecipeCardQuery(BaseModel):
ingredients: list[RecipeIngredient] = []
flavors: list[str] = [] # target flavors this recipe was designed for
notes: list[str] = [] # target aroma notes
title: str = "" # optional recipe name
note: str = "" # the "how it was dosed" caption
@app.post("/api/recipe_card")
def api_recipe_card(rc: RecipeCardQuery, dl: int = 0):
"""A branded, shareable 'recipe card' PNG for a designed/analyzed formulation β
the bench-sheet parity of /api/card. Lists each ingredient (structure swatch,
name, formula, ppm, volatility, what it carries) under the target profile, with
the same honest 'directional, not calibrated' footing as the Studio itself.
SMILES/formula are recomputed server-side from each ingredient's structure, so the
card is authoritative even though the recipe rows are posted from the client."""
import io
from fastapi.responses import Response
from PIL import Image, ImageDraw, ImageFont
from rdkit.Chem.Draw import rdMolDraw2D
def font(path, size):
try:
return ImageFont.truetype(path, size)
except Exception: # noqa: BLE001 β font file missing; fall back to default
return ImageFont.load_default()
DJ = "/usr/share/fonts/truetype/dejavu/"
f_title = font("static/headerfont.ttf", 46)
f_tag = font("static/wordmark.ttf", 17)
f_sub = font(DJ + "DejaVuSans-Bold.ttf", 22)
f_name = font(DJ + "DejaVuSans-Bold.ttf", 21)
f_body = font(DJ + "DejaVuSans.ttf", 15)
f_mono = font(DJ + "DejaVuSansMono.ttf", 13)
f_ppm = font(DJ + "DejaVuSans-Bold.ttf", 26)
f_lab = font(DJ + "DejaVuSans-Bold.ttf", 13)
f_pill = font(DJ + "DejaVuSans-Bold.ttf", 15)
ink, muted, cream, teal = (231, 237, 234), (148, 162, 169), (217, 171, 116), (43, 196, 196)
W = 1000
# canonicalise ingredients server-side (authoritative formula + structure)
rows = []
for ing in rc.ingredients[:14]: # a bench recipe is a handful of ingredients; cap defensively
smi = (ing.smiles or "").strip()
mol = Chem.MolFromSmiles(smi) if smi else None
if mol is None and ing.name:
smi2 = _resolve(ing.name)
mol = Chem.MolFromSmiles(smi2) if smi2 else None
if mol is not None:
smi = smi2
rows.append({"mol": mol, "smiles": Chem.MolToSmiles(mol) if mol else smi,
"formula": _formula(smi) if mol else "",
"name": ing.name or (_name_local(smi) if mol else "") or smi,
"ppm": ing.ppm, "carries": ing.carries, "volatility": ing.volatility})
ROW_H = 92
head_h = 210 if (rc.flavors or rc.notes) else 168
H = max(420, head_h + len(rows) * ROW_H + 78)
img = Image.new("RGB", (W, H), (15, 19, 25))
dr = ImageDraw.Draw(img)
for cx, cy, col in [(0, 0, (138, 107, 224)), (W, H, (43, 196, 196))]:
glow = Image.new("RGB", (W, H), (15, 19, 25))
gd = ImageDraw.Draw(glow)
gd.ellipse([cx - 340, cy - 300, cx + 340, cy + 300], fill=col)
img = Image.blend(img, glow, 0.06)
dr = ImageDraw.Draw(img)
# header
with contextlib.suppress(Exception):
emblem = Image.open("static/logo.png").convert("RGBA").resize((58, 58))
img.paste(emblem, (40, 30), emblem)
dr.text((110, 30), "Flavormancer", font=f_title, fill=ink)
dr.text((112, 82), "taste & aroma from chemical structure", font=f_tag, fill=cream)
dr.line([40, 122, W - 40, 122], fill=(42, 50, 60), width=1)
# sub-title + target profile pills
title = rc.title.strip() or "Formulation"
dr.text((40, 138), title[:52], font=f_sub, fill=ink)
if rc.flavors or rc.notes:
dr.text((40, 174), "TARGET", font=f_lab, fill=muted)
px, py = 118, 170
for text, c in ([(f, cream) for f in rc.flavors] + [(n, teal) for n in rc.notes]):
w = dr.textlength(text, font=f_pill)
if px + w + 22 > W - 40:
px, py = 118, py + 34
dr.rounded_rectangle([px, py, px + w + 20, py + 28], radius=14, outline=c, width=2)
dr.text((px + 10, py + 5), text, font=f_pill, fill=c)
px += w + 28
# ingredient rows
y = head_h
for r in rows:
dr.rounded_rectangle([40, y, W - 40, y + ROW_H - 12], radius=12, outline=(42, 50, 60), width=1)
# structure swatch (white)
dr.rounded_rectangle([52, y + 10, 152, y + ROW_H - 22], radius=8, fill=(245, 247, 245))
if r["mol"] is not None:
d2 = rdMolDraw2D.MolDraw2DCairo(96, ROW_H - 36)
d2.drawOptions().padding = 0.1
d2.DrawMolecule(r["mol"])
d2.FinishDrawing()
sw = Image.open(io.BytesIO(d2.GetDrawingText())).convert("RGBA")
img.paste(sw, (54, y + 12), sw)
# name + identifiers
dr.text((168, y + 12), r["name"][:40], font=f_name, fill=ink)
ident = r["formula"] + (" " + r["smiles"][:40] if r["smiles"] else "")
dr.text((168, y + 40), ident[:70], font=f_mono, fill=muted)
carries = ", ".join(r["carries"]) if r["carries"] else ""
if carries:
dr.text((168, y + 60), ("carries: " + carries)[:64], font=f_body, fill=teal)
# ppm + volatility (right-aligned)
if r["ppm"] is not None:
ptxt = f"{r['ppm']:g} ppm"
pw = dr.textlength(ptxt, font=f_ppm)
dr.text((W - 60 - pw, y + 16), ptxt, font=f_ppm, fill=cream)
if r["volatility"]:
vt = r["volatility"] + " volatility"
vw = dr.textlength(vt, font=f_body)
dr.text((W - 60 - vw, y + 50), vt, font=f_body, fill=muted)
y += ROW_H
# caption (honest scope) + footer
cap = (rc.note.strip() or "Directional starting recipe β doses balanced by inverse volatility. "
"Tune on the bench; calibrated intensity comes with your odor-threshold / panel data.")
dr.text((40, y + 4), ("β " + cap)[:118], font=f_body, fill=muted)
fy = H - 46
dr.line([40, fy, W - 40, fy], fill=(42, 50, 60), width=1)
dr.text((40, fy + 12), "flavormancer.echelonts.net", font=f_mono, fill=teal)
tw = dr.textlength("before you pour", font=f_tag)
dr.text((W - 40 - tw, fy + 10), "before you pour", font=f_tag, fill=cream)
buf = io.BytesIO()
img.save(buf, "PNG")
data = buf.getvalue()
fn = "".join(ch for ch in title.lower().replace(" ", "-") if ch.isalnum() or ch in "-_") or "recipe"
headers = {"Content-Disposition": f'attachment; filename="flavormancer-{fn}.png"'} if dl else {}
return Response(content=data, media_type="image/png", headers=headers)
class MixtureQuery(BaseModel):
ingredients: list[str]
processes: list[str] = []
class BlendQuery(BaseModel):
ingredients: list[str]
weights: list[float] = []
k: int = 6
@app.post("/api/mixture_to_molecule")
def api_mixture_to_molecule(b: BlendQuery):
"""Collapse a blend to single equivalent molecules: the dose-weighted mean taste+aroma
profile of the components, then the molecules whose own profile is closest."""
smis = [s for s in (_resolve(x) for x in b.ingredients) if s]
if not smis:
return {"equivalents": []}
res = P.mixture_to_molecule(smis, weights=b.weights or None, k=b.k)
for n in res.get("equivalents", []): # enrich like neighbors/substitutes
n["svg"] = _svg(n["smiles"], 132, 96)
nm = _names(n["smiles"])
n["name"], n["iupac"] = nm[0], nm[1]
n["aroma"] = _aroma_tags_cheap(n["smiles"], n.pop("aromas", []))
_m = Chem.MolFromSmiles(n["smiles"])
n["gras"] = bool(_m is not None and Chem.MolToInchiKey(_m).split("-")[0] in P._GRAS)
return res
@app.post("/api/mixture")
def api_mixture(m: MixtureQuery):
"""Per-ingredient reads + documented-hazard screen + a single-molecule palette match."""
smis = [s for s in (_resolve(x) for x in m.ingredients) if s]
out = P.check_mixture(smis, m.processes)
reads, palette, aroma_palette = [], set(), set()
for s in smis:
r = P.predict(s)
tp = r.get("taste_profile", [])
tastes = [t for t in ("sweet", "bitter", "umami") if isinstance(r.get(t), (int, float)) and r[t] >= 0.5]
if r.get("sour"):
tastes.append("sour")
if r.get("salty") is True:
tastes.append("salty")
for t in (r.get("known_tastes") or []):
if t not in tastes:
tastes.append(t)
palette.update(tastes)
aromas = [d["odor"] for d in _aroma_tags(s)] # this ingredient's aroma notes
aroma_palette.update(aromas)
reads.append({"smiles": r["smiles"], "name": _names(s)[0], "svg": _svg(s, 110, 80),
"top_taste": tp[0]["taste"] if tp else None, "tastes": tastes, "aromas": aromas[:4],
"gras": r["safety"]["gras_status"], "alerts": r["safety"]["structural_alerts"],
"tox_flags": r["safety"]["tox_screen"].get("flags", []) if r["applicability"]["in_domain"] else []})
pal = P.palette_match(sorted(palette), sorted(aroma_palette), k=5)
for mt in pal.get("matches", []):
mt["svg"] = _svg(mt["smiles"], 110, 80)
mt["name"] = _names(mt["smiles"])[0]
out["ingredients"] = reads
out["palette"] = pal
# indicative reaction-template products (augments the documented-hazard screen) β with the
# product's own predicted taste + aroma so you see what would form, flavor-wise
rxns = P.reaction_products(smis)
for rx in rxns:
rx["svg"] = _svg(rx["smiles"], 110, 80)
rx["name"] = _names(rx["smiles"])[0]
rx["aromas"] = [d["odor"] for d in _aroma_tags(rx["smiles"])][:3]
pr = P.predict(rx["smiles"])
rtastes = [t for t in ("sweet", "bitter", "umami")
if isinstance(pr.get(t), (int, float)) and pr[t] >= 0.5]
if pr.get("sour"):
rtastes.append("sour")
if pr.get("salty") is True:
rtastes.append("salty")
rx["tastes"] = rtastes
out["reactions"] = rxns
return out
# ββ Formulation Studio ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# A recipe (ingredients + optional ppm) -> blended note-profile, dosing-balance /
# overpowering-component flag, hazard screen, and (with a target) a gap analysis.
# The whole point: read a formulation "before you pour" and save bench runs.
_VOL_W = {"high": 3.0, "moderate": 2.0, "low": 1.0}
_PROFILE_FLOOR = 0.35 # ignore each molecule's faint (<0.35 prob) heads so noise can't stack
class FormulationQuery(BaseModel):
ingredients: list[dict] = [] # [{name|smiles, ppm?}]
processes: list[str] = [] # high_heat / refining / fermentation
target: list[str] = [] # desired aroma notes for the gap analysis
@app.post("/api/formulation")
def api_formulation(f: FormulationQuery):
"""Formulation Studio engine β reads a full recipe before it is poured.
Returns the blended note-profile (which aromas the mix reads as, and which
ingredient drives each), the dosing balance / overpowering-component flag, a
documented-hazard screen, and β when a target profile is supplied β a gap
analysis with concrete add/cut moves.
HONEST SCOPE (surfaced in `data_gates`): the profile is DIRECTIONAL. Each
molecule's predicted notes are weighted by OAV where odor thresholds are