Spaces:
Build error
Build error
Update app.py
Browse files123456478910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808131828384858687883689909192939495969798991001011021031041051061071081091101111121131 unmodified line115116117118119120121122123124125126127128129130131132133134135136137138139474849140511411421431 unmodified line1451461475914814915015164651521531541556815615715871727374757677787980818283848586878889909192939495969798991001011021031041051061071591601611621091101631641651661131671681151691701711721731741751761771781791801811181191201211221231821831841851861871881891901911921931941301951961971981992001361372012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255261391405275285295305315325335345355365375385391421431441455405415425435445455465475485491515505515521545535541565551581591601611625565575585595605615625635645651685665675685692 unmodified lines5725735741775755765771801811821835785795805815824 unmodified lines5875885891945905915925935945955965971961975981985996002012022032042052062076016026036042096056066076081 unmodified line61061161221721861361461561661761861962022522662162262362462562623223323423523662762862963063163263363463563663763863964064164264323924024124224324424524624764464564664725064864965065165225565365425765565665765865966066166226226326426526626726826927066366466566666766866967027527627727827967167267367467567667767867928328468068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172228728828929029129272372472572672772872973073173273373429629729873573673773873974074174274374474574630174774874930330430530630775075175275375475575675775875976076176276376476576676776876977077177277377431031131231331431531677577677777877978078178278331932032178478578678778878979032332432532632779179279332933033179479579679779833379980033533633733880180280380480580680734034134234334480880981081181281381481534634781681781881982082182282382482582682782882983083135083283383483535235335435535635783683783883984035936084184284384484536284684784884985085136436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242385285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388442542688588688742842943088888989089143289289389489589689743443543643743843989889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993044244344444544644744844945093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019454455102010211022102310241025102610271028import ioimport osimport reimport mathimport zipfileimport tempfilefrom collections import Counterfrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tuple
import 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 Circos
try: 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", "ncRNA": "#e377c2", "mobile_element": "#7f7f7f", "source": "#bcbd22", "ORF": "#17becf", "default": "#4c78a8", "highlight": "#ffd700",}
DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "misc_feature", "repeat_region", "ncRNA"]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: List feature_tables: Dict[str, pd.DataFrame] source_mode: str notes: List[str]
# -----------------------------# Utilities# -----------------------------def safe_int(value, default=0): try: return int(value)1 unmodified line return default
def 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): """ 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))1 unmodified line 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"]: 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 feature.type return getattr(feature, "type", "feature")
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:def compute_gc_percent(sequence: str) -> float: seq = str(sequence).upper() if not seq: return 0.0 gc = sequence.count("G") + sequence.count("C") return (gc / len(sequence)) * 100 gc = seq.count("G") + seq.count("C") return (gc / len(seq)) * 100.0
def gc_skew_windows(sequence, window_size=1000):def chunk_gc_content(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]: seq = str(sequence).upper() values = [] if not seq: return [], [] positions = [] values = [] for i in range(0, len(seq), window_size): window = seq[i:i + window_size] if not window: continue gc = compute_gc_percent(window) positions.append(i + len(window) // 2) values.append(gc) return positions, values
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]
def 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 + c skew = (g - c) / denom if denom else 0 skew = (g - c) / denom if denom else 0.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()def 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: continue
df = 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 = frame while i <= len(s) - 3: codon = s[i:i + 3] if codon in start_codons: j = i + 3 while j <= len(s) - 3: stop = s[j:j + 3] if stop in stops: nt_len = (j + 3) - i aa_len = nt_len // 3 if aa_len >= min_aa: if strand_value == 1: start, end = i, j + 3 else: # map rc coords back to original start = seq_len - (j + 3) end = seq_len - i rows.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 + 3 break j += 3 i += 3
scan_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(): continue name = os.path.basename(info.filename) if not name: continue out[name] = zf.read(info.filename) return out
def 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 db
def 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]] = r alt_map[r.name] = r
tables: 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: continue
attrs = 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 0
tables[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, out
def 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_df else: tables[r.id] = base else: tables[r.id] = base if 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 = None fasta_name = None gff_name = None
for name in files: kind = infer_file_kind(name) if kind == "genbank" and gb_name is None: gb_name = name elif kind == "fasta" and fasta_name is None: fasta_name = name elif kind == "gff" and gff_name is None: gff_name = name
if 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_df else: 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.")
if gene_query.strip(): q = gene_query.strip().lower()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 filtered
query = normalize_text(query).lower() if query: 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["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"] = mask else: filtered["highlight"] = False
return filtered return filtered.sort_values(["start", "end"], kind="stable").reset_index(drop=True)
def build_linear_graphic_record(record, filtered_df):def build_linear_graphic_record(record, filtered_df: pd.DataFrame) -> GraphicRecord: 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] + "..." 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 0
features.append( GraphicFeature( start=int(row["start"]), end=int(row["end"]), strand=int(row["strand"]) if row["strand"] in (-1, 1) else 0, strand=strand, color=color, label=label, )2 unmodified lines return GraphicRecord(sequence_length=len(record.seq), features=features)
def draw_linear_map(record, filtered_df, annotate_limit=150):def draw_linear_map(record, filtered_df: pd.DataFrame, annotate_limit: int = 180): 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)) 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,4 unmodified lines return fig
def draw_circular_map(record, filtered_df, show_gc=True, gc_window=1000):def 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) sectors = {record.id: seq_len} circos = Circos(sectors, space=2) circos = Circos({record.id: seq_len}, 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) 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) outer_track.xticks_by_interval( 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 line label_size=8, )
pos_track = sector.add_track((60, 80)) neg_track = sector.add_track((40, 60)) 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 = "#ffd700" if row["highlight"] else FEATURE_COLORS.get(row["feature_type"], "#17becf")
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)
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) inner_bottom = 10 if 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 = 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) positions, skews = gc_skew_windows(record.seq, window_size) 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, ) 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) 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
def fig_to_png_bytes(fig, dpi=300):def fig_to_bytes(fig, fmt: str = "png", dpi: int = 300) -> bytes: buf = io.BytesIO() fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight") save_kwargs = {"bbox_inches": "tight"} if fmt.lower() == "png": save_kwargs["dpi"] = dpi fig.savefig(buf, format=fmt, **save_kwargs) 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()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 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)), "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 main(): st.title("🧬 Genome Visualization Tool")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 vc
def 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( """ Upload an annotated **GenBank (.gb / .gbk)** file to generate:
- **Circular genome map** - **Linear annotation map** - **Feature summary table** - **Downloadable publication-ready figures** **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("Settings") uploaded_file = st.file_uploader(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"], help="Only GenBank files are supported in this version.", accept_multiple_files=False, help="Best format for full sequence + annotation visualization.", )
gene_query = st.text_input( "Search/highlight gene", value="", help="Enter gene name, locus tag, or product keyword.", secondary_upload = None
elif 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 = None
elif 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.", )
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, 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 = None
if not uploaded_file: st.info("Upload a GenBank file to begin.") st.stop() st.header("Analysis settings") gene_query = st.text_input( "Search / highlight", value="", help="Search gene, locus tag, product, or note. Matches are highlighted in gold.", )
try: records = parse_genbank(uploaded_file) except Exception as exc: st.error(f"Failed to parse file: {exc}") st.stop() 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)
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) 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)
feature_df = record_to_feature_table(record) run_button = st.button("Run visualization", type="primary", use_container_width=True)
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))]# -----------------------------# 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()
selected_types = st.multiselect( "Feature types to display", options=available_types, default=default_selected, )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()
if not selected_types: st.warning("Please select at least one feature type.")# -----------------------------# 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()
filtered_df = filter_features(feature_df, selected_types, gene_query)if not parsed.records: st.error("No valid records were found.") st.stop()
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"])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())
with st.expander("Genome statistics", expanded=False): st.json(stats)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_types
tab1, tab2, tab3 = st.tabs(["Circular Map", "Linear Map", "Feature Table"])selected_types = st.multiselect( "Feature types to display", options=available_types, default=default_selected,)
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}")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)
with tab3: st.subheader("Feature Annotation Table")if legend_html: st.markdown('<div class="card"><b>Feature legend</b><br>' + legend_html + '</div>', unsafe_allow_html=True)
display_df = filtered_df.copy() if "highlight" in display_df.columns: display_df["highlight"] = display_df["highlight"].map({True: "yes", False: "no"})tab1, tab2, tab3, tab4 = st.tabs( ["Circular Map", "Linear Map", "Annotation Table", "Statistics"])
st.dataframe(display_df, use_container_width=True)# -----------------------------# Circular map# -----------------------------with tab1: st.subheader("Circular genome map")
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", 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", )
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** """ 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", )
if __name__ == "__main__": main()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