Update app.py
Browse files21 unmodified lines22232425262722 unmodified lines505152535455565758596061626364656667686970717273747576777832 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381394 unmodified lines14414514614714814915015115215315415515615715815916 unmodified lines1761771781791801811828 unmodified lines19119219319419519619719819920020120216 unmodified lines21922022122222322422544 unmodified lines27027127227327427527632 unmodified lines30931031131231331436 unmodified lines3513523533543553563573583 unmodified lines36236336436536636736836937037137237312 unmodified lines38638738838939039139216 unmodified lines4094104114124134144159 unmodified lines42542642742842943043126 unmodified lines45845946046146246346446548 unmodified lines51451551651751851952097 unmodified lines61861962062162262352 unmodified lines676677678679680681682683312 unmodified lines9969979989991000100110021003100410051006100710081009101010111012101310141015101610171018287 unmodified lines130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313347 unmodified lines134213431344134521 unmodified linesfrom matplotlib import cmimport iofrom PIL import Image# ─────────────────────────────────────────────# CACHE SYSTEM (TTL = 24 h)22 unmodified lineswith open(path, "w") as f:json.dump(data, f)# ─────────────────────────────────────────────# LAB JOURNAL# ─────────────────────────────────────────────JOURNAL_FILE = "./lab_journal.csv"def journal_log(tab: str, action: str, result: str, note: str = ""):ts = datetime.datetime.utcnow().isoformat()row = [ts, tab, action, result[:200], note]write_header = not os.path.exists(JOURNAL_FILE)with open(JOURNAL_FILE, "a", newline="") as f:w = csv.writer(f)if write_header:w.writerow(["timestamp", "tab", "action", "result_summary", "note"])w.writerow(row)return tsdef journal_read() -> str:if not os.path.exists(JOURNAL_FILE):return "No entries yet."df = pd.read_csv(JOURNAL_FILE)if df.empty:return "No entries yet."return df.tail(20).to_markdown(index=False)# ─────────────────────────────────────────────# CONSTANTS32 unmodified linesCT_BASE = "https://clinicaltrials.gov/api/v2"# ─────────────────────────────────────────────# SHARED API HELPERS# ─────────────────────────────────────────────def pubmed_count(query: str) -> int:"""Return paper count for a PubMed query (cached)."""cached = cache_get("pubmed_count", query)if cached is not None:return cachedtry:time.sleep(0.34)r = requests.get(f"{PUBMED_BASE}/esearch.fcgi",params={"db": "pubmed", "term": query, "rettype": "count", "retmode": "json"},timeout=10)r.raise_for_status()count = int(r.json()["esearchresult"]["count"])cache_set("pubmed_count", query, count)return countexcept Exception:return -1def pubmed_search(query: str, retmax: int = 10) -> list:"""Return list of PMIDs (cached)."""cached = cache_get("pubmed_search", f"{query}_{retmax}")4 unmodified linesr = requests.get(f"{PUBMED_BASE}/esearch.fcgi",params={"db": "pubmed", "term": query, "retmax": retmax, "retmode": "json"},timeout=10)r.raise_for_status()ids = r.json()["esearchresult"]["idlist"]cache_set("pubmed_search", f"{query}_{retmax}", ids)return idsexcept Exception:return []def pubmed_summary(pmids: list) -> list:"""Fetch summaries for a list of PMIDs."""if not pmids:16 unmodified linesexcept Exception:return []def ot_query(gql: str, variables: dict = None) -> dict:"""Run an OpenTargets GraphQL query (cached)."""key = json.dumps({"q": gql, "v": variables}, sort_keys=True)8 unmodified lines)r.raise_for_status()data = r.json()cache_set("ot_gql", key, data)return dataexcept Exception as e:return {"error": str(e)}# ─────────────────────────────────────────────# TAB A1 — GRAY ZONES EXPLORER# ─────────────────────────────────────────────16 unmodified linesfig, ax = plt.subplots(figsize=(6, 8), facecolor="white")valid = df[cancer_type].fillna(0).values.reshape(-1, 1)cmap = plt.cm.get_cmap("YlOrRd")cmap.set_bad("white")masked = np.ma.masked_where(df[cancer_type].isna().values.reshape(-1, 1), valid)im = ax.imshow(masked, aspect="auto", cmap=cmap, vmin=0)44 unmodified linesif "df" in _depmap_cache:return _depmap_cache["df"]# Use a curated list of known essential/cancer genes as fallback# (full DepMap CSV is ~500 MB; we use the public summary endpoint instead)genes = ["MYC", "KRAS", "TP53", "EGFR", "PTEN", "RB1", "CDKN2A","PIK3CA", "AKT1", "BRAF", "NRAS", "IDH1", "IDH2", "ARID1A",32 unmodified lines}"""ot_data = ot_query(gql, {"efoId": efo, "size": 40})rows_ot = []try:rows_ot = ot_data["data"]["disease"]["associatedTargets"]["rows"]36 unmodified linesdepmap_dict = dict(zip(depmap_df["gene"], depmap_df["gene_effect"]))# 5. Build result table# Research gap index = |essentiality| / log(papers + 1)# Per know-how: DepMap scores are negative for essential genesrecords = []for gene in genes_ot[:20]:raw_ess = depmap_dict.get(gene, None)3 unmodified linesess_display = "N/A"gap_idx = 0.0else:# Invert: positive = more essential (per DepMap know-how: negative raw = essential)ess_inverted = -raw_essess_display = f"{ess_inverted:.3f}"papers_safe = max(papers, 0)# Use log(papers + 2) to guarantee denominator >= log(2) ≈ 0.693# preventing division-by-near-zero for genes with 0 publicationsgap_idx = ess_inverted / math.log(papers_safe + 2) if ess_inverted > 0 else 0.0records.append({"Gene": gene,12 unmodified linesf"For real analysis, download `CRISPR_gene_effect.csv` from [depmap.org](https://depmap.org/portal/download/all/) "f"and replace `_load_depmap_sample()` in `app.py`.")journal_log("A2-TargetFinder", f"cancer={cancer_type}", f"top_gap={result_df.iloc[0]['Gene'] if len(result_df) else 'none'}")return result_df, note16 unmodified linestry:time.sleep(0.34)r = requests.get(f"{PUBMED_BASE.replace('entrez/eutils','entrez/eutils')}/esearch.fcgi",params={"db": "clinvar", "term": hgvs, "retmode": "json", "retmax": 5},timeout=10)9 unmodified linestry:time.sleep(0.34)r2 = requests.get(f"{PUBMED_BASE.replace('entrez/eutils','entrez/eutils')}/esummary.fcgi",params={"db": "clinvar", "id": ",".join(clinvar_cached[:3]), "retmode": "json"},timeout=10)26 unmodified lines)# ── gnomAD ──# gnomAD GraphQL expects rsID or gene-level; HGVS lookup is limited# We attempt a search via the variant endpointgnomad_cached = cache_get("gnomad", hgvs)if gnomad_cached is None:try:48 unmodified lines)result_parts.append(f"\n*Source: ClinVar E-utilities + gnomAD GraphQL | Date: {today}*")journal_log("A3-VariantLookup", f"hgvs={hgvs}", result_parts[0][:100])return "\n\n".join(result_parts)97 unmodified lines}"""ot_data = ot_query(gql, {"efoId": efo, "size": 50})rows_ot = []try:rows_ot = ot_data["data"]["disease"]["associatedTargets"]["rows"]52 unmodified lines)journal_log("A5-DruggableOrphans", f"cancer={cancer_type}", f"orphans={len(df)}")return df, note# ─────────────────────────────────────────────# GROUP B — LEARNING SANDBOX# ─────────────────────────────────────────────312 unmodified linesfooter { display: none !important; }"""def build_journal_sidebar():with gr.Column(scale=1, min_width=260):gr.Markdown("## 📓 Lab Journal")note_input = gr.Textbox(label="Add note", placeholder="Your observation...", lines=2)save_btn = gr.Button("💾 Save Note", size="sm")refresh_btn = gr.Button("🔄 Refresh Journal", size="sm")journal_display = gr.Markdown(value="*Click Refresh to load entries.*")def save_note(note):if note.strip():journal_log("Manual", "note", note.strip(), note.strip())return journal_read()save_btn.click(save_note, inputs=[note_input], outputs=[journal_display])refresh_btn.click(lambda: journal_read(), outputs=[journal_display])return note_input, journal_displaydef build_app():with gr.Blocks(css=CUSTOM_CSS, title="K R&D Lab — Cancer Research Suite") as demo:287 unmodified lines)b5_btn.click(b5_run, inputs=[b5_class], outputs=[b5_result])# ── SIDEBAR ──with gr.Column(scale=1, min_width=260):gr.Markdown("## 📓 Lab Journal")note_input = gr.Textbox(label="Add note", placeholder="Your observation...", lines=2)save_btn = gr.Button("💾 Save Note", size="sm")refresh_btn = gr.Button("🔄 Refresh Journal", size="sm")journal_display = gr.Markdown(value="*Click Refresh to load entries.*")def save_note(note):if note.strip():journal_log("Manual", "note", note.strip(), note.strip())return journal_read()save_btn.click(save_note, inputs=[note_input], outputs=[journal_display])refresh_btn.click(lambda: journal_read(), outputs=[journal_display])# === Інтеграція з Learning Playground ===with gr.Row():gr.Markdown("""### 🧪 New to the concepts?Explore our **[Learning Playground](https://huggingface.co/spaces/K-RnD-Lab/Learning-Playground_03-2026)** with simulated environments.""")gr.Markdown("---\n""*K R&D Lab Cancer Research Suite · "7 unmodified linesif __name__ == "__main__":app = build_app()app.launch(share=False)21 unmodified lines2223242526272822 unmodified lines5152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511632 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851864 unmodified lines19119219319419519619719819920020120220320420520620716 unmodified lines2242252262272282292308 unmodified lines23924024124224324424524624724824925025125216 unmodified lines26927027127227327427527644 unmodified lines32132232332432532632 unmodified lines35936036136236336436536636736 unmodified lines4044054064074084093 unmodified lines41341441541641741841942042142212 unmodified lines43543643743843944044144244344416 unmodified lines4614624634644654664679 unmodified lines47747847948048148248326 unmodified lines51051151251351451548 unmodified lines56456556656756856957097 unmodified lines66866967067167267367467567652 unmodified lines729730731732733734312 unmodified lines104710481049105010511052287 unmodified lines1340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813997 unmodified lines140714081409141021 unmodified linesfrom matplotlib import cmimport iofrom PIL import Imagefrom functools import wraps# ─────────────────────────────────────────────# CACHE SYSTEM (TTL = 24 h)22 unmodified lineswith open(path, "w") as f:json.dump(data, f)# ─────────────────────────────────────────────# RETRY DECORATOR# ─────────────────────────────────────────────def retry(max_attempts=3, delay=1):"""Decorator to retry a function on exception."""def decorator(func):@wraps(func)def wrapper(*args, **kwargs):for attempt in range(max_attempts):try:return func(*args, **kwargs)except Exception as e:print(f"Attempt {attempt+1} failed for {func.__name__}: {e}")if attempt == max_attempts - 1:raisetime.sleep(delay * (attempt + 1))return Nonereturn wrapperreturn decorator# ─────────────────────────────────────────────# LAB JOURNAL# ─────────────────────────────────────────────JOURNAL_FILE = "./lab_journal.csv"JOURNAL_CATEGORIES = ["A1-GrayZones", "A2-TargetFinder", "A3-VariantLookup", "A4-LitGap", "A5-Orphans", "A6-Chatbot","B1-miRNA", "B2-siRNA", "B3-LNPCorona", "B4-FlowCorona", "B5-VariantConcepts","Manual"]def journal_log(category: str, action: str, result: str, note: str = ""):"""Log an entry with category."""ts = datetime.datetime.utcnow().isoformat()row = [ts, category, action, result[:200], note]write_header = not os.path.exists(JOURNAL_FILE)with open(JOURNAL_FILE, "a", newline="") as f:w = csv.writer(f)if write_header:w.writerow(["timestamp", "category", "action", "result_summary", "note"])w.writerow(row)return tsdef journal_read(category: str = "All") -> str:"""Read journal entries, optionally filtered by category. Returns markdown."""if not os.path.exists(JOURNAL_FILE):return "No entries yet."try:df = pd.read_csv(JOURNAL_FILE)if df.empty:return "No entries yet."if category != "All":df = df[df["category"] == category]if df.empty:return f"No entries for category: {category}"# Format for better readabilitydf_display = df[["timestamp", "category", "action", "result_summary"]].tail(20)return df_display.to_markdown(index=False)except Exception as e:print(f"Journal read error: {e}")return "Error reading journal."# ─────────────────────────────────────────────# CONSTANTS32 unmodified linesCT_BASE = "https://clinicaltrials.gov/api/v2"# ─────────────────────────────────────────────# SHARED API HELPERS (with retry)# ─────────────────────────────────────────────@retry(max_attempts=3, delay=1)def pubmed_count(query: str) -> int:"""Return paper count for a PubMed query (cached)."""cached = cache_get("pubmed_count", query)if cached is not None:return cachedtry:time.sleep(0.34) # Rate limit compliancer = requests.get(f"{PUBMED_BASE}/esearch.fcgi",params={"db": "pubmed", "term": query, "rettype": "count", "retmode": "json"},timeout=15)r.raise_for_status()data = r.json()count = int(data.get("esearchresult", {}).get("count", 0))cache_set("pubmed_count", query, count)return countexcept requests.exceptions.Timeout:print(f"Timeout for query: {query}")return -1except requests.exceptions.RequestException as e:print(f"Request error for {query}: {e}")return -1except (KeyError, ValueError) as e:print(f"Parsing error for {query}: {e}")return -1@retry(max_attempts=3, delay=1)def pubmed_search(query: str, retmax: int = 10) -> list:"""Return list of PMIDs (cached)."""cached = cache_get("pubmed_search", f"{query}_{retmax}")4 unmodified linesr = requests.get(f"{PUBMED_BASE}/esearch.fcgi",params={"db": "pubmed", "term": query, "retmax": retmax, "retmode": "json"},timeout=15)r.raise_for_status()data = r.json()ids = data.get("esearchresult", {}).get("idlist", [])cache_set("pubmed_search", f"{query}_{retmax}", ids)return idsexcept Exception:return []@retry(max_attempts=3, delay=1)def pubmed_summary(pmids: list) -> list:"""Fetch summaries for a list of PMIDs."""if not pmids:16 unmodified linesexcept Exception:return []@retry(max_attempts=3, delay=1)def ot_query(gql: str, variables: dict = None) -> dict:"""Run an OpenTargets GraphQL query (cached)."""key = json.dumps({"q": gql, "v": variables}, sort_keys=True)8 unmodified lines)r.raise_for_status()data = r.json()if "errors" in data:print(f"GraphQL errors: {data['errors']}")return {"error": data["errors"]}cache_set("ot_gql", key, data)return dataexcept Exception as e:print(f"OT query error: {e}")return {"error": str(e)}# ─────────────────────────────────────────────# TAB A1 — GRAY ZONES EXPLORER# ─────────────────────────────────────────────16 unmodified linesfig, ax = plt.subplots(figsize=(6, 8), facecolor="white")valid = df[cancer_type].fillna(0).values.reshape(-1, 1)# Виправлено deprecated get_cmapcmap = plt.colormaps.get_cmap("YlOrRd")cmap.set_bad("white")masked = np.ma.masked_where(df[cancer_type].isna().values.reshape(-1, 1), valid)im = ax.imshow(masked, aspect="auto", cmap=cmap, vmin=0)44 unmodified linesif "df" in _depmap_cache:return _depmap_cache["df"]# Use a curated list of known essential/cancer genes as fallbackgenes = ["MYC", "KRAS", "TP53", "EGFR", "PTEN", "RB1", "CDKN2A","PIK3CA", "AKT1", "BRAF", "NRAS", "IDH1", "IDH2", "ARID1A",32 unmodified lines}"""ot_data = ot_query(gql, {"efoId": efo, "size": 40})if "error" in ot_data:return None, f"⚠️ OpenTargets API error: {ot_data['error']}\n\n*Source: OpenTargets | Date: {today}*"rows_ot = []try:rows_ot = ot_data["data"]["disease"]["associatedTargets"]["rows"]36 unmodified linesdepmap_dict = dict(zip(depmap_df["gene"], depmap_df["gene_effect"]))# 5. Build result tablerecords = []for gene in genes_ot[:20]:raw_ess = depmap_dict.get(gene, None)3 unmodified linesess_display = "N/A"gap_idx = 0.0else:# Invert: positive = more essentialess_inverted = -raw_essess_display = f"{ess_inverted:.3f}"papers_safe = max(papers, 0)gap_idx = ess_inverted / math.log(papers_safe + 2) if ess_inverted > 0 else 0.0records.append({"Gene": gene,12 unmodified linesf"For real analysis, download `CRISPR_gene_effect.csv` from [depmap.org](https://depmap.org/portal/download/all/) "f"and replace `_load_depmap_sample()` in `app.py`.")if not result_df.empty:journal_log("A2-TargetFinder", f"cancer={cancer_type}", f"top_gap={result_df.iloc[0]['Gene']}")else:journal_log("A2-TargetFinder", f"cancer={cancer_type}", "no targets found")return result_df, note16 unmodified linestry:time.sleep(0.34)r = requests.get(f"{PUBMED_BASE}/esearch.fcgi",params={"db": "clinvar", "term": hgvs, "retmode": "json", "retmax": 5},timeout=10)9 unmodified linestry:time.sleep(0.34)r2 = requests.get(f"{PUBMED_BASE}/esummary.fcgi",params={"db": "clinvar", "id": ",".join(clinvar_cached[:3]), "retmode": "json"},timeout=10)26 unmodified lines)# ── gnomAD ──gnomad_cached = cache_get("gnomad", hgvs)if gnomad_cached is None:try:48 unmodified lines)result_parts.append(f"\n*Source: ClinVar E-utilities + gnomAD GraphQL | Date: {today}*")journal_log("A3-VariantLookup", f"hgvs={hgvs}", result_parts[0][:100] if result_parts else "no results")return "\n\n".join(result_parts)97 unmodified lines}"""ot_data = ot_query(gql, {"efoId": efo, "size": 50})if "error" in ot_data:return None, f"⚠️ OpenTargets API error: {ot_data['error']}\n\n*Source: OpenTargets | Date: {today}*"rows_ot = []try:rows_ot = ot_data["data"]["disease"]["associatedTargets"]["rows"]52 unmodified lines)journal_log("A5-DruggableOrphans", f"cancer={cancer_type}", f"orphans={len(df)}")return df, note# ─────────────────────────────────────────────# GROUP B — LEARNING SANDBOX# ─────────────────────────────────────────────312 unmodified linesfooter { display: none !important; }"""def build_app():with gr.Blocks(css=CUSTOM_CSS, title="K R&D Lab — Cancer Research Suite") as demo:287 unmodified lines)b5_btn.click(b5_run, inputs=[b5_class], outputs=[b5_result])# ── SIDEBAR (JOURNAL) ──with gr.Column(scale=1, min_width=260):gr.Markdown("## 📓 Lab Journal")note_category = gr.Dropdown(choices=JOURNAL_CATEGORIES,value="Manual",label="Category")note_input = gr.Textbox(label="Observation",placeholder="Type your note here...",lines=3)with gr.Row():save_btn = gr.Button("💾 Save Note", size="sm", variant="primary")clear_note_btn = gr.Button("🗑️ Clear", size="sm")save_status = gr.Markdown("")gr.Markdown("---")gr.Markdown("## 🔍 Full Journal")journal_filter = gr.Dropdown(choices=["All"] + JOURNAL_CATEGORIES,value="All",label="Filter by category")refresh_btn = gr.Button("🔄 Refresh", size="sm")journal_display = gr.Markdown(value=journal_read())def save_note(category, note):if note.strip():journal_log(category, "manual note", note, note)return "✅ Note saved.", ""return "⚠️ Note is empty.", ""def refresh_journal(category):return journal_read(category)save_btn.click(save_note,inputs=[note_category, note_input],outputs=[save_status, note_input])clear_note_btn.click(lambda: ("", ""), outputs=[note_input, save_status])refresh_btn.click(refresh_journal, inputs=[journal_filter], outputs=journal_display)journal_filter.change(refresh_journal, inputs=[journal_filter], outputs=journal_display)# === Інтеграція з Learning Playground ===with gr.Row():gr.Markdown("""---### 🧪 New to the concepts?Explore our **[Learning Playground](https://huggingface.co/spaces/K-RnD-Lab/Learning-Playground_03-2026)** with simulated environments.""")gr.Markdown("---\n""*K R&D Lab Cancer Research Suite · "7 unmodified linesif __name__ == "__main__":app = build_app()app.launch(share=False)
app.py+129-64