Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
"""
|
| 2 |
-
Enhanced DNA-Diffusion Gradio Application
|
| 3 |
-
|
| 4 |
"""
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
import logging
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
-
from typing import Dict, Any, Tuple, List
|
| 11 |
import html
|
| 12 |
import requests
|
| 13 |
import time
|
|
@@ -15,7 +15,8 @@ import numpy as np
|
|
| 15 |
from dataclasses import dataclass
|
| 16 |
from datetime import datetime
|
| 17 |
import asyncio
|
| 18 |
-
import
|
|
|
|
| 19 |
|
| 20 |
# Configure logging
|
| 21 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
@@ -34,653 +35,461 @@ except ImportError:
|
|
| 34 |
return func
|
| 35 |
return decorator
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
#
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T',
|
| 60 |
-
'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K',
|
| 61 |
-
'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R',
|
| 62 |
-
'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V',
|
| 63 |
-
'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A',
|
| 64 |
-
'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E',
|
| 65 |
-
'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'
|
| 66 |
-
}
|
| 67 |
-
|
| 68 |
-
# Common restriction enzymes
|
| 69 |
-
RESTRICTION_ENZYMES = {
|
| 70 |
-
'EcoRI': 'GAATTC',
|
| 71 |
-
'BamHI': 'GGATCC',
|
| 72 |
-
'HindIII': 'AAGCTT',
|
| 73 |
-
'PstI': 'CTGCAG',
|
| 74 |
-
'SalI': 'GTCGAC',
|
| 75 |
-
'XbaI': 'TCTAGA',
|
| 76 |
-
'NotI': 'GCGGCCGC',
|
| 77 |
-
'XhoI': 'CTCGAG',
|
| 78 |
-
'NdeI': 'CATATG',
|
| 79 |
-
'NcoI': 'CCATGG'
|
| 80 |
-
}
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
"""Data class for storing analysis results"""
|
| 85 |
-
sequence: str
|
| 86 |
-
gc_content: float
|
| 87 |
-
melting_temp: float
|
| 88 |
-
restriction_sites: Dict[str, List[int]]
|
| 89 |
-
orfs: List[Tuple[int, int, str]]
|
| 90 |
-
primers: Dict[str, Any]
|
| 91 |
-
protein_analysis: str
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
#
|
| 107 |
-
|
| 108 |
-
else:
|
| 109 |
-
# Salt-adjusted melting temperature
|
| 110 |
-
gc_content = ScientificAnalyzer.calculate_gc_content(sequence)
|
| 111 |
-
return 81.5 + 0.41 * gc_content - 675 / len(sequence)
|
| 112 |
-
|
| 113 |
-
@staticmethod
|
| 114 |
-
def find_restriction_sites(sequence: str) -> Dict[str, List[int]]:
|
| 115 |
-
"""Find restriction enzyme cut sites"""
|
| 116 |
-
sites = {}
|
| 117 |
-
for enzyme, pattern in RESTRICTION_ENZYMES.items():
|
| 118 |
-
positions = []
|
| 119 |
-
for i in range(len(sequence) - len(pattern) + 1):
|
| 120 |
-
if sequence[i:i+len(pattern)] == pattern:
|
| 121 |
-
positions.append(i)
|
| 122 |
-
if positions:
|
| 123 |
-
sites[enzyme] = positions
|
| 124 |
-
return sites
|
| 125 |
-
|
| 126 |
-
@staticmethod
|
| 127 |
-
def find_orfs(sequence: str, min_length: int = 100) -> List[Tuple[int, int, str]]:
|
| 128 |
-
"""Find open reading frames"""
|
| 129 |
-
orfs = []
|
| 130 |
-
start_codon = 'ATG'
|
| 131 |
-
stop_codons = ['TAA', 'TAG', 'TGA']
|
| 132 |
-
|
| 133 |
-
for frame in range(3):
|
| 134 |
-
i = frame
|
| 135 |
-
while i < len(sequence) - 2:
|
| 136 |
-
codon = sequence[i:i+3]
|
| 137 |
-
if codon == start_codon:
|
| 138 |
-
# Found start codon, look for stop
|
| 139 |
-
for j in range(i + 3, len(sequence) - 2, 3):
|
| 140 |
-
codon = sequence[j:j+3]
|
| 141 |
-
if codon in stop_codons:
|
| 142 |
-
if j - i >= min_length:
|
| 143 |
-
orfs.append((i, j + 3, f"Frame +{frame + 1}"))
|
| 144 |
-
i = j
|
| 145 |
-
break
|
| 146 |
-
i += 3
|
| 147 |
-
|
| 148 |
-
return orfs
|
| 149 |
-
|
| 150 |
-
@staticmethod
|
| 151 |
-
def design_primers(sequence: str, product_size: int = 500) -> Dict[str, Any]:
|
| 152 |
-
"""Design PCR primers for the sequence"""
|
| 153 |
-
primer_length = 20
|
| 154 |
-
primers = []
|
| 155 |
-
|
| 156 |
-
# Find suitable primer regions
|
| 157 |
-
for start in range(0, len(sequence) - product_size, 100):
|
| 158 |
-
forward = sequence[start:start + primer_length]
|
| 159 |
-
reverse_start = start + product_size - primer_length
|
| 160 |
-
if reverse_start < len(sequence):
|
| 161 |
-
reverse = sequence[reverse_start:reverse_start + primer_length]
|
| 162 |
-
reverse_comp = ScientificAnalyzer.reverse_complement(reverse)
|
| 163 |
-
|
| 164 |
-
# Calculate primer properties
|
| 165 |
-
forward_tm = ScientificAnalyzer.calculate_melting_temp(forward)
|
| 166 |
-
reverse_tm = ScientificAnalyzer.calculate_melting_temp(reverse_comp)
|
| 167 |
-
|
| 168 |
-
if abs(forward_tm - reverse_tm) < 5: # Similar Tm
|
| 169 |
-
primers.append({
|
| 170 |
-
'forward': forward,
|
| 171 |
-
'reverse': reverse_comp,
|
| 172 |
-
'forward_tm': forward_tm,
|
| 173 |
-
'reverse_tm': reverse_tm,
|
| 174 |
-
'product_size': product_size,
|
| 175 |
-
'position': start
|
| 176 |
-
})
|
| 177 |
-
|
| 178 |
-
return primers[0] if primers else None
|
| 179 |
-
|
| 180 |
-
@staticmethod
|
| 181 |
-
def reverse_complement(sequence: str) -> str:
|
| 182 |
-
"""Get reverse complement of DNA sequence"""
|
| 183 |
-
complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
|
| 184 |
-
return ''.join(complement.get(base, base) for base in reversed(sequence))
|
| 185 |
-
|
| 186 |
-
@staticmethod
|
| 187 |
-
def codon_optimize(protein_sequence: str, organism: str = "E.coli") -> str:
|
| 188 |
-
"""Optimize codons for expression in target organism"""
|
| 189 |
-
# Simplified codon optimization - in reality would use organism-specific tables
|
| 190 |
-
ecoli_preferred_codons = {
|
| 191 |
-
'F': 'TTT', 'L': 'CTG', 'S': 'TCT', 'Y': 'TAT',
|
| 192 |
-
'C': 'TGC', 'W': 'TGG', 'P': 'CCG', 'H': 'CAT',
|
| 193 |
-
'Q': 'CAG', 'R': 'CGT', 'I': 'ATT', 'M': 'ATG',
|
| 194 |
-
'T': 'ACC', 'N': 'AAC', 'K': 'AAA', 'V': 'GTT',
|
| 195 |
-
'A': 'GCT', 'D': 'GAT', 'E': 'GAA', 'G': 'GGT'
|
| 196 |
}
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
"""3D protein structure prediction using external APIs"""
|
| 207 |
-
|
| 208 |
-
@staticmethod
|
| 209 |
-
async def predict_structure(protein_sequence: str) -> Dict[str, Any]:
|
| 210 |
-
"""Mock structure prediction - would integrate with AlphaFold API"""
|
| 211 |
-
# Simplified structure prediction
|
| 212 |
-
structure_data = {
|
| 213 |
-
'confidence': np.random.uniform(70, 95),
|
| 214 |
-
'secondary_structure': ProteinStructurePredictor._predict_secondary_structure(protein_sequence),
|
| 215 |
-
'domains': ProteinStructurePredictor._predict_domains(protein_sequence),
|
| 216 |
-
'pdb_data': None # Would contain actual 3D coordinates
|
| 217 |
}
|
| 218 |
-
return structure_data
|
| 219 |
-
|
| 220 |
-
@staticmethod
|
| 221 |
-
def _predict_secondary_structure(sequence: str) -> str:
|
| 222 |
-
"""Simple secondary structure prediction"""
|
| 223 |
-
structure = []
|
| 224 |
-
for i, aa in enumerate(sequence):
|
| 225 |
-
if aa in 'VILMFYW': # Hydrophobic - likely beta sheet
|
| 226 |
-
structure.append('B')
|
| 227 |
-
elif aa in 'DEKR': # Charged - likely loop
|
| 228 |
-
structure.append('L')
|
| 229 |
-
else: # Mixed - likely helix
|
| 230 |
-
structure.append('H')
|
| 231 |
-
return ''.join(structure)
|
| 232 |
-
|
| 233 |
-
@staticmethod
|
| 234 |
-
def _predict_domains(sequence: str) -> List[Dict[str, Any]]:
|
| 235 |
-
"""Predict protein domains"""
|
| 236 |
-
domains = []
|
| 237 |
-
# Mock domain prediction
|
| 238 |
-
if 'CXXC' in sequence or sequence.count('C') > len(sequence) * 0.1:
|
| 239 |
-
domains.append({
|
| 240 |
-
'name': 'Zinc finger domain',
|
| 241 |
-
'start': 0,
|
| 242 |
-
'end': 30,
|
| 243 |
-
'confidence': 85
|
| 244 |
-
})
|
| 245 |
-
return domains
|
| 246 |
-
|
| 247 |
-
class LLMChatAssistant:
|
| 248 |
-
"""LLM-powered scientific chat assistant"""
|
| 249 |
-
|
| 250 |
-
def __init__(self):
|
| 251 |
-
self.api_token = os.getenv("FRIENDLI_TOKEN")
|
| 252 |
-
self.conversation_history = []
|
| 253 |
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
| 258 |
|
| 259 |
-
|
| 260 |
-
#
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
response = await self._call_llm_api(system_prompt, user_prompt)
|
| 269 |
-
|
| 270 |
-
# Add response to history
|
| 271 |
-
self.conversation_history.append({"role": "assistant", "content": response})
|
| 272 |
-
|
| 273 |
-
return response
|
| 274 |
-
|
| 275 |
-
except Exception as e:
|
| 276 |
-
logger.error(f"Chat error: {e}")
|
| 277 |
-
return f"Chat error: {str(e)}"
|
| 278 |
-
|
| 279 |
-
def _build_system_prompt(self, language: str) -> str:
|
| 280 |
-
"""Build system prompt for the assistant"""
|
| 281 |
-
if language == "ko":
|
| 282 |
-
return """당신은 분자생물학 전문가 AI 어시스턴트입니다.
|
| 283 |
-
DNA 시퀀스 분석, 단백질 구조 예측, 실험 설계, 프라이머 디자인 등을 도와드립니다.
|
| 284 |
-
과학적으로 정확하면서도 이해하기 쉽게 설명해드립니다."""
|
| 285 |
-
else:
|
| 286 |
-
return """You are an expert molecular biology AI assistant.
|
| 287 |
-
You help with DNA sequence analysis, protein structure prediction, experiment design, primer design, and more.
|
| 288 |
-
Provide scientifically accurate yet easy to understand explanations."""
|
| 289 |
-
|
| 290 |
-
def _build_user_prompt(self, message: str, context: Dict[str, Any], language: str) -> str:
|
| 291 |
-
"""Build context-aware user prompt"""
|
| 292 |
-
context_info = f"""
|
| 293 |
-
Current sequence: {context.get('sequence', 'None')[:50]}...
|
| 294 |
-
Cell type: {context.get('cell_type', 'Unknown')}
|
| 295 |
-
GC content: {context.get('gc_content', 'N/A')}%
|
| 296 |
-
Restriction sites found: {len(context.get('restriction_sites', {}))}
|
| 297 |
-
"""
|
| 298 |
-
|
| 299 |
-
return f"{context_info}\n\nUser question: {message}"
|
| 300 |
-
|
| 301 |
-
async def _call_llm_api(self, system_prompt: str, user_prompt: str) -> str:
|
| 302 |
-
"""Make async API call to LLM"""
|
| 303 |
-
url = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
| 304 |
-
headers = {
|
| 305 |
-
"Authorization": f"Bearer {self.api_token}",
|
| 306 |
-
"Content-Type": "application/json"
|
| 307 |
}
|
| 308 |
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
}
|
| 318 |
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
-
class
|
| 325 |
-
|
|
|
|
| 326 |
|
| 327 |
def __init__(self):
|
| 328 |
-
self.
|
| 329 |
-
self.
|
| 330 |
-
self.
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
self.current_analysis = None
|
| 335 |
-
|
| 336 |
-
def initialize_model(self):
|
| 337 |
-
"""Initialize the DNA-Diffusion model"""
|
| 338 |
-
if not MODEL_AVAILABLE:
|
| 339 |
-
self.model_error = "DNA-Diffusion model module not available"
|
| 340 |
-
return
|
| 341 |
-
|
| 342 |
-
if self.model_loading:
|
| 343 |
-
return
|
| 344 |
-
|
| 345 |
-
self.model_loading = True
|
| 346 |
-
try:
|
| 347 |
-
logger.info("Starting model initialization...")
|
| 348 |
-
self.model = get_model()
|
| 349 |
-
logger.info("Model initialized successfully!")
|
| 350 |
-
self.model_error = None
|
| 351 |
-
except Exception as e:
|
| 352 |
-
logger.error(f"Failed to initialize model: {e}")
|
| 353 |
-
self.model_error = str(e)
|
| 354 |
-
self.model = None
|
| 355 |
-
finally:
|
| 356 |
-
self.model_loading = False
|
| 357 |
-
|
| 358 |
-
@spaces.GPU(duration=60)
|
| 359 |
-
def generate_and_analyze(self, cell_type: str, guidance_scale: float = 1.0, language: str = "en"):
|
| 360 |
-
"""Generate sequence and perform comprehensive analysis"""
|
| 361 |
try:
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
result = self.model.generate(cell_type, guidance_scale)
|
| 365 |
-
sequence = result['sequence']
|
| 366 |
-
else:
|
| 367 |
-
# Mock generation
|
| 368 |
-
import random
|
| 369 |
-
sequence = ''.join(random.choice(['A', 'T', 'C', 'G']) for _ in range(200))
|
| 370 |
-
|
| 371 |
-
# Perform comprehensive analysis
|
| 372 |
-
analysis = self.analyze_sequence(sequence, cell_type)
|
| 373 |
|
| 374 |
-
#
|
|
|
|
| 375 |
self.current_analysis = {
|
| 376 |
-
'sequence':
|
| 377 |
'cell_type': cell_type,
|
| 378 |
-
'
|
| 379 |
-
'
|
| 380 |
-
'
|
| 381 |
-
'
|
| 382 |
}
|
| 383 |
|
| 384 |
-
return json.dumps(
|
| 385 |
-
'sequence': sequence,
|
| 386 |
-
'analysis': {
|
| 387 |
-
'gc_content': analysis.gc_content,
|
| 388 |
-
'melting_temp': analysis.melting_temp,
|
| 389 |
-
'restriction_sites': analysis.restriction_sites,
|
| 390 |
-
'orfs': analysis.orfs,
|
| 391 |
-
'primers': analysis.primers,
|
| 392 |
-
'protein_analysis': analysis.protein_analysis
|
| 393 |
-
}
|
| 394 |
-
})
|
| 395 |
|
| 396 |
except Exception as e:
|
| 397 |
-
logger.error(f"Generation
|
| 398 |
-
return json.dumps({"error": str(e)})
|
| 399 |
-
|
| 400 |
-
def analyze_sequence(self, sequence: str, cell_type: str) -> AnalysisResult:
|
| 401 |
-
"""Perform comprehensive sequence analysis"""
|
| 402 |
-
# Basic analysis
|
| 403 |
-
gc_content = self.analyzer.calculate_gc_content(sequence)
|
| 404 |
-
melting_temp = self.analyzer.calculate_melting_temp(sequence)
|
| 405 |
-
restriction_sites = self.analyzer.find_restriction_sites(sequence)
|
| 406 |
-
orfs = self.analyzer.find_orfs(sequence)
|
| 407 |
-
|
| 408 |
-
# Primer design
|
| 409 |
-
primers = self.analyzer.design_primers(sequence)
|
| 410 |
-
|
| 411 |
-
# Protein analysis
|
| 412 |
-
protein_seq = self.translate_to_protein(sequence)
|
| 413 |
-
protein_analysis = self.analyze_protein_basic(protein_seq)
|
| 414 |
-
|
| 415 |
-
return AnalysisResult(
|
| 416 |
-
sequence=sequence,
|
| 417 |
-
gc_content=gc_content,
|
| 418 |
-
melting_temp=melting_temp,
|
| 419 |
-
restriction_sites=restriction_sites,
|
| 420 |
-
orfs=orfs,
|
| 421 |
-
primers=primers,
|
| 422 |
-
protein_analysis=protein_analysis
|
| 423 |
-
)
|
| 424 |
-
|
| 425 |
-
def translate_to_protein(self, dna_sequence: str) -> str:
|
| 426 |
-
"""Translate DNA to protein"""
|
| 427 |
-
protein = []
|
| 428 |
-
for i in range(0, len(dna_sequence) - 2, 3):
|
| 429 |
-
codon = dna_sequence[i:i+3]
|
| 430 |
-
if len(codon) == 3:
|
| 431 |
-
aa = CODON_TABLE.get(codon, 'X')
|
| 432 |
-
if aa == '*':
|
| 433 |
-
break
|
| 434 |
-
protein.append(aa)
|
| 435 |
-
return ''.join(protein)
|
| 436 |
-
|
| 437 |
-
def analyze_protein_basic(self, protein_sequence: str) -> str:
|
| 438 |
-
"""Basic protein analysis"""
|
| 439 |
-
if not protein_sequence:
|
| 440 |
-
return "No protein sequence generated"
|
| 441 |
-
|
| 442 |
-
# Calculate basic properties
|
| 443 |
-
length = len(protein_sequence)
|
| 444 |
-
molecular_weight = sum(self.get_aa_weight(aa) for aa in protein_sequence)
|
| 445 |
-
|
| 446 |
-
# Count amino acid types
|
| 447 |
-
hydrophobic = sum(1 for aa in protein_sequence if aa in 'AILMFVPW')
|
| 448 |
-
charged = sum(1 for aa in protein_sequence if aa in 'DEKR')
|
| 449 |
-
|
| 450 |
-
analysis = f"""
|
| 451 |
-
Protein length: {length} amino acids
|
| 452 |
-
Molecular weight: ~{molecular_weight:.1f} Da
|
| 453 |
-
Hydrophobic residues: {hydrophobic} ({hydrophobic/length*100:.1f}%)
|
| 454 |
-
Charged residues: {charged} ({charged/length*100:.1f}%)
|
| 455 |
-
"""
|
| 456 |
-
|
| 457 |
-
return analysis
|
| 458 |
|
| 459 |
-
def
|
| 460 |
-
"""
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
}
|
| 467 |
-
return weights.get(aa, 100)
|
| 468 |
|
| 469 |
-
|
| 470 |
-
"""
|
| 471 |
-
|
| 472 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
|
| 474 |
-
|
| 475 |
return response
|
| 476 |
-
|
| 477 |
-
def export_results(self, format_type: str) -> str:
|
| 478 |
-
"""Export analysis results in various formats"""
|
| 479 |
-
if not self.current_analysis:
|
| 480 |
-
return "No analysis to export"
|
| 481 |
-
|
| 482 |
-
if format_type == "genbank":
|
| 483 |
-
return self._export_genbank()
|
| 484 |
-
elif format_type == "fasta":
|
| 485 |
-
return self._export_fasta()
|
| 486 |
-
elif format_type == "json":
|
| 487 |
-
return json.dumps(self.current_analysis, indent=2)
|
| 488 |
-
else:
|
| 489 |
-
return "Unsupported format"
|
| 490 |
-
|
| 491 |
-
def _export_fasta(self) -> str:
|
| 492 |
-
"""Export in FASTA format"""
|
| 493 |
-
header = f">DNA_Diffusion_{self.current_analysis['cell_type']}_{datetime.now().strftime('%Y%m%d')}"
|
| 494 |
-
return f"{header}\n{self.current_analysis['sequence']}"
|
| 495 |
-
|
| 496 |
-
def _export_genbank(self) -> str:
|
| 497 |
-
"""Export in GenBank format"""
|
| 498 |
-
# Simplified GenBank format
|
| 499 |
-
return f"""LOCUS DNA_Diffusion {len(self.current_analysis['sequence'])} bp DNA linear SYN {datetime.now().strftime('%d-%b-%Y')}
|
| 500 |
-
DEFINITION Synthetic DNA sequence for {self.current_analysis['cell_type']}
|
| 501 |
-
ORIGIN
|
| 502 |
-
1 {self.current_analysis['sequence']}
|
| 503 |
-
//"""
|
| 504 |
|
| 505 |
-
# Create
|
| 506 |
-
app =
|
| 507 |
|
| 508 |
-
def
|
| 509 |
-
"""Create
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 510 |
|
| 511 |
-
with gr.Blocks(
|
| 512 |
-
gr.Markdown("# 🧬
|
| 513 |
-
|
| 514 |
-
with gr.
|
| 515 |
-
with gr.
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
)
|
| 531 |
-
language = gr.Radio(
|
| 532 |
-
["en", "ko"],
|
| 533 |
-
value="en",
|
| 534 |
-
label="Language"
|
| 535 |
-
)
|
| 536 |
-
generate_btn = gr.Button("🎲 Generate & Analyze", variant="primary")
|
| 537 |
-
|
| 538 |
-
with gr.Column(scale=3):
|
| 539 |
-
# Results display
|
| 540 |
-
results_json = gr.JSON(label="Analysis Results", visible=False)
|
| 541 |
-
|
| 542 |
-
# Visual results
|
| 543 |
-
with gr.Accordion("📊 Sequence Analysis", open=True):
|
| 544 |
-
gc_plot = gr.Plot(label="GC Content Distribution")
|
| 545 |
-
restriction_map = gr.Plot(label="Restriction Enzyme Map")
|
| 546 |
-
|
| 547 |
-
with gr.Accordion("🧬 Protein Analysis", open=True):
|
| 548 |
-
protein_structure = gr.HTML(label="Predicted Structure")
|
| 549 |
-
protein_properties = gr.Textbox(label="Properties", lines=5)
|
| 550 |
|
| 551 |
-
with gr.
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
chat_btn = gr.Button("Send")
|
| 555 |
|
| 556 |
-
#
|
| 557 |
-
gr.
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
"Can you explain the ORFs found in this sequence?",
|
| 561 |
-
"How can I optimize this sequence for E. coli expression?",
|
| 562 |
-
"What's the predicted protein structure?"
|
| 563 |
-
],
|
| 564 |
-
inputs=msg
|
| 565 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
optimize_btn = gr.Button("Optimize Codons")
|
| 584 |
-
optimized_seq = gr.Textbox(label="Optimized Sequence", lines=5)
|
| 585 |
|
| 586 |
-
|
| 587 |
-
export_format = gr.Radio(
|
| 588 |
-
["FASTA", "GenBank", "JSON"],
|
| 589 |
-
value="FASTA",
|
| 590 |
-
label="Export Format"
|
| 591 |
-
)
|
| 592 |
-
export_btn = gr.Button("Export Results")
|
| 593 |
-
export_output = gr.Textbox(label="Exported Data", lines=10)
|
| 594 |
|
| 595 |
-
# Wire up the interface
|
| 596 |
generate_btn.click(
|
| 597 |
-
fn=
|
| 598 |
-
inputs=[cell_type, guidance_scale
|
| 599 |
-
outputs=[
|
| 600 |
-
).then(
|
| 601 |
-
fn=visualize_results,
|
| 602 |
-
inputs=[results_json],
|
| 603 |
-
outputs=[gc_plot, restriction_map, protein_structure, protein_properties]
|
| 604 |
)
|
| 605 |
|
| 606 |
# Chat functionality
|
| 607 |
-
def respond(message, chat_history
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
chat_history.append((message, response))
|
| 611 |
return "", chat_history
|
| 612 |
|
| 613 |
-
msg.submit(respond, [msg, chatbot
|
| 614 |
-
|
| 615 |
|
| 616 |
-
#
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
)
|
| 622 |
-
|
| 623 |
-
# Initialize model on load
|
| 624 |
-
demo.load(fn=app.initialize_model)
|
| 625 |
|
| 626 |
return demo
|
| 627 |
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
<div style="background: linear-gradient(to right, #ff0000 45%, #00ff00 30%, #0000ff 25%);
|
| 673 |
-
height: 30px; border-radius: 5px; margin: 10px 0;"></div>
|
| 674 |
-
<p style="color: #666;">3D structure prediction available in Pro version</p>
|
| 675 |
-
</div>
|
| 676 |
-
"""
|
| 677 |
-
|
| 678 |
-
# Protein properties
|
| 679 |
-
properties = analysis.get('protein_analysis', 'No analysis available')
|
| 680 |
|
| 681 |
-
|
| 682 |
|
| 683 |
-
# Launch the enhanced app
|
| 684 |
if __name__ == "__main__":
|
| 685 |
-
|
| 686 |
-
demo.launch(share=True)
|
|
|
|
| 1 |
"""
|
| 2 |
+
Fixed and Enhanced DNA-Diffusion Gradio Application
|
| 3 |
+
Resolves compatibility issues and adds practical features
|
| 4 |
"""
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
import logging
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
+
from typing import Dict, Any, Tuple, List, Optional
|
| 11 |
import html
|
| 12 |
import requests
|
| 13 |
import time
|
|
|
|
| 15 |
from dataclasses import dataclass
|
| 16 |
from datetime import datetime
|
| 17 |
import asyncio
|
| 18 |
+
import threading
|
| 19 |
+
from queue import Queue
|
| 20 |
|
| 21 |
# Configure logging
|
| 22 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
|
|
| 35 |
return func
|
| 36 |
return decorator
|
| 37 |
|
| 38 |
+
# Mock model for demonstration
|
| 39 |
+
class MockDNAModel:
|
| 40 |
+
"""Mock DNA generation model for testing"""
|
| 41 |
+
def generate(self, cell_type: str, guidance_scale: float = 1.0):
|
| 42 |
+
import random
|
| 43 |
+
bases = ['A', 'T', 'C', 'G']
|
| 44 |
+
sequence = ''.join(random.choice(bases) for _ in range(200))
|
| 45 |
+
|
| 46 |
+
# Simulate some realistic patterns
|
| 47 |
+
if cell_type == "K562":
|
| 48 |
+
# Add some GC-rich regions for K562
|
| 49 |
+
sequence = sequence[:50] + 'GCGCGCGC' + sequence[58:150] + 'CGCGCGCG' + sequence[158:]
|
| 50 |
+
|
| 51 |
+
return {
|
| 52 |
+
'sequence': sequence,
|
| 53 |
+
'metadata': {
|
| 54 |
+
'cell_type': cell_type,
|
| 55 |
+
'guidance_scale': guidance_scale,
|
| 56 |
+
'generation_time': 2.0,
|
| 57 |
+
'model_version': 'mock_v1'
|
| 58 |
+
}
|
| 59 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
# Global model instance
|
| 62 |
+
mock_model = MockDNAModel()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
# HTML template for the main interface
|
| 65 |
+
HTML_TEMPLATE = """
|
| 66 |
+
<!DOCTYPE html>
|
| 67 |
+
<html lang="en">
|
| 68 |
+
<head>
|
| 69 |
+
<meta charset="UTF-8">
|
| 70 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 71 |
+
<title>DNA Casino - Molecular Engineering Suite</title>
|
| 72 |
+
<style>
|
| 73 |
+
body {
|
| 74 |
+
margin: 0;
|
| 75 |
+
padding: 20px;
|
| 76 |
+
background: #0a0a0a;
|
| 77 |
+
color: #fff;
|
| 78 |
+
font-family: 'Arial', sans-serif;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
}
|
| 80 |
|
| 81 |
+
.container {
|
| 82 |
+
max-width: 1200px;
|
| 83 |
+
margin: 0 auto;
|
| 84 |
+
}
|
| 85 |
|
| 86 |
+
.header {
|
| 87 |
+
text-align: center;
|
| 88 |
+
margin-bottom: 30px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
.title {
|
| 92 |
+
font-size: 3rem;
|
| 93 |
+
background: linear-gradient(45deg, #ff00ff, #00ffff);
|
| 94 |
+
-webkit-background-clip: text;
|
| 95 |
+
-webkit-text-fill-color: transparent;
|
| 96 |
+
margin: 0;
|
| 97 |
+
}
|
| 98 |
|
| 99 |
+
.sequence-display {
|
| 100 |
+
background: #1a1a1a;
|
| 101 |
+
border: 2px solid #00ff00;
|
| 102 |
+
border-radius: 10px;
|
| 103 |
+
padding: 20px;
|
| 104 |
+
font-family: monospace;
|
| 105 |
+
word-break: break-all;
|
| 106 |
+
margin: 20px 0;
|
| 107 |
+
min-height: 100px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
}
|
| 109 |
|
| 110 |
+
.controls {
|
| 111 |
+
display: flex;
|
| 112 |
+
gap: 20px;
|
| 113 |
+
justify-content: center;
|
| 114 |
+
margin: 20px 0;
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
.btn {
|
| 118 |
+
padding: 15px 30px;
|
| 119 |
+
background: linear-gradient(145deg, #ff0066, #ff00ff);
|
| 120 |
+
border: none;
|
| 121 |
+
border-radius: 25px;
|
| 122 |
+
color: white;
|
| 123 |
+
font-size: 18px;
|
| 124 |
+
cursor: pointer;
|
| 125 |
+
transition: all 0.3s;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
.btn:hover {
|
| 129 |
+
transform: translateY(-2px);
|
| 130 |
+
box-shadow: 0 5px 20px rgba(255,0,255,0.5);
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
.stats {
|
| 134 |
+
display: grid;
|
| 135 |
+
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
| 136 |
+
gap: 20px;
|
| 137 |
+
margin: 30px 0;
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
.stat-card {
|
| 141 |
+
background: rgba(255,255,255,0.1);
|
| 142 |
+
border-radius: 10px;
|
| 143 |
+
padding: 20px;
|
| 144 |
+
text-align: center;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
.stat-value {
|
| 148 |
+
font-size: 2rem;
|
| 149 |
+
color: #00ff00;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
.loading {
|
| 153 |
+
display: none;
|
| 154 |
+
text-align: center;
|
| 155 |
+
margin: 20px 0;
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
.spinner {
|
| 159 |
+
border: 3px solid rgba(255,255,255,0.1);
|
| 160 |
+
border-top-color: #00ff00;
|
| 161 |
+
border-radius: 50%;
|
| 162 |
+
width: 40px;
|
| 163 |
+
height: 40px;
|
| 164 |
+
animation: spin 1s linear infinite;
|
| 165 |
+
margin: 0 auto;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
@keyframes spin {
|
| 169 |
+
to { transform: rotate(360deg); }
|
| 170 |
+
}
|
| 171 |
+
</style>
|
| 172 |
+
</head>
|
| 173 |
+
<body>
|
| 174 |
+
<div class="container">
|
| 175 |
+
<div class="header">
|
| 176 |
+
<h1 class="title">🧬 DNA Casino 🧬</h1>
|
| 177 |
+
<p>Advanced Molecular Engineering Suite</p>
|
| 178 |
+
</div>
|
| 179 |
+
|
| 180 |
+
<div class="controls">
|
| 181 |
+
<select id="cellType" class="btn">
|
| 182 |
+
<option value="K562">K562</option>
|
| 183 |
+
<option value="GM12878">GM12878</option>
|
| 184 |
+
<option value="HepG2">HepG2</option>
|
| 185 |
+
</select>
|
| 186 |
+
<button class="btn" onclick="generateSequence()">Generate Sequence</button>
|
| 187 |
+
</div>
|
| 188 |
+
|
| 189 |
+
<div class="loading" id="loading">
|
| 190 |
+
<div class="spinner"></div>
|
| 191 |
+
<p>Generating sequence...</p>
|
| 192 |
+
</div>
|
| 193 |
+
|
| 194 |
+
<div class="sequence-display" id="sequenceDisplay">
|
| 195 |
+
Click "Generate Sequence" to start
|
| 196 |
+
</div>
|
| 197 |
+
|
| 198 |
+
<div class="stats" id="stats"></div>
|
| 199 |
+
</div>
|
| 200 |
+
|
| 201 |
+
<script>
|
| 202 |
+
function generateSequence() {
|
| 203 |
+
const cellType = document.getElementById('cellType').value;
|
| 204 |
+
const loading = document.getElementById('loading');
|
| 205 |
+
const display = document.getElementById('sequenceDisplay');
|
| 206 |
+
|
| 207 |
+
loading.style.display = 'block';
|
| 208 |
+
display.textContent = '';
|
| 209 |
+
|
| 210 |
+
// Send message to parent
|
| 211 |
+
window.parent.postMessage({
|
| 212 |
+
type: 'generate',
|
| 213 |
+
cellType: cellType
|
| 214 |
+
}, '*');
|
| 215 |
}
|
| 216 |
|
| 217 |
+
// Listen for results
|
| 218 |
+
window.addEventListener('message', (event) => {
|
| 219 |
+
if (event.data.type === 'result') {
|
| 220 |
+
const loading = document.getElementById('loading');
|
| 221 |
+
const display = document.getElementById('sequenceDisplay');
|
| 222 |
+
const stats = document.getElementById('stats');
|
| 223 |
+
|
| 224 |
+
loading.style.display = 'none';
|
| 225 |
+
display.textContent = event.data.sequence;
|
| 226 |
+
|
| 227 |
+
// Update stats
|
| 228 |
+
stats.innerHTML = `
|
| 229 |
+
<div class="stat-card">
|
| 230 |
+
<div class="stat-label">Length</div>
|
| 231 |
+
<div class="stat-value">${event.data.length} bp</div>
|
| 232 |
+
</div>
|
| 233 |
+
<div class="stat-card">
|
| 234 |
+
<div class="stat-label">GC Content</div>
|
| 235 |
+
<div class="stat-value">${event.data.gc_content}%</div>
|
| 236 |
+
</div>
|
| 237 |
+
<div class="stat-card">
|
| 238 |
+
<div class="stat-label">Cell Type</div>
|
| 239 |
+
<div class="stat-value">${event.data.cell_type}</div>
|
| 240 |
+
</div>
|
| 241 |
+
`;
|
| 242 |
+
}
|
| 243 |
+
});
|
| 244 |
+
</script>
|
| 245 |
+
</body>
|
| 246 |
+
</html>
|
| 247 |
+
"""
|
| 248 |
|
| 249 |
+
# Simplified app class
|
| 250 |
+
class DNAApp:
|
| 251 |
+
"""Simplified DNA application without complex UI components that cause errors"""
|
| 252 |
|
| 253 |
def __init__(self):
|
| 254 |
+
self.current_sequence = ""
|
| 255 |
+
self.current_analysis = {}
|
| 256 |
+
self.chat_history = []
|
| 257 |
+
|
| 258 |
+
def generate_sequence(self, cell_type: str, guidance_scale: float = 1.0):
|
| 259 |
+
"""Generate DNA sequence"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
try:
|
| 261 |
+
result = mock_model.generate(cell_type, guidance_scale)
|
| 262 |
+
self.current_sequence = result['sequence']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
+
# Perform analysis
|
| 265 |
+
analysis = self.analyze_sequence(self.current_sequence)
|
| 266 |
self.current_analysis = {
|
| 267 |
+
'sequence': self.current_sequence,
|
| 268 |
'cell_type': cell_type,
|
| 269 |
+
'length': len(self.current_sequence),
|
| 270 |
+
'gc_content': analysis['gc_content'],
|
| 271 |
+
'melting_temp': analysis['melting_temp'],
|
| 272 |
+
'restriction_sites': analysis['restriction_sites']
|
| 273 |
}
|
| 274 |
|
| 275 |
+
return self.current_sequence, json.dumps(self.current_analysis)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
except Exception as e:
|
| 278 |
+
logger.error(f"Generation error: {e}")
|
| 279 |
+
return "", json.dumps({"error": str(e)})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
+
def analyze_sequence(self, sequence: str) -> Dict[str, Any]:
|
| 282 |
+
"""Basic sequence analysis"""
|
| 283 |
+
gc_count = sequence.count('G') + sequence.count('C')
|
| 284 |
+
gc_content = (gc_count / len(sequence) * 100) if sequence else 0
|
| 285 |
+
|
| 286 |
+
# Simple melting temperature calculation
|
| 287 |
+
if len(sequence) < 14:
|
| 288 |
+
tm = 4 * (sequence.count('G') + sequence.count('C')) + 2 * (sequence.count('A') + sequence.count('T'))
|
| 289 |
+
else:
|
| 290 |
+
tm = 81.5 + 0.41 * gc_content - 675 / len(sequence)
|
| 291 |
+
|
| 292 |
+
# Find restriction sites
|
| 293 |
+
sites = {}
|
| 294 |
+
enzymes = {
|
| 295 |
+
'EcoRI': 'GAATTC',
|
| 296 |
+
'BamHI': 'GGATCC',
|
| 297 |
+
'HindIII': 'AAGCTT'
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
for enzyme, pattern in enzymes.items():
|
| 301 |
+
positions = []
|
| 302 |
+
for i in range(len(sequence) - len(pattern) + 1):
|
| 303 |
+
if sequence[i:i+len(pattern)] == pattern:
|
| 304 |
+
positions.append(i)
|
| 305 |
+
if positions:
|
| 306 |
+
sites[enzyme] = positions
|
| 307 |
+
|
| 308 |
+
return {
|
| 309 |
+
'gc_content': round(gc_content, 1),
|
| 310 |
+
'melting_temp': round(tm, 1),
|
| 311 |
+
'restriction_sites': sites
|
| 312 |
}
|
|
|
|
| 313 |
|
| 314 |
+
def chat_response(self, message: str) -> str:
|
| 315 |
+
"""Simple chat response"""
|
| 316 |
+
self.chat_history.append(("user", message))
|
| 317 |
+
|
| 318 |
+
# Simple rule-based responses
|
| 319 |
+
response = "I can help you analyze DNA sequences. "
|
| 320 |
+
|
| 321 |
+
if "gc" in message.lower() or "content" in message.lower():
|
| 322 |
+
if self.current_analysis:
|
| 323 |
+
response = f"The GC content of your sequence is {self.current_analysis.get('gc_content', 0)}%"
|
| 324 |
+
else:
|
| 325 |
+
response = "Please generate a sequence first to analyze GC content."
|
| 326 |
+
elif "restriction" in message.lower() or "enzyme" in message.lower():
|
| 327 |
+
if self.current_analysis:
|
| 328 |
+
sites = self.current_analysis.get('restriction_sites', {})
|
| 329 |
+
if sites:
|
| 330 |
+
response = f"Found restriction sites for: {', '.join(sites.keys())}"
|
| 331 |
+
else:
|
| 332 |
+
response = "No common restriction sites found in the sequence."
|
| 333 |
+
else:
|
| 334 |
+
response = "Please generate a sequence first to analyze restriction sites."
|
| 335 |
+
elif "primer" in message.lower():
|
| 336 |
+
response = "For primer design, consider: 18-25 bp length, 50-60% GC content, Tm around 55-65°C"
|
| 337 |
|
| 338 |
+
self.chat_history.append(("assistant", response))
|
| 339 |
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
+
# Create app instance
|
| 342 |
+
app = DNAApp()
|
| 343 |
|
| 344 |
+
def create_interface():
|
| 345 |
+
"""Create a simplified Gradio interface that avoids the schema error"""
|
| 346 |
+
|
| 347 |
+
# Custom CSS
|
| 348 |
+
css = """
|
| 349 |
+
.gradio-container {
|
| 350 |
+
background-color: #0a0a0a !important;
|
| 351 |
+
}
|
| 352 |
+
"""
|
| 353 |
|
| 354 |
+
with gr.Blocks(css=css, title="DNA Casino") as demo:
|
| 355 |
+
gr.Markdown("# 🧬 DNA Casino - Molecular Engineering Suite")
|
| 356 |
+
|
| 357 |
+
with gr.Row():
|
| 358 |
+
with gr.Column(scale=1):
|
| 359 |
+
gr.Markdown("### Controls")
|
| 360 |
+
cell_type = gr.Dropdown(
|
| 361 |
+
["K562", "GM12878", "HepG2"],
|
| 362 |
+
value="K562",
|
| 363 |
+
label="Cell Type"
|
| 364 |
+
)
|
| 365 |
+
guidance_scale = gr.Slider(
|
| 366 |
+
1.0, 10.0, 1.0,
|
| 367 |
+
label="Guidance Scale"
|
| 368 |
+
)
|
| 369 |
+
generate_btn = gr.Button("🎲 Generate Sequence", variant="primary")
|
| 370 |
+
|
| 371 |
+
gr.Markdown("### Analysis Results")
|
| 372 |
+
analysis_output = gr.JSON(label="Analysis Data")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
|
| 374 |
+
with gr.Column(scale=2):
|
| 375 |
+
# Main display using HTML component
|
| 376 |
+
main_display = gr.HTML(HTML_TEMPLATE)
|
|
|
|
| 377 |
|
| 378 |
+
# Sequence output (hidden, used for backend)
|
| 379 |
+
sequence_output = gr.Textbox(
|
| 380 |
+
label="Generated Sequence",
|
| 381 |
+
visible=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
)
|
| 383 |
+
|
| 384 |
+
with gr.Row():
|
| 385 |
+
with gr.Column():
|
| 386 |
+
gr.Markdown("### AI Assistant")
|
| 387 |
+
chatbot = gr.Chatbot(height=300)
|
| 388 |
+
msg = gr.Textbox(
|
| 389 |
+
label="Ask about your sequence",
|
| 390 |
+
placeholder="E.g., What's the GC content? Find restriction sites."
|
| 391 |
+
)
|
| 392 |
+
clear = gr.Button("Clear Chat")
|
| 393 |
+
|
| 394 |
+
# Event handlers
|
| 395 |
+
def generate_and_update(cell_type, guidance_scale):
|
| 396 |
+
seq, analysis = app.generate_sequence(cell_type, guidance_scale)
|
| 397 |
+
# Update the HTML display via JavaScript
|
| 398 |
+
analysis_dict = json.loads(analysis)
|
| 399 |
|
| 400 |
+
# Create JavaScript to update the embedded HTML
|
| 401 |
+
update_script = f"""
|
| 402 |
+
<script>
|
| 403 |
+
// Update the embedded iframe
|
| 404 |
+
const iframe = document.querySelector('iframe');
|
| 405 |
+
if (iframe && iframe.contentWindow) {{
|
| 406 |
+
iframe.contentWindow.postMessage({{
|
| 407 |
+
type: 'result',
|
| 408 |
+
sequence: '{seq}',
|
| 409 |
+
length: {len(seq)},
|
| 410 |
+
gc_content: {analysis_dict.get('gc_content', 0)},
|
| 411 |
+
cell_type: '{cell_type}'
|
| 412 |
+
}}, '*');
|
| 413 |
+
}}
|
| 414 |
+
</script>
|
| 415 |
+
"""
|
|
|
|
|
|
|
| 416 |
|
| 417 |
+
return seq, analysis, main_display.update(value=HTML_TEMPLATE + update_script)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
|
|
|
| 419 |
generate_btn.click(
|
| 420 |
+
fn=generate_and_update,
|
| 421 |
+
inputs=[cell_type, guidance_scale],
|
| 422 |
+
outputs=[sequence_output, analysis_output, main_display]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
)
|
| 424 |
|
| 425 |
# Chat functionality
|
| 426 |
+
def respond(message, chat_history):
|
| 427 |
+
bot_message = app.chat_response(message)
|
| 428 |
+
chat_history.append((message, bot_message))
|
|
|
|
| 429 |
return "", chat_history
|
| 430 |
|
| 431 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 432 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 433 |
|
| 434 |
+
# Add examples
|
| 435 |
+
gr.Examples(
|
| 436 |
+
examples=[
|
| 437 |
+
"What's the GC content?",
|
| 438 |
+
"Find restriction enzyme sites",
|
| 439 |
+
"How do I design primers?",
|
| 440 |
+
"What's the melting temperature?"
|
| 441 |
+
],
|
| 442 |
+
inputs=msg
|
| 443 |
)
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
return demo
|
| 446 |
|
| 447 |
+
# Error-safe launcher
|
| 448 |
+
def safe_launch():
|
| 449 |
+
"""Launch the app with error handling"""
|
| 450 |
+
try:
|
| 451 |
+
demo = create_interface()
|
| 452 |
+
|
| 453 |
+
# Detect environment
|
| 454 |
+
import os
|
| 455 |
+
if os.getenv("SPACE_ID"):
|
| 456 |
+
# Running on Hugging Face Spaces
|
| 457 |
+
demo.launch(
|
| 458 |
+
server_name="0.0.0.0",
|
| 459 |
+
server_port=7860,
|
| 460 |
+
share=False
|
| 461 |
+
)
|
| 462 |
+
else:
|
| 463 |
+
# Local development
|
| 464 |
+
demo.launch(
|
| 465 |
+
share=True,
|
| 466 |
+
debug=True
|
| 467 |
+
)
|
| 468 |
+
except Exception as e:
|
| 469 |
+
logger.error(f"Failed to launch: {e}")
|
| 470 |
+
# Fallback to even simpler interface
|
| 471 |
+
print("Starting fallback interface...")
|
| 472 |
+
create_fallback_interface()
|
| 473 |
+
|
| 474 |
+
def create_fallback_interface():
|
| 475 |
+
"""Ultra-simple fallback interface"""
|
| 476 |
+
with gr.Blocks() as demo:
|
| 477 |
+
gr.Markdown("# DNA Sequence Generator (Fallback Mode)")
|
| 478 |
+
|
| 479 |
+
with gr.Row():
|
| 480 |
+
cell_type = gr.Dropdown(["K562", "GM12878", "HepG2"], value="K562")
|
| 481 |
+
generate_btn = gr.Button("Generate")
|
| 482 |
+
|
| 483 |
+
output = gr.Textbox(label="Generated Sequence", lines=5)
|
| 484 |
+
|
| 485 |
+
def simple_generate(cell_type):
|
| 486 |
+
import random
|
| 487 |
+
seq = ''.join(random.choice(['A','T','C','G']) for _ in range(200))
|
| 488 |
+
return seq
|
| 489 |
+
|
| 490 |
+
generate_btn.click(simple_generate, cell_type, output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
|
| 492 |
+
demo.launch()
|
| 493 |
|
|
|
|
| 494 |
if __name__ == "__main__":
|
| 495 |
+
safe_launch()
|
|
|