Update app.py
Browse files8 unmodified lines9101112131428 unmodified lines4344454647484950515253545596 unmodified lines15215315415515615715813 unmodified lines17217317417517617717817918018118218318418518618718822 unmodified lines2112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563572 unmodified lines3603613623633643653663673683693703713723733743753763773783793801 unmodified line38238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643719 unmodified lines45745845946046146286 unmodified lines5495505515525535545559 unmodified lines5655665675685695705715725735745755765775785795805815825835845855861 unmodified line5885895905915925935945955965975985996001 unmodified line6026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746 unmodified lines6816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628634 unmodified lines8688698708718728738748 unmodified linesfrom PIL import Imagefrom datetime import datetimefrom pathlib import Path# ========== Діагностичний друк ==========print("Gradio version:", gr.__version__)28 unmodified linestry:if not LOG_PATH.exists():return pd.DataFrame(columns=["timestamp","tab","inputs","result","note"])return pd.read_csv(LOG_PATH)except Exception:return pd.DataFrame(columns=["timestamp","tab","inputs","result","note"])def save_note(note, tab, last_result):log_entry(tab, "", last_result, note)return "✅ Saved!", load_journal()# ========== БАЗИ ДАНИХ ==========MIRNA_DB = {96 unmodified lines"clusterin","igm","iga","igg","complement","transferrin","alpha-2-macroglobulin"]# ========== ФУНКЦІЇ ПРЕДИКЦІЇ ==========def predict_mirna(gene):df = pd.DataFrame(MIRNA_DB.get(gene, []))log_entry("S1-B · R1a · miRNA", gene, f"{len(df)} miRNAs")13 unmodified linesreturn pd.DataFrame(ASO)def predict_drug(pocket):df = pd.DataFrame(FGFR3.get(pocket, []))fig, ax = plt.subplots(figsize=(6, 4), facecolor=CARD)ax.set_facecolor(CARD)ax.barh(df["Compound"], df["Final_score"], color=ACC)ax.set_xlabel("Final Score", color=TXT); ax.tick_params(colors=TXT)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title(f"Top compounds — {pocket}", color=TXT, fontsize=10)plt.tight_layout()buf = BytesIO(); plt.savefig(buf, format="png", dpi=120, facecolor=CARD); plt.close(); buf.seek(0)log_entry("S1-C · R1a · FGFR3", pocket, f"Top: {df.iloc[0]['Compound'] if len(df) else 'none'}")return df, Image.open(buf)def predict_variant(hgvs, sift, polyphen, gnomad):hgvs = hgvs.strip()22 unmodified lines)def predict_corona(size, zeta, peg, lipid):score = 0if lipid == "Ionizable": score += 2elif lipid == "Cationic": score += 1if abs(zeta) < 10: score += 1if peg > 1.5: score += 2if size < 100: score += 1dominant = ["ApoE","Albumin","Fibrinogen","Vitronectin","ApoA-I"][min(score, 4)]efficacy = "High" if score >= 4 else "Medium" if score >= 2 else "Low"log_entry("S1-D · R1a · Corona", f"size={size},peg={peg}", f"dominant={dominant}")return f"**Dominant corona protein:** {dominant}\n\n**Predicted efficacy:** {efficacy}\n\n**Score:** {score}/6"def predict_cancer(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10):vals = [c1,c2,c3,c4,c5,c6,c7,c8,c9,c10]names, weights = list(BM_W.keys()), list(BM_W.values())raw = sum(v*w for v,w in zip(vals, weights))prob = 1 / (1 + np.exp(-raw * 2))label = "CANCER" if prob > 0.5 else "HEALTHY"colour = RED if prob > 0.5 else GRNcontribs = [v*w for v,w in zip(vals, weights)]fig, ax = plt.subplots(figsize=(6, 3.5), facecolor=CARD)ax.set_facecolor(CARD)ax.barh(names, contribs, color=[ACC if c > 0 else ACC2 for c in contribs])ax.axvline(0, color=TXT, linewidth=0.8)ax.set_xlabel("Contribution to cancer score", color=TXT)ax.tick_params(colors=TXT, labelsize=8)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("Protein contributions", color=TXT, fontsize=10)plt.tight_layout()buf = BytesIO(); plt.savefig(buf, format="png", dpi=120, facecolor=CARD); plt.close(); buf.seek(0)log_entry("S1-E · R1a · Liquid Biopsy", f"CTHRC1={c1},FHL2={c2}", f"{label} {prob:.2f}")return (f"<div style=\'background:{CARD};padding:14px;border-radius:8px;font-family:sans-serif;\'>"f"<p style=\'font-size:11px;color:{DIM};margin:0 0 6px\'>S1-E · R1a · Liquid Biopsy</p>"f"<span style=\'color:{colour};font-size:24px;font-weight:bold\'>{label}</span><br>"f"<span style=\'color:{TXT};font-size:14px\'>Probability: {prob:.2f}</span></div>"), Image.open(buf)def predict_flow(size, zeta, peg, charge, flow_rate):csi = round(min((flow_rate/40)*0.6 + (peg/5)*0.2 + (1 if charge=="Cationic" else 0)*0.2, 1.0), 3)stability = "High remodeling" if csi > 0.6 else "Medium" if csi > 0.3 else "Stable"t = np.linspace(0, 60, 200)kf, ks = 0.03*(1+flow_rate/40), 0.038*(1+flow_rate/40)fig, ax = plt.subplots(figsize=(6, 3.5), facecolor=CARD)ax.set_facecolor(CARD)ax.plot(t, 60*np.exp(-0.03*t)+20, color="#60a5fa", ls="--", label="Albumin (static)")ax.plot(t, 60*np.exp(-kf*t)+10, color="#60a5fa", label="Albumin (flow)")ax.plot(t, 14*(1-np.exp(-0.038*t))+5, color=ACC, ls="--", label="ApoE (static)")ax.plot(t, 20*(1-np.exp(-ks*t))+5, color=ACC, label="ApoE (flow)")ax.set_xlabel("Time (min)", color=TXT); ax.set_ylabel("% Corona", color=TXT)ax.tick_params(colors=TXT); ax.legend(fontsize=7, labelcolor=TXT, facecolor=CARD)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("Vroman Effect — flow vs static", color=TXT, fontsize=9)plt.tight_layout()buf = BytesIO(); plt.savefig(buf, format="png", dpi=120, facecolor=CARD); plt.close(); buf.seek(0)log_entry("S1-D · R2a · Flow Corona", f"flow={flow_rate}", f"CSI={csi}")return f"**Corona Shift Index: {csi}** — {stability}", Image.open(buf)def predict_bbb(smiles, pka, zeta):logp = smiles.count("C")*0.3 - smiles.count("O")*0.5 + 1.5apoe_pct = max(0, min(40, (7.0-pka)*8 + abs(zeta)*0.5 + logp*0.8))bbb_prob = min(0.95, apoe_pct/30)tier = "HIGH (>20%)" if apoe_pct > 20 else "MEDIUM (10-20%)" if apoe_pct > 10 else "LOW (<10%)"cats = ["ApoE%","BBB","logP","pKa fit","Zeta"]vals = [apoe_pct/40, bbb_prob, min(logp/5,1), (7-abs(pka-6.5))/7, (10-abs(zeta))/10]angles = np.linspace(0, 2*np.pi, len(cats), endpoint=False).tolist()v2, a2 = vals+[vals[0]], angles+[angles[0]]fig, ax = plt.subplots(figsize=(5, 4), subplot_kw={"polar":True}, facecolor=CARD)ax.set_facecolor(CARD)ax.plot(a2, v2, color=ACC, linewidth=2); ax.fill(a2, v2, color=ACC, alpha=0.2)ax.set_xticks(angles); ax.set_xticklabels(cats, color=TXT, fontsize=8)ax.tick_params(colors=TXT)plt.tight_layout()buf = BytesIO(); plt.savefig(buf, format="png", dpi=120, facecolor=CARD); plt.close(); buf.seek(0)log_entry("S1-D · R3a · LNP Brain", f"pka={pka},zeta={zeta}", f"ApoE={apoe_pct:.1f}%")return f"**Predicted ApoE:** {apoe_pct:.1f}% — {tier}\n\n**BBB Probability:** {bbb_prob:.2f}", Image.open(buf)def extract_corona(text):out = {"nanoparticle_composition":"","size_nm":None,"zeta_mv":None,"PDI":None,"protein_source":"","corona_proteins":[],"confidence":{}}for pat, key in [(r"(\d+\.?\d*)\s*(?:nm|nanometer)","size_nm"),(r"([+-]?\d+\.?\d*)\s*mV","zeta_mv"),(r"PDI\s*[=:of]*\s*(\d+\.?\d*)","PDI")]:m = re.search(pat, text, re.I)if m: out[key] = float(m.group(1)); out["confidence"][key] = "HIGH"for src in ["human plasma","human serum","fetal bovine serum","FBS","PBS"]:if src.lower() in text.lower():out["protein_source"] = src; out["confidence"]["protein_source"] = "HIGH"; breakout["corona_proteins"] = [{"name":p,"confidence":"MEDIUM"} for p in PROTEINS if p in text.lower()]for lip in ["DSPC","DOPE","MC3","DLin","cholesterol","PEG","DOTAP"]:if lip in text: out["nanoparticle_composition"] += lip + " "out["nanoparticle_composition"] = out["nanoparticle_composition"].strip()flags = []if not out["size_nm"]: flags.append("size_nm not found")if not out["zeta_mv"]: flags.append("zeta_mv not found")if not out["corona_proteins"]: flags.append("no proteins detected")summary = "All key fields extracted" if not flags else " | ".join(flags)log_entry("S1-D · R4a · AutoCorona NLP", text[:80], f"proteins={len(out['corona_proteins'])}")return json.dumps(out, indent=2), summary# ---------- S1-F RARE ----------DIPG_VARIANTS = [{"Variant":"H3K27M (H3F3A)","Freq_pct":78,"Pathway":"PRC2 inhibition → global H3K27me3 loss","Drug_status":"ONC201 (clinical)","Circadian_gene":"BMAL1 suppressed"},{"Variant":"ACVR1 p.R206H","Freq_pct":21,"Pathway":"BMP/SMAD hyperactivation","Drug_status":"LDN-193189 (preclinical)","Circadian_gene":"PER1 disrupted"},{"Variant":"PIK3CA p.H1047R","Freq_pct":15,"Pathway":"PI3K/AKT/mTOR","Drug_status":"Copanlisib (clinical)","Circadian_gene":"CRY1 altered"},{"Variant":"TP53 p.R248W","Freq_pct":14,"Pathway":"DNA damage response loss","Drug_status":"APR-246 (clinical)","Circadian_gene":"p53-CLOCK axis"},{"Variant":"PDGFRA amp","Freq_pct":13,"Pathway":"RTK/RAS signalling","Drug_status":"Avapritinib (clinical)","Circadian_gene":"REV-ERB altered"},]DIPG_CSF_LNP = [{"Formulation":"MC3-DSPC-Chol-PEG","Size_nm":92,"Zeta_mV":-4.1,"CSF_protein":"Beta2-microglobulin","ApoE_pct":12.4,"BBB_est":0.41,"Priority":"HIGH"},{"Formulation":"DLin-KC2-DSPE-PEG","Size_nm":87,"Zeta_mV":-3.8,"CSF_protein":"Cystatin C","ApoE_pct":14.1,"BBB_est":0.47,"Priority":"HIGH"},{"Formulation":"C12-200-DOPE-PEG","Size_nm":103,"Zeta_mV":-5.2,"CSF_protein":"Albumin (low)","ApoE_pct":9.8,"BBB_est":0.33,"Priority":"MEDIUM"},{"Formulation":"DODAP-DSPC-Chol","Size_nm":118,"Zeta_mV":-2.1,"CSF_protein":"Transferrin","ApoE_pct":7.2,"BBB_est":0.24,"Priority":"LOW"},]UVM_VARIANTS = [{"Variant":"GNAQ p.Q209L","Freq_pct":46,"Pathway":"PLCβ → PKC → MAPK","Drug_status":"Darovasertib (clinical)","m6A_writer":"METTL3 upregulated"},{"Variant":"GNA11 p.Q209L","Freq_pct":32,"Pathway":"PLCβ → PKC → MAPK","Drug_status":"Darovasertib (clinical)","m6A_writer":"WTAP upregulated"},{"Variant":"BAP1 loss","Freq_pct":47,"Pathway":"Chromatin remodeling → metastasis","Drug_status":"No approved (HDAC trials)","m6A_writer":"FTO overexpressed"},{"Variant":"SF3B1 p.R625H","Freq_pct":19,"Pathway":"Splicing alteration → neoepitopes","Drug_status":"H3B-8800 (clinical)","m6A_writer":"METTL14 altered"},{"Variant":"EIF1AX p.A113_splice","Freq_pct":14,"Pathway":"Translation initiation","Drug_status":"Novel — no drug","m6A_writer":"YTHDF2 suppressed"},]UVM_VITREOUS_LNP = [{"Formulation":"SM-102-DSPC-Chol-PEG","Vitreal_protein":"Hyaluronan-binding","Size_nm":95,"Zeta_mV":-3.2,"Retention_h":18,"Priority":"HIGH"},{"Formulation":"Lipid-H-DOPE-PEG","Vitreal_protein":"Vitronectin dominant","Size_nm":88,"Zeta_mV":-4.0,"Retention_h":22,"Priority":"HIGH"},{"Formulation":"DOTAP-DSPC-PEG","Vitreal_protein":"Albumin wash-out","Size_nm":112,"Zeta_mV":+2.1,"Retention_h":6,"Priority":"LOW"},{"Formulation":"MC3-DPPC-Chol","Vitreal_protein":"Clusterin-rich","Size_nm":101,"Zeta_mV":-2.8,"Retention_h":14,"Priority":"MEDIUM"},]PAML_VARIANTS = [{"Variant":"FLT3-ITD","Freq_pct":25,"Pathway":"RTK constitutive activation → JAK/STAT","Drug_status":"Midostaurin (approved)","Ferroptosis":"GPX4 suppressed"},{"Variant":"NPM1 c.860_863dupTCAG","Freq_pct":30,"Pathway":"Nuclear export deregulation","Drug_status":"APR-548 combo (clinical)","Ferroptosis":"SLC7A11 upregulated"},{"Variant":"DNMT3A p.R882H","Freq_pct":18,"Pathway":"Epigenetic dysregulation","Drug_status":"Azacitidine (approved)","Ferroptosis":"ACSL4 altered"},{"Variant":"CEBPA biallelic","Freq_pct":8,"Pathway":"Myeloid differentiation block","Drug_status":"Novel target","Ferroptosis":"NRF2 pathway"},{"Variant":"IDH1/2 mutation","Freq_pct":15,"Pathway":"2-HG oncometabolite → TET2 inhibition","Drug_status":"Enasidenib (approved)","Ferroptosis":"Iron metabolism disrupted"},]PAML_BM_LNP = [{"Formulation":"ALC-0315-DSPC-Chol-PEG","BM_protein":"ApoE + Clusterin","Size_nm":98,"Zeta_mV":-3.5,"Marrow_uptake_pct":34,"Priority":"HIGH"},{"Formulation":"MC3-DOPE-Chol-PEG","BM_protein":"Fibronectin dominant","Size_nm":105,"Zeta_mV":-4.2,"Marrow_uptake_pct":28,"Priority":"HIGH"},{"Formulation":"DLin-MC3-DPPC","BM_protein":"Vitronectin-rich","Size_nm":91,"Zeta_mV":-2.9,"Marrow_uptake_pct":19,"Priority":"MEDIUM"},{"Formulation":"Cationic-DOTAP-Chol","BM_protein":"Opsonin-heavy","Size_nm":132,"Zeta_mV":+8.1,"Marrow_uptake_pct":8,"Priority":"LOW"},]def dipg_variants(sort_by):df = pd.DataFrame(DIPG_VARIANTS).sort_values(2 unmodified linesreturn dfdef dipg_csf(peg, size):df = pd.DataFrame(DIPG_CSF_LNP)df["Score"] = df["ApoE_pct"]/40 + df["BBB_est"] - abs(df["Size_nm"]-size)/200df = df.sort_values("Score", ascending=False)fig, ax = plt.subplots(figsize=(6, 3), facecolor=CARD)ax.set_facecolor(CARD)colors = [GRN if p=="HIGH" else ACC if p=="MEDIUM" else RED for p in df["Priority"]]ax.barh(df["Formulation"], df["ApoE_pct"], color=colors)ax.set_xlabel("ApoE% in CSF corona", color=TXT)ax.tick_params(colors=TXT, labelsize=8)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("DIPG — CSF LNP formulations (ApoE%)", color=TXT, fontsize=9)plt.tight_layout()buf = BytesIO(); plt.savefig(buf, format="png", dpi=120, facecolor=CARD); plt.close(); buf.seek(0)log_entry("S1-F · R1a · DIPG CSF", f"peg={peg},size={size}", "formulation ranking")return df[["Formulation","Size_nm","Zeta_mV","ApoE_pct","BBB_est","Priority"]], Image.open(buf)def uvm_variants():df = pd.DataFrame(UVM_VARIANTS)1 unmodified linereturn dfdef uvm_vitreous():df = pd.DataFrame(UVM_VITREOUS_LNP)fig, ax = plt.subplots(figsize=(6, 3), facecolor=CARD)ax.set_facecolor(CARD)colors = [GRN if p=="HIGH" else ACC if p=="MEDIUM" else RED for p in df["Priority"]]ax.barh(df["Formulation"], df["Retention_h"], color=colors)ax.set_xlabel("Vitreous retention (hours)", color=TXT)ax.tick_params(colors=TXT, labelsize=8)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("UVM — LNP retention in vitreous humor", color=TXT, fontsize=9)plt.tight_layout()buf = BytesIO(); plt.savefig(buf, format="png", dpi=120, facecolor=CARD); plt.close(); buf.seek(0)log_entry("S1-F · R2a · UVM Vitreous", "load", "vitreous LNP ranking")return df, Image.open(buf)def paml_ferroptosis(variant):row = next((r for r in PAML_VARIANTS if variant in r["Variant"]), PAML_VARIANTS[0])ferr_map = {"GPX4 suppressed": 0.85, "SLC7A11 upregulated": 0.72,"ACSL4 altered": 0.61, "NRF2 pathway": 0.55, "Iron metabolism disrupted": 0.78}ferr_score = ferr_map.get(row["Ferroptosis"], 0.5)cats = ["Ferroptosis\nsensitivity", "Drug\navailable", "BM niche\ncoverage", "Data\nmaturity", "Target\nnovelty"]has_drug = 0.9 if row["Drug_status"] not in ["Novel target"] else 0.3vals = [ferr_score, has_drug, 0.6, 0.55, 1-has_drug+0.2]angles = np.linspace(0, 2*np.pi, len(cats), endpoint=False).tolist()v2, a2 = vals+[vals[0]], angles+[angles[0]]fig, ax = plt.subplots(figsize=(5, 4), subplot_kw={"polar":True}, facecolor=CARD)ax.set_facecolor(CARD)ax.plot(a2, v2, color=ACC2, linewidth=2); ax.fill(a2, v2, color=ACC2, alpha=0.2)ax.set_xticks(angles); ax.set_xticklabels(cats, color=TXT, fontsize=8)ax.tick_params(colors=TXT)ax.set_title(f"pAML · {row['Variant'][:20]}", color=TXT, fontsize=9)plt.tight_layout()buf = BytesIO(); plt.savefig(buf, format="png", dpi=120, facecolor=CARD); plt.close(); buf.seek(0)log_entry("S1-F · R3a · pAML", variant, f"ferr={ferr_score:.2f}")_v = row["Variant"]_p = row["Pathway"]_d = row["Drug_status"]_f = row["Ferroptosis"]_fs = f"{ferr_score:.2f}"summary = (f"<div style='background:{CARD};padding:14px;border-radius:8px;font-family:sans-serif;'>"f"<p style='color:{DIM};font-size:11px;margin:0 0 6px'>S1-F · R3a · pAML</p>"f"<b style='color:{ACC2};font-size:15px'>{_v}</b><br>"f"<p style='color:{TXT};margin:6px 0'><b>Pathway:</b> {_p}</p>"f"<p style='color:{TXT};margin:0'><b>Drug:</b> {_d}</p>"f"<p style='color:{TXT};margin:6px 0'><b>Ferroptosis link:</b> {_f}</p>"f"<p style='color:{TXT}'><b>Ferroptosis sensitivity score:</b> "f"<span style='color:{ACC};font-size:18px'>{_fs}</span></p>"f"<p style='font-size:11px;color:{DIM}'>Research only. Not clinical advice.</p></div>")return summary, Image.open(buf)# ========== ДОПОМІЖНІ ФУНКЦІЇ ==========def section_header(code, name, tagline, projects_html):19 unmodified linesf"</div>")# ========== CSS ==========css = f"""body, .gradio-container {{ background: {BG} !important; color: {TXT} !important; }}86 unmodified lineswith gr.TabItem("🗺️ Lab Map"):gr.HTML(MAP_HTML)# === АКТИВНІ ВКЛАДКИ (працюють) ===with gr.TabItem("S1-A · R1a · OpenVariant"):gr.HTML(proj_badge("S1-A · R1a", "OpenVariant — SNV Pathogenicity Classifier", "AUC = 0.939"))hgvs = gr.Textbox(label="HGVS notation", placeholder="BRCA1:p.R1699Q")9 unmodified lines["BRCA2:p.D2723A",0.01,0.98,0.0]], inputs=[hgvs,sift,pp,gn], cache_examples=False)b_v.click(predict_variant, [hgvs,sift,pp,gn], o_v)# === ВСІ ІНШІ ВКЛАДКИ ЗАКОМЕНТОВАНІ ===# Розкоментуйте блок цілком, щоб перевірити, чи викликає помилку# =============================================================================# === START: S1-A · R1b · Somatic Classifier 🔶 ===============================# =============================================================================with gr.TabItem("S1-A · R1b · Somatic Classifier 🔶"):gr.HTML(proj_badge("S1-A · R1b", "Somatic Mutation Classifier", "🔶 In progress"))gr.Markdown("> This module is in active development. Coming in the next release.")# =============================================================================# === END: S1-A · R1b =========================================================# =============================================================================# =============================================================================# === START: S1-B · R1a · BRCA2 miRNA ========================================# =============================================================================with gr.TabItem("S1-B · R1a · BRCA2 miRNA"):gr.HTML(proj_badge("S1-B · R1a", "miRNA Silencing — BRCA1/2 · TP53"))g1 = gr.Dropdown(["BRCA2","BRCA1","TP53"], value="BRCA2", label="Gene")1 unmodified lineo1 = gr.Dataframe(label="Top 5 downregulated miRNAs")gr.Examples([["BRCA2"],["BRCA1"],["TP53"]], inputs=[g1])b1.click(predict_mirna, [g1], o1)# =============================================================================# === END: S1-B · R1a =========================================================# =============================================================================# =============================================================================# === START: S1-B · R2a · TP53 siRNA =========================================# =============================================================================with gr.TabItem("S1-B · R2a · TP53 siRNA"):gr.HTML(proj_badge("S1-B · R2a", "siRNA Synthetic Lethal — TP53-null"))g2 = gr.Dropdown(["LUAD","BRCA","COAD"], value="LUAD", label="Cancer type")1 unmodified lineo2 = gr.Dataframe(label="Top 5 synthetic lethal targets")gr.Examples([["LUAD"],["BRCA"],["COAD"]], inputs=[g2], cache_examples=False)b2.click(predict_sirna, [g2], o2)# =============================================================================# === END: S1-B · R2a =========================================================# =============================================================================# =============================================================================# === START: S1-B · R3a · lncRNA-TREM2 =======================================# =============================================================================with gr.TabItem("S1-B · R3a · lncRNA-TREM2"):gr.HTML(proj_badge("S1-B · R3a", "lncRNA-TREM2 ceRNA Network"))b3 = gr.Button("Load Network", variant="primary")o3 = gr.Dataframe(label="ceRNA Network")b3.click(get_lncrna, [], o3)# =============================================================================# === END: S1-B · R3a =========================================================# =============================================================================# =============================================================================# === START: S1-B · R3b · ASO Designer =======================================# =============================================================================with gr.TabItem("S1-B · R3b · ASO Designer"):gr.HTML(proj_badge("S1-B · R3b", "ASO Candidates"))b4 = gr.Button("Show ASOs", variant="primary")o4 = gr.Dataframe(label="ASO Candidates")b4.click(get_aso, [], o4)# =============================================================================# === END: S1-B · R3b =========================================================# =============================================================================# =============================================================================# === START: S1-C · R1a · FGFR3 RNA Drug ===================================== оце# =============================================================================# with gr.TabItem("S1-C · R1a · FGFR3 RNA Drug"):# gr.HTML(proj_badge("S1-C · R1a", "FGFR3 RNA-Directed Drug Discovery", "top score 0.793"))# g4 = gr.Radio(["P1 (hairpin loop)","P10 (G-quadruplex)"],# value="P1 (hairpin loop)", label="Target pocket")# b4 = gr.Button("Screen Compounds", variant="primary")# o4t = gr.Dataframe(label="Top 5 candidates")# o4p = gr.Image(label="Binding scores")# gr.Examples([["P1 (hairpin loop)"],["P10 (G-quadruplex)"]], inputs=[g4])# b4.click(predict_drug, [g4], [o4t, o4p])# =============================================================================# === END: S1-C · R1a =========================================================# =============================================================================# =============================================================================# === START: S1-C · R1b · SL Drug Mapping 🔶 =================================# =============================================================================with gr.TabItem("S1-C · R1b · SL Drug Mapping 🔶"):gr.HTML(proj_badge("S1-C · R1b", "Synthetic Lethal Drug Mapping", "🔶 In progress"))gr.Markdown("> Coming soon.")# =============================================================================# === END: S1-C · R1b =========================================================# =============================================================================# =============================================================================# === START: S1-C · R2a · Frontier 🔴 ========================================# =============================================================================with gr.TabItem("S1-C · R2a · Frontier 🔴"):gr.HTML(proj_badge("S1-C · R2a", "m6A × Ferroptosis × Circadian", "🔴 Frontier"))gr.Markdown("> Planned for Q3 2026")# =============================================================================# === END: S1-C · R2a =========================================================# =============================================================================# =============================================================================# === START: S1-D · R1a · LNP Corona =========================================# =============================================================================with gr.TabItem("S1-D · R1a · LNP Corona"):gr.HTML(proj_badge("S1-D · R1a", "LNP Protein Corona (Serum)", "AUC = 0.791"))with gr.Row():6 unmodified lineso6 = gr.Markdown()gr.Examples([[100,-5,1.5,"Ionizable"],[80,5,0.5,"Cationic"]], inputs=[sz,zt,pg,lp])b6.click(predict_corona, [sz,zt,pg,lp], o6)# =============================================================================# === END: S1-D · R1a =========================================================# =============================================================================# =============================================================================# === START: S1-D · R2a · Flow Corona ========================================# =============================================================================# with gr.TabItem("S1-D · R2a · Flow Corona"):# gr.HTML(proj_badge("S1-D · R2a", "Flow Corona — Vroman Effect"))# with gr.Row():# s8 = gr.Slider(50,300,value=100,step=1,label="Size (nm)")# z8 = gr.Slider(-40,10,value=-5,step=1,label="Zeta (mV)")# pg8 = gr.Slider(0,5,value=1.5,step=0.1,label="PEG mol%")# with gr.Row():# ch8 = gr.Dropdown(["Ionizable","Cationic","Anionic","Neutral"],value="Ionizable",label="Charge")# fl8 = gr.Slider(0,40,value=20,step=1,label="Flow cm/s")# b8 = gr.Button("Model Vroman Effect", variant="primary")# o8t = gr.Markdown(); o8p = gr.Image(label="Kinetics")# gr.Examples([[100,-5,1.5,"Ionizable",40],[150,5,0.5,"Cationic",10]], inputs=[s8,z8,pg8,ch8,fl8])# b8.click(predict_flow, [s8,z8,pg8,ch8,fl8], [o8t,o8p])# =============================================================================# === END: S1-D · R2a =========================================================# =============================================================================# =============================================================================# === START: S1-D · R3a · LNP Brain ========================================== оце# =============================================================================# with gr.TabItem("S1-D · R3a · LNP Brain"):# gr.HTML(proj_badge("S1-D · R3a", "LNP Brain Delivery — ApoE% + BBB probability"))# smi = gr.Textbox(label="Ionizable lipid SMILES",# value="CC(C)CC(=O)OCC(COC(=O)CC(C)C)OC(=O)CC(C)C")# with gr.Row():# pk = gr.Slider(4,8,value=6.5,step=0.1,label="pKa")# zt9 = gr.Slider(-20,10,value=-3,step=1,label="Zeta (mV)")# b9 = gr.Button("Predict BBB Crossing", variant="primary")# o9t = gr.Markdown(); o9p = gr.Image(label="Radar profile")# gr.Examples([["CC(C)CC(=O)OCC(COC(=O)CC(C)C)OC(=O)CC(C)C",6.5,-3]], inputs=[smi,pk,zt9])# b9.click(predict_bbb, [smi,pk,zt9], [o9t,o9p])# =============================================================================# === END: S1-D · R3a =========================================================# =============================================================================# =============================================================================# === START: S1-D · R4a · AutoCorona NLP =====================================# =============================================================================# with gr.TabItem("S1-D · R4a · AutoCorona NLP"):# gr.HTML(proj_badge("S1-D · R4a", "AutoCorona NLP — from abstracts", "F1 = 0.71"))# txt = gr.Textbox(lines=5,label="Paper abstract",placeholder="Paste abstract here...")# b10 = gr.Button("Extract Data", variant="primary")# o10j = gr.Code(label="Extracted JSON", language="json")# o10f = gr.Textbox(label="Validation flags")# gr.Examples([[# "LNPs composed of MC3, DSPC, Cholesterol (50:10:40 mol%) with 1.5% PEG-DMG. "# "Hydrodynamic diameter was 98 nm, zeta potential -3.2 mV, PDI 0.12. "# "Incubated in human plasma. Corona: albumin, apolipoprotein E, fibrinogen."# ]], inputs=[txt])# b10.click(extract_corona, txt, [o10j, o10f])# =============================================================================# === END: S1-D · R4a =========================================================# =============================================================================# =============================================================================# === START: S1-D · R5a · CSF/BM 🔴 ==========================================# =============================================================================with gr.TabItem("S1-D · R5a · CSF/BM 🔴"):gr.HTML(proj_badge("S1-D · R5a", "LNP Corona in CSF · Vitreous · Bone Marrow", "🔴 0 prior studies"))gr.Markdown("> Planned for Q2–Q3 2026")# =============================================================================# === END: S1-D · R5a =========================================================# =============================================================================# =============================================================================# === START: S1-E · R1a · Liquid Biopsy ====================================== оце# =============================================================================# with gr.TabItem("S1-E · R1a · Liquid Biopsy"):# gr.HTML(proj_badge("S1-E · R1a", "Liquid Biopsy Classifier", "AUC = 0.992*"))# with gr.Row():# p1=gr.Slider(-3,3,value=0,step=0.1,label="CTHRC1")# p2=gr.Slider(-3,3,value=0,step=0.1,label="FHL2")# p3=gr.Slider(-3,3,value=0,step=0.1,label="LDHA")# p4=gr.Slider(-3,3,value=0,step=0.1,label="P4HA1")# p5=gr.Slider(-3,3,value=0,step=0.1,label="SERPINH1")# with gr.Row():# p6=gr.Slider(-3,3,value=0,step=0.1,label="ABCA8")# p7=gr.Slider(-3,3,value=0,step=0.1,label="CA4")# p8=gr.Slider(-3,3,value=0,step=0.1,label="CKB")# p9=gr.Slider(-3,3,value=0,step=0.1,label="NNMT")# p10=gr.Slider(-3,3,value=0,step=0.1,label="CACNA2D2")# b7=gr.Button("Classify", variant="primary")# o7t=gr.HTML(); o7p=gr.Image(label="Feature contributions")# gr.Examples([[2,2,1.5,1.8,1.6,-1,-1.2,-0.8,1.4,-1.1],[0]*10],# inputs=[p1,p2,p3,p4,p5,p6,p7,p8,p9,p10])# b7.click(predict_cancer, [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10], [o7t,o7p])# =============================================================================# === END: S1-E · R1a =========================================================# =============================================================================# =============================================================================# === START: S1-E · R1b · Validator 🔶 =======================================# =============================================================================with gr.TabItem("S1-E · R1b · Validator 🔶"):gr.HTML(proj_badge("S1-E · R1b", "Protein Panel Validator", "🔶 In progress"))gr.Markdown("> Coming next.")# =============================================================================# === END: S1-E · R1b =========================================================# =============================================================================# =============================================================================# === START: S1-F · R1a · DIPG Toolkit ======================================= оце# =============================================================================# with gr.TabItem("S1-F · R1a · DIPG Toolkit"):# gr.HTML(proj_badge("S1-F · R1a", "DIPG: H3K27M + CSF LNP + Circadian", "PBTA"))# sort_d = gr.Radio(["Frequency", "Drug status"], value="Frequency", label="Sort by")# b_dv = gr.Button("Load DIPG Variants", variant="primary")# o_dv = gr.Dataframe(label="H3K27M co-mutations")# b_dv.click(dipg_variants, [sort_d], o_dv)# gr.Markdown("---")# with gr.Row():# d_peg = gr.Slider(0.5, 3.0, value=1.5, step=0.1, label="PEG mol%")# d_size = gr.Slider(60, 150, value=90, step=5, label="Target size (nm)")# b_dc = gr.Button("Rank CSF Formulations", variant="primary")# o_dct = gr.Dataframe(label="CSF LNP ranking")# o_dcp = gr.Image(label="ApoE% in CSF corona")# b_dc.click(dipg_csf, [d_peg, d_size], [o_dct, o_dcp])# =============================================================================# === END: S1-F · R1a =========================================================# =============================================================================# =============================================================================# === START: S1-F · R2a · UVM Toolkit ======================================== оце# =============================================================================# with gr.TabItem("S1-F · R2a · UVM Toolkit"):# gr.HTML(proj_badge("S1-F · R2a", "UVM: GNAQ/GNA11 + vitreous + m6A", "TCGA-UVM"))# b_uv = gr.Button("Load UVM Variants", variant="primary")# o_uv = gr.Dataframe(label="GNAQ/GNA11 map")# b_uv.click(uvm_variants, [], o_uv)# b_uw = gr.Button("Rank Vitreous Formulations", variant="primary")# o_uwt = gr.Dataframe(label="Vitreous LNP retention ranking")# o_uwp = gr.Image(label="Retention (hours)")# b_uw.click(uvm_vitreous, [], [o_uwt, o_uwp])# =============================================================================# === END: S1-F · R2a =========================================================# =============================================================================# =============================================================================# === START: S1-F · R3a · pAML Toolkit ======================================= оце# =============================================================================# with gr.TabItem("S1-F · R3a · pAML Toolkit"):# gr.HTML(proj_badge("S1-F · R3a", "pAML: FLT3-ITD + BM niche + ferroptosis", "TARGET-AML"))# var_sel = gr.Dropdown(# ["FLT3-ITD", "NPM1 c.860_863dupTCAG", "DNMT3A p.R882H",# "CEBPA biallelic", "IDH1/2 mutation"],# value="FLT3-ITD", label="Select variant"# )# b_pf = gr.Button("Analyze Ferroptosis Profile", variant="primary")# o_pft = gr.HTML()# o_pfp = gr.Image(label="Target radar")# b_pf.click(paml_ferroptosis, var_sel, [o_pft, o_pfp])# =============================================================================# === END: S1-F · R3a =========================================================# =============================================================================# 📓 Journalwith gr.TabItem("📓 Journal"):gr.Markdown("### Lab Journal")with gr.Row():note_text = gr.Textbox(label="📝 Observation", placeholder="What did you discover?", lines=3)note_tab = gr.Textbox(label="Project code (e.g. S1-A·R1a)", value="General")note_last = gr.Textbox(visible=False)save_btn = gr.Button("💾 Save", variant="primary")save_msg = gr.Markdown()journal_df = gr.Dataframe(label="📋 Full History", value=load_journal(), interactive=False)refresh_btn = gr.Button("🔄 Refresh")refresh_btn.click(load_journal, [], journal_df)save_btn.click(save_note, [note_text,note_tab,note_last], [save_msg,journal_df])# 📚 Learningwith gr.TabItem("📚 Learning"):gr.Markdown("""## 🧪 Guided Investigations4 unmodified lines**S1-D · R2a** Flow Corona – compare flow 0 vs 40 cm/s**S1-B · R2a** siRNA – count "Novel" targets across cancer types**S1-E · R1a** Liquid Biopsy – find minimal signal for CANCER... (more cases)""")gr.Markdown(8 unmodified lines91011121314151628 unmodified lines4546474849505152535455565758596061626364656667686996 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923013 unmodified lines24424524624724824925025125225325425525625725825926026126226326426526626722 unmodified lines2902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084092 unmodified lines4124134144154164174184194204214224234244254264274284294304314324334344351 unmodified line43743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749819 unmodified lines51851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659786 unmodified lines6846856866876886896909 unmodified lines7007017027037047057067077087097101 unmodified line7127137147157167177181 unmodified line7207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587596 unmodified lines7667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319324 unmodified lines9379389399409419429438 unmodified linesfrom PIL import Imagefrom datetime import datetimefrom pathlib import Pathimport plotly.graph_objects as goimport plotly.express as px# ========== Діагностичний друк ==========print("Gradio version:", gr.__version__)28 unmodified linestry:if not LOG_PATH.exists():return pd.DataFrame(columns=["timestamp","tab","inputs","result","note"])df = pd.read_csv(LOG_PATH)# Convert to markdown for nice displayif df.empty:return "No entries yet."return df.tail(20).to_markdown(index=False)except Exception:return "Error loading journal."def save_note(note, tab):log_entry(tab, "manual note", note, note)return load_journal()def clear_journal():try:if LOG_PATH.exists():LOG_PATH.unlink()return "Journal cleared."except Exception:return "Error clearing journal."# ========== БАЗИ ДАНИХ ==========MIRNA_DB = {96 unmodified lines"clusterin","igm","iga","igg","complement","transferrin","alpha-2-macroglobulin"]# ---------- S1-F RARE ----------DIPG_VARIANTS = [{"Variant":"H3K27M (H3F3A)","Freq_pct":78,"Pathway":"PRC2 inhibition → global H3K27me3 loss","Drug_status":"ONC201 (clinical)","Circadian_gene":"BMAL1 suppressed"},{"Variant":"ACVR1 p.R206H","Freq_pct":21,"Pathway":"BMP/SMAD hyperactivation","Drug_status":"LDN-193189 (preclinical)","Circadian_gene":"PER1 disrupted"},{"Variant":"PIK3CA p.H1047R","Freq_pct":15,"Pathway":"PI3K/AKT/mTOR","Drug_status":"Copanlisib (clinical)","Circadian_gene":"CRY1 altered"},{"Variant":"TP53 p.R248W","Freq_pct":14,"Pathway":"DNA damage response loss","Drug_status":"APR-246 (clinical)","Circadian_gene":"p53-CLOCK axis"},{"Variant":"PDGFRA amp","Freq_pct":13,"Pathway":"RTK/RAS signalling","Drug_status":"Avapritinib (clinical)","Circadian_gene":"REV-ERB altered"},]DIPG_CSF_LNP = [{"Formulation":"MC3-DSPC-Chol-PEG","Size_nm":92,"Zeta_mV":-4.1,"CSF_protein":"Beta2-microglobulin","ApoE_pct":12.4,"BBB_est":0.41,"Priority":"HIGH"},{"Formulation":"DLin-KC2-DSPE-PEG","Size_nm":87,"Zeta_mV":-3.8,"CSF_protein":"Cystatin C","ApoE_pct":14.1,"BBB_est":0.47,"Priority":"HIGH"},{"Formulation":"C12-200-DOPE-PEG","Size_nm":103,"Zeta_mV":-5.2,"CSF_protein":"Albumin (low)","ApoE_pct":9.8,"BBB_est":0.33,"Priority":"MEDIUM"},{"Formulation":"DODAP-DSPC-Chol","Size_nm":118,"Zeta_mV":-2.1,"CSF_protein":"Transferrin","ApoE_pct":7.2,"BBB_est":0.24,"Priority":"LOW"},]UVM_VARIANTS = [{"Variant":"GNAQ p.Q209L","Freq_pct":46,"Pathway":"PLCβ → PKC → MAPK","Drug_status":"Darovasertib (clinical)","m6A_writer":"METTL3 upregulated"},{"Variant":"GNA11 p.Q209L","Freq_pct":32,"Pathway":"PLCβ → PKC → MAPK","Drug_status":"Darovasertib (clinical)","m6A_writer":"WTAP upregulated"},{"Variant":"BAP1 loss","Freq_pct":47,"Pathway":"Chromatin remodeling → metastasis","Drug_status":"No approved (HDAC trials)","m6A_writer":"FTO overexpressed"},{"Variant":"SF3B1 p.R625H","Freq_pct":19,"Pathway":"Splicing alteration → neoepitopes","Drug_status":"H3B-8800 (clinical)","m6A_writer":"METTL14 altered"},{"Variant":"EIF1AX p.A113_splice","Freq_pct":14,"Pathway":"Translation initiation","Drug_status":"Novel — no drug","m6A_writer":"YTHDF2 suppressed"},]UVM_VITREOUS_LNP = [{"Formulation":"SM-102-DSPC-Chol-PEG","Vitreal_protein":"Hyaluronan-binding","Size_nm":95,"Zeta_mV":-3.2,"Retention_h":18,"Priority":"HIGH"},{"Formulation":"Lipid-H-DOPE-PEG","Vitreal_protein":"Vitronectin dominant","Size_nm":88,"Zeta_mV":-4.0,"Retention_h":22,"Priority":"HIGH"},{"Formulation":"DOTAP-DSPC-PEG","Vitreal_protein":"Albumin wash-out","Size_nm":112,"Zeta_mV":+2.1,"Retention_h":6,"Priority":"LOW"},{"Formulation":"MC3-DPPC-Chol","Vitreal_protein":"Clusterin-rich","Size_nm":101,"Zeta_mV":-2.8,"Retention_h":14,"Priority":"MEDIUM"},]PAML_VARIANTS = [{"Variant":"FLT3-ITD","Freq_pct":25,"Pathway":"RTK constitutive activation → JAK/STAT","Drug_status":"Midostaurin (approved)","Ferroptosis":"GPX4 suppressed"},{"Variant":"NPM1 c.860_863dupTCAG","Freq_pct":30,"Pathway":"Nuclear export deregulation","Drug_status":"APR-548 combo (clinical)","Ferroptosis":"SLC7A11 upregulated"},{"Variant":"DNMT3A p.R882H","Freq_pct":18,"Pathway":"Epigenetic dysregulation","Drug_status":"Azacitidine (approved)","Ferroptosis":"ACSL4 altered"},{"Variant":"CEBPA biallelic","Freq_pct":8,"Pathway":"Myeloid differentiation block","Drug_status":"Novel target","Ferroptosis":"NRF2 pathway"},{"Variant":"IDH1/2 mutation","Freq_pct":15,"Pathway":"2-HG oncometabolite → TET2 inhibition","Drug_status":"Enasidenib (approved)","Ferroptosis":"Iron metabolism disrupted"},]PAML_BM_LNP = [{"Formulation":"ALC-0315-DSPC-Chol-PEG","BM_protein":"ApoE + Clusterin","Size_nm":98,"Zeta_mV":-3.5,"Marrow_uptake_pct":34,"Priority":"HIGH"},{"Formulation":"MC3-DOPE-Chol-PEG","BM_protein":"Fibronectin dominant","Size_nm":105,"Zeta_mV":-4.2,"Marrow_uptake_pct":28,"Priority":"HIGH"},{"Formulation":"DLin-MC3-DPPC","BM_protein":"Vitronectin-rich","Size_nm":91,"Zeta_mV":-2.9,"Marrow_uptake_pct":19,"Priority":"MEDIUM"},{"Formulation":"Cationic-DOTAP-Chol","BM_protein":"Opsonin-heavy","Size_nm":132,"Zeta_mV":+8.1,"Marrow_uptake_pct":8,"Priority":"LOW"},]# ========== ФУНКЦІЇ ПРЕДИКЦІЇ (з обробкою помилок) ==========def safe_img_from_fig(fig):"""Convert matplotlib figure to PIL Image safely."""try:buf = BytesIO()fig.savefig(buf, format="png", dpi=120, facecolor=CARD)buf.seek(0)img = Image.open(buf)plt.close(fig)return imgexcept Exception:plt.close(fig)# Return a blank image as fallbackreturn Image.new('RGB', (100, 100), color=CARD)def predict_mirna(gene):df = pd.DataFrame(MIRNA_DB.get(gene, []))log_entry("S1-B · R1a · miRNA", gene, f"{len(df)} miRNAs")13 unmodified linesreturn pd.DataFrame(ASO)def predict_drug(pocket):try:df = pd.DataFrame(FGFR3.get(pocket, []))if df.empty:return pd.DataFrame(), Nonefig, ax = plt.subplots(figsize=(6, 4), facecolor=CARD)ax.set_facecolor(CARD)ax.barh(df["Compound"], df["Final_score"], color=ACC)ax.set_xlabel("Final Score", color=TXT)ax.tick_params(colors=TXT)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title(f"Top compounds — {pocket}", color=TXT, fontsize=10)plt.tight_layout()img = safe_img_from_fig(fig)log_entry("S1-C · R1a · FGFR3", pocket, f"Top: {df.iloc[0]['Compound'] if len(df) else 'none'}")return df, imgexcept Exception as e:log_entry("S1-C · R1a · FGFR3", pocket, f"Error: {str(e)}")return pd.DataFrame(), Nonedef predict_variant(hgvs, sift, polyphen, gnomad):hgvs = hgvs.strip()22 unmodified lines)def predict_corona(size, zeta, peg, lipid):try:score = 0if lipid == "Ionizable": score += 2elif lipid == "Cationic": score += 1if abs(zeta) < 10: score += 1if peg > 1.5: score += 2if size < 100: score += 1dominant = ["ApoE","Albumin","Fibrinogen","Vitronectin","ApoA-I"][min(score, 4)]efficacy = "High" if score >= 4 else "Medium" if score >= 2 else "Low"log_entry("S1-D · R1a · Corona", f"size={size},peg={peg}", f"dominant={dominant}")return f"**Dominant corona protein:** {dominant}\n\n**Predicted efficacy:** {efficacy}\n\n**Score:** {score}/6"except Exception as e:return f"Error: {str(e)}"def predict_cancer(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10):try:vals = [c1,c2,c3,c4,c5,c6,c7,c8,c9,c10]names, weights = list(BM_W.keys()), list(BM_W.values())raw = sum(v*w for v,w in zip(vals, weights))prob = 1 / (1 + np.exp(-raw * 2))label = "CANCER" if prob > 0.5 else "HEALTHY"colour = RED if prob > 0.5 else GRNcontribs = [v*w for v,w in zip(vals, weights)]fig, ax = plt.subplots(figsize=(6, 3.5), facecolor=CARD)ax.set_facecolor(CARD)ax.barh(names, contribs, color=[ACC if c > 0 else ACC2 for c in contribs])ax.axvline(0, color=TXT, linewidth=0.8)ax.set_xlabel("Contribution to cancer score", color=TXT)ax.tick_params(colors=TXT, labelsize=8)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("Protein contributions", color=TXT, fontsize=10)plt.tight_layout()img = safe_img_from_fig(fig)log_entry("S1-E · R1a · Liquid Biopsy", f"CTHRC1={c1},FHL2={c2}", f"{label} {prob:.2f}")html_out = (f"<div style=\'background:{CARD};padding:14px;border-radius:8px;font-family:sans-serif;\'>"f"<p style=\'font-size:11px;color:{DIM};margin:0 0 6px\'>S1-E · R1a · Liquid Biopsy</p>"f"<span style=\'color:{colour};font-size:24px;font-weight:bold\'>{label}</span><br>"f"<span style=\'color:{TXT};font-size:14px\'>Probability: {prob:.2f}</span></div>")return html_out, imgexcept Exception as e:return f"<div style='color:{RED}'>Error: {str(e)}</div>", Nonedef predict_flow(size, zeta, peg, charge, flow_rate):try:csi = round(min((flow_rate/40)*0.6 + (peg/5)*0.2 + (1 if charge=="Cationic" else 0)*0.2, 1.0), 3)stability = "High remodeling" if csi > 0.6 else "Medium" if csi > 0.3 else "Stable"t = np.linspace(0, 60, 200)kf, ks = 0.03*(1+flow_rate/40), 0.038*(1+flow_rate/40)fig, ax = plt.subplots(figsize=(6, 3.5), facecolor=CARD)ax.set_facecolor(CARD)ax.plot(t, 60*np.exp(-0.03*t)+20, color="#60a5fa", ls="--", label="Albumin (static)")ax.plot(t, 60*np.exp(-kf*t)+10, color="#60a5fa", label="Albumin (flow)")ax.plot(t, 14*(1-np.exp(-0.038*t))+5, color=ACC, ls="--", label="ApoE (static)")ax.plot(t, 20*(1-np.exp(-ks*t))+5, color=ACC, label="ApoE (flow)")ax.set_xlabel("Time (min)", color=TXT); ax.set_ylabel("% Corona", color=TXT)ax.tick_params(colors=TXT); ax.legend(fontsize=7, labelcolor=TXT, facecolor=CARD)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("Vroman Effect — flow vs static", color=TXT, fontsize=9)plt.tight_layout()img = safe_img_from_fig(fig)log_entry("S1-D · R2a · Flow Corona", f"flow={flow_rate}", f"CSI={csi}")return f"**Corona Shift Index: {csi}** — {stability}", imgexcept Exception as e:return f"Error: {str(e)}", Nonedef predict_bbb(smiles, pka, zeta):try:logp = smiles.count("C")*0.3 - smiles.count("O")*0.5 + 1.5apoe_pct = max(0, min(40, (7.0-pka)*8 + abs(zeta)*0.5 + logp*0.8))bbb_prob = min(0.95, apoe_pct/30)tier = "HIGH (>20%)" if apoe_pct > 20 else "MEDIUM (10-20%)" if apoe_pct > 10 else "LOW (<10%)"cats = ["ApoE%","BBB","logP","pKa fit","Zeta"]vals = [apoe_pct/40, bbb_prob, min(logp/5,1), (7-abs(pka-6.5))/7, (10-abs(zeta))/10]angles = np.linspace(0, 2*np.pi, len(cats), endpoint=False).tolist()v2, a2 = vals+[vals[0]], angles+[angles[0]]fig, ax = plt.subplots(figsize=(5, 4), subplot_kw={"polar":True}, facecolor=CARD)ax.set_facecolor(CARD)ax.plot(a2, v2, color=ACC, linewidth=2); ax.fill(a2, v2, color=ACC, alpha=0.2)ax.set_xticks(angles); ax.set_xticklabels(cats, color=TXT, fontsize=8)ax.tick_params(colors=TXT)plt.tight_layout()img = safe_img_from_fig(fig)log_entry("S1-D · R3a · LNP Brain", f"pka={pka},zeta={zeta}", f"ApoE={apoe_pct:.1f}%")return f"**Predicted ApoE:** {apoe_pct:.1f}% — {tier}\n\n**BBB Probability:** {bbb_prob:.2f}", imgexcept Exception as e:return f"Error: {str(e)}", Nonedef extract_corona(text):try:out = {"nanoparticle_composition":"","size_nm":None,"zeta_mv":None,"PDI":None,"protein_source":"","corona_proteins":[],"confidence":{}}for pat, key in [(r"(\d+\.?\d*)\s*(?:nm|nanometer)","size_nm"),(r"([+-]?\d+\.?\d*)\s*mV","zeta_mv"),(r"PDI\s*[=:of]*\s*(\d+\.?\d*)","PDI")]:m = re.search(pat, text, re.I)if m: out[key] = float(m.group(1)); out["confidence"][key] = "HIGH"for src in ["human plasma","human serum","fetal bovine serum","FBS","PBS"]:if src.lower() in text.lower():out["protein_source"] = src; out["confidence"]["protein_source"] = "HIGH"; breakout["corona_proteins"] = [{"name":p,"confidence":"MEDIUM"} for p in PROTEINS if p in text.lower()]for lip in ["DSPC","DOPE","MC3","DLin","cholesterol","PEG","DOTAP"]:if lip in text: out["nanoparticle_composition"] += lip + " "out["nanoparticle_composition"] = out["nanoparticle_composition"].strip()flags = []if not out["size_nm"]: flags.append("size_nm not found")if not out["zeta_mv"]: flags.append("zeta_mv not found")if not out["corona_proteins"]: flags.append("no proteins detected")summary = "All key fields extracted" if not flags else " | ".join(flags)log_entry("S1-D · R4a · AutoCorona NLP", text[:80], f"proteins={len(out['corona_proteins'])}")return json.dumps(out, indent=2), summaryexcept Exception as e:return json.dumps({"error": str(e)}), "Extraction error"def dipg_variants(sort_by):df = pd.DataFrame(DIPG_VARIANTS).sort_values(2 unmodified linesreturn dfdef dipg_csf(peg, size):try:df = pd.DataFrame(DIPG_CSF_LNP)df["Score"] = df["ApoE_pct"]/40 + df["BBB_est"] - abs(df["Size_nm"]-size)/200df = df.sort_values("Score", ascending=False)fig, ax = plt.subplots(figsize=(6, 3), facecolor=CARD)ax.set_facecolor(CARD)colors = [GRN if p=="HIGH" else ACC if p=="MEDIUM" else RED for p in df["Priority"]]ax.barh(df["Formulation"], df["ApoE_pct"], color=colors)ax.set_xlabel("ApoE% in CSF corona", color=TXT)ax.tick_params(colors=TXT, labelsize=8)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("DIPG — CSF LNP formulations (ApoE%)", color=TXT, fontsize=9)plt.tight_layout()img = safe_img_from_fig(fig)log_entry("S1-F · R1a · DIPG CSF", f"peg={peg},size={size}", "formulation ranking")return df[["Formulation","Size_nm","Zeta_mV","ApoE_pct","BBB_est","Priority"]], imgexcept Exception as e:return pd.DataFrame(), Nonedef uvm_variants():df = pd.DataFrame(UVM_VARIANTS)1 unmodified linereturn dfdef uvm_vitreous():try:df = pd.DataFrame(UVM_VITREOUS_LNP)fig, ax = plt.subplots(figsize=(6, 3), facecolor=CARD)ax.set_facecolor(CARD)colors = [GRN if p=="HIGH" else ACC if p=="MEDIUM" else RED for p in df["Priority"]]ax.barh(df["Formulation"], df["Retention_h"], color=colors)ax.set_xlabel("Vitreous retention (hours)", color=TXT)ax.tick_params(colors=TXT, labelsize=8)for sp in ax.spines.values(): sp.set_edgecolor(BORDER)ax.set_title("UVM — LNP retention in vitreous humor", color=TXT, fontsize=9)plt.tight_layout()img = safe_img_from_fig(fig)log_entry("S1-F · R2a · UVM Vitreous", "load", "vitreous LNP ranking")return df, imgexcept Exception as e:return pd.DataFrame(), Nonedef paml_ferroptosis(variant):try:row = next((r for r in PAML_VARIANTS if variant in r["Variant"]), PAML_VARIANTS[0])ferr_map = {"GPX4 suppressed": 0.85, "SLC7A11 upregulated": 0.72,"ACSL4 altered": 0.61, "NRF2 pathway": 0.55, "Iron metabolism disrupted": 0.78}ferr_score = ferr_map.get(row["Ferroptosis"], 0.5)cats = ["Ferroptosis\nsensitivity", "Drug\navailable", "BM niche\ncoverage", "Data\nmaturity", "Target\nnovelty"]has_drug = 0.9 if row["Drug_status"] not in ["Novel target"] else 0.3vals = [ferr_score, has_drug, 0.6, 0.55, 1-has_drug+0.2]angles = np.linspace(0, 2*np.pi, len(cats), endpoint=False).tolist()v2, a2 = vals+[vals[0]], angles+[angles[0]]fig, ax = plt.subplots(figsize=(5, 4), subplot_kw={"polar":True}, facecolor=CARD)ax.set_facecolor(CARD)ax.plot(a2, v2, color=ACC2, linewidth=2); ax.fill(a2, v2, color=ACC2, alpha=0.2)ax.set_xticks(angles); ax.set_xticklabels(cats, color=TXT, fontsize=8)ax.tick_params(colors=TXT)ax.set_title(f"pAML · {row['Variant'][:20]}", color=TXT, fontsize=9)plt.tight_layout()img = safe_img_from_fig(fig)log_entry("S1-F · R3a · pAML", variant, f"ferr={ferr_score:.2f}")_v = row["Variant"]_p = row["Pathway"]_d = row["Drug_status"]_f = row["Ferroptosis"]_fs = f"{ferr_score:.2f}"summary = (f"<div style='background:{CARD};padding:14px;border-radius:8px;font-family:sans-serif;'>"f"<p style='color:{DIM};font-size:11px;margin:0 0 6px'>S1-F · R3a · pAML</p>"f"<b style='color:{ACC2};font-size:15px'>{_v}</b><br>"f"<p style='color:{TXT};margin:6px 0'><b>Pathway:</b> {_p}</p>"f"<p style='color:{TXT};margin:0'><b>Drug:</b> {_d}</p>"f"<p style='color:{TXT};margin:6px 0'><b>Ferroptosis link:</b> {_f}</p>"f"<p style='color:{TXT}'><b>Ferroptosis sensitivity score:</b> "f"<span style='color:{ACC};font-size:18px'>{_fs}</span></p>"f"<p style='font-size:11px;color:{DIM}'>Research only. Not clinical advice.</p></div>")return summary, imgexcept Exception as e:return f"<div style='color:{RED}'>Error: {str(e)}</div>", None# ========== ДОПОМІЖНІ ФУНКЦІЇ ==========def section_header(code, name, tagline, projects_html):19 unmodified linesf"</div>")# ========== 3D моделі (функції) ==========def plot_nanoparticle(r, peg):theta = np.linspace(0, 2*np.pi, 30)phi = np.linspace(0, np.pi, 30)theta, phi = np.meshgrid(theta, phi)x = r * np.sin(phi) * np.cos(theta)y = r * np.sin(phi) * np.sin(theta)z = r * np.cos(phi)fig = go.Figure(data=[go.Surface(x=x, y=y, z=z, colorscale='Blues', opacity=0.7)])if peg > 0:n_points = int(100 * peg)u = np.random.uniform(0, 1, n_points)v = np.random.uniform(0, 1, n_points)theta_pts = 2 * np.pi * uphi_pts = np.arccos(2*v - 1)x_pts = (r + 0.5) * np.sin(phi_pts) * np.cos(theta_pts)y_pts = (r + 0.5) * np.sin(phi_pts) * np.sin(theta_pts)z_pts = (r + 0.5) * np.cos(phi_pts)fig.add_scatter3d(x=x_pts, y=y_pts, z=z_pts, mode='markers',marker=dict(size=3, color='red'), name='PEG')fig.update_layout(title=f"Nanoparticle (r={r} nm, PEG={peg})",scene=dict(xaxis_title='X (nm)', yaxis_title='Y (nm)', zaxis_title='Z (nm)'),width=500, height=400)return figdef plot_dna():t = np.linspace(0, 4*np.pi, 200)x1 = np.cos(t)y1 = np.sin(t)z1 = tx2 = np.cos(t + np.pi)y2 = np.sin(t + np.pi)z2 = tfig = go.Figure()fig.add_scatter3d(x=x1, y=y1, z=z1, mode='lines', line=dict(color='blue', width=5), name='Strand 1')fig.add_scatter3d(x=x2, y=y2, z=z2, mode='lines', line=dict(color='red', width=5), name='Strand 2')for i in range(0, len(t), 10):fig.add_scatter3d(x=[x1[i], x2[i]], y=[y1[i], y2[i]], z=[z1[i], z2[i]],mode='lines', line=dict(color='gray', width=1), showlegend=False)fig.update_layout(title='DNA Double Helix',scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),width=500, height=400)return figdef plot_corona():r = 5theta = np.linspace(0, 2*np.pi, 20)phi = np.linspace(0, np.pi, 20)theta, phi = np.meshgrid(theta, phi)x = r * np.sin(phi) * np.cos(theta)y = r * np.sin(phi) * np.sin(theta)z = r * np.cos(phi)fig = go.Figure(data=[go.Surface(x=x, y=y, z=z, colorscale='Blues', opacity=0.5)])n_proteins = 50u = np.random.uniform(0, 1, n_proteins)v = np.random.uniform(0, 1, n_proteins)theta_pts = 2 * np.pi * uphi_pts = np.arccos(2*v - 1)x_pts = (r + 1.5) * np.sin(phi_pts) * np.cos(theta_pts)y_pts = (r + 1.5) * np.sin(phi_pts) * np.sin(theta_pts)z_pts = (r + 1.5) * np.cos(phi_pts)fig.add_scatter3d(x=x_pts, y=y_pts, z=z_pts, mode='markers',marker=dict(size=5, color='orange'), name='Proteins')fig.update_layout(title='Protein Corona',scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),width=500, height=400)return fig# ========== CSS ==========css = f"""body, .gradio-container {{ background: {BG} !important; color: {TXT} !important; }}86 unmodified lineswith gr.TabItem("🗺️ Lab Map"):gr.HTML(MAP_HTML)# === S1-A · PHYLO-GENOMICS ===with gr.TabItem("S1-A · R1a · OpenVariant"):gr.HTML(proj_badge("S1-A · R1a", "OpenVariant — SNV Pathogenicity Classifier", "AUC = 0.939"))hgvs = gr.Textbox(label="HGVS notation", placeholder="BRCA1:p.R1699Q")9 unmodified lines["BRCA2:p.D2723A",0.01,0.98,0.0]], inputs=[hgvs,sift,pp,gn], cache_examples=False)b_v.click(predict_variant, [hgvs,sift,pp,gn], o_v)with gr.TabItem("S1-A · R1b · Somatic Classifier 🔶"):gr.HTML(proj_badge("S1-A · R1b", "Somatic Mutation Classifier", "🔶 In progress"))gr.Markdown("> This module is in active development. Coming in the next release.")# === S1-B · PHYLO-RNA ===with gr.TabItem("S1-B · R1a · BRCA2 miRNA"):gr.HTML(proj_badge("S1-B · R1a", "miRNA Silencing — BRCA1/2 · TP53"))g1 = gr.Dropdown(["BRCA2","BRCA1","TP53"], value="BRCA2", label="Gene")1 unmodified lineo1 = gr.Dataframe(label="Top 5 downregulated miRNAs")gr.Examples([["BRCA2"],["BRCA1"],["TP53"]], inputs=[g1])b1.click(predict_mirna, [g1], o1)with gr.TabItem("S1-B · R2a · TP53 siRNA"):gr.HTML(proj_badge("S1-B · R2a", "siRNA Synthetic Lethal — TP53-null"))g2 = gr.Dropdown(["LUAD","BRCA","COAD"], value="LUAD", label="Cancer type")1 unmodified lineo2 = gr.Dataframe(label="Top 5 synthetic lethal targets")gr.Examples([["LUAD"],["BRCA"],["COAD"]], inputs=[g2], cache_examples=False)b2.click(predict_sirna, [g2], o2)with gr.TabItem("S1-B · R3a · lncRNA-TREM2"):gr.HTML(proj_badge("S1-B · R3a", "lncRNA-TREM2 ceRNA Network"))b3 = gr.Button("Load Network", variant="primary")o3 = gr.Dataframe(label="ceRNA Network")b3.click(get_lncrna, [], o3)with gr.TabItem("S1-B · R3b · ASO Designer"):gr.HTML(proj_badge("S1-B · R3b", "ASO Candidates"))b4 = gr.Button("Show ASOs", variant="primary")o4 = gr.Dataframe(label="ASO Candidates")b4.click(get_aso, [], o4)# === S1-C · PHYLO-DRUG ===# Розкоментовано проблемну вкладку "оце" - FGFR3with gr.TabItem("S1-C · R1a · FGFR3 RNA Drug"):gr.HTML(proj_badge("S1-C · R1a", "FGFR3 RNA-Directed Drug Discovery", "top score 0.793"))g4 = gr.Radio(["P1 (hairpin loop)","P10 (G-quadruplex)"],value="P1 (hairpin loop)", label="Target pocket")b4_drug = gr.Button("Screen Compounds", variant="primary")o4t = gr.Dataframe(label="Top 5 candidates")o4p = gr.Image(label="Binding scores")gr.Examples([["P1 (hairpin loop)"],["P10 (G-quadruplex)"]], inputs=[g4])b4_drug.click(predict_drug, [g4], [o4t, o4p])with gr.TabItem("S1-C · R1b · SL Drug Mapping 🔶"):gr.HTML(proj_badge("S1-C · R1b", "Synthetic Lethal Drug Mapping", "🔶 In progress"))gr.Markdown("> Coming soon.")with gr.TabItem("S1-C · R2a · Frontier 🔴"):gr.HTML(proj_badge("S1-C · R2a", "m6A × Ferroptosis × Circadian", "🔴 Frontier"))gr.Markdown("> Planned for Q3 2026")# === S1-D · PHYLO-LNP ===with gr.TabItem("S1-D · R1a · LNP Corona"):gr.HTML(proj_badge("S1-D · R1a", "LNP Protein Corona (Serum)", "AUC = 0.791"))with gr.Row():6 unmodified lineso6 = gr.Markdown()gr.Examples([[100,-5,1.5,"Ionizable"],[80,5,0.5,"Cationic"]], inputs=[sz,zt,pg,lp])b6.click(predict_corona, [sz,zt,pg,lp], o6)# Розкоментовано проблемну вкладку "оце" - Flow Coronawith gr.TabItem("S1-D · R2a · Flow Corona"):gr.HTML(proj_badge("S1-D · R2a", "Flow Corona — Vroman Effect"))with gr.Row():s8 = gr.Slider(50,300,value=100,step=1,label="Size (nm)")z8 = gr.Slider(-40,10,value=-5,step=1,label="Zeta (mV)")pg8 = gr.Slider(0,5,value=1.5,step=0.1,label="PEG mol%")with gr.Row():ch8 = gr.Dropdown(["Ionizable","Cationic","Anionic","Neutral"],value="Ionizable",label="Charge")fl8 = gr.Slider(0,40,value=20,step=1,label="Flow cm/s")b8 = gr.Button("Model Vroman Effect", variant="primary")o8t = gr.Markdown()o8p = gr.Image(label="Kinetics")gr.Examples([[100,-5,1.5,"Ionizable",40],[150,5,0.5,"Cationic",10]], inputs=[s8,z8,pg8,ch8,fl8])b8.click(predict_flow, [s8,z8,pg8,ch8,fl8], [o8t,o8p])# Розкоментовано проблемну вкладку "оце" - LNP Brainwith gr.TabItem("S1-D · R3a · LNP Brain"):gr.HTML(proj_badge("S1-D · R3a", "LNP Brain Delivery — ApoE% + BBB probability"))smi = gr.Textbox(label="Ionizable lipid SMILES",value="CC(C)CC(=O)OCC(COC(=O)CC(C)C)OC(=O)CC(C)C")with gr.Row():pk = gr.Slider(4,8,value=6.5,step=0.1,label="pKa")zt9 = gr.Slider(-20,10,value=-3,step=1,label="Zeta (mV)")b9 = gr.Button("Predict BBB Crossing", variant="primary")o9t = gr.Markdown()o9p = gr.Image(label="Radar profile")gr.Examples([["CC(C)CC(=O)OCC(COC(=O)CC(C)C)OC(=O)CC(C)C",6.5,-3]], inputs=[smi,pk,zt9])b9.click(predict_bbb, [smi,pk,zt9], [o9t,o9p])# Розкоментовано проблемну вкладку "оце" - AutoCorona NLPwith gr.TabItem("S1-D · R4a · AutoCorona NLP"):gr.HTML(proj_badge("S1-D · R4a", "AutoCorona NLP — from abstracts", "F1 = 0.71"))txt = gr.Textbox(lines=5,label="Paper abstract",placeholder="Paste abstract here...")b10 = gr.Button("Extract Data", variant="primary")o10j = gr.Code(label="Extracted JSON", language="json")o10f = gr.Textbox(label="Validation flags")gr.Examples([["LNPs composed of MC3, DSPC, Cholesterol (50:10:40 mol%) with 1.5% PEG-DMG. ""Hydrodynamic diameter was 98 nm, zeta potential -3.2 mV, PDI 0.12. ""Incubated in human plasma. Corona: albumin, apolipoprotein E, fibrinogen."]], inputs=[txt])b10.click(extract_corona, txt, [o10j, o10f])with gr.TabItem("S1-D · R5a · CSF/BM 🔴"):gr.HTML(proj_badge("S1-D · R5a", "LNP Corona in CSF · Vitreous · Bone Marrow", "🔴 0 prior studies"))gr.Markdown("> Planned for Q2–Q3 2026")# === S1-E · PHYLO-BIOMARKERS ===# Розкоментовано проблемну вкладку "оце" - Liquid Biopsywith gr.TabItem("S1-E · R1a · Liquid Biopsy"):gr.HTML(proj_badge("S1-E · R1a", "Liquid Biopsy Classifier", "AUC = 0.992*"))with gr.Row():p1=gr.Slider(-3,3,value=0,step=0.1,label="CTHRC1")p2=gr.Slider(-3,3,value=0,step=0.1,label="FHL2")p3=gr.Slider(-3,3,value=0,step=0.1,label="LDHA")p4=gr.Slider(-3,3,value=0,step=0.1,label="P4HA1")p5=gr.Slider(-3,3,value=0,step=0.1,label="SERPINH1")with gr.Row():p6=gr.Slider(-3,3,value=0,step=0.1,label="ABCA8")p7=gr.Slider(-3,3,value=0,step=0.1,label="CA4")p8=gr.Slider(-3,3,value=0,step=0.1,label="CKB")p9=gr.Slider(-3,3,value=0,step=0.1,label="NNMT")p10=gr.Slider(-3,3,value=0,step=0.1,label="CACNA2D2")b7=gr.Button("Classify", variant="primary")o7t=gr.HTML()o7p=gr.Image(label="Feature contributions")gr.Examples([[2,2,1.5,1.8,1.6,-1,-1.2,-0.8,1.4,-1.1],[0]*10],inputs=[p1,p2,p3,p4,p5,p6,p7,p8,p9,p10])b7.click(predict_cancer, [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10], [o7t,o7p])with gr.TabItem("S1-E · R1b · Validator 🔶"):gr.HTML(proj_badge("S1-E · R1b", "Protein Panel Validator", "🔶 In progress"))gr.Markdown("> Coming next.")# === S1-F · PHYLO-RARE ===# Розкоментовано проблемну вкладку "оце" - DIPGwith gr.TabItem("S1-F · R1a · DIPG Toolkit"):gr.HTML(proj_badge("S1-F · R1a", "DIPG: H3K27M + CSF LNP + Circadian", "PBTA"))sort_d = gr.Radio(["Frequency", "Drug status"], value="Frequency", label="Sort by")b_dv = gr.Button("Load DIPG Variants", variant="primary")o_dv = gr.Dataframe(label="H3K27M co-mutations")b_dv.click(dipg_variants, [sort_d], o_dv)gr.Markdown("---")with gr.Row():d_peg = gr.Slider(0.5, 3.0, value=1.5, step=0.1, label="PEG mol%")d_size = gr.Slider(60, 150, value=90, step=5, label="Target size (nm)")b_dc = gr.Button("Rank CSF Formulations", variant="primary")o_dct = gr.Dataframe(label="CSF LNP ranking")o_dcp = gr.Image(label="ApoE% in CSF corona")b_dc.click(dipg_csf, [d_peg, d_size], [o_dct, o_dcp])# Розкоментовано проблемну вкладку "оце" - UVMwith gr.TabItem("S1-F · R2a · UVM Toolkit"):gr.HTML(proj_badge("S1-F · R2a", "UVM: GNAQ/GNA11 + vitreous + m6A", "TCGA-UVM"))b_uv = gr.Button("Load UVM Variants", variant="primary")o_uv = gr.Dataframe(label="GNAQ/GNA11 map")b_uv.click(uvm_variants, [], o_uv)b_uw = gr.Button("Rank Vitreous Formulations", variant="primary")o_uwt = gr.Dataframe(label="Vitreous LNP retention ranking")o_uwp = gr.Image(label="Retention (hours)")b_uw.click(uvm_vitreous, [], [o_uwt, o_uwp])# Розкоментовано проблемну вкладку "оце" - pAMLwith gr.TabItem("S1-F · R3a · pAML Toolkit"):gr.HTML(proj_badge("S1-F · R3a", "pAML: FLT3-ITD + BM niche + ferroptosis", "TARGET-AML"))var_sel = gr.Dropdown(["FLT3-ITD", "NPM1 c.860_863dupTCAG", "DNMT3A p.R882H","CEBPA biallelic", "IDH1/2 mutation"],value="FLT3-ITD", label="Select variant")b_pf = gr.Button("Analyze Ferroptosis Profile", variant="primary")o_pft = gr.HTML()o_pfp = gr.Image(label="Target radar")b_pf.click(paml_ferroptosis, var_sel, [o_pft, o_pfp])# === S1-G · 3D Lab (НОВА ВКЛАДКА) ===with gr.TabItem("🧊 3D Lab"):gr.HTML(section_header("S1-G", "PHYLO-SIM", "— 3D Models & Simulations","Interactive visualizations for learning"))with gr.Tabs(elem_classes="inner-tabs"):with gr.TabItem("Nanoparticle"):gr.Markdown("### 3D Model of a Lipid Nanoparticle")with gr.Row():np_radius = gr.Slider(2, 20, value=5, step=1, label="Radius (nm)")np_peg = gr.Slider(0, 1, value=0.3, step=0.05, label="PEG density")np_btn = gr.Button("Generate", variant="primary")np_plot = gr.Plotly(label="Nanoparticle")np_btn.click(plot_nanoparticle, [np_radius, np_peg], np_plot)with gr.TabItem("DNA Helix"):gr.Markdown("### 3D Model of a DNA Double Helix")dna_btn = gr.Button("Generate DNA", variant="primary")dna_plot = gr.Plotly()dna_btn.click(plot_dna, [], dna_plot)with gr.TabItem("Protein Corona"):gr.Markdown("### Schematic of Protein Corona on Nanoparticle")corona_btn = gr.Button("Show Corona", variant="primary")corona_plot = gr.Plotly()corona_btn.click(plot_corona, [], corona_plot)# === Journal (покращений) ===with gr.TabItem("📓 Journal"):gr.Markdown("### Lab Journal")with gr.Row():note_text = gr.Textbox(label="📝 Observation", placeholder="What did you discover?", lines=3)note_tab = gr.Textbox(label="Project code (e.g. S1-A·R1a)", value="General")save_btn = gr.Button("💾 Save", variant="primary")clear_btn = gr.Button("🗑️ Clear Journal", variant="secondary")refresh_btn = gr.Button("🔄 Refresh")journal_display = gr.Markdown(value=load_journal())save_btn.click(save_note, [note_text, note_tab], journal_display)refresh_btn.click(load_journal, [], journal_display)clear_btn.click(clear_journal, [], journal_display)# === Learning ===with gr.TabItem("📚 Learning"):gr.Markdown("""## 🧪 Guided Investigations4 unmodified lines**S1-D · R2a** Flow Corona – compare flow 0 vs 40 cm/s**S1-B · R2a** siRNA – count "Novel" targets across cancer types**S1-E · R1a** Liquid Biopsy – find minimal signal for CANCER**S1-G · 3D Lab** – explore nanoparticle, DNA, and protein corona models""")gr.Markdown(
app.py+513-444