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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

GUI Interface for Docking@HOME



A modern web-based GUI using FastAPI and HTML/JavaScript for molecular docking.

Integrates with AutoDock backend for real molecular docking simulations.



Authors: OpenPeer AI, Riemann Computing Inc., Bleunomics, Andrew Magdy Kamal

"""

import os
import json
import asyncio
from pathlib import Path
from typing import Optional, List, Dict
from datetime import datetime

from fastapi import FastAPI, File, UploadFile, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import uvicorn

# Import the docking server components
from .server import job_manager, initialize_server

# Initialize FastAPI app
app = FastAPI(
    title="Docking@HOME",
    description="Distributed Molecular Docking Platform",
    version="1.0.0"
)

# Data models
class DockingJobRequest(BaseModel):
    num_runs: int = 100
    use_gpu: bool = True
    job_name: Optional[str] = None

class JobStatus(BaseModel):
    job_id: str
    status: str
    progress: float
    message: str

# Active WebSocket connections
active_websockets: List[WebSocket] = []

# File upload directory
UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(exist_ok=True)

RESULTS_DIR = Path("results")
RESULTS_DIR.mkdir(exist_ok=True)


@app.get("/", response_class=HTMLResponse)
async def root():
    """Serve the main GUI page"""
    html_content = """

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Docking@HOME - Molecular Docking Platform</title>

    <style>

        * {

            margin: 0;

            padding: 0;

            box-sizing: border-box;

        }

        

        body {

            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            min-height: 100vh;

            padding: 20px;

        }

        

        .container {

            max-width: 1200px;

            margin: 0 auto;

        }

        

        .header {

            background: white;

            padding: 30px;

            border-radius: 15px;

            box-shadow: 0 10px 40px rgba(0,0,0,0.1);

            margin-bottom: 30px;

            text-align: center;

        }

        

        .header h1 {

            color: #667eea;

            font-size: 2.5em;

            margin-bottom: 10px;

        }

        

        .header p {

            color: #666;

            font-size: 1.1em;

        }

        

        .authors {

            color: #888;

            font-size: 0.9em;

            margin-top: 10px;

        }

        

        .main-content {

            display: grid;

            grid-template-columns: 1fr 1fr;

            gap: 20px;

        }

        

        .card {

            background: white;

            padding: 25px;

            border-radius: 15px;

            box-shadow: 0 10px 40px rgba(0,0,0,0.1);

        }

        

        .card h2 {

            color: #667eea;

            margin-bottom: 20px;

            font-size: 1.5em;

        }

        

        .form-group {

            margin-bottom: 20px;

        }

        

        label {

            display: block;

            margin-bottom: 8px;

            color: #333;

            font-weight: 600;

        }

        

        input[type="file"],

        input[type="number"],

        select {

            width: 100%;

            padding: 12px;

            border: 2px solid #e0e0e0;

            border-radius: 8px;

            font-size: 1em;

            transition: border-color 0.3s;

        }

        

        input:focus, select:focus {

            outline: none;

            border-color: #667eea;

        }

        

        .checkbox-group {

            display: flex;

            align-items: center;

            gap: 10px;

        }

        

        input[type="checkbox"] {

            width: 20px;

            height: 20px;

            cursor: pointer;

        }

        

        .btn {

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            color: white;

            padding: 15px 30px;

            border: none;

            border-radius: 8px;

            font-size: 1.1em;

            font-weight: 600;

            cursor: pointer;

            width: 100%;

            transition: transform 0.2s, box-shadow 0.2s;

        }

        

        .btn:hover {

            transform: translateY(-2px);

            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);

        }

        

        .btn:disabled {

            opacity: 0.5;

            cursor: not-allowed;

        }

        

        .job-list {

            max-height: 400px;

            overflow-y: auto;

        }

        

        .job-item {

            background: #f8f9fa;

            padding: 15px;

            border-radius: 8px;

            margin-bottom: 15px;

            border-left: 4px solid #667eea;

        }

        

        .job-header {

            display: flex;

            justify-content: space-between;

            align-items: center;

            margin-bottom: 10px;

        }

        

        .job-id {

            font-weight: 600;

            color: #333;

        }

        

        .status-badge {

            padding: 5px 15px;

            border-radius: 20px;

            font-size: 0.85em;

            font-weight: 600;

        }

        

        .status-pending {

            background: #ffeaa7;

            color: #d63031;

        }

        

        .status-running {

            background: #74b9ff;

            color: #0984e3;

        }

        

        .status-completed {

            background: #55efc4;

            color: #00b894;

        }

        

        .progress-bar {

            width: 100%;

            height: 8px;

            background: #e0e0e0;

            border-radius: 4px;

            overflow: hidden;

            margin-top: 10px;

        }

        

        .progress-fill {

            height: 100%;

            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);

            transition: width 0.3s ease;

        }

        

        .stats {

            display: grid;

            grid-template-columns: repeat(3, 1fr);

            gap: 15px;

            margin-top: 20px;

        }

        

        .stat-card {

            background: #f8f9fa;

            padding: 15px;

            border-radius: 8px;

            text-align: center;

        }

        

        .stat-value {

            font-size: 2em;

            font-weight: 700;

            color: #667eea;

        }

        

        .stat-label {

            color: #666;

            font-size: 0.9em;

            margin-top: 5px;

        }

        

        .notification {

            position: fixed;

            top: 20px;

            right: 20px;

            background: white;

            padding: 20px;

            border-radius: 8px;

            box-shadow: 0 5px 20px rgba(0,0,0,0.2);

            display: none;

            min-width: 300px;

            animation: slideIn 0.3s ease;

        }

        

        @keyframes slideIn {

            from {

                transform: translateX(400px);

                opacity: 0;

            }

            to {

                transform: translateX(0);

                opacity: 1;

            }

        }

        

        .notification.success {

            border-left: 4px solid #00b894;

        }

        

        .notification.error {

            border-left: 4px solid #d63031;

        }

        

        .footer {

            text-align: center;

            color: white;

            margin-top: 30px;

            padding: 20px;

        }

        

        .full-width {

            grid-column: 1 / -1;

        }

    </style>

</head>

<body>

    <div class="container">

        <div class="header">

            <h1>🧬 Docking@HOME</h1>

            <p>Distributed Molecular Docking Platform</p>

            <div class="authors">

                OpenPeer AI · Riemann Computing Inc. · Bleunomics · Andrew Magdy Kamal

            </div>

        </div>

        

        <div class="main-content">

            <div class="card">

                <h2>📤 Submit Docking Job</h2>

                <form id="dockingForm">

                    <div class="form-group">

                        <label>Ligand File (PDBQT)</label>

                        <input type="file" id="ligandFile" accept=".pdbqt,.pdb" required>

                    </div>

                    

                    <div class="form-group">

                        <label>Receptor File (PDBQT)</label>

                        <input type="file" id="receptorFile" accept=".pdbqt,.pdb" required>

                    </div>

                    

                    <div class="form-group">

                        <label>Number of Runs</label>

                        <input type="number" id="numRuns" value="100" min="1" max="1000" required>

                    </div>

                    

                    <div class="form-group checkbox-group">

                        <input type="checkbox" id="useGPU" checked>

                        <label for="useGPU">Use GPU Acceleration</label>

                    </div>

                    

                    <button type="submit" class="btn" id="submitBtn">

                        🚀 Start Docking

                    </button>

                </form>

            </div>

            

            <div class="card">

                <h2>📊 Active Jobs</h2>

                <div class="job-list" id="jobList">

                    <p style="text-align: center; color: #999; padding: 20px;">

                        No jobs yet. Submit a docking job to get started!

                    </p>

                </div>

            </div>

            

            <div class="card full-width">

                <h2>📈 System Statistics</h2>

                <div class="stats">

                    <div class="stat-card">

                        <div class="stat-value" id="totalJobs">0</div>

                        <div class="stat-label">Total Jobs</div>

                    </div>

                    <div class="stat-card">

                        <div class="stat-value" id="completedJobs">0</div>

                        <div class="stat-label">Completed</div>

                    </div>

                    <div class="stat-card">

                        <div class="stat-value" id="avgTime">0s</div>

                        <div class="stat-label">Avg. Time</div>

                    </div>

                </div>

            </div>

        </div>

        

        <div class="footer">

            <p>Support: andrew@bleunomics.com | Issues: <a href="https://huggingface.co/OpenPeerAI/DockingAtHOME/discussions" style="color: white;">HuggingFace</a></p>

        </div>

    </div>

    

    <div class="notification" id="notification">

        <div id="notificationMessage"></div>

    </div>

    

    <script>

        const API_BASE = window.location.origin;

        

        // WebSocket connection for real-time updates

        let ws = null;

        

        function connectWebSocket() {

            ws = new WebSocket(`ws://${window.location.host}/ws`);

            

            ws.onmessage = (event) => {

                const data = JSON.parse(event.data);

                updateJobList();

                updateStats();

            };

            

            ws.onerror = () => {

                setTimeout(connectWebSocket, 5000);

            };

        }

        

        // Submit docking job

        document.getElementById('dockingForm').addEventListener('submit', async (e) => {

            e.preventDefault();

            

            const ligandFile = document.getElementById('ligandFile').files[0];

            const receptorFile = document.getElementById('receptorFile').files[0];

            const numRuns = document.getElementById('numRuns').value;

            const useGPU = document.getElementById('useGPU').checked;

            

            if (!ligandFile || !receptorFile) {

                showNotification('Please select both ligand and receptor files', 'error');

                return;

            }

            

            const submitBtn = document.getElementById('submitBtn');

            submitBtn.disabled = true;

            submitBtn.textContent = '⏳ Uploading...';

            

            try {

                // Upload ligand

                const ligandFormData = new FormData();

                ligandFormData.append('file', ligandFile);

                const ligandResponse = await fetch(`${API_BASE}/upload`, {

                    method: 'POST',

                    body: ligandFormData

                });

                const ligandData = await ligandResponse.json();

                

                // Upload receptor

                const receptorFormData = new FormData();

                receptorFormData.append('file', receptorFile);

                const receptorResponse = await fetch(`${API_BASE}/upload`, {

                    method: 'POST',

                    body: receptorFormData

                });

                const receptorData = await receptorResponse.json();

                

                // Submit job

                const jobResponse = await fetch(`${API_BASE}/api/jobs`, {

                    method: 'POST',

                    headers: {

                        'Content-Type': 'application/json'

                    },

                    body: JSON.stringify({

                        ligand_file: ligandData.filename,

                        receptor_file: receptorData.filename,

                        num_runs: parseInt(numRuns),

                        use_gpu: useGPU

                    })

                });

                

                const jobData = await jobResponse.json();

                

                showNotification(`Job submitted successfully! ID: ${jobData.job_id}`, 'success');

                

                // Reset form

                document.getElementById('dockingForm').reset();

                

                // Update job list

                updateJobList();

                updateStats();

                

            } catch (error) {

                showNotification('Error submitting job: ' + error.message, 'error');

            } finally {

                submitBtn.disabled = false;

                submitBtn.textContent = '🚀 Start Docking';

            }

        });

        

        // Update job list

        async function updateJobList() {

            try {

                const response = await fetch(`${API_BASE}/api/jobs`);

                const jobs = await response.json();

                

                const jobList = document.getElementById('jobList');

                

                if (jobs.length === 0) {

                    jobList.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">No jobs yet. Submit a docking job to get started!</p>';

                    return;

                }

                

                jobList.innerHTML = jobs.map(job => `

                    <div class="job-item">

                        <div class="job-header">

                            <span class="job-id">${job.job_id}</span>

                            <span class="status-badge status-${job.status}">${job.status.toUpperCase()}</span>

                        </div>

                        <div style="font-size: 0.9em; color: #666;">

                            <div>Ligand: ${job.ligand_file}</div>

                            <div>Receptor: ${job.receptor_file}</div>

                            <div>Runs: ${job.num_runs} | GPU: ${job.use_gpu ? 'Yes' : 'No'}</div>

                        </div>

                        <div class="progress-bar">

                            <div class="progress-fill" style="width: ${job.progress * 100}%"></div>

                        </div>

                        <div style="margin-top: 5px; font-size: 0.85em; color: #666;">

                            Progress: ${(job.progress * 100).toFixed(1)}%

                        </div>

                    </div>

                `).join('');

                

            } catch (error) {

                console.error('Error updating job list:', error);

            }

        }

        

        // Update statistics

        async function updateStats() {

            try {

                const response = await fetch(`${API_BASE}/api/stats`);

                const stats = await response.json();

                

                document.getElementById('totalJobs').textContent = stats.total_jobs;

                document.getElementById('completedJobs').textContent = stats.completed_jobs;

                document.getElementById('avgTime').textContent = stats.avg_time + 's';

                

            } catch (error) {

                console.error('Error updating stats:', error);

            }

        }

        

        // Show notification

        function showNotification(message, type) {

            const notification = document.getElementById('notification');

            const messageElement = document.getElementById('notificationMessage');

            

            messageElement.textContent = message;

            notification.className = `notification ${type}`;

            notification.style.display = 'block';

            

            setTimeout(() => {

                notification.style.display = 'none';

            }, 5000);

        }

        

        // Initialize

        connectWebSocket();

        updateJobList();

        updateStats();

        

        // Refresh job list every 2 seconds

        setInterval(() => {

            updateJobList();

            updateStats();

        }, 2000);

    </script>

</body>

</html>

    """
    return HTMLResponse(content=html_content)


@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    """Upload ligand or receptor file"""
    try:
        file_path = UPLOAD_DIR / file.filename
        
        with open(file_path, "wb") as f:
            content = await file.read()
            f.write(content)
        
        return {"filename": file.filename, "path": str(file_path)}
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/jobs")
async def create_job(

    ligand_file: str,

    receptor_file: str,

    num_runs: int = 100,

    use_gpu: bool = True,

    job_name: Optional[str] = None

):
    """Create a new docking job with real AutoDock integration"""
    try:
        # Submit job to the docking server
        job_id = await job_manager.submit_job(
            ligand_file=ligand_file,
            receptor_file=receptor_file,
            num_runs=num_runs,
            use_gpu=use_gpu,
            job_name=job_name
        )
        
        # Start broadcasting updates
        asyncio.create_task(broadcast_job_updates(job_id))
        
        return job_manager.get_job(job_id)
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/jobs")
async def get_jobs():
    """Get all jobs"""
    return job_manager.get_all_jobs()


@app.get("/api/jobs/{job_id}")
async def get_job(job_id: str):
    """Get specific job"""
    job = job_manager.get_job(job_id)
    
    if not job:
        raise HTTPException(status_code=404, detail="Job not found")
    
    return job


@app.get("/api/stats")
async def get_stats():
    """Get system statistics"""
    return job_manager.get_stats()


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    """WebSocket for real-time updates"""
    await websocket.accept()
    active_websockets.append(websocket)
    
    try:
        while True:
            data = await websocket.receive_text()
            # Echo back or handle commands
            await websocket.send_json({"status": "connected"})
    except WebSocketDisconnect:
        active_websockets.remove(websocket)
    except Exception as e:
        if websocket in active_websockets:
            active_websockets.remove(websocket)


async def broadcast_job_updates(job_id: str):
    """Broadcast job progress to all connected WebSocket clients"""
    
    while True:
        await asyncio.sleep(0.5)  # Update every 500ms
        
        job = job_manager.get_job(job_id)
        
        if not job:
            break
        
        # Send update to all connected clients
        for ws in active_websockets[:]:  # Copy list to avoid modification during iteration
            try:
                await ws.send_json({
                    "type": "job_update",
                    "job_id": job_id,
                    "status": job["status"],
                    "progress": job["progress"]
                })
            except Exception:
                # Remove disconnected clients
                if ws in active_websockets:
                    active_websockets.remove(ws)
        
        # Stop broadcasting if job is complete or failed
        if job["status"] in ["completed", "failed"]:
            break


@app.on_event("startup")
async def startup_event():
    """Initialize the server on startup"""
    await initialize_server()


def start_gui(host: str = "localhost", port: int = 8080):
    """Start the GUI server with AutoDock integration"""
    print(f"""

╔═══════════════════════════════════════════════════════════════╗

║                   Docking@HOME GUI Server                     ║

║          Real AutoDock Integration with GPU Support           ║

║                                                               ║

║  🌐 Server: http://{host}:{port}
║  🧬 AutoDock: Enabled (GPU acceleration supported)           ║

║  📧 Support: andrew@bleunomics.com                           ║

║  🤗 Issues: https://huggingface.co/OpenPeerAI/DockingAtHOME  ║

║                                                               ║

║  Open your browser to start docking!                         ║

╚═══════════════════════════════════════════════════════════════╝

    """)
    
    uvicorn.run(app, host=host, port=port, log_level="info")


if __name__ == "__main__":
    start_gui()