import gradio as gr import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots import numpy as np import torch from transformers import AutoModelForSequenceClassification, AutoTokenizer import logging # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class PrimerAnalyzer: def __init__(self): self.thermo_params = { 'mv_conc': 50, 'dv_conc': 0, 'dntp_conc': 0.2, 'dna_conc': 50, 'temp_c': 37 } def calculate_gc_content(self, sequence): """Calculate GC content percentage""" if not sequence: return 0 gc_count = sequence.upper().count('G') + sequence.upper().count('C') return (gc_count / len(sequence)) * 100 def calculate_tm(self, sequence): """Calculate melting temperature using basic Wallace rule""" if not sequence: return 0 return 2 * sequence.upper().count('A') + 2 * sequence.upper().count('T') + \ 4 * sequence.upper().count('G') + 4 * sequence.upper().count('C') def check_self_complementarity(self, sequence): """Check for self-complementarity""" if not sequence: return 0 rev_comp = self.reverse_complement(sequence) max_complementarity = 0 for i in range(len(sequence) - 4): for j in range(4, min(8, len(sequence) - i)): if sequence[i:i+j] in rev_comp: max_complementarity = max(max_complementarity, j) return max_complementarity def reverse_complement(self, sequence): """Generate reverse complement""" comp_map = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'N': 'N'} return ''.join(comp_map.get(base, base) for base in sequence.upper()[::-1]) def predict_secondary_structure(self, sequence): """Predict likelihood of secondary structure formation""" if not sequence: return 0 hairpin_potential = sum(1 for i in range(len(sequence)-4) if sequence[i:i+2] == sequence[i+2:i+4][::-1]) return hairpin_potential / len(sequence) def calculate_quality_score(self, analysis): """Calculate overall primer quality score""" score = 0 # Length check (18-25 bp ideal) if 18 <= analysis['length'] <= 25: score += 25 else: score -= 10 # GC content (40-60% ideal) if 40 <= analysis['gc_content'] <= 60: score += 25 else: score -= 10 # TM check (55-65°C ideal) if 55 <= analysis['tm'] <= 65: score += 25 else: score -= 10 # Self-complementarity (max 4bp acceptable) if analysis['self_complementarity'] <= 4: score += 15 else: score -= 10 # Secondary structure risk if analysis['secondary_structure_risk'] < 0.1: score += 10 return max(0, min(100, score)) def analyze_primer(self, sequence): """Comprehensive primer analysis""" if not sequence or len(sequence) < 10: return { 'sequence': sequence, 'length': len(sequence) if sequence else 0, 'gc_content': 0, 'tm': 0, 'self_complementarity': 0, 'secondary_structure_risk': 0, 'quality_score': 0 } # Validate sequence contains only DNA bases valid_bases = {'A', 'T', 'G', 'C', 'N'} sequence_clean = ''.join(base for base in sequence.upper() if base in valid_bases) if len(sequence_clean) < 10: return { 'sequence': sequence, 'length': len(sequence), 'gc_content': 0, 'tm': 0, 'self_complementarity': 0, 'secondary_structure_risk': 0, 'quality_score': 0 } analysis = { 'sequence': sequence_clean, 'length': len(sequence_clean), 'gc_content': self.calculate_gc_content(sequence_clean), 'tm': self.calculate_tm(sequence_clean), 'self_complementarity': self.check_self_complementarity(sequence_clean), 'secondary_structure_risk': self.predict_secondary_structure(sequence_clean) } # Quality assessment analysis['quality_score'] = self.calculate_quality_score(analysis) return analysis class PrimerDesignUI: def __init__(self): self.analyzer = PrimerAnalyzer() self.model = None self.tokenizer = None self.load_default_model() def load_default_model(self): """Try to load a compatible default model""" try: # Use a more compatible model - distilbert is widely supported model_name = "distilbert-base-uncased" self.tokenizer = AutoTokenizer.from_pretrained(model_name) self.model = AutoModelForSequenceClassification.from_pretrained( model_name, num_labels=3 ) logger.info("Loaded DistilBERT model successfully") except Exception as e: logger.warning(f"Could not load model: {e}. Using analytical mode only.") self.model = None self.tokenizer = None def predict_primer_quality(self, sequence): """Predict primer quality using model""" if self.model is None or self.tokenizer is None or not sequence: return "Analytical Mode", 0.0 try: # Validate sequence first valid_bases = {'A', 'T', 'G', 'C', 'N'} sequence_clean = ''.join(base for base in sequence.upper() if base in valid_bases) if len(sequence_clean) < 10: return "Invalid Sequence", 0.0 inputs = self.tokenizer( sequence_clean, return_tensors="pt", padding=True, truncation=True, max_length=128 ) with torch.no_grad(): outputs = self.model(**inputs) predictions = torch.nn.functional.softmax(outputs.logits, dim=-1) predicted_class = torch.argmax(predictions, dim=1).item() confidence = predictions[0][predicted_class].item() quality_labels = {0: "Poor", 1: "Average", 2: "Good"} return quality_labels[predicted_class], confidence except Exception as e: logger.error(f"Prediction error: {e}") return "Error in prediction", 0.0 def create_analysis_plots(self, analysis): """Create visualization plots for primer analysis""" try: # Create subplots fig = make_subplots( rows=2, cols=2, subplot_titles=('GC Content Analysis', 'Length Distribution', 'Melting Temperature', 'Quality Metrics'), specs=[[{"type": "indicator"}, {"type": "bar"}], [{"type": "indicator"}, {"type": "pie"}]] ) # GC Content gauge fig.add_trace(go.Indicator( mode = "gauge+number+delta", value = analysis['gc_content'], domain = {'x': [0, 1], 'y': [0, 1]}, title = {'text': "GC Content (%)"}, gauge = { 'axis': {'range': [0, 100]}, 'bar': {'color': "darkblue"}, 'steps': [ {'range': [0, 40], 'color': "lightgray"}, {'range': [40, 60], 'color': "lightgreen"}, {'range': [60, 100], 'color': "lightcoral"} ], 'threshold': { 'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 50 } } ), row=1, col=1) # Length comparison ideal_lengths = [18, 20, 22, 24, 25] length_quality = [abs(analysis['length'] - l) for l in ideal_lengths] fig.add_trace(go.Bar( x=ideal_lengths, y=length_quality, name="Length Deviation", marker_color='coral' ), row=1, col=2) # Melting Temperature gauge fig.add_trace(go.Indicator( mode = "gauge+number+delta", value = analysis['tm'], domain = {'x': [0, 1], 'y': [0, 1]}, title = {'text': "Melting Temp (°C)"}, gauge = { 'axis': {'range': [0, 100]}, 'bar': {'color': "darkblue"}, 'steps': [ {'range': [0, 55], 'color': "lightgray"}, {'range': [55, 65], 'color': "lightgreen"}, {'range': [65, 100], 'color': "lightcoral"} ] } ), row=2, col=1) # Quality score pie chart quality_components = { 'Length': min(25, max(0, 25 - abs(analysis['length'] - 21.5) * 2)), 'GC Content': min(25, max(0, 25 - abs(analysis['gc_content'] - 50) / 2)), 'TM': min(25, max(0, 25 - abs(analysis['tm'] - 60) / 2)), 'Specificity': min(15, max(0, 15 - analysis['self_complementarity'] * 3)), 'Structure': min(10, max(0, 10 - analysis['secondary_structure_risk'] * 100)) } fig.add_trace(go.Pie( labels=list(quality_components.keys()), values=list(quality_components.values()), name="Quality Components" ), row=2, col=2) fig.update_layout( height=600, showlegend=False, template="plotly_white", title_text="Primer Analysis Dashboard", title_x=0.5 ) return fig except Exception as e: logger.error(f"Plot creation error: {e}") # Return empty figure on error return go.Figure().update_layout( title={"text": "Error creating visualization", "x": 0.5} ) def generate_recommendations(self, analysis): """Generate recommendations for primer improvement""" if analysis['length'] < 10: return "Please enter a valid primer sequence (minimum 10 bases containing only A, T, G, C)." recommendations = [] # Length recommendations if analysis['length'] < 18: recommendations.append("❌ Primer too short. Increase length to 18-25 bp.") elif analysis['length'] > 25: recommendations.append("❌ Primer too long. Decrease length to 18-25 bp.") else: recommendations.append("✅ Primer length is optimal.") # GC content recommendations if analysis['gc_content'] < 40: recommendations.append("❌ GC content too low. Aim for 40-60%.") elif analysis['gc_content'] > 60: recommendations.append("❌ GC content too high. Aim for 40-60%.") else: recommendations.append("✅ GC content is optimal.") # TM recommendations if analysis['tm'] < 55: recommendations.append("❌ Melting temperature too low. Aim for 55-65°C.") elif analysis['tm'] > 65: recommendations.append("❌ Melting temperature too high. Aim for 55-65°C.") else: recommendations.append("✅ Melting temperature is optimal.") # Self-complementarity recommendations if analysis['self_complementarity'] > 4: recommendations.append(f"⚠️ High self-complementarity ({analysis['self_complementarity']}bp). Consider redesign.") else: recommendations.append("✅ Self-complementarity is acceptable.") # Secondary structure recommendations if analysis['secondary_structure_risk'] > 0.1: recommendations.append("⚠️ Potential secondary structure issues detected.") else: recommendations.append("✅ Secondary structure risk is low.") return "\n".join(recommendations) def batch_analyze_sequences(self, sequences_text): """Analyze multiple sequences at once""" if not sequences_text: return pd.DataFrame() sequences = [seq.strip() for seq in sequences_text.split('\n') if seq.strip()] results = [] for seq in sequences: if len(seq) < 10: # Basic validation continue analysis = self.analyzer.analyze_primer(seq) quality_pred, confidence = self.predict_primer_quality(seq) results.append({ 'Sequence': seq[:30] + "..." if len(seq) > 30 else seq, 'Length': analysis['length'], 'GC%': round(analysis['gc_content'], 2), 'TM': round(analysis['tm'], 2), 'SelfComp': analysis['self_complementarity'], 'QualityScore': round(analysis['quality_score'], 2), 'AIPrediction': quality_pred, 'Confidence': round(confidence, 3) }) if not results: return pd.DataFrame({"Message": ["No valid sequences found"]}) return pd.DataFrame(results) def create_primer_analysis_dashboard(self, sequence): """Create comprehensive analysis dashboard""" if not sequence or len(sequence) < 10: return 0, go.Figure(), "Please enter a valid primer sequence (minimum 10 bases containing only A, T, G, C).", "N/A", 0.0 analysis = self.analyzer.analyze_primer(sequence) fig = self.create_analysis_plots(analysis) recommendations = self.generate_recommendations(analysis) quality_pred, confidence = self.predict_primer_quality(sequence) return analysis['quality_score'], fig, recommendations, quality_pred, confidence # Create the Gradio interface with minimal configuration def create_demo(): analyzer_ui = PrimerDesignUI() # Use simplest Blocks initialization with gr.Blocks() as demo: gr.Markdown(""" # 🧬 Advanced Primer Design & Analysis **AI-Powered Primer Quality Assessment** *Analyze single primers or batch process multiple sequences with comprehensive quality metrics* """) with gr.Tab("🧪 Single Primer Analysis"): with gr.Row(): with gr.Column(): gr.Markdown("### Primer Input") sequence_input = gr.Textbox( label="Primer Sequence", placeholder="Enter DNA sequence (e.g., ATGCATGCATGCATGCATGC)", value="ATCGATCGATCGATCGATCGATCG" ) analyze_btn = gr.Button("Analyze Primer", variant="primary") with gr.Accordion("💡 Example Sequences", open=False): gr.Markdown(""" **Good Primer:** `ATCGATCGATCGATCGATCGATCG` **Short Primer:** `ATCGATCGATCG` **High GC:** `GGCCGGCCGGCCGGCCGGCCGGCC` **Low GC:** `ATATATATATATATATATATATAT` """) with gr.Column(): gr.Markdown("### AI Assessment") with gr.Row(): quality_output = gr.Textbox( label="AI Quality Prediction", interactive=False ) confidence_output = gr.Number( label="Confidence Score", interactive=False ) score_output = gr.Number( label="Overall Quality Score", interactive=False ) gr.Markdown("### 📊 Comprehensive Analysis Dashboard") analysis_plot = gr.Plot() recommendations_output = gr.Textbox( label="🔍 Recommendations & Improvements", lines=4, interactive=False ) with gr.Tab("📊 Batch Analysis"): gr.Markdown("### Analyze Multiple Primers") with gr.Row(): with gr.Column(): batch_input = gr.Textbox( label="Primer Sequences (one per line)", placeholder="ATCGATCGATCGATCGATCGATCG\nGCTAGCTAGCTAGCTAGCTAGCTA\nTTTTTTTTTTTTTTTTTTTTTTTT\n...", lines=10, value="ATCGATCGATCGATCGATCGATCG\nGCTAGCTAGCTAGCTAGCTAGCTA\nCCCCCCCCCCCCCCCCCCCCCCCC\nATATATATATATATATATATATAT" ) batch_btn = gr.Button("Analyze All Primers", variant="primary") with gr.Column(): batch_output = gr.Dataframe( label="Batch Analysis Results", wrap=True ) with gr.Tab("ℹ️ About"): gr.Markdown(""" ## About This Tool This AI-powered primer analysis system provides: ### 🔬 Key Features - **AI Quality Prediction**: Transformer model for primer quality assessment - **Comprehensive Analysis**: GC content, melting temperature, self-complementarity, secondary structure - **Batch Processing**: Analyze multiple primers simultaneously - **Visual Analytics**: Interactive dashboards with detailed metrics ### 🧪 Analysis Parameters - **GC Content**: Optimal range 40-60% - **Length**: Optimal range 18-25 bp - **Melting Temperature**: Optimal range 55-65°C - **Self-complementarity**: Maximum 4 bp allowed - **Secondary Structure**: Minimal hairpin formation ### 🚀 How to Use 1. Enter a DNA sequence in the Single Primer Analysis tab 2. Click "Analyze Primer" for comprehensive assessment 3. View AI predictions and quality scores 4. Use recommendations to optimize your primers 5. For multiple primers, use the Batch Analysis tab *Note: Sequences should contain only A, T, G, C bases (N is also accepted)* """) # Event handlers analyze_btn.click( fn=analyzer_ui.create_primer_analysis_dashboard, inputs=[sequence_input], outputs=[score_output, analysis_plot, recommendations_output, quality_output, confidence_output] ) batch_btn.click( fn=analyzer_ui.batch_analyze_sequences, inputs=[batch_input], outputs=[batch_output] ) # Examples gr.Examples( examples=[ ["ATCGATCGATCGATCGATCGATCG"], # Good primer ["ATCGATCGATCG"], # Too short ["GGCCGGCCGGCCGGCCGGCCGGCC"], # High GC ["ATATATATATATATATATATATAT"], # Low GC ], inputs=sequence_input, outputs=[score_output, analysis_plot, recommendations_output, quality_output, confidence_output], fn=analyzer_ui.create_primer_analysis_dashboard ) return demo # Launch the application if __name__ == "__main__": demo = create_demo() demo.launch()