Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,11 +15,23 @@ import tempfile
|
|
| 15 |
import shutil
|
| 16 |
import sys
|
| 17 |
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# --- Global Variables ---
|
| 20 |
MAFFT_PATH = "mafft/mafftdir/bin/mafft" # Update this path as needed
|
| 21 |
IQTREE_PATH = "iqtree/bin/iqtree2" # Update this path as needed
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# --- Logging ---
|
| 24 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 25 |
|
|
@@ -114,6 +126,7 @@ def check_tool_availability():
|
|
| 114 |
'/usr/bin/mafft',
|
| 115 |
'/usr/local/bin/mafft',
|
| 116 |
'mafft.bat', # Windows
|
|
|
|
| 117 |
]
|
| 118 |
|
| 119 |
for candidate in mafft_candidates:
|
|
@@ -132,12 +145,16 @@ def check_tool_availability():
|
|
| 132 |
IQTREE_PATH,
|
| 133 |
'iqtree2',
|
| 134 |
'iqtree',
|
| 135 |
-
'
|
| 136 |
-
'/usr/
|
| 137 |
-
'/usr/bin/
|
|
|
|
| 138 |
'/usr/local/bin/iqtree',
|
| 139 |
'iqtree2.exe', # Windows
|
| 140 |
'iqtree.exe', # Windows
|
|
|
|
|
|
|
|
|
|
| 141 |
]
|
| 142 |
|
| 143 |
for candidate in iqtree_candidates:
|
|
@@ -149,6 +166,142 @@ def check_tool_availability():
|
|
| 149 |
|
| 150 |
return mafft_available, iqtree_available, mafft_cmd, iqtree_cmd
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
def install_dependencies_guide():
|
| 153 |
"""Provide installation guidance for missing dependencies"""
|
| 154 |
guide = """
|
|
@@ -465,24 +618,24 @@ def build_maximum_likelihood_tree(f_gene_sequence):
|
|
| 465 |
logging.error(f"ML tree construction failed: {e}")
|
| 466 |
return False, f"ML tree construction failed: {str(e)}", None, None
|
| 467 |
|
| 468 |
-
# --- Tree Analysis Function
|
| 469 |
-
def analyze_sequence_for_tree(sequence: str, matching_percentage: float) ->
|
| 470 |
"""
|
| 471 |
-
Analyze sequence and create phylogenetic tree
|
| 472 |
"""
|
| 473 |
try:
|
| 474 |
if not analyzer:
|
| 475 |
-
return "Error: Tree analyzer not initialized.
|
| 476 |
|
| 477 |
if not sequence:
|
| 478 |
-
return "Error:
|
| 479 |
|
| 480 |
if not (1 <= matching_percentage <= 99):
|
| 481 |
-
return "Error: Matching percentage must be
|
| 482 |
|
| 483 |
# Find query sequence
|
| 484 |
if not analyzer.find_query_sequence(sequence):
|
| 485 |
-
return "Error: Invalid query
|
| 486 |
|
| 487 |
# Set matching percentage
|
| 488 |
analyzer.matching_percentage = matching_percentage
|
|
@@ -491,19 +644,19 @@ def analyze_sequence_for_tree(sequence: str, matching_percentage: float) -> str:
|
|
| 491 |
matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
|
| 492 |
|
| 493 |
if not matched_ids:
|
| 494 |
-
return f"No similar sequences
|
| 495 |
|
| 496 |
-
logging.info(f"Found {len(matched_ids)} similar sequences at {actual_percentage:.1f}%
|
| 497 |
|
| 498 |
# Build tree structure
|
| 499 |
tree_structure = analyzer.build_tree_structure(matched_ids)
|
| 500 |
if not tree_structure:
|
| 501 |
-
return "Error: Failed to build tree structure."
|
| 502 |
|
| 503 |
# Create interactive tree
|
| 504 |
fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
|
| 505 |
if not fig:
|
| 506 |
-
return "Error: Failed to create tree visualization."
|
| 507 |
|
| 508 |
# Generate HTML content
|
| 509 |
html_content = fig.to_html(full_html=True, include_plotlyjs='cdn')
|
|
@@ -521,14 +674,14 @@ def analyze_sequence_for_tree(sequence: str, matching_percentage: float) -> str:
|
|
| 521 |
|
| 522 |
logging.info(f"Tree HTML saved to {html_filename}")
|
| 523 |
|
| 524 |
-
return html_content
|
| 525 |
|
| 526 |
except Exception as e:
|
| 527 |
error_msg = f"Tree analysis error: {str(e)}"
|
| 528 |
logging.error(error_msg)
|
| 529 |
import traceback
|
| 530 |
logging.error(f"Full traceback: {traceback.format_exc()}")
|
| 531 |
-
return error_msg
|
| 532 |
|
| 533 |
# --- Keras Prediction ---
|
| 534 |
def predict_with_keras(sequence):
|
|
@@ -540,485 +693,384 @@ def predict_with_keras(sequence):
|
|
| 540 |
return "Sequence too short for k-mer prediction (minimum 6 nucleotides required)."
|
| 541 |
|
| 542 |
# Generate k-mers
|
| 543 |
-
kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
|
| 544 |
-
indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
|
| 545 |
|
| 546 |
-
#
|
| 547 |
-
|
| 548 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 549 |
|
| 550 |
-
# Format prediction
|
| 551 |
-
|
| 552 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
except Exception as e:
|
| 554 |
-
logging.error(f"Keras prediction
|
| 555 |
return f"Keras prediction failed: {str(e)}"
|
| 556 |
|
| 557 |
-
# ---
|
| 558 |
-
def
|
| 559 |
try:
|
| 560 |
-
if
|
| 561 |
-
return ""
|
| 562 |
-
|
| 563 |
-
#
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
else:
|
| 568 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 569 |
|
| 570 |
-
lines = content.strip().split("\n")
|
| 571 |
-
seq_lines = [line.strip() for line in lines if not line.startswith(">")]
|
| 572 |
-
return ''.join(seq_lines)
|
| 573 |
except Exception as e:
|
| 574 |
-
logging.error(f"
|
| 575 |
-
return ""
|
| 576 |
|
| 577 |
-
# ---
|
| 578 |
-
def
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 588 |
|
| 589 |
-
|
|
|
|
|
|
|
| 590 |
try:
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
if regions:
|
| 610 |
-
processed_sequence = regions[0]["sequence"] # Use the extracted gene region
|
| 611 |
-
boundary_output = processed_sequence # Output the actual F gene sequence
|
| 612 |
-
logging.info(f"F gene extracted: {len(processed_sequence)} bp (confidence: {confidence:.3f})")
|
| 613 |
-
else:
|
| 614 |
-
boundary_output = f"No F gene regions found in input sequence"
|
| 615 |
-
processed_sequence = dna_input
|
| 616 |
-
logging.warning("No gene regions found, using full sequence")
|
| 617 |
-
logging.info("Boundary model prediction completed")
|
| 618 |
-
except Exception as e:
|
| 619 |
-
logging.error(f"Boundary model failed: {e}")
|
| 620 |
-
boundary_output = f"Boundary model error: {str(e)}"
|
| 621 |
-
processed_sequence = dna_input # Fall back to original sequence
|
| 622 |
-
else:
|
| 623 |
-
boundary_output = f"Boundary model not available. Using original input: {len(dna_input)} bp"
|
| 624 |
-
processed_sequence = dna_input
|
| 625 |
-
|
| 626 |
-
# Step 2: Keras Prediction (F gene validation)
|
| 627 |
-
keras_output = ""
|
| 628 |
-
if processed_sequence and len(processed_sequence) >= 6:
|
| 629 |
-
keras_prediction = predict_with_keras(processed_sequence)
|
| 630 |
-
# Interpret keras prediction as F gene validation
|
| 631 |
-
if keras_prediction and not keras_prediction.startswith(("Keras", "Sequence too short")):
|
| 632 |
-
# You might want to add logic here to interpret the prediction scores
|
| 633 |
-
# For now, just show the prediction
|
| 634 |
-
keras_output = f"F gene validation scores: {keras_prediction[:100]}..."
|
| 635 |
else:
|
| 636 |
-
|
| 637 |
-
else:
|
| 638 |
-
keras_output = "Skipped: sequence too short for F gene validation"
|
| 639 |
-
|
| 640 |
-
# Step 3: Maximum Likelihood Tree (MAFFT + IQ-TREE)
|
| 641 |
-
aligned_file = None
|
| 642 |
-
phy_file = None
|
| 643 |
-
ml_tree_output = ""
|
| 644 |
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
ml_success, ml_message, ml_aligned, ml_tree = build_maximum_likelihood_tree(processed_sequence)
|
| 649 |
-
|
| 650 |
-
if ml_success:
|
| 651 |
-
ml_tree_output = ml_message
|
| 652 |
-
aligned_file = ml_aligned
|
| 653 |
-
phy_file = ml_tree
|
| 654 |
-
else:
|
| 655 |
-
ml_tree_output = ml_message # This now includes detailed error information
|
| 656 |
-
|
| 657 |
-
except Exception as e:
|
| 658 |
-
ml_tree_output = f"❌ ML Tree construction failed: {str(e)}"
|
| 659 |
-
logging.error(f"ML Tree failed: {e}")
|
| 660 |
-
elif build_ml_tree:
|
| 661 |
-
ml_tree_output = "❌ F gene sequence too short for ML tree construction (minimum 50 bp)"
|
| 662 |
-
else:
|
| 663 |
-
ml_tree_output = "ML tree construction skipped (not requested)"
|
| 664 |
-
|
| 665 |
-
# Step 4: ML Simplified Tree (using the existing approach)
|
| 666 |
-
html_file = None
|
| 667 |
-
tree_html_content = "No tree generated"
|
| 668 |
-
simplified_ml_output = ""
|
| 669 |
|
| 670 |
-
if
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
if analyzer.find_query_sequence(processed_sequence):
|
| 692 |
-
matched_ids, perc = analyzer.find_similar_sequences(similarity_score)
|
| 693 |
-
simplified_ml_output += f"\n- {len(matched_ids)} sequences analyzed"
|
| 694 |
-
simplified_ml_output += f"\n- Similarity threshold: {perc:.1f}%"
|
| 695 |
-
else:
|
| 696 |
-
simplified_ml_output = f"❌ Simplified ML tree failed: {tree_result}"
|
| 697 |
-
tree_html_content = f"<p>Error: {tree_result}</p>"
|
| 698 |
-
|
| 699 |
-
except Exception as e:
|
| 700 |
-
logging.error(f"Simplified ML tree analysis failed: {e}")
|
| 701 |
-
simplified_ml_output = f"❌ Simplified ML tree analysis failed: {str(e)}"
|
| 702 |
-
tree_html_content = f"<p>Error: {str(e)}</p>"
|
| 703 |
-
else:
|
| 704 |
-
if not analyzer:
|
| 705 |
-
simplified_ml_output = "❌ Tree analyzer not available"
|
| 706 |
-
else:
|
| 707 |
-
simplified_ml_output = "❌ F gene sequence too short for tree analysis (minimum 10 bp)"
|
| 708 |
-
|
| 709 |
-
# Return all results
|
| 710 |
-
return (
|
| 711 |
-
boundary_output, # F gene extraction result
|
| 712 |
-
keras_output, # F gene validation result
|
| 713 |
-
ml_tree_output, # ML tree construction status
|
| 714 |
-
simplified_ml_output, # Simplified tree analysis status
|
| 715 |
-
tree_html_content, # HTML content for tree display
|
| 716 |
-
aligned_file, # Path to aligned FASTA file
|
| 717 |
-
phy_file, # Path to phylogenetic tree file
|
| 718 |
-
html_file, # Path to HTML tree file
|
| 719 |
-
f"Pipeline completed. F gene length: {len(processed_sequence)} bp" # Summary
|
| 720 |
-
)
|
| 721 |
|
| 722 |
except Exception as e:
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
import traceback
|
| 726 |
-
logging.error(f"Full traceback: {traceback.format_exc()}")
|
| 727 |
-
return (
|
| 728 |
-
error_msg, "", "", "", f"<p>Error: {error_msg}</p>",
|
| 729 |
-
None, None, None, error_msg
|
| 730 |
-
)
|
| 731 |
|
| 732 |
# --- Gradio Interface ---
|
| 733 |
-
def
|
| 734 |
-
"""Create the Gradio interface
|
| 735 |
-
|
| 736 |
-
# Custom CSS for better styling
|
| 737 |
-
custom_css = """
|
| 738 |
-
.gradio-container {
|
| 739 |
-
max-width: 1200px !important;
|
| 740 |
-
}
|
| 741 |
-
.tab-nav button {
|
| 742 |
-
font-size: 16px !important;
|
| 743 |
-
}
|
| 744 |
-
.output-html {
|
| 745 |
-
height: 600px !important;
|
| 746 |
-
overflow: auto;
|
| 747 |
-
}
|
| 748 |
-
"""
|
| 749 |
|
| 750 |
-
with gr.Blocks(
|
| 751 |
gr.Markdown("""
|
| 752 |
-
# 🧬 F Gene Analysis
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
- **Gene Boundary Detection**: Extract F gene sequences from larger genomic sequences
|
| 756 |
-
- **Gene Validation**: Validate extracted sequences using machine learning
|
| 757 |
-
- **Phylogenetic Analysis**: Build maximum likelihood trees and simplified phylogenetic trees
|
| 758 |
-
|
| 759 |
-
**Instructions:**
|
| 760 |
-
1. Enter your sequence directly or upload a FASTA file
|
| 761 |
-
2. Adjust similarity threshold for phylogenetic analysis (1-99%)
|
| 762 |
-
3. Choose whether to build maximum likelihood trees (requires MAFFT & IQ-TREE)
|
| 763 |
-
4. Click "Run Analysis" to start the pipeline
|
| 764 |
""")
|
| 765 |
|
| 766 |
-
with gr.
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
gr.Markdown("### Input Sequence")
|
| 771 |
-
dna_input = gr.Textbox(
|
| 772 |
-
label="DNA Sequence",
|
| 773 |
-
placeholder="Enter your DNA sequence here (ATCG format)...",
|
| 774 |
-
lines=5,
|
| 775 |
-
max_lines=10
|
| 776 |
-
)
|
| 777 |
-
|
| 778 |
-
fasta_file = gr.File(
|
| 779 |
-
label="Or Upload FASTA File",
|
| 780 |
-
file_types=[".fasta", ".fa", ".fas", ".txt"]
|
| 781 |
-
)
|
| 782 |
-
|
| 783 |
-
with gr.Row():
|
| 784 |
-
similarity_score = gr.Slider(
|
| 785 |
-
minimum=1,
|
| 786 |
-
maximum=99,
|
| 787 |
-
value=95.0,
|
| 788 |
-
step=1.0,
|
| 789 |
-
label="Similarity Threshold (%)",
|
| 790 |
-
info="Minimum similarity for phylogenetic analysis"
|
| 791 |
-
)
|
| 792 |
-
|
| 793 |
-
build_ml_tree = gr.Checkbox(
|
| 794 |
-
label="Build ML Tree",
|
| 795 |
-
value=False,
|
| 796 |
-
info="Build maximum likelihood tree (requires MAFFT & IQ-TREE)"
|
| 797 |
-
)
|
| 798 |
-
|
| 799 |
-
# Action buttons
|
| 800 |
-
with gr.Row():
|
| 801 |
-
run_btn = gr.Button("🚀 Run Analysis", variant="primary", size="lg")
|
| 802 |
-
clear_btn = gr.Button("🗑️ Clear", variant="secondary")
|
| 803 |
|
| 804 |
-
with gr.
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
)
|
| 813 |
-
|
| 814 |
-
# Model status
|
| 815 |
-
gr.Markdown("### Available Models")
|
| 816 |
-
model_status = []
|
| 817 |
-
if boundary_model:
|
| 818 |
-
model_status.append("✅ Boundary Detection Model")
|
| 819 |
-
else:
|
| 820 |
-
model_status.append("❌ Boundary Detection Model")
|
| 821 |
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 826 |
|
| 827 |
-
|
| 828 |
-
model_status.append("✅ Tree Analysis Module")
|
| 829 |
-
else:
|
| 830 |
-
model_status.append("❌ Tree Analysis Module")
|
| 831 |
-
|
| 832 |
-
gr.Markdown("\n".join(model_status))
|
| 833 |
-
|
| 834 |
-
with gr.Tab("📊 Results"):
|
| 835 |
-
with gr.Row():
|
| 836 |
-
with gr.Column():
|
| 837 |
-
# Text outputs
|
| 838 |
-
boundary_output = gr.Textbox(
|
| 839 |
-
label="🎯 F Gene Extraction",
|
| 840 |
-
lines=5,
|
| 841 |
-
interactive=False
|
| 842 |
-
)
|
| 843 |
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
simplified_ml_output = gr.Textbox(
|
| 858 |
-
label="📈 Simplified Phylogenetic Analysis",
|
| 859 |
-
lines=3,
|
| 860 |
-
interactive=False
|
| 861 |
-
)
|
| 862 |
-
|
| 863 |
-
# Tree visualization
|
| 864 |
-
gr.Markdown("### 🌲 Phylogenetic Tree Visualization")
|
| 865 |
-
tree_html = gr.HTML(
|
| 866 |
-
label="Interactive Tree",
|
| 867 |
-
value="<p>No tree generated yet. Run analysis to see results.</p>"
|
| 868 |
-
)
|
| 869 |
-
|
| 870 |
-
# File downloads
|
| 871 |
-
gr.Markdown("### 📁 Download Results")
|
| 872 |
-
with gr.Row():
|
| 873 |
-
aligned_file = gr.File(
|
| 874 |
-
label="Aligned Sequences (FASTA)",
|
| 875 |
interactive=False
|
| 876 |
)
|
| 877 |
|
| 878 |
-
|
| 879 |
-
label="Phylogenetic Tree
|
| 880 |
-
|
| 881 |
)
|
| 882 |
|
| 883 |
-
|
| 884 |
-
label="
|
| 885 |
-
interactive=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 886 |
)
|
| 887 |
-
|
| 888 |
-
with gr.Tab("ℹ️ Help & Info"):
|
| 889 |
-
gr.Markdown("""
|
| 890 |
-
## About This Tool
|
| 891 |
-
|
| 892 |
-
### F Gene Analysis Pipeline
|
| 893 |
-
This comprehensive pipeline analyzes F genes through multiple computational approaches:
|
| 894 |
-
|
| 895 |
-
#### 🎯 Gene Boundary Detection
|
| 896 |
-
- Uses deep learning to identify and extract F gene sequences from larger genomic sequences
|
| 897 |
-
- Provides confidence scores for detected boundaries
|
| 898 |
-
- Automatically trims sequences to focus on the F gene region
|
| 899 |
-
|
| 900 |
-
#### 🔍 Gene Validation
|
| 901 |
-
- Employs k-mer based machine learning models to validate extracted sequences
|
| 902 |
-
- Provides probability scores indicating likelihood of being a genuine F gene
|
| 903 |
-
- Uses 6-mer frequency patterns for classification
|
| 904 |
-
|
| 905 |
-
#### 🌳 Phylogenetic Analysis
|
| 906 |
-
|
| 907 |
-
**Maximum Likelihood Trees:**
|
| 908 |
-
- Requires MAFFT (sequence alignment) and IQ-TREE (phylogenetic reconstruction)
|
| 909 |
-
- Performs model selection and bootstrap analysis
|
| 910 |
-
- Generates publication-quality phylogenetic trees
|
| 911 |
-
- Provides detailed evolutionary analysis
|
| 912 |
-
|
| 913 |
-
**Simplified Trees:**
|
| 914 |
-
- Uses built-in algorithms for quick phylogenetic analysis
|
| 915 |
-
- Interactive visualization with similarity-based clustering
|
| 916 |
-
- Faster alternative when external tools are not available
|
| 917 |
-
|
| 918 |
-
### Input Requirements
|
| 919 |
-
- **DNA Sequences**: ATCG format, minimum 50 bp for meaningful analysis
|
| 920 |
-
- **FASTA Files**: Standard FASTA format with single or multiple sequences
|
| 921 |
-
- **Similarity Threshold**: 1-99% for controlling phylogenetic analysis sensitivity
|
| 922 |
-
|
| 923 |
-
### Dependencies
|
| 924 |
-
|
| 925 |
-
**Required for ML Trees:**
|
| 926 |
-
```bash
|
| 927 |
-
# Ubuntu/Debian
|
| 928 |
-
sudo apt-get install mafft iqtree
|
| 929 |
-
|
| 930 |
-
# macOS
|
| 931 |
-
brew install mafft iqtree
|
| 932 |
-
|
| 933 |
-
# Conda
|
| 934 |
-
conda install -c bioconda mafft iqtree
|
| 935 |
-
```
|
| 936 |
-
|
| 937 |
-
### Output Files
|
| 938 |
-
- **Aligned FASTA**: Multiple sequence alignment in FASTA format
|
| 939 |
-
- **Tree File**: Newick format phylogenetic tree
|
| 940 |
-
- **HTML Tree**: Interactive visualization for web browsers
|
| 941 |
-
|
| 942 |
-
### Troubleshooting
|
| 943 |
-
|
| 944 |
-
**Common Issues:**
|
| 945 |
-
- *"No similar sequences found"*: Lower the similarity threshold
|
| 946 |
-
- *"Sequence too short"*: Provide sequences longer than 50 bp
|
| 947 |
-
- *"MAFFT/IQ-TREE not found"*: Install required dependencies
|
| 948 |
-
- *"Model not available"*: Check model files are properly downloaded
|
| 949 |
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 955 |
|
| 956 |
-
#
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 966 |
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
phy_file, html_file, status_display
|
| 985 |
-
]
|
| 986 |
-
)
|
| 987 |
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 991 |
)
|
| 992 |
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
def load_example():
|
| 998 |
-
example_seq = "ATGAAACTGTCAACACTCACTGAGTACATTAGCCAAGTTCTCAAGACTGAGTGTTTACCTTTGTGAATACACTGAGTCCTTGTCAACGTTCGGCTGCAGTCACACTGATGGTCTTGTCTTCAGGAGCAACTGCAGTCTGTGCTGTGTACTATAGTGCTAAGAGTGATAATGCACTGTTCAGTACCTTTGACAGTGTGTCTCTGTCACCTGGTGCTATGCAGAGCTGCGATGAGATCTACATTGGTCTGATCGATAAGACTGAGTCCAAGGGTGTTGCTGTGTGTACTGTAGAGTGTGATAGTGTTGCCTGCACTGTGTCTATGGCTGATCTTGAGGCTCTGCTTATGTCAACACTGAGTGTGAAATGTTCATTTGCTACTTCAAGACTGATGTGAAGACTGTGTATTGTACTCAGTCATGCAGAGTGAAGTCCTTGAGCCACTTGCTTTGTACAATGTGGGTGATGAGATGTTGTGCTGCAGTGTCAAGGGGCCACAGTCTTGCCTTGATAGTGCGATTGCTGTGATGATGTGCACTTCAATGAGTGGTCGAGATGCTGCTGTGTGTAAGGATGCTGCTGTGTGTAAGAAGGATGCTGCTGTGTGTAAGA"
|
| 999 |
-
return example_seq, "Example F gene sequence loaded"
|
| 1000 |
-
|
| 1001 |
-
example_btn.click(
|
| 1002 |
-
fn=load_example,
|
| 1003 |
-
outputs=[dna_input, status_display]
|
| 1004 |
-
)
|
| 1005 |
|
| 1006 |
-
return
|
| 1007 |
|
| 1008 |
-
# --- Main Execution ---
|
| 1009 |
if __name__ == "__main__":
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
# Launch with enhanced configuration
|
| 1014 |
-
interface.launch(
|
| 1015 |
-
server_name="0.0.0.0", # Allow external connections
|
| 1016 |
-
server_port=7860, # Default Gradio port
|
| 1017 |
-
share=False, # Set to True for public sharing
|
| 1018 |
-
debug=True, # Enable debug mode
|
| 1019 |
-
show_error=True, # Show detailed errors
|
| 1020 |
-
max_threads=4, # Limit concurrent threads
|
| 1021 |
-
auth=None, # Add authentication if needed: ("username", "password")
|
| 1022 |
-
ssl_verify=False, # For development environments
|
| 1023 |
-
quiet=False # Show startup messages
|
| 1024 |
-
)
|
|
|
|
| 15 |
import shutil
|
| 16 |
import sys
|
| 17 |
from pathlib import Path
|
| 18 |
+
import uuid
|
| 19 |
+
from Bio import SeqIO
|
| 20 |
+
from Bio.Seq import Seq
|
| 21 |
+
from Bio.SeqRecord import SeqRecord
|
| 22 |
|
| 23 |
# --- Global Variables ---
|
| 24 |
MAFFT_PATH = "mafft/mafftdir/bin/mafft" # Update this path as needed
|
| 25 |
IQTREE_PATH = "iqtree/bin/iqtree2" # Update this path as needed
|
| 26 |
|
| 27 |
+
# Reference files for phylogenetic placement
|
| 28 |
+
REFERENCE_ALIGNMENT_PATH = "f_gene_sequences_aligned.fasta"
|
| 29 |
+
REFERENCE_TREE_PATH = "f_gene_sequences.phy.treefile"
|
| 30 |
+
QUERY_OUTPUT_DIR = "queries"
|
| 31 |
+
|
| 32 |
+
# Create output directory
|
| 33 |
+
os.makedirs(QUERY_OUTPUT_DIR, exist_ok=True)
|
| 34 |
+
|
| 35 |
# --- Logging ---
|
| 36 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 37 |
|
|
|
|
| 126 |
'/usr/bin/mafft',
|
| 127 |
'/usr/local/bin/mafft',
|
| 128 |
'mafft.bat', # Windows
|
| 129 |
+
os.path.join("binaries", "mafft", "mafft.bat"), # Local binaries
|
| 130 |
]
|
| 131 |
|
| 132 |
for candidate in mafft_candidates:
|
|
|
|
| 145 |
IQTREE_PATH,
|
| 146 |
'iqtree2',
|
| 147 |
'iqtree',
|
| 148 |
+
'iqtree3',
|
| 149 |
+
'/usr/bin/iqtree3',
|
| 150 |
+
'/usr/local/bin/iqtree3_arm',
|
| 151 |
+
'/usr/bin/iqtree3_intel',
|
| 152 |
'/usr/local/bin/iqtree',
|
| 153 |
'iqtree2.exe', # Windows
|
| 154 |
'iqtree.exe', # Windows
|
| 155 |
+
'iqtree3.exe', # Windows
|
| 156 |
+
os.path.join("binaries", "iqtree", "bin", "iqtree2"),
|
| 157 |
+
os.path.join("binaries", "iqtree", "bin", "iqtree3"),
|
| 158 |
]
|
| 159 |
|
| 160 |
for candidate in iqtree_candidates:
|
|
|
|
| 166 |
|
| 167 |
return mafft_available, iqtree_available, mafft_cmd, iqtree_cmd
|
| 168 |
|
| 169 |
+
# --- Phylogenetic Placement Functions ---
|
| 170 |
+
def place_sequence_in_tree(sequence: str):
|
| 171 |
+
"""
|
| 172 |
+
Place a new sequence into the existing reference tree using MAFFT + IQ-TREE
|
| 173 |
+
"""
|
| 174 |
+
try:
|
| 175 |
+
# Input validation
|
| 176 |
+
if not sequence or len(sequence.strip()) < 100:
|
| 177 |
+
return None, None, "Error: Sequence is too short for phylogenetic placement (minimum 100 bp required)."
|
| 178 |
+
|
| 179 |
+
# Clean sequence
|
| 180 |
+
sequence = sequence.upper().strip()
|
| 181 |
+
sequence = ''.join(c if c in 'ACTGN' else 'N' for c in sequence)
|
| 182 |
+
|
| 183 |
+
# Check if reference files exist
|
| 184 |
+
if not os.path.exists(REFERENCE_ALIGNMENT_PATH):
|
| 185 |
+
return None, None, f"Error: Reference alignment file not found: {REFERENCE_ALIGNMENT_PATH}"
|
| 186 |
+
|
| 187 |
+
if not os.path.exists(REFERENCE_TREE_PATH):
|
| 188 |
+
return None, None, f"Error: Reference tree file not found: {REFERENCE_TREE_PATH}"
|
| 189 |
+
|
| 190 |
+
# Check tool availability
|
| 191 |
+
mafft_available, iqtree_available, mafft_cmd, iqtree_cmd = check_tool_availability()
|
| 192 |
+
|
| 193 |
+
if not mafft_available:
|
| 194 |
+
return None, None, "Error: MAFFT not found. Please install MAFFT for phylogenetic placement."
|
| 195 |
+
|
| 196 |
+
if not iqtree_available:
|
| 197 |
+
return None, None, "Error: IQ-TREE not found. Please install IQ-TREE for phylogenetic placement."
|
| 198 |
+
|
| 199 |
+
# Generate unique ID for this query
|
| 200 |
+
query_id = f"QUERY_{uuid.uuid4().hex[:8]}"
|
| 201 |
+
query_fasta = os.path.join(QUERY_OUTPUT_DIR, f"{query_id}.fa")
|
| 202 |
+
aligned_with_query = os.path.join(QUERY_OUTPUT_DIR, f"{query_id}_aligned.fa")
|
| 203 |
+
output_prefix = os.path.join(QUERY_OUTPUT_DIR, f"{query_id}_placed_tree")
|
| 204 |
+
|
| 205 |
+
# Save query sequence to FASTA file
|
| 206 |
+
try:
|
| 207 |
+
query_record = SeqRecord(Seq(sequence), id=query_id, description="Query sequence for phylogenetic placement")
|
| 208 |
+
SeqIO.write([query_record], query_fasta, "fasta")
|
| 209 |
+
logging.info(f"Query sequence saved: {query_fasta}")
|
| 210 |
+
except Exception as e:
|
| 211 |
+
return None, None, f"Error: Failed to save query sequence: {str(e)}"
|
| 212 |
+
|
| 213 |
+
# Step 1: Add query sequence to reference alignment using MAFFT
|
| 214 |
+
logging.info("Adding query sequence to reference alignment...")
|
| 215 |
+
try:
|
| 216 |
+
with open(aligned_with_query, "w") as output_file:
|
| 217 |
+
mafft_cmd_list = [
|
| 218 |
+
mafft_cmd,
|
| 219 |
+
"--add", query_fasta,
|
| 220 |
+
"--reorder",
|
| 221 |
+
REFERENCE_ALIGNMENT_PATH
|
| 222 |
+
]
|
| 223 |
+
|
| 224 |
+
result = subprocess.run(
|
| 225 |
+
mafft_cmd_list,
|
| 226 |
+
stdout=output_file,
|
| 227 |
+
stderr=subprocess.PIPE,
|
| 228 |
+
text=True,
|
| 229 |
+
timeout=300, # 5 minute timeout
|
| 230 |
+
check=True
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
logging.info(f"MAFFT alignment completed: {aligned_with_query}")
|
| 234 |
+
|
| 235 |
+
except subprocess.TimeoutExpired:
|
| 236 |
+
return None, None, "Error: MAFFT alignment timed out (>5 minutes)."
|
| 237 |
+
except subprocess.CalledProcessError as e:
|
| 238 |
+
error_msg = e.stderr.decode() if e.stderr else "Unknown MAFFT error"
|
| 239 |
+
logging.error(f"MAFFT failed: {error_msg}")
|
| 240 |
+
return None, None, f"Error: MAFFT alignment failed: {error_msg}"
|
| 241 |
+
except Exception as e:
|
| 242 |
+
return None, None, f"Error: MAFFT execution failed: {str(e)}"
|
| 243 |
+
|
| 244 |
+
# Verify alignment file was created
|
| 245 |
+
if not os.path.exists(aligned_with_query) or os.path.getsize(aligned_with_query) == 0:
|
| 246 |
+
return None, None, "Error: MAFFT alignment file was not created or is empty."
|
| 247 |
+
|
| 248 |
+
# Step 2: Place sequence in tree using IQ-TREE with constraint tree
|
| 249 |
+
logging.info("Placing sequence in phylogenetic tree...")
|
| 250 |
+
try:
|
| 251 |
+
iqtree_cmd_list = [
|
| 252 |
+
iqtree_cmd,
|
| 253 |
+
"-s", aligned_with_query,
|
| 254 |
+
"-g", REFERENCE_TREE_PATH, # Constraint tree
|
| 255 |
+
"-m", "GTR+G", # Substitution model
|
| 256 |
+
"-pre", output_prefix, # Output prefix
|
| 257 |
+
"-redo", # Overwrite existing files
|
| 258 |
+
"--quiet" # Reduce verbosity
|
| 259 |
+
]
|
| 260 |
+
|
| 261 |
+
result = subprocess.run(
|
| 262 |
+
iqtree_cmd_list,
|
| 263 |
+
capture_output=True,
|
| 264 |
+
text=True,
|
| 265 |
+
timeout=600, # 10 minute timeout
|
| 266 |
+
check=True
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
logging.info("IQ-TREE placement completed")
|
| 270 |
+
|
| 271 |
+
except subprocess.TimeoutExpired:
|
| 272 |
+
return None, None, "Error: IQ-TREE placement timed out (>10 minutes)."
|
| 273 |
+
except subprocess.CalledProcessError as e:
|
| 274 |
+
error_msg = e.stderr if e.stderr else "Unknown IQ-TREE error"
|
| 275 |
+
logging.error(f"IQ-TREE failed: {error_msg}")
|
| 276 |
+
return None, None, f"Error: IQ-TREE placement failed: {error_msg}"
|
| 277 |
+
except Exception as e:
|
| 278 |
+
return None, None, f"Error: IQ-TREE execution failed: {str(e)}"
|
| 279 |
+
|
| 280 |
+
# Check if tree file was generated
|
| 281 |
+
treefile = f"{output_prefix}.treefile"
|
| 282 |
+
if not os.path.exists(treefile):
|
| 283 |
+
return None, None, "Error: Tree file was not generated by IQ-TREE."
|
| 284 |
+
|
| 285 |
+
if os.path.getsize(treefile) == 0:
|
| 286 |
+
return None, None, "Error: Generated tree file is empty."
|
| 287 |
+
|
| 288 |
+
# Success! Return the tree file and alignment
|
| 289 |
+
success_msg = f"✅ Success: Phylogenetic placement completed!\n"
|
| 290 |
+
success_msg += f"- Query ID: {query_id}\n"
|
| 291 |
+
success_msg += f"- Sequence length: {len(sequence)} bp\n"
|
| 292 |
+
success_msg += f"- Placed in tree with constraint from reference\n"
|
| 293 |
+
success_msg += f"- Tree file: {os.path.basename(treefile)}\n"
|
| 294 |
+
success_msg += f"- Alignment file: {os.path.basename(aligned_with_query)}"
|
| 295 |
+
|
| 296 |
+
logging.info(f"Phylogenetic placement successful: {treefile}")
|
| 297 |
+
|
| 298 |
+
return treefile, aligned_with_query, success_msg
|
| 299 |
+
|
| 300 |
+
except Exception as e:
|
| 301 |
+
error_msg = f"Phylogenetic placement failed: {str(e)}"
|
| 302 |
+
logging.error(error_msg)
|
| 303 |
+
return None, None, error_msg
|
| 304 |
+
|
| 305 |
def install_dependencies_guide():
|
| 306 |
"""Provide installation guidance for missing dependencies"""
|
| 307 |
guide = """
|
|
|
|
| 618 |
logging.error(f"ML tree construction failed: {e}")
|
| 619 |
return False, f"ML tree construction failed: {str(e)}", None, None
|
| 620 |
|
| 621 |
+
# --- Tree Analysis Function ---
|
| 622 |
+
def analyze_sequence_for_tree(sequence: str, matching_percentage: float = 80.0) -> tuple:
|
| 623 |
"""
|
| 624 |
+
Analyze sequence and create phylogenetic tree, returning HTML content and file path
|
| 625 |
"""
|
| 626 |
try:
|
| 627 |
if not analyzer:
|
| 628 |
+
return "Error: Tree analyzer not initialized. Check CSV data.", None
|
| 629 |
|
| 630 |
if not sequence:
|
| 631 |
+
return "Error: Provide a sequence.", None
|
| 632 |
|
| 633 |
if not (1 <= matching_percentage <= 99):
|
| 634 |
+
return "Error: Matching percentage must be 1-99.", None
|
| 635 |
|
| 636 |
# Find query sequence
|
| 637 |
if not analyzer.find_query_sequence(sequence):
|
| 638 |
+
return "Error: Invalid query or not in dataset.", None
|
| 639 |
|
| 640 |
# Set matching percentage
|
| 641 |
analyzer.matching_percentage = matching_percentage
|
|
|
|
| 644 |
matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
|
| 645 |
|
| 646 |
if not matched_ids:
|
| 647 |
+
return f"No similar sequences at {matching_percentage}% similarity. Lower threshold.", None
|
| 648 |
|
| 649 |
+
logging.info(f"Found {len(matched_ids)} similar sequences at {actual_percentage:.1f}%")
|
| 650 |
|
| 651 |
# Build tree structure
|
| 652 |
tree_structure = analyzer.build_tree_structure(matched_ids)
|
| 653 |
if not tree_structure:
|
| 654 |
+
return "Error: Failed to build tree structure.", None
|
| 655 |
|
| 656 |
# Create interactive tree
|
| 657 |
fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
|
| 658 |
if not fig:
|
| 659 |
+
return "Error: Failed to create tree visualization.", None
|
| 660 |
|
| 661 |
# Generate HTML content
|
| 662 |
html_content = fig.to_html(full_html=True, include_plotlyjs='cdn')
|
|
|
|
| 674 |
|
| 675 |
logging.info(f"Tree HTML saved to {html_filename}")
|
| 676 |
|
| 677 |
+
return html_content, html_filename
|
| 678 |
|
| 679 |
except Exception as e:
|
| 680 |
error_msg = f"Tree analysis error: {str(e)}"
|
| 681 |
logging.error(error_msg)
|
| 682 |
import traceback
|
| 683 |
logging.error(f"Full traceback: {traceback.format_exc()}")
|
| 684 |
+
return error_msg, None
|
| 685 |
|
| 686 |
# --- Keras Prediction ---
|
| 687 |
def predict_with_keras(sequence):
|
|
|
|
| 693 |
return "Sequence too short for k-mer prediction (minimum 6 nucleotides required)."
|
| 694 |
|
| 695 |
# Generate k-mers
|
| 696 |
+
kmers = [sequence[i:i+6] for i in range(len(sequence) - 5)]
|
|
|
|
| 697 |
|
| 698 |
+
# Convert k-mers to indices
|
| 699 |
+
kmer_indices = []
|
| 700 |
+
for kmer in kmers:
|
| 701 |
+
if kmer in kmer_to_index:
|
| 702 |
+
kmer_indices.append(kmer_to_index[kmer])
|
| 703 |
+
else:
|
| 704 |
+
kmer_indices.append(0)
|
| 705 |
+
|
| 706 |
+
if not kmer_indices:
|
| 707 |
+
return "No valid k-mers found in sequence."
|
| 708 |
+
|
| 709 |
+
# Pad or truncate sequence to model's expected input length
|
| 710 |
+
max_length = 1000 # Adjust based on your model's training
|
| 711 |
+
if len(kmer_indices) > max_length:
|
| 712 |
+
kmer_indices = kmer_indices[:max_length]
|
| 713 |
+
else:
|
| 714 |
+
kmer_indices.extend([0] * (max_length - len(kmer_indices)))
|
| 715 |
+
|
| 716 |
+
# Convert to numpy array and reshape for model input
|
| 717 |
+
input_array = np.array([kmer_indices])
|
| 718 |
+
|
| 719 |
+
# Make prediction
|
| 720 |
+
prediction = keras_model.predict(input_array, verbose=0)
|
| 721 |
|
| 722 |
+
# Format prediction results
|
| 723 |
+
if prediction.shape[1] == 1:
|
| 724 |
+
# Binary classification
|
| 725 |
+
probability = float(prediction[0][0])
|
| 726 |
+
result = "Positive" if probability > 0.5 else "Negative"
|
| 727 |
+
return f"Keras Prediction: {result} (confidence: {probability:.3f})"
|
| 728 |
+
else:
|
| 729 |
+
# Multi-class classification
|
| 730 |
+
predicted_class = np.argmax(prediction[0])
|
| 731 |
+
confidence = float(np.max(prediction[0]))
|
| 732 |
+
return f"Keras Prediction: Class {predicted_class} (confidence: {confidence:.3f})"
|
| 733 |
+
|
| 734 |
except Exception as e:
|
| 735 |
+
logging.error(f"Keras prediction error: {e}")
|
| 736 |
return f"Keras prediction failed: {str(e)}"
|
| 737 |
|
| 738 |
+
# --- Boundary Prediction ---
|
| 739 |
+
def predict_with_boundary_model(sequence):
|
| 740 |
try:
|
| 741 |
+
if not boundary_model:
|
| 742 |
+
return f"Boundary model not available. Input sequence: {sequence[:100]}...", None
|
| 743 |
+
|
| 744 |
+
# Use the boundary model predictor to extract F gene sequence
|
| 745 |
+
result = boundary_model.predict(sequence)
|
| 746 |
+
|
| 747 |
+
# Assume result is either a sequence (str) or a dict with sequence
|
| 748 |
+
if isinstance(result, str):
|
| 749 |
+
extracted_sequence = result
|
| 750 |
+
elif isinstance(result, dict) and 'sequence' in result:
|
| 751 |
+
extracted_sequence = result['sequence']
|
| 752 |
+
elif isinstance(result, (list, tuple)) and len(result) > 0:
|
| 753 |
+
extracted_sequence = result[0]
|
| 754 |
else:
|
| 755 |
+
return f"Boundary model returned invalid output: {result}", None
|
| 756 |
+
|
| 757 |
+
# Validate extracted sequence
|
| 758 |
+
if not extracted_sequence or not all(c in 'ATCGN' for c in extracted_sequence.upper()):
|
| 759 |
+
return f"Invalid F gene sequence extracted: {extracted_sequence[:100]}...", None
|
| 760 |
+
|
| 761 |
+
return f"Boundary Prediction: Extracted F gene sequence (length: {len(extracted_sequence)} bp)", extracted_sequence
|
| 762 |
|
|
|
|
|
|
|
|
|
|
| 763 |
except Exception as e:
|
| 764 |
+
logging.error(f"Boundary prediction error: {e}")
|
| 765 |
+
return f"Boundary prediction failed: {str(e)}", None
|
| 766 |
|
| 767 |
+
# --- Combined Prediction Function ---
|
| 768 |
+
def predict_sequence(sequence, use_keras=True, use_boundary=True):
|
| 769 |
+
"""Combined prediction using available models with automatic tree building"""
|
| 770 |
+
results = []
|
| 771 |
+
tree_html = "<p>No tree generated.</p>"
|
| 772 |
+
tree_file = None
|
| 773 |
+
|
| 774 |
+
if not sequence:
|
| 775 |
+
return "Please provide a DNA sequence.", tree_html, tree_file
|
| 776 |
+
|
| 777 |
+
# Clean sequence
|
| 778 |
+
sequence = sequence.upper().strip()
|
| 779 |
+
sequence = ''.join(c for c in sequence if c in 'ATCGN')
|
| 780 |
+
|
| 781 |
+
if len(sequence) < 10:
|
| 782 |
+
return "Sequence too short for prediction (minimum 10 nucleotides required).", tree_html, tree_file
|
| 783 |
+
|
| 784 |
+
results.append(f"Analyzing sequence of length: {len(sequence)} bp")
|
| 785 |
+
results.append("-" * 50)
|
| 786 |
+
|
| 787 |
+
# Keras prediction
|
| 788 |
+
if use_keras:
|
| 789 |
+
keras_result = predict_with_keras(sequence)
|
| 790 |
+
results.append(f"🧠 {keras_result}")
|
| 791 |
+
|
| 792 |
+
# Boundary prediction and tree building
|
| 793 |
+
if use_boundary:
|
| 794 |
+
boundary_result, extracted_sequence = predict_with_boundary_model(sequence)
|
| 795 |
+
results.append(f"🎯 {boundary_result}")
|
| 796 |
+
|
| 797 |
+
if extracted_sequence:
|
| 798 |
+
# Automatically build tree with extracted sequence
|
| 799 |
+
tree_result, tree_filename = analyze_sequence_for_tree(extracted_sequence, matching_percentage=80.0)
|
| 800 |
+
results.append(f"🌳 Tree Analysis: {tree_result[:100]}... (see visualization below)")
|
| 801 |
+
if tree_filename:
|
| 802 |
+
tree_html = tree_result
|
| 803 |
+
tree_file = tree_filename
|
| 804 |
+
else:
|
| 805 |
+
tree_html = f"<p>Error in tree generation: {tree_result}</p>"
|
| 806 |
+
|
| 807 |
+
return "\n".join(results), tree_html, tree_file
|
| 808 |
|
| 809 |
+
# --- File Upload Handler ---
|
| 810 |
+
def process_uploaded_file(file):
|
| 811 |
+
"""Process uploaded FASTA file and extract sequences"""
|
| 812 |
try:
|
| 813 |
+
if file is None:
|
| 814 |
+
return "No file uploaded."
|
| 815 |
+
|
| 816 |
+
# Read file content
|
| 817 |
+
content = file.read().decode('utf-8')
|
| 818 |
+
|
| 819 |
+
# Parse FASTA format
|
| 820 |
+
sequences = []
|
| 821 |
+
current_seq = ""
|
| 822 |
+
current_header = ""
|
| 823 |
+
|
| 824 |
+
for line in content.split('\n'):
|
| 825 |
+
line = line.strip()
|
| 826 |
+
if line.startswith('>'):
|
| 827 |
+
if current_header and current_seq:
|
| 828 |
+
sequences.append((current_header, current_seq))
|
| 829 |
+
current_header = line[1:]
|
| 830 |
+
current_seq = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 831 |
else:
|
| 832 |
+
current_seq += line
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 833 |
|
| 834 |
+
# Add last sequence
|
| 835 |
+
if current_header and current_seq:
|
| 836 |
+
sequences.append((current_header, current_seq))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 837 |
|
| 838 |
+
if not sequences:
|
| 839 |
+
return "No valid sequences found in file."
|
| 840 |
+
|
| 841 |
+
# Process sequences
|
| 842 |
+
results = []
|
| 843 |
+
results.append(f"Found {len(sequences)} sequences in file:")
|
| 844 |
+
results.append("=" * 60)
|
| 845 |
+
|
| 846 |
+
for i, (header, seq) in enumerate(sequences[:5]): # Limit to first 5 sequences
|
| 847 |
+
results.append(f"\nSequence {i+1}: {header}")
|
| 848 |
+
results.append(f"Length: {len(seq)} bp")
|
| 849 |
+
|
| 850 |
+
# Run predictions (tree output not captured for file processing)
|
| 851 |
+
pred_result, _, _ = predict_sequence(seq)
|
| 852 |
+
results.append(pred_result)
|
| 853 |
+
results.append("-" * 40)
|
| 854 |
+
|
| 855 |
+
if len(sequences) > 5:
|
| 856 |
+
results.append(f"\n... and {len(sequences) - 5} more sequences.")
|
| 857 |
+
|
| 858 |
+
return "\n".join(results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 859 |
|
| 860 |
except Exception as e:
|
| 861 |
+
logging.error(f"File processing error: {e}")
|
| 862 |
+
return f"File processing failed: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 863 |
|
| 864 |
# --- Gradio Interface ---
|
| 865 |
+
def create_gradio_interface():
|
| 866 |
+
"""Create the main Gradio interface"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 867 |
|
| 868 |
+
with gr.Blocks(title="F Gene Analysis Tool", theme=gr.themes.Soft()) as demo:
|
| 869 |
gr.Markdown("""
|
| 870 |
+
# 🧬 F Gene Analysis Tool
|
| 871 |
+
|
| 872 |
+
Advanced analysis tool for F gene sequences with prediction models and phylogenetic analysis.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 873 |
""")
|
| 874 |
|
| 875 |
+
with gr.Tabs():
|
| 876 |
+
# Tab 1: Sequence Prediction
|
| 877 |
+
with gr.TabItem("🔬 Sequence Prediction"):
|
| 878 |
+
gr.Markdown("### Enter a DNA sequence for analysis")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 879 |
|
| 880 |
+
with gr.Row():
|
| 881 |
+
with gr.Column(scale=2):
|
| 882 |
+
sequence_input = gr.Textbox(
|
| 883 |
+
label="DNA Sequence",
|
| 884 |
+
placeholder="Enter your DNA sequence here (ATCG format)...",
|
| 885 |
+
lines=10,
|
| 886 |
+
max_lines=10
|
| 887 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 888 |
|
| 889 |
+
with gr.Row():
|
| 890 |
+
use_keras_check = gr.Checkbox(
|
| 891 |
+
label="Use Keras Model",
|
| 892 |
+
value=True,
|
| 893 |
+
info="Deep learning model for sequence classification"
|
| 894 |
+
)
|
| 895 |
+
use_boundary_check = gr.Checkbox(
|
| 896 |
+
label="Use Boundary Model",
|
| 897 |
+
value=True,
|
| 898 |
+
info="Extracts F gene sequence and builds tree"
|
| 899 |
+
)
|
| 900 |
|
| 901 |
+
predict_btn = gr.Button("🧠 Predict", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 902 |
|
| 903 |
+
with gr.Column(scale=1):
|
| 904 |
+
gr.Markdown("""
|
| 905 |
+
**Tips:**
|
| 906 |
+
- Use standard DNA nucleotides (A, T, C, G)
|
| 907 |
+
- Minimum sequence length: 10 bp
|
| 908 |
+
- Longer sequences provide better predictions
|
| 909 |
+
- Boundary model will extract F gene and generate a tree
|
| 910 |
+
""")
|
| 911 |
+
|
| 912 |
+
prediction_output = gr.Textbox(
|
| 913 |
+
label="Prediction Results",
|
| 914 |
+
lines=8,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 915 |
interactive=False
|
| 916 |
)
|
| 917 |
|
| 918 |
+
tree_output = gr.HTML(
|
| 919 |
+
label="Phylogenetic Tree",
|
| 920 |
+
value="<p>Tree visualization will appear here after boundary prediction.</p>"
|
| 921 |
)
|
| 922 |
|
| 923 |
+
tree_download = gr.File(
|
| 924 |
+
label="Download Tree HTML",
|
| 925 |
+
interactive=False,
|
| 926 |
+
visible=False
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
predict_btn.click(
|
| 930 |
+
fn=predict_sequence,
|
| 931 |
+
inputs=[sequence_input, use_keras_check, use_boundary_check],
|
| 932 |
+
outputs=[prediction_output, tree_output, tree_download]
|
| 933 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 934 |
|
| 935 |
+
# Tab 2: File Analysis
|
| 936 |
+
with gr.TabItem("📁 File Analysis"):
|
| 937 |
+
gr.Markdown("### Upload FASTA file for batch analysis")
|
| 938 |
+
|
| 939 |
+
file_input = gr.File(
|
| 940 |
+
label="Upload FASTA File",
|
| 941 |
+
file_types=[".fasta", ".fa", ".fas", ".txt"],
|
| 942 |
+
file_count="single"
|
| 943 |
+
)
|
| 944 |
+
|
| 945 |
+
process_file_btn = gr.Button("📊 Process File", variant="primary")
|
| 946 |
+
|
| 947 |
+
file_output = gr.Textbox(
|
| 948 |
+
label="File Analysis Results",
|
| 949 |
+
lines=15,
|
| 950 |
+
interactive=False
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
process_file_btn.click(
|
| 954 |
+
fn=process_uploaded_file,
|
| 955 |
+
inputs=file_input,
|
| 956 |
+
outputs=file_output
|
| 957 |
+
)
|
| 958 |
|
| 959 |
+
# Tab 3: Phylogenetic Analysis
|
| 960 |
+
with gr.TabItem("🌳 Phylogenetic Tree"):
|
| 961 |
+
gr.Markdown("### Phylogenetic tree analysis and sequence placement")
|
| 962 |
+
|
| 963 |
+
with gr.Row():
|
| 964 |
+
with gr.Column():
|
| 965 |
+
tree_sequence_input = gr.Textbox(
|
| 966 |
+
label="Query Sequence",
|
| 967 |
+
placeholder="Enter DNA sequence for phylogenetic placement...",
|
| 968 |
+
lines=5
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
similarity_slider = gr.Slider(
|
| 972 |
+
minimum=1,
|
| 973 |
+
maximum=99,
|
| 974 |
+
value=80,
|
| 975 |
+
step=1",
|
| 976 |
+
label="Similarity Threshold (%)",
|
| 977 |
+
info="Minimum similarity for including sequences in tree"
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
with gr.Row():
|
| 981 |
+
tree_analysis_btn = gr.Button("🌳 Build Tree", variant="primary")
|
| 982 |
+
ml_tree_btn = gr.Button("🔬 ML Tree", variant="secondary")
|
| 983 |
+
place_sequence_btn = gr.Button("📍 Place in Tree", variant="secondary")
|
| 984 |
+
|
| 985 |
+
tree_output = gr.HTML(
|
| 986 |
+
label="Phylogenetic Tree",
|
| 987 |
+
value="<p>Tree visualization will appear here after analysis.</p>"
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
tree_download = gr.File(
|
| 991 |
+
label="Download Tree HTML",
|
| 992 |
+
interactive=False,
|
| 993 |
+
visible=False
|
| 994 |
+
)
|
| 995 |
+
|
| 996 |
+
tree_status = gr.Textbox(
|
| 997 |
+
label="Analysis Status",
|
| 998 |
+
lines=5,
|
| 999 |
+
interactive=False
|
| 1000 |
+
)
|
| 1001 |
+
|
| 1002 |
+
# Event handlers for tree analysis
|
| 1003 |
+
def tree_analysis_wrapper(sequence, similarity):
|
| 1004 |
+
html_content, html_filename = analyze_sequence_for_tree(sequence, similarity)
|
| 1005 |
+
return html_content, html_filename, "Tree generated successfully"
|
| 1006 |
+
|
| 1007 |
+
tree_analysis_btn.click(
|
| 1008 |
+
fn=tree_analysis_wrapper,
|
| 1009 |
+
inputs=[tree_sequence_input, similarity_slider],
|
| 1010 |
+
outputs=[tree_output, tree_download, tree_status]
|
| 1011 |
+
)
|
| 1012 |
+
|
| 1013 |
+
def ml_tree_wrapper(sequence):
|
| 1014 |
+
success, message, alignment, tree = build_maximum_likelihood_tree(sequence)
|
| 1015 |
+
return message
|
| 1016 |
+
|
| 1017 |
+
ml_tree_btn.click(
|
| 1018 |
+
fn=ml_tree_wrapper,
|
| 1019 |
+
inputs=tree_sequence_input,
|
| 1020 |
+
outputs=tree_status
|
| 1021 |
+
)
|
| 1022 |
+
|
| 1023 |
+
def place_sequence_wrapper(sequence):
|
| 1024 |
+
tree_file, alignment_file, message = place_sequence_in_tree(sequence)
|
| 1025 |
+
return message
|
| 1026 |
+
|
| 1027 |
+
place_sequence_btn.click(
|
| 1028 |
+
fn=place_sequence_wrapper,
|
| 1029 |
+
inputs=tree_sequence_input,
|
| 1030 |
+
outputs=tree_status
|
| 1031 |
+
)
|
| 1032 |
|
| 1033 |
+
# Footer
|
| 1034 |
+
gr.Markdown("""
|
| 1035 |
+
---
|
| 1036 |
+
**F Gene Analysis Tool** - Advanced sequence analysis with machine learning and phylogenetics
|
| 1037 |
+
""")
|
| 1038 |
+
|
| 1039 |
+
return demo
|
| 1040 |
+
|
| 1041 |
+
# --- Main Application ---
|
| 1042 |
+
def main():
|
| 1043 |
+
"""Main application entry point"""
|
| 1044 |
+
try:
|
| 1045 |
+
# Log startup information
|
| 1046 |
+
logging.info("Starting F Gene Analysis Tool")
|
| 1047 |
+
logging.info(f"Boundary model available: {boundary_model is not None}")
|
| 1048 |
+
logging.info(f"Keras model available: {keras_model is not None}")
|
| 1049 |
+
logging.info(f"Tree analyzer available: {analyzer is not None}")
|
|
|
|
|
|
|
|
|
|
| 1050 |
|
| 1051 |
+
# Check tool availability
|
| 1052 |
+
mafft_available, iqtree_available, mafft_cmd, iqtree_cmd = check_tool_availability()
|
| 1053 |
+
logging.info(f"MAFFT available: {mafft_available}")
|
| 1054 |
+
logging.info(f"IQ-TREE available: {iqtree_available}")
|
| 1055 |
+
|
| 1056 |
+
# Create and launch Gradio interface
|
| 1057 |
+
demo = create_gradio_interface()
|
| 1058 |
+
|
| 1059 |
+
# Launch with appropriate settings
|
| 1060 |
+
demo.launch(
|
| 1061 |
+
server_name="0.0.0.0",
|
| 1062 |
+
server_port=7860,
|
| 1063 |
+
share=False,
|
| 1064 |
+
show_error=True
|
| 1065 |
)
|
| 1066 |
|
| 1067 |
+
except Exception as e:
|
| 1068 |
+
logging.error(f"Application startup failed: {e}")
|
| 1069 |
+
print(f"Error starting application: {e}")
|
| 1070 |
+
return 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1071 |
|
| 1072 |
+
return 0
|
| 1073 |
|
|
|
|
| 1074 |
if __name__ == "__main__":
|
| 1075 |
+
exit_code = main()
|
| 1076 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|