Update app.py
Browse files1234567812 unmodified lines21222324252660 unmodified lines878889909192936 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401414 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671685 unmodified lines17417517617717817918018118218318418518618718818919019119219319414 unmodified lines209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240import osimport ioimport reimport uuidimport base64import tempfileimport subprocessfrom pathlib import Path12 unmodified linesALLOWED_CHARS = set("ACGTURYSWKMBDHVN-")def clean_header(header: str) -> str:return re.sub(r"\s+", "_", header.strip())60 unmodified linescode, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"MAFFT failed:\n{stderr}")output_fasta.write_text(stdout)return output_fasta6 unmodified linescode, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"FastTree failed:\n{stderr}")output_tree.write_text(stdout)return output_treedef 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_filedef 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)4 unmodified lines- 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 = []5 unmodified linesraw_records.extend(parse_fasta_text(fasta_text))if not raw_records:st.error("Please upload or paste FASTA sequences.")returnrecords, errors = validate_fasta_records(raw_records)if errors:for err in errors:st.error(err)returnst.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)14 unmodified linesnucleotide=(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__":1234512 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596060 unmodified lines1211221231241251261276 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183194 unmodified lines3243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593605 unmodified lines36636736836937037137237337437537637737837938038138238338414 unmodified lines399400401402403404405406407408409410411412413414415416417418419420421422423import ioimport reimport tempfileimport subprocessfrom pathlib import Path12 unmodified linesALLOWED_CHARS = set("ACGTURYSWKMBDHVN-")def init_session_state():defaults = {"result_ready": False,"summary_df": None,"tree_png_bytes": None,"tree_newick_text": None,"aligned_fasta_text": None,"error_messages": [],"success_message": "",}for k, v in defaults.items():if k not in st.session_state:st.session_state[k] = vdef clear_results():keys_to_clear = ["result_ready","summary_df","tree_png_bytes","tree_newick_text","aligned_fasta_text","error_messages","success_message",]for k in keys_to_clear:if k in st.session_state:if k == "result_ready":st.session_state[k] = Falseelif k == "error_messages":st.session_state[k] = []elif k == "success_message":st.session_state[k] = ""else:st.session_state[k] = Nonedef clean_header(header: str) -> str:return re.sub(r"\s+", "_", header.strip())60 unmodified linescode, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"MAFFT failed:\n{stderr}")output_fasta.write_text(stdout, encoding="utf-8")return output_fasta6 unmodified linescode, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"FastTree failed:\n{stderr}")output_tree.write_text(stdout, encoding="utf-8")return output_treedef dataframe_from_records(records):return pd.DataFrame({"Sequence_ID": [r.id for r in records],"Length": [len(r.seq) for r in records],})def draw_tree_rectangular(tree, image_file: Path, figure_width=12, figure_height=8, dpi=300):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)def _get_terminals_in_order(tree):return tree.get_terminals()def draw_tree_circular(tree, image_file: Path, figure_width=10, figure_height=10, dpi=300):terminals = _get_terminals_in_order(tree)n = len(terminals)if n < 2:raise RuntimeError("Circular tree requires at least 2 terminal sequences.")depths = tree.depths()if not max(depths.values()):depths = tree.depths(unit_branch_lengths=True)term_angle = {term: 2 * plt.pi * i / n for i, term in enumerate(terminals)}def clade_angle(clade):if clade.is_terminal():return term_angle[clade]child_angles = [clade_angle(c) for c in clade.clades]return sum(child_angles) / len(child_angles)fig = plt.figure(figsize=(figure_width, figure_height), dpi=dpi)ax = fig.add_subplot(111, projection="polar")ax.set_theta_direction(-1)ax.set_theta_offset(plt.pi / 2)ax.set_axis_off()def draw_clade(clade, parent_radius=0.0, parent_angle=None):radius = depths.get(clade, 0.0)angle = clade_angle(clade)if parent_angle is not None:ax.plot([parent_angle, parent_angle], [parent_radius, radius], lw=1.2)if len(clade.clades) > 0:child_angles = [clade_angle(c) for c in clade.clades]ax.plot([min(child_angles), max(child_angles)],[radius, radius],lw=1.2)if clade.is_terminal():label = clade.name if clade.name else ""ax.text(angle,radius + max(depths.values()) * 0.05,label,fontsize=8,ha="center",va="center")for child in clade.clades:draw_clade(child, parent_radius=radius, parent_angle=clade_angle(child))root = tree.rootdraw_clade(root, parent_radius=0.0, parent_angle=None)plt.tight_layout()fig.savefig(image_file, bbox_inches="tight")plt.close(fig)def draw_tree_unrooted(tree, image_file: Path, figure_width=10, figure_height=10, dpi=300):fig = plt.figure(figsize=(figure_width, figure_height), dpi=dpi)ax = fig.add_subplot(1, 1, 1)try:Phylo.draw_graphviz(tree, prog="neato", axes=ax, do_show=False)except Exception:# fallback to standard drawing if graphviz-style unrooted rendering is unavailablePhylo.draw(tree, axes=ax, do_show=False)plt.tight_layout()fig.savefig(image_file, bbox_inches="tight")plt.close(fig)def draw_tree_layout(tree_file: Path, image_file: Path, layout: str, figure_width=12, figure_height=8, dpi=300):tree = Phylo.read(str(tree_file), "newick")if layout == "Rectangular":draw_tree_rectangular(tree, image_file, figure_width, figure_height, dpi)elif layout == "Circular":draw_tree_circular(tree, image_file, figure_width, figure_height, dpi)elif layout == "Unrooted":draw_tree_unrooted(tree, image_file, figure_width, figure_height, dpi)else:draw_tree_rectangular(tree, image_file, figure_width, figure_height, dpi)return image_filedef render_persisted_results():if st.session_state.get("error_messages"):for err in st.session_state["error_messages"]:st.error(err)if st.session_state.get("success_message"):st.success(st.session_state["success_message"])if st.session_state.get("summary_df") is not None:st.subheader("Sequence summary")st.dataframe(st.session_state["summary_df"], use_container_width=True)if st.session_state.get("tree_png_bytes") is not None:st.subheader("Tree visualization")st.image(st.session_state["tree_png_bytes"], caption="Phylogenetic tree", use_container_width=True)if (st.session_state.get("tree_newick_text") is not Noneor st.session_state.get("aligned_fasta_text") is not Noneor st.session_state.get("tree_png_bytes") is not None):st.subheader("Download outputs")col1, col2, col3 = st.columns(3)with col1:if st.session_state.get("tree_newick_text") is not None:st.download_button(label="Download Newick tree",data=st.session_state["tree_newick_text"],file_name="tree.nwk",mime="text/plain",key="download_newick")with col2:if st.session_state.get("aligned_fasta_text") is not None:st.download_button(label="Download aligned FASTA",data=st.session_state["aligned_fasta_text"],file_name="aligned.fasta",mime="text/plain",key="download_aligned")with col3:if st.session_state.get("tree_png_bytes") is not None:st.download_button(label="Download tree image (PNG)",data=st.session_state["tree_png_bytes"],file_name="tree.png",mime="image/png",key="download_png")if st.session_state.get("tree_newick_text") is not None:st.subheader("Newick tree")st.code(st.session_state["tree_newick_text"], language="text")def main():st.set_page_config(page_title=APP_TITLE, layout="wide")init_session_state()st.title(APP_TITLE)st.caption(APP_SUBTITLE)4 unmodified lines- performs multiple sequence alignment with **MAFFT**- builds a phylogenetic tree with **FastTree**- exports **Newick**, aligned FASTA, and a publication-style PNG image- supports **Rectangular**, **Circular**, and **Unrooted** tree layouts""")with st.sidebar:st.header("Settings")seq_type = st.radio("Sequence type", ["Nucleotide", "Protein"], index=0)tree_layout = st.selectbox("Tree layout",["Rectangular", "Circular", "Unrooted"],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)col_run, col_clear = st.columns([3, 1])with col_run:run_clicked = st.button("Build Phylogenetic Tree", type="primary", use_container_width=True)with col_clear:st.button("Clear", use_container_width=True, on_click=clear_results)if run_clicked:clear_results()try:raw_records = []5 unmodified linesraw_records.extend(parse_fasta_text(fasta_text))if not raw_records:st.session_state["error_messages"] = ["Please upload or paste FASTA sequences."]render_persisted_results()returnrecords, errors = validate_fasta_records(raw_records)if errors:st.session_state["error_messages"] = errorsrender_persisted_results()returnst.session_state["success_message"] = f"{len(records)} valid sequences detected."st.session_state["summary_df"] = dataframe_from_records(records)with tempfile.TemporaryDirectory() as tmpdir:tmpdir = Path(tmpdir)14 unmodified linesnucleotide=(seq_type == "Nucleotide"))with st.spinner("Rendering tree image..."):draw_tree_layout(tree_file,image_file,layout=tree_layout,figure_width=figure_width,figure_height=figure_height,dpi=dpi)st.session_state["aligned_fasta_text"] = aligned_fasta.read_text(encoding="utf-8")st.session_state["tree_newick_text"] = tree_file.read_text(encoding="utf-8")st.session_state["tree_png_bytes"] = image_file.read_bytes()st.session_state["result_ready"] = Trueexcept Exception as e:st.session_state["error_messages"] = [f"Pipeline failed: {e}"]render_persisted_results()if __name__ == "__main__":
app.py+233-50