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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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d2208d17-47b6-4ff1-b6b6-ba09a9d490c7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7864\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7864/\" 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": 5,
     "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": "code",
   "execution_count": 4,
   "id": "a1088e14-f09c-48ff-8632-cc4685306d7c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7863\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7863/\" 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"
    }
   ],
   "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": "code",
   "execution_count": 8,
   "id": "cdf7fd26-0464-40d9-9107-71c29dbcaef8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7867\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7867/\" 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": 8,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/tm/ym2tckv54b96ws82y3b7cqhh0000gn/T/ipykernel_11794/4072855226.py:39: MatplotlibDeprecationWarning: The get_cmap function was deprecated in Matplotlib 3.7 and will be removed in 3.11. Use ``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()`` or ``pyplot.get_cmap()`` instead.\n",
      "  colors = [cm.get_cmap('coolwarm')(score)[:3] for score in normalized_scores]\n",
      "Traceback (most recent call last):\n",
      "  File \"/Users/thorben_froehlking/anaconda3/envs/LLM/lib/python3.12/site-packages/gradio/queueing.py\", line 622, in process_events\n",
      "    response = await route_utils.call_process_api(\n",
      "               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/Users/thorben_froehlking/anaconda3/envs/LLM/lib/python3.12/site-packages/gradio/route_utils.py\", line 323, in call_process_api\n",
      "    output = await app.get_blocks().process_api(\n",
      "             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/Users/thorben_froehlking/anaconda3/envs/LLM/lib/python3.12/site-packages/gradio/blocks.py\", line 2024, in process_api\n",
      "    data = await self.postprocess_data(block_fn, result[\"prediction\"], state)\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/Users/thorben_froehlking/anaconda3/envs/LLM/lib/python3.12/site-packages/gradio/blocks.py\", line 1830, in postprocess_data\n",
      "    prediction_value = block.postprocess(prediction_value)\n",
      "                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/Users/thorben_froehlking/anaconda3/envs/LLM/lib/python3.12/site-packages/gradio_molecule3d/molecule3d.py\", line 210, in postprocess\n",
      "    orig_name=Path(file).name,\n",
      "              ^^^^^^^^^^\n",
      "  File \"/Users/thorben_froehlking/anaconda3/envs/LLM/lib/python3.12/pathlib.py\", line 1162, in __init__\n",
      "    super().__init__(*args)\n",
      "  File \"/Users/thorben_froehlking/anaconda3/envs/LLM/lib/python3.12/pathlib.py\", line 373, in __init__\n",
      "    raise TypeError(\n",
      "TypeError: argument should be a str or an os.PathLike object where __fspath__ returns a str, not 'dict'\n"
     ]
    }
   ],
   "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",
    "from matplotlib import cm\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, 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, 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",
    "    # Normalize scores for coloring (0 = blue, 1 = red)\n",
    "    normalized_scores = (random_scores - np.min(random_scores)) / (np.max(random_scores) - np.min(random_scores))\n",
    "    colors = [cm.get_cmap('coolwarm')(score)[:3] for score in normalized_scores]\n",
    "    hex_colors = [f'#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}' for r, g, b in colors]\n",
    "\n",
    "    # Result string and representation\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",
    "    # Representation for the protein structure\n",
    "    reps = [\n",
    "        {\n",
    "            \"model\": 0,\n",
    "            \"style\": \"cartoon\",\n",
    "            \"color\": \"whiteCarbon\"\n",
    "        }\n",
    "    ] + [\n",
    "        {\n",
    "            \"model\": 0,\n",
    "            \"style\": \"cartoon\",\n",
    "            \"residue_index\": i,\n",
    "            \"color\": color\n",
    "        }\n",
    "        for i, color in enumerate(hex_colors)\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, reps, prediction_file\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",
    "    prediction_btn.click(\n",
    "        fn=process_pdb,\n",
    "        inputs=[pdb_input, segment_input],\n",
    "        outputs=[predictions_output, molecule_output, download_output]\n",
    "    )\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": "ee215c16-a1fb-450f-bb93-37aaee6fb3f1",
   "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
}