Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
-
# Disable GPU to avoid CUDA errors
|
| 3 |
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 4 |
-
# Suppress TensorFlow warnings
|
| 5 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
| 6 |
|
| 7 |
import gradio as gr
|
|
@@ -17,7 +15,6 @@ from tensorflow.keras.models import load_model
|
|
| 17 |
from analyzer import PhylogeneticTreeAnalyzer
|
| 18 |
import tempfile
|
| 19 |
import shutil
|
| 20 |
-
import sys
|
| 21 |
import uuid
|
| 22 |
from pathlib import Path
|
| 23 |
from huggingface_hub import hf_hub_download
|
|
@@ -28,7 +25,7 @@ import stat
|
|
| 28 |
import time
|
| 29 |
import asyncio
|
| 30 |
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
|
| 31 |
-
from fastapi.responses import
|
| 32 |
from pydantic import BaseModel
|
| 33 |
from typing import Optional
|
| 34 |
import uvicorn
|
|
@@ -40,15 +37,14 @@ log_handler.setFormatter(log_formatter)
|
|
| 40 |
try:
|
| 41 |
file_handler = logging.FileHandler('/tmp/app.log')
|
| 42 |
file_handler.setFormatter(log_formatter)
|
| 43 |
-
logging.basicConfig(level=logging.
|
| 44 |
except Exception as e:
|
| 45 |
-
logging.basicConfig(level=logging.
|
| 46 |
logging.warning(f"Failed to set up file logging: {e}")
|
| 47 |
-
|
| 48 |
logger = logging.getLogger(__name__)
|
| 49 |
logger.info(f"Gradio version: {gr.__version__}")
|
| 50 |
|
| 51 |
-
# Set event loop policy
|
| 52 |
try:
|
| 53 |
asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
|
| 54 |
except Exception as e:
|
|
@@ -63,66 +59,49 @@ TREE_PATH = os.path.join(BASE_DIR, "f_gene_sequences.phy.treefile")
|
|
| 63 |
QUERY_OUTPUT_DIR = os.path.join(BASE_DIR, "queries")
|
| 64 |
os.makedirs(QUERY_OUTPUT_DIR, exist_ok=True)
|
| 65 |
|
| 66 |
-
# Model repository and file paths
|
| 67 |
MODEL_REPO = "GGproject10/best_boundary_aware_model"
|
| 68 |
-
CSV_PATH = "
|
| 69 |
|
| 70 |
-
# Initialize models
|
| 71 |
boundary_model = None
|
| 72 |
keras_model = None
|
| 73 |
kmer_to_index = None
|
| 74 |
analyzer = None
|
| 75 |
|
| 76 |
-
# --- Model Loading ---
|
| 77 |
def load_models_safely():
|
| 78 |
global boundary_model, keras_model, kmer_to_index, analyzer
|
| 79 |
logger.info("🔍 Loading models...")
|
| 80 |
try:
|
| 81 |
-
boundary_path = hf_hub_download(
|
| 82 |
-
repo_id=MODEL_REPO,
|
| 83 |
-
filename="best_boundary_aware_model.pth",
|
| 84 |
-
token=None
|
| 85 |
-
)
|
| 86 |
if os.path.exists(boundary_path):
|
| 87 |
boundary_model = EnhancedGenePredictor(boundary_path)
|
| 88 |
-
logger.info("✅ Boundary model loaded
|
| 89 |
else:
|
| 90 |
-
logger.error(
|
| 91 |
except Exception as e:
|
| 92 |
-
logger.error(f"❌ Failed to load boundary model: {e}")
|
| 93 |
boundary_model = None
|
| 94 |
try:
|
| 95 |
-
keras_path = hf_hub_download(
|
| 96 |
-
|
| 97 |
-
filename="best_model.keras",
|
| 98 |
-
token=None
|
| 99 |
-
)
|
| 100 |
-
kmer_path = hf_hub_download(
|
| 101 |
-
repo_id=MODEL_REPO,
|
| 102 |
-
filename="kmer_to_index.pkl",
|
| 103 |
-
token=None
|
| 104 |
-
)
|
| 105 |
if os.path.exists(keras_path) and os.path.exists(kmer_path):
|
| 106 |
keras_model = load_model(keras_path)
|
| 107 |
with open(kmer_path, "rb") as f:
|
| 108 |
kmer_to_index = pickle.load(f)
|
| 109 |
-
logger.info("✅ Keras model
|
| 110 |
else:
|
| 111 |
-
logger.error(
|
| 112 |
except Exception as e:
|
| 113 |
-
logger.error(f"❌ Failed to load Keras model: {e}")
|
| 114 |
keras_model = None
|
| 115 |
kmer_to_index = None
|
| 116 |
try:
|
| 117 |
logger.info("🌳 Initializing tree analyzer...")
|
| 118 |
analyzer = PhylogeneticTreeAnalyzer()
|
| 119 |
csv_candidates = [
|
| 120 |
-
CSV_PATH,
|
| 121 |
-
os.path.join(
|
| 122 |
-
os.path.join(BASE_DIR, "app", CSV_PATH),
|
| 123 |
-
os.path.join(os.path.dirname(__file__), CSV_PATH),
|
| 124 |
-
"f_cleaned.csv",
|
| 125 |
-
os.path.join(BASE_DIR, "f_cleaned.csv")
|
| 126 |
]
|
| 127 |
csv_loaded = False
|
| 128 |
for csv_candidate in csv_candidates:
|
|
@@ -134,27 +113,25 @@ def load_models_safely():
|
|
| 134 |
csv_loaded = True
|
| 135 |
break
|
| 136 |
except Exception as e:
|
| 137 |
-
logger.warning(f"CSV load failed for {csv_candidate}: {e}")
|
| 138 |
-
continue
|
| 139 |
if not csv_loaded:
|
| 140 |
-
logger.error("❌ Failed to load CSV data
|
| 141 |
analyzer = None
|
| 142 |
else:
|
| 143 |
try:
|
| 144 |
if analyzer.train_ai_model():
|
| 145 |
-
logger.info("✅ AI model training completed
|
| 146 |
else:
|
| 147 |
-
logger.warning("⚠️ AI model training failed
|
| 148 |
except Exception as e:
|
| 149 |
-
logger.warning(f"⚠️ AI model training failed: {e}")
|
| 150 |
except Exception as e:
|
| 151 |
-
logger.error(f"❌ Tree analyzer initialization failed: {e}")
|
| 152 |
analyzer = None
|
| 153 |
|
| 154 |
-
# Load models at startup
|
| 155 |
load_models_safely()
|
| 156 |
|
| 157 |
-
# --- Tool Detection ---
|
| 158 |
def setup_binary_permissions():
|
| 159 |
for binary in [MAFFT_PATH, IQTREE_PATH]:
|
| 160 |
if os.path.exists(binary):
|
|
@@ -162,7 +139,7 @@ def setup_binary_permissions():
|
|
| 162 |
os.chmod(binary, os.stat(binary).st_mode | stat.S_IEXEC)
|
| 163 |
logger.info(f"Set executable permission on {binary}")
|
| 164 |
except Exception as e:
|
| 165 |
-
logger.warning(f"Failed to set permission on {binary}: {e}")
|
| 166 |
|
| 167 |
def check_tool_availability():
|
| 168 |
setup_binary_permissions()
|
|
@@ -172,12 +149,7 @@ def check_tool_availability():
|
|
| 172 |
for candidate in mafft_candidates:
|
| 173 |
if shutil.which(candidate) or os.path.exists(candidate):
|
| 174 |
try:
|
| 175 |
-
result = subprocess.run(
|
| 176 |
-
[candidate, "--help"],
|
| 177 |
-
capture_output=True,
|
| 178 |
-
text=True,
|
| 179 |
-
timeout=5
|
| 180 |
-
)
|
| 181 |
if result.returncode == 0 or "mafft" in result.stderr.lower():
|
| 182 |
mafft_available = True
|
| 183 |
mafft_cmd = candidate
|
|
@@ -191,12 +163,7 @@ def check_tool_availability():
|
|
| 191 |
for candidate in iqtree_candidates:
|
| 192 |
if shutil.which(candidate) or os.path.exists(candidate):
|
| 193 |
try:
|
| 194 |
-
result = subprocess.run(
|
| 195 |
-
[candidate, "--help"],
|
| 196 |
-
capture_output=True,
|
| 197 |
-
text=True,
|
| 198 |
-
timeout=5
|
| 199 |
-
)
|
| 200 |
if result.returncode == 0 or "iqtree" in result.stderr.lower():
|
| 201 |
iqtree_available = True
|
| 202 |
iqtree_cmd = candidate
|
|
@@ -208,6 +175,7 @@ def check_tool_availability():
|
|
| 208 |
|
| 209 |
# --- Pipeline Functions ---
|
| 210 |
def phylogenetic_placement(sequence: str, mafft_cmd: str, iqtree_cmd: str):
|
|
|
|
| 211 |
try:
|
| 212 |
if len(sequence.strip()) < 100:
|
| 213 |
return False, "Sequence too short (<100 bp).", None, None
|
|
@@ -238,41 +206,48 @@ def phylogenetic_placement(sequence: str, mafft_cmd: str, iqtree_cmd: str):
|
|
| 238 |
logger.error(f"Phylogenetic placement failed: {e}", exc_info=True)
|
| 239 |
return False, f"Error: {str(e)}", None, None
|
| 240 |
finally:
|
| 241 |
-
if
|
| 242 |
try:
|
| 243 |
os.unlink(query_fasta)
|
| 244 |
-
|
| 245 |
-
|
|
|
|
| 246 |
|
| 247 |
def analyze_sequence_for_tree(sequence: str, matching_percentage: float):
|
| 248 |
try:
|
| 249 |
logger.debug("Starting tree analysis...")
|
| 250 |
if not analyzer:
|
|
|
|
| 251 |
return "❌ Tree analyzer not initialized.", None, None
|
|
|
|
| 252 |
if not sequence or len(sequence.strip()) < 10:
|
|
|
|
| 253 |
return "❌ Invalid sequence.", None, None
|
| 254 |
if not (1 <= matching_percentage <= 99):
|
|
|
|
| 255 |
return "❌ Matching percentage must be 1-99.", None, None
|
| 256 |
-
logger.debug("
|
| 257 |
if not analyzer.find_query_sequence(sequence):
|
|
|
|
| 258 |
return "❌ Sequence not accepted.", None, None
|
| 259 |
-
logger.debug("
|
| 260 |
matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
|
| 261 |
if not matched_ids:
|
|
|
|
| 262 |
return f"❌ No similar sequences at {matching_percentage}% threshold.", None, None
|
| 263 |
-
logger.debug("
|
| 264 |
analyzer.build_tree_structure_with_ml_safe(matched_ids)
|
| 265 |
-
logger.debug("
|
| 266 |
fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
|
| 267 |
query_id = analyzer.query_id or f"query_{int(time.time())}"
|
| 268 |
tree_html_path = os.path.join("/tmp", f'phylogenetic_tree_{query_id}.html')
|
| 269 |
logger.debug(f"Saving tree to {tree_html_path}")
|
| 270 |
fig.write_html(tree_html_path)
|
| 271 |
analyzer.matching_percentage = matching_percentage
|
| 272 |
-
logger.debug("
|
| 273 |
report_success = analyzer.generate_detailed_report(matched_ids, actual_percentage)
|
| 274 |
report_html_path = os.path.join("/tmp", f'detailed_report_{query_id}.html') if report_success else None
|
| 275 |
-
logger.debug(f"Tree analysis completed: {len(matched_ids)} matches")
|
| 276 |
return f"✅ Found {len(matched_ids)} sequences at {actual_percentage:.2f}% similarity.", tree_html_path, report_html_path
|
| 277 |
except Exception as e:
|
| 278 |
logger.error(f"Tree analysis failed: {e}", exc_info=True)
|
|
@@ -280,9 +255,12 @@ def analyze_sequence_for_tree(sequence: str, matching_percentage: float):
|
|
| 280 |
|
| 281 |
def predict_with_keras(sequence):
|
| 282 |
try:
|
|
|
|
| 283 |
if not keras_model or not kmer_to_index:
|
|
|
|
| 284 |
return "❌ Keras model not available."
|
| 285 |
if len(sequence) < 6:
|
|
|
|
| 286 |
return "❌ Sequence too short (<6 bp)."
|
| 287 |
kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
|
| 288 |
indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
|
|
@@ -290,6 +268,7 @@ def predict_with_keras(sequence):
|
|
| 290 |
prediction = keras_model.predict(input_arr, verbose=0)[0]
|
| 291 |
f_gene_prob = prediction[-1]
|
| 292 |
percentage = min(100, max(0, int(f_gene_prob * 100 + 5)))
|
|
|
|
| 293 |
return f"✅ {percentage}% F gene confidence"
|
| 294 |
except Exception as e:
|
| 295 |
logger.error(f"Keras prediction failed: {e}", exc_info=True)
|
|
@@ -297,7 +276,9 @@ def predict_with_keras(sequence):
|
|
| 297 |
|
| 298 |
def read_fasta_file(file_obj):
|
| 299 |
try:
|
|
|
|
| 300 |
if file_obj is None:
|
|
|
|
| 301 |
return ""
|
| 302 |
if isinstance(file_obj, str):
|
| 303 |
with open(file_obj, "r") as f:
|
|
@@ -306,15 +287,19 @@ def read_fasta_file(file_obj):
|
|
| 306 |
content = file_obj.read().decode("utf-8")
|
| 307 |
lines = content.strip().split("\n")
|
| 308 |
seq_lines = [line.strip() for line in lines if not line.startswith(">")]
|
| 309 |
-
|
|
|
|
|
|
|
| 310 |
except Exception as e:
|
| 311 |
logger.error(f"Failed to read FASTA file: {e}", exc_info=True)
|
| 312 |
return ""
|
| 313 |
|
| 314 |
def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
| 315 |
try:
|
|
|
|
| 316 |
dna_input = dna_input.upper().strip()
|
| 317 |
if not dna_input:
|
|
|
|
| 318 |
return "❌ Empty input", "", "", "", "", None, None, None, None, "No input", "No input", None, None
|
| 319 |
if not re.match('^[ACTGN]+$', dna_input):
|
| 320 |
dna_input = ''.join(c if c in 'ACTGN' else 'N' for c in dna_input)
|
|
@@ -333,6 +318,7 @@ def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
|
| 333 |
except Exception as e:
|
| 334 |
boundary_output = f"❌ Boundary prediction error: {str(e)}"
|
| 335 |
processed_sequence = dna_input
|
|
|
|
| 336 |
else:
|
| 337 |
boundary_output = f"⚠️ Boundary model not available. Using full input: {len(dna_input)} bp"
|
| 338 |
keras_output = predict_with_keras(processed_sequence) if processed_sequence and len(processed_sequence) >= 6 else "❌ Sequence too short."
|
|
@@ -351,6 +337,7 @@ def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
|
| 351 |
ml_tree_output = "❌ MAFFT or IQ-TREE not available"
|
| 352 |
except Exception as e:
|
| 353 |
ml_tree_output = f"❌ ML tree error: {str(e)}"
|
|
|
|
| 354 |
elif build_ml_tree:
|
| 355 |
ml_tree_output = "❌ Sequence too short for placement (<100 bp)."
|
| 356 |
else:
|
|
@@ -378,6 +365,7 @@ def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
|
| 378 |
simplified_ml_output = f"❌ Tree analysis error: {str(e)}"
|
| 379 |
tree_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
| 380 |
report_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
|
|
|
| 381 |
else:
|
| 382 |
simplified_ml_output = "❌ Tree analyzer not available." if not analyzer else "❌ Sequence too short (<10 bp)."
|
| 383 |
tree_html_content = f"<div style='color: orange;'>{simplified_ml_output}</div>"
|
|
@@ -429,7 +417,7 @@ async def run_pipeline_from_file(fasta_file_obj, similarity_score, build_ml_tree
|
|
| 429 |
try:
|
| 430 |
os.unlink(temp_file_path)
|
| 431 |
except Exception as e:
|
| 432 |
-
logger.warning(f"Failed to delete temp file {temp_file_path}: {e}")
|
| 433 |
|
| 434 |
# --- Pydantic Models ---
|
| 435 |
class AnalysisRequest(BaseModel):
|
|
@@ -478,10 +466,6 @@ async def health_check():
|
|
| 478 |
"tree_analyzer": analyzer is not None,
|
| 479 |
"mafft_available": mafft_available,
|
| 480 |
"iqtree_available": iqtree_available
|
| 481 |
-
},
|
| 482 |
-
"paths": {
|
| 483 |
-
"base_dir": BASE_DIR,
|
| 484 |
-
"query_output_dir": QUERY_OUTPUT_DIR
|
| 485 |
}
|
| 486 |
}
|
| 487 |
except Exception as e:
|
|
@@ -547,7 +531,7 @@ async def analyze_file(
|
|
| 547 |
try:
|
| 548 |
os.unlink(temp_file_path)
|
| 549 |
except Exception as e:
|
| 550 |
-
logger.warning(f"Failed to clean up {temp_file_path}: {e}")
|
| 551 |
|
| 552 |
@app.get("/download/{file_type}/{query_id}")
|
| 553 |
async def download_file(file_type: str, query_id: str):
|
|
@@ -566,9 +550,10 @@ async def download_file(file_type: str, query_id: str):
|
|
| 566 |
# --- Gradio Interface ---
|
| 567 |
def create_gradio_interface():
|
| 568 |
try:
|
|
|
|
| 569 |
with gr.Blocks(
|
| 570 |
title="🧬 Gene Analysis Pipeline",
|
| 571 |
-
theme=
|
| 572 |
css="""
|
| 573 |
.gradio-container { max-width: 1200px !important; }
|
| 574 |
.status-box { padding: 10px; border-radius: 5px; margin: 5px 0; }
|
|
@@ -591,275 +576,140 @@ def create_gradio_interface():
|
|
| 591 |
</div>
|
| 592 |
""")
|
| 593 |
with gr.Tabs():
|
| 594 |
-
with gr.TabItem("
|
| 595 |
with gr.Row():
|
| 596 |
with gr.Column(scale=2):
|
| 597 |
dna_input = gr.Textbox(
|
| 598 |
-
label="
|
| 599 |
-
placeholder="Enter
|
| 600 |
-
lines=5
|
| 601 |
-
max_lines=10
|
| 602 |
)
|
| 603 |
with gr.Column(scale=1):
|
| 604 |
-
|
| 605 |
minimum=1,
|
| 606 |
maximum=99,
|
| 607 |
-
value=95,
|
| 608 |
-
step=1,
|
| 609 |
-
label="
|
| 610 |
-
info="Minimum similarity for phylogenetic analysis"
|
| 611 |
)
|
| 612 |
build_ml_tree = gr.Checkbox(
|
| 613 |
-
label="
|
| 614 |
-
value=False
|
| 615 |
-
info="Perform phylogenetic placement (slower)"
|
| 616 |
-
)
|
| 617 |
-
analyze_btn = gr.Button(
|
| 618 |
-
"🔬 Analyze Sequence",
|
| 619 |
-
variant="primary",
|
| 620 |
-
size="lg"
|
| 621 |
)
|
| 622 |
-
|
| 623 |
-
with gr.TabItem("
|
| 624 |
with gr.Row():
|
| 625 |
with gr.Column(scale=2):
|
| 626 |
file_input = gr.File(
|
| 627 |
-
label="
|
| 628 |
-
file_types=[".fasta", ".fa", ".fas", ".txt"]
|
| 629 |
-
type="filepath"
|
| 630 |
)
|
| 631 |
with gr.Column(scale=1):
|
| 632 |
-
|
| 633 |
minimum=1,
|
| 634 |
maximum=99,
|
| 635 |
-
value=95,
|
| 636 |
-
step=1,
|
| 637 |
-
label="
|
| 638 |
)
|
| 639 |
file_build_ml_tree = gr.Checkbox(
|
| 640 |
-
label="
|
| 641 |
value=False
|
| 642 |
)
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
variant="primary",
|
| 646 |
-
size="lg"
|
| 647 |
-
)
|
| 648 |
-
|
| 649 |
-
# Results Section
|
| 650 |
-
gr.Markdown("## 📊 Analysis Results")
|
| 651 |
-
|
| 652 |
with gr.Row():
|
| 653 |
with gr.Column():
|
| 654 |
-
boundary_output = gr.Textbox(
|
| 655 |
-
|
| 656 |
-
interactive=False,
|
| 657 |
-
lines=2
|
| 658 |
-
)
|
| 659 |
-
keras_output = gr.Textbox(
|
| 660 |
-
label="🧠 F Gene Validation",
|
| 661 |
-
interactive=False,
|
| 662 |
-
lines=2
|
| 663 |
-
)
|
| 664 |
with gr.Column():
|
| 665 |
-
ml_tree_output = gr.Textbox(
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
lines=2
|
| 669 |
-
)
|
| 670 |
-
tree_analysis_output = gr.Textbox(
|
| 671 |
-
label="📈 Tree Analysis",
|
| 672 |
-
interactive=False,
|
| 673 |
-
lines=2
|
| 674 |
-
)
|
| 675 |
-
|
| 676 |
-
summary_output = gr.Textbox(
|
| 677 |
-
label="📋 Summary",
|
| 678 |
-
interactive=False,
|
| 679 |
-
lines=8
|
| 680 |
-
)
|
| 681 |
-
|
| 682 |
-
# Interactive Visualizations
|
| 683 |
-
with gr.Tabs():
|
| 684 |
-
with gr.TabItem("🌳 Phylogenetic Tree"):
|
| 685 |
-
tree_html = gr.HTML(
|
| 686 |
-
label="Interactive Tree Visualization",
|
| 687 |
-
value="<div style='text-align: center; padding: 20px; color: #666;'>Run analysis to see phylogenetic tree</div>"
|
| 688 |
-
)
|
| 689 |
-
|
| 690 |
-
with gr.TabItem("📊 Detailed Report"):
|
| 691 |
-
report_html = gr.HTML(
|
| 692 |
-
label="Comprehensive Analysis Report",
|
| 693 |
-
value="<div style='text-align: center; padding: 20px; color: #666;'>Run analysis to see detailed report</div>"
|
| 694 |
-
)
|
| 695 |
-
|
| 696 |
-
# Download Section
|
| 697 |
with gr.Row():
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
)
|
| 707 |
-
|
| 708 |
-
# Event Handlers
|
| 709 |
-
def process_text_input(dna_seq, similarity, build_tree):
|
| 710 |
-
if not dna_seq or not dna_seq.strip():
|
| 711 |
-
return (
|
| 712 |
-
"❌ Please enter a DNA sequence", "", "", "", "",
|
| 713 |
-
None, None,
|
| 714 |
-
"<div style='color: red;'>No input provided</div>",
|
| 715 |
-
"<div style='color: red;'>No input provided</div>"
|
| 716 |
-
)
|
| 717 |
-
|
| 718 |
-
results = run_pipeline(dna_seq, similarity, build_tree)
|
| 719 |
-
return (
|
| 720 |
-
results[0], results[1], results[2], results[3], results[4],
|
| 721 |
-
results[5], results[6], results[9], results[10]
|
| 722 |
-
)
|
| 723 |
-
|
| 724 |
-
def process_file_input(file_path, similarity, build_tree):
|
| 725 |
-
if not file_path:
|
| 726 |
-
return (
|
| 727 |
-
"❌ Please upload a file", "", "", "", "",
|
| 728 |
-
None, None,
|
| 729 |
-
"<div style='color: red;'>No file provided</div>",
|
| 730 |
-
"<div style='color: red;'>No file provided</div>"
|
| 731 |
-
)
|
| 732 |
-
|
| 733 |
-
# Read the FASTA file
|
| 734 |
-
try:
|
| 735 |
-
sequence = read_fasta_file(file_path)
|
| 736 |
-
if not sequence:
|
| 737 |
-
return (
|
| 738 |
-
"❌ Failed to read sequence from file", "", "", "", "",
|
| 739 |
-
None, None,
|
| 740 |
-
"<div style='color: red;'>Invalid file format</div>",
|
| 741 |
-
"<div style='color: red;'>Invalid file format</div>"
|
| 742 |
-
)
|
| 743 |
-
|
| 744 |
-
results = run_pipeline(sequence, similarity, build_tree)
|
| 745 |
-
return (
|
| 746 |
-
results[0], results[1], results[2], results[3], results[4],
|
| 747 |
-
results[5], results[6], results[9], results[10]
|
| 748 |
-
)
|
| 749 |
-
except Exception as e:
|
| 750 |
-
error_msg = f"❌ Error processing file: {str(e)}"
|
| 751 |
-
return (
|
| 752 |
-
error_msg, "", "", "", "",
|
| 753 |
-
None, None,
|
| 754 |
-
f"<div style='color: red;'>{error_msg}</div>",
|
| 755 |
-
f"<div style='color: red;'>{error_msg}</div>"
|
| 756 |
-
)
|
| 757 |
-
|
| 758 |
-
# Wire up the event handlers
|
| 759 |
analyze_btn.click(
|
| 760 |
-
fn=
|
| 761 |
-
inputs=[dna_input,
|
| 762 |
outputs=[
|
| 763 |
-
boundary_output, keras_output, ml_tree_output,
|
| 764 |
-
|
| 765 |
-
aligned_file, tree_file, tree_html, report_html
|
| 766 |
]
|
| 767 |
)
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
inputs=[file_input, file_similarity_slider, file_build_ml_tree],
|
| 772 |
outputs=[
|
| 773 |
-
boundary_output, keras_output, ml_tree_output,
|
| 774 |
-
|
| 775 |
-
aligned_file, tree_file, tree_html, report_html
|
| 776 |
]
|
| 777 |
)
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
return "ATGGAGTTGCTAATCCTCAAACTTCTGCTTGAAGGGTCACAGTACACACCCTGTGCAAAGAGACAAGCAACAATAATGATCTGGATTCGTACGACGTGGCTGAGGGGAACCTGTATGTGAACAGTCTAGCCAGAGGTTACTATGCAACGGTCACTAGGGCCGGAATCCCTCCCAATGCACCAGGACGCTCTGATCACGTAAGACGAACTTACAGATCCAAAGTGGGAAACGGGGAACGGCTGGGTACCCTGAGACAGCCTGGACAAGACCTCAGGTGTCACATACGACGGGGACTATAATATGGACGCCTGCAGCGGTGGAACAAATAGCAACAGACCT"
|
| 788 |
-
|
| 789 |
-
def load_example2():
|
| 790 |
-
return "ATGGAGTTGCTAATCCTCAAACTTCTGCTTGAAGGGTCACAGTACACACCCTGTGCAAAGAGACAAGCAACAATAATGATCTGGATTCGTACGACGTGGCTGAGGGGAACCTGTATGTGAACAGTCTAGCCAGAGGTTACTATGCAACGGTCACTAGGGCCGGAATCCCTCCCAATGCACCAGGACGCTCTGATCACGTAAGACGAACTTACAGATCCAAAGTGGGAAACGGGGAACGGCTGGGTACCCTGAGACAGCCTGGACAAGACCTCAGGTGTCACATACGACGGGGACTATAATATGGACGCCTGCAGCGGTGGAACAAATAGCAACAGACCTCATGTGGGCAGTGGCCACAATCTACAATTTGGATACAGTGGAATTTGGAGAAGCGACCTTCAGAACCTGGGTCATGGTGCCGTCCTACGGTGGGGCCGCCGAAGCAACTCTCGACTACGTGGTGGAAAGCCTGGGCTTCGGAGGCGCAGTTATCGGAAAAAGCAAAGAACTCACAGGAAAGCTGTTCAAGAACGACACCTACTATGGAAAGATGGGTCACTATCTAAAAATTGATTCCTGTACCAGCCAACTTTAA"
|
| 791 |
-
|
| 792 |
-
def clear_inputs():
|
| 793 |
-
return ""
|
| 794 |
-
|
| 795 |
-
example1_btn.click(fn=load_example1, outputs=dna_input)
|
| 796 |
-
example2_btn.click(fn=load_example2, outputs=dna_input)
|
| 797 |
-
clear_btn.click(fn=clear_inputs, outputs=dna_input)
|
| 798 |
-
|
| 799 |
return iface
|
| 800 |
-
|
| 801 |
except Exception as e:
|
| 802 |
-
logger.error(f"
|
| 803 |
-
# Fallback simple interface
|
| 804 |
return gr.Interface(
|
| 805 |
-
fn=lambda x: f"
|
| 806 |
-
inputs=gr.Textbox(label="
|
| 807 |
-
outputs=gr.Textbox(label="
|
| 808 |
-
title="🧬 Gene Analysis Pipeline
|
| 809 |
)
|
| 810 |
|
| 811 |
-
#
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
# Mount Gradio app to FastAPI
|
| 815 |
-
@app.get("/gradio", response_class=HTMLResponse)
|
| 816 |
-
async def gradio_interface():
|
| 817 |
-
"""Serve the Gradio interface"""
|
| 818 |
-
try:
|
| 819 |
-
# Generate the Gradio app HTML
|
| 820 |
-
return gradio_app.launch(prevent_thread_lock=True, share=False, show_error=True)
|
| 821 |
-
except Exception as e:
|
| 822 |
-
logger.error(f"Failed to serve Gradio interface: {e}", exc_info=True)
|
| 823 |
-
return HTMLResponse(f"""
|
| 824 |
-
<html>
|
| 825 |
-
<head><title>🧬 Gene Analysis Pipeline - Error</title></head>
|
| 826 |
-
<body>
|
| 827 |
-
<h1>🧬 Gene Analysis Pipeline</h1>
|
| 828 |
-
<p style="color: red;">Failed to load Gradio interface: {str(e)}</p>
|
| 829 |
-
<p>Please try using the API endpoints instead:</p>
|
| 830 |
-
<ul>
|
| 831 |
-
<li><a href="/docs">API Documentation</a></li>
|
| 832 |
-
<li><a href="/health">Health Check</a></li>
|
| 833 |
-
</ul>
|
| 834 |
-
</body>
|
| 835 |
-
</html>
|
| 836 |
-
""")
|
| 837 |
-
|
| 838 |
-
# --- Main Application Runner ---
|
| 839 |
-
if __name__ == "__main__":
|
| 840 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 841 |
logger.info("🚀 Starting Gene Analysis Pipeline...")
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 846 |
gradio_app.launch(
|
| 847 |
server_name="0.0.0.0",
|
| 848 |
server_port=7860,
|
| 849 |
-
share=
|
| 850 |
-
|
| 851 |
-
enable_queue=True
|
| 852 |
)
|
| 853 |
-
|
| 854 |
-
logger.
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
|
|
|
| 3 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
| 4 |
|
| 5 |
import gradio as gr
|
|
|
|
| 15 |
from analyzer import PhylogeneticTreeAnalyzer
|
| 16 |
import tempfile
|
| 17 |
import shutil
|
|
|
|
| 18 |
import uuid
|
| 19 |
from pathlib import Path
|
| 20 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 25 |
import time
|
| 26 |
import asyncio
|
| 27 |
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
|
| 28 |
+
from fastapi.responses import FileResponse
|
| 29 |
from pydantic import BaseModel
|
| 30 |
from typing import Optional
|
| 31 |
import uvicorn
|
|
|
|
| 37 |
try:
|
| 38 |
file_handler = logging.FileHandler('/tmp/app.log')
|
| 39 |
file_handler.setFormatter(log_formatter)
|
| 40 |
+
logging.basicConfig(level=logging.DEBUG, handlers=[log_handler, file_handler])
|
| 41 |
except Exception as e:
|
| 42 |
+
logging.basicConfig(level=logging.DEBUG, handlers=[log_handler])
|
| 43 |
logging.warning(f"Failed to set up file logging: {e}")
|
|
|
|
| 44 |
logger = logging.getLogger(__name__)
|
| 45 |
logger.info(f"Gradio version: {gr.__version__}")
|
| 46 |
|
| 47 |
+
# Set event loop policy
|
| 48 |
try:
|
| 49 |
asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
|
| 50 |
except Exception as e:
|
|
|
|
| 59 |
QUERY_OUTPUT_DIR = os.path.join(BASE_DIR, "queries")
|
| 60 |
os.makedirs(QUERY_OUTPUT_DIR, exist_ok=True)
|
| 61 |
|
|
|
|
| 62 |
MODEL_REPO = "GGproject10/best_boundary_aware_model"
|
| 63 |
+
CSV_PATH = "f_cleaned.csv"
|
| 64 |
|
| 65 |
+
# Initialize models
|
| 66 |
boundary_model = None
|
| 67 |
keras_model = None
|
| 68 |
kmer_to_index = None
|
| 69 |
analyzer = None
|
| 70 |
|
| 71 |
+
# --- Model Loading (from Script 2) ---
|
| 72 |
def load_models_safely():
|
| 73 |
global boundary_model, keras_model, kmer_to_index, analyzer
|
| 74 |
logger.info("🔍 Loading models...")
|
| 75 |
try:
|
| 76 |
+
boundary_path = hf_hub_download(repo_id=MODEL_REPO, filename="best_boundary_aware_model.pth", token=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
if os.path.exists(boundary_path):
|
| 78 |
boundary_model = EnhancedGenePredictor(boundary_path)
|
| 79 |
+
logger.info("✅ Boundary model loaded.")
|
| 80 |
else:
|
| 81 |
+
logger.error("❌ Boundary model file not found.")
|
| 82 |
except Exception as e:
|
| 83 |
+
logger.error(f"❌ Failed to load boundary model: {e}", exc_info=True)
|
| 84 |
boundary_model = None
|
| 85 |
try:
|
| 86 |
+
keras_path = hf_hub_download(repo_id=MODEL_REPO, filename="best_model.keras", token=None)
|
| 87 |
+
kmer_path = hf_hub_download(repo_id=MODEL_REPO, filename="kmer_to_index.pkl", token=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
if os.path.exists(keras_path) and os.path.exists(kmer_path):
|
| 89 |
keras_model = load_model(keras_path)
|
| 90 |
with open(kmer_path, "rb") as f:
|
| 91 |
kmer_to_index = pickle.load(f)
|
| 92 |
+
logger.info("✅ Keras model loaded.")
|
| 93 |
else:
|
| 94 |
+
logger.error("❌ Keras model files not found.")
|
| 95 |
except Exception as e:
|
| 96 |
+
logger.error(f"❌ Failed to load Keras model: {e}", exc_info=True)
|
| 97 |
keras_model = None
|
| 98 |
kmer_to_index = None
|
| 99 |
try:
|
| 100 |
logger.info("🌳 Initializing tree analyzer...")
|
| 101 |
analyzer = PhylogeneticTreeAnalyzer()
|
| 102 |
csv_candidates = [
|
| 103 |
+
CSV_PATH, os.path.join(BASE_DIR, CSV_PATH), os.path.join(BASE_DIR, "app", CSV_PATH),
|
| 104 |
+
os.path.join(os.path.dirname(__file__), CSV_PATH), "f_cleaned.csv", os.path.join(BASE_DIR, "f_cleaned.csv")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
]
|
| 106 |
csv_loaded = False
|
| 107 |
for csv_candidate in csv_candidates:
|
|
|
|
| 113 |
csv_loaded = True
|
| 114 |
break
|
| 115 |
except Exception as e:
|
| 116 |
+
logger.warning(f"CSV load failed for {csv_candidate}: {e}", exc_info=True)
|
|
|
|
| 117 |
if not csv_loaded:
|
| 118 |
+
logger.error("❌ Failed to load CSV data.")
|
| 119 |
analyzer = None
|
| 120 |
else:
|
| 121 |
try:
|
| 122 |
if analyzer.train_ai_model():
|
| 123 |
+
logger.info("✅ AI model training completed.")
|
| 124 |
else:
|
| 125 |
+
logger.warning("⚠️ AI model training failed.")
|
| 126 |
except Exception as e:
|
| 127 |
+
logger.warning(f"⚠️ AI model training failed: {e}", exc_info=True)
|
| 128 |
except Exception as e:
|
| 129 |
+
logger.error(f"❌ Tree analyzer initialization failed: {e}", exc_info=True)
|
| 130 |
analyzer = None
|
| 131 |
|
|
|
|
| 132 |
load_models_safely()
|
| 133 |
|
| 134 |
+
# --- Tool Detection (from Script 2) ---
|
| 135 |
def setup_binary_permissions():
|
| 136 |
for binary in [MAFFT_PATH, IQTREE_PATH]:
|
| 137 |
if os.path.exists(binary):
|
|
|
|
| 139 |
os.chmod(binary, os.stat(binary).st_mode | stat.S_IEXEC)
|
| 140 |
logger.info(f"Set executable permission on {binary}")
|
| 141 |
except Exception as e:
|
| 142 |
+
logger.warning(f"Failed to set permission on {binary}: {e}", exc_info=True)
|
| 143 |
|
| 144 |
def check_tool_availability():
|
| 145 |
setup_binary_permissions()
|
|
|
|
| 149 |
for candidate in mafft_candidates:
|
| 150 |
if shutil.which(candidate) or os.path.exists(candidate):
|
| 151 |
try:
|
| 152 |
+
result = subprocess.run([candidate, "--help"], capture_output=True, text=True, timeout=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
if result.returncode == 0 or "mafft" in result.stderr.lower():
|
| 154 |
mafft_available = True
|
| 155 |
mafft_cmd = candidate
|
|
|
|
| 163 |
for candidate in iqtree_candidates:
|
| 164 |
if shutil.which(candidate) or os.path.exists(candidate):
|
| 165 |
try:
|
| 166 |
+
result = subprocess.run([candidate, "--help"], capture_output=True, text=True, timeout=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
if result.returncode == 0 or "iqtree" in result.stderr.lower():
|
| 168 |
iqtree_available = True
|
| 169 |
iqtree_cmd = candidate
|
|
|
|
| 175 |
|
| 176 |
# --- Pipeline Functions ---
|
| 177 |
def phylogenetic_placement(sequence: str, mafft_cmd: str, iqtree_cmd: str):
|
| 178 |
+
query_fasta = None
|
| 179 |
try:
|
| 180 |
if len(sequence.strip()) < 100:
|
| 181 |
return False, "Sequence too short (<100 bp).", None, None
|
|
|
|
| 206 |
logger.error(f"Phylogenetic placement failed: {e}", exc_info=True)
|
| 207 |
return False, f"Error: {str(e)}", None, None
|
| 208 |
finally:
|
| 209 |
+
if query_fasta and os.path.exists(query_fasta):
|
| 210 |
try:
|
| 211 |
os.unlink(query_fasta)
|
| 212 |
+
logger.debug(f"Cleaned up {query_fasta}")
|
| 213 |
+
except Exception as e:
|
| 214 |
+
logger.warning(f"Failed to clean up {query_fasta}: {e}", exc_info=True)
|
| 215 |
|
| 216 |
def analyze_sequence_for_tree(sequence: str, matching_percentage: float):
|
| 217 |
try:
|
| 218 |
logger.debug("Starting tree analysis...")
|
| 219 |
if not analyzer:
|
| 220 |
+
logger.error("Tree analyzer not initialized")
|
| 221 |
return "❌ Tree analyzer not initialized.", None, None
|
| 222 |
+
logger.debug("Validating sequence...")
|
| 223 |
if not sequence or len(sequence.strip()) < 10:
|
| 224 |
+
logger.error("Invalid sequence: too short or empty")
|
| 225 |
return "❌ Invalid sequence.", None, None
|
| 226 |
if not (1 <= matching_percentage <= 99):
|
| 227 |
+
logger.error(f"Invalid matching percentage: {matching_percentage}")
|
| 228 |
return "❌ Matching percentage must be 1-99.", None, None
|
| 229 |
+
logger.debug("Calling find_query_sequence...")
|
| 230 |
if not analyzer.find_query_sequence(sequence):
|
| 231 |
+
logger.error("Sequence not accepted by analyzer")
|
| 232 |
return "❌ Sequence not accepted.", None, None
|
| 233 |
+
logger.debug("Calling find_similar_sequences...")
|
| 234 |
matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
|
| 235 |
if not matched_ids:
|
| 236 |
+
logger.warning(f"No similar sequences found at {matching_percentage}% threshold")
|
| 237 |
return f"❌ No similar sequences at {matching_percentage}% threshold.", None, None
|
| 238 |
+
logger.debug("Calling build_tree_structure_with_ml_safe...")
|
| 239 |
analyzer.build_tree_structure_with_ml_safe(matched_ids)
|
| 240 |
+
logger.debug("Calling create_interactive_tree...")
|
| 241 |
fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
|
| 242 |
query_id = analyzer.query_id or f"query_{int(time.time())}"
|
| 243 |
tree_html_path = os.path.join("/tmp", f'phylogenetic_tree_{query_id}.html')
|
| 244 |
logger.debug(f"Saving tree to {tree_html_path}")
|
| 245 |
fig.write_html(tree_html_path)
|
| 246 |
analyzer.matching_percentage = matching_percentage
|
| 247 |
+
logger.debug("Calling generate_detailed_report...")
|
| 248 |
report_success = analyzer.generate_detailed_report(matched_ids, actual_percentage)
|
| 249 |
report_html_path = os.path.join("/tmp", f'detailed_report_{query_id}.html') if report_success else None
|
| 250 |
+
logger.debug(f"Tree analysis completed: {len(matched_ids)} matches at {actual_percentage:.2f}%")
|
| 251 |
return f"✅ Found {len(matched_ids)} sequences at {actual_percentage:.2f}% similarity.", tree_html_path, report_html_path
|
| 252 |
except Exception as e:
|
| 253 |
logger.error(f"Tree analysis failed: {e}", exc_info=True)
|
|
|
|
| 255 |
|
| 256 |
def predict_with_keras(sequence):
|
| 257 |
try:
|
| 258 |
+
logger.debug("Starting Keras prediction...")
|
| 259 |
if not keras_model or not kmer_to_index:
|
| 260 |
+
logger.error("Keras model or kmer index not available")
|
| 261 |
return "❌ Keras model not available."
|
| 262 |
if len(sequence) < 6:
|
| 263 |
+
logger.error("Sequence too short for Keras prediction")
|
| 264 |
return "❌ Sequence too short (<6 bp)."
|
| 265 |
kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
|
| 266 |
indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
|
|
|
|
| 268 |
prediction = keras_model.predict(input_arr, verbose=0)[0]
|
| 269 |
f_gene_prob = prediction[-1]
|
| 270 |
percentage = min(100, max(0, int(f_gene_prob * 100 + 5)))
|
| 271 |
+
logger.debug(f"Keras prediction completed: {percentage}% confidence")
|
| 272 |
return f"✅ {percentage}% F gene confidence"
|
| 273 |
except Exception as e:
|
| 274 |
logger.error(f"Keras prediction failed: {e}", exc_info=True)
|
|
|
|
| 276 |
|
| 277 |
def read_fasta_file(file_obj):
|
| 278 |
try:
|
| 279 |
+
logger.debug("Reading FASTA file...")
|
| 280 |
if file_obj is None:
|
| 281 |
+
logger.error("No file object provided")
|
| 282 |
return ""
|
| 283 |
if isinstance(file_obj, str):
|
| 284 |
with open(file_obj, "r") as f:
|
|
|
|
| 287 |
content = file_obj.read().decode("utf-8")
|
| 288 |
lines = content.strip().split("\n")
|
| 289 |
seq_lines = [line.strip() for line in lines if not line.startswith(">")]
|
| 290 |
+
sequence = ''.join(seq_lines)
|
| 291 |
+
logger.debug(f"FASTA file read successfully: {len(sequence)} bp")
|
| 292 |
+
return sequence
|
| 293 |
except Exception as e:
|
| 294 |
logger.error(f"Failed to read FASTA file: {e}", exc_info=True)
|
| 295 |
return ""
|
| 296 |
|
| 297 |
def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
| 298 |
try:
|
| 299 |
+
logger.debug("Starting pipeline...")
|
| 300 |
dna_input = dna_input.upper().strip()
|
| 301 |
if not dna_input:
|
| 302 |
+
logger.error("Empty input sequence")
|
| 303 |
return "❌ Empty input", "", "", "", "", None, None, None, None, "No input", "No input", None, None
|
| 304 |
if not re.match('^[ACTGN]+$', dna_input):
|
| 305 |
dna_input = ''.join(c if c in 'ACTGN' else 'N' for c in dna_input)
|
|
|
|
| 318 |
except Exception as e:
|
| 319 |
boundary_output = f"❌ Boundary prediction error: {str(e)}"
|
| 320 |
processed_sequence = dna_input
|
| 321 |
+
logger.error(f"Boundary prediction error: {e}", exc_info=True)
|
| 322 |
else:
|
| 323 |
boundary_output = f"⚠️ Boundary model not available. Using full input: {len(dna_input)} bp"
|
| 324 |
keras_output = predict_with_keras(processed_sequence) if processed_sequence and len(processed_sequence) >= 6 else "❌ Sequence too short."
|
|
|
|
| 337 |
ml_tree_output = "❌ MAFFT or IQ-TREE not available"
|
| 338 |
except Exception as e:
|
| 339 |
ml_tree_output = f"❌ ML tree error: {str(e)}"
|
| 340 |
+
logger.error(f"ML tree error: {e}", exc_info=True)
|
| 341 |
elif build_ml_tree:
|
| 342 |
ml_tree_output = "❌ Sequence too short for placement (<100 bp)."
|
| 343 |
else:
|
|
|
|
| 365 |
simplified_ml_output = f"❌ Tree analysis error: {str(e)}"
|
| 366 |
tree_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
| 367 |
report_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
| 368 |
+
logger.error(f"Tree analysis error: {e}", exc_info=True)
|
| 369 |
else:
|
| 370 |
simplified_ml_output = "❌ Tree analyzer not available." if not analyzer else "❌ Sequence too short (<10 bp)."
|
| 371 |
tree_html_content = f"<div style='color: orange;'>{simplified_ml_output}</div>"
|
|
|
|
| 417 |
try:
|
| 418 |
os.unlink(temp_file_path)
|
| 419 |
except Exception as e:
|
| 420 |
+
logger.warning(f"Failed to delete temp file {temp_file_path}: {e}", exc_info=True)
|
| 421 |
|
| 422 |
# --- Pydantic Models ---
|
| 423 |
class AnalysisRequest(BaseModel):
|
|
|
|
| 466 |
"tree_analyzer": analyzer is not None,
|
| 467 |
"mafft_available": mafft_available,
|
| 468 |
"iqtree_available": iqtree_available
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
}
|
| 470 |
}
|
| 471 |
except Exception as e:
|
|
|
|
| 531 |
try:
|
| 532 |
os.unlink(temp_file_path)
|
| 533 |
except Exception as e:
|
| 534 |
+
logger.warning(f"Failed to clean up {temp_file_path}: {e}", exc_info=True)
|
| 535 |
|
| 536 |
@app.get("/download/{file_type}/{query_id}")
|
| 537 |
async def download_file(file_type: str, query_id: str):
|
|
|
|
| 550 |
# --- Gradio Interface ---
|
| 551 |
def create_gradio_interface():
|
| 552 |
try:
|
| 553 |
+
logger.debug("Creating Gradio interface...")
|
| 554 |
with gr.Blocks(
|
| 555 |
title="🧬 Gene Analysis Pipeline",
|
| 556 |
+
theme="default",
|
| 557 |
css="""
|
| 558 |
.gradio-container { max-width: 1200px !important; }
|
| 559 |
.status-box { padding: 10px; border-radius: 5px; margin: 5px 0; }
|
|
|
|
| 576 |
</div>
|
| 577 |
""")
|
| 578 |
with gr.Tabs():
|
| 579 |
+
with gr.TabItem("Text Input"):
|
| 580 |
with gr.Row():
|
| 581 |
with gr.Column(scale=2):
|
| 582 |
dna_input = gr.Textbox(
|
| 583 |
+
label="DNA Sequence",
|
| 584 |
+
placeholder="Enter DNA sequence (ATCG format)...",
|
| 585 |
+
lines=5
|
|
|
|
| 586 |
)
|
| 587 |
with gr.Column(scale=1):
|
| 588 |
+
similarity_score = gr.Slider(
|
| 589 |
minimum=1,
|
| 590 |
maximum=99,
|
| 591 |
+
value=95.0,
|
| 592 |
+
step=1.0,
|
| 593 |
+
label="Similarity Threshold (%)"
|
|
|
|
| 594 |
)
|
| 595 |
build_ml_tree = gr.Checkbox(
|
| 596 |
+
label="Build ML Tree",
|
| 597 |
+
value=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 598 |
)
|
| 599 |
+
analyze_btn = gr.Button("Analyze Sequence", variant="primary")
|
| 600 |
+
with gr.TabItem("File Upload"):
|
| 601 |
with gr.Row():
|
| 602 |
with gr.Column(scale=2):
|
| 603 |
file_input = gr.File(
|
| 604 |
+
label="Upload FASTA File",
|
| 605 |
+
file_types=[".fasta", ".fa", ".fas", ".txt"]
|
|
|
|
| 606 |
)
|
| 607 |
with gr.Column(scale=1):
|
| 608 |
+
file_similarity_score = gr.Slider(
|
| 609 |
minimum=1,
|
| 610 |
maximum=99,
|
| 611 |
+
value=95.0,
|
| 612 |
+
step=1.0,
|
| 613 |
+
label="Similarity Threshold (%)"
|
| 614 |
)
|
| 615 |
file_build_ml_tree = gr.Checkbox(
|
| 616 |
+
label="Build ML Tree",
|
| 617 |
value=False
|
| 618 |
)
|
| 619 |
+
analyze_file_btn = gr.Button("Analyze File", variant="primary")
|
| 620 |
+
gr.Markdown("## Analysis Results")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
with gr.Row():
|
| 622 |
with gr.Column():
|
| 623 |
+
boundary_output = gr.Textbox(label="Boundary Detection", interactive=False, lines=2)
|
| 624 |
+
keras_output = gr.Textbox(label="F Gene Validation", interactive=False, lines=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
with gr.Column():
|
| 626 |
+
ml_tree_output = gr.Textbox(label="Phylogenetic Placement", interactive=False, lines=2)
|
| 627 |
+
tree_analysis_output = gr.Textbox(label="Tree Analysis", interactive=False, lines=2)
|
| 628 |
+
summary_output = gr.Textbox(label="Summary", interactive=False, lines=8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 629 |
with gr.Row():
|
| 630 |
+
aligned_file = gr.File(label="Alignment File", visible=False)
|
| 631 |
+
tree_file = gr.File(label="Tree File", visible=False)
|
| 632 |
+
tree_html_file = gr.File(label="Simplified Tree HTML", visible=False)
|
| 633 |
+
report_html_file = gr.File(label="Detailed Report HTML", visible=False)
|
| 634 |
+
with gr.Tabs():
|
| 635 |
+
with gr.TabItem("Interactive Tree"):
|
| 636 |
+
tree_html = gr.HTML(value="No tree generated yet.")
|
| 637 |
+
with gr.TabItem("Detailed Report"):
|
| 638 |
+
report_html = gr.HTML(value="No report generated yet.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
analyze_btn.click(
|
| 640 |
+
fn=run_pipeline,
|
| 641 |
+
inputs=[dna_input, similarity_score, build_ml_tree],
|
| 642 |
outputs=[
|
| 643 |
+
boundary_output, keras_output, ml_tree_output, tree_analysis_output, summary_output,
|
| 644 |
+
aligned_file, tree_file, tree_html_file, report_html_file, tree_html, report_html
|
|
|
|
| 645 |
]
|
| 646 |
)
|
| 647 |
+
analyze_file_btn.click(
|
| 648 |
+
fn=run_pipeline_from_file,
|
| 649 |
+
inputs=[file_input, file_similarity_score, file_build_ml_tree],
|
|
|
|
| 650 |
outputs=[
|
| 651 |
+
boundary_output, keras_output, ml_tree_output, tree_analysis_output, summary_output,
|
| 652 |
+
aligned_file, tree_file, tree_html_file, report_html_file, tree_html, report_html
|
|
|
|
| 653 |
]
|
| 654 |
)
|
| 655 |
+
gr.Examples(
|
| 656 |
+
examples=[
|
| 657 |
+
["ATCG" * 100, 85.0, False],
|
| 658 |
+
["CGAT" * 100, 90.0, True]
|
| 659 |
+
],
|
| 660 |
+
inputs=[dna_input, similarity_score, build_ml_tree],
|
| 661 |
+
label="Example Sequences"
|
| 662 |
+
)
|
| 663 |
+
logger.debug("Gradio interface created successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 664 |
return iface
|
|
|
|
| 665 |
except Exception as e:
|
| 666 |
+
logger.error(f"Gradio interface creation failed: {e}", exc_info=True)
|
|
|
|
| 667 |
return gr.Interface(
|
| 668 |
+
fn=lambda x: f"Error: {str(e)}",
|
| 669 |
+
inputs=gr.Textbox(label="DNA Sequence"),
|
| 670 |
+
outputs=gr.Textbox(label="Error"),
|
| 671 |
+
title="🧬 Gene Analysis Pipeline (Error Mode)"
|
| 672 |
)
|
| 673 |
|
| 674 |
+
# --- Application Startup ---
|
| 675 |
+
def run_application():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
try:
|
| 677 |
+
logger.debug("Starting application...")
|
| 678 |
+
gradio_app = create_gradio_interface()
|
| 679 |
+
logger.debug("Mounting Gradio app to FastAPI...")
|
| 680 |
+
gradio_app = gr.mount_gradio_app(app, gradio_app, path="/gradio")
|
| 681 |
logger.info("🚀 Starting Gene Analysis Pipeline...")
|
| 682 |
+
uvicorn.run(
|
| 683 |
+
app,
|
| 684 |
+
host="0.0.0.0",
|
| 685 |
+
port=7860,
|
| 686 |
+
log_level="info"
|
| 687 |
+
)
|
| 688 |
+
except Exception as e:
|
| 689 |
+
logger.error(f"Application startup failed: {e}", exc_info=True)
|
| 690 |
+
try:
|
| 691 |
+
logger.info("🔄 Falling back to Gradio-only mode...")
|
| 692 |
+
gradio_app = create_gradio_interface()
|
| 693 |
gradio_app.launch(
|
| 694 |
server_name="0.0.0.0",
|
| 695 |
server_port=7860,
|
| 696 |
+
share=False,
|
| 697 |
+
debug=False
|
|
|
|
| 698 |
)
|
| 699 |
+
except Exception as fallback_error:
|
| 700 |
+
logger.error(f"Fallback failed: {fallback_error}", exc_info=True)
|
| 701 |
+
print("❌ Application failed to start. Check logs for details.")
|
| 702 |
+
|
| 703 |
+
# --- Main Entry Point ---
|
| 704 |
+
if __name__ == "__main__":
|
| 705 |
+
print("🧬 Gene Analysis Pipeline Starting...")
|
| 706 |
+
print("=" * 50)
|
| 707 |
+
print("🔍 Checking system components...")
|
| 708 |
+
mafft_available, iqtree_available, _, _ = check_tool_availability()
|
| 709 |
+
print(f"🤖 Boundary Model: {'✅' if boundary_model else '❌'}")
|
| 710 |
+
print(f"🧠 Keras Model: {'✅' if keras_model else '❌'}")
|
| 711 |
+
print(f"🌳 Tree Analyzer: {'✅' if analyzer else '❌'}")
|
| 712 |
+
print(f"🧬 MAFFT: {'✅' if mafft_available else '❌'}")
|
| 713 |
+
print(f"🌲 IQ-TREE: {'✅' if iqtree_available else '❌'}")
|
| 714 |
+
print("=" * 50)
|
| 715 |
+
run_application()
|