re-type commited on
Commit
126c1f7
·
verified ·
1 Parent(s): 0ad2075

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -6
app.py CHANGED
@@ -504,22 +504,73 @@ def analyze_sequence_for_tree(sequence: str, matching_percentage: float) -> tupl
504
 
505
  logging.info(f"Found {len(matched_ids)} similar sequences at {actual_percentage:.2f}% similarity")
506
 
 
 
 
507
  # Build tree structure
508
  analyzer.build_tree_structure_with_ml_safe(matched_ids)
509
 
510
  # Create interactive tree
511
  fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
 
 
 
512
 
513
  # Save tree to temporary file
514
  temp_dir = tempfile.gettempdir()
515
  query_id = analyzer.query_id or f"query_{int(time.time())}"
516
  tree_html_path = os.path.join(temp_dir, f'phylogenetic_tree_interactive_{query_id}.html')
517
- fig.write_html(tree_html_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
 
519
  # Ensure the analyzer has the correct user input threshold for the report
520
  analyzer.matching_percentage = matching_percentage
521
 
522
- # Generate detailed report - FIXED: Only pass the two required parameters
523
  report_success = analyzer.generate_detailed_report(matched_ids, actual_percentage)
524
  report_html_path = None
525
  if report_success:
@@ -533,15 +584,14 @@ def analyze_sequence_for_tree(sequence: str, matching_percentage: float) -> tupl
533
 
534
  success_msg = f"✅ Analysis complete! Found {len(matched_ids)} similar sequences with {actual_percentage:.2f}% average similarity."
535
 
536
- return success_msg, tree_html_path, report_html_path
537
 
538
  except Exception as e:
539
  error_msg = f"❌ Error during analysis: {str(e)}"
540
  logging.error(error_msg)
541
  import traceback
542
  logging.error(f"Full traceback: {traceback.format_exc()}")
543
- return error_msg, None, None# --- Keras Prediction ---
544
- def predict_with_keras(sequence):
545
  try:
546
  if not keras_model or not kmer_to_index:
547
  return f"Keras model not available. Input sequence: {sequence[:100]}..."
@@ -948,7 +998,9 @@ def create_interface():
948
  )
949
  tree_html_display = gr.HTML(
950
  label="Interactive Phylogenetic Tree",
951
- value="<div style='text-align: center; color: #6b7280; padding: 40px;'>No tree generated yet. Run analysis to create interactive tree.</div>"
 
 
952
  )
953
 
954
  with gr.TabItem("📝 Detailed Report"):
 
504
 
505
  logging.info(f"Found {len(matched_ids)} similar sequences at {actual_percentage:.2f}% similarity")
506
 
507
+ # Limit sequences for testing (optional)
508
+ matched_ids = matched_ids[:5] # Remove this after confirming fix
509
+
510
  # Build tree structure
511
  analyzer.build_tree_structure_with_ml_safe(matched_ids)
512
 
513
  # Create interactive tree
514
  fig = analyzer.create_interactive_tree(matched_ids, actual_percentage)
515
+ if fig is None or not hasattr(fig, 'write_html'):
516
+ logging.error("Failed to create valid Plotly figure")
517
+ return "❌ Error: Failed to create interactive tree (invalid Plotly figure)", None, None
518
 
519
  # Save tree to temporary file
520
  temp_dir = tempfile.gettempdir()
521
  query_id = analyzer.query_id or f"query_{int(time.time())}"
522
  tree_html_path = os.path.join(temp_dir, f'phylogenetic_tree_interactive_{query_id}.html')
523
+ try:
524
+ fig.write_html(tree_html_path, include_plotlyjs=True) # Embed Plotly.js
525
+ if not os.path.exists(tree_html_path) or os.path.getsize(tree_html_path) == 0:
526
+ logging.error(f"Tree HTML file is empty or not created: {tree_html_path}")
527
+ return "❌ Error: Failed to save interactive tree", None, None
528
+ except Exception as e:
529
+ logging.error(f"Failed to write tree HTML: {e}")
530
+ return f"❌ Error: Failed to save interactive tree: {str(e)}", None, None
531
+
532
+ # Copy tree HTML to output directory
533
+ output_dir = "output"
534
+ os.makedirs(output_dir, exist_ok=True)
535
+ safe_seq_name = re.sub(r'[^a-zA-Z0-9_-]', '', sequence[:20])
536
+ timestamp = str(int(time.time()))
537
+ tree_html_filename = f"tree_{safe_seq_name}_{timestamp}.html"
538
+ tree_html_final_path = os.path.join(output_dir, tree_html_filename)
539
+ try:
540
+ shutil.copy2(tree_html_path, tree_html_final_path)
541
+ if not os.path.exists(tree_html_final_path):
542
+ logging.error(f"Failed to copy tree HTML to: {tree_html_final_path}")
543
+ return "❌ Error: Failed to copy interactive tree", None, None
544
+ except Exception as e:
545
+ logging.error(f"Failed to copy tree HTML: {e}")
546
+ return f"❌ Error: Failed to copy interactive tree: {str(e)}", None, None
547
+
548
+ # Read tree HTML content from final path for display
549
+ try:
550
+ with open(tree_html_final_path, 'r', encoding='utf-8') as f:
551
+ tree_html_content = f.read()
552
+ if not tree_html_content.strip():
553
+ logging.error(f"Tree HTML content is empty: {tree_html_final_path}")
554
+ return "❌ Error: Tree HTML content is empty", None, None
555
+ logging.info(f"Tree HTML content length: {len(tree_html_content)}")
556
+ logging.debug(f"Tree HTML content preview: {tree_html_content[:200]}")
557
+ # Use iframe to isolate Plotly content
558
+ tree_html_content = f'<iframe srcdoc="{tree_html_content.replace('"', '&quot;')}" width="100%" height="600px" style="border:none;"></iframe>'
559
+ except Exception as e:
560
+ logging.error(f"Failed to read tree HTML: {e}")
561
+ return f"❌ Error: Failed to read interactive tree: {str(e)}", None, None
562
+
563
+ # Clean up temporary tree file
564
+ try:
565
+ if os.path.exists(tree_html_path):
566
+ os.unlink(tree_html_path)
567
+ except Exception as e:
568
+ logging.warning(f"Failed to delete temporary tree file: {e}")
569
 
570
  # Ensure the analyzer has the correct user input threshold for the report
571
  analyzer.matching_percentage = matching_percentage
572
 
573
+ # Generate detailed report
574
  report_success = analyzer.generate_detailed_report(matched_ids, actual_percentage)
575
  report_html_path = None
576
  if report_success:
 
584
 
585
  success_msg = f"✅ Analysis complete! Found {len(matched_ids)} similar sequences with {actual_percentage:.2f}% average similarity."
586
 
587
+ return success_msg, tree_html_final_path, report_html_path
588
 
589
  except Exception as e:
590
  error_msg = f"❌ Error during analysis: {str(e)}"
591
  logging.error(error_msg)
592
  import traceback
593
  logging.error(f"Full traceback: {traceback.format_exc()}")
594
+ return error_msg, None, Nonedef predict_with_keras(sequence):
 
595
  try:
596
  if not keras_model or not kmer_to_index:
597
  return f"Keras model not available. Input sequence: {sequence[:100]}..."
 
998
  )
999
  tree_html_display = gr.HTML(
1000
  label="Interactive Phylogenetic Tree",
1001
+ value="<div style='text-align: center; color: #6b7280; padding: 40px;'>No tree generated yet. Run analysis to create interactive tree.</div>",
1002
+ elem_id="tree_html_display",
1003
+ height=600
1004
  )
1005
 
1006
  with gr.TabItem("📝 Detailed Report"):