Spaces:
Build error
Build error
Update app.py
Browse files1234456878910111214131415181617184 unmodified lines2324252930312627281 unmodified line3031323940413334353646373839409 unmodified lines50515262636465535455565771727358596013 unmodified lines747576937778799798998081822 unmodified lines85868710810911088899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215352 unmodified lines20620720816917020921021121221321417721517921621721821922022118518618718822222322422522646 unmodified lines27327427524224324424527627727816 unmodified lines29529629726829829930085 unmodified lines38638738836038939039139244 unmodified lines4374384394114124134144154164174404414424434214444454464472 unmodified lines4504514524304534544554564574584364594604614625 unmodified lines46846947044847147245045145245345447347447547647747847946046148048148248348432 unmodified lines5175185195205215225235245255265275285295305315065075085095105115325335135145155165175185345355365379 unmodified lines54754854953455055155255336 unmodified lines59059159257759359458058158258358459559659759859960059059159259359459559660160260360452 unmodified lines65765865965566066165765866266366466566618 unmodified lines6856866876836846886896906876916926936945 unmodified lines7007017027037047057067077087097107117127137146 unmodified lines7217227237117127137247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118127168138148158167207217227237247257267277287297307317327337348178188193 unmodified lines8238248257447457467477487498268277518287537547557567577588298307608317627637647657667677687697707717727737748328338347767777787797807818358368378387857867877887897908398408418423 unmodified lines8468478488498508018028038048058068078088098108118128138148518528538548168178188198208218228238248258268278288298558568578588598608618628328338348358368378388398408418428438448638648658668678688698708718728738748758768778788798468478488498508808818828838528848858868878548558568578888898901 unmodified line89289389486589589689786889889990090187287387487587687787887988088188288388488588690290390488888989090590689289389490790889789889990090190290390490590690790890990991091191291391491291391591691791891691992092191992092292392492592392692792892692792993093193293393193293393493593693793493594094194293693793894494594694794894995095195295395495595695795895996096196296396496596696796896993994094194294394494594694794894995095195295395495595695795895996096197097197296297497597696396497998098198298396598598696696798999096896997097197299499599697397499910001001100210039759769771006100797897998010109819821012983984101510169859869879889899909919921023102410251026993994995996997998999import ioimport osimport reimport mathimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tuplefrom typing import Dict, List, Tuple
import matplotlibmatplotlib.use("Agg")
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport streamlit as stfrom Bio import SeqIOfrom Bio.Seq import Seqfrom Bio.SeqFeature import CompoundLocationfrom dna_features_viewer import GraphicFeature, GraphicRecordfrom pycirclize import Circos4 unmodified lines gffutils = None
# -----------------------------# Streamlit page setup# -----------------------------st.set_page_config( page_title="Genome Visualization Tool", page_icon="🧬",1 unmodified line initial_sidebar_state="expanded",)
# -----------------------------# Styling# -----------------------------st.markdown( """ <style> .main-title { font-size: 2.0rem; font-size: 2rem; font-weight: 800; margin-bottom: 0.2rem; }9 unmodified lines background: rgba(250,250,250,0.02); margin-bottom: 0.8rem; } .small-note { font-size: 0.88rem; color: #666; } </style> """, unsafe_allow_html=True,)
# -----------------------------# Constants# -----------------------------FEATURE_COLORS = { "CDS": "#1f77b4", "gene": "#2ca02c",13 unmodified linesFASTA_EXTS = {".fa", ".fasta", ".fna", ".fas"}GB_EXTS = {".gb", ".gbk", ".genbank"}GFF_EXTS = {".gff", ".gff3"}
DNA_COMPLEMENT = str.maketrans("ATGCatgcNn", "TACGtacgNn")
# -----------------------------# Data classes# -----------------------------@dataclassclass ParsedGenome: records: List2 unmodified lines notes: List[str]
# -----------------------------# Utilities# -----------------------------def init_session_state(): defaults = { "analysis_done": False, "parsed": None, "record_ids": [], "selected_record_id": None, "full_df": pd.DataFrame(), "filtered_df": pd.DataFrame(), "display_df": pd.DataFrame(), "stats": {}, "notes": [], "available_types": [], "selected_types_cache": [], "legend_html": "", "circ_png": None, "circ_svg": None, "circ_pdf": None, "lin_png": None, "lin_svg": None, "lin_pdf": None, "table_csv": None, "summary_zip": None, "stats_df": pd.DataFrame(), "dist_df": pd.DataFrame(), "last_run_signature": None, } for k, v in defaults.items(): if k not in st.session_state: st.session_state[k] = v
def clear_results(): keys = [ "analysis_done", "parsed", "record_ids", "selected_record_id", "full_df", "filtered_df", "display_df", "stats", "notes", "available_types", "selected_types_cache", "legend_html", "circ_png", "circ_svg", "circ_pdf", "lin_png", "lin_svg", "lin_pdf", "table_csv", "summary_zip", "stats_df", "dist_df", "last_run_signature", ] for key in keys: if key in st.session_state: del st.session_state[key] init_session_state()
def safe_int(value, default=0): try: return int(value)52 unmodified lines
def chunk_gc_content(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]: seq = str(sequence).upper() if not seq: return [], [] positions = [] values = [] for i in range(0, len(seq), window_size): window = seq[i:i + window_size] if not window: continue gc = compute_gc_percent(window) positions.append(i + len(window) // 2) values.append(gc) values.append(compute_gc_percent(window)) return positions, values
def gc_skew_windows(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]: seq = str(sequence).upper() if not seq: return [], []
values = [] positions = [] values = [] for i in range(0, len(seq), window_size): window = seq[i:i + window_size] g = window.count("G")46 unmodified lines
def find_orfs_in_sequence(sequence: str, min_aa: int = 90) -> pd.DataFrame: """ Lightweight ORF finder for FASTA-only mode. Coordinates are 0-based half-open for plotting consistency. """ seq = str(sequence).upper() seq_len = len(seq) stops = {"TAA", "TAG", "TGA"}16 unmodified lines if strand_value == 1: start, end = i, j + 3 else: # map rc coords back to original start = seq_len - (j + 3) end = seq_len - i rows.append(85 unmodified lines alt_map[r.id.split()[0]] = r alt_map[r.name] = r
tables: Dict[str, List[dict]] = {r.id: [] for r in records} tables = {r.id: [] for r in records}
with tempfile.TemporaryDirectory() as td: db = build_gff_db(gff_text, td)44 unmodified lines return records, out
def parse_input_bundle( primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int,) -> ParsedGenome:def parse_input_bundle(primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int) -> ParsedGenome: notes = []
if input_mode == "GenBank": data = primary_upload.read() data = primary_upload.getvalue() records = parse_genbank_bytes(data) if not records: raise ValueError("No GenBank records were found.")2 unmodified lines return ParsedGenome(records=records, feature_tables=tables, source_mode="genbank", notes=notes)
if input_mode == "FASTA": data = primary_upload.read() data = primary_upload.getvalue() records = parse_fasta_bytes(data) if not records: raise ValueError("No FASTA records were found.") tables = {} for r in records: base = pd.DataFrame( empty_df = pd.DataFrame( columns=[ "record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source"5 unmodified lines orf_df.insert(0, "record_id", r.id) tables[r.id] = orf_df else: tables[r.id] = base tables[r.id] = empty_df else: tables[r.id] = base if infer_orfs: notes.append("FASTA-only input: ORF prediction was used to create approximate annotation tracks.") else: notes.append("FASTA-only input: no native annotations were available.") tables[r.id] = empty_df notes.append("FASTA-only input." + (" ORF prediction enabled." if infer_orfs else " No native annotation available.")) return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes)
if input_mode == "GFF + FASTA": if secondary_upload is None: raise ValueError("Both GFF/GFF3 and FASTA files are required.") gff_bytes = primary_upload.read() fasta_bytes = secondary_upload.read() gff_bytes = primary_upload.getvalue() fasta_bytes = secondary_upload.getvalue() records, tables = gff_and_fasta_to_tables(gff_bytes, fasta_bytes) notes.append("Parsed GFF/GFF3 annotation with FASTA sequence.") return ParsedGenome(records=records, feature_tables=tables, source_mode="gff_fasta", notes=notes)32 unmodified lines raise ValueError("ZIP contained a FASTA file but no records were parsed.") tables = {} for r in records: empty_df = pd.DataFrame( columns=[ "record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source" ] ) if infer_orfs: orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa) if not orf_df.empty: orf_df.insert(0, "record_id", r.id) tables[r.id] = orf_df else: tables[r.id] = pd.DataFrame( columns=[ "record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source" ] ) tables[r.id] = empty_df else: tables[r.id] = pd.DataFrame( columns=[ "record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source" ] ) tables[r.id] = empty_df notes.append(f"ZIP detected FASTA-only input: {fasta_name}") return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes)
9 unmodified lines filtered = filtered[filtered["feature_type"].isin(selected_types)].copy()
if filtered.empty: filtered["highlight"] = [] filtered["highlight"] = False return filtered
query = normalize_text(query).lower()36 unmodified lines
def draw_linear_map(record, filtered_df: pd.DataFrame, annotate_limit: int = 180): graphic_record = build_linear_graphic_record(record, filtered_df)
fig_height = 4.5 if len(filtered_df) <= 80 else 6.0 if len(filtered_df) <= 180 else 8.0 fig, ax = plt.subplots(figsize=(16, fig_height)) graphic_record.plot( ax=ax, with_ruler=True, annotate_inline=(len(filtered_df) <= annotate_limit), ) graphic_record.plot(ax=ax, with_ruler=True, annotate_inline=(len(filtered_df) <= annotate_limit)) ax.set_title(f"Linear Genome Map: {record.id}", fontsize=14, weight="bold") plt.tight_layout() return fig
def draw_circular_map( record, filtered_df: pd.DataFrame, show_gc_content: bool = True, show_gc_skew: bool = True, window_size: int = 1000,):def draw_circular_map(record, filtered_df: pd.DataFrame, show_gc_content: bool = True, show_gc_skew: bool = True, window_size: int = 1000): seq_len = len(record.seq) circos = Circos({record.id: seq_len}, space=2) sector = circos.sectors[0]52 unmodified lines
def fig_to_bytes(fig, fmt: str = "png", dpi: int = 300) -> bytes: buf = io.BytesIO() save_kwargs = {"bbox_inches": "tight"} kwargs = {"bbox_inches": "tight"} if fmt.lower() == "png": save_kwargs["dpi"] = dpi fig.savefig(buf, format=fmt, **save_kwargs) kwargs["dpi"] = dpi fig.savefig(buf, format=fmt, **kwargs) buf.seek(0) return buf.getvalue()
18 unmodified linesdef feature_distribution_table(df: pd.DataFrame) -> pd.DataFrame: if df.empty: return pd.DataFrame(columns=["feature_type", "count"]) vc = df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count") return vc return df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count")
def build_legend_html(feature_types: List[str]) -> str:def build_legend_html(feature_types: List[str], include_highlight: bool = False) -> str: parts = [] for ft in feature_types: color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"])5 unmodified lines </span> """ ) if include_highlight: parts.append( f""" <span style="display:inline-flex;align-items:center;margin-right:14px;margin-bottom:6px;"> <span style="display:inline-block;width:13px;height:13px;border-radius:3px;background:{FEATURE_COLORS['highlight']};margin-right:6px;border:1px solid #aaa;"></span> <span style="font-size:0.92rem;">highlighted match</span> </span> """ ) return "".join(parts)
6 unmodified lines return mem.getvalue()
# -----------------------------# UI# -----------------------------def run_analysis( primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa, gene_query, show_gc_content, show_gc_skew, window_size,): parsed = parse_input_bundle( primary_upload=primary_upload, secondary_upload=secondary_upload, input_mode=input_mode, infer_orfs=infer_orfs, min_orf_aa=min_orf_aa, )
record_ids = [r.id for r in parsed.records] selected_record_id = record_ids[0] record = parsed.records[0] full_df = parsed.feature_tables.get(record.id, pd.DataFrame())
available_types = sorted(full_df["feature_type"].dropna().unique().tolist()) if not full_df.empty else [] default_selected = [x for x in DEFAULT_FEATURES if x in available_types] if not default_selected: default_selected = available_types
filtered_df = filter_features(full_df, default_selected, gene_query) display_df = filtered_df.copy() if not display_df.empty and "highlight" in display_df.columns: display_df["highlight"] = display_df["highlight"].map({True: "yes", False: "no"})
stats = build_summary_stats(record, full_df, filtered_df) stats_df = pd.DataFrame([stats]) dist_df = feature_distribution_table(full_df) legend_html = build_legend_html( default_selected, include_highlight=(gene_query.strip() and not filtered_df.empty and filtered_df["highlight"].any()) )
circ_fig = draw_circular_map( record=record, filtered_df=filtered_df, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=int(window_size), ) lin_fig = draw_linear_map(record, filtered_df) if not filtered_df.empty else None
st.session_state["parsed"] = parsed st.session_state["analysis_done"] = True st.session_state["record_ids"] = record_ids st.session_state["selected_record_id"] = selected_record_id st.session_state["full_df"] = full_df st.session_state["filtered_df"] = filtered_df st.session_state["display_df"] = display_df st.session_state["stats"] = stats st.session_state["notes"] = parsed.notes st.session_state["available_types"] = available_types st.session_state["selected_types_cache"] = default_selected st.session_state["legend_html"] = legend_html st.session_state["stats_df"] = stats_df st.session_state["dist_df"] = dist_df
st.session_state["circ_png"] = fig_to_bytes(circ_fig, fmt="png") st.session_state["circ_svg"] = fig_to_bytes(circ_fig, fmt="svg") st.session_state["circ_pdf"] = fig_to_bytes(circ_fig, fmt="pdf") plt.close(circ_fig)
if lin_fig is not None: st.session_state["lin_png"] = fig_to_bytes(lin_fig, fmt="png") st.session_state["lin_svg"] = fig_to_bytes(lin_fig, fmt="svg") st.session_state["lin_pdf"] = fig_to_bytes(lin_fig, fmt="pdf") plt.close(lin_fig) else: st.session_state["lin_png"] = None st.session_state["lin_svg"] = None st.session_state["lin_pdf"] = None
st.session_state["table_csv"] = display_df.to_csv(index=False).encode("utf-8") st.session_state["summary_zip"] = make_results_bundle_csv(stats_df, display_df)
init_session_state()
st.markdown('<div class="main-title">🧬 Genome Visualization Tool</div>', unsafe_allow_html=True)st.markdown( '<div class="subtle">Interactive circular and linear genome maps with support for GenBank, FASTA, GFF/GFF3 + FASTA, and ZIP packages.</div>', '<div class="subtle">Results remain visible after download and are cleared only when you press Clear results.</div>', unsafe_allow_html=True,)
with st.expander("Supported input formats", expanded=False): st.markdown( """ **Recommended for full gene annotation visualization** - **GenBank (.gb, .gbk, .genbank)** - **GFF/GFF3 + FASTA**
**Also supported** - **FASTA** FASTA alone does not contain annotations, so this app can optionally predict simple ORFs for approximate feature tracks. - **ZIP** Auto-detects supported file combinations inside a ZIP archive. """ )
with st.sidebar: st.header("Input") input_mode = st.selectbox(3 unmodified lines )
if input_mode == "GenBank": primary_upload = st.file_uploader( "Upload GenBank file", type=["gb", "gbk", "genbank"], accept_multiple_files=False, help="Best format for full sequence + annotation visualization.", ) primary_upload = st.file_uploader("Upload GenBank file", type=["gb", "gbk", "genbank"], accept_multiple_files=False) secondary_upload = None
elif input_mode == "FASTA": primary_upload = st.file_uploader( "Upload FASTA file", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=False, help="FASTA contains sequence only. You can enable ORF prediction below.", ) primary_upload = st.file_uploader("Upload FASTA file", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=False) secondary_upload = None
elif input_mode == "GFF + FASTA": primary_upload = st.file_uploader( "Upload GFF/GFF3 annotation file", type=["gff", "gff3"], accept_multiple_files=False, help="Gene coordinates and annotation table.", ) secondary_upload = st.file_uploader( "Upload matching FASTA file", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=False, help="Sequence used for coordinates and nucleotide statistics.", )
primary_upload = st.file_uploader("Upload GFF/GFF3 annotation file", type=["gff", "gff3"], accept_multiple_files=False) secondary_upload = st.file_uploader("Upload matching FASTA file", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=False) else: primary_upload = st.file_uploader( "Upload ZIP archive", type=["zip"], accept_multiple_files=False, help="ZIP can contain GenBank, or GFF/GFF3 + FASTA, or FASTA.", ) primary_upload = st.file_uploader("Upload ZIP archive", type=["zip"], accept_multiple_files=False) secondary_upload = None
st.header("Analysis settings") gene_query = st.text_input( "Search / highlight", value="", help="Search gene, locus tag, product, or note. Matches are highlighted in gold.", )
gene_query = st.text_input("Search / highlight", value="") infer_orfs = st.checkbox("Predict ORFs for FASTA-only input", value=True) min_orf_aa = st.slider("Minimum ORF length (aa)", min_value=30, max_value=300, value=90, step=10)
3 unmodified lines window_size = st.number_input("Window size", min_value=100, max_value=50000, value=1000, step=100)
run_button = st.button("Run visualization", type="primary", use_container_width=True) clear_button = st.button("Clear results", use_container_width=True)
# -----------------------------# Guard rails: don't process until user clicks# -----------------------------if not run_button: st.info("Upload your file(s), adjust settings, and click **Run visualization**.") st.stop()
if primary_upload is None: st.error("Please upload the required input file.") st.stop()
if input_mode == "GFF + FASTA" and secondary_upload is None: st.error("Please upload both the GFF/GFF3 file and the FASTA file.") st.stop()if clear_button: clear_results() st.rerun()
# -----------------------------# Parsing# -----------------------------with st.spinner("Parsing input and preparing visualization..."): try: parsed = parse_input_bundle( primary_upload=primary_upload, secondary_upload=secondary_upload, input_mode=input_mode, infer_orfs=infer_orfs, min_orf_aa=min_orf_aa, ) except Exception as exc: st.error(f"Input parsing failed: {exc}")if run_button: if primary_upload is None: st.error("Please upload the required input file.") st.stop() if input_mode == "GFF + FASTA" and secondary_upload is None: st.error("Please upload both the GFF/GFF3 file and the FASTA file.") st.stop()
if not parsed.records: st.error("No valid records were found.") st.stop()
record_ids = [r.id for r in parsed.records]selected_record_id = st.selectbox("Select record / contig", record_ids, index=0)record = next(r for r in parsed.records if r.id == selected_record_id)full_df = parsed.feature_tables.get(record.id, pd.DataFrame())
available_types = sorted(full_df["feature_type"].dropna().unique().tolist()) if not full_df.empty else []default_selected = [x for x in DEFAULT_FEATURES if x in available_types]if not default_selected: default_selected = available_types with st.spinner("Parsing input and preparing visualization..."): try: run_analysis( primary_upload=primary_upload, secondary_upload=secondary_upload, input_mode=input_mode, infer_orfs=infer_orfs, min_orf_aa=min_orf_aa, gene_query=gene_query, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=window_size, ) except Exception as exc: st.error(f"Input parsing failed: {exc}") st.stop()
selected_types = st.multiselect( "Feature types to display", options=available_types, default=default_selected,)if not st.session_state["analysis_done"]: st.info("Upload your file(s), click Run visualization, and the results will stay on screen until you click Clear results.") st.stop()
filtered_df = filter_features(full_df, selected_types, gene_query)stats = st.session_state["stats"]display_df = st.session_state["display_df"]full_df = st.session_state["full_df"]
# -----------------------------# Summary cards# -----------------------------stats = build_summary_stats(record, full_df, filtered_df)c1, c2, c3, c4, c5 = st.columns(5)c1.metric("Genome length (bp)", f"{stats['Genome length (bp)']:,}")c2.metric("GC (%)", stats["GC (%)"])1 unmodified linec4.metric("Total parsed features", stats["Total parsed features"])c5.metric("CDS", stats["CDS"])
if parsed.notes:if st.session_state["notes"]: st.markdown('<div class="card">', unsafe_allow_html=True) st.markdown("**Run notes**") for note in parsed.notes: for note in st.session_state["notes"]: st.write(f"- {note}") st.markdown("</div>", unsafe_allow_html=True)
legend_types = selected_types[:]if gene_query.strip() and not filtered_df.empty and filtered_df["highlight"].any(): legend_html = build_legend_html(legend_types) + ( f""" <span style="display:inline-flex;align-items:center;margin-right:14px;margin-bottom:6px;"> <span style="display:inline-block;width:13px;height:13px;border-radius:3px;background:{FEATURE_COLORS['highlight']};margin-right:6px;border:1px solid #aaa;"></span> <span style="font-size:0.92rem;">highlighted match</span> </span> """ )else: legend_html = build_legend_html(legend_types)
if legend_html: st.markdown('<div class="card"><b>Feature legend</b><br>' + legend_html + '</div>', unsafe_allow_html=True)if st.session_state["legend_html"]: st.markdown('<div class="card"><b>Feature legend</b><br>' + st.session_state["legend_html"] + '</div>', unsafe_allow_html=True)
tab1, tab2, tab3, tab4 = st.tabs( ["Circular Map", "Linear Map", "Annotation Table", "Statistics"])tab1, tab2, tab3, tab4 = st.tabs(["Circular Map", "Linear Map", "Annotation Table", "Statistics"])
# -----------------------------# Circular map# -----------------------------with tab1: st.subheader("Circular genome map")
try: circ_fig = draw_circular_map( record=record, filtered_df=filtered_df, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=int(window_size), ) st.pyplot(circ_fig, use_container_width=True)
col1, col2, col3 = st.columns(3) with col1: if st.session_state["circ_png"] is not None: st.image(st.session_state["circ_png"], use_container_width=True) a, b, c = st.columns(3) with a: st.download_button( "Download PNG", data=fig_to_bytes(circ_fig, fmt="png"), file_name=f"{record.id}_circular_map.png", data=st.session_state["circ_png"], file_name="circular_map.png", mime="image/png", ) with col2: with b: st.download_button( "Download SVG", data=fig_to_bytes(circ_fig, fmt="svg"), file_name=f"{record.id}_circular_map.svg", data=st.session_state["circ_svg"], file_name="circular_map.svg", mime="image/svg+xml", ) with col3: with c: st.download_button( "Download PDF", data=fig_to_bytes(circ_fig, fmt="pdf"), file_name=f"{record.id}_circular_map.pdf", data=st.session_state["circ_pdf"], file_name="circular_map.pdf", mime="application/pdf", )
plt.close(circ_fig) except Exception as exc: st.error(f"Could not render circular map: {exc}")
# -----------------------------# Linear map# -----------------------------with tab2: st.subheader("Linear gene annotation map")
if filtered_df.empty: st.warning("No features matched the selected filters.") if st.session_state["lin_png"] is None: st.warning("No linear map available for the current result.") else: try: lin_fig = draw_linear_map(record, filtered_df) st.pyplot(lin_fig, use_container_width=True)
col1, col2, col3 = st.columns(3) with col1: st.download_button( "Download PNG", data=fig_to_bytes(lin_fig, fmt="png"), file_name=f"{record.id}_linear_map.png", mime="image/png", ) with col2: st.download_button( "Download SVG", data=fig_to_bytes(lin_fig, fmt="svg"), file_name=f"{record.id}_linear_map.svg", mime="image/svg+xml", ) with col3: st.download_button( "Download PDF", data=fig_to_bytes(lin_fig, fmt="pdf"), file_name=f"{record.id}_linear_map.pdf", mime="application/pdf", ) st.image(st.session_state["lin_png"], use_container_width=True) a, b, c = st.columns(3) with a: st.download_button( "Download PNG", data=st.session_state["lin_png"], file_name="linear_map.png", mime="image/png", ) with b: st.download_button( "Download SVG", data=st.session_state["lin_svg"], file_name="linear_map.svg", mime="image/svg+xml", ) with c: st.download_button( "Download PDF", data=st.session_state["lin_pdf"], file_name="linear_map.pdf", mime="application/pdf", ) plt.close(lin_fig) except Exception as exc: st.error(f"Could not render linear map: {exc}")
# -----------------------------# Table# -----------------------------with tab3: st.subheader("Annotation table")
display_df = filtered_df.copy() if not display_df.empty and "highlight" in display_df.columns: display_df["highlight"] = display_df["highlight"].map({True: "yes", False: "no"})
st.dataframe(display_df, use_container_width=True, height=430)
table_csv = display_df.to_csv(index=False).encode("utf-8") st.download_button( "Download annotation table (CSV)", data=table_csv, file_name=f"{record.id}_feature_annotations.csv", data=st.session_state["table_csv"], file_name="feature_annotations.csv", mime="text/csv", )
# -----------------------------# Statistics# -----------------------------with tab4: st.subheader("Genome statistics and feature distribution")
stats_df = pd.DataFrame([stats]) dist_df = feature_distribution_table(full_df)
left, right = st.columns([1, 1]) left, right = st.columns(2) with left: st.markdown("**Summary statistics**") st.dataframe(stats_df, use_container_width=True, height=220)
st.dataframe(st.session_state["stats_df"], use_container_width=True, height=220) with right: st.markdown("**Feature type distribution**") st.dataframe(dist_df, use_container_width=True, height=220) st.dataframe(st.session_state["dist_df"], use_container_width=True, height=220)
summary_zip = make_results_bundle_csv(stats_df, display_df if "display_df" in locals() else filtered_df) st.download_button( "Download summary bundle (ZIP)", data=summary_zip, file_name=f"{record.id}_results_bundle.zip", data=st.session_state["summary_zip"], file_name="results_bundle.zip", mime="application/zip", )
st.markdown("---")st.markdown( """ **Interpretation notes** - **GenBank** and **GFF + FASTA** provide true annotation-based maps. - **FASTA-only** does not contain annotation metadata; ORF mode gives an approximate coding-region view. - For journal-quality gene annotation figures, prefer **GenBank** or **GFF/GFF3 + FASTA**. **How this revision works** - Results are saved in `st.session_state` - Download buttons use saved bytes, not freshly regenerated figures - Nothing disappears after download - Results are removed only when **Clear results** is clicked """)app.py+282-311