Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241import osimport ioimport reimport uuidimport base64import tempfileimport subprocessfrom pathlib import Path
import streamlit as stimport pandas as pdimport matplotlib.pyplot as plt
from Bio import SeqIO, Phylofrom Bio.Seq import Seqfrom Bio.SeqRecord import SeqRecord
APP_TITLE = "Phylogenetic Tree Builder"APP_SUBTITLE = "Build publication-ready phylogenetic trees from FASTA sequences"
ALLOWED_CHARS = set("ACGTURYSWKMBDHVN-")
def clean_header(header: str) -> str: return re.sub(r"\s+", "_", header.strip())
def validate_fasta_records(records): errors = [] cleaned = []
if len(records) < 2: errors.append("At least 2 sequences are required to build a phylogenetic tree.") return cleaned, errors
seen_ids = set() for i, rec in enumerate(records, start=1): seq_id = clean_header(rec.id if rec.id else f"seq_{i}") seq_str = str(rec.seq).upper().replace(" ", "").replace("\n", "")
if not seq_str: errors.append(f"Sequence {seq_id} is empty.") continue
bad_chars = set(seq_str) - ALLOWED_CHARS if bad_chars: errors.append( f"Sequence {seq_id} contains invalid characters: {', '.join(sorted(bad_chars))}" ) continue
if seq_id in seen_ids: seq_id = f"{seq_id}_{i}" seen_ids.add(seq_id)
cleaned.append(SeqRecord(Seq(seq_str), id=seq_id, description=""))
if len(cleaned) < 2: errors.append("After validation, fewer than 2 valid sequences remain.")
return cleaned, errors
def parse_fasta_text(text: str): handle = io.StringIO(text) return list(SeqIO.parse(handle, "fasta"))
def save_fasta(records, path: Path): with open(path, "w") as handle: SeqIO.write(records, handle, "fasta")
def run_command(cmd, cwd=None): result = subprocess.run( cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) return result.returncode, result.stdout, result.stderr
def run_mafft(input_fasta: Path, output_fasta: Path): cmd = ["mafft", "--auto", str(input_fasta)] code, stdout, stderr = run_command(cmd) if code != 0: raise RuntimeError(f"MAFFT failed:\n{stderr}") output_fasta.write_text(stdout) return output_fasta
def run_fasttree(aligned_fasta: Path, output_tree: Path, nucleotide=True): if nucleotide: cmd = ["FastTree", "-nt", str(aligned_fasta)] else: cmd = ["FastTree", str(aligned_fasta)]
code, stdout, stderr = run_command(cmd) if code != 0: raise RuntimeError(f"FastTree failed:\n{stderr}") output_tree.write_text(stdout) return output_tree
def draw_tree(tree_file: Path, image_file: Path, figure_width=12, figure_height=8, dpi=300): tree = Phylo.read(str(tree_file), "newick") fig = plt.figure(figsize=(figure_width, figure_height), dpi=dpi) ax = fig.add_subplot(1, 1, 1) Phylo.draw(tree, axes=ax, do_show=False) plt.tight_layout() fig.savefig(image_file, bbox_inches="tight") plt.close(fig) return image_file
def dataframe_from_records(records): return pd.DataFrame( { "Sequence_ID": [r.id for r in records], "Length": [len(r.seq) for r in records], } )
def download_button_bytes(label, file_path, mime_type): with open(file_path, "rb") as f: st.download_button( label=label, data=f, file_name=file_path.name, mime=mime_type )
def main(): st.set_page_config(page_title=APP_TITLE, layout="wide") st.title(APP_TITLE) st.caption(APP_SUBTITLE)
st.markdown( """This tool:- validates uploaded FASTA sequences- performs multiple sequence alignment with **MAFFT**- builds a phylogenetic tree with **FastTree**- exports **Newick**, aligned FASTA, and a publication-style PNG image""" )
with st.sidebar: st.header("Settings") seq_type = st.radio("Sequence type", ["Nucleotide", "Protein"], index=0) figure_width = st.slider("Figure width", 8, 20, 12) figure_height = st.slider("Figure height", 6, 20, 8) dpi = st.selectbox("Image DPI", [150, 300, 600], index=1)
st.subheader("Input sequences") uploaded_file = st.file_uploader("Upload FASTA file", type=["fasta", "fa", "fna", "faa", "txt"]) fasta_text = st.text_area("Or paste FASTA sequences here", height=220)
run_clicked = st.button("Build Phylogenetic Tree", type="primary", use_container_width=True)
if run_clicked: try: raw_records = []
if uploaded_file is not None: content = uploaded_file.read().decode("utf-8", errors="ignore") raw_records.extend(parse_fasta_text(content))
if fasta_text.strip(): raw_records.extend(parse_fasta_text(fasta_text))
if not raw_records: st.error("Please upload or paste FASTA sequences.") return
records, errors = validate_fasta_records(raw_records)
if errors: for err in errors: st.error(err) return
st.success(f"{len(records)} valid sequences detected.")
df = dataframe_from_records(records) st.subheader("Sequence summary") st.dataframe(df, use_container_width=True)
with tempfile.TemporaryDirectory() as tmpdir: tmpdir = Path(tmpdir) input_fasta = tmpdir / "input.fasta" aligned_fasta = tmpdir / "aligned.fasta" tree_file = tmpdir / "tree.nwk" image_file = tmpdir / "tree.png"
save_fasta(records, input_fasta)
with st.spinner("Running multiple sequence alignment with MAFFT..."): run_mafft(input_fasta, aligned_fasta)
with st.spinner("Building phylogenetic tree with FastTree..."): run_fasttree( aligned_fasta, tree_file, nucleotide=(seq_type == "Nucleotide") )
with st.spinner("Rendering publication-style tree image..."): draw_tree( tree_file, image_file, figure_width=figure_width, figure_height=figure_height, dpi=dpi )
st.subheader("Tree visualization") st.image(str(image_file), caption="Phylogenetic tree", use_container_width=True)
st.subheader("Download outputs") col1, col2, col3 = st.columns(3) with col1: download_button_bytes("Download Newick tree", tree_file, "text/plain") with col2: download_button_bytes("Download aligned FASTA", aligned_fasta, "text/plain") with col3: download_button_bytes("Download tree image (PNG)", image_file, "image/png")
st.subheader("Newick tree") st.code(tree_file.read_text(), language="text")
except Exception as e: st.error(f"Pipeline failed: {e}")
if __name__ == "__main__": main()app.pyAdded+241