Spaces:
Build error
Build error
Update app.py
Browse files1 unmodified line234567789101183 unmodified lines95969798979910010110210310470 unmodified lines175176177178179180181182183184185186187188189190191192193194187 unmodified lines38238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155281 unmodified lines6346356366376386396404616416426436441 unmodified line6466476486496506516526536546556566576584706596606616626636644764774784794804816656666676686 unmodified lines6756766774946786794964974984995006806816826836846856866876886896906916926936946956966976986997005055065075087017027037047057067077087097107117127137147157167175197187197205225235247217227237247257267277287295275285297307317327337347357367377387397407415327427437447457465375385395405415427477487497503 unmodified lines754755756552553757758555759760761762451 unmodified lines121412151216101312171218121912201221122212231224122510171018122612271228122912301231123210211233123410231024102512351236123712381239124012411242124312441027124512461247124812 unmodified lines126112621263104610471264126512661267126810 unmodified lines12791280128110641282128312841285137 unmodified lines142314241425120814261427142814293 unmodified lines14331434143514361 unmodified lineimport osimport reimport zipfileimport gzipimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Tuplefrom typing import Dict, List, Tuple, Optional
import matplotlibmatplotlib.use("Agg")83 unmodified linesDEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "misc_feature", "repeat_region", "ORF"]FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas"}GB_EXTS = {".gb", ".gbk", ".genbank"}EMBL_EXTS = {".embl"}GFF_EXTS = {".gff", ".gff3"}GFF_EXTS = {".gff", ".gff3", ".gtf"}BED_EXTS = {".bed"}TEXT_EXTS = {".txt", ".csv", ".tsv", ".tab", ".tbl", ".ann"}DNA_COMPLEMENT = str.maketrans("ATGCatgcNn", "TACGtacgNn")
70 unmodified lines
def infer_file_kind(filename: str) -> str: ext = file_suffix(filename) if ext == ".gz": ext = os.path.splitext(os.path.splitext(filename)[0])[1].lower() or ext if ext in GB_EXTS: return "genbank" if ext in EMBL_EXTS: return "embl" if ext in FASTA_EXTS: return "fasta" if ext in GFF_EXTS: return "gff" if ext in BED_EXTS: return "bed" if ext in TEXT_EXTS: return "text" if ext == ".zip": return "zip" return "unknown"187 unmodified lines return list(SeqIO.parse(handle, "fasta"))
def maybe_decompress_bytes(data: bytes, filename: str = "") -> bytes: if (filename or "").lower().endswith(".gz"): try: return gzip.decompress(data) except Exception: return data return data
def parse_embl_bytes(data: bytes): handle = io.StringIO(data.decode("utf-8", errors="replace")) return list(SeqIO.parse(handle, "embl"))
def parse_any_seq_records(data: bytes, filename: str = "") -> Tuple[Optional[str], List]: payload = maybe_decompress_bytes(data, filename) ordered = [] detected = infer_file_kind(filename) if detected in {"genbank", "embl", "fasta"}: ordered.append(detected) for fmt in ["genbank", "embl", "fasta"]: if fmt not in ordered: ordered.append(fmt) for fmt in ordered: try: if fmt == "genbank": recs = parse_genbank_bytes(payload) elif fmt == "embl": recs = parse_embl_bytes(payload) else: recs = parse_fasta_bytes(payload) if recs: return fmt, recs except Exception: pass return None, []
def bed_to_tables(bed_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: records = parse_fasta_bytes(maybe_decompress_bytes(fasta_bytes, "input.fasta")) if not records: raise ValueError("No FASTA records found for BED-guided visualization.") record_map = {r.id: r for r in records} alt_map = {r.id.split()[0]: r for r in records} tables = {r.id: [] for r in records} text = maybe_decompress_bytes(bed_bytes, "input.bed").decode("utf-8", errors="replace") for line in text.splitlines(): if not line.strip() or line.startswith("#"): continue parts = line.split(" ") if " " in line else re.split(r"\s+", line.strip()) if len(parts) < 3: continue rec = record_map.get(parts[0]) or alt_map.get(parts[0]) if rec is None: continue try: start, end = int(float(parts[1])), int(float(parts[2])) except Exception: continue label = parts[3] if len(parts) > 3 else "BED_feature" strand_token = parts[5] if len(parts) > 5 else "." strand = 1 if strand_token == "+" else -1 if strand_token == "-" else 0 tables[rec.id].append({ "record_id": rec.id, "feature_type": "BED_feature", "label": normalize_text(label), "start": max(0, start), "end": max(start, end), "length": max(0, end-start), "strand": strand, "locus_tag": "", "gene": label, "product": "BED interval", "note": "Imported from BED", "source": "bed" }) 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 annotation_table_to_tables(table_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: records = parse_fasta_bytes(maybe_decompress_bytes(fasta_bytes, "input.fasta")) if not records: raise ValueError("No FASTA records found for table-based annotation.") raw = maybe_decompress_bytes(table_bytes, "input.txt").decode("utf-8", errors="replace") sep = " " if " " in raw else None df = pd.read_csv(io.StringIO(raw), sep=sep, engine="python") cols = {str(c).lower().strip(): c for c in df.columns} seq_col = cols.get("record_id") or cols.get("seqid") or cols.get("chrom") or cols.get("contig") or cols.get("sequence") start_col = cols.get("start") end_col = cols.get("end") or cols.get("stop") type_col = cols.get("feature_type") or cols.get("type") or cols.get("feature") label_col = cols.get("label") or cols.get("gene") or cols.get("name") or cols.get("id") strand_col = cols.get("strand") if not start_col or not end_col: raise ValueError("Table input requires at least start and end columns, plus a FASTA file.") record_map = {r.id: r for r in records} alt_map = {r.id.split()[0]: r for r in records} rows={r.id: [] for r in records} for _, row in df.iterrows(): seqid = str(row[seq_col]) if seq_col and pd.notna(row[seq_col]) else records[0].id rec = record_map.get(seqid) or alt_map.get(seqid) or records[0] try: start, end = int(row[start_col]), int(row[end_col]) except Exception: continue sval = str(row[strand_col]).strip() if strand_col and pd.notna(row[strand_col]) else "." strand = 1 if sval == "+" else -1 if sval == "-" else 0 ftype = str(row[type_col]) if type_col and pd.notna(row[type_col]) else "table_feature" label = str(row[label_col]) if label_col and pd.notna(row[label_col]) else ftype rows[rec.id].append({ "record_id": rec.id, "feature_type": ftype, "label": normalize_text(label), "start": max(0, start), "end": max(start, end), "length": max(0, end-start), "strand": strand, "locus_tag": "", "gene": normalize_text(label), "product": ftype, "note": "Imported from annotation table", "source": "table" }) out={} for rec in records: dfr=pd.DataFrame(rows.get(rec.id, [])) if dfr.empty: dfr = pd.DataFrame(columns=["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"]) out[rec.id]=dfr.sort_values(["start","end"], kind="stable").reset_index(drop=True) return records, out
def parse_universal_inputs(primary_upload, secondary_upload, infer_orfs: bool, min_orf_aa: int) -> ParsedGenome: primary_name = getattr(primary_upload, "name", "input") primary_data = primary_upload.getvalue() kind = infer_file_kind(primary_name) if kind == "zip": return parse_input_bundle(primary_upload, secondary_upload, "ZIP (auto-detect)", infer_orfs, min_orf_aa)
seq_fmt, seq_records = parse_any_seq_records(primary_data, primary_name) if seq_records: if seq_fmt in {"genbank", "embl"}: return ParsedGenome(records=seq_records, feature_tables={r.id: record_to_feature_table(r) for r in seq_records}, source_mode=seq_fmt, notes=[f"Auto-detected {seq_fmt.upper()} annotated sequence input."]) tables={} for r in seq_records: empty_df = 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]=empty_df else: tables[r.id]=empty_df return ParsedGenome(records=seq_records, feature_tables=tables, source_mode=seq_fmt or "fasta", notes=[f"Auto-detected {seq_fmt.upper()} sequence input." + (" ORF prediction enabled." if infer_orfs else " No native annotation available.")])
if secondary_upload is not None: sec_name = getattr(secondary_upload, "name", "input2") sec_data = secondary_upload.getvalue() sec_fmt, sec_records = parse_any_seq_records(sec_data, sec_name) if sec_records: if kind == "gff": records, tables = gff_and_fasta_to_tables(maybe_decompress_bytes(primary_data, primary_name), maybe_decompress_bytes(sec_data, sec_name)) return ParsedGenome(records=records, feature_tables=tables, source_mode="gff_fasta", notes=[f"Auto-detected {primary_name} as GFF/GTF annotation with {sec_name} sequence."]) if kind == "bed": records, tables = bed_to_tables(maybe_decompress_bytes(primary_data, primary_name), maybe_decompress_bytes(sec_data, sec_name)) return ParsedGenome(records=records, feature_tables=tables, source_mode="bed_fasta", notes=[f"Auto-detected {primary_name} as BED annotation with {sec_name} sequence."]) if kind in {"text", "unknown"}: records, tables = annotation_table_to_tables(maybe_decompress_bytes(primary_data, primary_name), maybe_decompress_bytes(sec_data, sec_name)) return ParsedGenome(records=records, feature_tables=tables, source_mode="table_fasta", notes=[f"Auto-detected {primary_name} as a table-based annotation file with {sec_name} sequence."])
raise ValueError("Could not auto-detect a supported sequence/annotation combination. Supported inputs include GenBank, EMBL, FASTA, GFF/GFF3/GTF + FASTA, BED + FASTA, ZIP bundles, and CSV/TSV/TXT annotation tables + FASTA. Gzip-compressed versions are also accepted.")
def build_gff_db(gff_text: str, workdir: str): if gffutils is None: raise RuntimeError("gffutils is not installed.")81 unmodified linesdef parse_input_bundle(primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int) -> ParsedGenome: notes = []
if input_mode == "Universal / Auto-detect": return parse_universal_inputs(primary_upload, secondary_upload, infer_orfs, min_orf_aa)
if input_mode == "GenBank": data = primary_upload.getvalue() data = maybe_decompress_bytes(primary_upload.getvalue(), getattr(primary_upload, "name", "input.gb")) records = parse_genbank_bytes(data) if not records: raise ValueError("No GenBank records were found.")1 unmodified line notes.append("Parsed annotated GenBank input.") return ParsedGenome(records=records, feature_tables=tables, source_mode="genbank", notes=notes)
if input_mode == "EMBL": data = maybe_decompress_bytes(primary_upload.getvalue(), getattr(primary_upload, "name", "input.embl")) records = parse_embl_bytes(data) if not records: raise ValueError("No EMBL records were found.") tables = {r.id: record_to_feature_table(r) for r in records} notes.append("Parsed annotated EMBL input.") return ParsedGenome(records=records, feature_tables=tables, source_mode="embl", notes=notes)
if input_mode == "FASTA": data = primary_upload.getvalue() data = maybe_decompress_bytes(primary_upload.getvalue(), getattr(primary_upload, "name", "input.fasta")) records = parse_fasta_bytes(data) if not records: raise ValueError("No FASTA records were found.") tables = {} for r in records: empty_df = pd.DataFrame( columns=[ "record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source" ] ) empty_df = 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:6 unmodified lines notes.append("FASTA-only input." + (" ORF prediction enabled." if infer_orfs else " No native annotation available.")) return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes)
if input_mode == "GFF + FASTA": if input_mode == "GFF/GTF + FASTA": if secondary_upload is None: raise ValueError("Both GFF/GFF3 and FASTA files are required.") gff_bytes = primary_upload.getvalue() fasta_bytes = secondary_upload.getvalue() records, tables = gff_and_fasta_to_tables(gff_bytes, fasta_bytes) notes.append("Parsed GFF/GFF3 annotation with FASTA sequence.") raise ValueError("Both GFF/GTF and FASTA files are required.") records, tables = gff_and_fasta_to_tables(maybe_decompress_bytes(primary_upload.getvalue(), getattr(primary_upload, "name", "input.gff")), maybe_decompress_bytes(secondary_upload.getvalue(), getattr(secondary_upload, "name", "input.fasta"))) notes.append("Parsed GFF/GFF3/GTF annotation with FASTA sequence.") return ParsedGenome(records=records, feature_tables=tables, source_mode="gff_fasta", notes=notes)
if input_mode == "BED + FASTA": if secondary_upload is None: raise ValueError("Both BED and FASTA files are required.") records, tables = bed_to_tables(maybe_decompress_bytes(primary_upload.getvalue(), getattr(primary_upload, "name", "input.bed")), maybe_decompress_bytes(secondary_upload.getvalue(), getattr(secondary_upload, "name", "input.fasta"))) notes.append("Parsed BED annotation with FASTA sequence.") return ParsedGenome(records=records, feature_tables=tables, source_mode="bed_fasta", notes=notes)
if input_mode == "Annotation table + FASTA": if secondary_upload is None: raise ValueError("Both the annotation table and FASTA file are required.") records, tables = annotation_table_to_tables(maybe_decompress_bytes(primary_upload.getvalue(), getattr(primary_upload, "name", "input.tsv")), maybe_decompress_bytes(secondary_upload.getvalue(), getattr(secondary_upload, "name", "input.fasta"))) notes.append("Parsed delimited annotation table with FASTA sequence.") return ParsedGenome(records=records, feature_tables=tables, source_mode="table_fasta", notes=notes)
if input_mode == "ZIP (auto-detect)": files = parse_uploaded_zip(primary_upload) gb_name = None fasta_name = None gff_name = None
gb_name = embl_name = fasta_name = gff_name = bed_name = table_name = None for name in files: kind = infer_file_kind(name) if kind == "genbank" and gb_name is None: gb_name = name elif kind == "embl" and embl_name is None: embl_name = name elif kind == "fasta" and fasta_name is None: fasta_name = name elif kind == "gff" and gff_name is None: gff_name = name elif kind == "bed" and bed_name is None: bed_name = name elif kind == "text" and table_name is None: table_name = name
if gb_name: records = parse_genbank_bytes(files[gb_name]) records = parse_genbank_bytes(maybe_decompress_bytes(files[gb_name], 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) return ParsedGenome(records=records, feature_tables={r.id: record_to_feature_table(r) for r in records}, source_mode="genbank", notes=[f"ZIP detected GenBank input: {gb_name}"])
if embl_name: records = parse_embl_bytes(maybe_decompress_bytes(files[embl_name], embl_name)) if not records: raise ValueError("ZIP contained an EMBL file but no records were parsed.") return ParsedGenome(records=records, feature_tables={r.id: record_to_feature_table(r) for r in records}, source_mode="embl", notes=[f"ZIP detected EMBL input: {embl_name}"])
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) records, tables = gff_and_fasta_to_tables(maybe_decompress_bytes(files[gff_name], gff_name), maybe_decompress_bytes(files[fasta_name], fasta_name)) return ParsedGenome(records=records, feature_tables=tables, source_mode="gff_fasta", notes=[f"ZIP detected GFF/GTF + FASTA input: {gff_name} + {fasta_name}"])
if bed_name and fasta_name: records, tables = bed_to_tables(maybe_decompress_bytes(files[bed_name], bed_name), maybe_decompress_bytes(files[fasta_name], fasta_name)) return ParsedGenome(records=records, feature_tables=tables, source_mode="bed_fasta", notes=[f"ZIP detected BED + FASTA input: {bed_name} + {fasta_name}"])
if table_name and fasta_name: records, tables = annotation_table_to_tables(maybe_decompress_bytes(files[table_name], table_name), maybe_decompress_bytes(files[fasta_name], fasta_name)) return ParsedGenome(records=records, feature_tables=tables, source_mode="table_fasta", notes=[f"ZIP detected annotation table + FASTA input: {table_name} + {fasta_name}"])
if fasta_name: records = parse_fasta_bytes(files[fasta_name]) records = parse_fasta_bytes(maybe_decompress_bytes(files[fasta_name], fasta_name)) if not records: raise ValueError("ZIP contained a FASTA file but no records were parsed.") tables = {} for r in records: empty_df = pd.DataFrame( columns=[ "record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source" ] ) empty_df = 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:3 unmodified lines tables[r.id] = empty_df else: tables[r.id] = empty_df notes.append(f"ZIP detected FASTA-only input: {fasta_name}") return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=notes) return ParsedGenome(records=records, feature_tables=tables, source_mode="fasta", notes=[f"ZIP detected FASTA-only input: {fasta_name}"])
raise ValueError("ZIP file did not contain a supported GenBank, FASTA, or GFF+FASTA combination.") raise ValueError("ZIP file did not contain a supported GenBank, EMBL, FASTA, GFF/GTF + FASTA, BED + FASTA, or annotation table + FASTA combination.")
raise ValueError("Unsupported input mode selected.")
451 unmodified lines st.header("Input") input_mode = st.selectbox( "Select input type", ["GenBank", "FASTA", "GFF + FASTA", "ZIP (auto-detect)"], ["Universal / Auto-detect", "GenBank", "EMBL", "FASTA", "GFF/GTF + FASTA", "BED + FASTA", "Annotation table + FASTA", "ZIP (auto-detect)"], index=0, )
universal_help = "Supported: GenBank, EMBL, FASTA, GFF/GFF3/GTF + FASTA, BED + FASTA, CSV/TSV/TXT annotation table + FASTA, ZIP bundles, and .gz-compressed versions."
if input_mode == "Universal / Auto-detect": primary_upload = st.file_uploader("Upload primary file", type=None, accept_multiple_files=False, help=universal_help) secondary_upload = st.file_uploader("Optional secondary file", type=None, accept_multiple_files=False, help="Use this for annotation + sequence pairs such as GFF/GTF + FASTA, BED + FASTA, or table + FASTA.") if input_mode == "GenBank": primary_upload = st.file_uploader("Upload GenBank file", type=["gb", "gbk", "genbank"], accept_multiple_files=False) elif input_mode == "GenBank": primary_upload = st.file_uploader("Upload GenBank file", type=["gb", "gbk", "genbank", "gz"], accept_multiple_files=False) secondary_upload = None elif input_mode == "EMBL": primary_upload = st.file_uploader("Upload EMBL file", type=["embl", "gz"], accept_multiple_files=False) secondary_upload = None elif input_mode == "FASTA": primary_upload = st.file_uploader("Upload FASTA file", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=False) primary_upload = st.file_uploader("Upload FASTA file", type=["fa", "fasta", "fna", "fas", "gz"], accept_multiple_files=False) 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) secondary_upload = st.file_uploader("Upload matching FASTA file", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=False) elif input_mode == "GFF/GTF + FASTA": primary_upload = st.file_uploader("Upload GFF/GFF3/GTF annotation file", type=["gff", "gff3", "gtf", "gz"], accept_multiple_files=False) secondary_upload = st.file_uploader("Upload matching FASTA file", type=["fa", "fasta", "fna", "fas", "gz"], accept_multiple_files=False) elif input_mode == "BED + FASTA": primary_upload = st.file_uploader("Upload BED annotation file", type=["bed", "gz"], accept_multiple_files=False) secondary_upload = st.file_uploader("Upload matching FASTA file", type=["fa", "fasta", "fna", "fas", "gz"], accept_multiple_files=False) elif input_mode == "Annotation table + FASTA": primary_upload = st.file_uploader("Upload annotation table", type=["txt", "csv", "tsv", "tab", "tbl", "ann", "gz"], accept_multiple_files=False, help="Required columns: start and end. Optional columns: record_id/seqid, feature_type/type, label/gene/name, and strand.") secondary_upload = st.file_uploader("Upload matching FASTA file", type=["fa", "fasta", "fna", "fas", "gz"], accept_multiple_files=False) else: primary_upload = st.file_uploader("Upload ZIP archive", type=["zip"], accept_multiple_files=False) primary_upload = st.file_uploader("Upload ZIP archive", type=["zip"], accept_multiple_files=False, help=universal_help) secondary_upload = None
st.header("Parsing settings")12 unmodified lines 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.") 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()
with st.spinner("Parsing input and preparing premium visualization..."):10 unmodified lines st.stop()
if not st.session_state["analysis_done"]: st.info("Upload your file(s), click Run visualization, and the figures and tables will remain visible until you click Clear results.") 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()
parsed = st.session_state["parsed"]137 unmodified linesst.markdown("---")st.markdown( """ **Included in this version** **Premium improvements included in this version** - High-resolution figure export suitable for journal submission (PNG, SVG, PDF) - Clear panel labels (A–D), figure captions, legends, and axis titles - Record/contig selection after parsing multi-record files3 unmodified lines - Persistent results using `st.session_state` so downloads do not clear outputs """)
app.py+268-49