Spaces:
Build error
Build error
Update app.py
Browse files9 unmodified lines1011121314157 unmodified lines23242526272829303 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666768697071727311 unmodified lines85868788899014 unmodified lines1051061071081091101111121131141151 unmodified line11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215378 unmodified lines232233234235236237302 unmodified lines54054154254354454554654754854955055114 unmodified lines5665675685695705715725735745755765775785795803 unmodified lines5845855865875885895905915925935945955965975985994 unmodified lines6046056066076086096106 unmodified lines6176186196206216226236247 unmodified lines6326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367371 unmodified line7397407417427437447457467477487497507517527537547557562 unmodified lines75976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079110 unmodified lines80280380480580680780880981081181281381481581618 unmodified lines8358368378388398408418428438448458468478488498509 unmodified lines8608618628638648658661 unmodified line8688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679681 unmodified line9709719729739749759769779789799809819829839849859869879889899909919929939949959969979989999 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltimport pandas as pdimport streamlit as stfrom Bio import SeqIO7 unmodified linesgffutils = Nonest.set_page_config(page_title="Genome Visualization Tool",page_icon="🧬",layout="wide",initial_sidebar_state="expanded",3 unmodified lines"""<style>.main-title {font-size: 2rem;font-weight: 800;margin-bottom: 0.2rem;}.subtle {color: #666;font-size: 0.98rem;margin-bottom: 1rem;}.card {padding: 0.9rem 1rem;border-radius: 14px;border: 1px solid rgba(120,120,120,0.18);background: rgba(250,250,250,0.02);margin-bottom: 0.8rem;}</style>""",unsafe_allow_html=True,)FEATURE_COLORS = {"CDS": "#1f77b4","gene": "#2ca02c","tRNA": "#ff7f0e","rRNA": "#d62728","ncRNA": "#e377c2","misc_feature": "#9467bd","repeat_region": "#8c564b","mobile_element": "#7f7f7f","source": "#bcbd22","ORF": "#17becf","default": "#4c78a8","highlight": "#ffd700",}DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "misc_feature", "repeat_region", "ORF"]11 unmodified linesnotes: List[str]def init_session_state():defaults = {"analysis_done": False,14 unmodified lines"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:1 unmodified linedef 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)78 unmodified linesreturn positions, valuesdef record_to_feature_table(record) -> pd.DataFrame:rows = []for feature in getattr(record, "features", []):302 unmodified linesraise ValueError("Unsupported input mode selected.")def filter_features(df: pd.DataFrame, selected_types: List[str], query: str) -> pd.DataFrame:filtered = df.copy()if selected_types:filtered = filtered[filtered["feature_type"].isin(selected_types)].copy()if filtered.empty:filtered["highlight"] = Falsereturn filtered14 unmodified linesreturn filtered.sort_values(["start", "end"], kind="stable").reset_index(drop=True)def build_linear_graphic_record(record, filtered_df: pd.DataFrame) -> GraphicRecord:features = []for _, row in filtered_df.iterrows():color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"])label = normalize_text(row.get("label", row["feature_type"]))if len(label) > 35:label = label[:32] + "..."strand = int(row["strand"]) if row["strand"] in (-1, 1) else 0features.append(GraphicFeature(start=int(row["start"]),3 unmodified lineslabel=label,))return GraphicRecord(sequence_length=len(record.seq), features=features)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.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 fig4 unmodified linessector = circos.sectors[0]tick_track = sector.add_track((88, 100))tick_track.axis(fc="#f7f7f7", ec="black", lw=0.4)tick_interval = max(1000, seq_len // 10) if seq_len <= 100000 else max(5000, seq_len // 12)tick_track.xticks_by_interval(6 unmodified linespos_track = sector.add_track((64, 84))neg_track = sector.add_track((44, 64))pos_track.axis(fc="#ffffff", ec="black", lw=0.3)neg_track.axis(fc="#ffffff", ec="black", lw=0.3)for _, row in filtered_df.iterrows():start = int(row["start"])7 unmodified linesinner_bottom = 10if show_gc_content:gc_track = sector.add_track((26, 40))gc_track.axis(fc="#f8f8f8", ec="black", lw=0.25)positions, gc_values = chunk_gc_content(record.seq, window_size)if gc_values:gc_track.line(positions, gc_values, vmin=0, vmax=100)baseline = [50.0] * len(gc_values)gc_track.fill_between(positions, gc_values, y2=baseline, vmin=0, vmax=100, alpha=0.35)inner_bottom = 24if show_gc_skew:skew_track = sector.add_track((inner_bottom, inner_bottom + 12))skew_track.axis(fc="#f8f8f8", ec="black", lw=0.25)positions, skews = gc_skew_windows(record.seq, window_size)if skews:vmax = max(abs(min(skews)), abs(max(skews)), 0.1)skew_track.line(positions, skews, vmin=-vmax, vmax=vmax)skew_track.fill_between(positions, skews, y2=0, vmin=-vmax, vmax=vmax, alpha=0.45)fig = circos.plotfig()fig.set_size_inches(8.8, 8.8)fig.suptitle(f"Circular Genome Map: {record.id}", fontsize=14, weight="bold", y=0.98)return figdef 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()def build_summary_stats(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame) -> Dict[str, object]:counts = full_df["feature_type"].value_counts().to_dict() if not full_df.empty else {}return {"Record ID": record.id,"Description": normalize_text(getattr(record, "description", "")),"Genome length (bp)": len(record.seq),"GC (%)": round(compute_gc_percent(record.seq), 2),"Displayed features": len(filtered_df),"Total parsed features": len(full_df),"CDS": safe_int(counts.get("CDS", 0)),"gene": safe_int(counts.get("gene", 0)),"tRNA": safe_int(counts.get("tRNA", 0)),"rRNA": safe_int(counts.get("rRNA", 0)),"ORF": safe_int(counts.get("ORF", 0)),}def 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"])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:{color};margin-right:6px;border:1px solid #aaa;"></span><span style="font-size:0.92rem;">{ft}</span></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)def make_results_bundle_csv(summary_df: pd.DataFrame, feature_df: pd.DataFrame) -> bytes:mem = io.BytesIO()with zipfile.ZipFile(mem, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:zf.writestr("summary_statistics.csv", summary_df.to_csv(index=False))zf.writestr("feature_annotations.csv", feature_df.to_csv(index=False))mem.seek(0)return 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,1 unmodified lineinfer_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"})2 unmodified linesstats_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")10 unmodified linesst.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,)18 unmodified linesprimary_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)st.header("Plot settings")show_gc_content = st.checkbox("Show GC content track", value=True)show_gc_skew = st.checkbox("Show GC skew track", value=True)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)9 unmodified linesst.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,1 unmodified lineinput_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 (%)"])c3.metric("Displayed features", stats["Displayed features"])c4.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"],1 unmodified linemime="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""")9 unmodified lines1011121314151617187 unmodified lines26272829303132333435363 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939411 unmodified lines10610710810911011111211311414 unmodified lines1291301311321331341351361371381391401411421431441 unmodified line14614714814915015115215315415515615715815978 unmodified lines238239240241242243244245246247248249250251252253254302 unmodified lines55755855956056156256356456556656756856957057157257357414 unmodified lines5895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726733 unmodified lines6776786796806816826836846856866876886896906916926936946956966976986997007017027037047054 unmodified lines7107117127137147157166 unmodified lines7237247257267277287297307 unmodified lines7387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908911 unmodified line8938948958968978988999009019029039049059069079089099109119129132 unmodified lines91691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794810 unmodified lines95996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100818 unmodified lines102710281029103010311032103310341035103610379 unmodified lines10471048104910501051105210531 unmodified line105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821 unmodified line11841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612179 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patchimport numpy as npimport pandas as pdimport streamlit as stfrom Bio import SeqIO7 unmodified linesgffutils = None# -----------------------------# Page config + styling# -----------------------------st.set_page_config(page_title="Genome Visualization Pro",page_icon="🧬",layout="wide",initial_sidebar_state="expanded",3 unmodified lines"""<style>.main-title {font-size: 2.2rem;font-weight: 900;margin-bottom: 0.15rem;letter-spacing: -0.02em;}.subtle {color: #5b6472;font-size: 1.0rem;margin-bottom: 1rem;}.card {padding: 0.95rem 1rem;border-radius: 16px;border: 1px solid rgba(120,120,120,0.18);background: linear-gradient(180deg, rgba(255,255,255,0.72), rgba(247,249,252,0.72));margin-bottom: 0.85rem;box-shadow: 0 2px 8px rgba(0,0,0,0.04);}.small-note {color: #6b7280;font-size: 0.88rem;}.section-title {font-weight: 800;font-size: 1.05rem;margin-bottom: 0.35rem;}</style>""",unsafe_allow_html=True,)# -----------------------------# Constants# -----------------------------FEATURE_COLORS = {"CDS": "#2F6BFF","gene": "#20A66B","tRNA": "#FF8C42","rRNA": "#D94E4E","ncRNA": "#C95DFF","misc_feature": "#7F60D9","repeat_region": "#8B6D5C","mobile_element": "#6E7781","source": "#C5A100","ORF": "#00A3A3","default": "#4C78A8","highlight": "#F2C94C",}DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "misc_feature", "repeat_region", "ORF"]11 unmodified linesnotes: List[str]# -----------------------------# Session helpers# -----------------------------def init_session_state():defaults = {"analysis_done": False,14 unmodified lines"lin_png": None,"lin_svg": None,"lin_pdf": None,"dist_png": None,"dist_svg": None,"density_png": None,"density_svg": None,"table_csv": None,"summary_zip": None,"stats_df": pd.DataFrame(),"dist_df": pd.DataFrame(),"manuscript_text": "","last_params": {},}for k, v in defaults.items():if k not in st.session_state:1 unmodified linedef clear_results():for key in list(st.session_state.keys()):del st.session_state[key]init_session_state()# -----------------------------# Generic utilities# -----------------------------def safe_int(value, default=0):try:return int(value)78 unmodified linesreturn positions, valuesdef bp_tick_formatter(x):if x >= 1_000_000:return f"{x/1_000_000:.2f} Mb"if x >= 1_000:return f"{x/1_000:.1f} kb"return f"{int(x)} bp"# -----------------------------# Parsing + feature extraction# -----------------------------def record_to_feature_table(record) -> pd.DataFrame:rows = []for feature in getattr(record, "features", []):302 unmodified linesraise ValueError("Unsupported input mode selected.")# -----------------------------# Filtering + tables# -----------------------------def filter_features(df: pd.DataFrame, selected_types: List[str], query: str, min_len: int = 0, max_len: int = 10**12) -> pd.DataFrame:filtered = df.copy()if selected_types:filtered = filtered[filtered["feature_type"].isin(selected_types)].copy()if not filtered.empty:filtered = filtered[(filtered["length"] >= min_len) & (filtered["length"] <= max_len)].copy()if filtered.empty:filtered["highlight"] = Falsereturn filtered14 unmodified linesreturn filtered.sort_values(["start", "end"], kind="stable").reset_index(drop=True)def 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_summary_stats(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame) -> Dict[str, object]:counts = full_df["feature_type"].value_counts().to_dict() if not full_df.empty else {}return {"Record ID": record.id,"Description": normalize_text(getattr(record, "description", "")),"Genome length (bp)": len(record.seq),"GC (%)": round(compute_gc_percent(record.seq), 2),"Displayed features": len(filtered_df),"Total parsed features": len(full_df),"CDS": safe_int(counts.get("CDS", 0)),"gene": safe_int(counts.get("gene", 0)),"tRNA": safe_int(counts.get("tRNA", 0)),"rRNA": safe_int(counts.get("rRNA", 0)),"ORF": safe_int(counts.get("ORF", 0)),}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"])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:{color};margin-right:6px;border:1px solid #aaa;"></span><span style="font-size:0.92rem;">{ft}</span></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)# -----------------------------# Figure building# -----------------------------def figure_label(ax, label_text: str):ax.text(-0.08, 1.05, label_text,transform=ax.transAxes,fontsize=16,fontweight="bold",va="top",ha="left",)def fig_to_bytes(fig, fmt: str = "png", dpi: int = 600) -> 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()def build_linear_graphic_record(record, filtered_df: pd.DataFrame) -> GraphicRecord:features = []for _, row in filtered_df.iterrows():color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"])label = normalize_text(row.get("label", row["feature_type"]))if len(label) > 36:label = label[:33] + "..."strand = int(row["strand"]) if row["strand"] in (-1, 1) else 0features.append(GraphicFeature(start=int(row["start"]),3 unmodified lineslabel=label,))return GraphicRecord(sequence_length=len(record.seq), features=features)def draw_linear_map(record, filtered_df: pd.DataFrame, annotate_limit: int = 120):graphic_record = build_linear_graphic_record(record, filtered_df)n = len(filtered_df)fig_height = 5.0 if n <= 70 else 6.4 if n <= 160 else 8.0fig, ax = plt.subplots(figsize=(18, fig_height))graphic_record.plot(ax=ax, with_ruler=True, annotate_inline=(n <= annotate_limit))ax.set_title(f"Linear genome architecture: {record.id}", fontsize=15, fontweight="bold", pad=14)ax.set_xlabel("Genomic position", fontsize=11, fontweight="bold")ax.tick_params(axis="x", labelsize=10)handles = []present_types = list(dict.fromkeys(filtered_df["feature_type"].tolist()))for ft in present_types[:10]:handles.append(Patch(facecolor=FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]), edgecolor="black", label=ft))if filtered_df.get("highlight", pd.Series(dtype=bool)).any():handles.append(Patch(facecolor=FEATURE_COLORS["highlight"], edgecolor="black", label="Highlighted match"))if handles:ax.legend(handles=handles, loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=min(5, len(handles)), frameon=False, fontsize=10)figure_label(ax, "A")plt.tight_layout()return fig4 unmodified linessector = circos.sectors[0]tick_track = sector.add_track((88, 100))tick_track.axis(fc="#fbfbfd", ec="black", lw=0.45)tick_interval = max(1000, seq_len // 10) if seq_len <= 100000 else max(5000, seq_len // 12)tick_track.xticks_by_interval(6 unmodified linespos_track = sector.add_track((64, 84))neg_track = sector.add_track((44, 64))pos_track.axis(fc="#ffffff", ec="black", lw=0.35)neg_track.axis(fc="#ffffff", ec="black", lw=0.35)for _, row in filtered_df.iterrows():start = int(row["start"])7 unmodified linesinner_bottom = 10if show_gc_content:gc_track = sector.add_track((26, 40))gc_track.axis(fc="#fbfbfd", ec="black", lw=0.25)positions, gc_values = chunk_gc_content(record.seq, window_size)if gc_values:gc_track.line(positions, gc_values, vmin=0, vmax=100, lw=1.5)baseline = [50.0] * len(gc_values)gc_track.fill_between(positions, gc_values, y2=baseline, vmin=0, vmax=100, alpha=0.35)inner_bottom = 24if show_gc_skew:skew_track = sector.add_track((inner_bottom, inner_bottom + 12))skew_track.axis(fc="#fbfbfd", ec="black", lw=0.25)positions, skews = gc_skew_windows(record.seq, window_size)if skews:vmax = max(abs(min(skews)), abs(max(skews)), 0.1)skew_track.line(positions, skews, vmin=-vmax, vmax=vmax, lw=1.5)skew_track.fill_between(positions, skews, y2=0, vmin=-vmax, vmax=vmax, alpha=0.45)fig = circos.plotfig()fig.set_size_inches(10.2, 10.2)fig.suptitle(f"Circular genome map: {record.id}", fontsize=16, fontweight="bold", y=0.985)legend_elements = [Patch(facecolor=FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]), edgecolor="black", label=ft)for ft in list(dict.fromkeys(filtered_df["feature_type"].tolist()))[:8]]if filtered_df.get("highlight", pd.Series(dtype=bool)).any():legend_elements.append(Patch(facecolor=FEATURE_COLORS["highlight"], edgecolor="black", label="Highlighted match"))if show_gc_content:legend_elements.append(Line2D([0], [0], color="#4C78A8", lw=2, label="GC content"))if show_gc_skew:legend_elements.append(Line2D([0], [0], color="#D94E4E", lw=2, label="GC skew"))if legend_elements:fig.legend(handles=legend_elements, loc="lower center", bbox_to_anchor=(0.5, -0.02), ncol=min(4, len(legend_elements)), frameon=False, fontsize=10)fig.text(0.02, 0.98, "B", fontsize=16, fontweight="bold", ha="left", va="top")return figdef draw_feature_distribution(dist_df: pd.DataFrame):fig, ax = plt.subplots(figsize=(10.5, 5.8))if dist_df.empty:ax.text(0.5, 0.5, "No feature distribution available", ha="center", va="center", fontsize=13)ax.axis("off")return figx = np.arange(len(dist_df))colors = [FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) for ft in dist_df["feature_type"]]bars = ax.bar(x, dist_df["count"], edgecolor="black", linewidth=0.7)for bar, c in zip(bars, colors):bar.set_facecolor(c)ax.set_xticks(x)ax.set_xticklabels(dist_df["feature_type"], rotation=35, ha="right", fontsize=10)ax.set_ylabel("Feature count", fontsize=11, fontweight="bold")ax.set_xlabel("Feature class", fontsize=11, fontweight="bold")ax.set_title("Feature-type composition", fontsize=15, fontweight="bold", pad=12)ax.grid(axis="y", alpha=0.25, linestyle="--")ymax = max(dist_df["count"].max() * 1.18, 1)ax.set_ylim(0, ymax)for i, val in enumerate(dist_df["count"]):ax.text(i, val + ymax * 0.02, str(val), ha="center", va="bottom", fontsize=10, fontweight="bold")figure_label(ax, "C")plt.tight_layout()return figdef compute_density_by_windows(record, filtered_df: pd.DataFrame, bins: int = 50) -> pd.DataFrame:genome_len = len(record.seq)if genome_len == 0:return pd.DataFrame(columns=["window_mid", "count"])bins = max(10, bins)edges = np.linspace(0, genome_len, bins + 1)mids = (edges[:-1] + edges[1:]) / 2starts = filtered_df["start"].values if not filtered_df.empty else np.array([])counts, _ = np.histogram(starts, bins=edges)return pd.DataFrame({"window_mid": mids, "count": counts})def draw_density_plot(record, filtered_df: pd.DataFrame):density_df = compute_density_by_windows(record, filtered_df, bins=60)fig, ax = plt.subplots(figsize=(12.2, 4.8))if density_df.empty:ax.text(0.5, 0.5, "No density information available", ha="center", va="center", fontsize=13)ax.axis("off")return figax.plot(density_df["window_mid"], density_df["count"], lw=2.2)ax.fill_between(density_df["window_mid"], density_df["count"], alpha=0.22)ax.set_title("Spatial density of displayed features", fontsize=15, fontweight="bold", pad=12)ax.set_xlabel("Genomic position", fontsize=11, fontweight="bold")ax.set_ylabel("Features per window", fontsize=11, fontweight="bold")ax.grid(alpha=0.25, linestyle="--")xmax = density_df["window_mid"].max() if len(density_df) else 1ticks = np.linspace(0, xmax, 6)ax.set_xticks(ticks)ax.set_xticklabels([bp_tick_formatter(t) for t in ticks], rotation=0, fontsize=10)figure_label(ax, "D")plt.tight_layout()return fig# -----------------------------# Output text + export bundle# -----------------------------def build_manuscript_text(record, full_df, filtered_df, stats, query, source_mode, window_size):top_types = feature_distribution_table(full_df)if top_types.empty:top_summary = "No annotated feature class was recovered from the uploaded record."else:top_rows = top_types.head(4)top_summary = ", ".join([f"{r.feature_type} ({r.count})" for r in top_rows.itertuples()])query_sentence = ""if normalize_text(query):n_hits = int(filtered_df.get("highlight", pd.Series(dtype=bool)).sum()) if not filtered_df.empty else 0query_sentence = f" The search term '{query}' matched {n_hits} displayed feature(s), which were emphasized in yellow across the maps."return (f"Genome visualization of record {record.id} revealed a sequence length of {stats['Genome length (bp)']:,} bp with an overall GC content of {stats['GC (%)']:.2f}%. "f"A total of {stats['Total parsed features']} annotated features were parsed from the {source_mode} input, of which {stats['Displayed features']} satisfied the current display filters. "f"The dominant feature classes were {top_summary}. "f"The circular map integrated strand-aware annotation with GC-content and GC-skew tracks calculated at a window size of {window_size:,} bp, while the linear map resolved feature order and orientation along the genome."f"{query_sentence} These figures are suitable for manuscript presentation, figure assembly, and comparative genome annotation reporting.")def make_results_bundle(stats_df, feature_df, manuscript_text, figure_payloads: Dict[str, bytes]) -> bytes:mem = io.BytesIO()with zipfile.ZipFile(mem, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:zf.writestr("summary_statistics.csv", stats_df.to_csv(index=False))zf.writestr("feature_annotations.csv", feature_df.to_csv(index=False))zf.writestr("manuscript_ready_results.txt", manuscript_text)for filename, data in figure_payloads.items():if data is not None:zf.writestr(filename, data)mem.seek(0)return mem.getvalue()# -----------------------------# Core analysis routine# -----------------------------def run_analysis(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa):parsed = parse_input_bundle(primary_upload=primary_upload,secondary_upload=secondary_upload,1 unmodified lineinfer_orfs=infer_orfs,min_orf_aa=min_orf_aa,)st.session_state["parsed"] = parsedst.session_state["record_ids"] = [r.id for r in parsed.records]if st.session_state["record_ids"]:st.session_state["selected_record_id"] = st.session_state["record_ids"][0]st.session_state["notes"] = parsed.notesst.session_state["analysis_done"] = Truedef refresh_views(selected_record_id, selected_types, gene_query, min_len, max_len, show_gc_content, show_gc_skew, window_size):parsed = st.session_state["parsed"]record = next(r for r in parsed.records if r.id == selected_record_id)full_df = parsed.feature_tables.get(record.id, pd.DataFrame()).copy()available_types = sorted(full_df["feature_type"].dropna().unique().tolist()) if not full_df.empty else []filtered_df = filter_features(full_df, selected_types, gene_query, min_len=min_len, max_len=max_len)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"})2 unmodified linesstats_df = pd.DataFrame([stats])dist_df = feature_distribution_table(full_df)legend_html = build_legend_html(selected_types,include_highlight=(normalize_text(gene_query) and not filtered_df.empty and filtered_df["highlight"].any()))circ_fig = draw_circular_map(record, 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 Nonedist_fig = draw_feature_distribution(dist_df)density_fig = draw_density_plot(record, filtered_df)st.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["available_types"] = available_typesst.session_state["selected_types_cache"] = selected_typesst.session_state["legend_html"] = legend_htmlst.session_state["stats_df"] = stats_dfst.session_state["dist_df"] = dist_dfst.session_state["last_params"] = {"gene_query": gene_query,"min_len": min_len,"max_len": max_len,"show_gc_content": show_gc_content,"show_gc_skew": show_gc_skew,"window_size": int(window_size),}st.session_state["circ_png"] = fig_to_bytes(circ_fig, fmt="png")st.session_state["circ_svg"] = fig_to_bytes(circ_fig, fmt="svg")10 unmodified linesst.session_state["lin_svg"] = Nonest.session_state["lin_pdf"] = Nonest.session_state["dist_png"] = fig_to_bytes(dist_fig, fmt="png")st.session_state["dist_svg"] = fig_to_bytes(dist_fig, fmt="svg")plt.close(dist_fig)st.session_state["density_png"] = fig_to_bytes(density_fig, fmt="png")st.session_state["density_svg"] = fig_to_bytes(density_fig, fmt="svg")plt.close(density_fig)st.session_state["table_csv"] = display_df.to_csv(index=False).encode("utf-8")manuscript_text = build_manuscript_text(record=record,full_df=full_df,filtered_df=filtered_df,stats=stats,query=gene_query,source_mode=parsed.source_mode,window_size=int(window_size),)st.session_state["manuscript_text"] = manuscript_textst.session_state["summary_zip"] = make_results_bundle(stats_df=stats_df,feature_df=display_df,manuscript_text=manuscript_text,figure_payloads={"figure_A_linear_map.png": st.session_state["lin_png"],"figure_A_linear_map.svg": st.session_state["lin_svg"],"figure_B_circular_map.png": st.session_state["circ_png"],"figure_B_circular_map.svg": st.session_state["circ_svg"],"figure_C_feature_distribution.png": st.session_state["dist_png"],"figure_C_feature_distribution.svg": st.session_state["dist_svg"],"figure_D_feature_density.png": st.session_state["density_png"],"figure_D_feature_density.svg": st.session_state["density_svg"],},)# -----------------------------# UI# -----------------------------init_session_state()st.markdown('<div class="main-title">🧬 Genome Visualization Pro</div>', unsafe_allow_html=True)st.markdown('<div class="subtle">Premium genome mapping with publication-ready figures, clean legends, figure panels, searchable annotation layers, and manuscript-ready results text.</div>',unsafe_allow_html=True,)18 unmodified linesprimary_upload = st.file_uploader("Upload ZIP archive", type=["zip"], accept_multiple_files=False)secondary_upload = Nonest.header("Parsing settings")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)st.header("Run")run_button = st.button("Run visualization", type="primary", use_container_width=True)clear_button = st.button("Clear results", use_container_width=True)9 unmodified linesst.error("Please upload both the GFF/GFF3 file and the FASTA file.")st.stop()with st.spinner("Parsing input and preparing premium visualization..."):try:run_analysis(primary_upload=primary_upload,1 unmodified lineinput_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 st.session_state["analysis_done"]:st.info("Upload your file(s), click Run visualization, and the figures and tables will remain visible until you click Clear results.")st.stop()parsed = st.session_state["parsed"]record_ids = st.session_state["record_ids"]selected_record_id = st.session_state["selected_record_id"]with st.sidebar:st.header("Display filters")selected_record_id = st.selectbox("Select record/contig", record_ids, index=record_ids.index(selected_record_id) if selected_record_id in record_ids else 0)full_df_current = parsed.feature_tables.get(selected_record_id, pd.DataFrame()).copy()available_types = sorted(full_df_current["feature_type"].dropna().unique().tolist()) if not full_df_current.empty else []default_selected = [x for x in DEFAULT_FEATURES if x in available_types] or available_typesselected_types = st.multiselect("Feature classes to display", available_types, default=default_selected)gene_query = st.text_input("Search / highlight label, gene, product, or note", value=st.session_state.get("last_params", {}).get("gene_query", ""))min_len = st.number_input("Minimum feature length (bp)", min_value=0, value=int(st.session_state.get("last_params", {}).get("min_len", 0)), step=50)max_len_default = int(full_df_current["length"].max()) if not full_df_current.empty else 1000000max_len = st.number_input("Maximum feature length (bp)", min_value=1, value=int(st.session_state.get("last_params", {}).get("max_len", max_len_default)), step=100)st.header("Figure settings")show_gc_content = st.checkbox("Show GC content track", value=st.session_state.get("last_params", {}).get("show_gc_content", True))show_gc_skew = st.checkbox("Show GC skew track", value=st.session_state.get("last_params", {}).get("show_gc_skew", True))window_size = st.number_input("Window size for GC tracks", min_value=100, max_value=50000, value=int(st.session_state.get("last_params", {}).get("window_size", 1000)), step=100)refresh_views(selected_record_id=selected_record_id,selected_types=selected_types,gene_query=gene_query,min_len=int(min_len),max_len=int(max_len),show_gc_content=show_gc_content,show_gc_skew=show_gc_skew,window_size=int(window_size),)stats = st.session_state["stats"]display_df = st.session_state["display_df"]c1, c2, c3, c4, c5, c6 = st.columns(6)c1.metric("Genome length", f"{stats['Genome length (bp)']:,} bp")c2.metric("GC content", f"{stats['GC (%)']:.2f}%")c3.metric("Displayed features", stats["Displayed features"])c4.metric("Total parsed", stats["Total parsed features"])c5.metric("CDS", stats["CDS"])c6.metric("Record", stats["Record ID"])if st.session_state["notes"]:st.markdown('<div class="card">', unsafe_allow_html=True)st.markdown('<div class="section-title">Run notes</div>', unsafe_allow_html=True)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"><div class="section-title">Feature key</div>' + st.session_state["legend_html"] + '</div>', unsafe_allow_html=True)tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["Circular map","Linear map","Distribution","Density","Annotation table","Statistics & text",])with tab1:st.subheader("Circular genome map")st.caption("Panel B. Strand-aware circular architecture with optional GC-content and GC-skew tracks.")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 genome map")st.caption("Panel A. High-resolution linear representation with labeled features and explicit legend.")if st.session_state["lin_png"] is None:st.warning("No linear map is available for the current record and filters.")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("Feature distribution")st.caption("Panel C. Bar chart summarizing the distribution of annotated feature classes.")st.image(st.session_state["dist_png"], use_container_width=True)a, b = st.columns(2)with a:st.download_button("Download PNG", data=st.session_state["dist_png"], file_name="feature_distribution.png", mime="image/png")with b:st.download_button("Download SVG", data=st.session_state["dist_svg"], file_name="feature_distribution.svg", mime="image/svg+xml")with tab4:st.subheader("Feature density across the genome")st.caption("Panel D. Window-based density profile showing where displayed annotations accumulate along the genome.")st.image(st.session_state["density_png"], use_container_width=True)a, b = st.columns(2)with a:st.download_button("Download PNG", data=st.session_state["density_png"], file_name="feature_density.png", mime="image/png")with b:st.download_button("Download SVG", data=st.session_state["density_svg"], file_name="feature_density.svg", mime="image/svg+xml")with tab5:st.subheader("Annotation table")st.dataframe(display_df, use_container_width=True, height=470)st.download_button("Download annotation table (CSV)",data=st.session_state["table_csv"],1 unmodified linemime="text/csv",)with tab6:st.subheader("Statistics and manuscript-ready summary")left, right = st.columns([1, 1])with left:st.markdown("**Summary statistics**")st.dataframe(st.session_state["stats_df"], use_container_width=True, height=220)st.markdown("**Feature type distribution**")st.dataframe(st.session_state["dist_df"], use_container_width=True, height=260)with right:st.markdown("**Manuscript-ready results paragraph**")st.text_area("Copy text", value=st.session_state["manuscript_text"], height=320)st.download_button("Download results bundle (ZIP)",data=st.session_state["summary_zip"],file_name="genome_visualization_pro_results.zip",mime="application/zip",)st.markdown("---")st.markdown("""**Included in this version**- High-resolution figure export suitable for journal submission (PNG, SVG, PDF)- Clear panel labels (A–D), figure captions, legends, and axis titles- Record/contig selection after parsing multi-record files- Advanced display filters for feature class, text query, and feature length- Additional publishable plots for feature distribution and genome-wide feature density- Manuscript-ready interpretation text and bundled export package- Persistent results using `st.session_state` so downloads do not clear outputs""")
app.py+461-243