re-type commited on
Commit
0a52ea5
·
verified ·
1 Parent(s): b50d177

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +820 -302
app.py CHANGED
@@ -99,113 +99,390 @@ except Exception as e:
99
  logging.error(f"Failed to initialize tree analyzer: {e}")
100
  analyzer = None
101
 
102
- # --- Individual Model Functions (Separated) ---
103
- def predict_with_boundary_only(sequence):
104
- """Boundary model prediction only"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  try:
106
- if not boundary_model:
107
- return "❌ Boundary model not available", None
108
-
109
- # Clean sequence
110
- sequence = re.sub(r'[^ATCG]', '', sequence.upper())
111
- if len(sequence) < 10:
112
- return "❌ Sequence too short (minimum 10 bp required)", None
113
-
114
- # Get predictions from boundary model
115
- predictions, probabilities, confidence = boundary_model.predict(sequence)
116
-
117
- # Extract gene regions
118
- regions = boundary_model.extract_gene_regions(predictions, sequence)
119
-
120
- result = f"🎯 BOUNDARY DETECTION MODEL RESULTS:\n"
121
- result += f"Input Length: {len(sequence)} bp\n"
122
- result += f"Overall Confidence: {confidence:.4f}\n"
123
- result += f"Regions Detected: {len(regions) if regions else 0}\n"
124
-
125
- extracted_sequence = None
126
- if regions:
127
- for i, region in enumerate(regions[:3]): # Show first 3 regions
128
- result += f"\n--- Region {i+1} ---\n"
129
- result += f"Start: {region['start']}\n"
130
- result += f"End: {region['end']}\n"
131
- result += f"Length: {len(region['sequence'])} bp\n"
132
- result += f"Confidence: {region.get('confidence', 'N/A'):.4f}\n"
133
- result += f"Sequence: {region['sequence'][:50]}{'...' if len(region['sequence']) > 50 else ''}\n"
134
-
135
- # Use the first region as extracted sequence
136
- if i == 0:
137
- extracted_sequence = region['sequence']
138
 
139
- return result, extracted_sequence
 
 
 
 
 
 
 
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  except Exception as e:
142
- logging.error(f"Boundary prediction error: {e}")
143
- return f"❌ Boundary prediction failed: {str(e)}", None
144
 
145
- def predict_with_keras_only(sequence):
146
- """Keras model prediction only"""
147
  try:
148
- if not keras_model or not kmer_to_index:
149
- return "❌ Keras validation model not available"
 
 
 
 
 
 
 
 
 
 
150
 
151
- # Clean sequence
152
- sequence = re.sub(r'[^ATCG]', '', sequence.upper())
153
- if len(sequence) < 6:
154
- return "❌ Sequence too short for k-mer analysis (minimum 6 bp required)"
155
 
156
- # Generate k-mers
157
- kmers = [sequence[i:i+6] for i in range(len(sequence)-5)]
158
- indices = [kmer_to_index.get(kmer, 0) for kmer in kmers]
 
 
 
 
 
159
 
160
- # Prepare input
161
- input_arr = np.array([indices])
162
- prediction = keras_model.predict(input_arr, verbose=0)[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- # Format prediction as probabilities/scores
165
- mean_score = np.mean(prediction)
166
- max_score = np.max(prediction)
167
- min_score = np.min(prediction)
168
-
169
- result = f"🔍 KERAS VALIDATION MODEL RESULTS:\n"
170
- result += f"Input Length: {len(sequence)} bp\n"
171
- result += f"K-mers Generated: {len(kmers)}\n"
172
- result += f"Mean Score: {mean_score:.4f}\n"
173
- result += f"Max Score: {max_score:.4f}\n"
174
- result += f"Min Score: {min_score:.4f}\n"
175
-
176
- # Interpretation
177
- if mean_score > 0.7:
178
- result += f"Interpretation: ✅ High confidence gene sequence\n"
179
- elif mean_score > 0.4:
180
- result += f"Interpretation: ⚠️ Moderate confidence\n"
181
  else:
182
- result += f"Interpretation: ❌ Low confidence gene sequence\n"
 
183
 
184
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
  except Exception as e:
187
- logging.error(f"Keras prediction error: {e}")
188
- return f"❌ Keras prediction failed: {str(e)}"
189
 
190
- def analyze_sequence_for_tree_display(sequence, matching_percentage=80):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  """
192
- Create phylogenetic tree and return both HTML content and file path
193
  """
194
  try:
195
  if not analyzer:
196
- return None, None, "❌ Tree analyzer not initialized"
197
 
198
  if not sequence:
199
- return None, None, "❌ Please provide a sequence"
200
 
201
- # Clean sequence
202
- sequence = re.sub(r'[^ATCG]', '', sequence.upper())
203
- if len(sequence) < 20:
204
- return None, None, "❌ Sequence too short for tree analysis (minimum 20 bp)"
205
 
206
  # Find query sequence
207
  if not analyzer.find_query_sequence(sequence):
208
- return None, None, "❌ Sequence not found in reference dataset"
209
 
210
  # Set matching percentage
211
  analyzer.matching_percentage = matching_percentage
@@ -214,32 +491,22 @@ def analyze_sequence_for_tree_display(sequence, matching_percentage=80):
214
  matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
215
 
216
  if not matched_ids:
217
- return None, None, f"❌ No similar sequences found at {matching_percentage}% similarity"
218
 
219
  logging.info(f"Found {len(matched_ids)} similar sequences at {actual_percentage:.1f}% similarity")
220
 
221
  # Build tree structure
222
  tree_structure = analyzer.build_tree_structure(matched_ids)
223
  if not tree_structure:
224
- return None, None, "❌ Failed to build tree structure"
225
 
226
  # Create interactive tree
227
  fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
228
  if not fig:
229
- return None, None, "❌ Failed to create tree visualization"
230
 
231
- # Generate HTML content with custom height
232
- html_content = fig.to_html(
233
- full_html=True,
234
- include_plotlyjs='cdn',
235
- config={'displayModeBar': True, 'responsive': True}
236
- )
237
-
238
- # Modify HTML to set a specific height
239
- html_content = html_content.replace(
240
- '<div id="',
241
- '<div style="height: 600px; width: 100%;" id="'
242
- )
243
 
244
  # Save to output folder
245
  output_dir = "output"
@@ -254,253 +521,504 @@ def analyze_sequence_for_tree_display(sequence, matching_percentage=80):
254
 
255
  logging.info(f"Tree HTML saved to {html_filename}")
256
 
257
- success_msg = f"✅ Phylogenetic tree generated!\n"
258
- success_msg += f"Sequences analyzed: {len(matched_ids)}\n"
259
- success_msg += f"Similarity threshold: {actual_percentage:.1f}%"
260
 
261
- return html_content, html_filename, success_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  except Exception as e:
264
- error_msg = f"❌ Tree analysis error: {str(e)}"
265
  logging.error(error_msg)
266
- return None, None, error_msg
267
 
268
- # --- Combined Analysis Function ---
269
- def analyze_with_boundary_and_tree(sequence, similarity_threshold=80):
270
- """
271
- Analyze sequence with boundary model and create tree from extracted sequence
272
- """
273
  try:
274
- # Step 1: Boundary analysis
275
- boundary_result, extracted_seq = predict_with_boundary_only(sequence)
 
 
276
 
277
- if not extracted_seq:
278
- return boundary_result, None, None, "❌ No sequence extracted from boundary model"
 
 
 
 
 
 
279
 
280
- # Step 2: Tree analysis using extracted sequence
281
- html_content, html_file, tree_msg = analyze_sequence_for_tree_display(
282
- extracted_seq, similarity_threshold
283
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
- # Combine results
286
- combined_result = boundary_result + "\n\n🌳 PHYLOGENETIC TREE ANALYSIS:\n" + tree_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
 
288
- return combined_result, html_content, html_file, tree_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
290
  except Exception as e:
291
- error_msg = f"❌ Combined analysis failed: {str(e)}"
292
  logging.error(error_msg)
293
- return error_msg, None, None, error_msg
 
 
 
 
 
294
 
295
  # --- Gradio Interface ---
296
- def create_gradio_interface():
297
- """Create simplified Gradio interface"""
298
 
299
- css = """
 
300
  .gradio-container {
301
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
302
  }
303
- .output-text {
304
- font-family: 'Courier New', monospace;
305
- font-size: 12px;
306
- line-height: 1.4;
307
  }
308
- .custom-html {
309
  height: 600px !important;
310
  overflow: auto;
311
  }
312
  """
313
 
314
- with gr.Blocks(css=css, title="Gene Analysis Tool") as interface:
315
  gr.Markdown("""
316
- # 🧬 Gene Analysis Tool
317
- Analyze gene sequences with boundary detection, validation, and phylogenetic trees.
 
 
 
 
 
 
 
 
 
 
318
  """)
319
 
320
- with gr.Tabs():
321
- # Tab 1: Individual Model Analysis
322
- with gr.Tab("🔬 Individual Models"):
323
- gr.Markdown("### Analyze with individual models separately")
324
-
325
- with gr.Row():
326
- with gr.Column():
327
- individual_seq_input = gr.Textbox(
328
- label="DNA Sequence",
329
- placeholder="Enter DNA sequence (A, T, C, G only)...",
330
- lines=4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  )
332
 
333
- with gr.Row():
334
- boundary_btn = gr.Button("🎯 Boundary Detection", variant="primary")
335
- keras_btn = gr.Button("🔍 Keras Validation", variant="secondary")
336
-
337
- with gr.Row():
338
- with gr.Column():
339
- boundary_output = gr.Textbox(
340
- label="Boundary Model Results",
341
- lines=12,
342
- elem_classes=["output-text"]
343
  )
344
 
345
- with gr.Column():
346
- keras_output = gr.Textbox(
347
- label="Keras Model Results",
348
- lines=12,
349
- elem_classes=["output-text"]
350
- )
351
-
352
- # Button actions
353
- boundary_btn.click(
354
- fn=lambda seq: predict_with_boundary_only(seq)[0],
355
- inputs=[individual_seq_input],
356
- outputs=[boundary_output]
357
- )
358
-
359
- keras_btn.click(
360
- fn=predict_with_keras_only,
361
- inputs=[individual_seq_input],
362
- outputs=[keras_output]
363
- )
364
-
365
- # Tab 2: Integrated Analysis
366
- with gr.Tab("🌳 Boundary + Tree Analysis"):
367
- gr.Markdown("### Boundary detection with automatic phylogenetic tree generation")
368
 
369
- with gr.Row():
370
- with gr.Column(scale=1):
371
- integrated_seq_input = gr.Textbox(
372
- label="DNA Sequence",
373
- placeholder="Enter DNA sequence for boundary detection and tree analysis...",
374
- lines=4
375
- )
 
 
 
 
 
 
 
 
 
 
376
 
377
- similarity_slider = gr.Slider(
378
- minimum=1,
379
- maximum=99,
380
- value=80,
381
- step=1,
382
- label="Tree Similarity Threshold (%)"
383
- )
384
 
385
- integrated_btn = gr.Button("🚀 Analyze & Build Tree", variant="primary")
 
 
 
386
 
387
- with gr.Column(scale=2):
388
- integrated_output = gr.Textbox(
389
- label="Analysis Results",
390
- lines=15,
391
- elem_classes=["output-text"]
392
- )
393
-
394
- # Tree display section
395
- gr.Markdown("### 🌳 Interactive Phylogenetic Tree")
396
-
397
- with gr.Row():
398
- with gr.Column():
399
- tree_html = gr.HTML(
400
- label="Phylogenetic Tree",
401
- elem_classes=["custom-html"]
402
- )
403
 
404
- with gr.Column(scale=0.3):
405
- tree_download = gr.File(
406
- label="Download Tree (HTML)",
407
- file_count="single"
408
- )
409
-
410
- tree_status = gr.Textbox(
411
- label="Tree Status",
412
- lines=3,
413
- elem_classes=["output-text"]
414
- )
415
-
416
- # Integrated analysis action
417
- integrated_btn.click(
418
- fn=analyze_with_boundary_and_tree,
419
- inputs=[integrated_seq_input, similarity_slider],
420
- outputs=[integrated_output, tree_html, tree_download, tree_status]
421
- )
422
 
423
- # Tab 3: Quick Tree Analysis
424
- with gr.Tab("🌲 Direct Tree Analysis"):
425
- gr.Markdown("### Create phylogenetic tree from any sequence")
426
-
427
- with gr.Row():
428
- with gr.Column():
429
- direct_seq_input = gr.Textbox(
430
- label="DNA Sequence",
431
- placeholder="Enter sequence for direct tree analysis...",
432
- lines=4
433
- )
434
-
435
- direct_similarity_slider = gr.Slider(
436
- minimum=1,
437
- maximum=99,
438
- value=80,
439
- step=1,
440
- label="Similarity Threshold (%)"
441
- )
442
-
443
- direct_tree_btn = gr.Button("🌳 Generate Tree", variant="primary")
444
 
445
- with gr.Row():
446
- with gr.Column():
447
- direct_tree_html = gr.HTML(
448
- label="Phylogenetic Tree",
449
- elem_classes=["custom-html"]
450
- )
451
-
452
- with gr.Column(scale=0.3):
453
- direct_tree_download = gr.File(
454
- label="Download Tree (HTML)"
455
- )
456
-
457
- direct_tree_status = gr.Textbox(
458
- label="Tree Status",
459
- lines=4,
460
- elem_classes=["output-text"]
461
- )
462
 
463
- # Direct tree analysis action
464
- direct_tree_btn.click(
465
- fn=analyze_sequence_for_tree_display,
466
- inputs=[direct_seq_input, direct_similarity_slider],
467
- outputs=[direct_tree_html, direct_tree_download, direct_tree_status]
468
  )
469
 
470
- # Footer with model status
471
- gr.Markdown(f"""
472
- ---
473
- **Model Status:**
474
- Boundary Model: {"✅" if boundary_model else "❌"} |
475
- Keras Model: {"✅" if keras_model else "❌"} |
476
- Tree Analyzer: {"✅" if analyzer else "❌"}
477
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
 
479
- return interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
 
481
- # --- Main Application ---
482
  if __name__ == "__main__":
483
- # Create output directories
484
- os.makedirs("output", exist_ok=True)
485
-
486
- # Log startup information
487
- logging.info("Starting Gene Analysis Tool")
488
- logging.info(f"Boundary model loaded: {boundary_model is not None}")
489
- logging.info(f"Keras model loaded: {keras_model is not None}")
490
- logging.info(f"Tree analyzer initialized: {analyzer is not None}")
491
 
492
- # Create and launch interface
493
- try:
494
- interface = create_gradio_interface()
495
-
496
- # Launch with appropriate settings
497
- interface.launch(
498
- share=False,
499
- server_name="0.0.0.0",
500
- server_port=7860,
501
- show_error=True
502
- )
503
-
504
- except Exception as e:
505
- logging.error(f"Failed to launch interface: {e}")
506
- sys.exit(1)
 
99
  logging.error(f"Failed to initialize tree analyzer: {e}")
100
  analyzer = None
101
 
102
+ # --- Enhanced Tool Detection ---
103
+ def check_tool_availability():
104
+ """Enhanced check for MAFFT and IQ-TREE availability with multiple fallback options"""
105
+
106
+ # Check MAFFT
107
+ mafft_available = False
108
+ mafft_cmd = None
109
+
110
+ # Try multiple MAFFT locations
111
+ mafft_candidates = [
112
+ MAFFT_PATH,
113
+ 'mafft',
114
+ '/usr/bin/mafft',
115
+ '/usr/local/bin/mafft',
116
+ 'mafft.bat', # Windows
117
+ ]
118
+
119
+ for candidate in mafft_candidates:
120
+ if candidate and (os.path.exists(candidate) or shutil.which(candidate) is not None):
121
+ mafft_available = True
122
+ mafft_cmd = candidate
123
+ logging.info(f"Found MAFFT at: {candidate}")
124
+ break
125
+
126
+ # Check IQ-TREE
127
+ iqtree_available = False
128
+ iqtree_cmd = None
129
+
130
+ # Try multiple IQ-TREE locations and names
131
+ iqtree_candidates = [
132
+ IQTREE_PATH,
133
+ 'iqtree2',
134
+ 'iqtree',
135
+ '/usr/bin/iqtree2',
136
+ '/usr/local/bin/iqtree2',
137
+ '/usr/bin/iqtree',
138
+ '/usr/local/bin/iqtree',
139
+ 'iqtree2.exe', # Windows
140
+ 'iqtree.exe', # Windows
141
+ ]
142
+
143
+ for candidate in iqtree_candidates:
144
+ if candidate and (os.path.exists(candidate) or shutil.which(candidate) is not None):
145
+ iqtree_available = True
146
+ iqtree_cmd = candidate
147
+ logging.info(f"Found IQ-TREE at: {candidate}")
148
+ break
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 = """
155
+ 🔧 INSTALLATION GUIDE FOR MISSING DEPENDENCIES:
156
+
157
+ For MAFFT:
158
+ - Ubuntu/Debian: sudo apt-get install mafft
159
+ - CentOS/RHEL: sudo yum install mafft
160
+ - macOS: brew install mafft
161
+ - Windows: Download from https://mafft.cbrc.jp/alignment/software/
162
+
163
+ For IQ-TREE:
164
+ - Ubuntu/Debian: sudo apt-get install iqtree
165
+ - CentOS/RHEL: sudo yum install iqtree
166
+ - macOS: brew install iqtree
167
+ - Windows: Download from http://www.iqtree.org/
168
+
169
+ Alternative: Use conda/mamba:
170
+ - conda install -c bioconda mafft iqtree
171
+
172
+ Docker option:
173
+ - docker run -it --rm -v $(pwd):/data quay.io/biocontainers/mafft:7.490--h779adbc_0
174
+ - docker run -it --rm -v $(pwd):/data quay.io/biocontainers/iqtree:2.1.4_beta--hdcc8f71_0
175
+ """
176
+ return guide
177
+
178
+ def run_mafft_alignment(input_fasta, output_fasta, mafft_cmd):
179
+ """Run MAFFT alignment with enhanced error handling"""
180
  try:
181
+ # MAFFT command with more robust options
182
+ cmd = [
183
+ mafft_cmd,
184
+ '--auto', # Automatic strategy selection
185
+ '--quiet', # Reduce output verbosity
186
+ input_fasta
187
+ ]
188
+
189
+ logging.info(f"Running MAFFT: {' '.join(cmd)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
+ # Run MAFFT with enhanced error handling
192
+ result = subprocess.run(
193
+ cmd,
194
+ capture_output=True,
195
+ text=True,
196
+ timeout=600, # Increased timeout to 10 minutes
197
+ cwd=os.getcwd() # Ensure working directory is set
198
+ )
199
 
200
+ if result.returncode == 0:
201
+ # Write aligned sequences to output file
202
+ with open(output_fasta, 'w') as f:
203
+ f.write(result.stdout)
204
+ logging.info(f"MAFFT alignment completed: {output_fasta}")
205
+
206
+ # Verify output file
207
+ if os.path.exists(output_fasta) and os.path.getsize(output_fasta) > 0:
208
+ return True, output_fasta
209
+ else:
210
+ return False, "MAFFT completed but output file is empty"
211
+ else:
212
+ error_msg = result.stderr.strip() if result.stderr else "Unknown MAFFT error"
213
+ logging.error(f"MAFFT failed: {error_msg}")
214
+ return False, f"MAFFT error: {error_msg}"
215
+
216
+ except subprocess.TimeoutExpired:
217
+ logging.error("MAFFT timeout")
218
+ return False, "MAFFT timeout (>10 minutes). Try with fewer sequences."
219
+ except FileNotFoundError:
220
+ return False, f"MAFFT executable not found: {mafft_cmd}"
221
  except Exception as e:
222
+ logging.error(f"MAFFT execution failed: {e}")
223
+ return False, f"MAFFT execution failed: {str(e)}"
224
 
225
+ def run_iqtree_analysis(aligned_fasta, output_prefix, iqtree_cmd):
226
+ """Run IQ-TREE with enhanced options and error handling"""
227
  try:
228
+ # Enhanced IQ-TREE command
229
+ cmd = [
230
+ iqtree_cmd,
231
+ '-s', aligned_fasta,
232
+ '-m', 'MFP', # ModelFinder Plus for automatic model selection
233
+ '-bb', '1000', # Bootstrap replicates
234
+ '-alrt', '1000', # SH-aLRT test
235
+ '-nt', 'AUTO', # Auto detect threads
236
+ '--prefix', output_prefix,
237
+ '-redo', # Overwrite existing files
238
+ '--quiet' # Reduce verbosity
239
+ ]
240
 
241
+ logging.info(f"Running IQ-TREE: {' '.join(cmd)}")
 
 
 
242
 
243
+ # Run IQ-TREE with enhanced error handling
244
+ result = subprocess.run(
245
+ cmd,
246
+ capture_output=True,
247
+ text=True,
248
+ timeout=1200, # 20 minute timeout for larger datasets
249
+ cwd=os.getcwd()
250
+ )
251
 
252
+ if result.returncode == 0:
253
+ tree_file = f"{output_prefix}.treefile"
254
+ if os.path.exists(tree_file) and os.path.getsize(tree_file) > 0:
255
+ logging.info(f"IQ-TREE analysis completed: {tree_file}")
256
+ return True, tree_file
257
+ else:
258
+ logging.error("IQ-TREE completed but tree file not found or empty")
259
+ return False, "Tree file not generated or empty"
260
+ else:
261
+ error_msg = result.stderr.strip() if result.stderr else "Unknown IQ-TREE error"
262
+ logging.error(f"IQ-TREE failed: {error_msg}")
263
+ return False, f"IQ-TREE error: {error_msg}"
264
+
265
+ except subprocess.TimeoutExpired:
266
+ logging.error("IQ-TREE timeout")
267
+ return False, "IQ-TREE timeout (>20 minutes). Try with fewer sequences or simpler model."
268
+ except FileNotFoundError:
269
+ return False, f"IQ-TREE executable not found: {iqtree_cmd}"
270
+ except Exception as e:
271
+ logging.error(f"IQ-TREE execution failed: {e}")
272
+ return False, f"IQ-TREE execution failed: {str(e)}"
273
+
274
+ def create_simple_neighbor_joining_tree(sequences_dict):
275
+ """Create a simple distance-based tree when ML tools are not available"""
276
+ try:
277
+ # This is a simplified implementation
278
+ # In a real scenario, you'd want to use a proper NJ implementation
279
+ import random
280
 
281
+ seq_names = list(sequences_dict.keys())
282
+ n_seqs = len(seq_names)
283
+
284
+ if n_seqs < 2:
285
+ return None, "Need at least 2 sequences for tree construction"
286
+
287
+ # Create a simple Newick tree structure
288
+ if n_seqs == 2:
289
+ tree_str = f"({seq_names[0]}:0.1,{seq_names[1]}:0.1);"
 
 
 
 
 
 
 
 
290
  else:
291
+ # Simple clustering approach
292
+ tree_str = "(" + ",".join([f"{name}:0.1" for name in seq_names[:5]]) + ");"
293
 
294
+ # Save to temporary file
295
+ tree_file = "simple_tree.nwk"
296
+ with open(tree_file, 'w') as f:
297
+ f.write(tree_str)
298
+
299
+ return tree_file, "Simple distance-based tree created"
300
+
301
+ except Exception as e:
302
+ return None, f"Simple tree creation failed: {str(e)}"
303
+
304
+ def create_multi_fasta_with_query(query_sequence, query_id="Query_F_Gene"):
305
+ """Create a multi-FASTA file with query sequence and reference sequences"""
306
+ try:
307
+ # Create temporary FASTA file
308
+ temp_fasta = tempfile.NamedTemporaryFile(mode='w', suffix='.fasta', delete=False)
309
+
310
+ # Add query sequence
311
+ temp_fasta.write(f">{query_id}\n{query_sequence}\n")
312
+
313
+ # Add reference sequences from existing aligned FASTA if available
314
+ ref_fasta_path = "f_gene_sequences_aligned.fasta"
315
+ if os.path.exists(ref_fasta_path):
316
+ with open(ref_fasta_path, 'r') as ref_file:
317
+ temp_fasta.write(ref_file.read())
318
+ logging.info(f"Added reference sequences from {ref_fasta_path}")
319
+ else:
320
+ # If no reference file, try to create from CSV data
321
+ if analyzer and hasattr(analyzer, 'data'):
322
+ count = 0
323
+ for idx, row in analyzer.data.iterrows():
324
+ if 'sequence' in row and len(str(row['sequence'])) > 50:
325
+ seq_id = row.get('id', f"Ref_{count}")
326
+ sequence = str(row['sequence']).upper()
327
+ temp_fasta.write(f">{seq_id}\n{sequence}\n")
328
+ count += 1
329
+ if count >= 20: # Limit to prevent too large datasets
330
+ break
331
+ logging.info(f"Added {count} reference sequences from CSV")
332
+
333
+ temp_fasta.close()
334
+ return temp_fasta.name
335
 
336
  except Exception as e:
337
+ logging.error(f"Failed to create multi-FASTA: {e}")
338
+ return None
339
 
340
+ def build_maximum_likelihood_tree(f_gene_sequence):
341
+ """Build maximum likelihood phylogenetic tree with comprehensive fallback options"""
342
+ try:
343
+ # Check tool availability with enhanced detection
344
+ mafft_available, iqtree_available, mafft_cmd, iqtree_cmd = check_tool_availability()
345
+
346
+ # Prepare status message
347
+ status_msg = "🔍 Checking dependencies...\n"
348
+
349
+ if not mafft_available:
350
+ status_msg += "❌ MAFFT not found\n"
351
+ else:
352
+ status_msg += f"✅ MAFFT found: {mafft_cmd}\n"
353
+
354
+ if not iqtree_available:
355
+ status_msg += "❌ IQ-TREE not found\n"
356
+ else:
357
+ status_msg += f"✅ IQ-TREE found: {iqtree_cmd}\n"
358
+
359
+ # If neither tool is available, provide installation guide
360
+ if not mafft_available and not iqtree_available:
361
+ guide = install_dependencies_guide()
362
+ return False, f"{status_msg}\n{guide}", None, None
363
+
364
+ # If only one tool is missing, provide specific guidance
365
+ if not mafft_available:
366
+ return False, f"{status_msg}\n❌ MAFFT is required for sequence alignment. Please install MAFFT first.", None, None
367
+
368
+ if not iqtree_available:
369
+ status_msg += "\n⚠️ IQ-TREE not available. Attempting simple tree construction...\n"
370
+
371
+ # Try to create a simple tree as fallback
372
+ multi_fasta = create_multi_fasta_with_query(f_gene_sequence)
373
+ if multi_fasta:
374
+ # Read sequences
375
+ sequences = {}
376
+ current_seq = ""
377
+ current_name = ""
378
+
379
+ with open(multi_fasta, 'r') as f:
380
+ for line in f:
381
+ line = line.strip()
382
+ if line.startswith('>'):
383
+ if current_name and current_seq:
384
+ sequences[current_name] = current_seq
385
+ current_name = line[1:]
386
+ current_seq = ""
387
+ else:
388
+ current_seq += line
389
+ if current_name and current_seq:
390
+ sequences[current_name] = current_seq
391
+
392
+ simple_tree, simple_msg = create_simple_neighbor_joining_tree(sequences)
393
+ os.unlink(multi_fasta)
394
+
395
+ if simple_tree:
396
+ return True, f"{status_msg}✅ {simple_msg}", None, simple_tree
397
+ else:
398
+ return False, f"{status_msg}❌ {simple_msg}", None, None
399
+ else:
400
+ return False, f"{status_msg}❌ Failed to create input sequences", None, None
401
+
402
+ # Both tools available - proceed with full ML analysis
403
+ # Create output directory
404
+ output_dir = "ml_tree_output"
405
+ os.makedirs(output_dir, exist_ok=True)
406
+
407
+ # Step 1: Create multi-FASTA file with query and reference sequences
408
+ logging.info("Creating multi-FASTA file...")
409
+ multi_fasta = create_multi_fasta_with_query(f_gene_sequence)
410
+ if not multi_fasta:
411
+ return False, f"{status_msg}❌ Failed to create input FASTA", None, None
412
+
413
+ # Step 2: Run MAFFT alignment
414
+ logging.info("Running MAFFT alignment...")
415
+ aligned_fasta = os.path.join(output_dir, "aligned_sequences.fasta")
416
+ mafft_success, mafft_result = run_mafft_alignment(multi_fasta, aligned_fasta, mafft_cmd)
417
+
418
+ # Clean up temporary file
419
+ os.unlink(multi_fasta)
420
+
421
+ if not mafft_success:
422
+ return False, f"{status_msg}❌ MAFFT failed: {mafft_result}", None, None
423
+
424
+ # Step 3: Run IQ-TREE analysis
425
+ logging.info("Running IQ-TREE analysis...")
426
+ tree_prefix = os.path.join(output_dir, "ml_tree")
427
+ iqtree_success, iqtree_result = run_iqtree_analysis(aligned_fasta, tree_prefix, iqtree_cmd)
428
+
429
+ if not iqtree_success:
430
+ return False, f"{status_msg}❌ IQ-TREE failed: {iqtree_result}", aligned_fasta, None
431
+
432
+ # Step 4: Prepare output files
433
+ tree_file = iqtree_result
434
+ log_file = f"{tree_prefix}.log"
435
+
436
+ # Copy to standard names for compatibility
437
+ standard_aligned = "f_gene_sequences_aligned.fasta"
438
+ standard_tree = "f_gene_sequences.phy.treefile"
439
+
440
+ if os.path.exists(aligned_fasta):
441
+ shutil.copy2(aligned_fasta, standard_aligned)
442
+ if os.path.exists(tree_file):
443
+ shutil.copy2(tree_file, standard_tree)
444
+
445
+ success_msg = f"{status_msg}✅ Maximum likelihood tree built successfully!\n"
446
+ success_msg += f"- Alignment: {os.path.basename(aligned_fasta)}\n"
447
+ success_msg += f"- Tree: {os.path.basename(tree_file)}\n"
448
+
449
+ if os.path.exists(log_file):
450
+ try:
451
+ with open(log_file, 'r') as f:
452
+ log_content = f.read()
453
+ # Extract model information
454
+ if "Best-fit model:" in log_content:
455
+ model_lines = [line for line in log_content.split('\n') if "Best-fit model:" in line]
456
+ if model_lines:
457
+ success_msg += f"- {model_lines[0].strip()}\n"
458
+ except Exception as e:
459
+ logging.warning(f"Could not read log file: {e}")
460
+
461
+ logging.info("Maximum likelihood tree construction completed")
462
+ return True, success_msg, aligned_fasta, tree_file
463
+
464
+ except Exception as e:
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 (Based on old Gradio API) ---
469
+ def analyze_sequence_for_tree(sequence: str, matching_percentage: float) -> str:
470
  """
471
+ Analyze sequence and create phylogenetic tree using the working Gradio API pattern
472
  """
473
  try:
474
  if not analyzer:
475
+ return "Error: Tree analyzer not initialized. Please check if the CSV data file is available."
476
 
477
  if not sequence:
478
+ return "Error: Please provide a sequence."
479
 
480
+ if not (1 <= matching_percentage <= 99):
481
+ return "Error: Matching percentage must be between 1 and 99."
 
 
482
 
483
  # Find query sequence
484
  if not analyzer.find_query_sequence(sequence):
485
+ return "Error: Invalid query sequence or sequence not found in dataset."
486
 
487
  # Set matching percentage
488
  analyzer.matching_percentage = matching_percentage
 
491
  matched_ids, actual_percentage = analyzer.find_similar_sequences(matching_percentage)
492
 
493
  if not matched_ids:
494
+ return f"No similar sequences found at {matching_percentage}% similarity. Try lowering the threshold."
495
 
496
  logging.info(f"Found {len(matched_ids)} similar sequences at {actual_percentage:.1f}% similarity")
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')
 
 
 
 
 
 
 
 
 
 
510
 
511
  # Save to output folder
512
  output_dir = "output"
 
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):
535
+ try:
536
+ if not keras_model or not kmer_to_index:
537
+ return f"Keras model not available. Input sequence: {sequence[:100]}..."
538
+
539
+ if len(sequence) < 6:
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
+ # Prepare input
547
+ input_arr = np.array([indices])
548
+ prediction = keras_model.predict(input_arr, verbose=0)[0]
549
+
550
+ # Format prediction as probabilities/scores (not a sequence)
551
+ result = ''.join([str(round(p, 3)) for p in prediction])
552
+ return result
553
+ except Exception as e:
554
+ logging.error(f"Keras prediction failed: {e}")
555
+ return f"Keras prediction failed: {str(e)}"
556
+
557
+ # --- FASTA Reader ---
558
+ def read_fasta_file(file_obj):
559
+ try:
560
+ if file_obj is None:
561
+ return ""
562
+
563
+ # Handle file object
564
+ if hasattr(file_obj, 'name'):
565
+ with open(file_obj.name, "r") as f:
566
+ content = f.read()
567
+ else:
568
+ content = file_obj.read().decode("utf-8") if hasattr(file_obj, "read") else str(file_obj)
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"Failed to read FASTA file: {e}")
575
+ return ""
576
+
577
+ # --- Full Pipeline ---
578
+ def run_pipeline_from_file(fasta_file_obj, similarity_score, build_ml_tree):
579
+ try:
580
+ dna_input = read_fasta_file(fasta_file_obj)
581
+ if not dna_input:
582
+ return "Failed to read FASTA file", "", "", "", "", None, None, None, "No input sequence"
583
+ return run_pipeline(dna_input, similarity_score, build_ml_tree)
584
  except Exception as e:
585
+ error_msg = f"Pipeline error: {str(e)}"
586
  logging.error(error_msg)
587
+ return error_msg, "", "", "", "", None, None, None, error_msg
588
 
589
+ def run_pipeline(dna_input, similarity_score=95.0, build_ml_tree=False):
 
 
 
 
590
  try:
591
+ # Clean input
592
+ dna_input = dna_input.upper().strip()
593
+ if not dna_input:
594
+ return "Empty input", "", "", "", "", None, None, None, "No input provided"
595
 
596
+ # Sanitize DNA sequence
597
+ if not re.match('^[ACTGN]+$', dna_input):
598
+ dna_input = ''.join(c if c in 'ACTGN' else 'N' for c in dna_input)
599
+ logging.info("DNA sequence sanitized")
600
+
601
+ # Step 1: Boundary Prediction - Extract F gene sequence
602
+ processed_sequence = dna_input # This will be the sequence used for downstream analysis
603
+ boundary_output = ""
604
 
605
+ if boundary_model:
606
+ try:
607
+ predictions, probs, confidence = boundary_model.predict(dna_input)
608
+ regions = boundary_model.extract_gene_regions(predictions, dna_input)
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
+ keras_output = keras_prediction
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
+ if build_ml_tree and processed_sequence and len(processed_sequence) >= 50:
646
+ try:
647
+ logging.info("Starting maximum likelihood tree construction...")
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 analyzer and processed_sequence and len(processed_sequence) >= 10:
671
+ try:
672
+ logging.info(f"Starting simplified ML tree analysis with F gene sequence length: {len(processed_sequence)}")
673
+
674
+ # Use the existing tree analysis function with user-specified similarity
675
+ tree_result = analyze_sequence_for_tree(processed_sequence, matching_percentage=similarity_score)
676
+
677
+ if tree_result and not tree_result.startswith("Error:"):
678
+ # Success - we have HTML content
679
+ tree_html_content = tree_result
680
+ simplified_ml_output = "✅ Simplified phylogenetic tree generated successfully!"
681
+
682
+ # Check if HTML file was created
683
+ output_dir = "output"
684
+ if os.path.exists(output_dir):
685
+ html_files = [f for f in os.listdir(output_dir) if f.endswith('.html')]
686
+ if html_files:
687
+ html_file = os.path.join(output_dir, html_files[-1]) # Get the latest
688
+ simplified_ml_output += f"\n- Tree file: {html_files[-1]}"
689
+
690
+ # Count sequences analyzed
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
+ error_msg = f"Pipeline execution failed: {str(e)}"
724
  logging.error(error_msg)
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 create_interface():
734
+ """Create the Gradio interface with enhanced layout and features"""
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(css=custom_css, title="F Gene Analysis Pipeline") as iface:
751
  gr.Markdown("""
752
+ # 🧬 F Gene Analysis Pipeline
753
+
754
+ This tool provides comprehensive analysis of F genes including:
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.Tab("🔬 Analysis Pipeline"):
767
+ with gr.Row():
768
+ with gr.Column(scale=2):
769
+ # Input section
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.Column(scale=1):
805
+ # Status and info
806
+ gr.Markdown("### Analysis Status")
807
+ status_display = gr.Textbox(
808
+ label="Status",
809
+ value="Ready to analyze",
810
+ interactive=False,
811
+ lines=3
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
+ if keras_model:
823
+ model_status.append("✅ Gene Validation Model")
824
+ else:
825
+ model_status.append("❌ Gene Validation Model")
 
 
 
826
 
827
+ if analyzer:
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
+ keras_output = gr.Textbox(
845
+ label="🔍 Gene Validation",
846
+ lines=3,
847
+ interactive=False
848
+ )
849
+
850
+ with gr.Column():
851
+ ml_tree_output = gr.Textbox(
852
+ label="🌳 Maximum Likelihood Tree",
853
+ lines=5,
854
+ interactive=False
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
+ phy_file = gr.File(
879
+ label="Phylogenetic Tree File",
880
+ interactive=False
881
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
882
 
883
+ html_file = gr.File(
884
+ label="Interactive Tree (HTML)",
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
+ **Performance Tips:**
951
+ - Use sequences between 100-2000 bp for optimal performance
952
+ - Limit to <50 sequences for faster tree construction
953
+ - Lower similarity thresholds find more distant relatives
954
+ - Higher thresholds focus on closely related sequences
955
+
956
+ ### Citation
957
+ If you use this tool in your research, please cite the appropriate methods and tools used.
958
+ """)
959
+
960
+ # Event handlers
961
+ def run_analysis_text(dna_seq, sim_score, build_tree):
962
+ return run_pipeline(dna_seq, sim_score, build_tree)
963
+
964
+ def run_analysis_file(file_obj, sim_score, build_tree):
965
+ return run_pipeline_from_file(file_obj, sim_score, build_tree)
966
 
967
+ def run_analysis_combined(dna_seq, file_obj, sim_score, build_tree):
968
+ # Priority: file upload over text input
969
+ if file_obj is not None:
970
+ return run_pipeline_from_file(file_obj, sim_score, build_tree)
971
+ else:
972
+ return run_pipeline(dna_seq, sim_score, build_tree)
973
+
974
+ def clear_inputs():
975
+ return "", None, 95.0, False, "Ready to analyze"
976
+
977
+ # Connect events
978
+ run_btn.click(
979
+ fn=run_analysis_combined,
980
+ inputs=[dna_input, fasta_file, similarity_score, build_ml_tree],
981
+ outputs=[
982
+ boundary_output, keras_output, ml_tree_output,
983
+ simplified_ml_output, tree_html, aligned_file,
984
+ phy_file, html_file, status_display
985
+ ]
986
+ )
987
+
988
+ clear_btn.click(
989
+ fn=clear_inputs,
990
+ outputs=[dna_input, fasta_file, similarity_score, build_ml_tree, status_display]
991
+ )
992
+
993
+ # Example data loading
994
+ gr.Markdown("### 🧪 Example Data")
995
+ example_btn = gr.Button("Load Example F Gene Sequence", variant="secondary")
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 iface
1007
 
1008
+ # --- Main Execution ---
1009
  if __name__ == "__main__":
1010
+ # Initialize and launch interface
1011
+ interface = create_interface()
 
 
 
 
 
 
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
+ )