Spaces:
Build error
Build error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455import ioimport mathimport tempfilefrom collections import Counter
import 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 Circos
st.set_page_config( page_title="Genome Visualization Tool", page_icon="🧬", layout="wide",)
FEATURE_COLORS = { "CDS": "#1f77b4", "gene": "#2ca02c", "tRNA": "#ff7f0e", "rRNA": "#d62728", "misc_feature": "#9467bd", "repeat_region": "#8c564b", "ncRNA": "#e377c2", "mobile_element": "#7f7f7f", "source": "#bcbd22",}
DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "misc_feature", "repeat_region", "ncRNA"]
def safe_int(value, default=0): try: return int(value) except Exception: return default
def get_feature_bounds(feature): """ Return start, end, strand for both simple and compound feature locations. """ strand = feature.location.strand if feature.location.strand in (-1, 1) else 0
if isinstance(feature.location, CompoundLocation): parts = list(feature.location.parts) start = int(min(part.start for part in parts)) end = int(max(part.end for part in parts)) else: start = int(feature.location.start) end = int(feature.location.end)
return start, end, strand
def get_feature_label(feature): qualifiers = feature.qualifiers for key in ["gene", "locus_tag", "product", "note"]: if key in qualifiers and qualifiers[key]: return str(qualifiers[key][0]) return feature.type
def parse_genbank(uploaded_file): records = list(SeqIO.parse(uploaded_file, "genbank")) if not records: raise ValueError("No GenBank records were found in the uploaded file.") return records
def record_to_feature_table(record): rows = [] for feature in record.features: ftype = feature.type start, end, strand = get_feature_bounds(feature) length = max(0, end - start) label = get_feature_label(feature) qualifiers = feature.qualifiers
rows.append( { "feature_type": ftype, "label": label, "start": start, "end": end, "length": length, "strand": strand, "locus_tag": "; ".join(qualifiers.get("locus_tag", [])), "gene": "; ".join(qualifiers.get("gene", [])), "product": "; ".join(qualifiers.get("product", [])), "note": "; ".join(qualifiers.get("note", [])), } )
return pd.DataFrame(rows)
def compute_gc_percent(sequence): sequence = str(sequence).upper() if not sequence: return 0.0 gc = sequence.count("G") + sequence.count("C") return (gc / len(sequence)) * 100
def gc_skew_windows(sequence, window_size=1000): seq = str(sequence).upper() values = [] positions = []
if len(seq) < window_size: g = seq.count("G") c = seq.count("C") denom = g + c skew = (g - c) / denom if denom else 0 return [len(seq) // 2], [skew]
for i in range(0, len(seq), window_size): window = seq[i:i + window_size] g = window.count("G") c = window.count("C") denom = g + c skew = (g - c) / denom if denom else 0 positions.append(i + len(window) // 2) values.append(skew) return positions, values
def filter_features(df, selected_types, gene_query): filtered = df[df["feature_type"].isin(selected_types)].copy()
if gene_query.strip(): q = gene_query.strip().lower() mask = ( filtered["label"].fillna("").str.lower().str.contains(q, na=False) | filtered["gene"].fillna("").str.lower().str.contains(q, na=False) | filtered["locus_tag"].fillna("").str.lower().str.contains(q, na=False) | filtered["product"].fillna("").str.lower().str.contains(q, na=False) ) filtered["highlight"] = mask else: filtered["highlight"] = False
return filtered
def build_linear_graphic_record(record, filtered_df): features = []
for _, row in filtered_df.iterrows(): color = "#ffd700" if row["highlight"] else FEATURE_COLORS.get(row["feature_type"], "#17becf") label = row["label"]
if len(label) > 30: label = label[:27] + "..."
features.append( GraphicFeature( start=int(row["start"]), end=int(row["end"]), strand=int(row["strand"]) if row["strand"] in (-1, 1) else 0, color=color, label=label, ) )
return GraphicRecord(sequence_length=len(record.seq), features=features)
def draw_linear_map(record, filtered_df, annotate_limit=150): graphic_record = build_linear_graphic_record(record, filtered_df)
fig_width = 16 fig_height = 4 if len(filtered_df) < 80 else 6
fig, ax = plt.subplots(figsize=(fig_width, 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 fig
def draw_circular_map(record, filtered_df, show_gc=True, gc_window=1000): seq_len = len(record.seq) sectors = {record.id: seq_len} circos = Circos(sectors, space=2)
sector = circos.sectors[0]
outer_track = sector.add_track((82, 98)) outer_track.axis(fc="#f8f9fa", ec="black", lw=0.5)
if seq_len <= 100000: tick_interval = max(1000, seq_len // 10) else: tick_interval = max(5000, seq_len // 12)
outer_track.xticks_by_interval( tick_interval, label_formatter=lambda v: f"{int(v/1000)} kb" if v >= 1000 else str(v), show_bottom_line=True, label_orientation="vertical", label_size=8, )
pos_track = sector.add_track((60, 80)) neg_track = sector.add_track((40, 60)) 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"]) end = int(row["end"]) color = "#ffd700" if row["highlight"] else FEATURE_COLORS.get(row["feature_type"], "#17becf")
if row["strand"] == -1: neg_track.rect(start, end, fc=color, ec=color) else: pos_track.rect(start, end, fc=color, ec=color)
if show_gc: gc_track = sector.add_track((20, 36)) gc_track.axis(fc="#f8f9fa", ec="black", lw=0.3)
positions, skews = gc_skew_windows(record.seq, window_size=gc_window) if skews: vmax = max(abs(min(skews)), abs(max(skews)), 0.1) gc_track.line(positions, skews, vmin=-vmax, vmax=vmax) gc_track.fill_between( positions, skews, y2=0, vmin=-vmax, vmax=vmax, alpha=0.5, )
fig = circos.plotfig() fig.set_size_inches(8, 8) fig.suptitle(f"Circular Genome Map: {record.id}", fontsize=14, weight="bold", y=0.98) return fig
def fig_to_png_bytes(fig, dpi=300): buf = io.BytesIO() fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight") buf.seek(0) return buf.getvalue()
def fig_to_svg_bytes(fig): buf = io.BytesIO() fig.savefig(buf, format="svg", bbox_inches="tight") buf.seek(0) return buf.getvalue()
def summary_stats(record, feature_df): feature_counts = feature_df["feature_type"].value_counts().to_dict() return { "Record ID": record.id, "Genome length (bp)": len(record.seq), "GC (%)": round(compute_gc_percent(record.seq), 2), "Total features": len(feature_df), "CDS": safe_int(feature_counts.get("CDS", 0)), "gene": safe_int(feature_counts.get("gene", 0)), "tRNA": safe_int(feature_counts.get("tRNA", 0)), "rRNA": safe_int(feature_counts.get("rRNA", 0)), }
def main(): st.title("🧬 Genome Visualization Tool") st.markdown( """ Upload an annotated **GenBank (.gb / .gbk)** file to generate:
- **Circular genome map** - **Linear annotation map** - **Feature summary table** - **Downloadable publication-ready figures** """ )
with st.sidebar: st.header("Settings") uploaded_file = st.file_uploader( "Upload GenBank file", type=["gb", "gbk", "genbank"], help="Only GenBank files are supported in this version.", )
gene_query = st.text_input( "Search/highlight gene", value="", help="Enter gene name, locus tag, or product keyword.", )
show_gc_track = st.checkbox("Show GC skew track in circular map", value=True) gc_window = st.number_input( "GC skew window size", min_value=100, max_value=50000, value=1000, step=100, )
if not uploaded_file: st.info("Upload a GenBank file to begin.") st.stop()
try: records = parse_genbank(uploaded_file) except Exception as exc: st.error(f"Failed to parse file: {exc}") st.stop()
record_ids = [r.id for r in records] selected_record_id = st.selectbox("Select record", record_ids, index=0) record = next(r for r in records if r.id == selected_record_id)
feature_df = record_to_feature_table(record)
available_types = sorted(feature_df["feature_type"].dropna().unique().tolist()) default_selected = [f for f in DEFAULT_FEATURES if f in available_types] if not default_selected: default_selected = available_types[: min(5, len(available_types))]
selected_types = st.multiselect( "Feature types to display", options=available_types, default=default_selected, )
if not selected_types: st.warning("Please select at least one feature type.") st.stop()
filtered_df = filter_features(feature_df, selected_types, gene_query)
stats = summary_stats(record, feature_df) c1, c2, c3, c4 = st.columns(4) c1.metric("Genome length (bp)", f"{stats['Genome length (bp)']:,}") c2.metric("GC (%)", stats["GC (%)"]) c3.metric("Total features", stats["Total features"]) c4.metric("CDS", stats["CDS"])
with st.expander("Genome statistics", expanded=False): st.json(stats)
tab1, tab2, tab3 = st.tabs(["Circular Map", "Linear Map", "Feature Table"])
with tab1: st.subheader("Circular Genome Map") if filtered_df.empty: st.warning("No features matched the current filters.") else: try: circ_fig = draw_circular_map( record, filtered_df, show_gc=show_gc_track, gc_window=int(gc_window), ) st.pyplot(circ_fig, use_container_width=True)
col1, col2 = st.columns(2) with col1: st.download_button( "Download circular map (PNG)", data=fig_to_png_bytes(circ_fig), file_name=f"{record.id}_circular_map.png", mime="image/png", ) with col2: st.download_button( "Download circular map (SVG)", data=fig_to_svg_bytes(circ_fig), file_name=f"{record.id}_circular_map.svg", mime="image/svg+xml", ) plt.close(circ_fig) except Exception as exc: st.error(f"Could not render circular map: {exc}")
with tab2: st.subheader("Linear Annotation Map") if filtered_df.empty: st.warning("No features matched the current filters.") else: try: lin_fig = draw_linear_map(record, filtered_df) st.pyplot(lin_fig, use_container_width=True)
col1, col2 = st.columns(2) with col1: st.download_button( "Download linear map (PNG)", data=fig_to_png_bytes(lin_fig), file_name=f"{record.id}_linear_map.png", mime="image/png", ) with col2: st.download_button( "Download linear map (SVG)", data=fig_to_svg_bytes(lin_fig), file_name=f"{record.id}_linear_map.svg", mime="image/svg+xml", ) plt.close(lin_fig) except Exception as exc: st.error(f"Could not render linear map: {exc}")
with tab3: st.subheader("Feature Annotation Table")
display_df = filtered_df.copy() if "highlight" in display_df.columns: display_df["highlight"] = display_df["highlight"].map({True: "yes", False: "no"})
st.dataframe(display_df, use_container_width=True)
csv_data = display_df.to_csv(index=False).encode("utf-8") st.download_button( "Download feature table (CSV)", data=csv_data, file_name=f"{record.id}_feature_annotations.csv", mime="text/csv", )
st.markdown("---") st.markdown( """ **Notes** - Best input format: **annotated GenBank** - Circular map uses **pyCirclize** - Linear map uses **DNA Features Viewer** - Gene search highlights matched annotations in **gold** """ )
if __name__ == "__main__": main()app.pyAdded+455