Spaces:
Paused
Paused
Download ProtHGT_app.py from HUBioDataLab/ProtHGT: direct link, hf CLI and curl.
- Browser
- Download file 33.3 kB
-
https://huggingface.co/spaces/HUBioDataLab/ProtHGT/resolve/main/ProtHGT_app.py
- Command line
-
hf download hf://spaces/HUBioDataLab/ProtHGT/ProtHGT_app.py
-
curl -L -o ProtHGT_app.py https://huggingface.co/spaces/HUBioDataLab/ProtHGT/resolve/main/ProtHGT_app.py
33.3 kB
| """ProtHGT — guided three-step interface (add proteins → choose what to predict → review results).""" | |
| import os | |
| import random | |
| import re | |
| import streamlit as st | |
| st.set_page_config( | |
| page_title="ProtHGT · Protein function prediction", | |
| page_icon="🧬", | |
| layout="wide", | |
| initial_sidebar_state="collapsed", | |
| ) | |
| from rapidfuzz import fuzz, process | |
| from run_prothgt_app import KG_PATH, generate_prediction_df, load_kg, load_model, load_name_info | |
| from run_prothgt_ec_app import EC_KG_PATH, generate_ec_prediction_df, load_ec_kg, load_ec_model | |
| from visualize_kg import visualize_protein_subgraph | |
| from ui import GITHUB_URL, KG_VIEW_GUIDE, STRICTNESS, render_header, render_stepper | |
| # --------------------------------------------------------------------------- | |
| # Settings | |
| # --------------------------------------------------------------------------- | |
| MAX_PROTEINS = 100 | |
| MAX_KG_VIZ_PROTEINS = 10 | |
| SEARCH_LIMIT = 50 | |
| KG_DOWNLOAD_URL = "https://huggingface.co/datasets/HUBioDataLab/ProtHGT/blob/main/knowledge_graphs/go/prothgt-kg.pt" | |
| ASPECTS = { | |
| "GO_term_F": ("Molecular function", "What the protein does at the molecular level, e.g. binding or catalysis."), | |
| "GO_term_P": ("Biological process", "Which larger pathways or programs it takes part in."), | |
| "GO_term_C": ("Cellular component", "Where in the cell the protein is located."), | |
| } | |
| ASPECT_SHORT = {"GO_term_F": "MF", "GO_term_P": "BP", "GO_term_C": "CC"} | |
| CATEGORY_TO_KEY = {"Molecular Function": "GO_term_F", "Biological Process": "GO_term_P", "Cellular Component": "GO_term_C"} | |
| # Widget values that must survive moving between steps (Streamlit drops the state of | |
| # widgets that are not rendered; re-assigning keeps it). | |
| PERSISTENT_KEYS = ["proteins", "aspect_GO_term_F", "aspect_GO_term_P", "aspect_GO_term_C", | |
| "predict_ec", "strictness", "use_custom_threshold", "custom_threshold"] | |
| for _k in PERSISTENT_KEYS: | |
| if _k in st.session_state: | |
| st.session_state[_k] = st.session_state[_k] | |
| DEFAULTS = { | |
| "step": 1, | |
| "proteins": [], | |
| "aspect_GO_term_F": True, | |
| "aspect_GO_term_P": True, | |
| "aspect_GO_term_C": True, | |
| "predict_ec": False, | |
| "strictness": "Balanced", | |
| "use_custom_threshold": False, | |
| "custom_threshold": 0.50, | |
| "notice": None, | |
| "results": None, | |
| "results_cache": {}, | |
| "viz": {}, | |
| } | |
| for _k, _v in DEFAULTS.items(): | |
| st.session_state.setdefault(_k, _v) | |
| # --------------------------------------------------------------------------- | |
| # Cached heavy resources (shared by every visitor of the Space, loaded once) | |
| # --------------------------------------------------------------------------- | |
| def get_protein_names(): | |
| """UniProt ID -> protein name, for every protein in the knowledge graph.""" | |
| return load_name_info()["Protein"] | |
| def get_search_index(): | |
| """(id, lower-cased name) pairs plus fuzzy-match choices, built once per process.""" | |
| names = get_protein_names() | |
| lowered = [(pid, name.lower()) for pid, name in names.items()] | |
| choices = {pid: f"{pid} {name}" for pid, name in names.items()} | |
| return lowered, choices | |
| def get_kg(): | |
| return load_kg() | |
| def get_model(go_cat): | |
| return load_model(go_cat, get_kg()) | |
| def get_ec_kg(): | |
| return load_ec_kg() | |
| def get_ec_model(): | |
| return load_ec_model(get_ec_kg()) | |
| def search_proteins(query): | |
| """Exact ID → ID prefix → name substring (closest names first) → fuzzy fallback.""" | |
| q = query.strip() | |
| qu, ql = q.upper(), q.lower() | |
| names = get_protein_names() | |
| lowered, choices = get_search_index() | |
| hits = [qu] if qu in names else [] | |
| if re.fullmatch(r"[A-Za-z0-9_]+", q): | |
| hits += sorted(pid for pid, _ in lowered if pid.startswith(qu))[:SEARCH_LIMIT] | |
| substr = [(name != ql, len(name), pid) for pid, name in lowered if ql in name] | |
| hits += [pid for _, _, pid in sorted(substr)[:SEARCH_LIMIT]] | |
| if len(hits) < SEARCH_LIMIT: | |
| hits += [m[2] for m in process.extract(q, choices, scorer=fuzz.WRatio, limit=SEARCH_LIMIT)] | |
| return list(dict.fromkeys(hits))[:SEARCH_LIMIT] | |
| # --------------------------------------------------------------------------- | |
| # State helpers / callbacks | |
| # --------------------------------------------------------------------------- | |
| def go_to(step): | |
| st.session_state.step = step | |
| def selected_aspects(): | |
| return [k for k in ASPECTS if st.session_state[f"aspect_{k}"]] | |
| def current_threshold(): | |
| if st.session_state.use_custom_threshold: | |
| return float(st.session_state.custom_threshold) | |
| return STRICTNESS[st.session_state.strictness][0] | |
| def add_proteins(candidates, source): | |
| names = get_protein_names() | |
| candidates = list(dict.fromkeys(c.strip().upper() for c in candidates if c and c.strip())) | |
| known = [c for c in candidates if c in names] | |
| unknown = [c for c in candidates if c not in names] | |
| current = list(st.session_state.proteins) | |
| new = [p for p in known if p not in current] | |
| room = MAX_PROTEINS - len(current) | |
| dropped = new[room:] if room < len(new) else [] | |
| current.extend(new[:max(room, 0)]) | |
| st.session_state.proteins = current | |
| st.session_state.notice = { | |
| "source": source, | |
| "added": len(new) - len(dropped), | |
| "duplicates": len(known) - len(new), | |
| "unknown": unknown, | |
| "over_limit": dropped, | |
| } | |
| def add_from_paste(): | |
| text = st.session_state.get("paste_text", "") | |
| add_proteins(re.split(r"[\s,;]+", text), "pasted list") | |
| def add_from_search(): | |
| add_proteins(st.session_state.get("search_pick", []), "search") | |
| st.session_state.search_pick = [] | |
| def add_from_file(): | |
| uploaded = st.session_state.get("upload_file") | |
| if uploaded is None: | |
| return | |
| text = uploaded.getvalue().decode("utf-8", errors="ignore") | |
| add_proteins(re.split(r"[\s,;]+", text), uploaded.name) | |
| def add_example(): | |
| pool = list(get_protein_names().keys()) | |
| add_proteins(random.sample(pool, 5), "example set") | |
| def clear_proteins(): | |
| st.session_state.proteins = [] | |
| st.session_state.notice = None | |
| def clear_visualizations(): | |
| for path in st.session_state.viz.values(): | |
| try: | |
| os.unlink(path["path"]) | |
| except OSError: | |
| pass | |
| st.session_state.viz = {} | |
| def start_new_prediction(): | |
| st.session_state.results = None | |
| st.session_state.results_cache = {} | |
| st.session_state.notice = None | |
| clear_visualizations() | |
| go_to(1) | |
| # --------------------------------------------------------------------------- | |
| # Page | |
| # --------------------------------------------------------------------------- | |
| render_header() | |
| step = st.session_state.step | |
| hero_slot = st.empty() # always created so the elements below keep a stable position across steps | |
| if step < 3: | |
| hero_slot.markdown( | |
| '<div class="phgt-hero"><h1>Protein function prediction with knowledge graphs</h1>' | |
| "<p>Gene Ontology term and Enzyme Commission number predictions from a heterogeneous graph " | |
| "transformer that combines protein language model embeddings with a large-scale biological " | |
| "knowledge graph.</p></div>", | |
| unsafe_allow_html=True, | |
| ) | |
| else: | |
| hero_slot.markdown('<div class="phgt-hero-spacer"></div>', unsafe_allow_html=True) | |
| render_stepper(step) | |
| def protein_chips_html(proteins, limit=40): | |
| shown = "".join(f'<span class="phgt-chip">{p}</span>' for p in proteins[:limit]) | |
| more = f'<span class="phgt-muted">+{len(proteins) - limit} more</span>' if len(proteins) > limit else "" | |
| return f'<div class="phgt-chips">{shown}{more}</div>' | |
| def render_limit_aside(): | |
| n = len(st.session_state.proteins) | |
| with st.container(border=True): | |
| st.markdown("**Your proteins**") | |
| if n: | |
| st.markdown(protein_chips_html(st.session_state.proteins), unsafe_allow_html=True) | |
| else: | |
| st.markdown('<span class="phgt-muted">None added yet.</span>', unsafe_allow_html=True) | |
| st.markdown( | |
| f'<div class="phgt-meter"><div style="width:{n / MAX_PROTEINS * 100:.0f}%"></div></div>' | |
| f'<span class="phgt-muted phgt-count">{n} of {MAX_PROTEINS} proteins per run</span>', | |
| unsafe_allow_html=True, | |
| ) | |
| if step == 2: | |
| st.button("Edit proteins", on_click=go_to, args=(1,), use_container_width=True) | |
| with st.container(border=True): | |
| st.markdown("**Need more than 100?**") | |
| st.markdown( | |
| f'<span class="phgt-muted">Run ProtHGT locally with the code and pretrained models on ' | |
| f'<a href="{GITHUB_URL}" target="_blank">GitHub</a>.</span>', | |
| unsafe_allow_html=True, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Step 1 — add proteins | |
| # --------------------------------------------------------------------------- | |
| def render_step_1(): | |
| main, aside = st.columns([2.3, 1], gap="large") | |
| with main: | |
| with st.container(border=True): | |
| st.subheader("Which proteins do you want to annotate?") | |
| st.caption("ProtHGT works on the ~326K UniProtKB/Swiss-Prot proteins in its knowledge graph. " | |
| "Up to 100 proteins per run.") | |
| paste_tab, search_tab, upload_tab, example_tab = st.tabs( | |
| ["Paste IDs", "Search", "Upload file", "Try an example"]) | |
| with paste_tab: | |
| with st.form("paste_form", clear_on_submit=True, border=False): | |
| st.text_area( | |
| "UniProt accessions", | |
| key="paste_text", | |
| placeholder="P69905, P68871\nQ9Y6K9", | |
| help="Separate IDs with commas, spaces or new lines.", | |
| height=110, | |
| ) | |
| st.form_submit_button("Add proteins", on_click=add_from_paste) | |
| with search_tab: | |
| query = st.text_input( | |
| "Search by UniProt ID or protein name", | |
| key="search_q", | |
| placeholder="e.g. hemoglobin, kinase, P699…", | |
| ) | |
| if len(query.strip()) >= 3: | |
| names = get_protein_names() | |
| with st.spinner("Searching…"): | |
| hits = search_proteins(query) | |
| st.multiselect( | |
| f"Top {len(hits)} matches" if len(hits) == SEARCH_LIMIT else f"Matches ({len(hits)})", | |
| options=hits, | |
| key="search_pick", | |
| format_func=lambda p: f"{p} — {names.get(p, '')}", | |
| placeholder="Pick one or more matches", | |
| ) | |
| st.button("Add selected", on_click=add_from_search, key="add_search", | |
| disabled=not st.session_state.get("search_pick")) | |
| else: | |
| st.caption("Type at least 3 characters.") | |
| with upload_tab: | |
| st.file_uploader("Text file with one UniProt ID per line", type=["txt", "csv", "tsv"], | |
| key="upload_file") | |
| st.button("Add from file", on_click=add_from_file, key="add_file", | |
| disabled=st.session_state.get("upload_file") is None) | |
| with example_tab: | |
| st.markdown('<span class="phgt-muted">Load five random proteins from the knowledge graph ' | |
| "to see how ProtHGT works.</span>", unsafe_allow_html=True) | |
| st.button("Load example proteins", on_click=add_example, key="add_example") | |
| notice = st.session_state.notice | |
| if notice: | |
| parts = [] | |
| if notice["added"]: | |
| parts.append(f"Added {notice['added']} protein{'s' if notice['added'] != 1 else ''} " | |
| f"from {notice['source']}.") | |
| if notice["duplicates"]: | |
| parts.append(f"{notice['duplicates']} already in your list.") | |
| if parts: | |
| st.success(" ".join(parts)) | |
| elif not notice["unknown"]: | |
| st.info("No UniProt IDs found in the input.") | |
| if notice["unknown"]: | |
| st.warning( | |
| f"{len(notice['unknown'])} ID(s) are not in the ProtHGT knowledge graph and were skipped. " | |
| "Predictions for proteins outside the graph are not supported yet." | |
| ) | |
| with st.expander("Show skipped IDs"): | |
| st.code("\n".join(notice["unknown"]), language=None) | |
| if notice["over_limit"]: | |
| st.error(f"{len(notice['over_limit'])} protein(s) were not added: the limit is " | |
| f"{MAX_PROTEINS} per run.") | |
| st.divider() | |
| st.multiselect( | |
| f"Selected proteins ({len(st.session_state.proteins)}/{MAX_PROTEINS})", | |
| options=st.session_state.proteins, | |
| key="proteins", | |
| placeholder="Add proteins using one of the tabs above", | |
| help="Click × on a protein to remove it.", | |
| ) | |
| if st.session_state.proteins: | |
| c1, c2, _ = st.columns([1, 1, 2]) | |
| c1.download_button("Download list", "\n".join(st.session_state.proteins), | |
| file_name="selected_proteins.txt", mime="text/plain") | |
| c2.button("Clear all", on_click=clear_proteins) | |
| _, nav = st.columns([3, 1.3]) | |
| nav.button("Continue →", type="primary", use_container_width=True, | |
| disabled=not st.session_state.proteins, on_click=go_to, args=(2,)) | |
| with aside: | |
| render_limit_aside() | |
| # --------------------------------------------------------------------------- | |
| # Step 2 — choose what to predict | |
| # --------------------------------------------------------------------------- | |
| def render_step_2(): | |
| if not st.session_state.proteins: | |
| go_to(1) | |
| st.rerun() | |
| main, aside = st.columns([2.3, 1], gap="large") | |
| with main: | |
| with st.container(border=True): | |
| st.subheader("Which functions are you interested in?") | |
| # 2x2 grid: the three GO aspects plus EC numbers. Fixed-height cards so | |
| # every box is the same size regardless of how much text it holds. | |
| items = [(f"aspect_{k}", "Gene Ontology", label, desc) for k, (label, desc) in ASPECTS.items()] | |
| items.append(( | |
| "predict_ec", "Enzyme Commission", "EC number", | |
| "EC numbers for enzymes, predicted across the four hierarchy levels (L1–L4) as a " | |
| "consistent top-down chain. Non-enzymes return no EC number.", | |
| )) | |
| for i in range(0, len(items), 2): | |
| cols = st.columns(2) | |
| for col, (key, eyebrow, title, desc) in zip(cols, items[i:i + 2]): | |
| with col: | |
| with st.container(border=True, height=158): | |
| st.markdown(f'<span class="phgt-eyebrow">{eyebrow}</span>', | |
| unsafe_allow_html=True) | |
| st.checkbox(f"**{title}**", key=key) | |
| st.caption(desc) | |
| st.subheader("How strict should predictions be?") | |
| st.radio( | |
| "Prediction strictness", | |
| options=list(STRICTNESS), | |
| key="strictness", | |
| horizontal=True, | |
| label_visibility="collapsed", | |
| captions=[f"{d} · score ≥ {t:.2f}" for t, d in STRICTNESS.values()], | |
| disabled=st.session_state.use_custom_threshold, | |
| ) | |
| with st.expander("Advanced: set a custom score threshold", | |
| expanded=st.session_state.use_custom_threshold): | |
| st.checkbox("Use a custom threshold", key="use_custom_threshold") | |
| st.slider("Minimum score", 0.0, 1.0, step=0.05, key="custom_threshold", | |
| disabled=not st.session_state.use_custom_threshold, | |
| help="Only GO terms scoring at or above this value are returned. " | |
| "Lower values return many more terms and take longer.") | |
| if st.session_state.use_custom_threshold and st.session_state.custom_threshold < 0.1: | |
| st.caption("A very low threshold returns almost every GO term for each protein; " | |
| "expect a large table.") | |
| anything = selected_aspects() or st.session_state.predict_ec | |
| back, _, run = st.columns([1, 1.7, 1.3]) | |
| back.button("← Back", use_container_width=True, on_click=go_to, args=(1,)) | |
| run.button("Run prediction →", type="primary", use_container_width=True, | |
| disabled=not anything, on_click=go_to, args=(3,)) | |
| if not anything: | |
| st.caption("Select at least one function category or EC numbers.") | |
| with aside: | |
| render_limit_aside() | |
| # --------------------------------------------------------------------------- | |
| # Step 3 — run & review | |
| # --------------------------------------------------------------------------- | |
| def run_go_prediction(proteins, aspects, threshold): | |
| with st.status("Running ProtHGT (GO terms)…", expanded=True) as status: | |
| if os.path.exists(KG_PATH): | |
| st.write("Loading the knowledge graph…") | |
| else: | |
| st.write("Downloading dataset files for the first time, this may take a few minutes…") | |
| heterodata = get_kg() | |
| progress = st.progress(0.0) | |
| def on_category(i, n, go_cat): | |
| progress.progress(i / n, text=f"Scoring {ASPECTS[go_cat][0].lower()} terms ({i + 1}/{n})") | |
| models = {cat: get_model(cat) for cat in aspects} | |
| _, df = generate_prediction_df( | |
| protein_ids=proteins, | |
| go_category=aspects, | |
| threshold=threshold, | |
| heterodata=heterodata, | |
| models=models, | |
| progress_callback=on_category, | |
| ) | |
| progress.progress(1.0, text="Done") | |
| status.update(label=f"Predicted {len(df):,} protein–GO term associations", state="complete", | |
| expanded=False) | |
| return df.sort_values("Probability", ascending=False, ignore_index=True) | |
| def run_ec_prediction(proteins, threshold): | |
| with st.status("Running ProtHGT (EC numbers)…", expanded=True) as status: | |
| if os.path.exists(EC_KG_PATH): | |
| st.write("Loading the EC knowledge graph…") | |
| else: | |
| st.write("Downloading EC dataset files for the first time, this may take a few minutes…") | |
| heterodata = get_ec_kg() | |
| model = get_ec_model() | |
| progress = st.progress(0.0) | |
| def on_protein(i, n): | |
| progress.progress(i / n, text=f"Scoring EC numbers ({i + 1}/{n})") | |
| _, df = generate_ec_prediction_df( | |
| proteins, heterodata, model, threshold=threshold, progress_callback=on_protein) | |
| progress.progress(1.0, text="Done") | |
| status.update(label=f"Predicted {len(df):,} protein–EC number associations", state="complete", | |
| expanded=False) | |
| return df.sort_values("Probability", ascending=False, ignore_index=True) | |
| def render_predictions(df, threshold): | |
| if df.empty: | |
| st.info("No GO terms passed the score threshold. Try a lower strictness in step 2.") | |
| return | |
| f1, f2, f3 = st.columns([1.2, 1.2, 1.6]) | |
| proteins = ["All proteins"] + sorted(df["UniProt_ID"].unique()) | |
| protein = f1.selectbox("Protein", proteins, format_func=lambda p: p if p == "All proteins" | |
| else f"{p} — {df.loc[df.UniProt_ID == p, 'Protein'].iat[0]}") | |
| available = [c for c in CATEGORY_TO_KEY if c in set(df["GO_category"])] | |
| aspects = f2.pills("Aspect", available, selection_mode="multi", default=available, | |
| format_func=lambda c: ASPECT_SHORT[CATEGORY_TO_KEY[c]]) | |
| text = f3.text_input("Search GO ID or term", placeholder="e.g. GO:0005524 or binding") | |
| min_score = st.slider("Minimum score", float(threshold), 1.0, float(threshold), step=0.01) | |
| view = df | |
| if protein != "All proteins": | |
| view = view[view["UniProt_ID"] == protein] | |
| view = view[view["GO_category"].isin(aspects or [])] | |
| if text.strip(): | |
| t = text.strip() | |
| view = view[view["GO_ID"].str.contains(t, case=False, regex=False) | |
| | view["GO_term"].str.contains(t, case=False, regex=False)] | |
| view = view[view["Probability"] >= min_score] | |
| display = view.assign( | |
| UniProt_ID="https://www.uniprot.org/uniprotkb/" + view["UniProt_ID"] + "/entry", | |
| GO_ID="https://www.ebi.ac.uk/QuickGO/term/" + view["GO_ID"], | |
| GO_category=view["GO_category"].map(lambda c: ASPECT_SHORT[CATEGORY_TO_KEY[c]]), # MF/BP/CC; CSV keeps full names | |
| ) | |
| # Fixed widths for the long text columns so the table fits the page instead of scrolling sideways; | |
| # truncated cells show their full text on hover. Short columns keep their automatic width. | |
| st.dataframe( | |
| display, | |
| hide_index=True, | |
| use_container_width=True, | |
| height=520, | |
| column_config={ | |
| "UniProt_ID": st.column_config.LinkColumn("UniProt ID", display_text=r"uniprotkb/([A-Z0-9]+)/entry"), | |
| "Protein": st.column_config.TextColumn("Protein", width="large"), | |
| "GO_ID": st.column_config.LinkColumn("GO ID", display_text=r"term/(GO:[0-9]+)"), | |
| "GO_term": st.column_config.TextColumn("GO term", width="medium"), | |
| "GO_category": st.column_config.TextColumn( | |
| "Aspect", help="MF: molecular function · BP: biological process · CC: cellular component"), | |
| # Plain number: scores cluster near 1, so a bar adds little; 3 decimals keep close scores apart | |
| "Probability": st.column_config.NumberColumn("Score", format="%.3f", width="small"), | |
| }, | |
| ) | |
| st.caption(f"Showing {len(view):,} of {len(df):,} predictions") | |
| def _expasy_url(ec): | |
| """ExPASy ENZYME URL for an EC number or class prefix (padded to four fields with '-').""" | |
| parts = ec.split(".") | |
| parts += ["-"] * (4 - len(parts)) | |
| return "https://enzyme.expasy.org/EC/" + ".".join(parts) | |
| def render_ec_predictions(df, threshold): | |
| if df.empty: | |
| st.info("No EC numbers passed the score threshold — none of these proteins were predicted as " | |
| "enzymes at this strictness. Try a lower strictness in step 2.") | |
| return | |
| f1, f2, f3 = st.columns([1.2, 1.2, 1.6]) | |
| proteins = ["All proteins"] + sorted(df["UniProt_ID"].unique()) | |
| protein = f1.selectbox("Protein", proteins, key="ec_protein", | |
| format_func=lambda p: p if p == "All proteins" | |
| else f"{p} — {df.loc[df.UniProt_ID == p, 'Protein'].iat[0]}") | |
| all_levels = ["L1", "L2", "L3", "L4"] | |
| available = [lv for lv in all_levels if lv in set(df["EC_level"])] | |
| levels = f2.pills("Level", available, selection_mode="multi", default=available, key="ec_levels") | |
| text = f3.text_input("Search EC number", placeholder="e.g. 2.7.11", key="ec_search") | |
| min_score = st.slider("Minimum score", float(threshold), 1.0, float(threshold), step=0.01, key="ec_min") | |
| view = df | |
| if protein != "All proteins": | |
| view = view[view["UniProt_ID"] == protein] | |
| view = view[view["EC_level"].isin(levels or [])] | |
| if text.strip(): | |
| view = view[view["EC"].str.contains(text.strip(), case=False, regex=False)] | |
| view = view[view["Probability"] >= min_score] | |
| display = view.assign( | |
| UniProt_ID="https://www.uniprot.org/uniprotkb/" + view["UniProt_ID"] + "/entry", | |
| EC=view["EC"].map(_expasy_url), | |
| ) | |
| st.dataframe( | |
| display, | |
| hide_index=True, | |
| use_container_width=True, | |
| height=520, | |
| column_config={ | |
| "UniProt_ID": st.column_config.LinkColumn("UniProt ID", width="small", | |
| display_text=r"uniprotkb/([A-Z0-9]+)/entry"), | |
| "Protein": st.column_config.TextColumn("Protein", width="medium"), | |
| "EC": st.column_config.LinkColumn("EC number", width="small", display_text=r"EC/([\d.]*\d)", | |
| help="L1 (class) → L4 (full EC number). Opens the ExPASy ENZYME entry."), | |
| "EC_name": st.column_config.TextColumn("Name", width="large", | |
| help="Enzyme class (L1–L3) or enzyme name (L4)."), | |
| "EC_level": st.column_config.TextColumn("Level", width="small"), | |
| "Probability": st.column_config.NumberColumn("Score", format="%.3f", width="small"), | |
| }, | |
| ) | |
| st.caption("Predictions form a consistent hierarchy: every predicted L4 number has its predicted " | |
| "L3/L2/L1 ancestors. A protein can stop at an intermediate level when no deeper level " | |
| "passes the threshold.") | |
| st.caption(f"Showing {len(view):,} of {len(df):,} predictions") | |
| def render_knowledge_graph(df_go, df_ec, proteins, aspects): | |
| if len(proteins) > MAX_KG_VIZ_PROTEINS: | |
| st.info(f"Knowledge graph views are available for runs of up to {MAX_KG_VIZ_PROTEINS} proteins.") | |
| return | |
| go_ok = df_go is not None | |
| ec_ok = df_ec is not None | |
| st.markdown('<span class="phgt-muted">Explore the biological relationships around a protein that ' | |
| "the model draws on: GO annotations, EC numbers, domains, interactions, pathways and more. " | |
| "Views go up to second-degree connections; for deeper exploration, " | |
| f'<a href="{KG_DOWNLOAD_URL}" target="_blank">download the complete knowledge graph</a>.</span>', | |
| unsafe_allow_html=True) | |
| with st.expander("How to read this graph"): | |
| st.markdown(KG_VIEW_GUIDE) | |
| # Which predictions to overlay on the graph (only when both types were run). | |
| if go_ok and ec_ok: | |
| overlays = st.pills("Predictions to show on the graph", ["GO terms", "EC numbers"], | |
| selection_mode="multi", default=["GO terms", "EC numbers"], key="viz_overlays") | |
| else: | |
| overlays = (["GO terms"] if go_ok else []) + (["EC numbers"] if ec_ok else []) | |
| show_go = "GO terms" in overlays | |
| show_ec = "EC numbers" in overlays | |
| # General graph settings (apply to every node type). | |
| g1, g2, g3 = st.columns([1.6, 1, 1]) | |
| protein = g1.selectbox("Protein", proteins, key="viz_protein") | |
| limit = g2.slider( | |
| "Neighbours per edge type", 5, 50, 10, step=5, | |
| help="Maximum direct neighbours shown for each relationship type (domains, interactions, " | |
| "pathways, …), including known annotations outside the top predictions.") | |
| second_limit = g3.slider( | |
| "Second-degree neighbours", 0, 10, 0, | |
| help="Neighbours of the protein's direct neighbours, e.g. other proteins sharing a domain or " | |
| "pathway with it. 0 shows direct neighbours only; higher values quickly make the graph dense. " | |
| "Does not affect the EC hierarchy, which is always drawn in full.") | |
| include_second = second_limit > 0 | |
| # Prediction-type-specific settings (only for the overlays being shown). | |
| pred_limit, ec_top1 = 5, False | |
| if show_go or show_ec: | |
| boxes = st.columns(2) if (show_go and show_ec) else [st.container()] | |
| bi = 0 | |
| box_h = 150 # equal height so the GO (slider) and EC (checkbox) cards line up | |
| if show_go: | |
| with boxes[bi]: | |
| with st.container(border=True, height=box_h): | |
| st.markdown("**GO term predictions**") | |
| pred_limit = st.slider( | |
| "Top terms shown per category", 1, 20, 5, key="go_pred_limit", | |
| help="Highest-scoring GO predictions per category. Purple: also annotated in the " | |
| "knowledge graph; red: novel.") | |
| bi += 1 | |
| if show_ec: | |
| with boxes[bi]: | |
| with st.container(border=True, height=box_h): | |
| st.markdown("**EC number predictions**") | |
| ec_top1 = st.checkbox( | |
| "Best prediction per level only", key="ec_top1", | |
| help="Show only the single highest-scoring EC at each hierarchy level (one clean " | |
| "chain) instead of every EC above the threshold.") | |
| st.caption("Otherwise every EC scoring above the threshold is shown.") | |
| # The EC knowledge graph is a superset (GO context + EC hierarchy), so it serves both overlays; | |
| # use the GO graph only when EC was not predicted. | |
| kg = get_ec_kg() if ec_ok else get_kg() | |
| viz_key = f"{protein}|{pred_limit}|{limit}|{second_limit}|{show_go}|{show_ec}|{ec_top1}" | |
| viz = st.session_state.viz.get(viz_key) | |
| if viz is None: | |
| disabled = not (show_go or show_ec) | |
| if st.button("Show graph", type="primary", key="viz_go", disabled=disabled): | |
| with st.spinner("Building subgraph…"): | |
| path, edges = visualize_protein_subgraph( | |
| kg, protein, go_df=df_go, ec_df=df_ec, show_go=show_go, show_ec=show_ec, | |
| limit=limit, prediction_limit=pred_limit, predicted_categories=aspects, | |
| second_degree_limit=second_limit, include_second_degree=include_second, ec_top1=ec_top1) | |
| st.session_state.viz[viz_key] = {"path": path, "edges": edges} | |
| st.rerun(scope="fragment") | |
| if disabled: | |
| st.caption("Select at least one prediction type to overlay.") | |
| return | |
| with open(viz["path"], "r", encoding="utf-8") as f: | |
| # 760px graph with both legends inside it; PNG and edges-JSON downloads are in its toolbox | |
| # (kg_graph_template.html) | |
| st.components.v1.html(f.read(), height=775, scrolling=True) | |
| def render_step_3(): | |
| proteins = list(st.session_state.proteins) | |
| aspects = selected_aspects() | |
| predict_ec = st.session_state.predict_ec | |
| if not proteins or not (aspects or predict_ec): | |
| go_to(1 if not proteins else 2) | |
| st.rerun() | |
| threshold = current_threshold() | |
| run_key = (tuple(proteins), tuple(aspects), predict_ec, threshold) | |
| results = st.session_state.results | |
| if results is None or results["key"] != run_key: | |
| clear_visualizations() | |
| cache = st.session_state.results_cache | |
| if run_key in cache: # switching back to settings already run in this session is instant | |
| payload = cache[run_key] | |
| else: | |
| try: | |
| df_go = run_go_prediction(proteins, aspects, threshold) if aspects else None | |
| df_ec = run_ec_prediction(proteins, threshold) if predict_ec else None | |
| except Exception as exc: # surface failures instead of a blank page | |
| st.error(f"Prediction failed: {exc}") | |
| st.button("← Back to settings", on_click=go_to, args=(2,)) | |
| return | |
| payload = {"go": df_go, "ec": df_ec} | |
| cache[run_key] = payload | |
| while len(cache) > 3: # keep memory per visitor bounded | |
| cache.pop(next(iter(cache))) | |
| st.session_state.results = {"key": run_key, "payload": payload} | |
| results = st.session_state.results | |
| payload = results["payload"] | |
| df_go, df_ec = payload["go"], payload["ec"] | |
| head, b1, b2 = st.columns([3, 1.1, 1.1], vertical_alignment="bottom") | |
| head.subheader("Results") | |
| b1.button("Change settings", on_click=go_to, args=(2,), use_container_width=True) | |
| b2.button("New prediction", on_click=start_new_prediction, use_container_width=True) | |
| m1, m2, m3, m4 = st.columns(4) | |
| m1.metric("Proteins", len(proteins)) | |
| m2.metric("Predicted GO terms", f"{len(df_go):,}" if df_go is not None else "—") | |
| m3.metric("Predicted EC numbers", f"{len(df_ec):,}" if df_ec is not None else "—") | |
| m4.metric("Score threshold", f"{threshold:.2f}") | |
| tab_specs = [] | |
| if aspects: | |
| tab_specs.append(("GO terms", lambda: render_predictions(df_go, threshold))) | |
| if predict_ec: | |
| tab_specs.append(("EC numbers", lambda: render_ec_predictions(df_ec, threshold))) | |
| if aspects or predict_ec: | |
| tab_specs.append(("Knowledge graph", lambda: render_knowledge_graph(df_go, df_ec, proteins, aspects))) | |
| for tab, (_, render) in zip(st.tabs([label for label, _ in tab_specs]), tab_specs): | |
| with tab: | |
| render() | |
| # Render the step inside one st.empty() slot so the previous step's widgets are replaced | |
| # immediately instead of lingering (greyed out) while a long prediction runs. | |
| with st.empty().container(): | |
| {1: render_step_1, 2: render_step_2, 3: render_step_3}[step]() | |