re-type commited on
Commit
ac86461
·
verified ·
1 Parent(s): 5f249ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -344
app.py CHANGED
@@ -8,390 +8,127 @@ import os
8
  import traceback
9
 
10
  # Configure logging
11
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
12
  logger = logging.getLogger(__name__)
13
 
14
- # Debug info for Hugging Face Spaces
15
- print("=== Hugging Face Spaces Debug Info ===")
16
- print(f"Current working directory: {os.getcwd()}")
17
- print(f"Files in current directory: {os.listdir('.')}")
18
- print(f"Python path: {os.environ.get('PYTHONPATH', 'Not set')}")
19
  print(f"PyTorch version: {torch.__version__}")
20
- print(f"CUDA available: {torch.cuda.is_available()}")
21
- print(f"Device count: {torch.cuda.device_count() if torch.cuda.is_available() else 0}")
22
- if torch.cuda.is_available():
23
- print(f"Current device: {torch.cuda.current_device()}")
24
- print(f"Device name: {torch.cuda.get_device_name()}")
25
- print("==========================================")
26
 
27
- # Initialize the predictor globally with error handling
28
  predictor = None
29
  initialization_error = None
30
 
31
  try:
32
- print("Attempting to import predictor...")
33
  from predictor import GenePredictor
34
- print("✅ Predictor module imported successfully")
35
-
36
- # Check if model file exists
37
  model_path = 'best_boundary_aware_model.pth'
 
38
  if os.path.exists(model_path):
39
- print(f"✅ Model file found: {model_path}")
40
  predictor = GenePredictor(model_path=model_path)
41
- print("✅ Gene predictor initialized successfully")
42
- logger.info("Gene predictor initialized successfully")
43
  else:
44
- print(f"❌ Model file not found: {model_path}")
45
- print(f"Available files: {[f for f in os.listdir('.') if f.endswith('.pth')]}")
46
  initialization_error = f"Model file {model_path} not found"
 
47
 
48
- except ImportError as e:
49
- print(f"❌ Import Error: {e}")
50
- print("Make sure predictor.py is in the same directory as app.py")
51
- logger.error(f"Failed to import predictor: {e}")
52
- initialization_error = f"Import error: {e}"
53
- except FileNotFoundError as e:
54
- print(f"❌ File Error: {e}")
55
- logger.error(f"Model file not found: {e}")
56
- initialization_error = f"File not found: {e}"
57
  except Exception as e:
58
- print(f"❌ Unexpected error during initialization: {e}")
59
- logger.error(f"Failed to initialize predictor: {e}")
60
- initialization_error = f"Initialization error: {e}"
61
 
62
- def predict_gene_regions(sequence: str,
63
- ground_truth_labels: Optional[str] = None,
64
- ground_truth_start: Optional[int] = None,
65
- ground_truth_end: Optional[int] = None) -> Tuple[str, str, str]:
66
- """
67
- Main prediction function for Gradio interface
68
-
69
- Returns:
70
- - regions_display: Formatted string showing predicted regions
71
- - metrics_display: Formatted string showing accuracy metrics (if ground truth provided)
72
- - detailed_json: JSON string with full prediction details
73
- """
74
-
75
  try:
76
- if predictor is None:
77
- error_msg = f"""**Model not loaded**
78
-
79
- Error: {initialization_error or 'Unknown initialization error'}
80
-
81
- Please check:
82
- 1. predictor.py file exists
83
- 2. best_boundary_aware_model.pth file exists
84
- 3. All dependencies are installed
85
- 4. Check the Hugging Face Spaces logs for specific errors"""
86
- return error_msg, "", "{}"
87
 
88
- # Input validation
89
  if not sequence or not sequence.strip():
90
- return "❌ Sequence cannot be empty", "", "{}"
91
 
92
  sequence = sequence.strip().upper()
93
 
94
- # Check for valid DNA characters
95
  valid_chars = set('ACTGN')
96
- invalid_chars = set(sequence) - valid_chars
97
- if invalid_chars:
98
- return f"❌ Sequence contains invalid characters: {', '.join(sorted(invalid_chars))}. Only A, C, T, G, N allowed", "", "{}"
99
 
100
- # Check sequence length
101
  if len(sequence) < 3:
102
- return "❌ Sequence too short. Minimum length is 3 nucleotides", "", "{}"
103
 
104
- if len(sequence) > 10000: # Add reasonable upper limit
105
- return "❌ Sequence too long. Maximum length is 10,000 nucleotides", "", "{}"
106
-
107
- # Process ground truth if provided
108
- labels = None
109
- try:
110
- if ground_truth_labels and ground_truth_labels.strip():
111
- # Parse comma-separated labels
112
- label_strings = [x.strip() for x in ground_truth_labels.split(',')]
113
- labels = [int(x) for x in label_strings if x] # Skip empty strings
114
-
115
- if len(labels) != len(sequence):
116
- return f"❌ Labels length ({len(labels)}) must match sequence length ({len(sequence)})", "", "{}"
117
-
118
- if not all(x in (0, 1) for x in labels):
119
- return "❌ Labels must be 0 or 1", "", "{}"
120
-
121
- elif ground_truth_start is not None and ground_truth_end is not None:
122
- start = int(ground_truth_start)
123
- end = int(ground_truth_end)
124
-
125
- if start < 0 or end > len(sequence) or start >= end:
126
- return f"❌ Invalid coordinates: start={start}, end={end}, sequence_length={len(sequence)}", "", "{}"
127
-
128
- # Create labels array
129
- labels = [0] * len(sequence)
130
- for i in range(start, end):
131
- labels[i] = 1
132
-
133
- except ValueError as e:
134
- return f"❌ Invalid ground truth format: {str(e)}", "", "{}"
135
 
136
  # Make prediction
137
- print(f"Making prediction for sequence of length {len(sequence)}")
138
  predictions, probs_dict, confidence = predictor.predict(sequence)
139
- print(f"Prediction completed. Confidence: {confidence}")
140
-
141
- # Extract gene regions
142
  regions = predictor.extract_gene_regions(predictions, sequence)
143
- print(f"Extracted {len(regions)} regions")
144
-
145
- # Format regions display
146
- regions_display = format_regions_display(regions, confidence)
147
 
148
- # Compute metrics if ground truth provided
149
- metrics_display = ""
150
- metrics = None
151
- if labels is not None:
152
- print("Computing accuracy metrics...")
153
- metrics = predictor.compute_accuracy(predictions, labels)
154
- metrics_display = format_metrics_display(metrics)
155
 
156
- # Create detailed JSON response
157
- detailed_response = {
158
- "regions": regions,
159
- "confidence": float(confidence),
160
- "metrics": metrics,
161
- "sequence_length": len(sequence),
162
- "num_predicted_genes": len(regions),
163
- "prediction_summary": {
164
- "total_gene_positions": int(np.sum(predictions)),
165
- "gene_coverage": float(np.sum(predictions) / len(predictions))
166
- }
167
- }
168
 
169
- detailed_json = json.dumps(detailed_response, indent=2)
170
- print("Prediction completed successfully")
 
 
 
 
 
 
 
 
 
 
171
 
172
- return regions_display, metrics_display, detailed_json
173
 
174
  except Exception as e:
175
- print(f"Error during prediction: {e}")
176
- print(f"Error type: {type(e).__name__}")
177
- print(f"Full traceback: {traceback.format_exc()}")
178
- logger.error(f"Prediction failed: {e}")
179
-
180
- error_msg = f"❌ Prediction failed: {str(e)}\n\nError type: {type(e).__name__}"
181
- return error_msg, "", "{}"
182
 
183
- def format_regions_display(regions: List[Dict], confidence: float) -> str:
184
- """Format the regions for display in the Gradio interface"""
185
-
186
- if not regions:
187
- return f"🔍 **No gene regions detected** (Confidence: {confidence:.3f})\n\nThe model did not identify any gene regions in the provided sequence."
188
-
189
- display = f"🧬 **Found {len(regions)} gene region(s)** (Overall Confidence: {confidence:.3f})\n\n"
190
-
191
- for i, region in enumerate(regions, 1):
192
- display += f"**Gene {i}:**\n"
193
- display += f" • Position: {region['start']} - {region['end']}\n"
194
- display += f" • Length: {region['length']} bp\n"
195
- display += f" • Start Codon: {region.get('start_codon', 'None detected') or 'None detected'}\n"
196
- display += f" • Stop Codon: {region.get('stop_codon', 'None detected') or 'None detected'}\n"
197
- display += f" • In Frame: {'✅ Yes' if region.get('in_frame', False) else '❌ No'}\n"
198
-
199
- # Safe sequence preview
200
- seq = region.get('sequence', '')
201
- if seq:
202
- preview = seq[:60] + ('...' if len(seq) > 60 else '')
203
- display += f" • Sequence Preview: {preview}\n\n"
204
- else:
205
- display += f" • Sequence Preview: Not available\n\n"
206
-
207
- return display
208
 
209
- def format_metrics_display(metrics: Dict) -> str:
210
- """Format the accuracy metrics for display"""
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
- display = "📊 **Accuracy Metrics** (vs Ground Truth)\n\n"
213
- display += f" • **Accuracy:** {metrics.get('accuracy', 0):.3f} ({metrics.get('accuracy', 0)*100:.1f}%)\n"
214
- display += f" • **Precision:** {metrics.get('precision', 0):.3f}\n"
215
- display += f" • **Recall:** {metrics.get('recall', 0):.3f}\n"
216
- display += f" • **F1 Score:** {metrics.get('f1', 0):.3f}\n\n"
217
- display += f"**Confusion Matrix:**\n"
218
- display += f" • True Positives: {metrics.get('true_positives', 0)}\n"
219
- display += f" • False Positives: {metrics.get('false_positives', 0)}\n"
220
- display += f" • False Negatives: {metrics.get('false_negatives', 0)}\n"
221
 
222
- return display
223
-
224
- def load_example_sequence():
225
- """Load an example DNA sequence for testing"""
226
- example = """ATGAAACGCATTAGCACCACCATTACCACCACCATCACCATTACCACAGGTAACGGTGCGGGCTGACGCGTACAGGAAACACAGAAAAAAGCCCGCACCTGACAGTGCGGGCTTTTTTTTTCGACCAAAGGTAACGAGGTAACAACCATGCGAGTGTTGAAGTTCGGCGGTACATCAGTGGCAAATGCAGAACGTTTTCTGCGGGTTGCCGATATTCTGGAAAGCAATGCCAGGCAGGGGCAGGTGGCCACCGTCCTCTCTGCCCCCGCCAAAATCACCAACCACCTGGTGGCGATGATTGAAAAAACCATTAGCGGCCAGGATGCTTTACCCAATATCAGCGATGCCGAACGTATTTTTGCCGAACTTTTGACGGGACTCGCCGCCGCCCAGCCGGGGTTCCCGCTGGCGCAATTGAAAACTTTCGTCGATCAGGAATTTGCCCAAATAAAACATGTCCTGCATGGCATTAGTTTGTTGGGGCAGTGCCCGGATAGCATCAACGCTGCGCTGATTTGCCGTGGCGAGAAAATGTCGATCGCCATTATGGCCGGCGTATTAGAAGCGCGCGGTCACAACGTTACTGTTATCGATCCGGTCGAAAAACTGCTGGCAGTGGGGCATTACCTCGAATCTACCGTCGATATTGCTGAGTCCACCCGCCGTATTGCGGCAAGCCGCATTCCGGCTGATCACATGGTGCTGATGGCAGGTTTCACCGCCGGTAATGAAAAAGGCGAACTGGTGGTGCTTGGACGCAACGGTTCCGACTACTCTGCTGCGGTGCTGGCTGCCTGTTTACGCGCCGATTGTTGCGAGATTTGGACGGACGTTGACGGGGTCTATACCTGCGACCCGCGTCAGGTGCCCGATGCGAGGTTGTTGAAGTCGATGTCCTACCAGGAAGCGATGGAGCTTTCCTACTTCGGCGCTAAAGTTCTTCACCCCCGCACCATTACCCCCATCGCCCAGTTCCAGATCCCTTGCCTGATTAAAAATACCGGAAATCCTCAAGCACCAGGTACGCTCATTGGTGCCAGCCGTGATGAAGACGAATTACCGGTCAAGGGCATTTCCAATCTGAATAACATGGCAATGTTCAGCGTTTCCGGCCCGGGGATGAAAGGGATGGTCGGCATGGCGGCGCGCGTCTTTGCAGCGATGTCACGCGCCCGTATTTCCGTGGTGCTGATTACGCAATCATCTTCCGAATACAGCATCAGTTTCTGCGTTCCACAAAGCGACTGTGTGCGAGCTGAACGGGCAATGCAGGAAGAGTTCTACCTGGAACTGAAAGAAGGCTTACTGGAGCCGCTGGCAGTGACGGAACGGCTGGCCATTATCTCGGTGGTAGG"""
227
- return example
 
 
 
 
228
 
229
- def clear_inputs():
230
- """Clear all input fields"""
231
- return "", None, None, ""
232
-
233
- # Create the Gradio interface with simpler structure
234
- def create_interface():
235
- try:
236
- # Show setup status
237
- if predictor:
238
- status_message = "✅ Model loaded successfully!"
239
- status_color = "green"
240
- else:
241
- status_message = f"❌ Model failed to load: {initialization_error}"
242
- status_color = "red"
243
-
244
- # Create interface with minimal configuration
245
- interface = gr.Blocks(
246
- title="Gene Prediction Tool",
247
- theme=gr.themes.Default() # Use default theme instead of Soft
248
- )
249
-
250
- with interface:
251
- # Header
252
- gr.HTML(f"""
253
- <div style="text-align: center; padding: 20px;">
254
- <h1>🧬 Gene Prediction Tool</h1>
255
- <p>This tool predicts gene regions in DNA sequences using a boundary-aware deep learning model.</p>
256
- <div style="padding: 10px; border-left: 4px solid {status_color}; background-color: #f9f9f9; margin: 10px 0;">
257
- <strong>Status:</strong> {status_message}
258
- </div>
259
- </div>
260
- """)
261
-
262
- # Input section
263
- gr.Markdown("## 📝 Input")
264
-
265
- sequence_input = gr.Textbox(
266
- label="DNA Sequence",
267
- placeholder="Enter your DNA sequence (A, C, T, G, N only)...",
268
- lines=5,
269
- info="Maximum length: 10,000 nucleotides"
270
- )
271
-
272
- with gr.Row():
273
- example_btn = gr.Button("📋 Load Example", size="sm")
274
- clear_btn = gr.Button("🗑️ Clear", size="sm")
275
- predict_btn = gr.Button("🔬 Predict Genes", variant="primary")
276
-
277
- # Ground truth section (optional)
278
- with gr.Accordion("🎯 Ground Truth (Optional)", open=False):
279
- gr.Markdown("*Provide ground truth data to calculate accuracy metrics*")
280
-
281
- with gr.Row():
282
- gt_start = gr.Number(
283
- label="Start Position",
284
- precision=0,
285
- minimum=0
286
- )
287
- gt_end = gr.Number(
288
- label="End Position",
289
- precision=0,
290
- minimum=0
291
- )
292
-
293
- gt_labels = gr.Textbox(
294
- label="OR: Labels (comma-separated 0s and 1s)",
295
- placeholder="0,0,1,1,1,0,0...",
296
- info="Alternative to start/end positions"
297
- )
298
-
299
- # Output section
300
- gr.Markdown("## 🔬 Prediction Results")
301
-
302
- regions_output = gr.Markdown(
303
- value="*Results will appear here after prediction...*"
304
- )
305
-
306
- metrics_output = gr.Markdown(
307
- value="*Metrics will appear here if ground truth is provided...*"
308
- )
309
-
310
- # Detailed JSON output (collapsible)
311
- with gr.Accordion("📄 Detailed JSON Output", open=False):
312
- json_output = gr.Code(
313
- language="json",
314
- value="{}",
315
- lines=10
316
- )
317
-
318
- # Event handlers
319
- example_btn.click(
320
- fn=load_example_sequence,
321
- outputs=sequence_input
322
- )
323
-
324
- clear_btn.click(
325
- fn=clear_inputs,
326
- outputs=[sequence_input, gt_start, gt_end, gt_labels]
327
- )
328
-
329
- predict_btn.click(
330
- fn=predict_gene_regions,
331
- inputs=[sequence_input, gt_labels, gt_start, gt_end],
332
- outputs=[regions_output, metrics_output, json_output]
333
- )
334
-
335
- # Also trigger prediction on Enter in the sequence box
336
- sequence_input.submit(
337
- fn=predict_gene_regions,
338
- inputs=[sequence_input, gt_labels, gt_start, gt_end],
339
- outputs=[regions_output, metrics_output, json_output]
340
- )
341
-
342
- # Footer
343
- gr.Markdown("""
344
- ---
345
- **Model Info:** Boundary-aware gene prediction using multi-task deep learning
346
- **Supported:** DNA sequences with A, C, T, G, N nucleotides
347
- **Output:** Gene regions with start/end positions, codons, and confidence scores
348
- """)
349
-
350
- return interface
351
-
352
- except Exception as e:
353
- print(f"❌ Error creating interface: {e}")
354
- print(f"Full traceback: {traceback.format_exc()}")
355
-
356
- # Create a minimal fallback interface
357
- fallback_interface = gr.Interface(
358
- fn=lambda x: f"Error: {str(e)}",
359
- inputs=gr.Textbox(label="DNA Sequence"),
360
- outputs=gr.Textbox(label="Output"),
361
- title="Gene Prediction Tool - Error Recovery Mode"
362
- )
363
- return fallback_interface
364
-
365
- # Main execution
366
  if __name__ == "__main__":
367
- try:
368
- print("Creating Gradio interface...")
369
- interface = create_interface()
370
- print("✅ Gradio interface created successfully")
371
-
372
- # Launch the interface
373
- # Remove custom CSS and use default settings for HF Spaces
374
- interface.launch(
375
- server_name="0.0.0.0", # Important for HF Spaces
376
- server_port=7860, # Standard port for HF Spaces
377
- share=False, # Don't create public link on HF Spaces
378
- debug=False, # Turn off debug mode for production
379
- show_error=True # Show errors in interface
380
- )
381
-
382
- except Exception as e:
383
- print(f"❌ Failed to launch interface: {e}")
384
- print(f"Full traceback: {traceback.format_exc()}")
385
-
386
- # Last resort - create the simplest possible interface
387
- try:
388
- simple_interface = gr.Interface(
389
- fn=lambda x: "Simple interface loaded - main interface failed",
390
- inputs=gr.Textbox(label="Test Input"),
391
- outputs=gr.Textbox(label="Test Output"),
392
- title="Gene Prediction Tool - Minimal Mode"
393
- )
394
- simple_interface.launch()
395
- except Exception as e2:
396
- print(f"❌ Even simple interface failed: {e2}")
397
- raise
 
8
  import traceback
9
 
10
  # Configure logging
11
+ logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
+ # Debug info
15
+ print("=== Debug Info ===")
16
+ print(f"Working directory: {os.getcwd()}")
17
+ print(f"Files: {os.listdir('.')}")
 
18
  print(f"PyTorch version: {torch.__version__}")
19
+ print("==================")
 
 
 
 
 
20
 
21
+ # Initialize predictor
22
  predictor = None
23
  initialization_error = None
24
 
25
  try:
 
26
  from predictor import GenePredictor
 
 
 
27
  model_path = 'best_boundary_aware_model.pth'
28
+
29
  if os.path.exists(model_path):
 
30
  predictor = GenePredictor(model_path=model_path)
31
+ print("✅ Model loaded successfully")
 
32
  else:
 
 
33
  initialization_error = f"Model file {model_path} not found"
34
+ print(f"❌ {initialization_error}")
35
 
 
 
 
 
 
 
 
 
 
36
  except Exception as e:
37
+ initialization_error = str(e)
38
+ print(f" Error: {e}")
 
39
 
40
+ def predict_genes(sequence):
41
+ """Simple prediction function"""
 
 
 
 
 
 
 
 
 
 
 
42
  try:
43
+ if not predictor:
44
+ return f"❌ Model not loaded: {initialization_error}"
 
 
 
 
 
 
 
 
 
45
 
 
46
  if not sequence or not sequence.strip():
47
+ return "❌ Please enter a DNA sequence"
48
 
49
  sequence = sequence.strip().upper()
50
 
51
+ # Validate sequence
52
  valid_chars = set('ACTGN')
53
+ if not set(sequence).issubset(valid_chars):
54
+ return "❌ Invalid characters. Use only A, C, T, G, N"
 
55
 
 
56
  if len(sequence) < 3:
57
+ return "❌ Sequence too short (minimum 3 nucleotides)"
58
 
59
+ if len(sequence) > 10000:
60
+ return "❌ Sequence too long (maximum 10,000 nucleotides)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  # Make prediction
 
63
  predictions, probs_dict, confidence = predictor.predict(sequence)
 
 
 
64
  regions = predictor.extract_gene_regions(predictions, sequence)
 
 
 
 
65
 
66
+ # Format output
67
+ if not regions:
68
+ return f"🔍 No gene regions detected (Confidence: {confidence:.3f})"
 
 
 
 
69
 
70
+ result = f"🧬 Found {len(regions)} gene region(s) (Confidence: {confidence:.3f})\n\n"
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ for i, region in enumerate(regions, 1):
73
+ result += f"**Gene {i}:**\n"
74
+ result += f" • Position: {region['start']} - {region['end']}\n"
75
+ result += f" • Length: {region['length']} bp\n"
76
+
77
+ # Safe sequence preview
78
+ seq = region.get('sequence', '')
79
+ if seq:
80
+ preview = seq[:60] + ('...' if len(seq) > 60 else '')
81
+ result += f" • Preview: {preview}\n\n"
82
+ else:
83
+ result += f" • Preview: Not available\n\n"
84
 
85
+ return result
86
 
87
  except Exception as e:
88
+ print(f"Prediction error: {e}")
89
+ return f" Prediction failed: {str(e)}"
 
 
 
 
 
90
 
91
+ def load_example():
92
+ """Load example DNA sequence"""
93
+ return "ATGAAACGCATTAGCACCACCATTACCACCACCATCACCATTACCACAGGTAACGGTGCGGGCTGACGCGTACAGGAAACACAGAAAAAAGCCCGCACCTGACAGTGCGGGCTTTTTTTTTCGACCAAAGGTAACGAGGTAACAACCATGCGAGTGTTGAAGTTCGGCGGTACATCAGTGGCAAATGCAGAACGTTTTCTGCGGGTTGCCGATATTCTGGAAAGCAATGCCAGGCAGGGGCAGGTGGCCACCGTCCTCTCTGCCCCCGCCAAAATCACCAACCACCTGGTGGCGATGATTGAAAAAACCATTAGCGGCCAGGATGCTTTACCCAATATCAGCGATGCCGAACGTATTTTTGCCGAACTTTTGACGGGACTCGCCGCCGCCCAGCCGGGGTTCCCGCTGGCGCAATTGAAAACTTTCGTCGATCAGGAATTTGCCCAAATAAAACATGTCCTGCATGGCATTAGTTTGTTGGGGCAGTGCCCGGATAGCATCAACGCTGCGCTGATTTGCCGTGGCGAGAAAATGTCGATCGCCATTATGGCCGGCGTATTAGAAGCGCGCGGTCACAACGTTACTGTTATCGATCCGGTCGAAAAACTGCTGGCAGTGGGGCATTACCTCGAATCTACCGTCGATATTGCTGAGTCCACCCGCCGTATTGCGGCAAGCCGCATTCCGGCTGATCACATGGTGCTGATGGCAGGTTTCACCGCCGGTAATGAAAAAGGCGAACTGGTGGTGCTTGGACGCAACGGTTCCGACTACTCTGCTGCGGTGCTGGCTGCCTGTTTACGCGCCGATTGTTGCGAGATTTGGACGGACGTTGACGGGGTCTATACCTGCGACCCGCGTCAGGTGCCCGATGCGAGGTTGTTGAAGTCGATGTCCTACCAGGAAGCGATGGAGCTTTCCTACTTCGGCGCTAAAGTTCTTCACCCCCGCACCATTACCCCCATCGCCCAGTTCCAGATCCCTTGCCTGATTAAAAATACCGGAAATCCTCAAGCACCAGGTACGCTCATTGGTGCCAGCCGTGATGAAGACGAATTACCGGTCAAGGGCATTTCCAATCTGAATAACATGGCAATGTTCAGCGTTTCCGGCCCGGGGATGAAAGGGATGGTCGGCATGGCGGCGCGCGTCTTTGCAGCGATGTCACGCGCCCGTATTTCCGTGGTGCTGATTACGCAATCATCTTCCGAATACAGCATCAGTTTCTGCGTTCCACAAAGCGACTGTGTGCGAGCTGAACGGGCAATGCAGGAAGAGTTCTACCTGGAACTGAAAGAAGGCTTACTGGAGCCGCTGGCAGTGACGGAACGGCTGGCCATTATCTCGGTGGTAGG"
94
+
95
+ # Status message
96
+ if predictor:
97
+ status_msg = " Model loaded successfully!"
98
+ status_color = "green"
99
+ else:
100
+ status_msg = f" Model loading failed: {initialization_error}"
101
+ status_color = "red"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
+ # Try gr.Interface first (simpler approach)
104
+ demo = gr.Interface(
105
+ fn=predict_genes,
106
+ inputs=gr.Textbox(
107
+ label="DNA Sequence",
108
+ placeholder="Enter DNA sequence (A, C, T, G, N)...",
109
+ lines=6
110
+ ),
111
+ outputs=gr.Textbox(
112
+ label="Prediction Results",
113
+ lines=15
114
+ ),
115
+ title="🧬 Gene Prediction Tool",
116
+ description=f"""
117
+ Predict gene regions in DNA sequences using deep learning.
118
 
119
+ **Status:** {status_msg}
 
 
 
 
 
 
 
 
120
 
121
+ **Instructions:**
122
+ 1. Enter a DNA sequence using only A, C, T, G, N characters
123
+ 2. Click Submit
124
+ 3. View predicted gene regions with positions and confidence scores
125
+ """,
126
+ examples=[
127
+ ["ATGAAACGCATTAGCACCACCATTACCACCACCATCACCATTACCACAGGTAACGGTGCGGGCTGACGCGTACAGGAAACACAGAAAAAAGCCCGCACCTGACAGTGCGGGCTTTTTTTTTCGACCAAAGGTAACGAGGTAACAACCATGCGAGTGTTGAAGTTCGGCGGTACATCAGTGGCAAATGCAGAACGTTTTCTGCGGGTTGCCGATATTCTGGAAAGCAATGCCAGGCAGGGGCAGGTGGCCACCGTCCTCTCTGCCCCCGCCAAAATCACCAACCACCTGGTGGCGATGATTGAAAAAACCATTAGCGGCCAGGATGCTTTACCCAATATCAGCGATGCCGAACGTATTTTTGCCGAACTTTTGACGGGACTCGCCGCCGCCCAGCCGGGGTTCCCGCTGGCGCAATTGAAAACTTTCGTCGATCAGGAATTTGCCCAAATAAAACATGTCCTGCATGGCATTAGTTTGTTGGGGCAGTGCCCGGATAGCATCAACGCTGCGCTGATTTGCCGTGGCGAGAAAATGTCGATCGCCATTATGGCCGGCGTATTAGAAGCGCGCGGTCACAACGTTACTGTTATCGATCCGGTCGAAAAACTGCTGGCAGTGGGGCATTACCTCGAATCTACCGTCGATATTGCTGAGTCCACCCGCCGTATTGCGGCAAGCCGCATTCCGGCTGATCACATGGTGCTGATGGCAGGTTTCACCGCCGGTAATGAAAAAGGCGAACTGGTGGTGCTTGGACGCAACGGTTCCGACTACTCTGCTGCGGTGCTGGCTGCCTGTTTACGCGCCGATTGTTGCGAGATTTGGACGGACGTTGACGGGGTCTATACCTGCGACCCGCGTCAGGTGCCCGATGCGAGGTTGTTGAAGTCGATGTCCTACCAGGAAGCGATGGAGCTTTCCTACTTCGGCGCTAAAGTTCTTCACCCCCGCACCATTACCCCCATCGCCCAGTTCCAGATCCCTTGCCTGATTAAAAATACCGGAAATCCTCAAGCACCAGGTACGCTCATTGGTGCCAGCCGTGATGAAGACGAATTACCGGTCAAGGGCATTTCCAATCTGAATAACATGGCAATGTTCAGCGTTTCCGGCCCGGGGATGAAAGGGATGGTCGGCATGGCGGCGCGCGTCTTTGCAGCGATGTCACGCGCCCGTATTTCCGTGGTGCTGATTACGCAATCATCTTCCGAATACAGCATCAGTTTCTGCGTTCCACAAAGCGACTGTGTGCGAGCTGAACGGGCAATGCAGGAAGAGTTCTACCTGGAACTGAAAGAAGGCTTACTGGAGCCGCTGGCAGTGACGGAACGGCTGGCCATTATCTCGGTGGTAGG"]
128
+ ],
129
+ allow_flagging="never"
130
+ )
131
 
132
+ # Launch the app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  if __name__ == "__main__":
134
+ demo.launch()