"""
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'''
'''
# Escape for srcdoc attribute
iframe_srcdoc = html.escape(iframe_html)
html_content = f'''
'''
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"""
Binding Affinity Comparison
"""
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"""
"""
chart_html += """
Binding Energy (kcal/mol) - Higher bars = stronger binding
"""
# 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"""
"""
# 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 "Please select a target
", ""
pdb_content = fetch_pdb_structure(target["pdb"])
if not pdb_content:
return f"Failed to fetch PDB structure for {target['pdb']}
", ""
viewer_html = create_3d_viewer(pdb_content, target.get("binding_site"), view_style.lower())
info_html = f"""
{target['name']}
PDB ID: {target['pdb']}
Disease: {target['disease']}
Sponsor: {target['sponsor']}
{target['description']}
đĄ The red sphere indicates the active binding site where drug candidates interact with the protein.
"""
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("""
đ§Ŧ BioPrime
AI-Powered Molecular Docking for Drug Discovery
10,000x Faster âĸ $5 per Million Compounds âĸ Blockchain-Verified Results
""")
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("""
đĄ Quick Start
- Select BRAF V600E - Melanoma
- Check Vemurafenib (the actual drug!)
- Add a few other compounds to compare
- Click Run Docking
""")
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="Select a protein and click 'View Structure'
"
)
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
---
""")
# Footer
gr.HTML("""
bioprime.one
Powered by Origin Neural AI âĸ Blockchain verification on BSV
""")
if __name__ == "__main__":
demo.launch()