deepromic / app.py
Arittra's picture
Update app.py
65d7097 verified
Raw History Blame Contribute Delete
9.08 kB
import streamlit as st
import os
import tempfile
import pandas as pd
from pathlib import Path
import subprocess
import sys
import zipfile
import io
# -----------------------------------------------------------
# 🧬 DeeProMic WebApp
# -----------------------------------------------------------
st.set_page_config(page_title="DeeProMic Web", page_icon="🧬", layout="wide")
# Quick check: XSRF must be disabled
#st.sidebar.write("XSRF protection:", st.get_option("server.enableXsrfProtection"))
# -----------------------------------------------------------
# Sidebar Debug Info
# -----------------------------------------------------------
# with st.sidebar:
#st.header("Debug Info")
#st.write(f"Python: {sys.version}")
#st.write(f"Current dir: {os.getcwd()}")
# st.write(f"Files: {[f for f in os.listdir('.') if os.path.isfile(f)]}")
# deepromic_exists = os.path.exists("deepromic.py")
# st.write(f"deepromic.py exists: {deepromic_exists}")
# if st.button("Check Dependencies"):
# try:
# result = subprocess.run(
#["python", "-c", "import tensorflow as tf; print('TF:', tf.__version__)"],
#capture_output=True, text=True
#)
# st.write("TensorFlow:", result.stdout or result.stderr)
# except Exception as e:
# st.error(f"Dependency check failed: {e}")
# -----------------------------------------------------------
# Title
# -----------------------------------------------------------
st.title("🧬 DeeProMic: Therapeutic Protein Classifier")
# -----------------------------------------------------------
# Upload-only input section
# -----------------------------------------------------------
st.subheader("Provide your Protein FASTA File")
input_fasta = None
uploaded_file = st.file_uploader(
"Upload a FASTA file",
type=['fasta', 'fa', 'txt'],
accept_multiple_files=False
)
if uploaded_file is not None:
suffix = Path(uploaded_file.name).suffix or ".fasta"
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
tmp.write(uploaded_file.getbuffer())
input_fasta = tmp.name
st.success(f"βœ… Uploaded: {uploaded_file.name} ({uploaded_file.size} bytes)")
st.info(f"Temporary file saved at: {input_fasta}")
# -----------------------------------------------------------
# Run Analysis
# -----------------------------------------------------------
if input_fasta:
threshold = st.slider("Probability Threshold", 0.0, 1.0, 0.5, 0.05)
if st.button("πŸš€ Run DeeProMic Analysis", type="primary"):
if not os.path.exists("deepromic.py"):
st.error("❌ deepromic.py not found! Make sure it's in your repository.")
st.stop()
with st.spinner("Running DeeProMic analysis... This may take several minutes."):
try:
with tempfile.TemporaryDirectory() as temp_dir:
output_dir = Path(temp_dir) / "results"
os.makedirs(output_dir, exist_ok=True)
cmd = [
"python", "deepromic.py",
"-i", str(input_fasta),
"-t", str(threshold),
"-o", str(output_dir)
]
st.write(f"Running command: {' '.join(cmd)}")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=os.getcwd(),
timeout=3600
)
# Logs
with st.expander("Execution Logs"):
st.text_area("STDOUT", result.stdout, height=200)
if result.stderr:
st.text_area("STDERR", result.stderr, height=200)
if result.returncode != 0:
st.error(f"❌ Analysis failed (exit code: {result.returncode})")
st.stop()
# Display Results
st.success("βœ… Analysis Complete!")
output_files = list(Path(output_dir).glob("*"))
st.write(f"Generated {len(output_files)} output files")
if output_files:
tab1, tab2, tab3, tab4 = st.tabs([
"πŸ“Š Probability Scores",
"🎯 Filtered Targets",
"πŸ” BLAST Results",
"πŸ“¦ Downloads"
])
# Tab 1: Probability scores
with tab1:
prob_file = Path(output_dir) / "probability_score.csv"
if prob_file.exists():
df = pd.read_csv(prob_file)
st.dataframe(df, use_container_width=True)
st.download_button(
"⬇️ Download Probability Scores",
df.to_csv(index=False),
"probability_scores.csv",
"text/csv"
)
else:
st.warning("Probability score file not found.")
# Tab 2: Filtered targets
with tab2:
filtered_file = Path(output_dir) / "filtered_sequences.csv"
fasta_file = Path(output_dir) / "potential_targets.fasta"
if filtered_file.exists():
df_filtered = pd.read_csv(filtered_file)
st.dataframe(df_filtered, use_container_width=True)
st.download_button(
"⬇️ Download Filtered Table",
df_filtered.to_csv(index=False),
"filtered_sequences.csv",
"text/csv"
)
else:
st.warning("Filtered table not found.")
if fasta_file.exists():
with open(fasta_file) as f:
st.download_button(
"⬇️ Download Potential Targets (FASTA)",
f.read(),
"potential_targets.fasta",
"text/fasta"
)
else:
st.warning("Potential targets FASTA not found.")
# Tab 3: BLAST results
with tab3:
blast_essential = Path(output_dir) / "blast_against_essential_genes.tsv"
blast_host = Path(output_dir) / "blast_against_host.tsv"
if blast_essential.exists():
st.subheader("BLAST vs Essential Genes")
df_blast = pd.read_csv(blast_essential, sep='\t')
st.dataframe(df_blast, use_container_width=True)
else:
st.warning("No BLAST essential gene results found.")
if blast_host.exists():
st.subheader("BLAST vs Host")
df_blast_host = pd.read_csv(blast_host, sep='\t')
st.dataframe(df_blast_host, use_container_width=True)
else:
st.warning("No BLAST host results found.")
# Tab 4: ZIP Download
with tab4:
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zf:
for file in output_files:
if file.is_file():
zf.write(file, file.name)
st.download_button(
"πŸ“¦ Download All Results (ZIP)",
zip_buffer.getvalue(),
"deepromic_results.zip",
"application/zip"
)
else:
st.warning("No output files were generated.")
except subprocess.TimeoutExpired:
st.error("⏰ Analysis timed out after 1 hour.")
except Exception as e:
st.error(f"❌ Error: {e}")
st.info("Check the logs above for details.")
else:
st.info("πŸ‘† Upload a FASTA file to start analysis.")