re-type commited on
Commit
255fa59
·
verified ·
1 Parent(s): 1c86223

Update app.py

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