Spaces:
Build error
Build error
Update app.py
Browse files12341 unmodified line67889101111121314159 unmodified lines25262727282930313233343536293031323334353637383940414243444546474849505152535455565758596061626364656667686939404142707172737475767778798081828384858644454647484950518788899091929394959697985 unmodified lines10410510663646566676869707172737475767778798081828384851071081091101111121131141151161171181191201211221231241251261271281291301 unmodified line13213313493949596971351361371381391401411021421431441451461071471481491501511521131141151531541551561571581591601221611621241631641261651661281671681301691701321331341351711721731741751761779 unmodified lines1871881891511521901911921931551941951961971981992001622012022032041 unmodified line2062072081701711721732092102112122132142151 unmodified line2172182191811822202212222232242251852262272282292301912312322331942342351961971981992002012022032042052062072362372382392402412422432442452462472482492502112122132512522532542552562572582202592602612232622632642652262662672682691 unmodified line2712722732342742752762771 unmodified line2792802812422822832842852862872482492502512522532542552562572582882892902912922932942952962972982993003012 unmodified lines3043053062672683073083093103112723123133143153162772783173183193203213222822833233243252852862872882892902912922933263273283293303313323333343353362952963373383393403413423433443033453463473483063073083093103113123133143153163493503513523533543553563573583593603183193613623633643653663673683253263273693703713723293303733743753763773783793803813823833843853863343353873883893373903913923933943953963973982 unmodified lines40140240335035140440540635335435535635735835936036136236336440740840941041141241341441541641741841942042142242336842442542642742837342943037537637743143243337943443543643743838243944044144244338438538638738838939039139239339439539639744444544644744844945045145245345445545645745845946011 unmodified lines4724734744154754764774784794194204804814824834224234244254264844854864874884284894904914304314324334924934944954964974984364374995005015024404415035045055064444455075085094475105115125135145154505165174525185194544554565205215225235245255265274595285294614625305315325334655345354675365375384704715395405414734745425435445455465474785485494805505514824835525535545555565575585595604855615624875635645654904915665675684935695704955715725734984995745755765015775785035795805815065075825835845095855865875125885895905155915925175935945955195965975985996006015245255265275286026036046056066075306086095326106116125345356136146156166175386186196206215425435445455465476226236246256266276286296306316326336346356366376385515525536396406416426436446456466476486496506516526536546555555565576566576586596606616622 unmodified lines6656666676686695676706715696726736746756766776786796806815725736826836846855755765776866876886896906916926936946956965816976986997005857017027037047055897067077087097107117127137145977157167177187197207217227237247256027267277286046057297307316076086096106116127327337347357367377387397407417427437446197457467477487497507516226236246256266276287527537547557567577587597606306317617627636336346356366376387647657667677687697707717727737746437757766457777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098106518118126536546556566576586596606616626638138148158168178188198208218228238248258266676686696708278288298308318328338348358368378388398408418428438448458468478488498506736748518528538548558568578586766776786796808598608618628638646848658666866876886896906916928678688698708718728738748758768778786976988798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429437007017027039449459469479489499509519529539547077089559569579589597117129607147157167177187199619629639649659669679689699709717217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657669729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100177177210021003100410051006100710087757767777781009101010111012101310141015101610171018101978178210201021102278478578678778810231024102579079179279310261027102810291030103110321033103410351036795796103710381039104010411 unmodified line104310441045804104610478068071048104910508098108118128138148158168178188198208218228238248258268278281051830831832833105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610778358368378388398401078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911108438448458468478488498508518528538548558568578588598608618628638648658668678688691111111211131114111511161117111811191120112111221123112411251126112711281129113011318711132113311341135113611371138113911401141873874875876114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165878879116611671168116911701171117288388488588611731174117588888989089189289389489589689789889990011761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
import ioimport osimport re1 unmodified lineimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Tuple, Optionalfrom typing import Dict, List, Tuple
import matplotlibmatplotlib.use('Agg')matplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as np9 unmodified linesexcept Exception: gffutils = None
st.set_page_config(page_title='Genome Visualization Tool Premium', page_icon='🧬', layout='wide', initial_sidebar_state='expanded')
st.markdown('''<style>.main-title {font-size:2rem;font-weight:800;margin-bottom:0.2rem;}.subtle {color:#666;font-size:0.98rem;margin-bottom:0.8rem;}.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)# =========================# Global style# =========================plt.rcParams.update({ "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"], "font.size": 10, "axes.titlesize": 12, "axes.labelsize": 10, "axes.linewidth": 0.8, "xtick.labelsize": 9, "ytick.labelsize": 9, "legend.fontsize": 8, "figure.dpi": 160, "savefig.dpi": 600, "pdf.fonttype": 42, "ps.fonttype": 42,})
st.set_page_config( page_title="Genome Visualization Tool Ultra-Premium", page_icon="🧬", layout="wide", initial_sidebar_state="expanded",)
st.markdown( """ <style> .main-title {font-size:2.1rem; font-weight:800; margin-bottom:0.2rem;} .subtle {color:#5c6670; font-size:0.98rem; margin-bottom:0.9rem;} .card {padding:0.9rem 1rem; border-radius:14px; border:1px solid rgba(120,120,120,0.18); background:rgba(250,250,250,0.03); margin-bottom:0.8rem;} .small-note {font-size:0.87rem; color:#6a7480;} .kpi {padding:0.6rem 0.8rem; border-radius:12px; background:#fafbfc; border:1px solid #e5e9ef;} </style> """, unsafe_allow_html=True,)
FEATURE_COLORS = { 'CDS': '#1f77b4', 'gene': '#2ca02c', 'tRNA': '#ff7f0e', 'rRNA': '#d62728', 'ncRNA': '#e377c2', 'misc_feature': '#9467bd', 'repeat_region': '#8c564b', 'mobile_element': '#7f7f7f', 'source': '#bcbd22', 'ORF': '#17becf', 'exon': '#4daf4a', 'mRNA': '#984ea3', 'transcript': '#a65628', 'promoter': '#f781bf', 'default': '#4c78a8', 'highlight': '#ffd700' "CDS": "#1f77b4", "gene": "#2ca02c", "tRNA": "#ff7f0e", "rRNA": "#d62728", "ncRNA": "#9467bd", "misc_feature": "#8c564b", "repeat_region": "#7f7f7f", "mobile_element": "#bcbd22", "ORF": "#17becf", "exon": "#4daf4a", "mRNA": "#984ea3", "transcript": "#a65628", "promoter": "#f781bf", "bed_feature": "#6c757d", "default": "#4c78a8", "highlight": "#ffd700",}DEFAULT_FEATURES = ['CDS', 'gene', 'tRNA', 'rRNA', 'ncRNA', 'misc_feature', 'repeat_region', 'ORF']FASTA_EXTS = {'.fa', '.fasta', '.fna', '.fas', '.ffn', '.faa'}GB_EXTS = {'.gb', '.gbk', '.genbank'}EMBL_EXTS = {'.embl'}GFF_EXTS = {'.gff', '.gff3', '.gtf'}BED_EXTS = {'.bed'}TABLE_EXTS = {'.csv', '.tsv', '.txt'}DNA_COMPLEMENT = str.maketrans('ATGCatgcNn', 'TACGtacgNn')DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "misc_feature", "repeat_region", "ORF"]FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas", ".ffn", ".faa"}GB_EXTS = {".gb", ".gbk", ".genbank"}EMBL_EXTS = {".embl"}GFF_EXTS = {".gff", ".gff3", ".gtf"}BED_EXTS = {".bed"}TABLE_EXTS = {".csv", ".tsv", ".txt"}DNA_COMPLEMENT = str.maketrans("ATGCatgcNn", "TACGtacgNn")
@dataclassclass ParsedGenome:5 unmodified lines
def init_session_state(): defaults = { 'analysis_done': False, 'analysis_error': '', 'run_in_progress': False, 'parsed': None, 'record_ids': [], 'selected_record_id': None, 'full_df': pd.DataFrame(), 'filtered_df': pd.DataFrame(), 'display_df': pd.DataFrame(), 'stats': {}, 'notes': [], 'available_types': [], 'selected_types_cache': [], 'circ_png': None, 'lin_png': None, 'summary_text': '', 'table_csv': None, 'summary_zip': None, 'stats_df': pd.DataFrame(), 'dist_df': pd.DataFrame(), 'density_df': pd.DataFrame(), 'signature': None, 'performance_note': '', "analysis_done": False, "analysis_error": "", "parsed": None, "record_ids": [], "selected_record_id": None, "full_df": pd.DataFrame(), "filtered_df": pd.DataFrame(), "display_df": pd.DataFrame(), "stats": {}, "notes": [], "available_types": [], "selected_types_cache": [], "stats_df": pd.DataFrame(), "dist_df": pd.DataFrame(), "density_df": pd.DataFrame(), "summary_text": "", "figure_pack": {}, "table_csv": None, "summary_zip": None, "legend_html": "", "run_mode_cache": "Fast preview", } for k, v in defaults.items(): if k not in st.session_state:1 unmodified line
def clear_results(): keys = list(st.session_state.keys()) for k in keys: if k.startswith('_'): continue del st.session_state[k] keys = [k for k in st.session_state.keys() if not k.startswith("_")] for key in keys: del st.session_state[key] init_session_state()
def normalize_text(value: str) -> str: return re.sub(r'\s+', ' ', str(value or '')).strip() return re.sub(r"\s+", " ", str(value or "")).strip()
def file_suffix(name: str) -> str: n = str(name).lower() if n.endswith('.gz'): if n.endswith(".gz"): n = os.path.splitext(n)[0] return os.path.splitext(n)[1]
def maybe_decompress(name: str, data: bytes) -> Tuple[str, bytes]: if str(name).lower().endswith('.gz'): base = os.path.splitext(name)[0] return base, gzip.decompress(data) if str(name).lower().endswith(".gz"): return os.path.splitext(name)[0], gzip.decompress(data) return name, data
def infer_file_kind(filename: str) -> str: ext = file_suffix(filename) if ext in GB_EXTS: return 'genbank' return "genbank" if ext in EMBL_EXTS: return 'embl' return "embl" if ext in FASTA_EXTS: return 'fasta' return "fasta" if ext in GFF_EXTS: return 'gff' return "gff" if ext in BED_EXTS: return 'bed' return "bed" if ext in TABLE_EXTS: return 'table' if str(filename).lower().endswith('.zip'): return 'zip' return 'unknown' return "table" if str(filename).lower().endswith(".zip"): return "zip" return "unknown"
def get_feature_bounds(feature):9 unmodified lines
def get_feature_label(feature): qualifiers = getattr(feature, 'qualifiers', {}) or {} for key in ['gene', 'locus_tag', 'product', 'note', 'ID', 'Name']: 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') return getattr(feature, "type", "feature")
def compute_gc_percent(sequence: str) -> float: seq = str(sequence).upper() if not seq: return 0.0 gc = seq.count('G') + seq.count('C') gc = seq.count("G") + seq.count("C") return (gc / len(seq)) * 100.0
1 unmodified line seq = str(sequence).upper() positions, values = [], [] for i in range(0, len(seq), window_size): w = seq[i:i + window_size] if w: positions.append(i + len(w) // 2) values.append(compute_gc_percent(w)) window = seq[i:i + window_size] if window: positions.append(i + len(window) // 2) values.append(compute_gc_percent(window)) return positions, values
1 unmodified line seq = str(sequence).upper() positions, values = [], [] for i in range(0, len(seq), window_size): w = seq[i:i + window_size] g, c = w.count('G'), w.count('C') window = seq[i:i + window_size] g = window.count("G") c = window.count("C") denom = g + c positions.append(i + len(window) // 2) values.append((g - c) / denom if denom else 0.0) positions.append(i + len(w) // 2) return positions, values
def record_to_feature_table(record) -> pd.DataFrame: rows = [] for feature in getattr(record, 'features', []): for feature in getattr(record, "features", []): try: start, end, strand = get_feature_bounds(feature) qualifiers = getattr(feature, 'qualifiers', {}) or {} 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', "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 cols = ['record_id', 'feature_type', 'label', 'start', 'end', 'length', 'strand', 'locus_tag', 'gene', 'product', 'note', 'source'] df = pd.DataFrame(rows, columns=cols) return df.sort_values(['start', 'end'], kind='stable').reset_index(drop=True) cols = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source"] return pd.DataFrame(rows, columns=cols).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, max_orfs: int = 3000) -> pd.DataFrame:def find_orfs_in_sequence(sequence: str, min_aa: int = 90, max_orfs: int = 2500) -> pd.DataFrame: seq = str(sequence).upper() seq_len = len(seq) stops, start_codons = {'TAA', 'TAG', 'TGA'}, {'ATG', 'GTG', 'TTG'} stops = {"TAA", "TAG", "TGA"} starts = {"ATG", "GTG", "TTG"} rows = []
def scan_strand(s: str, strand_value: int): def scan_strand(s: str, strand_val: int): nonlocal rows for frame in range(3): i = frame1 unmodified line if len(rows) >= max_orfs: return codon = s[i:i + 3] if codon in start_codons: if codon in starts: j = i + 3 while j <= len(s) - 3: stop = s[j:j + 3]1 unmodified line nt_len = (j + 3) - i aa_len = nt_len // 3 if aa_len >= min_aa: if strand_value == 1: if strand_val == 1: start, end = i, j + 3 else: 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', "feature_type": "ORF", "label": f"ORF_{strand_val}_{start+1}_{end}", "start": int(start), "end": int(end), "length": int(end - start), "strand": int(strand_val), "locus_tag": "", "gene": "", "product": f"Predicted ORF ({aa_len} aa)", "note": "FASTA-only inferred ORF", "source": "orf_prediction", }) i = j + 3 break2 unmodified lines
scan_strand(seq, 1) scan_strand(reverse_complement(seq), -1) cols = ['feature_type', 'label', 'start', 'end', 'length', 'strand', 'locus_tag', 'gene', 'product', 'note', 'source'] return pd.DataFrame(rows, columns=cols).sort_values(['start', 'end'], kind='stable').reset_index(drop=True) cols = ["feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source"] return pd.DataFrame(rows, columns=cols).sort_values(["start", "end"], kind="stable").reset_index(drop=True)
def parse_text_records(data: bytes, fmt: str): handle = io.StringIO(data.decode('utf-8', errors='replace')) handle = io.StringIO(data.decode("utf-8", errors="replace")) return list(SeqIO.parse(handle, fmt))
def parse_annotation_table(data: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: text = data.decode('utf-8', errors='replace') sep = ',' if ',' in text.splitlines()[0] else '\t' text = data.decode("utf-8", errors="replace") first = text.splitlines()[0] if text.splitlines() else "" sep = "," if "," in first else "\t" df = pd.read_csv(io.StringIO(text), sep=sep) df.columns = [c.strip() for c in df.columns] colmap = {c.lower(): c for c in df.columns} start_col = colmap.get('start') end_col = colmap.get('end') start_col = colmap.get("start") end_col = colmap.get("end") if start_col is None or end_col is None: raise ValueError('Annotation table requires start and end columns.') record_col = colmap.get('record_id') or colmap.get('seqid') or colmap.get('chrom') or colmap.get('contig') type_col = colmap.get('feature_type') or colmap.get('type') label_col = colmap.get('label') or colmap.get('gene') or colmap.get('name') strand_col = colmap.get('strand') product_col = colmap.get('product') note_col = colmap.get('note') locus_col = colmap.get('locus_tag') records = parse_text_records(fasta_bytes, 'fasta') raise ValueError("Annotation table requires start and end columns.") record_col = colmap.get("record_id") or colmap.get("seqid") or colmap.get("chrom") or colmap.get("contig") type_col = colmap.get("feature_type") or colmap.get("type") label_col = colmap.get("label") or colmap.get("gene") or colmap.get("name") strand_col = colmap.get("strand") product_col = colmap.get("product") note_col = colmap.get("note") locus_col = colmap.get("locus_tag")
records = parse_text_records(fasta_bytes, "fasta") if not records: raise ValueError('No FASTA records found for annotation table pairing.') record_ids = {r.id for r in records} raise ValueError("No FASTA records found for annotation table pairing.") tables = {}
for r in records: sdf = df if record_col is None else df[df[record_col].astype(str) == r.id].copy() if record_col is not None and sdf.empty: sdf = df[df[record_col].astype(str) == r.id.split()[0]].copy() if sdf.empty: tables[r.id] = pd.DataFrame(columns=['record_id','feature_type','label','start','end','length','strand','locus_tag','gene','product','note','source']) tables[r.id] = pd.DataFrame(columns=["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"]) continue
out = pd.DataFrame({ 'record_id': r.id, 'feature_type': sdf[type_col].astype(str) if type_col else 'misc_feature', 'label': sdf[label_col].astype(str) if label_col else 'feature', 'start': sdf[start_col].astype(int), 'end': sdf[end_col].astype(int), 'strand': sdf[strand_col].replace({'+':1,'-':-1}).fillna(0).astype(int) if strand_col else 0, 'locus_tag': sdf[locus_col].astype(str) if locus_col else '', 'gene': sdf[label_col].astype(str) if label_col else '', 'product': sdf[product_col].astype(str) if product_col else '', 'note': sdf[note_col].astype(str) if note_col else '', 'source': 'table', "record_id": r.id, "feature_type": sdf[type_col].astype(str) if type_col else "misc_feature", "label": sdf[label_col].astype(str) if label_col else "feature", "start": sdf[start_col].astype(int), "end": sdf[end_col].astype(int), "strand": sdf[strand_col].replace({"+": 1, "-": -1}).fillna(0).astype(int) if strand_col else 0, "locus_tag": sdf[locus_col].astype(str) if locus_col else "", "gene": sdf[label_col].astype(str) if label_col else "", "product": sdf[product_col].astype(str) if product_col else "", "note": sdf[note_col].astype(str) if note_col else "", "source": "table", }) out['length'] = (out['end'] - out['start']).clip(lower=0) tables[r.id] = out.sort_values(['start','end'], kind='stable').reset_index(drop=True) out["length"] = (out["end"] - out["start"]).clip(lower=0) tables[r.id] = out[["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"]].sort_values(["start","end"]).reset_index(drop=True)
return records, tables
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: 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') return 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) db_path = os.path.join(workdir, "temp_gff.db") return 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, )
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_text_records(fasta_bytes, 'fasta') gff_text = gff_bytes.decode("utf-8", errors="replace") records = parse_text_records(fasta_bytes, "fasta") if not records: raise ValueError('No FASTA records found.') raise ValueError("No FASTA records found.") record_map = {r.id: r for r in records} alt_map = {r.id.split()[0]: r for r in records} alt_map.update({r.name: r for r in records}) tables = {r.id: [] for r in records}
with tempfile.TemporaryDirectory() as td: db = build_gff_db(gff_text, td) for feature in db.all_features():2 unmodified lines 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 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', "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 = {} cols = ["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"] for rec in records: out[rec.id] = pd.DataFrame(tables.get(rec.id, [])).sort_values(['start','end'], kind='stable').reset_index(drop=True) out[rec.id] = pd.DataFrame(tables.get(rec.id, []), columns=cols).sort_values(["start","end"], kind="stable").reset_index(drop=True) return records, out
def bed_and_fasta_to_tables(bed_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: records = parse_text_records(fasta_bytes, 'fasta') records = parse_text_records(fasta_bytes, "fasta") if not records: raise ValueError('No FASTA records found.') cols = ['seqid','start','end','name','score','strand'] df = pd.read_csv(io.StringIO(bed_bytes.decode('utf-8', errors='replace')), sep='\t', comment='#', header=None) raise ValueError("No FASTA records found.") df = pd.read_csv(io.StringIO(bed_bytes.decode("utf-8", errors="replace")), sep="\t", comment="#", header=None) df = df.iloc[:, :min(6, df.shape[1])] df.columns = cols[:df.shape[1]] df.columns = ["seqid", "start", "end", "name", "score", "strand"][:df.shape[1]] tables = {} cols = ["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"]
for r in records: sdf = df[df['seqid'].astype(str) == r.id].copy() if 'seqid' in df.columns else pd.DataFrame() sdf = df[df["seqid"].astype(str) == r.id].copy() if "seqid" in df.columns else pd.DataFrame() if sdf.empty: tables[r.id] = pd.DataFrame(columns=cols) continue out = pd.DataFrame({ 'record_id': r.id, 'feature_type': 'bed_feature', 'label': sdf['name'].astype(str) if 'name' in sdf.columns else 'BED_feature', 'start': sdf['start'].astype(int), 'end': sdf['end'].astype(int), 'strand': sdf['strand'].replace({'+':1,'-':-1}).fillna(0).astype(int) if 'strand' in sdf.columns else 0, 'locus_tag': '', 'gene': sdf['name'].astype(str) if 'name' in sdf.columns else '', 'product': '', 'note': 'Imported from BED', 'source': 'bed', }) if not sdf.empty else pd.DataFrame(columns=['record_id','feature_type','label','start','end','strand','locus_tag','gene','product','note','source']) if not out.empty: out['length'] = (out['end'] - out['start']).clip(lower=0) else: out['length'] = pd.Series(dtype=int) tables[r.id] = out[['record_id','feature_type','label','start','end','length','strand','locus_tag','gene','product','note','source']] "record_id": r.id, "feature_type": "bed_feature", "label": sdf["name"].astype(str) if "name" in sdf.columns else "BED_feature", "start": sdf["start"].astype(int), "end": sdf["end"].astype(int), "strand": sdf["strand"].replace({"+":1, "-":-1}).fillna(0).astype(int) if "strand" in sdf.columns else 0, "locus_tag": "", "gene": sdf["name"].astype(str) if "name" in sdf.columns else "", "product": "", "note": "Imported from BED", "source": "bed", }) out["length"] = (out["end"] - out["start"]).clip(lower=0) tables[r.id] = out[cols].sort_values(["start","end"]).reset_index(drop=True) return records, tables
11 unmodified lines
def parse_input_bundle(primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int) -> ParsedGenome: notes = [] if input_mode == 'ZIP (auto-detect)':
if input_mode == "ZIP (auto-detect)": files = parse_uploaded_zip(primary_upload) normalized = {} for name, data in files.items(): n2, d2 = maybe_decompress(name, data) normalized[n2] = d2 new_name, new_data = maybe_decompress(name, data) normalized[new_name] = new_data
names = list(normalized.keys()) primary_name = next((n for n in names if infer_file_kind(n) in {'genbank','embl'}), None) if primary_name: data = normalized[primary_name] fmt = 'genbank' if infer_file_kind(primary_name) == 'genbank' else 'embl' records = parse_text_records(data, fmt) rich_name = next((n for n in names if infer_file_kind(n) in {"genbank", "embl"}), None) if rich_name: fmt = "genbank" if infer_file_kind(rich_name) == "genbank" else "embl" records = parse_text_records(normalized[rich_name], fmt) tables = {r.id: record_to_feature_table(r) for r in records} notes.append(f'ZIP detected {fmt.upper()} input: {primary_name}') notes.append(f"ZIP detected {fmt.upper()} input: {rich_name}") return ParsedGenome(records, tables, fmt, notes)
fasta_name = next((n for n in names if infer_file_kind(n) == 'fasta'), None) gff_name = next((n for n in names if infer_file_kind(n) == 'gff'), None) bed_name = next((n for n in names if infer_file_kind(n) == 'bed'), None) table_name = next((n for n in names if infer_file_kind(n) == 'table'), None) fasta_name = next((n for n in names if infer_file_kind(n) == "fasta"), None) gff_name = next((n for n in names if infer_file_kind(n) == "gff"), None) bed_name = next((n for n in names if infer_file_kind(n) == "bed"), None) table_name = next((n for n in names if infer_file_kind(n) == "table"), None)
if gff_name and fasta_name: records, tables = gff_and_fasta_to_tables(normalized[gff_name], normalized[fasta_name]) notes.append(f'ZIP detected GFF + FASTA input: {gff_name} + {fasta_name}') return ParsedGenome(records, tables, 'gff_fasta', notes) notes.append(f"ZIP detected GFF/GTF + FASTA input: {gff_name} + {fasta_name}") return ParsedGenome(records, tables, "gff_fasta", notes) if bed_name and fasta_name: records, tables = bed_and_fasta_to_tables(normalized[bed_name], normalized[fasta_name]) notes.append(f'ZIP detected BED + FASTA input: {bed_name} + {fasta_name}') return ParsedGenome(records, tables, 'bed_fasta', notes) notes.append(f"ZIP detected BED + FASTA input: {bed_name} + {fasta_name}") return ParsedGenome(records, tables, "bed_fasta", notes) if table_name and fasta_name: records, tables = parse_annotation_table(normalized[table_name], normalized[fasta_name]) notes.append(f'ZIP detected table + FASTA input: {table_name} + {fasta_name}') return ParsedGenome(records, tables, 'table_fasta', notes) notes.append(f"ZIP detected annotation table + FASTA input: {table_name} + {fasta_name}") return ParsedGenome(records, tables, "table_fasta", notes) if fasta_name: records = parse_text_records(normalized[fasta_name], 'fasta') records = parse_text_records(normalized[fasta_name], "fasta") long_input = sum(len(str(r.seq)) for r in records) > 3_000_000 do_orf = infer_orfs and not long_input tables = {} cols = ["feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"] for r in records: orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa) if infer_orfs else pd.DataFrame(columns=['feature_type','label','start','end','length','strand','locus_tag','gene','product','note','source']) orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa) if do_orf else pd.DataFrame(columns=cols) if not orf_df.empty: orf_df.insert(0, 'record_id', r.id) orf_df.insert(0, "record_id", r.id) tables[r.id] = orf_df notes.append(f'ZIP detected FASTA-only input: {fasta_name}') return ParsedGenome(records, tables, 'fasta', notes) raise ValueError('ZIP file did not contain a supported combination.') notes.append(f"ZIP detected FASTA-only input: {fasta_name}") if infer_orfs and long_input: notes.append("ORF prediction was disabled automatically because the FASTA input was very large.") return ParsedGenome(records, tables, "fasta", notes)
raise ValueError("ZIP file did not contain a supported combination.")
pname, pdata = maybe_decompress(primary_upload.name, primary_upload.getvalue()) kind = infer_file_kind(pname) if input_mode == 'Universal / Auto-detect' else None kind = infer_file_kind(pname) if input_mode == "Universal / Auto-detect" else None
if input_mode in {'GenBank', 'EMBL', 'Universal / Auto-detect'} and (input_mode != 'Universal / Auto-detect' or kind in {'genbank','embl'}): fmt = 'genbank' if (input_mode == 'GenBank' or kind == 'genbank') else 'embl' if input_mode in {"GenBank", "EMBL", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind in {"genbank", "embl"}): fmt = "genbank" if (input_mode == "GenBank" or kind == "genbank") else "embl" records = parse_text_records(pdata, fmt) if not records: raise ValueError(f'No {fmt} records were found.') raise ValueError(f"No {fmt} records were found.") tables = {r.id: record_to_feature_table(r) for r in records} notes.append(f'Parsed annotated {fmt.upper()} input.') notes.append(f"Parsed annotated {fmt.upper()} input.") return ParsedGenome(records, tables, fmt, notes)
if input_mode in {'FASTA', 'Universal / Auto-detect'} and (input_mode != 'Universal / Auto-detect' or kind == 'fasta'): records = parse_text_records(pdata, 'fasta') if input_mode in {"FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "fasta"): records = parse_text_records(pdata, "fasta") if not records: raise ValueError('No FASTA records were found.') tables = {} raise ValueError("No FASTA records were found.") long_input = sum(len(str(r.seq)) for r in records) > 3_000_000 do_orf = infer_orfs and not long_input tables = {} cols = ["feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"] for r in records: orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa) if do_orf else pd.DataFrame(columns=['feature_type','label','start','end','length','strand','locus_tag','gene','product','note','source']) orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa) if do_orf else pd.DataFrame(columns=cols) if not orf_df.empty: orf_df.insert(0, 'record_id', r.id) orf_df.insert(0, "record_id", r.id) tables[r.id] = orf_df notes.append('FASTA-only input.' + (' ORF prediction disabled automatically for very large input.' if infer_orfs and long_input else (' ORF prediction enabled.' if do_orf else ' No native annotation available.'))) return ParsedGenome(records, tables, 'fasta', notes) notes.append("FASTA-only input.") if do_orf: notes.append("ORF prediction enabled.") elif infer_orfs and long_input: notes.append("ORF prediction was disabled automatically because the FASTA input was very large.") else: notes.append("No native annotation available.") return ParsedGenome(records, tables, "fasta", notes)
if input_mode in {'GFF/GTF + FASTA', 'Universal / Auto-detect'} and (input_mode != 'Universal / Auto-detect' or kind == 'gff'): if input_mode in {"GFF/GTF + FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "gff"): if secondary_upload is None: raise ValueError('Please upload the matching FASTA file.') raise ValueError("Please upload the matching FASTA file.") sname, sdata = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) records, tables = gff_and_fasta_to_tables(pdata, sdata) notes.append('Parsed GFF/GTF annotation with FASTA sequence.') return ParsedGenome(records, tables, 'gff_fasta', notes) notes.append("Parsed GFF/GTF annotation with FASTA sequence.") return ParsedGenome(records, tables, "gff_fasta", notes)
if input_mode in {'BED + FASTA', 'Universal / Auto-detect'} and (input_mode != 'Universal / Auto-detect' or kind == 'bed'): if input_mode in {"BED + FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "bed"): if secondary_upload is None: raise ValueError('Please upload the matching FASTA file.') raise ValueError("Please upload the matching FASTA file.") sname, sdata = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) records, tables = bed_and_fasta_to_tables(pdata, sdata) notes.append('Parsed BED coordinates with FASTA sequence.') return ParsedGenome(records, tables, 'bed_fasta', notes) notes.append("Parsed BED coordinates with FASTA sequence.") return ParsedGenome(records, tables, "bed_fasta", notes)
if input_mode in {'Annotation table + FASTA', 'Universal / Auto-detect'} and (input_mode != 'Universal / Auto-detect' or kind == 'table'): if input_mode in {"Annotation table + FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "table"): if secondary_upload is None: raise ValueError('Please upload the matching FASTA file.') raise ValueError("Please upload the matching FASTA file.") sname, sdata = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) records, tables = parse_annotation_table(pdata, sdata) notes.append('Parsed tabular annotation with FASTA sequence.') return ParsedGenome(records, tables, 'table_fasta', notes) notes.append("Parsed annotation table with FASTA sequence.") return ParsedGenome(records, tables, "table_fasta", notes)
raise ValueError('Unsupported input or missing paired file.') raise ValueError("Unsupported input or missing paired file.")
def filter_features(df: pd.DataFrame, selected_types: List[str], query: str, min_len: int = 0, max_features: int = 20000) -> pd.DataFrame:def filter_features(df: pd.DataFrame, selected_types: List[str], query: str, min_len: int = 0, max_features: int = 25000) -> pd.DataFrame: filtered = df.copy() if selected_types: filtered = filtered[filtered['feature_type'].isin(selected_types)].copy() filtered = filtered[filtered["feature_type"].isin(selected_types)].copy() if min_len > 0 and not filtered.empty: filtered = filtered[filtered['length'].fillna(0) >= min_len].copy() filtered = filtered[filtered["length"].fillna(0) >= min_len].copy()
if filtered.empty: filtered['highlight'] = False filtered["highlight"] = False return filtered
query = 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["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 filtered["highlight"] = mask else: filtered['highlight'] = False filtered["highlight"] = False
if len(filtered) > max_features: filtered = filtered.nsmallest(max_features, 'start').copy() return filtered.sort_values(['start','end'], kind='stable').reset_index(drop=True) filtered = filtered.nsmallest(max_features, "start").copy()
return filtered.sort_values(["start", "end"], kind="stable").reset_index(drop=True)
def build_linear_graphic_record(record, filtered_df: pd.DataFrame, annotate_limit: int = 120) -> GraphicRecord:def build_linear_graphic_record(record, filtered_df: pd.DataFrame, annotate_limit: int = 120, label_max_len: int = 28) -> GraphicRecord: features = [] do_labels = len(filtered_df) <= annotate_limit 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 do_labels else None if label and len(label) > 24: label = label[:21] + '...' strand = int(row['strand']) if row['strand'] in (-1, 1) else 0 features.append(GraphicFeature(start=int(row['start']), end=int(row['end']), strand=strand, color=color, label=label)) 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 do_labels else None if label and len(label) > label_max_len: label = label[: label_max_len - 3] + "..." strand = int(row["strand"]) if row["strand"] in (-1, 1) else 0 features.append( GraphicFeature( start=int(row["start"]), end=int(row["end"]), strand=strand, color=color, label=label, ) ) return GraphicRecord(sequence_length=len(record.seq), features=features)
def draw_linear_map(record, filtered_df: pd.DataFrame): graphic_record = build_linear_graphic_record(record, filtered_df) fig_height = 4.2 if len(filtered_df) <= 80 else 5.2 if len(filtered_df) <= 250 else 6.0def add_feature_legend(ax, feature_types: List[str], include_highlight: bool): items = [] for ft in feature_types: color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) items.append(Line2D([0], [0], color=color, lw=4, label=ft)) if include_highlight: items.append(Line2D([0], [0], color=FEATURE_COLORS["highlight"], lw=4, label="highlighted match")) if items: ax.legend(handles=items, loc="upper right", frameon=False, ncol=2)
def draw_linear_map(record, filtered_df: pd.DataFrame, feature_types: List[str], publication_mode: bool = False): annotate_limit = 180 if publication_mode else 110 label_max_len = 34 if publication_mode else 24 graphic_record = build_linear_graphic_record(record, filtered_df, annotate_limit=annotate_limit, label_max_len=label_max_len) fig_height = 4.8 if len(filtered_df) <= 80 else 6.0 if len(filtered_df) <= 220 else 7.2 fig, ax = plt.subplots(figsize=(16, fig_height)) graphic_record.plot(ax=ax, with_ruler=True, annotate_inline=(len(filtered_df) <= 120)) ax.set_title('A. Linear genome map', fontsize=14, fontweight='bold', loc='left') ax.set_xlabel(f'Record: {record.id} | Length: {len(record.seq):,} bp', fontsize=10) graphic_record.plot(ax=ax, with_ruler=True, annotate_inline=(len(filtered_df) <= annotate_limit)) ax.set_title("A. Linear genome map", fontsize=14, fontweight="bold", loc="left") ax.set_xlabel(f"Record: {record.id} | Length: {len(record.seq):,} bp", fontsize=10) add_feature_legend(ax, feature_types, include_highlight=bool(filtered_df["highlight"].any()) if "highlight" in filtered_df.columns and not filtered_df.empty else False) plt.tight_layout() return fig
2 unmodified lines 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_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, label_orientation='vertical', label_size=8) 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, label_orientation="vertical", label_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) 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, end = int(row['start']), int(row['end']) color = FEATURE_COLORS['highlight'] if bool(row.get('highlight', False)) else FEATURE_COLORS.get(row['feature_type'], FEATURE_COLORS['default']) (neg_track if row['strand'] == -1 else pos_track).rect(start, end, fc=color, ec=color) 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 = 10 if show_gc_content: gc_track = sector.add_track((26, 40)) gc_track.axis(fc='#f8f8f8', ec='black', lw=0.25) gc_track.axis(fc="#f8f8f8", ec="black", lw=0.25) positions, values = chunk_gc_content(record.seq, window_size) if values: gc_track.line(positions, values, vmin=0, vmax=100) gc_track.fill_between(positions, values, y2=[50.0] * len(values), vmin=0, vmax=100, alpha=0.3) gc_track.fill_between(positions, values, y2=[50.0] * len(values), vmin=0, vmax=100, alpha=0.28) inner_bottom = 24
if show_gc_skew: skew_track = sector.add_track((inner_bottom, inner_bottom + 12)) skew_track.axis(fc='#f8f8f8', ec='black', lw=0.25) skew_track.axis(fc="#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.35)
fig = circos.plotfig() fig.set_size_inches(8.8, 8.8) fig.suptitle('B. Circular genome map', fontsize=14, fontweight='bold', y=0.98, x=0.12, ha='left') fig.suptitle("B. Circular genome map", fontsize=14, fontweight="bold", y=0.98, x=0.12, ha="left") return fig
def feature_distribution_table(df: pd.DataFrame) -> pd.DataFrame: if df.empty: return pd.DataFrame(columns=["feature_type", "count"]) return df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count")
def draw_feature_distribution(dist_df: pd.DataFrame): fig, ax = plt.subplots(figsize=(9, 4.8)) fig, ax = plt.subplots(figsize=(9, 5)) ax.set_title("C. Feature-type distribution", fontsize=14, fontweight="bold", loc="left") if dist_df.empty: ax.text(0.5, 0.5, 'No features available', ha='center', va='center') ax.axis('off') ax.text(0.5, 0.5, "No features available", ha="center", va="center") ax.axis("off") else: show_df = dist_df.head(15) ax.bar(show_df['feature_type'], show_df['count']) ax.set_title('C. Feature-type distribution', fontsize=14, fontweight='bold', loc='left') ax.set_xlabel('Feature class') ax.set_ylabel('Count') ax.tick_params(axis='x', rotation=45) show_df = dist_df.head(15).copy() colors = [FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) for ft in show_df["feature_type"]] ax.bar(show_df["feature_type"], show_df["count"], color=colors, edgecolor="black", linewidth=0.4) ax.set_xlabel("Feature class") ax.set_ylabel("Count") ax.tick_params(axis="x", rotation=40) ax.grid(axis="y", alpha=0.25, linestyle="--") plt.tight_layout() return fig
def build_density_df(record, filtered_df: pd.DataFrame, bins: int = 100) -> pd.DataFrame: if filtered_df.empty: return pd.DataFrame(columns=['bin_start', 'bin_end', 'count']) return pd.DataFrame(columns=["bin_start", "bin_end", "count"]) seq_len = len(record.seq) edges = np.linspace(0, seq_len, bins + 1, dtype=int) counts = [] for i in range(bins): start = edges[i] end = edges[i + 1] mids = ((filtered_df['start'].fillna(0) + filtered_df['end'].fillna(0)) / 2).astype(int).clip(0, seq_len) counts, _ = np.histogram(mids, bins=edges) return pd.DataFrame({'bin_start': edges[:-1], 'bin_end': edges[1:], 'count': counts})
def draw_density_plot(density_df: pd.DataFrame): fig, ax = plt.subplots(figsize=(10.5, 4.2)) count = ((filtered_df["start"] < end) & (filtered_df["end"] > start)).sum() counts.append(count) return pd.DataFrame({"bin_start": edges[:-1], "bin_end": edges[1:], "count": counts})
def draw_density_plot(density_df: pd.DataFrame, seq_len: int): fig, ax = plt.subplots(figsize=(10, 4.8)) ax.set_title("D. Genome-wide feature density", fontsize=14, fontweight="bold", loc="left") if density_df.empty: ax.text(0.5, 0.5, 'No features available', ha='center', va='center') ax.axis('off') ax.text(0.5, 0.5, "No features available", ha="center", va="center") ax.axis("off") else: x = (density_df['bin_start'] + density_df['bin_end']) / 2 ax.plot(x, density_df['count'], linewidth=1.6) ax.fill_between(x, density_df['count'], alpha=0.25) ax.set_title('D. Genome-wide feature density', fontsize=14, fontweight='bold', loc='left') ax.set_xlabel('Genomic position (bp)') ax.set_ylabel('Feature count per bin') mids = (density_df["bin_start"] + density_df["bin_end"]) / 2 ax.plot(mids, density_df["count"], linewidth=1.8) ax.fill_between(mids, density_df["count"], alpha=0.25) ax.set_xlabel("Genome position (bp)") ax.set_ylabel("Feature count") ax.set_xlim(0, seq_len) ax.grid(alpha=0.25, linestyle="--") plt.tight_layout() return fig
def fig_to_png(fig, dpi: int = 220) -> bytes:def fig_to_bytes(fig, fmt="png", dpi=600) -> bytes: buf = io.BytesIO() fig.savefig(buf, format='png', dpi=dpi, bbox_inches='tight') kwargs = {"bbox_inches": "tight"} if fmt.lower() == "png": kwargs["dpi"] = dpi fig.savefig(buf, format=fmt, **kwargs) buf.seek(0) return buf.getvalue()
def fig_to_rgb_array(fig, dpi=260): buf = io.BytesIO() fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight") buf.seek(0) img = plt.imread(buf) return img
def build_publication_composite(linear_fig, circular_fig, dist_fig, density_fig, record_id: str): linear_img = fig_to_rgb_array(linear_fig, dpi=260) circular_img = fig_to_rgb_array(circular_fig, dpi=260) dist_img = fig_to_rgb_array(dist_fig, dpi=260) density_img = fig_to_rgb_array(density_fig, dpi=260)
fig, axes = plt.subplots(2, 2, figsize=(16, 13)) fig.suptitle(f"Genome annotation figure set: {record_id}", fontsize=16, fontweight="bold", y=0.99)
for ax, img in zip(axes.ravel(), [linear_img, circular_img, dist_img, density_img]): ax.imshow(img) ax.axis("off")
plt.tight_layout(rect=[0, 0, 1, 0.975]) return fig
def build_summary_stats(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame) -> Dict[str, object]: counts = full_df['feature_type'].value_counts().to_dict() if not full_df.empty else {} 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': int(counts.get('CDS', 0)), 'gene': int(counts.get('gene', 0)), 'tRNA': int(counts.get('tRNA', 0)), 'rRNA': int(counts.get('rRNA', 0)), 'ORF': int(counts.get('ORF', 0)), "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": int(counts.get("CDS", 0)), "gene": int(counts.get("gene", 0)), "tRNA": int(counts.get("tRNA", 0)), "rRNA": int(counts.get("rRNA", 0)), "ORF": int(counts.get("ORF", 0)), }
def feature_distribution_table(df: pd.DataFrame) -> pd.DataFrame: if df.empty: return pd.DataFrame(columns=['feature_type', 'count']) return df['feature_type'].value_counts().rename_axis('feature_type').reset_index(name='count')def build_legend_html(feature_types: List[str], include_highlight: bool = False) -> str: parts = [] for ft in feature_types: color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) parts.append( f""" <span style="display:inline-flex;align-items:center;margin-right:14px;margin-bottom:6px;"> <span style="display:inline-block;width:13px;height:13px;border-radius:3px;background:{color};margin-right:6px;border:1px solid #aaa;"></span> <span style="font-size:0.92rem;">{ft}</span> </span> """ ) if include_highlight: parts.append( f""" <span style="display:inline-flex;align-items:center;margin-right:14px;margin-bottom:6px;"> <span style="display:inline-block;width:13px;height:13px;border-radius:3px;background:{FEATURE_COLORS['highlight']};margin-right:6px;border:1px solid #aaa;"></span> <span style="font-size:0.92rem;">highlighted match</span> </span> """ ) return "".join(parts)
def build_results_text(stats: Dict[str, object], dist_df: pd.DataFrame, source_mode: str, notes: List[str]) -> str: top = ', '.join([f"{r.feature_type} ({r.count})" for r in dist_df.head(5).itertuples(index=False)]) if not dist_df.empty else 'no annotated features'def manuscript_summary_text(stats: Dict[str, object], top_features: pd.DataFrame, record_id: str, query: str, run_mode: str) -> str: feature_phrase = "No annotated feature classes were available." if not top_features.empty: top3 = ", ".join([f"{r.feature_type} ({r.count})" for r in top_features.head(3).itertuples()]) feature_phrase = f"The most abundant annotated classes were {top3}." highlight_phrase = f' The search query "{query}" was highlighted in gold across the figure set.' if query.strip() else "" quality_phrase = "Publication mode was used to generate vector-ready figure exports (SVG/PDF) together with high-resolution PNG files." if run_mode == "Publication quality" else "Fast preview mode was used for rapid inspection, while preserving clear labels and feature legends." return ( f"Genome visualization was completed for record {stats['Record ID']} with a total sequence length of {stats['Genome length (bp)']:,} bp and GC content of {stats['GC (%)']}%. " f"A total of {stats['Total parsed features']} features were parsed and {stats['Displayed features']} features were displayed after filtering. " f"The dominant annotated classes were {top}. " f"Input mode was {source_mode}. " + (' '.join(notes) if notes else '') f"The record {record_id} spans {stats['Genome length (bp)']:,} bp with a GC content of {stats['GC (%)']:.2f}%. " f"A total of {stats['Total parsed features']} features were parsed, of which {stats['Displayed features']} were displayed after filtering. " f"{feature_phrase}{highlight_phrase} {quality_phrase}" )
def make_results_bundle(stats_df, feature_df, figs: Dict[str, bytes], results_text: str) -> bytes:def make_results_bundle(figure_pack: Dict[str, bytes], summary_df: pd.DataFrame, feature_df: pd.DataFrame, stats_df: pd.DataFrame, density_df: pd.DataFrame, summary_text: str) -> bytes: mem = io.BytesIO() with zipfile.ZipFile(mem, mode='w', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr('summary_statistics.csv', stats_df.to_csv(index=False)) zf.writestr('feature_annotations.csv', feature_df.to_csv(index=False)) zf.writestr('manuscript_ready_results.txt', results_text) for name, data in figs.items(): if data is not None: zf.writestr(name, data) with zipfile.ZipFile(mem, mode="w", compression=zipfile.ZIP_DEFLATED) as zf: for name, content in figure_pack.items(): if content is not None: zf.writestr(name, content) zf.writestr("feature_annotations.csv", feature_df.to_csv(index=False)) zf.writestr("summary_statistics.csv", stats_df.to_csv(index=False)) zf.writestr("feature_density.csv", density_df.to_csv(index=False)) zf.writestr("results_summary.txt", summary_text) mem.seek(0) return mem.getvalue()
def run_analysis(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa, gene_query, show_gc_content, show_gc_skew, window_size, min_feature_length, selected_record_id=None): parsed = parse_input_bundle(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa)def prepare_figures(record, filtered_df, full_df, available_types, show_gc_content, show_gc_skew, window_size, run_mode): publication = run_mode == "Publication quality"
linear_fig = draw_linear_map(record, filtered_df, available_types, publication_mode=publication) circular_fig = draw_circular_map(record, filtered_df, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=int(window_size)) dist_df = feature_distribution_table(full_df) density_df = build_density_df(record, filtered_df, bins=120 if publication else 80) dist_fig = draw_feature_distribution(dist_df) density_fig = draw_density_plot(density_df, len(record.seq)) composite_fig = build_publication_composite(linear_fig, circular_fig, dist_fig, density_fig, record.id)
figure_pack = { "panel_A_linear_map.png": fig_to_bytes(linear_fig, "png", dpi=600 if publication else 300), "panel_B_circular_map.png": fig_to_bytes(circular_fig, "png", dpi=600 if publication else 300), "panel_C_feature_distribution.png": fig_to_bytes(dist_fig, "png", dpi=600 if publication else 300), "panel_D_feature_density.png": fig_to_bytes(density_fig, "png", dpi=600 if publication else 300), "figure_composite_ABCD.png": fig_to_bytes(composite_fig, "png", dpi=600 if publication else 300), "panel_A_linear_map.svg": fig_to_bytes(linear_fig, "svg") if publication else None, "panel_B_circular_map.svg": fig_to_bytes(circular_fig, "svg") if publication else None, "panel_C_feature_distribution.svg": fig_to_bytes(dist_fig, "svg") if publication else None, "panel_D_feature_density.svg": fig_to_bytes(density_fig, "svg") if publication else None, "panel_A_linear_map.pdf": fig_to_bytes(linear_fig, "pdf") if publication else None, "panel_B_circular_map.pdf": fig_to_bytes(circular_fig, "pdf") if publication else None, "panel_C_feature_distribution.pdf": fig_to_bytes(dist_fig, "pdf") if publication else None, "panel_D_feature_density.pdf": fig_to_bytes(density_fig, "pdf") if publication else None, "figure_composite_ABCD.pdf": fig_to_bytes(composite_fig, "pdf") if publication else None, }
preview = { "linear_png": figure_pack["panel_A_linear_map.png"], "circular_png": figure_pack["panel_B_circular_map.png"], "dist_png": figure_pack["panel_C_feature_distribution.png"], "density_png": figure_pack["panel_D_feature_density.png"], "composite_png": figure_pack["figure_composite_ABCD.png"], }
for fig in [linear_fig, circular_fig, dist_fig, density_fig, composite_fig]: plt.close(fig)
return figure_pack, preview, dist_df, density_df
def run_analysis( primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa, gene_query, show_gc_content, show_gc_skew, window_size, run_mode, selected_record_id=None, min_feature_length=0,): 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, )
record_ids = [r.id for r in parsed.records] selected_record_id = selected_record_id or record_ids[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 [] if not record_ids: raise ValueError("No records were parsed from the input.")
chosen_record = selected_record_id if selected_record_id in record_ids else record_ids[0] record = next(r for r in parsed.records if r.id == chosen_record) full_df = parsed.feature_tables.get(record.id, pd.DataFrame()).copy()
available_types = sorted(full_df["feature_type"].dropna().unique().tolist()) if not full_df.empty else [] default_selected = [x for x in DEFAULT_FEATURES if x in available_types] or available_types filtered_df = filter_features(full_df, default_selected, gene_query, min_len=min_feature_length) 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'}) if not display_df.empty and "highlight" in display_df.columns: display_df["highlight"] = display_df["highlight"].map({True: "yes", False: "no"})
stats = build_summary_stats(record, full_df, filtered_df) stats_df = pd.DataFrame([stats]) dist_df = feature_distribution_table(full_df) density_df = build_density_df(record, filtered_df)
perf_notes = [] seq_len = len(record.seq) if len(filtered_df) > 2500: perf_notes.append('Large feature set detected: labels were reduced to speed up plotting.') if seq_len > 5_000_000: perf_notes.append('Large genome detected: rendering may still take time, but heavy steps were trimmed automatically.') figure_pack, preview, dist_df, density_df = prepare_figures( record=record, filtered_df=filtered_df, full_df=full_df, available_types=default_selected, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=window_size, run_mode=run_mode, )
circ_fig = draw_circular_map(record, filtered_df, show_gc_content, show_gc_skew, int(window_size)) lin_fig = draw_linear_map(record, filtered_df) if not filtered_df.empty else None dist_fig = draw_feature_distribution(dist_df) density_fig = draw_density_plot(density_df)
circ_png = fig_to_png(circ_fig) plt.close(circ_fig) lin_png = fig_to_png(lin_fig) if lin_fig is not None else None if lin_fig is not None: plt.close(lin_fig) dist_png = fig_to_png(dist_fig) plt.close(dist_fig) density_png = fig_to_png(density_fig) plt.close(density_fig)
summary_text = build_results_text(stats, dist_df, parsed.source_mode, parsed.notes) summary_zip = make_results_bundle(stats_df, display_df, { 'figure_A_linear_map.png': lin_png, 'figure_B_circular_map.png': circ_png, 'figure_C_feature_distribution.png': dist_png, 'figure_D_feature_density.png': density_png, }, summary_text)
st.session_state['parsed'] = parsed st.session_state['analysis_done'] = True st.session_state['analysis_error'] = '' st.session_state['record_ids'] = record_ids st.session_state['selected_record_id'] = selected_record_id st.session_state['full_df'] = full_df st.session_state['filtered_df'] = filtered_df st.session_state['display_df'] = display_df st.session_state['stats'] = stats st.session_state['notes'] = parsed.notes st.session_state['available_types'] = available_types st.session_state['selected_types_cache'] = default_selected st.session_state['circ_png'] = circ_png st.session_state['lin_png'] = lin_png st.session_state['dist_png'] = dist_png st.session_state['density_png'] = density_png st.session_state['stats_df'] = stats_df st.session_state['dist_df'] = dist_df st.session_state['density_df'] = density_df st.session_state['summary_text'] = summary_text st.session_state['table_csv'] = display_df.to_csv(index=False).encode('utf-8') st.session_state['summary_zip'] = summary_zip st.session_state['performance_note'] = ' '.join(perf_notes) summary_text = manuscript_summary_text(stats, dist_df, record.id, gene_query, run_mode) legend_html = build_legend_html(default_selected, include_highlight=(bool(filtered_df["highlight"].any()) if "highlight" in filtered_df.columns and not filtered_df.empty else False)) table_csv = display_df.to_csv(index=False).encode("utf-8") results_zip = make_results_bundle(figure_pack, display_df, display_df, stats_df, density_df, summary_text)
st.session_state["parsed"] = parsed st.session_state["analysis_done"] = True st.session_state["analysis_error"] = "" st.session_state["record_ids"] = record_ids st.session_state["selected_record_id"] = record.id st.session_state["full_df"] = full_df st.session_state["filtered_df"] = filtered_df st.session_state["display_df"] = display_df st.session_state["stats"] = stats st.session_state["notes"] = parsed.notes st.session_state["available_types"] = available_types st.session_state["selected_types_cache"] = default_selected st.session_state["stats_df"] = stats_df st.session_state["dist_df"] = dist_df st.session_state["density_df"] = density_df st.session_state["summary_text"] = summary_text st.session_state["figure_pack"] = {**figure_pack, **preview} st.session_state["table_csv"] = table_csv st.session_state["summary_zip"] = results_zip st.session_state["legend_html"] = legend_html st.session_state["run_mode_cache"] = run_mode
init_session_state()
st.markdown('<div class="main-title">🧬 Genome Visualization Tool Premium</div>', unsafe_allow_html=True)st.markdown('<div class="subtle">Faster and more stable for large uploads. Results stay visible until you click Clear results.</div>', unsafe_allow_html=True)st.markdown('<div class="main-title">🧬 Genome Visualization Tool — Ultra-Premium Journal Version</div>', unsafe_allow_html=True)st.markdown( '<div class="subtle">Fast preview is optimized for speed. Publication quality generates multi-panel journal-style figures with high-resolution PNG and vector-ready SVG/PDF exports.</div>', unsafe_allow_html=True,)
with st.sidebar: st.header('Input') input_mode = st.selectbox('Select input type', ['Universal / Auto-detect', 'GenBank', 'EMBL', 'FASTA', 'GFF/GTF + FASTA', 'BED + FASTA', 'Annotation table + FASTA', 'ZIP (auto-detect)'], index=0) if input_mode in {'Universal / Auto-detect', 'GenBank', 'EMBL', 'FASTA', 'ZIP (auto-detect)'}: primary_upload = st.file_uploader('Upload primary file', type=None, accept_multiple_files=False) st.header("Input") input_mode = st.selectbox( "Select input type", ["Universal / Auto-detect", "GenBank", "EMBL", "FASTA", "GFF/GTF + FASTA", "BED + FASTA", "Annotation table + FASTA", "ZIP (auto-detect)"], index=0, )
if input_mode in {"GenBank", "EMBL", "FASTA", "Universal / Auto-detect", "ZIP (auto-detect)"}: primary_upload = st.file_uploader("Upload primary input file", accept_multiple_files=False) secondary_upload = None else: primary_upload = st.file_uploader('Upload annotation/coordinate file', type=None, accept_multiple_files=False) secondary_upload = st.file_uploader('Upload matching FASTA file', type=None, accept_multiple_files=False) primary_upload = st.file_uploader("Upload annotation file", accept_multiple_files=False) secondary_upload = st.file_uploader("Upload matching FASTA file", accept_multiple_files=False)
st.header('Analysis settings') gene_query = st.text_input('Search / highlight', value='') infer_orfs = st.checkbox('Predict ORFs for FASTA-only input', value=False, help='Turn this on only for small FASTA files. It slows down large uploads.') min_orf_aa = st.slider('Minimum ORF length (aa)', min_value=30, max_value=300, value=120, step=10) min_feature_length = st.number_input('Minimum displayed feature length (bp)', min_value=0, max_value=100000, value=0, step=50) st.header("Run mode") run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1)
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=False) window_size = st.number_input('Window size', min_value=200, max_value=100000, value=2000, step=200) st.header("Analysis settings") gene_query = st.text_input("Search / highlight", value="") infer_orfs = st.checkbox("Predict ORFs for FASTA-only input", value=False) min_orf_aa = st.slider("Minimum ORF length (aa)", min_value=30, max_value=300, value=90, step=10) min_feature_length = st.number_input("Minimum displayed feature length (bp)", min_value=0, max_value=50000, value=0, step=50)
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("GC/skew window size", min_value=100, max_value=50000, value=1000, step=100)
run_button = st.button('Run visualization', type='primary', use_container_width=True) clear_button = st.button('Clear results', use_container_width=True) run_button = st.button("Run visualization", type="primary", use_container_width=True) clear_button = st.button("Clear results", use_container_width=True)
if clear_button: clear_results()1 unmodified line
if run_button: if primary_upload is None: st.error('Please upload the required input file.') st.error("Please upload the required input file.") st.stop() if input_mode in {'GFF/GTF + FASTA', 'BED + FASTA', 'Annotation table + FASTA'} and secondary_upload is None: st.error('Please upload both required files.') if input_mode in {"GFF/GTF + FASTA", "BED + FASTA", "Annotation table + FASTA"} and secondary_upload is None: st.error("Please upload both the annotation file and the FASTA file.") st.stop() st.session_state['run_in_progress'] = True st.session_state['analysis_error'] = '' try: with st.spinner('Parsing input and preparing figures...'): run_analysis(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa, gene_query, show_gc_content, show_gc_skew, window_size, min_feature_length) except Exception as exc: st.session_state['analysis_done'] = False st.session_state['analysis_error'] = str(exc) finally: st.session_state['run_in_progress'] = False
if st.session_state['analysis_error']: st.error(f"Run failed: {st.session_state['analysis_error']}")
if not st.session_state['analysis_done']: if st.session_state['run_in_progress']: st.info('Analysis is still running...') else: st.info('Upload your file(s) in any supported format, click Run visualization, and the figures and tables will remain visible until you click Clear results.') st.stop()
stats = st.session_state['stats']display_df = st.session_state['display_df']full_df = st.session_state['full_df']parsed = st.session_state['parsed'] with st.spinner("Parsing input and generating figure set..."): try: run_analysis( primary_upload=primary_upload, secondary_upload=secondary_upload, input_mode=input_mode, infer_orfs=infer_orfs, min_orf_aa=min_orf_aa, gene_query=gene_query, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=window_size, run_mode=run_mode, min_feature_length=min_feature_length, ) except Exception as exc: st.session_state["analysis_done"] = False st.session_state["analysis_error"] = str(exc)
if st.session_state["analysis_error"]: st.error(f"Input parsing or figure generation failed: {st.session_state['analysis_error']}")
if not st.session_state["analysis_done"]: st.info("Upload your file(s), choose Fast preview or Publication quality, then click Run visualization.") st.stop()
if parsed and len(st.session_state['record_ids']) > 1: new_record = st.selectbox('Select record / contig to display', st.session_state['record_ids'], index=st.session_state['record_ids'].index(st.session_state['selected_record_id'])) if new_record != st.session_state['selected_record_id']: primary_upload = None secondary_upload = None st.info('To switch record cleanly, rerun using the same file with the selected record after upload. This version keeps the current result stable.')parsed = st.session_state["parsed"]if parsed is not None and len(st.session_state["record_ids"]) > 1: selected_record = st.selectbox("Select record / contig", st.session_state["record_ids"], index=st.session_state["record_ids"].index(st.session_state["selected_record_id"])) rerun_record = st.button("Render selected record", use_container_width=False) if rerun_record: if primary_upload is None: st.warning("Please re-upload the file before re-rendering a different record.") else: with st.spinner("Rendering selected record..."): try: run_analysis( primary_upload=primary_upload, secondary_upload=secondary_upload, input_mode=input_mode, infer_orfs=infer_orfs, min_orf_aa=min_orf_aa, gene_query=gene_query, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=window_size, run_mode=run_mode, selected_record_id=selected_record, min_feature_length=min_feature_length, ) st.rerun() except Exception as exc: st.error(f"Re-rendering failed: {exc}")
stats = st.session_state["stats"]display_df = st.session_state["display_df"]figure_pack = st.session_state["figure_pack"]
c1, c2, c3, c4, c5 = st.columns(5)c1.metric('Genome length (bp)', f"{stats['Genome length (bp)']:,}")c2.metric('GC (%)', stats['GC (%)'])c3.metric('Displayed features', stats['Displayed features'])c4.metric('Total parsed features', stats['Total parsed features'])c5.metric('CDS', stats['CDS'])
if st.session_state['notes']: st.markdown('<div class="card"><b>Run notes</b></div>', unsafe_allow_html=True) for note in st.session_state['notes']: st.write(f'- {note}')
if st.session_state['performance_note']: st.warning(st.session_state['performance_note'])
legend_items = sorted(set(display_df['feature_type'].tolist()))[:12] if not display_df.empty else []if legend_items: handles = [Line2D([0], [0], color=FEATURE_COLORS.get(ft, FEATURE_COLORS['default']), lw=8, label=ft) for ft in legend_items] if 'yes' in display_df.get('highlight', pd.Series(dtype=str)).astype(str).tolist(): handles.append(Line2D([0], [0], color=FEATURE_COLORS['highlight'], lw=8, label='highlight')) fig_leg, ax_leg = plt.subplots(figsize=(12, 0.8)) ax_leg.axis('off') ax_leg.legend(handles=handles, ncol=min(6, len(handles)), loc='center', frameon=False) st.pyplot(fig_leg, use_container_width=True) plt.close(fig_leg)
tab1, tab2, tab3, tab4, tab5 = st.tabs(['Circular Map', 'Linear Map', 'Annotation Table', 'Statistics', 'Results Text'])c1.metric("Genome length (bp)", f"{stats['Genome length (bp)']:,}")c2.metric("GC (%)", stats["GC (%)"])c3.metric("Displayed features", stats["Displayed features"])c4.metric("Total parsed features", stats["Total parsed features"])c5.metric("CDS", stats["CDS"])
if st.session_state["notes"]: st.markdown('<div class="card">', unsafe_allow_html=True) st.markdown("**Run notes**") for note in st.session_state["notes"]: st.write(f"- {note}") st.markdown("</div>", unsafe_allow_html=True)
st.markdown(f'<div class="card"><b>Figure mode</b><br><span class="small-note">{st.session_state["run_mode_cache"]}</span></div>', unsafe_allow_html=True)
if st.session_state["legend_html"]: st.markdown('<div class="card"><b>Feature legend</b><br>' + st.session_state["legend_html"] + '</div>', unsafe_allow_html=True)
tab1, tab2, tab3, tab4, tab5 = st.tabs(["Composite Figure", "Individual Panels", "Annotation Table", "Statistics", "Manuscript Text"])
with tab1: st.image(st.session_state['circ_png'], use_container_width=True) st.subheader("Composite journal-style figure") st.image(figure_pack.get("composite_png"), use_container_width=True) a, b = st.columns(2) with a: st.download_button("Download composite PNG", data=figure_pack.get("figure_composite_ABCD.png"), file_name="figure_composite_ABCD.png", mime="image/png") with b: if figure_pack.get("figure_composite_ABCD.pdf") is not None: st.download_button("Download composite PDF", data=figure_pack.get("figure_composite_ABCD.pdf"), file_name="figure_composite_ABCD.pdf", mime="application/pdf")
with tab2: if st.session_state['lin_png'] is not None: st.image(st.session_state['lin_png'], use_container_width=True) else: st.warning('No linear map available for the current result.') st.subheader("Individual publication panels") subtabs = st.tabs(["Panel A", "Panel B", "Panel C", "Panel D"]) panel_meta = [ ("A", "linear_png", "panel_A_linear_map.png", "panel_A_linear_map.svg", "panel_A_linear_map.pdf"), ("B", "circular_png", "panel_B_circular_map.png", "panel_B_circular_map.svg", "panel_B_circular_map.pdf"), ("C", "dist_png", "panel_C_feature_distribution.png", "panel_C_feature_distribution.svg", "panel_C_feature_distribution.pdf"), ("D", "density_png", "panel_D_feature_density.png", "panel_D_feature_density.svg", "panel_D_feature_density.pdf"), ] for tab, meta in zip(subtabs, panel_meta): label, preview_key, png_name, svg_name, pdf_name = meta with tab: st.image(figure_pack.get(preview_key), use_container_width=True) x, y, z = st.columns(3) with x: st.download_button("PNG", data=figure_pack.get(png_name), file_name=png_name, mime="image/png", key=f"png_{label}") with y: if figure_pack.get(svg_name) is not None: st.download_button("SVG", data=figure_pack.get(svg_name), file_name=svg_name, mime="image/svg+xml", key=f"svg_{label}") with z: if figure_pack.get(pdf_name) is not None: st.download_button("PDF", data=figure_pack.get(pdf_name), file_name=pdf_name, mime="application/pdf", key=f"pdf_{label}")
with tab3: st.subheader("Annotation table") st.dataframe(display_df, use_container_width=True, height=420) st.download_button('Download annotation table (CSV)', data=st.session_state['table_csv'], file_name='feature_annotations.csv', mime='text/csv') st.dataframe(display_df, use_container_width=True, height=430) st.download_button("Download annotation table (CSV)", data=st.session_state["table_csv"], file_name="feature_annotations.csv", mime="text/csv")
with tab4: st.subheader("Genome statistics") left, right = st.columns(2) with left: st.markdown('**Summary statistics**') st.dataframe(st.session_state['stats_df'], use_container_width=True, height=220) st.markdown('**Feature distribution**') st.dataframe(st.session_state['dist_df'], use_container_width=True, height=220) st.markdown("**Summary statistics**") st.dataframe(st.session_state["stats_df"], use_container_width=True, height=220) with right: st.image(st.session_state['dist_png'], use_container_width=True) st.image(st.session_state['density_png'], use_container_width=True)with tab5: st.text_area('Manuscript-ready summary', value=st.session_state['summary_text'], height=180) st.download_button('Download result bundle (ZIP)', data=st.session_state['summary_zip'], file_name='genome_visualization_results.zip', mime='application/zip')
st.markdown('---')st.markdown('**Speed fixes in this revision**')st.markdown('- ORF prediction is off by default and auto-restricted for very large FASTA files.')st.markdown('- Heavy export formats were removed from the default run path; the app generates fast PNG outputs first.')st.markdown('- Dense labels are reduced automatically for large feature sets.')st.markdown('- State handling was tightened so the app does not fall back to the placeholder message after a successful run.')
st.markdown("**Feature type distribution**") st.dataframe(st.session_state["dist_df"], use_container_width=True, height=220) st.markdown("**Feature density table**") st.dataframe(st.session_state["density_df"], use_container_width=True, height=220) st.download_button("Download complete results bundle (ZIP)", data=st.session_state["summary_zip"], file_name="genome_visualization_results.zip", mime="application/zip")
with tab5: st.subheader("Manuscript-ready results text") st.text_area("Generated summary", value=st.session_state["summary_text"], height=180) st.download_button("Download summary text", data=st.session_state["summary_text"].encode("utf-8"), file_name="results_summary.txt", mime="text/plain")
st.markdown("---")st.markdown( """ **What this ultra-premium version adds** - Preview and publication-quality rendering modes - Multi-panel figure package (A–D) - High-resolution PNG export and vector-ready SVG/PDF export in publication mode - Clear feature-color legend, improved typography, and journal-style panel titles - Composite figure export for manuscript assembly - Persistent results after download until **Clear results** is clicked """)app.py+792-495