Spaces:
Build error
Build error
Update app.py
Browse files9 unmodified lines1011121314151617187 unmodified lines2627282930313227333435363 unmodified lines4041423738394344454647484243495051525347485455565051575859606162636465666768697071727374757677787959606162636465666768697080818283848586878889909192939411 unmodified lines10610710810911011111211311414 unmodified lines1291301311321331341351361371381391121401411421431441 unmodified line14614714812012112212312412512612712812913013113213313413513613713813914014114214314414514614714915015115215315415515615715815978 unmodified lines238239240241242243244245246247248249250251252253254302 unmodified lines55755855956056156254356356456556656756856957057157257357414 unmodified lines5895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666675745756686696705776716726733 unmodified lines6776786795876806816825916836846855935945955966866876886896906916926936946956966976986997007017027037047054 unmodified lines7107117126077137147157166 unmodified lines7237247256206217267277287297307 unmodified lines7387397406357417427436387447457467477487497506457517527537546497557567577586536546557597607617627637647657667677687697707717726586596606616626636646657737747757767777786686696706716726736746756766776786796806816827797807817827837847857867877887897907917927937947957967977987998008018028038048058068078086856866876888098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448456916926936946956966976986997007017027037047057067077087097107117128468478488498508518528538548558568578588598608618628638648658668678688698708717158728738747188758768778788798808818828838847247257267277287297307317327337348858868878888898908911 unmodified line8938948958968978988999009019027437447457469037487497507519049059069079087539099109119129132 unmodified lines91691791876276391992092192276676776876977077177292392492592692777577677792892993093193278393378593493593693793893994094194294394494594694794810 unmodified lines95996096196296396496596696796896997097197297397497597697797897998080698198298398498598698798898999099199299399499599699799899910001001100281110031004813100510061007100818 unmodified lines102710281029838839103010311032103384384484584684710341035103610379 unmodified lines10471048104986310501051105210531 unmodified line105510561057871872873874105810591060106110621063881106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110088611018888898901102110311041105892110611071108110911101111897111211131114111511161117903111811191120905112111221123112411251126112711281129113011319099109119129139149159169179189199209219229239249259269279289299309319321132113311341135113611371138113911401141114293511431144114593711461147114811491150942943944945946947115111529499509519529539541153115495695795895996096111551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117896511791180118111821 unmodified line11841185118697397497511871188118911901191119297911931194119598198298398498598698798811961197119811991200120112021203120412051206120799399499599699712081209121012111212121312141215121699912179 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 lines gffutils = None
# -----------------------------# Page config + styling# -----------------------------st.set_page_config( page_title="Genome Visualization Tool", page_title="Genome Visualization Pro", page_icon="🧬", layout="wide", initial_sidebar_state="expanded",3 unmodified lines """ <style> .main-title { font-size: 2rem; font-weight: 800; margin-bottom: 0.2rem; font-size: 2.2rem; font-weight: 900; margin-bottom: 0.15rem; letter-spacing: -0.02em; } .subtle { color: #666; font-size: 0.98rem; color: #5b6472; font-size: 1.0rem; margin-bottom: 1rem; } .card { padding: 0.9rem 1rem; border-radius: 14px; padding: 0.95rem 1rem; border-radius: 16px; border: 1px solid rgba(120,120,120,0.18); background: rgba(250,250,250,0.02); margin-bottom: 0.8rem; 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": "#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", "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 lines notes: 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(), "last_run_signature": None, "manuscript_text": "", "last_params": {}, } for k, v in defaults.items(): if k not in st.session_state:1 unmodified line
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] 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 lines return positions, values
def 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 lines raise ValueError("Unsupported input mode selected.")
# -----------------------------# Filtering + tables# -----------------------------def filter_features(df: pd.DataFrame, selected_types: List[str], query: str) -> pd.DataFrame: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"] = False return filtered14 unmodified lines return 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"] = dpi fig.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) > 35: label = label[:32] + "..." if len(label) > 36: label = label[:33] + "..." strand = int(row["strand"]) if row["strand"] in (-1, 1) else 0
features.append( GraphicFeature( start=int(row["start"]),3 unmodified lines label=label, ) )
return GraphicRecord(sequence_length=len(record.seq), features=features)
def draw_linear_map(record, filtered_df: pd.DataFrame, annotate_limit: int = 180):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 = 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)) ax.set_title(f"Linear Genome Map: {record.id}", fontsize=14, weight="bold") fig_height = 5.0 if n <= 70 else 6.4 if n <= 160 else 8.0 fig, 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 fig
4 unmodified lines sector = circos.sectors[0]
tick_track = sector.add_track((88, 100)) tick_track.axis(fc="#f7f7f7", ec="black", lw=0.4) 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 lines
pos_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) 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 lines inner_bottom = 10 if show_gc_content: gc_track = sector.add_track((26, 40)) gc_track.axis(fc="#f8f8f8", ec="black", lw=0.25) 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) 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 = 24
if show_gc_skew: skew_track = sector.add_track((inner_bottom, inner_bottom + 12)) skew_track.axis(fc="#f8f8f8", ec="black", lw=0.25) 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) 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(8.8, 8.8) fig.suptitle(f"Circular Genome Map: {record.id}", fontsize=14, weight="bold", y=0.98) return fig 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"))
def fig_to_bytes(fig, fmt: str = "png", dpi: int = 300) -> bytes: buf = io.BytesIO() kwargs = {"bbox_inches": "tight"} if fmt.lower() == "png": kwargs["dpi"] = dpi fig.savefig(buf, format=fmt, **kwargs) buf.seek(0) return buf.getvalue() 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 fig
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 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 fig
x = 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 fig
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 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:]) / 2 starts = 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 fig
ax.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 1 ticks = 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
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)
# -----------------------------# 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 0 query_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_csv(summary_df: pd.DataFrame, feature_df: pd.DataFrame) -> bytes: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", summary_df.to_csv(index=False)) 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()
def run_analysis( primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa, gene_query, show_gc_content, show_gc_skew, window_size,):# -----------------------------# 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 line infer_orfs=infer_orfs, min_orf_aa=min_orf_aa, ) st.session_state["parsed"] = parsed st.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.notes st.session_state["analysis_done"] = True
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_typesdef 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()
filtered_df = filter_features(full_df, default_selected, gene_query) 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 lines 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()) selected_types, include_highlight=(normalize_text(gene_query) 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), ) 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 None dist_fig = draw_feature_distribution(dist_df) density_fig = draw_density_plot(record, filtered_df)
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["selected_types_cache"] = selected_types st.session_state["legend_html"] = legend_html st.session_state["stats_df"] = stats_df st.session_state["dist_df"] = dist_df st.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 lines st.session_state["lin_svg"] = None st.session_state["lin_pdf"] = None
st.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_text st.session_state["summary_zip"] = make_results_bundle_csv(stats_df, display_df) st.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 Tool</div>', unsafe_allow_html=True)st.markdown('<div class="main-title">🧬 Genome Visualization Pro</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>', '<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 lines 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="") st.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("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)
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 lines st.error("Please upload both the GFF/GFF3 file and the FASTA file.") st.stop()
with st.spinner("Parsing input and preparing visualization..."): with st.spinner("Parsing input and preparing premium visualization..."): try: run_analysis( primary_upload=primary_upload,1 unmodified line 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.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_types selected_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 1000000 max_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"]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 (%)"])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 features", stats["Total parsed 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("**Run notes**") 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"><b>Feature legend</b><br>' + st.session_state["legend_html"] + '</div>', unsafe_allow_html=True) 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 = st.tabs(["Circular Map", "Linear Map", "Annotation Table", "Statistics"])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") 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", ) 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 gene annotation map") 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 available for the current result.") 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", ) 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", ) 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", ) 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=430) 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 line mime="text/csv", )
with tab4: st.subheader("Genome statistics and feature distribution") left, right = st.columns(2)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) with right: st.markdown("**Feature type distribution**") st.dataframe(st.session_state["dist_df"], use_container_width=True, height=260) with right: 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("**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( """ **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 **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