File size: 32,502 Bytes
c85a5b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1f8ea359-674c-4263-9c2a-7a8e7e464249",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7862\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7862/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "import requests\n",
    "from Bio.PDB import PDBParser\n",
    "from gradio_molecule3d import Molecule3D\n",
    "import numpy as np\n",
    "\n",
    "# Function to fetch a PDB file from RCSB PDB\n",
    "def fetch_pdb(pdb_id):\n",
    "    pdb_url = f'https://files.rcsb.org/download/{pdb_id}.pdb'\n",
    "    pdb_path = f'{pdb_id}.pdb'\n",
    "    response = requests.get(pdb_url)\n",
    "    if response.status_code == 200:\n",
    "        with open(pdb_path, 'wb') as f:\n",
    "            f.write(response.content)\n",
    "        return pdb_path\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Function to process the PDB file and return random predictions\n",
    "def process_pdb(pdb_id, segment):\n",
    "    pdb_path = fetch_pdb(pdb_id)\n",
    "    if not pdb_path:\n",
    "        return \"Failed to fetch PDB file\", None, None\n",
    "\n",
    "    parser = PDBParser(QUIET=True)\n",
    "    structure = parser.get_structure('protein', pdb_path)\n",
    "    \n",
    "    try:\n",
    "        chain = structure[0][segment]\n",
    "    except KeyError:\n",
    "        return \"Invalid Chain ID\", None, None\n",
    "\n",
    "    sequence = [residue.get_resname() for residue in chain if residue.id[0] == ' ']\n",
    "    random_scores = np.random.rand(len(sequence))\n",
    "\n",
    "    result_str = \"\\n\".join(\n",
    "        f\"{seq} {res.id[1]} {score:.2f}\" \n",
    "        for seq, res, score in zip(sequence, chain, random_scores)\n",
    "    )\n",
    "\n",
    "    # Save the predictions to a file\n",
    "    prediction_file = f\"{pdb_id}_predictions.txt\"\n",
    "    with open(prediction_file, \"w\") as f:\n",
    "        f.write(result_str)\n",
    "    \n",
    "    return result_str, pdb_path, prediction_file\n",
    "\n",
    "#reps = [{\"model\": 0, \"style\": \"cartoon\", \"color\": \"spectrum\"}]\n",
    "\n",
    "reps =    [\n",
    "        {\n",
    "          \"model\": 0,\n",
    "          \"style\": \"cartoon\",\n",
    "          \"color\": \"whiteCarbon\",\n",
    "          \"residue_range\": \"\",\n",
    "          \"around\": 0,\n",
    "          \"byres\": False,\n",
    "        },\n",
    "        {\n",
    "          \"model\": 0,\n",
    "          \"chain\": \"A\",\n",
    "          \"resname\": \"HIS\",\n",
    "          \"style\": \"stick\",\n",
    "          \"color\": \"red\"\n",
    "        }\n",
    "      ]\n",
    "\n",
    "\n",
    "# Gradio UI\n",
    "with gr.Blocks() as demo:\n",
    "    gr.Markdown(\"# Protein Binding Site Prediction (Random Scores)\")\n",
    "\n",
    "    with gr.Row():\n",
    "        pdb_input = gr.Textbox(value=\"2IWI\", label=\"PDB ID\", placeholder=\"Enter PDB ID here...\")\n",
    "        segment_input = gr.Textbox(value=\"A\", label=\"Chain ID\", placeholder=\"Enter Chain ID here...\")\n",
    "        visualize_btn = gr.Button(\"Visualize Structure\")\n",
    "        prediction_btn = gr.Button(\"Predict Random Binding Site Scores\")\n",
    "\n",
    "    molecule_output = Molecule3D(label=\"Protein Structure\", reps=reps)\n",
    "    predictions_output = gr.Textbox(label=\"Binding Site Predictions\")\n",
    "    download_output = gr.File(label=\"Download Predictions\")\n",
    "\n",
    "    visualize_btn.click(fetch_pdb, inputs=[pdb_input], outputs=molecule_output)\n",
    "    prediction_btn.click(process_pdb, inputs=[pdb_input, segment_input], outputs=[predictions_output, molecule_output, download_output])\n",
    "\n",
    "    gr.Markdown(\"## Examples\")\n",
    "    gr.Examples(\n",
    "        examples=[\n",
    "            [\"2IWI\", \"A\"],\n",
    "            [\"7RPZ\", \"B\"],\n",
    "            [\"3TJN\", \"C\"]\n",
    "        ],\n",
    "        inputs=[pdb_input, segment_input],\n",
    "        outputs=[predictions_output, molecule_output, download_output]\n",
    "    )\n",
    "\n",
    "demo.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd50ff2e-ed03-498e-8af2-73c0fb8ea07e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "raw",
   "id": "88affe12-7c48-4bd6-9e46-32cdffa729fe",
   "metadata": {},
   "source": [
    "import gradio as gr\n",
    "from gradio_molecule3d import Molecule3D\n",
    "\n",
    "\n",
    "example = Molecule3D().example_value()\n",
    "\n",
    "\n",
    "reps =    [\n",
    "        {\n",
    "          \"model\": 0,\n",
    "          \"style\": \"cartoon\",\n",
    "          \"color\": \"whiteCarbon\",\n",
    "          \"residue_range\": \"\",\n",
    "          \"around\": 0,\n",
    "          \"byres\": False,\n",
    "        },\n",
    "        {\n",
    "          \"model\": 0,\n",
    "          \"chain\": \"A\",\n",
    "          \"resname\": \"HIS\",\n",
    "          \"style\": \"stick\",\n",
    "          \"color\": \"red\"\n",
    "        }\n",
    "      ]\n",
    "\n",
    "\n",
    "\n",
    "def predict(x):\n",
    "    print(\"predict function\", x)\n",
    "    print(x.name)\n",
    "    return x\n",
    "\n",
    "with gr.Blocks() as demo:\n",
    "    gr.Markdown(\"# Molecule3D\")\n",
    "    inp = Molecule3D(label=\"Molecule3D\", reps=reps)\n",
    "    out = Molecule3D(label=\"Output\", reps=reps)\n",
    "\n",
    "    btn = gr.Button(\"Predict\")\n",
    "    gr.Markdown(\"\"\" \n",
    "    You can configure the default rendering of the molecule by adding a list of representations\n",
    "    <pre>\n",
    "        reps =    [\n",
    "        {\n",
    "          \"model\": 0,\n",
    "          \"style\": \"cartoon\",\n",
    "          \"color\": \"whiteCarbon\",\n",
    "          \"residue_range\": \"\",\n",
    "          \"around\": 0,\n",
    "          \"byres\": False,\n",
    "        },\n",
    "        {\n",
    "          \"model\": 0,\n",
    "          \"chain\": \"A\",\n",
    "          \"resname\": \"HIS\",\n",
    "          \"style\": \"stick\",\n",
    "          \"color\": \"red\"\n",
    "        }\n",
    "      ]\n",
    "    </pre>\n",
    "    \"\"\")\n",
    "    btn.click(predict, inputs=inp, outputs=out)\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    demo.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d27cc368-26a0-42c2-a68a-8833de7bb4a0",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "raw",
   "id": "2b970adb-3152-427f-bb58-b92974ff406e",
   "metadata": {},
   "source": [
    "import gradio as gr\n",
    "import os\n",
    "import requests\n",
    "from Bio.PDB import PDBParser, PDBIO\n",
    "import biotite.structure.io as bsio\n",
    "\n",
    "def read_mol(pdb_path):\n",
    "    \"\"\"Read PDB file and return its content as a string\"\"\"\n",
    "    with open(pdb_path, 'r') as f:\n",
    "        return f.read()\n",
    "\n",
    "# Function to fetch or upload the PDB file\n",
    "def get_pdb(pdb_code=\"\", filepath=\"\"):\n",
    "    if pdb_code and len(pdb_code) == 4:\n",
    "        pdb_file = f\"{pdb_code}.pdb\"\n",
    "        if not os.path.exists(pdb_file):\n",
    "            os.system(f\"wget -qnc https://files.rcsb.org/view/{pdb_code}.pdb\")\n",
    "        return pdb_file\n",
    "    elif filepath is not None:\n",
    "        return filepath\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def molecule(input_pdb):\n",
    "    mol = read_mol(input_pdb)  # Read PDB file content\n",
    "    \n",
    "    html_content = f\"\"\"\n",
    "    <!DOCTYPE html>\n",
    "    <html>\n",
    "    <head>    \n",
    "        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n",
    "        <style>\n",
    "        .mol-container {{\n",
    "            width: 100%;\n",
    "            height: 700px;\n",
    "            position: relative;\n",
    "        }}\n",
    "        </style>\n",
    "        <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js\"></script>\n",
    "        <script src=\"https://3Dmol.csb.pitt.edu/build/3Dmol-min.js\"></script>\n",
    "    </head>\n",
    "    <body>\n",
    "        <div id=\"container\" class=\"mol-container\"></div>\n",
    "        <script>\n",
    "            let pdb = `{mol}`; // Use template literal to properly escape PDB content\n",
    "            $(document).ready(function () {{\n",
    "                let element = $(\"#container\");\n",
    "                let config = {{ backgroundColor: \"white\" }};\n",
    "                let viewer = $3Dmol.createViewer(element, config);\n",
    "                viewer.addModel(pdb, \"pdb\");\n",
    "                viewer.getModel(0).setStyle({{}}, {{ cartoon: {{ colorscheme:\"whiteCarbon\" }} }});\n",
    "                viewer.zoomTo();\n",
    "                viewer.render();\n",
    "                viewer.zoom(0.8, 2000);\n",
    "            }});\n",
    "        </script>\n",
    "    </body>\n",
    "    </html>\n",
    "    \"\"\"\n",
    "    \n",
    "    # Return the HTML content within an iframe safely encoded for special characters\n",
    "    return f'<iframe width=\"100%\" height=\"700\" srcdoc=\"{html_content.replace(chr(34), \"&quot;\").replace(chr(39), \"&#39;\")}\"></iframe>'\n",
    "\n",
    "# Gradio function to update the visualization\n",
    "def update(inp, file):\n",
    "    pdb_path = get_pdb(inp, file)\n",
    "    if pdb_path:\n",
    "        return molecule(pdb_path)\n",
    "    else:\n",
    "        return \"Invalid input. Please provide a valid PDB code or upload a PDB file.\"\n",
    "\n",
    "# Gradio UI\n",
    "demo = gr.Blocks()\n",
    "with demo:\n",
    "    gr.Markdown(\"# PDB Viewer using 3Dmol.js\")\n",
    "    with gr.Row():\n",
    "        with gr.Column():\n",
    "            inp = gr.Textbox(\n",
    "                placeholder=\"PDB Code or upload file below\", label=\"Input structure\"\n",
    "            )\n",
    "            file = gr.File(file_count=\"single\")\n",
    "            btn = gr.Button(\"View structure\")\n",
    "        mol = gr.HTML()\n",
    "    btn.click(fn=update, inputs=[inp, file], outputs=mol)\n",
    "\n",
    "# Launch the Gradio interface \n",
    "demo.launch(debug=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee215c16-a1fb-450f-bb93-37aaee6fb3f1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "raw",
   "id": "050aa2e8-2dbe-4a28-8692-58ca7c50fccd",
   "metadata": {},
   "source": [
    "import gradio as gr\n",
    "import os\n",
    "import requests\n",
    "import numpy as np\n",
    "from Bio.PDB import PDBParser\n",
    "\n",
    "def read_mol(pdb_path):\n",
    "    \"\"\"Read PDB file and return its content as a string\"\"\"\n",
    "    with open(pdb_path, 'r') as f:\n",
    "        return f.read()\n",
    "\n",
    "# Function to fetch a PDB file from RCSB PDB\n",
    "def fetch_pdb(pdb_id):\n",
    "    pdb_url = f'https://files.rcsb.org/download/{pdb_id}.pdb'\n",
    "    pdb_path = f'{pdb_id}.pdb'\n",
    "    response = requests.get(pdb_url)\n",
    "    if response.status_code == 200:\n",
    "        with open(pdb_path, 'wb') as f:\n",
    "            f.write(response.content)\n",
    "        return molecule(pdb_path)\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Function to process the PDB file and return random predictions\n",
    "def process_pdb(pdb_id, segment):\n",
    "    pdb_path = fetch_pdb(pdb_id)\n",
    "    if not pdb_path:\n",
    "        return \"Failed to fetch PDB file\", None, None\n",
    "    \n",
    "    parser = PDBParser(QUIET=True)\n",
    "    structure = parser.get_structure('protein', pdb_path)\n",
    "    \n",
    "    try:\n",
    "        chain = structure[0][segment]\n",
    "    except KeyError:\n",
    "        return \"Invalid Chain ID\", None, None\n",
    "    \n",
    "    sequence = [residue.get_resname() for residue in chain if residue.id[0] == ' ']\n",
    "    random_scores = np.random.rand(len(sequence))\n",
    "    result_str = \"\\n\".join(\n",
    "        f\"{seq} {res.id[1]} {score:.2f}\" \n",
    "        for seq, res, score in zip(sequence, chain, random_scores)\n",
    "    )\n",
    "    \n",
    "    # Save the predictions to a file\n",
    "    prediction_file = f\"{pdb_id}_predictions.txt\"\n",
    "    with open(prediction_file, \"w\") as f:\n",
    "        f.write(result_str)\n",
    "    \n",
    "    return result_str, molecule(pdb_path), prediction_file\n",
    "\n",
    "def molecule(input_pdb):\n",
    "    mol = read_mol(input_pdb)  # Read PDB file content\n",
    "    \n",
    "    html_content = f\"\"\"\n",
    "    <!DOCTYPE html>\n",
    "    <html>\n",
    "    <head>    \n",
    "        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n",
    "        <style>\n",
    "        .mol-container {{\n",
    "            width: 100%;\n",
    "            height: 700px;\n",
    "            position: relative;\n",
    "        }}\n",
    "        </style>\n",
    "        <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js\"></script>\n",
    "        <script src=\"https://3Dmol.csb.pitt.edu/build/3Dmol-min.js\"></script>\n",
    "    </head>\n",
    "    <body>\n",
    "        <div id=\"container\" class=\"mol-container\"></div>\n",
    "        <script>\n",
    "            let pdb = `{mol}`; // Use template literal to properly escape PDB content\n",
    "            $(document).ready(function () {{\n",
    "                let element = $(\"#container\");\n",
    "                let config = {{ backgroundColor: \"white\" }};\n",
    "                let viewer = $3Dmol.createViewer(element, config);\n",
    "                viewer.addModel(pdb, \"pdb\");\n",
    "                \n",
    "                // Set cartoon representation with white carbon color scheme\n",
    "                viewer.getModel(0).setStyle({{}}, {{ cartoon: {{ colorscheme:\"whiteCarbon\" }} }});\n",
    "                \n",
    "                // Highlight specific histidine residues in red stick representation\n",
    "                viewer.getModel(0).setStyle(\n",
    "                    {{\"resn\": \"HIS\"}}, \n",
    "                    {{\"stick\": {{\"color\": \"red\"}}}}\n",
    "                );\n",
    "                \n",
    "                viewer.zoomTo();\n",
    "                viewer.render();\n",
    "                viewer.zoom(0.8, 2000);\n",
    "            }});\n",
    "        </script>\n",
    "    </body>\n",
    "    </html>\n",
    "    \"\"\"\n",
    "    \n",
    "    # Return the HTML content within an iframe safely encoded for special characters\n",
    "    return f'<iframe width=\"100%\" height=\"700\" srcdoc=\"{html_content.replace(chr(34), \"&quot;\").replace(chr(39), \"&#39;\")}\"></iframe>'\n",
    "\n",
    "# Gradio UI\n",
    "with gr.Blocks() as demo:\n",
    "    gr.Markdown(\"# Protein Binding Site Prediction (Random Scores)\")\n",
    "    with gr.Row():\n",
    "        pdb_input = gr.Textbox(value=\"2IWI\", label=\"PDB ID\", placeholder=\"Enter PDB ID here...\")\n",
    "        segment_input = gr.Textbox(value=\"A\", label=\"Chain ID\", placeholder=\"Enter Chain ID here...\")\n",
    "        visualize_btn = gr.Button(\"Visualize Structure\")\n",
    "        prediction_btn = gr.Button(\"Predict Random Binding Site Scores\")\n",
    "    \n",
    "    # Use HTML output instead of Molecule3D\n",
    "    molecule_output = gr.HTML(label=\"Protein Structure\")\n",
    "    predictions_output = gr.Textbox(label=\"Binding Site Predictions\")\n",
    "    download_output = gr.File(label=\"Download Predictions\")\n",
    "    \n",
    "    visualize_btn.click(fetch_pdb, inputs=[pdb_input], outputs=molecule_output)\n",
    "    prediction_btn.click(process_pdb, inputs=[pdb_input, segment_input], outputs=[predictions_output, molecule_output, download_output])\n",
    "    \n",
    "    gr.Markdown(\"## Examples\")\n",
    "    gr.Examples(\n",
    "        examples=[\n",
    "            [\"2IWI\", \"A\"],\n",
    "            [\"7RPZ\", \"B\"],\n",
    "            [\"3TJN\", \"C\"]\n",
    "        ],\n",
    "        inputs=[pdb_input, segment_input],\n",
    "        outputs=[predictions_output, molecule_output, download_output]\n",
    "    )\n",
    "\n",
    "demo.launch(debug=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9a5facd9-855c-4b35-8dd3-2c0c8c7dd356",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "raw",
   "id": "a762170f-92a9-473d-b18d-53607a780e3b",
   "metadata": {},
   "source": [
    "import gradio as gr\n",
    "import requests\n",
    "from Bio.PDB import PDBParser\n",
    "import numpy as np\n",
    "import os\n",
    "\n",
    "def read_mol(pdb_path):\n",
    "    \"\"\"Read PDB file and return its content as a string\"\"\"\n",
    "    with open(pdb_path, 'r') as f:\n",
    "        return f.read()\n",
    "\n",
    "# Function to fetch a PDB file from RCSB PDB\n",
    "def fetch_pdb(pdb_id):\n",
    "    pdb_url = f'https://files.rcsb.org/download/{pdb_id}.pdb'\n",
    "    pdb_path = f'{pdb_id}.pdb'\n",
    "    response = requests.get(pdb_url)\n",
    "    if response.status_code == 200:\n",
    "        with open(pdb_path, 'wb') as f:\n",
    "            f.write(response.content)\n",
    "        return pdb_path\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Function to process the PDB file and return random predictions\n",
    "def process_pdb(pdb_id, segment):\n",
    "    pdb_path = fetch_pdb(pdb_id)\n",
    "    if not pdb_path:\n",
    "        return \"Failed to fetch PDB file\", None, None\n",
    "    parser = PDBParser(QUIET=True)\n",
    "    structure = parser.get_structure('protein', pdb_path)\n",
    "    \n",
    "    try:\n",
    "        chain = structure[0][segment]\n",
    "    except KeyError:\n",
    "        return \"Invalid Chain ID\", None, None\n",
    "    sequence = [residue.get_resname() for residue in chain if residue.id[0] == ' ']\n",
    "    random_scores = np.random.rand(len(sequence))\n",
    "    result_str = \"\\n\".join(\n",
    "        f\"{seq} {res.id[1]} {score:.2f}\" \n",
    "        for seq, res, score in zip(sequence, chain, random_scores)\n",
    "    )\n",
    "    # Save the predictions to a file\n",
    "    prediction_file = f\"{pdb_id}_predictions.txt\"\n",
    "    with open(prediction_file, \"w\") as f:\n",
    "        f.write(result_str)\n",
    "    \n",
    "    return result_str, molecule(pdb_path), prediction_file\n",
    "\n",
    "def molecule(input_pdb):\n",
    "    mol = read_mol(input_pdb)  # Read PDB file content\n",
    "    \n",
    "    html_content = f\"\"\"\n",
    "    <!DOCTYPE html>\n",
    "    <html>\n",
    "    <head>    \n",
    "        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n",
    "        <style>\n",
    "        .mol-container {{\n",
    "            width: 100%;\n",
    "            height: 700px;\n",
    "            position: relative;\n",
    "        }}\n",
    "        </style>\n",
    "        <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js\"></script>\n",
    "        <script src=\"https://3Dmol.csb.pitt.edu/build/3Dmol-min.js\"></script>\n",
    "    </head>\n",
    "    <body>\n",
    "        <div id=\"container\" class=\"mol-container\"></div>\n",
    "        <script>\n",
    "            let pdb = `{mol}`; // Use template literal to properly escape PDB content\n",
    "            $(document).ready(function () {{\n",
    "                let element = $(\"#container\");\n",
    "                let config = {{ backgroundColor: \"white\" }};\n",
    "                let viewer = $3Dmol.createViewer(element, config);\n",
    "                viewer.addModel(pdb, \"pdb\");\n",
    "                \n",
    "                // Set cartoon representation with white carbon color scheme\n",
    "                viewer.getModel(0).setStyle({{}}, {{ cartoon: {{ colorscheme:\"whiteCarbon\" }} }});\n",
    "                \n",
    "                // Highlight specific histidine residues in red stick representation\n",
    "                viewer.getModel(0).setStyle(\n",
    "                    {{\"resn\": \"HIS\"}}, \n",
    "                    {{\"stick\": {{\"color\": \"red\"}}}}\n",
    "                );\n",
    "                \n",
    "                viewer.zoomTo();\n",
    "                viewer.render();\n",
    "                viewer.zoom(0.8, 2000);\n",
    "            }});\n",
    "        </script>\n",
    "    </body>\n",
    "    </html>\n",
    "    \"\"\"\n",
    "    \n",
    "    # Return the HTML content within an iframe safely encoded for special characters\n",
    "    return f'<iframe width=\"100%\" height=\"700\" srcdoc=\"{html_content.replace(chr(34), \"&quot;\").replace(chr(39), \"&#39;\")}\"></iframe>'\n",
    "\n",
    "# Gradio UI\n",
    "with gr.Blocks() as demo:\n",
    "    gr.Markdown(\"# Protein Binding Site Prediction (Random Scores)\")\n",
    "    with gr.Row():\n",
    "        pdb_input = gr.Textbox(value=\"2IWI\", label=\"PDB ID\", placeholder=\"Enter PDB ID here...\")\n",
    "        segment_input = gr.Textbox(value=\"A\", label=\"Chain ID\", placeholder=\"Enter Chain ID here...\")\n",
    "        visualize_btn = gr.Button(\"Visualize Structure\")\n",
    "        prediction_btn = gr.Button(\"Predict Random Binding Site Scores\")\n",
    "    \n",
    "    molecule_output = gr.HTML(label=\"Protein Structure\")\n",
    "    predictions_output = gr.Textbox(label=\"Binding Site Predictions\")\n",
    "    download_output = gr.File(label=\"Download Predictions\")\n",
    "    \n",
    "    # Update to explicitly use molecule() function for visualization\n",
    "    visualize_btn.click(\n",
    "        fn=lambda pdb_id: molecule(fetch_pdb(pdb_id)), \n",
    "        inputs=[pdb_input], \n",
    "        outputs=molecule_output\n",
    "    )\n",
    "    \n",
    "    prediction_btn.click(process_pdb, inputs=[pdb_input, segment_input], outputs=[predictions_output, molecule_output, download_output])\n",
    "    \n",
    "    gr.Markdown(\"## Examples\")\n",
    "    gr.Examples(\n",
    "        examples=[\n",
    "            [\"2IWI\", \"A\"],\n",
    "            [\"7RPZ\", \"B\"],\n",
    "            [\"3TJN\", \"C\"]\n",
    "        ],\n",
    "        inputs=[pdb_input, segment_input],\n",
    "        outputs=[predictions_output, molecule_output, download_output]\n",
    "    )\n",
    "\n",
    "demo.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15527a58-c449-4da0-8fab-3baaede15e41",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9ef3e330-cb88-4c29-b84a-2f8652883cfc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7860\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "import requests\n",
    "from Bio.PDB import PDBParser\n",
    "import numpy as np\n",
    "import os\n",
    "from gradio_molecule3d import Molecule3D\n",
    "\n",
    "def read_mol(pdb_path):\n",
    "    \"\"\"Read PDB file and return its content as a string\"\"\"\n",
    "    with open(pdb_path, 'r') as f:\n",
    "        return f.read()\n",
    "\n",
    "def fetch_pdb(pdb_id):\n",
    "    pdb_url = f'https://files.rcsb.org/download/{pdb_id}.pdb'\n",
    "    pdb_path = f'{pdb_id}.pdb'\n",
    "    response = requests.get(pdb_url)\n",
    "    if response.status_code == 200:\n",
    "        with open(pdb_path, 'wb') as f:\n",
    "            f.write(response.content)\n",
    "        return pdb_path\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def process_pdb(pdb_id, segment):\n",
    "    pdb_path = fetch_pdb(pdb_id)\n",
    "    if not pdb_path:\n",
    "        return \"Failed to fetch PDB file\", None, None\n",
    "    parser = PDBParser(QUIET=True)\n",
    "    structure = parser.get_structure('protein', pdb_path)\n",
    "    \n",
    "    try:\n",
    "        chain = structure[0][segment]\n",
    "    except KeyError:\n",
    "        return \"Invalid Chain ID\", None, None\n",
    "    sequence = [residue.get_resname() for residue in chain if residue.id[0] == ' ']\n",
    "    random_scores = np.random.rand(len(sequence))\n",
    "    result_str = \"\\n\".join(\n",
    "        f\"{seq} {res.id[1]} {score:.2f}\" \n",
    "        for seq, res, score in zip(sequence, chain, random_scores)\n",
    "    )\n",
    "    # Save the predictions to a file\n",
    "    prediction_file = f\"{pdb_id}_predictions.txt\"\n",
    "    with open(prediction_file, \"w\") as f:\n",
    "        f.write(result_str)\n",
    "    \n",
    "    return result_str, molecule(pdb_path, random_scores), prediction_file\n",
    "\n",
    "def molecule(input_pdb, scores=None):\n",
    "    mol = read_mol(input_pdb)  # Read PDB file content\n",
    "    \n",
    "    # Prepare high-scoring residues script if scores are provided\n",
    "    high_score_script = \"\"\n",
    "    if scores is not None:\n",
    "        high_score_script = \"\"\"\n",
    "        // Highlight residues with high scores\n",
    "        let highScoreResidues = [{}];\n",
    "        viewer.getModel(0).setStyle(\n",
    "            {{\"resi\": highScoreResidues}}, \n",
    "            {{\"stick\": {{\"color\": \"red\"}}}}\n",
    "        );\n",
    "        \"\"\".format(\n",
    "            \", \".join(str(i+1) for i, score in enumerate(scores) if score > 0.8)\n",
    "        )\n",
    "    \n",
    "    html_content = f\"\"\"\n",
    "    <!DOCTYPE html>\n",
    "    <html>\n",
    "    <head>    \n",
    "        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n",
    "        <style>\n",
    "        .mol-container {{\n",
    "            width: 100%;\n",
    "            height: 700px;\n",
    "            position: relative;\n",
    "        }}\n",
    "        </style>\n",
    "        <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js\"></script>\n",
    "        <script src=\"https://3Dmol.csb.pitt.edu/build/3Dmol-min.js\"></script>\n",
    "    </head>\n",
    "    <body>\n",
    "        <div id=\"container\" class=\"mol-container\"></div>\n",
    "        <script>\n",
    "            let pdb = `{mol}`; // Use template literal to properly escape PDB content\n",
    "            $(document).ready(function () {{\n",
    "                let element = $(\"#container\");\n",
    "                let config = {{ backgroundColor: \"white\" }};\n",
    "                let viewer = $3Dmol.createViewer(element, config);\n",
    "                viewer.addModel(pdb, \"pdb\");\n",
    "                \n",
    "                // Set cartoon representation with white carbon color scheme\n",
    "                viewer.getModel(0).setStyle({{}}, {{ cartoon: {{ colorscheme:\"whiteCarbon\" }} }});\n",
    "                \n",
    "                {high_score_script}\n",
    "                \n",
    "                viewer.zoomTo();\n",
    "                viewer.render();\n",
    "                viewer.zoom(0.8, 2000);\n",
    "            }});\n",
    "        </script>\n",
    "    </body>\n",
    "    </html>\n",
    "    \"\"\"\n",
    "    \n",
    "    # Return the HTML content within an iframe safely encoded for special characters\n",
    "    return f'<iframe width=\"100%\" height=\"700\" srcdoc=\"{html_content.replace(chr(34), \"&quot;\").replace(chr(39), \"&#39;\")}\"></iframe>'\n",
    "\n",
    "reps =    [\n",
    "        {\n",
    "          \"model\": 0,\n",
    "          \"style\": \"cartoon\",\n",
    "          \"color\": \"whiteCarbon\",\n",
    "          \"residue_range\": \"\",\n",
    "          \"around\": 0,\n",
    "          \"byres\": False,\n",
    "        }\n",
    "    ]\n",
    "# Gradio UI\n",
    "with gr.Blocks() as demo:\n",
    "    gr.Markdown(\"# Protein Binding Site Prediction (Random Scores)\")\n",
    "    with gr.Row():\n",
    "        pdb_input = gr.Textbox(value=\"2IWI\", label=\"PDB ID\", placeholder=\"Enter PDB ID here...\")\n",
    "        segment_input = gr.Textbox(value=\"A\", label=\"Chain ID\", placeholder=\"Enter Chain ID here...\")\n",
    "        visualize_btn = gr.Button(\"Visualize Structure\")\n",
    "        #prediction_btn = gr.Button(\"Predict Random Binding Site Scores\")\n",
    "\n",
    "    molecule_output2 = Molecule3D(label=\"Protein Structure\", reps=reps)\n",
    "\n",
    "    with gr.Row():\n",
    "        pdb_input = gr.Textbox(value=\"2IWI\", label=\"PDB ID\", placeholder=\"Enter PDB ID here...\")\n",
    "        segment_input = gr.Textbox(value=\"A\", label=\"Chain ID\", placeholder=\"Enter Chain ID here...\")\n",
    "        prediction_btn = gr.Button(\"Predict Random Binding Site Scores\")\n",
    "\n",
    "    molecule_output = gr.HTML(label=\"Protein Structure\")\n",
    "    predictions_output = gr.Textbox(label=\"Binding Site Predictions\")\n",
    "    download_output = gr.File(label=\"Download Predictions\")\n",
    "    \n",
    "    #visualize_btn.click(\n",
    "    #    fn=lambda pdb_id: molecule(fetch_pdb(pdb_id)), \n",
    "    #    inputs=[pdb_input], \n",
    "    #    outputs=molecule_output\n",
    "    #)\n",
    "    visualize_btn.click(fetch_pdb, inputs=[pdb_input], outputs=molecule_output2)\n",
    "    \n",
    "    \n",
    "    prediction_btn.click(process_pdb, inputs=[pdb_input, segment_input], outputs=[predictions_output, molecule_output, download_output])\n",
    "    \n",
    "    gr.Markdown(\"## Examples\")\n",
    "    gr.Examples(\n",
    "        examples=[\n",
    "            [\"2IWI\", \"A\"],\n",
    "            [\"7RPZ\", \"B\"],\n",
    "            [\"3TJN\", \"C\"]\n",
    "        ],\n",
    "        inputs=[pdb_input, segment_input],\n",
    "        outputs=[predictions_output, molecule_output, download_output]\n",
    "    )\n",
    "\n",
    "demo.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14605615-8610-4d9e-841b-db7618cde844",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (LLM)",
   "language": "python",
   "name": "llm"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}