RNA-flow / app.py
zhq0's picture
Update app.py
c4a2a56 verified
Raw History Blame Contribute Delete
10.6 kB
import gradio as gr
from modules.rna_predictor import RNAPredictor
from modules.visualizer import RNAVisualizer
import plotly.graph_objects as go
import re
import json
# Initialize the components
print("πŸš€ Initializing RNAFlow...")
rna_predictor = RNAPredictor()
rna_visualizer = RNAVisualizer()
# Your test sequence (converted to RNA)
TEST_SEQUENCE = (
"CAUAGGGUUUGUGAGUUUGCAUAAAGUGUCACGUAUAAGUGUUUCUAACAUGUGAGUUUGCAUAAGAGUC"
"UCGACUAUGUGUUUGUUCAAAAGUGACGUAAUGUGUUAGACUAGAGCCGGCCGUGAGCACAAGCGGGCCA"
"AGCCCAUGCUUGCGGCAGAUUAUCCUAUAAUUAUGUUUUGCGGCUUUACAAUUUUGAUUUGUUUUGUUG"
"UUUAGUGGUCGAGUCAGGGAUGAGUUUGUUCUCAAACAUCUCAAAUUUCUAAUCUUCCAAGUGUUGGUU"
"CACUCUACCUUAUUUUUUUUUUUUUUUUUAUUUUAAAUUUCUAUUAGAAAGAACUUGAACCUUAUUUCA"
"AGUGAACAUUAAAAAGAAUUGUAACCCUACCUUAUUUCUAUUAUUAUGAUAUUGUGUAAAGUAAAUUUU"
"UUACAAUAAGCAUGUAUAAAGUAAUAUAUUUUUGUUCUUUUCUUAUAGCCUUGUAAAUCAUAGGGACGGA"
"UCUAGUUUAGAAUAAAGUGUUGCAUAAGUUCUUCGACUAACAUGUGAGUCCAUUUUUGUGAGUUUUGCAU"
"AACUUUUGCGCCUUCGACAAUUUGAAUUUUAUGCAUAAGUGCUUUGACUAAUUUAUAUGUUUUGUCUAAG"
"UGAUUCGACAUUUCGACUAAGUGAUGUGAAUUGUGUCAUUCGUCGUCGUUGUCGCAUCCGGAAGCGUGUU"
"UGUGGUUCUUGUGUCUUACUUGCCGGGUUAUGAAGUCCUUUGUUUCGAGAGAUCUGCUCUCAUCAUGAUA"
)
def clean_sequence(sequence):
"""Clean and validate RNA sequence input"""
if not sequence:
return None, "Please enter an RNA sequence"
# Remove whitespace, numbers, and other non-RNA characters
sequence = re.sub(r'[^ACGUacgu\s]', '', sequence)
sequence = re.sub(r'\s+', '', sequence)
sequence = sequence.upper().strip()
if not sequence:
return None, "❌ No valid RNA characters found. Please use only A, C, G, U."
if len(sequence) < 10:
return None, "❌ Sequence too short. Please enter at least 10 nucleotides."
if len(sequence) > 2000:
return None, "❌ Sequence too long. Please enter less than 2000 nucleotides."
return sequence, None
def format_embeddings_for_display(embeddings):
"""Format embeddings data to be more user-friendly"""
if isinstance(embeddings, dict):
formatted = {
"model_used": embeddings.get('model_used', 'Unknown'),
"embedding_dimensions": embeddings.get('embedding_dim', 'N/A'),
"status": "Real Model" if rna_predictor.is_loaded else "Enhanced Mock Data"
}
if 'features' in embeddings:
formatted["key_features"] = {
"gc_bias": round(embeddings['features'].get('gc_bias', 0), 4),
"length_bias": round(embeddings['features'].get('length_bias', 0), 4)
}
if 'embeddings' in embeddings and isinstance(embeddings['embeddings'], list):
formatted["embedding_sample"] = embeddings['embeddings'][:5]
formatted["total_embedding_values"] = len(embeddings['embeddings'])
if 'error' in embeddings:
formatted["error_info"] = embeddings['error']
return json.dumps(formatted, indent=2)
return str(embeddings)
def analyze_rna_sequence(sequence):
"""Comprehensive RNA sequence analysis"""
cleaned_sequence, error = clean_sequence(sequence)
if error:
error_plot = rna_visualizer.create_error_plot(error)
return error, error_plot, error_plot, error_plot, error_plot, ""
try:
properties = rna_predictor.calculate_sequence_properties(cleaned_sequence)
structure_prediction = rna_predictor.predict_structure(cleaned_sequence)
embeddings = rna_predictor.predict_embeddings(cleaned_sequence)
structure_viz = rna_visualizer.create_interactive_structure_plot(cleaned_sequence, structure_prediction["predicted_structure"])
embedding_viz = rna_visualizer.create_embedding_visualization(embeddings, cleaned_sequence)
sequence_logo = rna_visualizer.create_sequence_logo(cleaned_sequence[:100])
gc_plot = rna_visualizer.create_gc_content_plot(cleaned_sequence)
analysis_results = format_testing_results(cleaned_sequence, properties, structure_prediction, embeddings)
formatted_embeddings = format_embeddings_for_display(embeddings)
return analysis_results, structure_viz, embedding_viz, sequence_logo, gc_plot, formatted_embeddings
except Exception as e:
error_msg = f"❌ Analysis error: {str(e)}"
print(f"Error in analysis: {e}")
error_plot = rna_visualizer.create_error_plot(error_msg)
return error_msg, error_plot, error_plot, error_plot, error_plot, ""
def format_testing_results(sequence, properties, structure, embeddings):
"""Format the analysis results with testing focus"""
gc_skew = (sequence.count('G') - sequence.count('C')) / (sequence.count('G') + sequence.count('C')) if (sequence.count('G') + sequence.count('C')) > 0 else 0
at_skew = (sequence.count('A') - sequence.count('U')) / (sequence.count('A') + sequence.count('U')) if (sequence.count('A') + sequence.count('U')) > 0 else 0
start_codons = sequence.count('AUG')
stop_codons = sequence.count('UAA') + sequence.count('UAG') + sequence.count('UGA')
dinucleotides = {}
for i in range(len(sequence)-1):
dinuc = sequence[i:i+2]
dinucleotides[dinuc] = dinucleotides.get(dinuc, 0) + 1
common_dinuc = sorted(dinucleotides.items(), key=lambda x: x[1], reverse=True)[:5]
results = f"""
## 🧬 RNA Sequence Analysis
### πŸ“Š Sequence Overview
- **Length**: {properties['length']} nucleotides
- **GC Content**: {properties['gc_content']:.1f}%
- **GC Skew**: {gc_skew:.3f}
- **Sequence Complexity**: {properties['sequence_complexity']:.1f}%
### 🧬 Base Composition
- **Adenine (A)**: {properties['a_content']:.1f}%
- **Uracil (U)**: {properties['u_content']:.1f}%
- **Guanine (G)**: {properties['g_content']:.1f}%
- **Cytosine (C)**: {properties['c_content']:.1f}%
- **Purine (A+G)**: {properties['purine_content']:.1f}%
### πŸ—οΈ Structural Features
- **Predicted Paired Bases**: {structure['paired_bases']} ({structure['pairing_percentage']:.1f}%)
- **Unpaired Bases**: {structure['unpaired_bases']}
- **Structure Method**: {structure['method']}
- **Start Codons (AUG)**: {start_codons}
- **Stop Codons**: {stop_codons}
### πŸ” Sequence Patterns
- **Common Dinucleotides**: {', '.join([f'{d[0]}' for d in common_dinuc[:3]])}
- **Poly-U Regions**: {len([m for m in re.finditer(r'U{4,}', sequence)])}
- **GC-rich Regions**: {len([m for m in re.finditer(r'[GC]{5,}', sequence)])}
### πŸ€– AI Analysis
- **Embedding Dimensions**: {embeddings.get('embedding_dim', 'N/A')}
- **Model Status**: {'βœ… REAL MODEL' if rna_predictor.is_loaded else 'πŸ”„ ENHANCED MOCK'}
"""
if 'features' in embeddings:
features = embeddings['features']
results += f"\n### 🎯 Key Features"
results += f"\n- GC Bias: {features.get('gc_bias', 0):.3f}"
results += f"\n- Length Bias: {features.get('length_bias', 0):.3f}"
if 'error' in embeddings:
results += f"\n**Note**: {embeddings['error']}"
return results
# Create the Gradio interface - SIMPLIFIED without theme
with gr.Blocks(title="RNAFlow - Advanced RNA Analysis") as demo:
gr.Markdown("""
# 🧬 RNAFlow - Advanced RNA Analysis
**Professional RNA sequence analysis with interactive visualizations**
""")
with gr.Row():
with gr.Column():
sequence_input = gr.Textbox(
label="🧬 RNA Sequence Input",
placeholder="Paste your RNA sequence here (A, C, G, U characters only)...",
lines=4,
max_lines=6,
value=""
)
with gr.Row():
analyze_btn = gr.Button("πŸš€ Analyze Sequence", variant="primary", size="lg")
clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πŸ“‹ Analysis Results")
output_text = gr.Markdown(label="", show_label=False)
with gr.Column(scale=2):
with gr.Tabs():
with gr.TabItem("πŸ—οΈ Structure"):
with gr.Row():
structure_plot = gr.Plot(show_label=False)
with gr.Row():
gr.Markdown("""
**Controls:** Zoom with mouse wheel β€’ Pan by dragging β€’ Double-click to reset
""")
with gr.Row():
reset_structure_btn = gr.Button("πŸ”„ Reset View", size="sm")
with gr.TabItem("πŸ”¬ Embeddings"):
embedding_plot = gr.Plot(show_label=False)
gr.Markdown("**AI-generated sequence features**")
with gr.TabItem("🧬 Sequence"):
sequence_plot = gr.Plot(show_label=False)
with gr.TabItem("πŸ“ˆ GC Profile"):
gc_plot = gr.Plot(show_label=False)
with gr.TabItem("πŸ“‹ Data"):
with gr.Row():
raw_output = gr.Code(
language="json",
lines=12,
interactive=False
)
# Examples
gr.Examples(
examples=[
[TEST_SEQUENCE],
["AUGCCGUAUCG" * 10],
["ACGU" * 25],
],
inputs=[sequence_input],
label="Test Sequences:"
)
# Usage tips
gr.Markdown("""
### πŸ’‘ Interactive Features:
- **All plots are interactive** - zoom, pan, hover for details
- **Structure view** can be reset with the button
- **Data tab** shows formatted JSON output
- **Enhanced mock analysis** provides realistic predictions
""")
# Button actions
analyze_btn.click(
fn=analyze_rna_sequence,
inputs=[sequence_input],
outputs=[output_text, structure_plot, embedding_plot, sequence_plot, gc_plot, raw_output]
)
def clear_all():
return "", None, None, None, None, "{}"
clear_btn.click(
fn=clear_all,
inputs=[],
outputs=[sequence_input, output_text, structure_plot, embedding_plot, sequence_plot, raw_output]
)
def reset_structure_view():
return structure_plot
reset_structure_btn.click(
fn=reset_structure_view,
inputs=[],
outputs=[structure_plot]
)
if __name__ == "__main__":
demo.launch(debug=True)