re-type commited on
Commit
7cccf18
·
verified ·
1 Parent(s): 3b2b697

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -7
app.py CHANGED
@@ -7,10 +7,14 @@ import pandas as pd
7
  import os
8
  import re
9
  import logging
 
10
  from predictor import GenePredictor
11
  from tensorflow.keras.models import load_model
12
  import ml_simplified_tree
13
 
 
 
 
14
  # --- Logging ---
15
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
16
 
@@ -37,13 +41,26 @@ if os.path.exists(keras_path) and os.path.exists(kmer_path):
37
 
38
  # --- Keras Prediction ---
39
  def predict_with_keras(sequence):
 
 
40
  kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
41
  indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
42
- input_arr = torch.tensor([indices])
43
  prediction = keras_model.predict(input_arr, verbose=0)[0]
44
  return ''.join(str(round(p, 3)) for p in prediction)
45
 
 
 
 
 
 
 
 
46
  # --- Full Pipeline ---
 
 
 
 
47
  def run_pipeline(dna_input):
48
  dna_input = dna_input.upper()
49
  if not re.match('^[ACTGN]+$', dna_input):
@@ -67,8 +84,9 @@ def run_pipeline(dna_input):
67
 
68
  # Run MAFFT
69
  aligned_file = "aligned.fasta"
 
70
  try:
71
- subprocess.run(["mafft", "--auto", fasta_file], stdout=open(aligned_file, "w"), check=True)
72
  except Exception as e:
73
  aligned_file = None
74
  logging.error(f"MAFFT failed: {e}")
@@ -90,21 +108,34 @@ def run_pipeline(dna_input):
90
  matched_ids, perc = analyzer.find_similar_sequences(analyzer.matching_percentage)
91
  analyzer.create_interactive_tree(matched_ids, perc)
92
  ml_output = "Tree generated."
 
 
 
 
 
93
  else:
94
  ml_output = "Query sequence not found."
 
95
  else:
96
  ml_output = "Failed to load CSV."
 
97
  else:
98
  ml_output = "CSV file missing."
 
99
 
100
- return step1_out, step2_out, csv_path, ml_output, html_file, aligned_file, phy_file
101
 
102
  # --- Gradio UI ---
103
  with gr.Blocks() as demo:
104
  gr.Markdown("# Viral Gene Phylogenetic Inference Pipeline")
105
 
106
- inp = gr.Textbox(label="DNA Input")
107
- btn = gr.Button("Run Pipeline")
 
 
 
 
 
108
 
109
  out1 = gr.Textbox(label="Boundary Model Output")
110
  out2 = gr.Textbox(label="Keras Model Output")
@@ -113,8 +144,10 @@ with gr.Blocks() as demo:
113
  html = gr.File(label="ML Tree (HTML)", file_types=['.html'])
114
  fasta = gr.File(label="Aligned FASTA", file_types=['.fasta'])
115
  phy = gr.File(label="IQ-TREE .phy File", file_types=['.phy'])
 
116
 
117
- btn.click(fn=run_pipeline, inputs=inp, outputs=[out1, out2, out3, out4, html, fasta, phy])
 
118
 
119
  if __name__ == '__main__':
120
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
7
  import os
8
  import re
9
  import logging
10
+ import numpy as np
11
  from predictor import GenePredictor
12
  from tensorflow.keras.models import load_model
13
  import ml_simplified_tree
14
 
15
+ # --- Global Variables ---
16
+ MAFFT_PATH = "mafft/mafftdir/bin/mafft"
17
+
18
  # --- Logging ---
19
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
20
 
 
41
 
42
  # --- Keras Prediction ---
43
  def predict_with_keras(sequence):
44
+ if len(sequence) < 6:
45
+ return "Sequence too short for k-mer prediction."
46
  kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
47
  indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
48
+ input_arr = np.array([indices]) # Changed from torch.tensor to np.array
49
  prediction = keras_model.predict(input_arr, verbose=0)[0]
50
  return ''.join(str(round(p, 3)) for p in prediction)
51
 
52
+ # --- FASTA Reader ---
53
+ def read_fasta_file(f):
54
+ content = f.read().decode("utf-8") if hasattr(f, "read") else open(f, "r").read()
55
+ lines = content.strip().split("\n")
56
+ seq_lines = [line.strip() for line in lines if not line.startswith(">")]
57
+ return ''.join(seq_lines)
58
+
59
  # --- Full Pipeline ---
60
+ def run_pipeline_from_file(fasta_file_obj):
61
+ dna_input = read_fasta_file(fasta_file_obj)
62
+ return run_pipeline(dna_input)
63
+
64
  def run_pipeline(dna_input):
65
  dna_input = dna_input.upper()
66
  if not re.match('^[ACTGN]+$', dna_input):
 
84
 
85
  # Run MAFFT
86
  aligned_file = "aligned.fasta"
87
+ mafft_exec = MAFFT_PATH # Use global variable
88
  try:
89
+ subprocess.run([mafft_exec, "--auto", fasta_file], stdout=open(aligned_file, "w"), check=True)
90
  except Exception as e:
91
  aligned_file = None
92
  logging.error(f"MAFFT failed: {e}")
 
108
  matched_ids, perc = analyzer.find_similar_sequences(analyzer.matching_percentage)
109
  analyzer.create_interactive_tree(matched_ids, perc)
110
  ml_output = "Tree generated."
111
+ if os.path.exists(html_file):
112
+ with open(html_file, "r") as f:
113
+ tree_html_content = f.read()
114
+ else:
115
+ tree_html_content = "Tree HTML file not generated."
116
  else:
117
  ml_output = "Query sequence not found."
118
+ tree_html_content = "No tree generated."
119
  else:
120
  ml_output = "Failed to load CSV."
121
+ tree_html_content = "No tree generated."
122
  else:
123
  ml_output = "CSV file missing."
124
+ tree_html_content = "No tree generated."
125
 
126
+ return step1_out, step2_out, csv_path, ml_output, html_file, aligned_file, phy_file, tree_html_content
127
 
128
  # --- Gradio UI ---
129
  with gr.Blocks() as demo:
130
  gr.Markdown("# Viral Gene Phylogenetic Inference Pipeline")
131
 
132
+ with gr.Tab("Paste DNA"):
133
+ inp = gr.Textbox(label="DNA Input")
134
+ btn1 = gr.Button("Run Pipeline")
135
+
136
+ with gr.Tab("Upload FASTA"):
137
+ file_input = gr.File(label="FASTA File", file_types=['.fasta', '.fa'])
138
+ btn2 = gr.Button("Run on FASTA")
139
 
140
  out1 = gr.Textbox(label="Boundary Model Output")
141
  out2 = gr.Textbox(label="Keras Model Output")
 
144
  html = gr.File(label="ML Tree (HTML)", file_types=['.html'])
145
  fasta = gr.File(label="Aligned FASTA", file_types=['.fasta'])
146
  phy = gr.File(label="IQ-TREE .phy File", file_types=['.phy'])
147
+ tree_html = gr.HTML(label="Interactive Tree Preview")
148
 
149
+ btn1.click(fn=run_pipeline, inputs=inp, outputs=[out1, out2, out3, out4, html, fasta, phy, tree_html])
150
+ btn2.click(fn=run_pipeline_from_file, inputs=file_input, outputs=[out1, out2, out3, out4, html, fasta, phy, tree_html])
151
 
152
  if __name__ == '__main__':
153
+ demo.launch(server_name="0.0.0.0", server_port=7860)