Spaces:
Build error
Build error
Update app.py
Browse files1231 unmodified line5678910111213149 unmodified lines242526272829303132333435363738394041424344454647484950515253545 unmodified lines60616263646566676869707172737475767778798081828384858687881 unmodified line909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371389 unmodified lines1481491501511521531541551561571581591601611621631641651 unmodified line1671681691701711721731741751761 unmodified line1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282291 unmodified line2312322332342352362371 unmodified line2392402412422432442452462472482492502512522532542552562572582592602612 unmodified lines2642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433442 unmodified lines34734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940011 unmodified lines4124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595602 unmodified lines5635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987991 unmodified line801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901import ioimport osimport re1 unmodified lineimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Tuple, Optionalimport matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as np9 unmodified linesexcept Exception:gffutils = Nonest.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)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'}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 linesdef 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': '',}for k, v in defaults.items():if k not in st.session_state:1 unmodified linedef clear_results():keys = list(st.session_state.keys())for k in keys:if k.startswith('_'):continuedel st.session_state[k]init_session_state()def normalize_text(value: str) -> str:return re.sub(r'\s+', ' ', str(value or '')).strip()def file_suffix(name: str) -> str:n = str(name).lower()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)return name, datadef infer_file_kind(filename: str) -> str:ext = file_suffix(filename)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 TABLE_EXTS:return 'table'if str(filename).lower().endswith('.zip'):return 'zip'return 'unknown'def get_feature_bounds(feature):9 unmodified linesdef get_feature_label(feature):qualifiers = getattr(feature, 'qualifiers', {}) or {}for key in ['gene', 'locus_tag', 'product', 'note', 'ID', 'Name']:if key in qualifiers and qualifiers[key]:return str(qualifiers[key][0])return getattr(feature, 'type', 'feature')def compute_gc_percent(sequence: str) -> float:seq = str(sequence).upper()if not seq:return 0.0gc = seq.count('G') + seq.count('C')return (gc / len(seq)) * 100.01 unmodified lineseq = 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))return positions, values1 unmodified lineseq = 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')denom = g + cvalues.append((g - c) / denom if denom else 0.0)positions.append(i + len(w) // 2)return positions, valuesdef record_to_feature_table(record) -> pd.DataFrame:rows = []for feature in getattr(record, 'features', []):try:start, end, strand = get_feature_bounds(feature)qualifiers = getattr(feature, 'qualifiers', {}) or {}rows.append({'record_id': record.id,'feature_type': getattr(feature, 'type', 'feature'),'label': get_feature_label(feature),'start': int(start),'end': int(end),'length': max(0, int(end) - int(start)),'strand': int(strand),'locus_tag': '; '.join(qualifiers.get('locus_tag', [])),'gene': '; '.join(qualifiers.get('gene', [])),'product': '; '.join(qualifiers.get('product', [])),'note': '; '.join(qualifiers.get('note', [])),'source': 'annotation',})except Exception:continuecols = ['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)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:seq = str(sequence).upper()seq_len = len(seq)stops, start_codons = {'TAA', 'TAG', 'TGA'}, {'ATG', 'GTG', 'TTG'}rows = []def scan_strand(s: str, strand_value: int):nonlocal rowsfor frame in range(3):i = frame1 unmodified lineif len(rows) >= max_orfs:returncodon = s[i:i + 3]if codon in start_codons:j = i + 3while j <= len(s) - 3:stop = s[j:j + 3]1 unmodified linent_len = (j + 3) - iaa_len = nt_len // 3if aa_len >= min_aa:if strand_value == 1:start, end = i, j + 3else:start = seq_len - (j + 3)end = seq_len - irows.append({'feature_type': 'ORF','label': f'ORF_{strand_value}_{start+1}_{end}','start': int(start),'end': int(end),'length': int(end - start),'strand': int(strand_value),'locus_tag': '','gene': '','product': f'Predicted ORF ({aa_len} aa)','note': 'FASTA-only inferred ORF','source': 'orf_prediction',})i = j + 3break2 unmodified linesscan_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)def parse_text_records(data: bytes, fmt: str):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'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')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')if not records:raise ValueError('No FASTA records found for annotation table pairing.')record_ids = {r.id for r in records}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'])continueout = 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',})out['length'] = (out['end'] - out['start']).clip(lower=0)tables[r.id] = out.sort_values(['start','end'], kind='stable').reset_index(drop=True)return records, tablesdef build_gff_db(gff_text: str, workdir: str):if gffutils is None:raise RuntimeError('gffutils is not installed.')gff_path = os.path.join(workdir, 'input.gff3')with open(gff_path, 'w', encoding='utf-8') as f:f.write(gff_text)db_path = os.path.join(workdir, 'temp_gff.db')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')if not records: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 linesif record is None:continueattrs = feature.attributes or {}label = attrs.get('Name', [''])[0] or attrs.get('gene', [''])[0] or attrs.get('locus_tag', [''])[0] or attrs.get('ID', [''])[0] or feature.featuretypestrand = 1 if feature.strand == '+' else -1 if feature.strand == '-' else 0tables[record.id].append({'record_id': record.id,'feature_type': str(feature.featuretype),'label': normalize_text(label),'start': max(0, int(feature.start) - 1),'end': int(feature.end),'length': max(0, int(feature.end) - (int(feature.start) - 1)),'strand': strand,'locus_tag': '; '.join(attrs.get('locus_tag', [])),'gene': '; '.join(attrs.get('gene', [])),'product': '; '.join(attrs.get('product', [])),'note': '; '.join(attrs.get('Note', [])),'source': 'gff',})out = {}for rec in records:out[rec.id] = pd.DataFrame(tables.get(rec.id, [])).sort_values(['start','end'], kind='stable').reset_index(drop=True)return records, outdef bed_and_fasta_to_tables(bed_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: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)df = df.iloc[:, :min(6, df.shape[1])]df.columns = cols[:df.shape[1]]tables = {}for r in records:sdf = df[df['seqid'].astype(str) == r.id].copy() if 'seqid' in df.columns else pd.DataFrame()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']]return records, tables11 unmodified linesdef 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)':files = parse_uploaded_zip(primary_upload)normalized = {}for name, data in files.items():n2, d2 = maybe_decompress(name, data)normalized[n2] = d2names = 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)tables = {r.id: record_to_feature_table(r) for r in records}notes.append(f'ZIP detected {fmt.upper()} input: {primary_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)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)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)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)if fasta_name:records = parse_text_records(normalized[fasta_name], 'fasta')tables = {}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'])if not orf_df.empty:orf_df.insert(0, 'record_id', r.id)tables[r.id] = orf_dfnotes.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.')pname, pdata = maybe_decompress(primary_upload.name, primary_upload.getvalue())kind = infer_file_kind(pname) if input_mode == 'Universal / Auto-detect' else Noneif 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.')tables = {r.id: record_to_feature_table(r) for r in records}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 not records:raise ValueError('No FASTA records were found.')tables = {}long_input = sum(len(str(r.seq)) for r in records) > 3_000_000do_orf = infer_orfs and not long_inputfor 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'])if not orf_df.empty:orf_df.insert(0, 'record_id', r.id)tables[r.id] = orf_dfnotes.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)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.')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)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.')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)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.')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)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:filtered = df.copy()if selected_types: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()if filtered.empty:filtered['highlight'] = Falsereturn filteredquery = normalize_text(query).lower()if query:mask = (filtered['label'].fillna('').str.lower().str.contains(query, na=False) |filtered['gene'].fillna('').str.lower().str.contains(query, na=False) |filtered['locus_tag'].fillna('').str.lower().str.contains(query, na=False) |filtered['product'].fillna('').str.lower().str.contains(query, na=False) |filtered['note'].fillna('').str.lower().str.contains(query, na=False))filtered['highlight'] = maskelse:filtered['highlight'] = Falseif len(filtered) > max_features: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:features = []do_labels = len(filtered_df) <= annotate_limitfor _, 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 Noneif label and len(label) > 24:label = label[:21] + '...'strand = int(row['strand']) if row['strand'] in (-1, 1) else 0features.append(GraphicFeature(start=int(row['start']), end=int(row['end']), strand=strand, color=color, label=label))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.0fig, 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)plt.tight_layout()return fig2 unmodified linesseq_len = len(record.seq)circos = Circos({record.id: seq_len}, space=2)sector = circos.sectors[0]tick_track = sector.add_track((88, 100))tick_track.axis(fc='#f7f7f7', ec='black', lw=0.4)tick_interval = max(1000, seq_len // 10) if seq_len <= 100000 else max(5000, seq_len // 12)tick_track.xticks_by_interval(tick_interval, label_formatter=lambda v: f'{int(v/1000)} kb' if v >= 1000 else str(v), show_bottom_line=True, 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)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)inner_bottom = 10if show_gc_content:gc_track = sector.add_track((26, 40))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)inner_bottom = 24if show_gc_skew:skew_track = sector.add_track((inner_bottom, inner_bottom + 12))skew_track.axis(fc='#f8f8f8', ec='black', lw=0.25)positions, skews = gc_skew_windows(record.seq, window_size)if skews:vmax = max(abs(min(skews)), abs(max(skews)), 0.1)skew_track.line(positions, skews, vmin=-vmax, vmax=vmax)skew_track.fill_between(positions, skews, y2=0, vmin=-vmax, vmax=vmax, alpha=0.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')return figdef draw_feature_distribution(dist_df: pd.DataFrame):fig, ax = plt.subplots(figsize=(9, 4.8))if dist_df.empty: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)plt.tight_layout()return figdef 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'])seq_len = len(record.seq)edges = np.linspace(0, seq_len, bins + 1, dtype=int)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))if density_df.empty: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']) / 2ax.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')plt.tight_layout()return figdef fig_to_png(fig, dpi: int = 220) -> bytes:buf = io.BytesIO()fig.savefig(buf, format='png', dpi=dpi, bbox_inches='tight')buf.seek(0)return buf.getvalue()def build_summary_stats(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame) -> Dict[str, object]:counts = full_df['feature_type'].value_counts().to_dict() if not full_df.empty else {}return {'Record ID': record.id,'Description': normalize_text(getattr(record, 'description', '')),'Genome length (bp)': len(record.seq),'GC (%)': round(compute_gc_percent(record.seq), 2),'Displayed features': len(filtered_df),'Total parsed features': len(full_df),'CDS': 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_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'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 ''))def make_results_bundle(stats_df, feature_df, figs: Dict[str, bytes], results_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)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)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 []default_selected = [x for x in DEFAULT_FEATURES if x in available_types] or available_typesfiltered_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'})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.')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 Nonedist_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 Noneif 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'] = parsedst.session_state['analysis_done'] = Truest.session_state['analysis_error'] = ''st.session_state['record_ids'] = record_idsst.session_state['selected_record_id'] = selected_record_idst.session_state['full_df'] = full_dfst.session_state['filtered_df'] = filtered_dfst.session_state['display_df'] = display_dfst.session_state['stats'] = statsst.session_state['notes'] = parsed.notesst.session_state['available_types'] = available_typesst.session_state['selected_types_cache'] = default_selectedst.session_state['circ_png'] = circ_pngst.session_state['lin_png'] = lin_pngst.session_state['dist_png'] = dist_pngst.session_state['density_png'] = density_pngst.session_state['stats_df'] = stats_dfst.session_state['dist_df'] = dist_dfst.session_state['density_df'] = density_dfst.session_state['summary_text'] = summary_textst.session_state['table_csv'] = display_df.to_csv(index=False).encode('utf-8')st.session_state['summary_zip'] = summary_zipst.session_state['performance_note'] = ' '.join(perf_notes)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)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)secondary_upload = Noneelse: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)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('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)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 lineif run_button:if primary_upload is None: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.')st.stop()st.session_state['run_in_progress'] = Truest.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'] = Falsest.session_state['analysis_error'] = str(exc)finally:st.session_state['run_in_progress'] = Falseif 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']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 = Nonesecondary_upload = Nonest.info('To switch record cleanly, rerun using the same file with the selected record after upload. This version keeps the current result stable.')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'])with tab1:st.image(st.session_state['circ_png'], use_container_width=True)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.')with tab3: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')with tab4: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)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.')12341 unmodified line67891011121314159 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697985 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301 unmodified line1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761779 unmodified lines1871881891901911921931941951961971981992002012022032041 unmodified line2062072082092102112122132142151 unmodified line2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682691 unmodified line2712722732742752762771 unmodified line2792802812822832842852862872882892902912922932942952962972982993003012 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973982 unmodified lines40140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946011 unmodified lines4724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616622 unmodified lines6656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411 unmodified line104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198import ioimport osimport re1 unmodified lineimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Tupleimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as np9 unmodified linesexcept Exception:gffutils = None# =========================# 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": "#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")@dataclassclass ParsedGenome:5 unmodified linesdef init_session_state():defaults = {"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 linedef clear_results():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()def file_suffix(name: str) -> str:n = str(name).lower()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"):return os.path.splitext(name)[0], gzip.decompress(data)return name, datadef infer_file_kind(filename: str) -> str:ext = file_suffix(filename)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 TABLE_EXTS:return "table"if str(filename).lower().endswith(".zip"):return "zip"return "unknown"def get_feature_bounds(feature):9 unmodified linesdef get_feature_label(feature):qualifiers = getattr(feature, "qualifiers", {}) or {}for key in ["gene", "locus_tag", "product", "note", "ID", "Name"]:if key in qualifiers and qualifiers[key]:return str(qualifiers[key][0])return getattr(feature, "type", "feature")def compute_gc_percent(sequence: str) -> float:seq = str(sequence).upper()if not seq:return 0.0gc = seq.count("G") + seq.count("C")return (gc / len(seq)) * 100.01 unmodified lineseq = str(sequence).upper()positions, values = [], []for i in range(0, len(seq), window_size):window = seq[i:i + window_size]if window:positions.append(i + len(window) // 2)values.append(compute_gc_percent(window))return positions, values1 unmodified lineseq = str(sequence).upper()positions, values = [], []for i in range(0, len(seq), window_size):window = seq[i:i + window_size]g = window.count("G")c = window.count("C")denom = g + cpositions.append(i + len(window) // 2)values.append((g - c) / denom if denom else 0.0)return positions, valuesdef record_to_feature_table(record) -> pd.DataFrame:rows = []for feature in getattr(record, "features", []):try:start, end, strand = get_feature_bounds(feature)qualifiers = getattr(feature, "qualifiers", {}) or {}rows.append({"record_id": record.id,"feature_type": getattr(feature, "type", "feature"),"label": get_feature_label(feature),"start": int(start),"end": int(end),"length": max(0, int(end) - int(start)),"strand": int(strand),"locus_tag": "; ".join(qualifiers.get("locus_tag", [])),"gene": "; ".join(qualifiers.get("gene", [])),"product": "; ".join(qualifiers.get("product", [])),"note": "; ".join(qualifiers.get("note", [])),"source": "annotation",})except Exception:continuecols = ["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 = 2500) -> pd.DataFrame:seq = str(sequence).upper()seq_len = len(seq)stops = {"TAA", "TAG", "TGA"}starts = {"ATG", "GTG", "TTG"}rows = []def scan_strand(s: str, strand_val: int):nonlocal rowsfor frame in range(3):i = frame1 unmodified lineif len(rows) >= max_orfs:returncodon = s[i:i + 3]if codon in starts:j = i + 3while j <= len(s) - 3:stop = s[j:j + 3]1 unmodified linent_len = (j + 3) - iaa_len = nt_len // 3if aa_len >= min_aa:if strand_val == 1:start, end = i, j + 3else:start = seq_len - (j + 3)end = seq_len - irows.append({"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 + 3break2 unmodified linesscan_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)def parse_text_records(data: bytes, fmt: str):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")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")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")if not 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"])continueout = 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",})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, tablesdef build_gff_db(gff_text: str, workdir: str):if gffutils is None:raise RuntimeError("gffutils is not installed.")gff_path = os.path.join(workdir, "input.gff3")with open(gff_path, "w", encoding="utf-8") as f:f.write(gff_text)db_path = os.path.join(workdir, "temp_gff.db")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")if not records: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 linesif record is None:continueattrs = feature.attributes or {}label = attrs.get("Name", [""])[0] or attrs.get("gene", [""])[0] or attrs.get("locus_tag", [""])[0] or attrs.get("ID", [""])[0] or feature.featuretypestrand = 1 if feature.strand == "+" else -1 if feature.strand == "-" else 0tables[record.id].append({"record_id": record.id,"feature_type": str(feature.featuretype),"label": normalize_text(label),"start": max(0, int(feature.start) - 1),"end": int(feature.end),"length": max(0, int(feature.end) - (int(feature.start) - 1)),"strand": strand,"locus_tag": "; ".join(attrs.get("locus_tag", [])),"gene": "; ".join(attrs.get("gene", [])),"product": "; ".join(attrs.get("product", [])),"note": "; ".join(attrs.get("Note", [])),"source": "gff",})out = {}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, []), columns=cols).sort_values(["start","end"], kind="stable").reset_index(drop=True)return records, outdef bed_and_fasta_to_tables(bed_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]:records = parse_text_records(fasta_bytes, "fasta")if not records: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 = ["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()if sdf.empty:tables[r.id] = pd.DataFrame(columns=cols)continueout = 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",})out["length"] = (out["end"] - out["start"]).clip(lower=0)tables[r.id] = out[cols].sort_values(["start","end"]).reset_index(drop=True)return records, tables11 unmodified linesdef 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)":files = parse_uploaded_zip(primary_upload)normalized = {}for name, data in files.items():new_name, new_data = maybe_decompress(name, data)normalized[new_name] = new_datanames = list(normalized.keys())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: {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)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/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)if table_name and fasta_name:records, tables = parse_annotation_table(normalized[table_name], normalized[fasta_name])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")long_input = sum(len(str(r.seq)) for r in records) > 3_000_000do_orf = infer_orfs and not long_inputtables = {}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=cols)if not orf_df.empty:orf_df.insert(0, "record_id", r.id)tables[r.id] = orf_dfnotes.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 Noneif 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.")tables = {r.id: record_to_feature_table(r) for r in records}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 not records:raise ValueError("No FASTA records were found.")long_input = sum(len(str(r.seq)) for r in records) > 3_000_000do_orf = infer_orfs and not long_inputtables = {}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=cols)if not orf_df.empty:orf_df.insert(0, "record_id", r.id)tables[r.id] = orf_dfnotes.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 secondary_upload is None: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)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.")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)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.")sname, sdata = maybe_decompress(secondary_upload.name, secondary_upload.getvalue())records, tables = parse_annotation_table(pdata, sdata)notes.append("Parsed annotation table with FASTA sequence.")return ParsedGenome(records, tables, "table_fasta", notes)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 = 25000) -> pd.DataFrame:filtered = df.copy()if selected_types: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()if filtered.empty:filtered["highlight"] = Falsereturn filteredquery = normalize_text(query).lower()if query:mask = (filtered["label"].fillna("").str.lower().str.contains(query, na=False)| filtered["gene"].fillna("").str.lower().str.contains(query, na=False)| filtered["locus_tag"].fillna("").str.lower().str.contains(query, na=False)| filtered["product"].fillna("").str.lower().str.contains(query, na=False)| filtered["note"].fillna("").str.lower().str.contains(query, na=False))filtered["highlight"] = maskelse:filtered["highlight"] = Falseif len(filtered) > max_features: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, label_max_len: int = 28) -> GraphicRecord:features = []do_labels = len(filtered_df) <= annotate_limitfor _, 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 Noneif label and len(label) > label_max_len:label = label[: label_max_len - 3] + "..."strand = int(row["strand"]) if row["strand"] in (-1, 1) else 0features.append(GraphicFeature(start=int(row["start"]),end=int(row["end"]),strand=strand,color=color,label=label,))return GraphicRecord(sequence_length=len(record.seq), features=features)def 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 110label_max_len = 34 if publication_mode else 24graphic_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.2fig, ax = plt.subplots(figsize=(16, fig_height))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 fig2 unmodified linesseq_len = len(record.seq)circos = Circos({record.id: seq_len}, space=2)sector = circos.sectors[0]tick_track = sector.add_track((88, 100))tick_track.axis(fc="#f7f7f7", ec="black", lw=0.4)tick_interval = max(1000, seq_len // 10) if seq_len <= 100000 else max(5000, seq_len // 12)tick_track.xticks_by_interval(tick_interval,label_formatter=lambda v: f"{int(v/1000)} kb" if v >= 1000 else str(v),show_bottom_line=True,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)for _, row in filtered_df.iterrows():start = int(row["start"])end = int(row["end"])color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"])if row["strand"] == -1:neg_track.rect(start, end, fc=color, ec=color)else:pos_track.rect(start, end, fc=color, ec=color)inner_bottom = 10if show_gc_content:gc_track = sector.add_track((26, 40))gc_track.axis(fc="#f8f8f8", ec="black", lw=0.25)positions, 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.28)inner_bottom = 24if show_gc_skew:skew_track = sector.add_track((inner_bottom, inner_bottom + 12))skew_track.axis(fc="#f8f8f8", ec="black", lw=0.25)positions, skews = gc_skew_windows(record.seq, window_size)if skews:vmax = max(abs(min(skews)), abs(max(skews)), 0.1)skew_track.line(positions, skews, vmin=-vmax, vmax=vmax)skew_track.fill_between(positions, skews, y2=0, vmin=-vmax, vmax=vmax, alpha=0.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")return figdef 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, 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")else: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 figdef 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"])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]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")else:mids = (density_df["bin_start"] + density_df["bin_end"]) / 2ax.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 figdef fig_to_bytes(fig, fmt="png", dpi=600) -> bytes:buf = io.BytesIO()kwargs = {"bbox_inches": "tight"}if fmt.lower() == "png":kwargs["dpi"] = dpifig.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 imgdef 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 figdef build_summary_stats(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame) -> Dict[str, object]:counts = full_df["feature_type"].value_counts().to_dict() if not full_df.empty else {}return {"Record ID": record.id,"Description": normalize_text(getattr(record, "description", "")),"Genome length (bp)": len(record.seq),"GC (%)": round(compute_gc_percent(record.seq), 2),"Displayed features": len(filtered_df),"Total parsed features": len(full_df),"CDS": 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 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 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"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(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: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 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_dfdef 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]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_typesfiltered_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"})stats = build_summary_stats(record, full_df, filtered_df)stats_df = pd.DataFrame([stats])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,)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"] = parsedst.session_state["analysis_done"] = Truest.session_state["analysis_error"] = ""st.session_state["record_ids"] = record_idsst.session_state["selected_record_id"] = record.idst.session_state["full_df"] = full_dfst.session_state["filtered_df"] = filtered_dfst.session_state["display_df"] = display_dfst.session_state["stats"] = statsst.session_state["notes"] = parsed.notesst.session_state["available_types"] = available_typesst.session_state["selected_types_cache"] = default_selectedst.session_state["stats_df"] = stats_dfst.session_state["dist_df"] = dist_dfst.session_state["density_df"] = density_dfst.session_state["summary_text"] = summary_textst.session_state["figure_pack"] = {**figure_pack, **preview}st.session_state["table_csv"] = table_csvst.session_state["summary_zip"] = results_zipst.session_state["legend_html"] = legend_htmlst.session_state["run_mode_cache"] = run_modeinit_session_state()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 {"GenBank", "EMBL", "FASTA", "Universal / Auto-detect", "ZIP (auto-detect)"}:primary_upload = st.file_uploader("Upload primary input file", accept_multiple_files=False)secondary_upload = Noneelse: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("Run mode")run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1)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)if clear_button:clear_results()1 unmodified lineif run_button:if primary_upload is None: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 the annotation file and the FASTA file.")st.stop()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"] = Falsest.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()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">', 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.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: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 = metawith 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=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)with right: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