Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 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,7 +17,6 @@ from tensorflow.keras.models import load_model
|
|
| 15 |
from analyzer import PhylogeneticTreeAnalyzer
|
| 16 |
import tempfile
|
| 17 |
import shutil
|
| 18 |
-
import sys
|
| 19 |
import uuid
|
| 20 |
from pathlib import Path
|
| 21 |
from huggingface_hub import hf_hub_download
|
|
@@ -38,9 +39,9 @@ log_handler.setFormatter(log_formatter)
|
|
| 38 |
try:
|
| 39 |
file_handler = logging.FileHandler('/tmp/app.log')
|
| 40 |
file_handler.setFormatter(log_formatter)
|
| 41 |
-
logging.basicConfig(level=logging.
|
| 42 |
except Exception as e:
|
| 43 |
-
logging.basicConfig(level=logging.
|
| 44 |
logging.warning(f"Failed to set up file logging: {e}")
|
| 45 |
logger = logging.getLogger(__name__)
|
| 46 |
logger.info(f"Gradio version: {gr.__version__}")
|
|
@@ -61,7 +62,7 @@ QUERY_OUTPUT_DIR = os.path.join(BASE_DIR, "queries")
|
|
| 61 |
os.makedirs(QUERY_OUTPUT_DIR, exist_ok=True)
|
| 62 |
|
| 63 |
MODEL_REPO = "GGproject10/best_boundary_aware_model"
|
| 64 |
-
CSV_PATH = "
|
| 65 |
|
| 66 |
# Initialize models
|
| 67 |
boundary_model = None
|
|
@@ -69,7 +70,7 @@ keras_model = None
|
|
| 69 |
kmer_to_index = None
|
| 70 |
analyzer = None
|
| 71 |
|
| 72 |
-
# --- Model Loading ---
|
| 73 |
def load_models_safely():
|
| 74 |
global boundary_model, keras_model, kmer_to_index, analyzer
|
| 75 |
logger.info("🔍 Loading models...")
|
|
@@ -79,9 +80,9 @@ def load_models_safely():
|
|
| 79 |
boundary_model = EnhancedGenePredictor(boundary_path)
|
| 80 |
logger.info("✅ Boundary model loaded.")
|
| 81 |
else:
|
| 82 |
-
logger.error("❌ Boundary model file not found.")
|
| 83 |
except Exception as e:
|
| 84 |
-
logger.error(f"❌ Failed to load boundary model: {e}"
|
| 85 |
boundary_model = None
|
| 86 |
try:
|
| 87 |
keras_path = hf_hub_download(repo_id=MODEL_REPO, filename="best_model.keras", token=None)
|
|
@@ -92,9 +93,9 @@ def load_models_safely():
|
|
| 92 |
kmer_to_index = pickle.load(f)
|
| 93 |
logger.info("✅ Keras model loaded.")
|
| 94 |
else:
|
| 95 |
-
logger.error("❌ Keras model files not found.")
|
| 96 |
except Exception as e:
|
| 97 |
-
logger.error(f"❌ Failed to load Keras model: {e}"
|
| 98 |
keras_model = None
|
| 99 |
kmer_to_index = None
|
| 100 |
try:
|
|
@@ -114,7 +115,7 @@ def load_models_safely():
|
|
| 114 |
csv_loaded = True
|
| 115 |
break
|
| 116 |
except Exception as e:
|
| 117 |
-
logger.warning(f"CSV load failed for {csv_candidate}: {e}"
|
| 118 |
if not csv_loaded:
|
| 119 |
logger.error("❌ Failed to load CSV data.")
|
| 120 |
analyzer = None
|
|
@@ -125,14 +126,14 @@ def load_models_safely():
|
|
| 125 |
else:
|
| 126 |
logger.warning("⚠️ AI model training failed.")
|
| 127 |
except Exception as e:
|
| 128 |
-
logger.warning(f"⚠️ AI model training failed: {e}"
|
| 129 |
except Exception as e:
|
| 130 |
-
logger.error(f"❌ Tree analyzer initialization failed: {e}"
|
| 131 |
analyzer = None
|
| 132 |
|
| 133 |
load_models_safely()
|
| 134 |
|
| 135 |
-
# --- Tool Detection ---
|
| 136 |
def setup_binary_permissions():
|
| 137 |
for binary in [MAFFT_PATH, IQTREE_PATH]:
|
| 138 |
if os.path.exists(binary):
|
|
@@ -140,7 +141,7 @@ def setup_binary_permissions():
|
|
| 140 |
os.chmod(binary, os.stat(binary).st_mode | stat.S_IEXEC)
|
| 141 |
logger.info(f"Set executable permission on {binary}")
|
| 142 |
except Exception as e:
|
| 143 |
-
logger.warning(f"Failed to set permission on {binary}: {e}"
|
| 144 |
|
| 145 |
def check_tool_availability():
|
| 146 |
setup_binary_permissions()
|
|
@@ -176,7 +177,6 @@ def check_tool_availability():
|
|
| 176 |
|
| 177 |
# --- Pipeline Functions ---
|
| 178 |
def phylogenetic_placement(sequence: str, mafft_cmd: str, iqtree_cmd: str):
|
| 179 |
-
query_fasta = None
|
| 180 |
try:
|
| 181 |
if len(sequence.strip()) < 100:
|
| 182 |
return False, "Sequence too short (<100 bp).", None, None
|
|
@@ -207,48 +207,41 @@ def phylogenetic_placement(sequence: str, mafft_cmd: str, iqtree_cmd: str):
|
|
| 207 |
logger.error(f"Phylogenetic placement failed: {e}", exc_info=True)
|
| 208 |
return False, f"Error: {str(e)}", None, None
|
| 209 |
finally:
|
| 210 |
-
if query_fasta and os.path.exists(query_fasta):
|
| 211 |
try:
|
| 212 |
os.unlink(query_fasta)
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
logger.warning(f"Failed to clean up {query_fasta}: {e}", exc_info=True)
|
| 216 |
|
| 217 |
def analyze_sequence_for_tree(sequence: str, matching_percentage: float):
|
| 218 |
try:
|
| 219 |
logger.debug("Starting tree analysis...")
|
| 220 |
if not analyzer:
|
| 221 |
-
logger.error("Tree analyzer not initialized")
|
| 222 |
return "❌ Tree analyzer not initialized.", None, None
|
| 223 |
-
logger.debug("Validating sequence...")
|
| 224 |
if not sequence or len(sequence.strip()) < 10:
|
| 225 |
-
logger.error("Invalid sequence: too short or empty")
|
| 226 |
return "❌ Invalid sequence.", None, None
|
| 227 |
if not (1 <= matching_percentage <= 99):
|
| 228 |
-
logger.error(f"Invalid matching percentage: {matching_percentage}")
|
| 229 |
return "❌ Matching percentage must be 1-99.", None, None
|
| 230 |
-
logger.debug("
|
| 231 |
if not analyzer.find_query_sequence(sequence):
|
| 232 |
-
logger.error("Sequence not accepted by analyzer")
|
| 233 |
return "❌ Sequence not accepted.", None, None
|
| 234 |
-
logger.debug("
|
| 235 |
matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
|
| 236 |
if not matched_ids:
|
| 237 |
-
logger.warning(f"No similar sequences found at {matching_percentage}% threshold")
|
| 238 |
return f"❌ No similar sequences at {matching_percentage}% threshold.", None, None
|
| 239 |
-
logger.debug("
|
| 240 |
analyzer.build_tree_structure_with_ml_safe(matched_ids)
|
| 241 |
-
logger.debug("
|
| 242 |
fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
|
| 243 |
query_id = analyzer.query_id or f"query_{int(time.time())}"
|
| 244 |
tree_html_path = os.path.join("/tmp", f'phylogenetic_tree_{query_id}.html')
|
| 245 |
logger.debug(f"Saving tree to {tree_html_path}")
|
| 246 |
fig.write_html(tree_html_path)
|
| 247 |
analyzer.matching_percentage = matching_percentage
|
| 248 |
-
logger.debug("
|
| 249 |
report_success = analyzer.generate_detailed_report(matched_ids, actual_percentage)
|
| 250 |
report_html_path = os.path.join("/tmp", f'detailed_report_{query_id}.html') if report_success else None
|
| 251 |
-
logger.debug(f"Tree analysis completed: {len(matched_ids)} matches
|
| 252 |
return f"✅ Found {len(matched_ids)} sequences at {actual_percentage:.2f}% similarity.", tree_html_path, report_html_path
|
| 253 |
except Exception as e:
|
| 254 |
logger.error(f"Tree analysis failed: {e}", exc_info=True)
|
|
@@ -256,12 +249,9 @@ def analyze_sequence_for_tree(sequence: str, matching_percentage: float):
|
|
| 256 |
|
| 257 |
def predict_with_keras(sequence):
|
| 258 |
try:
|
| 259 |
-
logger.debug("Starting Keras prediction...")
|
| 260 |
if not keras_model or not kmer_to_index:
|
| 261 |
-
logger.error("Keras model or kmer index not available")
|
| 262 |
return "❌ Keras model not available."
|
| 263 |
if len(sequence) < 6:
|
| 264 |
-
logger.error("Sequence too short for Keras prediction")
|
| 265 |
return "❌ Sequence too short (<6 bp)."
|
| 266 |
kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
|
| 267 |
indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
|
|
@@ -269,7 +259,6 @@ def predict_with_keras(sequence):
|
|
| 269 |
prediction = keras_model.predict(input_arr, verbose=0)[0]
|
| 270 |
f_gene_prob = prediction[-1]
|
| 271 |
percentage = min(100, max(0, int(f_gene_prob * 100 + 5)))
|
| 272 |
-
logger.debug(f"Keras prediction completed: {percentage}% confidence")
|
| 273 |
return f"✅ {percentage}% F gene confidence"
|
| 274 |
except Exception as e:
|
| 275 |
logger.error(f"Keras prediction failed: {e}", exc_info=True)
|
|
@@ -277,9 +266,7 @@ def predict_with_keras(sequence):
|
|
| 277 |
|
| 278 |
def read_fasta_file(file_obj):
|
| 279 |
try:
|
| 280 |
-
logger.debug("Reading FASTA file...")
|
| 281 |
if file_obj is None:
|
| 282 |
-
logger.error("No file object provided")
|
| 283 |
return ""
|
| 284 |
if isinstance(file_obj, str):
|
| 285 |
with open(file_obj, "r") as f:
|
|
@@ -288,19 +275,15 @@ def read_fasta_file(file_obj):
|
|
| 288 |
content = file_obj.read().decode("utf-8")
|
| 289 |
lines = content.strip().split("\n")
|
| 290 |
seq_lines = [line.strip() for line in lines if not line.startswith(">")]
|
| 291 |
-
|
| 292 |
-
logger.debug(f"FASTA file read successfully: {len(sequence)} bp")
|
| 293 |
-
return sequence
|
| 294 |
except Exception as e:
|
| 295 |
logger.error(f"Failed to read FASTA file: {e}", exc_info=True)
|
| 296 |
return ""
|
| 297 |
|
| 298 |
def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
| 299 |
try:
|
| 300 |
-
logger.debug("Starting pipeline...")
|
| 301 |
dna_input = dna_input.upper().strip()
|
| 302 |
if not dna_input:
|
| 303 |
-
logger.error("Empty input sequence")
|
| 304 |
return "❌ Empty input", "", "", "", "", None, None, None, None, "No input", "No input", None, None
|
| 305 |
if not re.match('^[ACTGN]+$', dna_input):
|
| 306 |
dna_input = ''.join(c if c in 'ACTGN' else 'N' for c in dna_input)
|
|
@@ -319,7 +302,6 @@ def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
|
| 319 |
except Exception as e:
|
| 320 |
boundary_output = f"❌ Boundary prediction error: {str(e)}"
|
| 321 |
processed_sequence = dna_input
|
| 322 |
-
logger.error(f"Boundary prediction error: {e}", exc_info=True)
|
| 323 |
else:
|
| 324 |
boundary_output = f"⚠️ Boundary model not available. Using full input: {len(dna_input)} bp"
|
| 325 |
keras_output = predict_with_keras(processed_sequence) if processed_sequence and len(processed_sequence) >= 6 else "❌ Sequence too short."
|
|
@@ -338,7 +320,6 @@ def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
|
| 338 |
ml_tree_output = "❌ MAFFT or IQ-TREE not available"
|
| 339 |
except Exception as e:
|
| 340 |
ml_tree_output = f"❌ ML tree error: {str(e)}"
|
| 341 |
-
logger.error(f"ML tree error: {e}", exc_info=True)
|
| 342 |
elif build_ml_tree:
|
| 343 |
ml_tree_output = "❌ Sequence too short for placement (<100 bp)."
|
| 344 |
else:
|
|
@@ -366,7 +347,6 @@ def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
|
| 366 |
simplified_ml_output = f"❌ Tree analysis error: {str(e)}"
|
| 367 |
tree_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
| 368 |
report_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
| 369 |
-
logger.error(f"Tree analysis error: {e}", exc_info=True)
|
| 370 |
else:
|
| 371 |
simplified_ml_output = "❌ Tree analyzer not available." if not analyzer else "❌ Sequence too short (<10 bp)."
|
| 372 |
tree_html_content = f"<div style='color: orange;'>{simplified_ml_output}</div>"
|
|
@@ -391,7 +371,7 @@ Tree Analysis: {'✅ OK' if 'Found' in simplified_ml_output else '❌ Failed'}
|
|
| 391 |
error_msg = f"❌ Pipeline Error: {str(e)}"
|
| 392 |
return error_msg, "", "", "", "", None, None, None, None, error_msg, error_msg, None, None
|
| 393 |
|
| 394 |
-
async def run_pipeline_from_file(fasta_file_obj, similarity_score,
|
| 395 |
temp_file_path = None
|
| 396 |
try:
|
| 397 |
if fasta_file_obj is None:
|
|
@@ -418,7 +398,7 @@ async def run_pipeline_from_file(fasta_file_obj, similarity_score, build_ml_tree
|
|
| 418 |
try:
|
| 419 |
os.unlink(temp_file_path)
|
| 420 |
except Exception as e:
|
| 421 |
-
logger.warning(f"Failed to delete temp file {temp_file_path}: {e}"
|
| 422 |
|
| 423 |
# --- Pydantic Models ---
|
| 424 |
class AnalysisRequest(BaseModel):
|
|
@@ -467,6 +447,10 @@ async def health_check():
|
|
| 467 |
"tree_analyzer": analyzer is not None,
|
| 468 |
"mafft_available": mafft_available,
|
| 469 |
"iqtree_available": iqtree_available
|
|
|
|
|
|
|
|
|
|
|
|
|
| 470 |
}
|
| 471 |
}
|
| 472 |
except Exception as e:
|
|
@@ -532,7 +516,7 @@ async def analyze_file(
|
|
| 532 |
try:
|
| 533 |
os.unlink(temp_file_path)
|
| 534 |
except Exception as e:
|
| 535 |
-
logger.warning(f"Failed to clean up {temp_file_path}: {e}"
|
| 536 |
|
| 537 |
@app.get("/download/{file_type}/{query_id}")
|
| 538 |
async def download_file(file_type: str, query_id: str):
|
|
@@ -551,10 +535,9 @@ async def download_file(file_type: str, query_id: str):
|
|
| 551 |
# --- Gradio Interface ---
|
| 552 |
def create_gradio_interface():
|
| 553 |
try:
|
| 554 |
-
logger.debug("Creating Gradio interface...")
|
| 555 |
with gr.Blocks(
|
| 556 |
title="🧬 Gene Analysis Pipeline",
|
| 557 |
-
theme=
|
| 558 |
css="""
|
| 559 |
.gradio-container { max-width: 1200px !important; }
|
| 560 |
.status-box { padding: 10px; border-radius: 5px; margin: 5px 0; }
|
|
@@ -577,153 +560,114 @@ def create_gradio_interface():
|
|
| 577 |
</div>
|
| 578 |
""")
|
| 579 |
with gr.Tabs():
|
| 580 |
-
with gr.TabItem("Text Input"):
|
| 581 |
with gr.Row():
|
| 582 |
with gr.Column(scale=2):
|
| 583 |
dna_input = gr.Textbox(
|
| 584 |
-
label="DNA Sequence",
|
| 585 |
placeholder="Enter DNA sequence (ATCG format)...",
|
| 586 |
lines=5
|
| 587 |
)
|
| 588 |
with gr.Column(scale=1):
|
| 589 |
-
|
| 590 |
minimum=1,
|
| 591 |
maximum=99,
|
| 592 |
-
value=95,
|
| 593 |
-
step=1,
|
| 594 |
-
label="Similarity Threshold (%)"
|
| 595 |
)
|
| 596 |
build_ml_tree = gr.Checkbox(
|
| 597 |
-
label="Build ML Tree",
|
| 598 |
value=False
|
| 599 |
)
|
| 600 |
-
analyze_btn = gr.Button("Analyze Sequence", variant="primary")
|
| 601 |
-
with gr.TabItem("File Upload"):
|
| 602 |
with gr.Row():
|
| 603 |
with gr.Column(scale=2):
|
| 604 |
file_input = gr.File(
|
| 605 |
-
label="Upload FASTA File",
|
| 606 |
file_types=[".fasta", ".fa", ".fas", ".txt"]
|
| 607 |
)
|
| 608 |
with gr.Column(scale=1):
|
| 609 |
-
|
| 610 |
minimum=1,
|
| 611 |
maximum=99,
|
| 612 |
-
value=95,
|
| 613 |
-
step=1,
|
| 614 |
-
label="Similarity Threshold (%)"
|
| 615 |
)
|
| 616 |
file_build_ml_tree = gr.Checkbox(
|
| 617 |
-
label="Build ML Tree",
|
| 618 |
value=False
|
| 619 |
)
|
| 620 |
-
|
| 621 |
-
gr.Markdown("## Analysis Results")
|
| 622 |
with gr.Row():
|
| 623 |
with gr.Column():
|
| 624 |
-
boundary_output = gr.Textbox(label="Boundary
|
| 625 |
-
keras_output = gr.Textbox(label="F Gene Validation", interactive=False, lines=2)
|
| 626 |
with gr.Column():
|
| 627 |
-
ml_tree_output = gr.Textbox(label="Phylogenetic Placement", interactive=False, lines=2)
|
| 628 |
-
tree_analysis_output = gr.Textbox(label="Tree Analysis", interactive=False, lines=2)
|
| 629 |
-
summary_output = gr.Textbox(label="Summary", interactive=False, lines=8)
|
| 630 |
-
with gr.Tabs():
|
| 631 |
-
with gr.TabItem("Phylogenetic Tree"):
|
| 632 |
-
tree_html = gr.HTML(value="Run analysis to see phylogenetic tree")
|
| 633 |
-
with gr.TabItem("Detailed Report"):
|
| 634 |
-
report_html = gr.HTML(value="Run analysis to see detailed report")
|
| 635 |
with gr.Row():
|
| 636 |
-
aligned_file = gr.File(label="
|
| 637 |
-
tree_file = gr.File(label="
|
| 638 |
-
tree_html_file = gr.File(label="
|
| 639 |
-
report_html_file = gr.File(label="
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
"<div style='color: red;'>No input provided</div>"
|
| 647 |
-
)
|
| 648 |
-
results = run_pipeline(dna_seq, similarity, build_tree)
|
| 649 |
-
return (
|
| 650 |
-
results[0], results[1], results[2], results[3], results[4],
|
| 651 |
-
results[5], results[6], results[11], results[12],
|
| 652 |
-
results[9], results[10]
|
| 653 |
-
)
|
| 654 |
-
def process_file_input(file_path, similarity, build_tree):
|
| 655 |
-
if not file_path:
|
| 656 |
-
return (
|
| 657 |
-
"❌ Please upload a file", "", "", "", "",
|
| 658 |
-
None, None, None, None,
|
| 659 |
-
"<div style='color: red;'>No file provided</div>",
|
| 660 |
-
"<div style='color: red;'>No file provided</div>"
|
| 661 |
-
)
|
| 662 |
-
sequence = read_fasta_file(file_path)
|
| 663 |
-
if not sequence:
|
| 664 |
-
return (
|
| 665 |
-
"❌ Failed to read sequence from file", "", "", "", "",
|
| 666 |
-
None, None, None, None,
|
| 667 |
-
"<div style='color: red;'>Invalid file format</div>",
|
| 668 |
-
"<div style='color: red;'>Invalid file format</div>"
|
| 669 |
-
)
|
| 670 |
-
results = run_pipeline(sequence, similarity, build_tree)
|
| 671 |
-
return (
|
| 672 |
-
results[0], results[1], results[2], results[3], results[4],
|
| 673 |
-
results[5], results[6], results[11], results[12],
|
| 674 |
-
results[9], results[10]
|
| 675 |
-
)
|
| 676 |
analyze_btn.click(
|
| 677 |
-
fn=
|
| 678 |
-
inputs=[dna_input,
|
| 679 |
outputs=[
|
| 680 |
-
boundary_output, keras_output, ml_tree_output,
|
| 681 |
-
|
| 682 |
-
aligned_file, tree_file, tree_html_file, report_html_file,
|
| 683 |
-
tree_html, report_html
|
| 684 |
]
|
| 685 |
)
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
|
|
|
| 689 |
outputs=[
|
| 690 |
-
boundary_output, keras_output, ml_tree_output,
|
| 691 |
-
|
| 692 |
-
aligned_file, tree_file, tree_html_file, report_html_file,
|
| 693 |
-
tree_html, report_html
|
| 694 |
]
|
| 695 |
)
|
|
|
|
| 696 |
gr.Examples(
|
| 697 |
examples=[
|
| 698 |
-
["
|
| 699 |
-
["
|
| 700 |
],
|
| 701 |
-
inputs=[dna_input,
|
| 702 |
label="Example Sequences"
|
| 703 |
)
|
| 704 |
-
|
| 705 |
return iface
|
| 706 |
except Exception as e:
|
| 707 |
-
logger.error(f"
|
| 708 |
return gr.Interface(
|
| 709 |
-
fn=lambda x: f"
|
| 710 |
-
inputs=gr.Textbox(label="
|
| 711 |
-
outputs=gr.Textbox(label="
|
| 712 |
-
title="🧬 Gene Analysis Pipeline
|
| 713 |
)
|
| 714 |
|
| 715 |
# --- Application Startup ---
|
| 716 |
def run_application():
|
| 717 |
try:
|
| 718 |
-
logger.debug("Starting application...")
|
| 719 |
gradio_app = create_gradio_interface()
|
| 720 |
-
logger.debug("Mounting Gradio app to FastAPI...")
|
| 721 |
gradio_app = gr.mount_gradio_app(app, gradio_app, path="/gradio")
|
| 722 |
logger.info("🚀 Starting Gene Analysis Pipeline...")
|
| 723 |
uvicorn.run(
|
| 724 |
app,
|
| 725 |
host="0.0.0.0",
|
| 726 |
-
port=
|
| 727 |
log_level="info"
|
| 728 |
)
|
| 729 |
except Exception as e:
|
|
@@ -733,24 +677,24 @@ def run_application():
|
|
| 733 |
gradio_app = create_gradio_interface()
|
| 734 |
gradio_app.launch(
|
| 735 |
server_name="0.0.0.0",
|
| 736 |
-
server_port=
|
| 737 |
-
share=
|
| 738 |
-
|
| 739 |
)
|
| 740 |
except Exception as fallback_error:
|
| 741 |
logger.error(f"Fallback failed: {fallback_error}", exc_info=True)
|
| 742 |
-
|
| 743 |
|
| 744 |
# --- Main Entry Point ---
|
| 745 |
if __name__ == "__main__":
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
mafft_available, iqtree_available, _, _ = check_tool_availability()
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
run_application()
|
|
|
|
| 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 |
from analyzer import PhylogeneticTreeAnalyzer
|
| 18 |
import tempfile
|
| 19 |
import shutil
|
|
|
|
| 20 |
import uuid
|
| 21 |
from pathlib import Path
|
| 22 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 39 |
try:
|
| 40 |
file_handler = logging.FileHandler('/tmp/app.log')
|
| 41 |
file_handler.setFormatter(log_formatter)
|
| 42 |
+
logging.basicConfig(level=logging.INFO, handlers=[log_handler, file_handler])
|
| 43 |
except Exception as e:
|
| 44 |
+
logging.basicConfig(level=logging.INFO, handlers=[log_handler])
|
| 45 |
logging.warning(f"Failed to set up file logging: {e}")
|
| 46 |
logger = logging.getLogger(__name__)
|
| 47 |
logger.info(f"Gradio version: {gr.__version__}")
|
|
|
|
| 62 |
os.makedirs(QUERY_OUTPUT_DIR, exist_ok=True)
|
| 63 |
|
| 64 |
MODEL_REPO = "GGproject10/best_boundary_aware_model"
|
| 65 |
+
CSV_PATH = "f cleaned.csv"
|
| 66 |
|
| 67 |
# Initialize models
|
| 68 |
boundary_model = None
|
|
|
|
| 70 |
kmer_to_index = None
|
| 71 |
analyzer = None
|
| 72 |
|
| 73 |
+
# --- Model Loading (from Script 2) ---
|
| 74 |
def load_models_safely():
|
| 75 |
global boundary_model, keras_model, kmer_to_index, analyzer
|
| 76 |
logger.info("🔍 Loading models...")
|
|
|
|
| 80 |
boundary_model = EnhancedGenePredictor(boundary_path)
|
| 81 |
logger.info("✅ Boundary model loaded.")
|
| 82 |
else:
|
| 83 |
+
logger.error(f"❌ Boundary model file not found.")
|
| 84 |
except Exception as e:
|
| 85 |
+
logger.error(f"❌ Failed to load boundary model: {e}")
|
| 86 |
boundary_model = None
|
| 87 |
try:
|
| 88 |
keras_path = hf_hub_download(repo_id=MODEL_REPO, filename="best_model.keras", token=None)
|
|
|
|
| 93 |
kmer_to_index = pickle.load(f)
|
| 94 |
logger.info("✅ Keras model loaded.")
|
| 95 |
else:
|
| 96 |
+
logger.error(f"❌ Keras model files not found.")
|
| 97 |
except Exception as e:
|
| 98 |
+
logger.error(f"❌ Failed to load Keras model: {e}")
|
| 99 |
keras_model = None
|
| 100 |
kmer_to_index = None
|
| 101 |
try:
|
|
|
|
| 115 |
csv_loaded = True
|
| 116 |
break
|
| 117 |
except Exception as e:
|
| 118 |
+
logger.warning(f"CSV load failed for {csv_candidate}: {e}")
|
| 119 |
if not csv_loaded:
|
| 120 |
logger.error("❌ Failed to load CSV data.")
|
| 121 |
analyzer = None
|
|
|
|
| 126 |
else:
|
| 127 |
logger.warning("⚠️ AI model training failed.")
|
| 128 |
except Exception as e:
|
| 129 |
+
logger.warning(f"⚠️ AI model training failed: {e}")
|
| 130 |
except Exception as e:
|
| 131 |
+
logger.error(f"❌ Tree analyzer initialization failed: {e}")
|
| 132 |
analyzer = None
|
| 133 |
|
| 134 |
load_models_safely()
|
| 135 |
|
| 136 |
+
# --- Tool Detection (from Script 2) ---
|
| 137 |
def setup_binary_permissions():
|
| 138 |
for binary in [MAFFT_PATH, IQTREE_PATH]:
|
| 139 |
if os.path.exists(binary):
|
|
|
|
| 141 |
os.chmod(binary, os.stat(binary).st_mode | stat.S_IEXEC)
|
| 142 |
logger.info(f"Set executable permission on {binary}")
|
| 143 |
except Exception as e:
|
| 144 |
+
logger.warning(f"Failed to set permission on {binary}: {e}")
|
| 145 |
|
| 146 |
def check_tool_availability():
|
| 147 |
setup_binary_permissions()
|
|
|
|
| 177 |
|
| 178 |
# --- Pipeline Functions ---
|
| 179 |
def phylogenetic_placement(sequence: str, mafft_cmd: str, iqtree_cmd: str):
|
|
|
|
| 180 |
try:
|
| 181 |
if len(sequence.strip()) < 100:
|
| 182 |
return False, "Sequence too short (<100 bp).", None, None
|
|
|
|
| 207 |
logger.error(f"Phylogenetic placement failed: {e}", exc_info=True)
|
| 208 |
return False, f"Error: {str(e)}", None, None
|
| 209 |
finally:
|
| 210 |
+
if 'query_fasta' in locals() and os.path.exists(query_fasta):
|
| 211 |
try:
|
| 212 |
os.unlink(query_fasta)
|
| 213 |
+
except Exception as e: # Fixed bare 'except'
|
| 214 |
+
logger.warning(f"Failed to clean up {query_fasta}: {e}")
|
|
|
|
| 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 |
return "❌ Tree analyzer not initialized.", None, None
|
|
|
|
| 221 |
if not sequence or len(sequence.strip()) < 10:
|
|
|
|
| 222 |
return "❌ Invalid sequence.", None, None
|
| 223 |
if not (1 <= matching_percentage <= 99):
|
|
|
|
| 224 |
return "❌ Matching percentage must be 1-99.", None, None
|
| 225 |
+
logger.debug("Finding query sequence...")
|
| 226 |
if not analyzer.find_query_sequence(sequence):
|
|
|
|
| 227 |
return "❌ Sequence not accepted.", None, None
|
| 228 |
+
logger.debug("Finding similar sequences...")
|
| 229 |
matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
|
| 230 |
if not matched_ids:
|
|
|
|
| 231 |
return f"❌ No similar sequences at {matching_percentage}% threshold.", None, None
|
| 232 |
+
logger.debug("Building tree structure...")
|
| 233 |
analyzer.build_tree_structure_with_ml_safe(matched_ids)
|
| 234 |
+
logger.debug("Creating interactive tree...")
|
| 235 |
fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
|
| 236 |
query_id = analyzer.query_id or f"query_{int(time.time())}"
|
| 237 |
tree_html_path = os.path.join("/tmp", f'phylogenetic_tree_{query_id}.html')
|
| 238 |
logger.debug(f"Saving tree to {tree_html_path}")
|
| 239 |
fig.write_html(tree_html_path)
|
| 240 |
analyzer.matching_percentage = matching_percentage
|
| 241 |
+
logger.debug("Generating detailed report...")
|
| 242 |
report_success = analyzer.generate_detailed_report(matched_ids, actual_percentage)
|
| 243 |
report_html_path = os.path.join("/tmp", f'detailed_report_{query_id}.html') if report_success else None
|
| 244 |
+
logger.debug(f"Tree analysis completed: {len(matched_ids)} matches")
|
| 245 |
return f"✅ Found {len(matched_ids)} sequences at {actual_percentage:.2f}% similarity.", tree_html_path, report_html_path
|
| 246 |
except Exception as e:
|
| 247 |
logger.error(f"Tree analysis failed: {e}", exc_info=True)
|
|
|
|
| 249 |
|
| 250 |
def predict_with_keras(sequence):
|
| 251 |
try:
|
|
|
|
| 252 |
if not keras_model or not kmer_to_index:
|
|
|
|
| 253 |
return "❌ Keras model not available."
|
| 254 |
if len(sequence) < 6:
|
|
|
|
| 255 |
return "❌ Sequence too short (<6 bp)."
|
| 256 |
kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
|
| 257 |
indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
|
|
|
|
| 259 |
prediction = keras_model.predict(input_arr, verbose=0)[0]
|
| 260 |
f_gene_prob = prediction[-1]
|
| 261 |
percentage = min(100, max(0, int(f_gene_prob * 100 + 5)))
|
|
|
|
| 262 |
return f"✅ {percentage}% F gene confidence"
|
| 263 |
except Exception as e:
|
| 264 |
logger.error(f"Keras prediction failed: {e}", exc_info=True)
|
|
|
|
| 266 |
|
| 267 |
def read_fasta_file(file_obj):
|
| 268 |
try:
|
|
|
|
| 269 |
if file_obj is None:
|
|
|
|
| 270 |
return ""
|
| 271 |
if isinstance(file_obj, str):
|
| 272 |
with open(file_obj, "r") as f:
|
|
|
|
| 275 |
content = file_obj.read().decode("utf-8")
|
| 276 |
lines = content.strip().split("\n")
|
| 277 |
seq_lines = [line.strip() for line in lines if not line.startswith(">")]
|
| 278 |
+
return ''.join(seq_lines)
|
|
|
|
|
|
|
| 279 |
except Exception as e:
|
| 280 |
logger.error(f"Failed to read FASTA file: {e}", exc_info=True)
|
| 281 |
return ""
|
| 282 |
|
| 283 |
def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
|
| 284 |
try:
|
|
|
|
| 285 |
dna_input = dna_input.upper().strip()
|
| 286 |
if not dna_input:
|
|
|
|
| 287 |
return "❌ Empty input", "", "", "", "", None, None, None, None, "No input", "No input", None, None
|
| 288 |
if not re.match('^[ACTGN]+$', dna_input):
|
| 289 |
dna_input = ''.join(c if c in 'ACTGN' else 'N' for c in dna_input)
|
|
|
|
| 302 |
except Exception as e:
|
| 303 |
boundary_output = f"❌ Boundary prediction error: {str(e)}"
|
| 304 |
processed_sequence = dna_input
|
|
|
|
| 305 |
else:
|
| 306 |
boundary_output = f"⚠️ Boundary model not available. Using full input: {len(dna_input)} bp"
|
| 307 |
keras_output = predict_with_keras(processed_sequence) if processed_sequence and len(processed_sequence) >= 6 else "❌ Sequence too short."
|
|
|
|
| 320 |
ml_tree_output = "❌ MAFFT or IQ-TREE not available"
|
| 321 |
except Exception as e:
|
| 322 |
ml_tree_output = f"❌ ML tree error: {str(e)}"
|
|
|
|
| 323 |
elif build_ml_tree:
|
| 324 |
ml_tree_output = "❌ Sequence too short for placement (<100 bp)."
|
| 325 |
else:
|
|
|
|
| 347 |
simplified_ml_output = f"❌ Tree analysis error: {str(e)}"
|
| 348 |
tree_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
| 349 |
report_html_content = f"<div style='color: red;'>{simplified_ml_output}</div>"
|
|
|
|
| 350 |
else:
|
| 351 |
simplified_ml_output = "❌ Tree analyzer not available." if not analyzer else "❌ Sequence too short (<10 bp)."
|
| 352 |
tree_html_content = f"<div style='color: orange;'>{simplified_ml_output}</div>"
|
|
|
|
| 371 |
error_msg = f"❌ Pipeline Error: {str(e)}"
|
| 372 |
return error_msg, "", "", "", "", None, None, None, None, error_msg, error_msg, None, None
|
| 373 |
|
| 374 |
+
async def run_pipeline_from_file(fasta_file_obj, similarity_score, build_ml_file):
|
| 375 |
temp_file_path = None
|
| 376 |
try:
|
| 377 |
if fasta_file_obj is None:
|
|
|
|
| 398 |
try:
|
| 399 |
os.unlink(temp_file_path)
|
| 400 |
except Exception as e:
|
| 401 |
+
logger.warning(f"Failed to delete temp file {temp_file_path}: {e}")
|
| 402 |
|
| 403 |
# --- Pydantic Models ---
|
| 404 |
class AnalysisRequest(BaseModel):
|
|
|
|
| 447 |
"tree_analyzer": analyzer is not None,
|
| 448 |
"mafft_available": mafft_available,
|
| 449 |
"iqtree_available": iqtree_available
|
| 450 |
+
},
|
| 451 |
+
"paths": {
|
| 452 |
+
"base_dir": BASE_DIR,
|
| 453 |
+
"query_output_dir": QUERY_OUTPUT_DIR
|
| 454 |
}
|
| 455 |
}
|
| 456 |
except Exception as e:
|
|
|
|
| 516 |
try:
|
| 517 |
os.unlink(temp_file_path)
|
| 518 |
except Exception as e:
|
| 519 |
+
logger.warning(f"Failed to clean up {temp_file_path}: {e}")
|
| 520 |
|
| 521 |
@app.get("/download/{file_type}/{query_id}")
|
| 522 |
async def download_file(file_type: str, query_id: str):
|
|
|
|
| 535 |
# --- Gradio Interface ---
|
| 536 |
def create_gradio_interface():
|
| 537 |
try:
|
|
|
|
| 538 |
with gr.Blocks(
|
| 539 |
title="🧬 Gene Analysis Pipeline",
|
| 540 |
+
theme=gr.themes.Soft(),
|
| 541 |
css="""
|
| 542 |
.gradio-container { max-width: 1200px !important; }
|
| 543 |
.status-box { padding: 10px; border-radius: 5px; margin: 5px 0; }
|
|
|
|
| 560 |
</div>
|
| 561 |
""")
|
| 562 |
with gr.Tabs():
|
| 563 |
+
with gr.TabItem("📝 Text Input"):
|
| 564 |
with gr.Row():
|
| 565 |
with gr.Column(scale=2):
|
| 566 |
dna_input = gr.Textbox(
|
| 567 |
+
label="🧬 DNA Sequence",
|
| 568 |
placeholder="Enter DNA sequence (ATCG format)...",
|
| 569 |
lines=5
|
| 570 |
)
|
| 571 |
with gr.Column(scale=1):
|
| 572 |
+
similarity_score = gr.Slider(
|
| 573 |
minimum=1,
|
| 574 |
maximum=99,
|
| 575 |
+
value=95.0,
|
| 576 |
+
step=1.0,
|
| 577 |
+
label="🎯 Similarity Threshold (%)"
|
| 578 |
)
|
| 579 |
build_ml_tree = gr.Checkbox(
|
| 580 |
+
label="🌲 Build ML Tree",
|
| 581 |
value=False
|
| 582 |
)
|
| 583 |
+
analyze_btn = gr.Button("🔬 Analyze Sequence", variant="primary")
|
| 584 |
+
with gr.TabItem("📁 File Upload"):
|
| 585 |
with gr.Row():
|
| 586 |
with gr.Column(scale=2):
|
| 587 |
file_input = gr.File(
|
| 588 |
+
label="📄 Upload FASTA File",
|
| 589 |
file_types=[".fasta", ".fa", ".fas", ".txt"]
|
| 590 |
)
|
| 591 |
with gr.Column(scale=1):
|
| 592 |
+
file_similarity_score = gr.Slider(
|
| 593 |
minimum=1,
|
| 594 |
maximum=99,
|
| 595 |
+
value=95.0,
|
| 596 |
+
step=1.0,
|
| 597 |
+
label="🎯 Similarity Threshold (%)"
|
| 598 |
)
|
| 599 |
file_build_ml_tree = gr.Checkbox(
|
| 600 |
+
label="🌲 Build ML Tree",
|
| 601 |
value=False
|
| 602 |
)
|
| 603 |
+
analyze_file_btn = gr.Button("🔬 Analyze File", variant="primary")
|
| 604 |
+
gr.Markdown("## 📊 Analysis Results")
|
| 605 |
with gr.Row():
|
| 606 |
with gr.Column():
|
| 607 |
+
boundary_output = gr.Textbox(label="🎯 Boundary Detection", interactive=False, lines=2)
|
| 608 |
+
keras_output = gr.Textbox(label="🧠 F Gene Validation", interactive=False, lines=2)
|
| 609 |
with gr.Column():
|
| 610 |
+
ml_tree_output = gr.Textbox(label="🌲 Phylogenetic Placement", interactive=False, lines=2)
|
| 611 |
+
tree_analysis_output = gr.Textbox(label="🌳 Tree Analysis", interactive=False, lines=2)
|
| 612 |
+
summary_output = gr.Textbox(label="📋 Summary", interactive=False, lines=8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 613 |
with gr.Row():
|
| 614 |
+
aligned_file = gr.File(label="📄 Alignment File", visible=False)
|
| 615 |
+
tree_file = gr.File(label="🌲 Tree File", visible=False)
|
| 616 |
+
tree_html_file = gr.File(label="🌳 Simplified Tree HTML", visible=False)
|
| 617 |
+
report_html_file = gr.File(label="📊 Detailed Report HTML", visible=False)
|
| 618 |
+
with gr.Tabs():
|
| 619 |
+
with gr.TabItem("🌳 Interactive Tree"):
|
| 620 |
+
tree_html = gr.HTML(value="<div style='text-align: center; color: #666; padding: 20px;'>No tree generated yet.</div>")
|
| 621 |
+
with gr.TabItem("📊 Detailed Report"):
|
| 622 |
+
report_html = gr.HTML(value="<div style='text-align: center; color: #666; padding: 20px;'>No report generated yet.</div>")
|
| 623 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 624 |
analyze_btn.click(
|
| 625 |
+
fn=run_pipeline,
|
| 626 |
+
inputs=[dna_input, similarity_score, build_ml_tree],
|
| 627 |
outputs=[
|
| 628 |
+
boundary_output, keras_output, ml_tree_output, tree_analysis_output, summary_output,
|
| 629 |
+
aligned_file, tree_file, tree_html_file, report_html_file, tree_html, report_html
|
|
|
|
|
|
|
| 630 |
]
|
| 631 |
)
|
| 632 |
+
|
| 633 |
+
analyze_file_btn.click(
|
| 634 |
+
fn=run_pipeline_from_file,
|
| 635 |
+
inputs=[file_input, file_similarity_score, file_build_ml_tree],
|
| 636 |
outputs=[
|
| 637 |
+
boundary_output, keras_output, ml_tree_output, tree_analysis_output, summary_output,
|
| 638 |
+
aligned_file, tree_file, tree_html_file, report_html_file, tree_html, report_html
|
|
|
|
|
|
|
| 639 |
]
|
| 640 |
)
|
| 641 |
+
|
| 642 |
gr.Examples(
|
| 643 |
examples=[
|
| 644 |
+
["ATCG" * 100, 85.0, False],
|
| 645 |
+
["CGAT" * 100, 90.0, True]
|
| 646 |
],
|
| 647 |
+
inputs=[dna_input, similarity_score, build_ml_tree],
|
| 648 |
label="Example Sequences"
|
| 649 |
)
|
| 650 |
+
|
| 651 |
return iface
|
| 652 |
except Exception as e:
|
| 653 |
+
logger.error(f"Gradio interface creation failed: {e}", exc_info=True)
|
| 654 |
return gr.Interface(
|
| 655 |
+
fn=lambda x: f"Error: {str(e)}",
|
| 656 |
+
inputs=gr.Textbox(label="DNA Sequence"),
|
| 657 |
+
outputs=gr.Textbox(label="Error"),
|
| 658 |
+
title="🧬 Gene Analysis Pipeline (Error Mode)"
|
| 659 |
)
|
| 660 |
|
| 661 |
# --- Application Startup ---
|
| 662 |
def run_application():
|
| 663 |
try:
|
|
|
|
| 664 |
gradio_app = create_gradio_interface()
|
|
|
|
| 665 |
gradio_app = gr.mount_gradio_app(app, gradio_app, path="/gradio")
|
| 666 |
logger.info("🚀 Starting Gene Analysis Pipeline...")
|
| 667 |
uvicorn.run(
|
| 668 |
app,
|
| 669 |
host="0.0.0.0",
|
| 670 |
+
port=7860,
|
| 671 |
log_level="info"
|
| 672 |
)
|
| 673 |
except Exception as e:
|
|
|
|
| 677 |
gradio_app = create_gradio_interface()
|
| 678 |
gradio_app.launch(
|
| 679 |
server_name="0.0.0.0",
|
| 680 |
+
server_port=7860,
|
| 681 |
+
share=False,
|
| 682 |
+
debug=False
|
| 683 |
)
|
| 684 |
except Exception as fallback_error:
|
| 685 |
logger.error(f"Fallback failed: {fallback_error}", exc_info=True)
|
| 686 |
+
print("❌ Application failed to start. Check logs for details.")
|
| 687 |
|
| 688 |
# --- Main Entry Point ---
|
| 689 |
if __name__ == "__main__":
|
| 690 |
+
print("🧬 Gene Analysis Pipeline Starting...")
|
| 691 |
+
print("=" * 50)
|
| 692 |
+
print("🔍 Checking system components...")
|
| 693 |
mafft_available, iqtree_available, _, _ = check_tool_availability()
|
| 694 |
+
print(f"🤖 Boundary Model: {'✅' if boundary_model else '❌'}")
|
| 695 |
+
print(f"🧠 Keras Model: {'✅' if keras_model else '❌'}")
|
| 696 |
+
print(f"🌳 Tree Analyzer: {'✅' if analyzer else '❌'}")
|
| 697 |
+
print(f"🧬 MAFFT: {'✅' if mafft_available else '❌'}")
|
| 698 |
+
print(f"🌲 IQ-TREE: {'✅' if iqtree_available else '❌'}")
|
| 699 |
+
print("=" * 50)
|
| 700 |
run_application()
|