Spaces:
Build error
Build error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940411 unmodified line4344454647484950515253541 unmodified line56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701712 unmodified lines1741751761771781791801811821831841851864 unmodified lines1911921931941951961971981992002012022032042052062072082092102112121 unmodified line214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455import ioimport mathimport tempfilefrom collections import Counterimport 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 Circosst.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)1 unmodified linereturn defaultdef 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 0if isinstance(feature.location, CompoundLocation):parts = list(feature.location.parts)start = int(min(part.start for part in parts))1 unmodified lineelse:start = int(feature.location.start)end = int(feature.location.end)return start, end, stranddef get_feature_label(feature):qualifiers = feature.qualifiersfor key in ["gene", "locus_tag", "product", "note"]:if key in qualifiers and qualifiers[key]:return str(qualifiers[key][0])return feature.typedef 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 recordsdef record_to_feature_table(record):rows = []for feature in record.features:ftype = feature.typestart, end, strand = get_feature_bounds(feature)length = max(0, end - start)label = get_feature_label(feature)qualifiers = feature.qualifiersrows.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.0gc = sequence.count("G") + sequence.count("C")return (gc / len(sequence)) * 100def 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 + cskew = (g - c) / denom if denom else 0return [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 + cskew = (g - c) / denom if denom else 0positions.append(i + len(window) // 2)values.append(skew)return positions, valuesdef 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"] = maskelse:filtered["highlight"] = Falsereturn filtereddef 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,)2 unmodified linesreturn 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 = 16fig_height = 4 if len(filtered_df) < 80 else 6fig, ax = plt.subplots(figsize=(fig_width, fig_height))graphic_record.plot(ax=ax,with_ruler=True,4 unmodified linesreturn figdef 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,1 unmodified linelabel_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 figdef 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131 unmodified line1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431 unmodified line1451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685692 unmodified lines5725735745755765775785795805815824 unmodified lines5875885895905915925935945955965975985996006016026036046056066076081 unmodified line61061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028import ioimport osimport reimport mathimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tupleimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport streamlit as stfrom Bio import SeqIOfrom Bio.Seq import Seqfrom Bio.SeqFeature import CompoundLocationfrom dna_features_viewer import GraphicFeature, GraphicRecordfrom pycirclize import Circostry:import gffutilsexcept Exception:gffutils = None# -----------------------------# Streamlit page setup# -----------------------------st.set_page_config(page_title="Genome Visualization Tool",page_icon="🧬",layout="wide",initial_sidebar_state="expanded",)# -----------------------------# Styling# -----------------------------st.markdown("""<style>.main-title {font-size: 2.0rem;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;}.small-note {font-size: 0.88rem;color: #666;}</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",}DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "misc_feature", "repeat_region", "ORF"]FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas"}GB_EXTS = {".gb", ".gbk", ".genbank"}GFF_EXTS = {".gff", ".gff3"}DNA_COMPLEMENT = str.maketrans("ATGCatgcNn", "TACGtacgNn")# -----------------------------# Data classes# -----------------------------@dataclassclass ParsedGenome:records: Listfeature_tables: Dict[str, pd.DataFrame]source_mode: strnotes: List[str]# -----------------------------# Utilities# -----------------------------def safe_int(value, default=0):try:return int(value)1 unmodified linereturn defaultdef normalize_text(value: str) -> str:return re.sub(r"\s+", " ", str(value or "")).strip()def file_suffix(name: str) -> str:return os.path.splitext(name)[1].lower()def infer_file_kind(filename: str) -> str:ext = file_suffix(filename)if ext in GB_EXTS:return "genbank"if ext in FASTA_EXTS:return "fasta"if ext in GFF_EXTS:return "gff"if ext == ".zip":return "zip"return "unknown"def get_feature_bounds(feature):strand = feature.location.strand if feature.location.strand in (-1, 1) else 0if isinstance(feature.location, CompoundLocation):parts = list(feature.location.parts)start = int(min(part.start for part in parts))1 unmodified lineelse:start = int(feature.location.start)end = int(feature.location.end)return start, end, stranddef get_feature_label(feature):qualifiers = getattr(feature, "qualifiers", {}) or {}for key in ["gene", "locus_tag", "product", "note", "ID", "Name"]:if key in qualifiers and qualifiers[key]:return str(qualifiers[key][0])return getattr(feature, "type", "feature")def compute_gc_percent(sequence: str) -> float:seq = str(sequence).upper()if not seq:return 0.0gc = seq.count("G") + seq.count("C")return (gc / len(seq)) * 100.0def chunk_gc_content(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]:seq = str(sequence).upper()if not seq:return [], []positions = []values = []for i in range(0, len(seq), window_size):window = seq[i:i + window_size]if not window:continuegc = compute_gc_percent(window)positions.append(i + len(window) // 2)values.append(gc)return positions, valuesdef gc_skew_windows(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]:seq = str(sequence).upper()if not seq:return [], []values = []positions = []for i in range(0, len(seq), window_size):window = seq[i:i + window_size]g = window.count("G")c = window.count("C")denom = g + cskew = (g - c) / denom if denom else 0.0positions.append(i + len(window) // 2)values.append(skew)return positions, valuesdef record_to_feature_table(record) -> pd.DataFrame:rows = []for feature in getattr(record, "features", []):try:start, end, strand = get_feature_bounds(feature)qualifiers = getattr(feature, "qualifiers", {}) or {}rows.append({"record_id": record.id,"feature_type": getattr(feature, "type", "feature"),"label": get_feature_label(feature),"start": int(start),"end": int(end),"length": max(0, int(end) - int(start)),"strand": int(strand),"locus_tag": "; ".join(qualifiers.get("locus_tag", [])),"gene": "; ".join(qualifiers.get("gene", [])),"product": "; ".join(qualifiers.get("product", [])),"note": "; ".join(qualifiers.get("note", [])),"source": "annotation",})except Exception:continuedf = pd.DataFrame(rows)if df.empty:df = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"])return df.sort_values(["start", "end"], kind="stable").reset_index(drop=True)def reverse_complement(seq: str) -> str:return seq.translate(DNA_COMPLEMENT)[::-1]def find_orfs_in_sequence(sequence: str, min_aa: int = 90) -> pd.DataFrame:"""Lightweight ORF finder for FASTA-only mode.Coordinates are 0-based half-open for plotting consistency."""seq = str(sequence).upper()seq_len = len(seq)stops = {"TAA", "TAG", "TGA"}start_codons = {"ATG", "GTG", "TTG"}rows = []def scan_strand(s: str, strand_value: int):for frame in range(3):i = framewhile i <= len(s) - 3:codon = s[i:i + 3]if codon in start_codons:j = i + 3while j <= len(s) - 3:stop = s[j:j + 3]if stop in stops:nt_len = (j + 3) - iaa_len = nt_len // 3if aa_len >= min_aa:if strand_value == 1:start, end = i, j + 3else:# map rc coords back to originalstart = seq_len - (j + 3)end = seq_len - irows.append({"feature_type": "ORF","label": f"ORF_{strand_value}_{start+1}_{end}","start": int(start),"end": int(end),"length": int(end - start),"strand": int(strand_value),"locus_tag": "","gene": "","product": f"Predicted ORF ({aa_len} aa)","note": "FASTA-only inferred ORF","source": "orf_prediction",})i = j + 3breakj += 3i += 3scan_strand(seq, 1)scan_strand(reverse_complement(seq), -1)df = pd.DataFrame(rows)if df.empty:return pd.DataFrame(columns=["feature_type", "label", "start", "end", "length", "strand","locus_tag", "gene", "product", "note", "source"])return df.sort_values(["start", "end"], kind="stable").reset_index(drop=True)def parse_uploaded_zip(uploaded_zip) -> Dict[str, bytes]:out = {}zip_bytes = io.BytesIO(uploaded_zip.read())with zipfile.ZipFile(zip_bytes) as zf:for info in zf.infolist():if info.is_dir():continuename = os.path.basename(info.filename)if not name:continueout[name] = zf.read(info.filename)return outdef parse_genbank_bytes(data: bytes):handle = io.StringIO(data.decode("utf-8", errors="replace"))return list(SeqIO.parse(handle, "genbank"))def parse_fasta_bytes(data: bytes):handle = io.StringIO(data.decode("utf-8", errors="replace"))return list(SeqIO.parse(handle, "fasta"))def build_gff_db(gff_text: str, workdir: str):if gffutils is None:raise RuntimeError("gffutils is not installed.")gff_path = os.path.join(workdir, "input.gff3")with open(gff_path, "w", encoding="utf-8") as f:f.write(gff_text)db_path = os.path.join(workdir, "temp_gff.db")db = gffutils.create_db(gff_path,dbfn=db_path,force=True,keep_order=True,merge_strategy="merge",sort_attribute_values=True,disable_infer_transcripts=True,disable_infer_genes=True,)return dbdef gff_and_fasta_to_tables(gff_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]:gff_text = gff_bytes.decode("utf-8", errors="replace")records = parse_fasta_bytes(fasta_bytes)if not records:raise ValueError("No FASTA records found.")record_map = {r.id: r for r in records}alt_map = {}for r in records:alt_map[r.id.split()[0]] = ralt_map[r.name] = rtables: Dict[str, List[dict]] = {r.id: [] for r in records}with tempfile.TemporaryDirectory() as td:db = build_gff_db(gff_text, td)for feature in db.all_features():seqid = str(feature.seqid)record = record_map.get(seqid) or alt_map.get(seqid)if record is None:continueattrs = feature.attributes or {}label = (attrs.get("Name", [""])[0]or attrs.get("gene", [""])[0]or attrs.get("locus_tag", [""])[0]or attrs.get("ID", [""])[0]or feature.featuretype)strand = 1 if feature.strand == "+" else -1 if feature.strand == "-" else 0tables[record.id].append({"record_id": record.id,"feature_type": str(feature.featuretype),"label": normalize_text(label),"start": max(0, int(feature.start) - 1),"end": int(feature.end),"length": max(0, int(feature.end) - (int(feature.start) - 1)),"strand": strand,"locus_tag": "; ".join(attrs.get("locus_tag", [])),"gene": "; ".join(attrs.get("gene", [])),"product": "; ".join(attrs.get("product", [])),"note": "; ".join(attrs.get("Note", [])),"source": "gff",})out = {}for rec in records:df = pd.DataFrame(tables.get(rec.id, []))if df.empty:df = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"])out[rec.id] = df.sort_values(["start", "end"], kind="stable").reset_index(drop=True)return records, outdef parse_input_bundle(primary_upload,secondary_upload,input_mode: str,infer_orfs: bool,min_orf_aa: int,) -> ParsedGenome:notes = []if input_mode == "GenBank":data = primary_upload.read()records = parse_genbank_bytes(data)if not records:raise ValueError("No GenBank records were found.")tables = {r.id: record_to_feature_table(r) for r in records}notes.append("Parsed annotated GenBank input.")return ParsedGenome(records=records, feature_tables=tables, source_mode="genbank", notes=notes)if input_mode == "FASTA":data = primary_upload.read()records = parse_fasta_bytes(data)if not records:raise ValueError("No FASTA records were found.")tables = {}for r in records:base = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"])if infer_orfs:orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa)if not orf_df.empty:orf_df.insert(0, "record_id", r.id)tables[r.id] = orf_dfelse:tables[r.id] = baseelse:tables[r.id] = baseif infer_orfs:notes.append("FASTA-only input: ORF prediction was used to create approximate annotation tracks.")else:notes.append("FASTA-only input: no native annotations were available.")return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes)if input_mode == "GFF + FASTA":if secondary_upload is None:raise ValueError("Both GFF/GFF3 and FASTA files are required.")gff_bytes = primary_upload.read()fasta_bytes = secondary_upload.read()records, tables = gff_and_fasta_to_tables(gff_bytes, fasta_bytes)notes.append("Parsed GFF/GFF3 annotation with FASTA sequence.")return ParsedGenome(records=records, feature_tables=tables, source_mode="gff_fasta", notes=notes)if input_mode == "ZIP (auto-detect)":files = parse_uploaded_zip(primary_upload)gb_name = Nonefasta_name = Nonegff_name = Nonefor name in files:kind = infer_file_kind(name)if kind == "genbank" and gb_name is None:gb_name = nameelif kind == "fasta" and fasta_name is None:fasta_name = nameelif kind == "gff" and gff_name is None:gff_name = nameif gb_name:records = parse_genbank_bytes(files[gb_name])if not records:raise ValueError("ZIP contained a GenBank file but no records were parsed.")tables = {r.id: record_to_feature_table(r) for r in records}notes.append(f"ZIP detected GenBank input: {gb_name}")return ParsedGenome(records=records, feature_tables=tables, source_mode="genbank", notes=notes)if gff_name and fasta_name:records, tables = gff_and_fasta_to_tables(files[gff_name], files[fasta_name])notes.append(f"ZIP detected GFF + FASTA input: {gff_name} + {fasta_name}")return ParsedGenome(records=records, feature_tables=tables, source_mode="gff_fasta", notes=notes)if fasta_name:records = parse_fasta_bytes(files[fasta_name])if not records:raise ValueError("ZIP contained a FASTA file but no records were parsed.")tables = {}for r in records:if infer_orfs:orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa)if not orf_df.empty:orf_df.insert(0, "record_id", r.id)tables[r.id] = orf_dfelse:tables[r.id] = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"])else:tables[r.id] = pd.DataFrame(columns=["record_id", "feature_type", "label", "start", "end", "length","strand", "locus_tag", "gene", "product", "note", "source"])notes.append(f"ZIP detected FASTA-only input: {fasta_name}")return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes)raise ValueError("ZIP file did not contain a supported GenBank, FASTA, or GFF+FASTA combination.")raise 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"] = []return filteredquery = normalize_text(query).lower()if query:mask = (filtered["label"].fillna("").str.lower().str.contains(query, na=False)| filtered["gene"].fillna("").str.lower().str.contains(query, na=False)| filtered["locus_tag"].fillna("").str.lower().str.contains(query, na=False)| filtered["product"].fillna("").str.lower().str.contains(query, na=False)| filtered["note"].fillna("").str.lower().str.contains(query, na=False))filtered["highlight"] = maskelse:filtered["highlight"] = Falsereturn 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"]),end=int(row["end"]),strand=strand,color=color,label=label,)2 unmodified linesreturn 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,4 unmodified linesreturn figdef draw_circular_map(record,filtered_df: pd.DataFrame,show_gc_content: bool = True,show_gc_skew: bool = True,window_size: int = 1000,):seq_len = len(record.seq)circos = Circos({record.id: seq_len}, space=2)sector = circos.sectors[0]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(tick_interval,label_formatter=lambda v: f"{int(v/1000)} kb" if v >= 1000 else str(v),show_bottom_line=True,1 unmodified linelabel_size=8,)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)for _, row in filtered_df.iterrows():start = int(row["start"])end = int(row["end"])color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"])if row["strand"] == -1:neg_track.rect(start, end, fc=color, ec=color)else:pos_track.rect(start, end, fc=color, ec=color)inner_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()save_kwargs = {"bbox_inches": "tight"}if fmt.lower() == "png":save_kwargs["dpi"] = dpifig.savefig(buf, format=fmt, **save_kwargs)buf.seek(0)return buf.getvalue()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"])vc = df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count")return vcdef build_legend_html(feature_types: List[str]) -> str:parts = []for ft in feature_types:color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"])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>""")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()# -----------------------------# UI# -----------------------------st.markdown('<div class="main-title">🧬 Genome Visualization Tool</div>', unsafe_allow_html=True)st.markdown('<div class="subtle">Interactive circular and linear genome maps with support for GenBank, FASTA, GFF/GFF3 + FASTA, and ZIP packages.</div>',unsafe_allow_html=True,)with st.expander("Supported input formats", expanded=False):st.markdown("""**Recommended for full gene annotation visualization**- **GenBank (.gb, .gbk, .genbank)**- **GFF/GFF3 + FASTA****Also supported**- **FASTA**FASTA alone does not contain annotations, so this app can optionally predict simple ORFs for approximate feature tracks.- **ZIP**Auto-detects supported file combinations inside a ZIP archive.""")with st.sidebar:st.header("Input")input_mode = st.selectbox("Select input type",["GenBank", "FASTA", "GFF + FASTA", "ZIP (auto-detect)"],index=0,)if input_mode == "GenBank":primary_upload = st.file_uploader("Upload GenBank file",type=["gb", "gbk", "genbank"],accept_multiple_files=False,help="Best format for full sequence + annotation visualization.",)secondary_upload = Noneelif input_mode == "FASTA":primary_upload = st.file_uploader("Upload FASTA file",type=["fa", "fasta", "fna", "fas"],accept_multiple_files=False,help="FASTA contains sequence only. You can enable ORF prediction below.",)secondary_upload = Noneelif input_mode == "GFF + FASTA":primary_upload = st.file_uploader("Upload GFF/GFF3 annotation file",type=["gff", "gff3"],accept_multiple_files=False,help="Gene coordinates and annotation table.",)secondary_upload = st.file_uploader("Upload matching FASTA file",type=["fa", "fasta", "fna", "fas"],accept_multiple_files=False,help="Sequence used for coordinates and nucleotide statistics.",)else:primary_upload = st.file_uploader("Upload ZIP archive",type=["zip"],accept_multiple_files=False,help="ZIP can contain GenBank, or GFF/GFF3 + FASTA, or FASTA.",)secondary_upload = Nonest.header("Analysis settings")gene_query = st.text_input("Search / highlight",value="",help="Search gene, locus tag, product, or note. Matches are highlighted in gold.",)infer_orfs = st.checkbox("Predict ORFs for FASTA-only input", value=True)min_orf_aa = st.slider("Minimum ORF length (aa)", min_value=30, max_value=300, value=90, step=10)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)# -----------------------------# Guard rails: don't process until user clicks# -----------------------------if not run_button:st.info("Upload your file(s), adjust settings, and click **Run visualization**.")st.stop()if primary_upload is None:st.error("Please upload the required input file.")st.stop()if input_mode == "GFF + FASTA" and secondary_upload is None:st.error("Please upload both the GFF/GFF3 file and the FASTA file.")st.stop()# -----------------------------# Parsing# -----------------------------with st.spinner("Parsing input and preparing visualization..."):try:parsed = parse_input_bundle(primary_upload=primary_upload,secondary_upload=secondary_upload,input_mode=input_mode,infer_orfs=infer_orfs,min_orf_aa=min_orf_aa,)except Exception as exc:st.error(f"Input parsing failed: {exc}")st.stop()if not parsed.records:st.error("No valid records were found.")st.stop()record_ids = [r.id for r in parsed.records]selected_record_id = st.selectbox("Select record / contig", record_ids, index=0)record = next(r for r in parsed.records if r.id == selected_record_id)full_df = parsed.feature_tables.get(record.id, pd.DataFrame())available_types = sorted(full_df["feature_type"].dropna().unique().tolist()) if not full_df.empty else []default_selected = [x for x in DEFAULT_FEATURES if x in available_types]if not default_selected:default_selected = available_typesselected_types = st.multiselect("Feature types to display",options=available_types,default=default_selected,)filtered_df = filter_features(full_df, selected_types, gene_query)# -----------------------------# Summary cards# -----------------------------stats = build_summary_stats(record, full_df, filtered_df)c1, c2, c3, c4, c5 = st.columns(5)c1.metric("Genome length (bp)", f"{stats['Genome length (bp)']:,}")c2.metric("GC (%)", stats["GC (%)"])c3.metric("Displayed features", stats["Displayed features"])c4.metric("Total parsed features", stats["Total parsed features"])c5.metric("CDS", stats["CDS"])if parsed.notes:st.markdown('<div class="card">', unsafe_allow_html=True)st.markdown("**Run notes**")for note in parsed.notes:st.write(f"- {note}")st.markdown("</div>", unsafe_allow_html=True)legend_types = selected_types[:]if gene_query.strip() and not filtered_df.empty and filtered_df["highlight"].any():legend_html = build_legend_html(legend_types) + (f"""<span style="display:inline-flex;align-items:center;margin-right:14px;margin-bottom:6px;"><span style="display:inline-block;width:13px;height:13px;border-radius:3px;background:{FEATURE_COLORS['highlight']};margin-right:6px;border:1px solid #aaa;"></span><span style="font-size:0.92rem;">highlighted match</span></span>""")else:legend_html = build_legend_html(legend_types)if legend_html:st.markdown('<div class="card"><b>Feature legend</b><br>' + legend_html + '</div>', unsafe_allow_html=True)tab1, tab2, tab3, tab4 = st.tabs(["Circular Map", "Linear Map", "Annotation Table", "Statistics"])# -----------------------------# Circular map# -----------------------------with tab1:st.subheader("Circular genome map")try:circ_fig = draw_circular_map(record=record,filtered_df=filtered_df,show_gc_content=show_gc_content,show_gc_skew=show_gc_skew,window_size=int(window_size),)st.pyplot(circ_fig, use_container_width=True)col1, col2, col3 = st.columns(3)with col1:st.download_button("Download PNG",data=fig_to_bytes(circ_fig, fmt="png"),file_name=f"{record.id}_circular_map.png",mime="image/png",)with col2:st.download_button("Download SVG",data=fig_to_bytes(circ_fig, fmt="svg"),file_name=f"{record.id}_circular_map.svg",mime="image/svg+xml",)with col3:st.download_button("Download PDF",data=fig_to_bytes(circ_fig, fmt="pdf"),file_name=f"{record.id}_circular_map.pdf",mime="application/pdf",)plt.close(circ_fig)except Exception as exc:st.error(f"Could not render circular map: {exc}")# -----------------------------# Linear map# -----------------------------with tab2:st.subheader("Linear gene annotation map")if filtered_df.empty:st.warning("No features matched the selected filters.")else:try:lin_fig = draw_linear_map(record, filtered_df)st.pyplot(lin_fig, use_container_width=True)col1, col2, col3 = st.columns(3)with col1:st.download_button("Download PNG",data=fig_to_bytes(lin_fig, fmt="png"),file_name=f"{record.id}_linear_map.png",mime="image/png",)with col2:st.download_button("Download SVG",data=fig_to_bytes(lin_fig, fmt="svg"),file_name=f"{record.id}_linear_map.svg",mime="image/svg+xml",)with col3:st.download_button("Download PDF",data=fig_to_bytes(lin_fig, fmt="pdf"),file_name=f"{record.id}_linear_map.pdf",mime="application/pdf",)plt.close(lin_fig)except Exception as exc:st.error(f"Could not render linear map: {exc}")# -----------------------------# Table# -----------------------------with tab3:st.subheader("Annotation table")display_df = filtered_df.copy()if not display_df.empty and "highlight" in display_df.columns:display_df["highlight"] = display_df["highlight"].map({True: "yes", False: "no"})st.dataframe(display_df, use_container_width=True, height=430)table_csv = display_df.to_csv(index=False).encode("utf-8")st.download_button("Download annotation table (CSV)",data=table_csv,file_name=f"{record.id}_feature_annotations.csv",mime="text/csv",)# -----------------------------# Statistics# -----------------------------with tab4:st.subheader("Genome statistics and feature distribution")stats_df = pd.DataFrame([stats])dist_df = feature_distribution_table(full_df)left, right = st.columns([1, 1])with left:st.markdown("**Summary statistics**")st.dataframe(stats_df, use_container_width=True, height=220)with right:st.markdown("**Feature type distribution**")st.dataframe(dist_df, use_container_width=True, height=220)summary_zip = make_results_bundle_csv(stats_df, display_df if "display_df" in locals() else filtered_df)st.download_button("Download summary bundle (ZIP)",data=summary_zip,file_name=f"{record.id}_results_bundle.zip",mime="application/zip",)st.markdown("---")st.markdown("""**Interpretation notes**- **GenBank** and **GFF + FASTA** provide true annotation-based maps.- **FASTA-only** does not contain annotation metadata; ORF mode gives an approximate coding-region view.- For journal-quality gene annotation figures, prefer **GenBank** or **GFF/GFF3 + FASTA**.""")
app.py+841-268