Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314151617181920214 unmodified lines2627282930313233341 unmodified line36373839404142434445464748499 unmodified lines59606162636465666768697071727374757613 unmodified lines909192939495969798991001011022 unmodified lines10510610710810911011111211352 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119246 unmodified lines23924024124224324424524624724816 unmodified lines26526626726826927027185 unmodified lines35735835936036136236344 unmodified lines4084094104114124134144154164174184194204214224234242 unmodified lines4274284294304314324334344354364374384395 unmodified lines44544644744844945045145245345445545645745845946046146246346432 unmodified lines4974984995005015025035045055065075085095105115125135145155165175185195205219 unmodified lines53153253353453553653736 unmodified lines57457557657757857958058158258358458558658758858959059159259359459559659759859952 unmodified lines65265365465565665765865966066118 unmodified lines6806816826836846856866876886896905 unmodified lines6966976986997007016 unmodified lines7087097107117127137147157167177187197207217227237247257267277287297307317327337347357367373 unmodified lines7417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927933 unmodified lines7977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598601 unmodified line86286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028import ioimport osimport reimport mathimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tupleimport 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 linesgffutils = None# -----------------------------# Streamlit page setup# -----------------------------st.set_page_config(page_title="Genome Visualization Tool",page_icon="🧬",1 unmodified lineinitial_sidebar_state="expanded",)# -----------------------------# Styling# -----------------------------st.markdown("""<style>.main-title {font-size: 2.0rem;font-weight: 800;margin-bottom: 0.2rem;}9 unmodified linesbackground: 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 linesnotes: List[str]# -----------------------------# Utilities# -----------------------------def safe_int(value, default=0):try:return int(value)52 unmodified linesdef 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:continuegc = compute_gc_percent(window)positions.append(i + len(window) // 2)values.append(gc)return positions, valuesdef gc_skew_windows(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]:seq = str(sequence).upper()if not seq:return [], []values = []positions = []for i in range(0, len(seq), window_size):window = seq[i:i + window_size]g = window.count("G")46 unmodified linesdef 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 linesif strand_value == 1:start, end = i, j + 3else:# map rc coords back to originalstart = seq_len - (j + 3)end = seq_len - irows.append(85 unmodified linesalt_map[r.id.split()[0]] = ralt_map[r.name] = rtables: Dict[str, List[dict]] = {r.id: [] for r in records}with tempfile.TemporaryDirectory() as td:db = build_gff_db(gff_text, td)44 unmodified linesreturn records, outdef 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()records = parse_genbank_bytes(data)if not records:raise ValueError("No GenBank records were found.")2 unmodified linesreturn ParsedGenome(records=records, feature_tables=tables, source_mode="genbank", notes=notes)if input_mode == "FASTA":data = primary_upload.read()records = parse_fasta_bytes(data)if not records:raise ValueError("No FASTA records were found.")tables = {}for r in records:base = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"5 unmodified linesorf_df.insert(0, "record_id", r.id)tables[r.id] = orf_dfelse:tables[r.id] = baseelse:tables[r.id] = baseif 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.")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()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 linesraise ValueError("ZIP contained a FASTA file but no records were parsed.")tables = {}for r in records: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_dfelse:tables[r.id] = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"])else:tables[r.id] = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"])notes.append(f"ZIP detected FASTA-only input: {fasta_name}")return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes)9 unmodified linesfiltered = filtered[filtered["feature_type"].isin(selected_types)].copy()if filtered.empty:filtered["highlight"] = []return filteredquery = normalize_text(query).lower()36 unmodified linesdef 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.0fig, ax = plt.subplots(figsize=(16, fig_height))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 figdef 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 linesdef fig_to_bytes(fig, fmt: str = "png", dpi: int = 300) -> bytes:buf = io.BytesIO()save_kwargs = {"bbox_inches": "tight"}if fmt.lower() == "png":save_kwargs["dpi"] = dpifig.savefig(buf, format=fmt, **save_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 vcdef build_legend_html(feature_types: List[str]) -> str:parts = []for ft in feature_types:color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"])5 unmodified lines</span>""")return "".join(parts)6 unmodified linesreturn mem.getvalue()# -----------------------------# UI# -----------------------------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>',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.",)secondary_upload = Noneelif 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.",)secondary_upload = Noneelif 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.",)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.",)secondary_upload = Nonest.header("Analysis settings")gene_query = st.text_input("Search / highlight",value="",help="Search gene, locus tag, product, or note. Matches are highlighted in gold.",)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 lineswindow_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)# -----------------------------# 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()# -----------------------------# 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}")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_typesselected_types = st.multiselect("Feature types to display",options=available_types,default=default_selected,)filtered_df = filter_features(full_df, selected_types, gene_query)# -----------------------------# 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:st.markdown('<div class="card">', unsafe_allow_html=True)st.markdown("**Run notes**")for note in parsed.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)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:st.download_button("Download PNG",data=fig_to_bytes(circ_fig, fmt="png"),file_name=f"{record.id}_circular_map.png",mime="image/png",)with col2:st.download_button("Download SVG",data=fig_to_bytes(circ_fig, fmt="svg"),file_name=f"{record.id}_circular_map.svg",mime="image/svg+xml",)with col3:st.download_button("Download PDF",data=fig_to_bytes(circ_fig, fmt="pdf"),file_name=f"{record.id}_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.")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",)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",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])with left:st.markdown("**Summary statistics**")st.dataframe(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)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",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**.""")1234567891011121314151617184 unmodified lines2324252627281 unmodified line30313233343536373839409 unmodified lines505152535455565758596013 unmodified lines7475767778798081822 unmodified lines85868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215352 unmodified lines20620720820921021121221321421521621721821922022122222322422522646 unmodified lines27327427527627727816 unmodified lines29529629729829930085 unmodified lines38638738838939039139244 unmodified lines4374384394404414424434444454464472 unmodified lines4504514524534544554564574584594604614625 unmodified lines46846947047147247347447547647747847948048148248348432 unmodified lines5175185195205215225235245255265275285295305315325335345355365379 unmodified lines54754854955055155255336 unmodified lines59059159259359459559659759859960060160260360452 unmodified lines65765865966066166266366466566618 unmodified lines6856866876886896906916926936945 unmodified lines7007017027037047057067077087097107117127137146 unmodified lines7217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188193 unmodified lines8238248258268278288298308318328338348358368378388398408418423 unmodified lines8468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898901 unmodified line892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999import ioimport osimport reimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Tupleimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport pandas as pdimport streamlit as stfrom Bio import SeqIOfrom Bio.SeqFeature import CompoundLocationfrom dna_features_viewer import GraphicFeature, GraphicRecordfrom pycirclize import Circos4 unmodified linesgffutils = Nonest.set_page_config(page_title="Genome Visualization Tool",page_icon="🧬",1 unmodified lineinitial_sidebar_state="expanded",)st.markdown("""<style>.main-title {font-size: 2rem;font-weight: 800;margin-bottom: 0.2rem;}9 unmodified linesbackground: rgba(250,250,250,0.02);margin-bottom: 0.8rem;}</style>""",unsafe_allow_html=True,)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")@dataclassclass ParsedGenome:records: List2 unmodified linesnotes: List[str]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] = vdef 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 linesdef chunk_gc_content(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]:seq = str(sequence).upper()positions = []values = []for i in range(0, len(seq), window_size):window = seq[i:i + window_size]if not window:continuepositions.append(i + len(window) // 2)values.append(compute_gc_percent(window))return positions, valuesdef gc_skew_windows(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]:seq = str(sequence).upper()positions = []values = []for i in range(0, len(seq), window_size):window = seq[i:i + window_size]g = window.count("G")46 unmodified linesdef find_orfs_in_sequence(sequence: str, min_aa: int = 90) -> pd.DataFrame:seq = str(sequence).upper()seq_len = len(seq)stops = {"TAA", "TAG", "TGA"}16 unmodified linesif strand_value == 1:start, end = i, j + 3else:start = seq_len - (j + 3)end = seq_len - irows.append(85 unmodified linesalt_map[r.id.split()[0]] = ralt_map[r.name] = rtables = {r.id: [] for r in records}with tempfile.TemporaryDirectory() as td:db = build_gff_db(gff_text, td)44 unmodified linesreturn records, outdef 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.getvalue()records = parse_genbank_bytes(data)if not records:raise ValueError("No GenBank records were found.")2 unmodified linesreturn ParsedGenome(records=records, feature_tables=tables, source_mode="genbank", notes=notes)if input_mode == "FASTA":data = primary_upload.getvalue()records = parse_fasta_bytes(data)if not records:raise ValueError("No FASTA records were found.")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"5 unmodified linesorf_df.insert(0, "record_id", r.id)tables[r.id] = orf_dfelse:tables[r.id] = empty_dfelse:tables[r.id] = empty_dfnotes.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.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 linesraise 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_dfelse:tables[r.id] = empty_dfelse:tables[r.id] = empty_dfnotes.append(f"ZIP detected FASTA-only input: {fasta_name}")return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes)9 unmodified linesfiltered = filtered[filtered["feature_type"].isin(selected_types)].copy()if filtered.empty:filtered["highlight"] = Falsereturn filteredquery = normalize_text(query).lower()36 unmodified linesdef 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.0fig, ax = plt.subplots(figsize=(16, fig_height))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 figdef 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 linesdef fig_to_bytes(fig, fmt: str = "png", dpi: int = 300) -> bytes:buf = io.BytesIO()kwargs = {"bbox_inches": "tight"}if fmt.lower() == "png":kwargs["dpi"] = dpifig.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"])return df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count")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 linesreturn mem.getvalue()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_typesfiltered_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 Nonest.session_state["parsed"] = parsedst.session_state["analysis_done"] = Truest.session_state["record_ids"] = record_idsst.session_state["selected_record_id"] = selected_record_idst.session_state["full_df"] = full_dfst.session_state["filtered_df"] = filtered_dfst.session_state["display_df"] = display_dfst.session_state["stats"] = statsst.session_state["notes"] = parsed.notesst.session_state["available_types"] = available_typesst.session_state["selected_types_cache"] = default_selectedst.session_state["legend_html"] = legend_htmlst.session_state["stats_df"] = stats_dfst.session_state["dist_df"] = dist_dfst.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"] = Nonest.session_state["lin_svg"] = Nonest.session_state["lin_pdf"] = Nonest.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">Results remain visible after download and are cleared only when you press Clear results.</div>',unsafe_allow_html=True,)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)secondary_upload = Noneelif input_mode == "FASTA":primary_upload = st.file_uploader("Upload FASTA file", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=False)secondary_upload = Noneelif input_mode == "GFF + FASTA":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)secondary_upload = Nonest.header("Analysis settings")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 lineswindow_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)if clear_button:clear_results()st.rerun()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()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()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()stats = st.session_state["stats"]display_df = st.session_state["display_df"]full_df = st.session_state["full_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 st.session_state["notes"]:st.markdown('<div class="card">', unsafe_allow_html=True)st.markdown("**Run notes**")for note in st.session_state["notes"]:st.write(f"- {note}")st.markdown("</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"])with tab1:st.subheader("Circular genome map")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=st.session_state["circ_png"],file_name="circular_map.png",mime="image/png",)with b:st.download_button("Download SVG",data=st.session_state["circ_svg"],file_name="circular_map.svg",mime="image/svg+xml",)with c:st.download_button("Download PDF",data=st.session_state["circ_pdf"],file_name="circular_map.pdf",mime="application/pdf",)with tab2:st.subheader("Linear gene annotation map")if st.session_state["lin_png"] is None:st.warning("No linear map available for the current result.")else: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",)with tab3:st.subheader("Annotation table")st.dataframe(display_df, use_container_width=True, height=430)st.download_button("Download annotation table (CSV)",data=st.session_state["table_csv"],file_name="feature_annotations.csv",mime="text/csv",)with tab4:st.subheader("Genome statistics and feature distribution")left, right = st.columns(2)with left:st.markdown("**Summary statistics**")st.dataframe(st.session_state["stats_df"], use_container_width=True, height=220)with right:st.markdown("**Feature type distribution**")st.dataframe(st.session_state["dist_df"], use_container_width=True, height=220)st.download_button("Download summary bundle (ZIP)",data=st.session_state["summary_zip"],file_name="results_bundle.zip",mime="application/zip",)st.markdown("---")st.markdown("""**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