File size: 33,863 Bytes
d0325f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7ba5e
10a0a58
dd7ba5e
d0325f0
dd7ba5e
 
10a0a58
 
d0325f0
10a0a58
d0325f0
dd7ba5e
d0325f0
10a0a58
d0325f0
10a0a58
 
 
d0325f0
10a0a58
 
d0325f0
dd7ba5e
10a0a58
dd7ba5e
 
 
 
10a0a58
dd7ba5e
 
 
 
 
 
 
10a0a58
dd7ba5e
 
 
10a0a58
 
 
 
 
 
 
dd7ba5e
10a0a58
dd7ba5e
 
 
 
 
 
 
 
 
 
 
 
 
10a0a58
d0325f0
10a0a58
d0325f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4db98d
 
 
0fdc371
f4db98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fdc371
f4db98d
 
 
 
 
 
 
 
 
d0325f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b75dfea
d0325f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b75dfea
 
d0325f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446e924
d0325f0
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
"""

BioPrime Molecular Docking Demo

================================

Interactive demo showcasing AI-powered molecular docking for drug discovery.



Features:

- 3D protein structure visualization

- Compound library selection

- Docking simulation with binding energy results

- BSV blockchain verification display



Powered by: Origin Neural AI Docking Engine

Sponsored by: Smartledger Solutions, Origin Neural AI, Bryan Daugherty

Website: https://bioprime.one

"""

import gradio as gr
import requests
import json
import hashlib
import random
from datetime import datetime
from typing import Optional, Dict, List, Tuple
import time

# =============================================================================
# Configuration
# =============================================================================

BIOPRIME_API = "https://bioprime.one/api/v1"
RCSB_PDB_URL = "https://files.rcsb.org/download"

# Demo targets with sponsored research campaigns
DEMO_TARGETS = [
    {
        "id": "melanoma",
        "name": "BRAF V600E - Melanoma",
        "pdb": "4MNE",
        "sponsor": "Bryan Daugherty",
        "disease": "Melanoma",
        "description": "Mutated BRAF kinase found in ~50% of melanomas, target for vemurafenib-like inhibitors.",
        "binding_site": {"x": 25.0, "y": 5.0, "z": 15.0},
        "color": "#FF6B6B"
    },
    {
        "id": "diabetes",
        "name": "DPP-4 - Type 2 Diabetes",
        "pdb": "2ONC",
        "sponsor": "Bryan Daugherty",
        "disease": "Type 2 Diabetes",
        "description": "Dipeptidyl peptidase-4, target for incretin-based diabetes medications like sitagliptin.",
        "binding_site": {"x": 35.0, "y": 40.0, "z": 45.0},
        "color": "#4ECDC4"
    },
    {
        "id": "covid",
        "name": "COVID-19 Main Protease",
        "pdb": "6LU7",
        "sponsor": "BioPrime Community",
        "disease": "COVID-19",
        "description": "SARS-CoV-2 main protease (Mpro), essential for viral replication. Target for Paxlovid.",
        "binding_site": {"x": -10.8, "y": 35.2, "z": 63.4},
        "color": "#9B59B6"
    },
    {
        "id": "hiv",
        "name": "HIV-1 Protease",
        "pdb": "1HVR",
        "sponsor": "Origin Neural AI",
        "disease": "HIV/AIDS",
        "description": "Critical enzyme for HIV replication, target for protease inhibitor antiretroviral drugs.",
        "binding_site": {"x": -6.2, "y": 20.1, "z": 41.8},
        "color": "#E74C3C"
    },
    {
        "id": "lung",
        "name": "EGFR Kinase - Lung Cancer",
        "pdb": "1M17",
        "sponsor": "Smartledger & Origin Neural AI",
        "disease": "Non-small Cell Lung Cancer",
        "description": "Epidermal growth factor receptor, key target in NSCLC therapy. Target for erlotinib.",
        "binding_site": {"x": 40.5, "y": 0.6, "z": 56.0},
        "color": "#3498DB"
    },
    {
        "id": "breast",
        "name": "CDK4/6 - Breast Cancer",
        "pdb": "5L2I",
        "sponsor": "Smartledger",
        "disease": "Breast Cancer",
        "description": "Cyclin-dependent kinase 4/6 inhibitor target for hormone-receptor positive breast cancer.",
        "binding_site": {"x": 15.0, "y": 25.0, "z": 35.0},
        "color": "#E91E63"
    },
]

# Demo compound library
COMPOUND_LIBRARY = [
    {"id": "aspirin", "name": "Aspirin", "smiles": "CC(=O)OC1=CC=CC=C1C(=O)O", "mw": 180.16, "category": "Anti-inflammatory"},
    {"id": "ibuprofen", "name": "Ibuprofen", "smiles": "CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", "mw": 206.29, "category": "Anti-inflammatory"},
    {"id": "caffeine", "name": "Caffeine", "smiles": "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "mw": 194.19, "category": "Stimulant"},
    {"id": "paracetamol", "name": "Acetaminophen", "smiles": "CC(=O)NC1=CC=C(O)C=C1", "mw": 151.16, "category": "Analgesic"},
    {"id": "metformin", "name": "Metformin", "smiles": "CN(C)C(=N)NC(=N)N", "mw": 129.17, "category": "Antidiabetic"},
    {"id": "atorvastatin", "name": "Atorvastatin", "smiles": "CC(C)C1=C(C(=C(N1CCC(CC(CC(=O)O)O)O)C2=CC=C(C=C2)F)C3=CC=CC=C3)C(=O)NC4=CC=CC=C4", "mw": 558.64, "category": "Statin"},
    {"id": "nirmatrelvir", "name": "Nirmatrelvir", "smiles": "CC1(CC1)C(=O)NC(CC2CCNC2=O)C(=O)NC(CC(F)(F)F)C#N", "mw": 499.53, "category": "Antiviral (COVID-19)"},
    {"id": "oseltamivir", "name": "Oseltamivir", "smiles": "CCOC(=O)C1=CC(OC(CC)CC)C(NC(C)=O)C(N)C1", "mw": 312.41, "category": "Antiviral (Flu)"},
    {"id": "remdesivir", "name": "Remdesivir", "smiles": "CCC(CC)COC(=O)C(C)NP(=O)(OCC1C(C(C(O1)N2C=CC(=O)NC2=O)O)O)OC3=CC=CC=C3", "mw": 602.58, "category": "Antiviral"},
    {"id": "sitagliptin", "name": "Sitagliptin", "smiles": "NC(CC(=O)N1CCN2C(C1)=NN=C2C(F)(F)F)CC1=C(F)C=C(F)C(F)=C1F", "mw": 407.31, "category": "Antidiabetic (DPP-4)"},
    {"id": "vemurafenib", "name": "Vemurafenib", "smiles": "CCCS(=O)(=O)NC1=CC=C(C=C1)C2=NC(=C(S2)C3=CC(=NC=C3)NC4=CC=C(C=C4)Cl)C#N", "mw": 489.93, "category": "Kinase Inhibitor (Melanoma)"},
    {"id": "erlotinib", "name": "Erlotinib", "smiles": "COCCOC1=C(C=C2C(=C1)C(=NC=N2)NC3=CC(=C(C=C3)F)Cl)OCCOC", "mw": 393.44, "category": "EGFR Inhibitor"},
]

# Pre-computed docking results (simulated but realistic)
PRECOMPUTED_RESULTS = {
    "melanoma": {
        "vemurafenib": -9.8,
        "erlotinib": -7.2,
        "caffeine": -4.1,
        "aspirin": -5.3,
        "ibuprofen": -5.8,
    },
    "diabetes": {
        "sitagliptin": -10.2,
        "metformin": -6.8,
        "caffeine": -4.5,
        "aspirin": -4.9,
        "ibuprofen": -5.1,
    },
    "covid": {
        "nirmatrelvir": -8.9,
        "remdesivir": -7.6,
        "caffeine": -5.2,
        "aspirin": -4.8,
        "oseltamivir": -6.4,
    },
    "hiv": {
        "remdesivir": -7.8,
        "oseltamivir": -6.2,
        "caffeine": -4.3,
        "aspirin": -4.5,
        "atorvastatin": -6.9,
    },
    "lung": {
        "erlotinib": -9.4,
        "vemurafenib": -7.1,
        "caffeine": -4.0,
        "aspirin": -4.7,
        "atorvastatin": -6.5,
    },
    "breast": {
        "atorvastatin": -7.3,
        "erlotinib": -6.8,
        "caffeine": -4.2,
        "aspirin": -4.4,
        "metformin": -5.1,
    },
}

# =============================================================================
# Helper Functions
# =============================================================================

def fetch_pdb_structure(pdb_id: str) -> Optional[str]:
    """Fetch PDB structure from RCSB."""
    try:
        # Try BioPrime API first
        response = requests.get(f"{BIOPRIME_API}/docking/demo/pdb/{pdb_id}", timeout=10)
        if response.status_code == 200:
            data = response.json()
            return data.get("pdb_content", data.get("pdb_data", None))
    except:
        pass

    # Fallback to RCSB
    try:
        response = requests.get(f"{RCSB_PDB_URL}/{pdb_id}.pdb", timeout=10)
        if response.status_code == 200:
            return response.text
    except:
        pass

    return None


def create_3d_viewer(pdb_content: str, binding_site: dict = None, style: str = "cartoon") -> str:
    """Create 3D molecular viewer HTML using iframe with srcdoc for JS execution."""
    import html
    import base64

    # Escape PDB content for JavaScript (double escape for iframe)
    pdb_escaped = pdb_content.replace('\\', '\\\\').replace('\n', '\\n').replace('\r', '').replace("'", "\\'").replace('"', '\\"')

    # Build style configuration
    if style == "cartoon":
        style_js = "viewer.setStyle({}, {cartoon: {color: 'spectrum'}});"
    elif style == "surface":
        style_js = "viewer.setStyle({}, {cartoon: {color: 'spectrum'}}); viewer.addSurface($3Dmol.SAS, {opacity: 0.7, color: 'white'});"
    elif style == "stick":
        style_js = "viewer.setStyle({}, {stick: {colorscheme: 'Jmol'}});"
    elif style == "sphere":
        style_js = "viewer.setStyle({}, {sphere: {colorscheme: 'Jmol', scale: 0.3}});"
    else:
        style_js = "viewer.setStyle({}, {cartoon: {color: 'spectrum'}});"

    # Binding site sphere
    binding_site_js = ""
    if binding_site:
        binding_site_js = f"viewer.addSphere({{center: {{x: {binding_site['x']}, y: {binding_site['y']}, z: {binding_site['z']}}}, radius: 8, color: 'red', opacity: 0.3}});"

    # Create complete HTML document for iframe
    iframe_html = f'''<!DOCTYPE html>

<html>

<head>

    <script src="https://3dmol.org/build/3Dmol-min.js"></script>

    <style>

        body {{ margin: 0; padding: 0; overflow: hidden; background: #1a1a2e; }}

        #viewer {{ width: 100%; height: 100%; }}

    </style>

</head>

<body>

    <div id="viewer"></div>

    <script>

        document.addEventListener('DOMContentLoaded', function() {{

            var pdbData = "{pdb_escaped}";

            var element = document.getElementById('viewer');

            var config = {{ backgroundColor: '0x1a1a2e' }};

            var viewer = $3Dmol.createViewer(element, config);

            viewer.addModel(pdbData, "pdb");

            {style_js}

            {binding_site_js}

            viewer.zoomTo();

            viewer.render();

        }});

    </script>

</body>

</html>'''

    # Escape for srcdoc attribute
    iframe_srcdoc = html.escape(iframe_html)

    html_content = f'''

    <div style="width: 100%; display: flex; justify-content: center;">

        <iframe srcdoc="{iframe_srcdoc}"

                style="width: 700px; height: 500px; border: none; border-radius: 12px; background: #1a1a2e;"

                sandbox="allow-scripts allow-same-origin">

        </iframe>

    </div>

    '''

    return html_content


def generate_docking_result(target_id: str, compound_ids: List[str]) -> Tuple[str, str, str]:
    """

    Simulate docking and return results.

    Returns: (results_text, binding_chart_data, receipt)

    """
    target = next((t for t in DEMO_TARGETS if t["id"] == target_id), None)
    if not target:
        return "Target not found", "", ""

    results = []
    precomputed = PRECOMPUTED_RESULTS.get(target_id, {})

    for comp_id in compound_ids:
        compound = next((c for c in COMPOUND_LIBRARY if c["id"] == comp_id), None)
        if not compound:
            continue

        # Use precomputed or generate realistic random
        if comp_id in precomputed:
            energy = precomputed[comp_id]
        else:
            # Generate realistic binding energy based on molecular weight
            base_energy = -4.0 - (compound["mw"] / 100)
            energy = round(base_energy + random.uniform(-1.5, 1.5), 2)

        results.append({
            "compound": compound["name"],
            "smiles": compound["smiles"],
            "energy": energy,
            "mw": compound["mw"],
            "category": compound["category"]
        })

    # Sort by binding energy (more negative = better)
    results.sort(key=lambda x: x["energy"])

    # Generate results text
    results_text = f"""

## Docking Results for {target['name']}



**Target Disease:** {target['disease']}

**Sponsor:** {target['sponsor']}

**PDB ID:** {target['pdb']}



---



### Top Binding Compounds



| Rank | Compound | Binding Energy | Category |

|------|----------|----------------|----------|

"""

    for i, r in enumerate(results[:10], 1):
        emoji = "๐Ÿ†" if i == 1 else "๐Ÿฅˆ" if i == 2 else "๐Ÿฅ‰" if i == 3 else "  "
        results_text += f"| {emoji} {i} | **{r['compound']}** | {r['energy']:.2f} kcal/mol | {r['category']} |\n"

    results_text += f"""

---



### Interpretation



- **Best Hit:** {results[0]['compound']} with {results[0]['energy']:.2f} kcal/mol

- **Binding energies < -7 kcal/mol** indicate strong binding potential

- **Binding energies < -9 kcal/mol** suggest drug-like affinity



---



*Powered by Origin Neural AI Docking Engine*

*Results simulated for demonstration - actual BioPrime uses GPU-accelerated physics*

"""

    # Generate chart data
    chart_labels = [r["compound"][:12] for r in results[:8]]
    chart_values = [abs(r["energy"]) for r in results[:8]]

    chart_html = f"""

<div style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); padding: 20px; border-radius: 12px; margin-top: 10px;">

    <h3 style="color: #4ECDC4; margin-bottom: 15px; text-align: center;">Binding Affinity Comparison</h3>

    <div style="display: flex; align-items: flex-end; justify-content: space-around; height: 200px; padding: 10px;">

"""

    max_val = max(chart_values) if chart_values else 1
    colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F"]

    for i, (label, val) in enumerate(zip(chart_labels, chart_values)):
        height = int((val / max_val) * 150)
        color = colors[i % len(colors)]
        chart_html += f"""

        <div style="display: flex; flex-direction: column; align-items: center; width: 60px;">

            <span style="color: white; font-size: 11px; margin-bottom: 5px;">-{val:.1f}</span>

            <div style="width: 40px; height: {height}px; background: {color}; border-radius: 4px 4px 0 0;"></div>

            <span style="color: #888; font-size: 9px; margin-top: 5px; text-align: center; word-wrap: break-word; width: 55px;">{label}</span>

        </div>

"""

    chart_html += """

    </div>

    <p style="color: #666; font-size: 11px; text-align: center; margin-top: 10px;">Binding Energy (kcal/mol) - Higher bars = stronger binding</p>

</div>

"""

    # Add social sharing buttons
    share_text = f"I just screened compounds against {target['name']} using BioPrime! Best hit: {results[0]['compound']} at {results[0]['energy']:.2f} kcal/mol. Try AI-powered drug discovery:"
    share_url = "https://bioprime.one"

    import urllib.parse
    encoded_text = urllib.parse.quote(share_text)
    encoded_url = urllib.parse.quote(share_url)

    chart_html += f"""

<div style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); padding: 15px; border-radius: 12px; margin-top: 10px;">

    <p style="color: #4ECDC4; font-size: 13px; text-align: center; margin-bottom: 12px; font-weight: 600;">Share Your Discovery</p>

    <div style="display: flex; justify-content: center; gap: 12px; flex-wrap: wrap;">

        <a href="https://twitter.com/intent/tweet?text={encoded_text}&url={encoded_url}" target="_blank"

           style="display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; background: #1DA1F2; color: white; text-decoration: none; border-radius: 6px; font-size: 13px; font-weight: 500;">

            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>

            Post on X

        </a>

        <a href="https://www.linkedin.com/sharing/share-offsite/?url={encoded_url}" target="_blank"

           style="display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; background: #0A66C2; color: white; text-decoration: none; border-radius: 6px; font-size: 13px; font-weight: 500;">

            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>

            LinkedIn

        </a>

        <a href="https://www.facebook.com/sharer/sharer.php?u={encoded_url}" target="_blank"

           style="display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; background: #1877F2; color: white; text-decoration: none; border-radius: 6px; font-size: 13px; font-weight: 500;">

            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>

            Facebook

        </a>

    </div>

    <p style="color: #666; font-size: 11px; text-align: center; margin-top: 12px;">

        Want real blockchain-verified results? <a href="https://bioprime.one" target="_blank" style="color: #4ECDC4;">Sign up at bioprime.one</a>

    </p>

</div>

"""

    # Generate blockchain receipt
    job_id = f"DEMO-{target_id.upper()}-{hashlib.md5(str(compound_ids).encode()).hexdigest()[:8]}"
    data_hash = hashlib.sha256(json.dumps(results, sort_keys=True).encode()).hexdigest()

    receipt = generate_demo_receipt(
        job_id=job_id,
        target_name=target['name'],
        compounds_screened=len(compound_ids),
        top_hits=len(results),
        best_energy=results[0]['energy'] if results else 0,
        data_hash=data_hash
    )

    return results_text, chart_html, receipt


def generate_demo_receipt(job_id: str, target_name: str, compounds_screened: int,

                          top_hits: int, best_energy: float, data_hash: str) -> str:
    """Generate a demo blockchain receipt."""
    timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
    demo_txid = f"demo_{hashlib.md5(data_hash.encode()).hexdigest()[:48]}"

    receipt = f"""

โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—

โ•‘                    BIOPRIME DISCOVERY CERTIFICATE                        โ•‘

โ•‘                         [DEMO - NOT ON CHAIN]                            โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                                                                          โ•‘

โ•‘  JOB ID:      {job_id:<57} โ•‘

โ•‘  TARGET:      {target_name[:47]:<57} โ•‘

โ•‘                                                                          โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                          SCREENING RESULTS                               โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                                                                          โ•‘

โ•‘  Compounds Screened:     {compounds_screened:<45} โ•‘

โ•‘  Top Poses Generated:    {top_hits:<45} โ•‘

โ•‘  Best Binding Energy:    {best_energy:.2f} kcal/mol{' ':<36} โ•‘

โ•‘                                                                          โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                        VERIFICATION DETAILS                              โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                                                                          โ•‘

โ•‘  Timestamp:      {timestamp:<53} โ•‘

โ•‘  Data Hash:      sha256:{data_hash[:49]:<46} โ•‘

โ•‘                                                                          โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                       BLOCKCHAIN VERIFICATION                            โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                                                                          โ•‘

โ•‘  Network:        BSV (Bitcoin SV) - Demo Mode                            โ•‘

โ•‘  Status:         Demo certificate - not anchored to blockchain           โ•‘

โ•‘                                                                          โ•‘

โ•‘  For real blockchain-verified results, visit:                            โ•‘

โ•‘  https://bioprime.one                                                    โ•‘

โ•‘                                                                          โ•‘

โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ

โ•‘                                                                          โ•‘

โ•‘  BioPrime anchors real docking results to the BSV blockchain for         โ•‘

โ•‘  immutable proof of discovery. Sign up to run verified experiments.      โ•‘

โ•‘                                                                          โ•‘

โ•‘                         โ”โ”โ” bioprime.one โ”โ”โ”                              โ•‘

โ•‘                                                                          โ•‘

โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

"""
    return receipt.strip()


# =============================================================================
# Gradio Interface
# =============================================================================

def view_protein(target_name: str, view_style: str) -> Tuple[str, str]:
    """View selected protein structure."""
    target = next((t for t in DEMO_TARGETS if t["name"] == target_name), None)
    if not target:
        return "<p>Please select a target</p>", ""

    pdb_content = fetch_pdb_structure(target["pdb"])
    if not pdb_content:
        return f"<p style='color: red;'>Failed to fetch PDB structure for {target['pdb']}</p>", ""

    viewer_html = create_3d_viewer(pdb_content, target.get("binding_site"), view_style.lower())

    info_html = f"""

<div style="background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%); padding: 20px; border-radius: 12px; color: white;">

    <h3 style="color: {target['color']}; margin-bottom: 10px;">{target['name']}</h3>

    <p><strong>PDB ID:</strong> <a href="https://www.rcsb.org/structure/{target['pdb']}" target="_blank" style="color: #4ECDC4;">{target['pdb']}</a></p>

    <p><strong>Disease:</strong> {target['disease']}</p>

    <p><strong>Sponsor:</strong> {target['sponsor']}</p>

    <p style="margin-top: 10px; color: #aaa;">{target['description']}</p>

    <div style="margin-top: 15px; padding: 10px; background: rgba(78, 205, 196, 0.1); border-radius: 8px; border-left: 3px solid #4ECDC4;">

        <p style="font-size: 12px; color: #4ECDC4; margin: 0;">

            ๐Ÿ’ก The red sphere indicates the active binding site where drug candidates interact with the protein.

        </p>

    </div>

</div>

"""

    return viewer_html, info_html


def run_docking(target_name: str, compounds: List[str]) -> Tuple[str, str, str]:
    """Run docking simulation."""
    if not target_name:
        return "Please select a target protein", "", ""
    if not compounds:
        return "Please select at least one compound", "", ""

    target = next((t for t in DEMO_TARGETS if t["name"] == target_name), None)
    if not target:
        return "Invalid target", "", ""

    # Get compound IDs from names
    compound_ids = []
    for comp_name in compounds:
        comp = next((c for c in COMPOUND_LIBRARY if c["name"] == comp_name), None)
        if comp:
            compound_ids.append(comp["id"])

    # Simulate docking (small delay for effect)
    time.sleep(1.5)

    results_text, chart_html, receipt = generate_docking_result(target["id"], compound_ids)

    return results_text, chart_html, receipt


# Create the Gradio interface
with gr.Blocks(
    title="BioPrime Molecular Docking Demo",
    theme=gr.themes.Base(
        primary_hue="teal",
        secondary_hue="purple",
        neutral_hue="slate",
        font=gr.themes.GoogleFont("Inter")
    ),
    css="""

    .gradio-container {

        max-width: 1400px !important;

        background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%) !important;

    }

    .gr-button-primary {

        background: linear-gradient(135deg, #4ECDC4 0%, #44A08D 100%) !important;

    }

    .header-text {

        text-align: center;

        color: white;

    }

    footer {display: none !important;}

    """
) as demo:

    # Header
    gr.HTML("""

    <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px; margin-bottom: 20px;">

        <h1 style="color: white; margin: 0; font-size: 2.5em;">๐Ÿงฌ BioPrime</h1>

        <p style="color: rgba(255,255,255,0.9); margin: 10px 0 0 0; font-size: 1.2em;">

            AI-Powered Molecular Docking for Drug Discovery

        </p>

        <p style="color: rgba(255,255,255,0.7); margin: 5px 0 0 0;">

            10,000x Faster โ€ข $5 per Million Compounds โ€ข Blockchain-Verified Results

        </p>

    </div>

    """)

    with gr.Tabs():
        # Tab 1: Interactive Docking Demo
        with gr.TabItem("๐Ÿ”ฌ Try Docking", id="docking"):
            gr.Markdown("""

            ### Dock Drug Candidates Against Disease Targets

            Select a protein target and compounds to simulate molecular docking. See binding energies and get a blockchain-ready certificate.

            """)

            with gr.Row():
                with gr.Column(scale=1):
                    target_dropdown = gr.Dropdown(
                        choices=[t["name"] for t in DEMO_TARGETS],
                        label="๐ŸŽฏ Select Disease Target",
                        info="Choose from sponsored research targets"
                    )

                    compound_select = gr.CheckboxGroup(
                        choices=[c["name"] for c in COMPOUND_LIBRARY],
                        label="๐Ÿ’Š Select Compounds to Test",
                        info="Choose multiple compounds for screening"
                    )

                    dock_btn = gr.Button("๐Ÿš€ Run Docking Simulation", variant="primary", size="lg")

                    gr.HTML("""

                    <div style="margin-top: 15px; padding: 15px; background: rgba(78, 205, 196, 0.1); border-radius: 8px; border: 1px solid rgba(78, 205, 196, 0.3);">

                        <h4 style="color: #4ECDC4; margin: 0 0 10px 0;">๐Ÿ’ก Quick Start</h4>

                        <ol style="color: #aaa; margin: 0; padding-left: 20px; font-size: 13px;">

                            <li>Select <strong>BRAF V600E - Melanoma</strong></li>

                            <li>Check <strong>Vemurafenib</strong> (the actual drug!)</li>

                            <li>Add a few other compounds to compare</li>

                            <li>Click Run Docking</li>

                        </ol>

                    </div>

                    """)

                with gr.Column(scale=2):
                    results_md = gr.Markdown("*Results will appear here after docking...*")
                    chart_html = gr.HTML()

            with gr.Accordion("๐Ÿ“œ Blockchain Certificate (Demo)", open=False):
                receipt_text = gr.Code(label="Discovery Certificate", language=None, lines=30)

            dock_btn.click(
                fn=run_docking,
                inputs=[target_dropdown, compound_select],
                outputs=[results_md, chart_html, receipt_text]
            )

        # Tab 2: 3D Protein Viewer
        with gr.TabItem("๐Ÿ”ฎ 3D Protein Viewer", id="viewer"):
            gr.Markdown("""

            ### Explore Protein Structures in 3D

            Visualize the molecular targets for drug discovery. The red sphere indicates the binding site.

            """)

            with gr.Row():
                with gr.Column(scale=1):
                    viewer_target = gr.Dropdown(
                        choices=[t["name"] for t in DEMO_TARGETS],
                        label="๐ŸŽฏ Select Protein",
                        value=DEMO_TARGETS[0]["name"]
                    )

                    view_style = gr.Radio(
                        choices=["Cartoon", "Surface", "Stick", "Sphere"],
                        value="Cartoon",
                        label="๐ŸŽจ Visualization Style"
                    )

                    view_btn = gr.Button("๐Ÿ‘๏ธ View Structure", variant="primary")

                    target_info = gr.HTML()

                with gr.Column(scale=2):
                    viewer_output = gr.HTML(
                        value="<div style='height: 500px; display: flex; align-items: center; justify-content: center; color: #666; background: #1a1a2e; border-radius: 12px;'><p>Select a protein and click 'View Structure'</p></div>"
                    )

            view_btn.click(
                fn=view_protein,
                inputs=[viewer_target, view_style],
                outputs=[viewer_output, target_info]
            )

        # Tab 3: About BioPrime
        with gr.TabItem("โ„น๏ธ About", id="about"):
            gr.Markdown("""

            ## About BioPrime Network



            BioPrime is a **decentralized molecular docking platform** that makes drug discovery accessible to everyone.



            ### Key Features



            | Feature | Traditional | BioPrime |

            |---------|-------------|----------|

            | Speed | Days-Weeks | Minutes |

            | Cost | $10,000+ | $5/million |

            | Verification | Manual | Blockchain |

            | Access | Limited | Open |



            ### How It Works



            1. **Submit** - Upload your protein target or select from our library

            2. **Screen** - Our Origin Neural AI engine docks millions of compounds

            3. **Discover** - Get ranked binding poses with energy scores

            4. **Verify** - Results anchored to BSV blockchain for immutable proof



            ### Sponsored Research Campaigns



            BioPrime features sponsored research targets where community members can contribute to drug discovery:



            - **Bryan Daugherty** - Melanoma (BRAF V600E), Type 2 Diabetes (DPP-4)

            - **Smartledger** - Breast Cancer (CDK4/6)

            - **Origin Neural AI** - HIV-1 Protease

            - **Greg Ward** - Tuberculosis, Dengue Fever

            - **Shawn Ryan** - Alzheimer's, Parkinson's



            ### Technology Stack



            - **Docking Engine**: Origin Neural AI (GPU-accelerated)

            - **Blockchain**: BSV (Bitcoin SV) for immutable verification

            - **Backend**: FastAPI, Python

            - **Frontend**: React, TypeScript



            ---



            ### Get Started



            **๐ŸŒ Visit [bioprime.one](https://bioprime.one) to run real docking experiments!**



            - Sign up for free (10 free credits)

            - Screen up to 1 million compounds per job

            - Get blockchain-verified discovery certificates

            - Participate in sponsored research campaigns



            ---



            <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px;">

                <p style="color: white; font-size: 1.2em; margin: 0;">

                    <strong>Ready to discover the next breakthrough drug?</strong>

                </p>

                <p style="color: rgba(255,255,255,0.8); margin: 10px 0 0 0;">

                    <a href="https://bioprime.one" target="_blank" style="color: #4ECDC4; text-decoration: none; font-size: 1.3em;">

                        ๐Ÿš€ Launch BioPrime โ†’

                    </a>

                </p>

            </div>

            """)

    # Footer
    gr.HTML("""

    <div style="text-align: center; padding: 20px; margin-top: 20px; border-top: 1px solid rgba(255,255,255,0.1);">

        <p style="color: #666; margin: 0;">

            <a href="https://bioprime.one" target="_blank" style="color: #4ECDC4;">bioprime.one</a>

        </p>

        <p style="color: #444; margin: 5px 0 0 0; font-size: 12px;">

            Powered by Origin Neural AI โ€ข Blockchain verification on BSV

        </p>

    </div>

    """)


if __name__ == "__main__":
    demo.launch()