{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "5b4c0ea3-c01d-4898-9a90-334b9dd378df", "metadata": {}, "outputs": [], "source": [ "# %pip install pandas requests beautifulsoup4 openai dashscope tqdm" ] }, { "cell_type": "code", "execution_count": null, "id": "f793b430-7369-4f00-b671-69d9ac57c64c", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import requests\n", "import json\n", "import random\n", "import time\n", "from bs4 import BeautifulSoup\n", "import openai\n", "from openai import OpenAI\n", "import dashscope\n", "import getpass\n", "from tqdm import tqdm\n", "\n", "from concurrent.futures import ThreadPoolExecutor, as_completed" ] }, { "cell_type": "code", "execution_count": null, "id": "8eaf4f2d-3612-4892-b1ae-582d939e60a6", "metadata": {}, "outputs": [], "source": [ "def retry_request(func, retries=3, wait_time=2):\n", " def wrapper(*args, **kwargs):\n", " attempt = 0\n", " while attempt < retries:\n", " try:\n", " return func(*args, **kwargs)\n", " except Exception as e:\n", " print(f\"Error: {e}. Retrying {attempt+1}/{retries}...\")\n", " attempt += 1\n", " time.sleep(wait_time)\n", " return None\n", " return wrapper" ] }, { "cell_type": "code", "execution_count": null, "id": "3eac8da7-dce3-4279-85f4-9b4163127a7c", "metadata": {}, "outputs": [], "source": [ "@retry_request\n", "def embed_with_str(text, model='text_embedding_v3'):\n", " resp = dashscope.TextEmbedding.call(\n", " model=eval(f'dashscope.TextEmbedding.Models.{model}'),\n", " input=text)\n", " return resp.output.get('embeddings')[0].get('embedding')" ] }, { "cell_type": "code", "execution_count": null, "id": "5a0ef5f6-bbb7-4d38-8ce6-91f2ea1e8635", "metadata": {}, "outputs": [], "source": [ "def generate_embeddings_multithread(text_df, text_column='Text', embedding_column='Embedding'):\n", " embeddings = [None] * len(text_df)\n", " with ThreadPoolExecutor(max_workers=10) as executor:\n", " future_to_index = {executor.submit(embed_with_str, text): idx for idx, text in enumerate(text_df[text_column])}\n", " \n", " for future in as_completed(future_to_index):\n", " idx = future_to_index[future]\n", " try:\n", " embedding = future.result()\n", " embeddings[idx] = embedding\n", " except Exception as e:\n", " print(f\"Error processing text at index {idx}: {e}\")\n", " embeddings[idx] = None\n", "\n", " text_df[embedding_column] = embeddings\n", " return text_df" ] }, { "cell_type": "code", "execution_count": null, "id": "29104f05-b781-46aa-83e8-476991f3f2da", "metadata": {}, "outputs": [], "source": [ "api_key = getpass.getpass(\"Enter your API key: \")\n", "# client = OpenAI(api_key=api_key)\n", "dashscope.api_key = api_key" ] }, { "cell_type": "markdown", "id": "176f0a62-30da-4a52-88b2-be9d673e3d9b", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# DrugBank" ] }, { "cell_type": "markdown", "id": "9a89cb11-0be0-4e8f-b008-be9252d2d29f", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "## Db2Text" ] }, { "cell_type": "code", "execution_count": null, "id": "fe489388-3c2a-4ef6-8171-7ea22bb7803c", "metadata": {}, "outputs": [], "source": [ "@retry_request\n", "def db2text(drugbank_accession_number=\"DB00460\"):\n", " url = \"https://go.drugbank.com/drugs/\" + drugbank_accession_number\n", " headers = {\n", " \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\"\n", " }\n", "\n", " proxies = {\n", " \"http\": \"http://127.0.0.1:7890\",\n", " \"https\": \"http://127.0.0.1:7890\",\n", " }\n", "\n", " try:\n", " response = requests.get(url, headers=headers, proxies=proxies, timeout=10)\n", " response.raise_for_status()\n", " soup = BeautifulSoup(response.content, 'html.parser')\n", "\n", " # Drug Name\n", " drug_name = soup.find('dt', {'id': 'generic-name'}).find_next_sibling('dd').text.strip()\n", "\n", " # Background\n", " background_section = soup.find('dt', {'id': 'background'})\n", " if background_section:\n", " background_dd = background_section.find_next('dd')\n", " \n", " for sup in background_dd.find_all('sup'):\n", " sup.decompose()\n", " \n", " background = background_dd.get_text(separator=\" \").replace(\"\\n\", \" \").strip()\n", " \n", " # Type\n", " type_value = soup.find('dt', {'id': 'type'}).find_next_sibling('dd').text.strip()\n", "\n", " # Chemical Formula\n", " chemical_formula = soup.find('dt', {'id': 'chemical-formula'}).find_next_sibling('dd').text.strip() if soup.find('dt', {'id': 'chemical-formula'}) else ''\n", "\n", " # Summary\n", " summary_section = soup.find('dt', {'id': 'summary'})\n", " if summary_section:\n", " summary = summary_section.find_next('dd').text.strip()\n", " drug_text = f\"{summary} {background} {drug_name} is of the type {type_value}, number {drugbank_accession_number}\"\n", " else:\n", " drug_text = f\"{background} {drug_name} is of the type {type_value}, number {drugbank_accession_number}\"\n", " \n", " if chemical_formula:\n", " drug_text += f\" and has the molecular formula {chemical_formula}.\"\n", "\n", " # print(drug_text)\n", " \n", " except requests.exceptions.RequestException as e:\n", " print(f\"Error fetching data for {drugbank_accession_number}: {e}\")\n", " except Exception as e:\n", " print(f\"Error parsing data for {drugbank_accession_number}: {e}\")\n", "\n", " return drug_text" ] }, { "cell_type": "code", "execution_count": null, "id": "69595623-6c3e-4b1e-a032-a839d55507c5", "metadata": {}, "outputs": [], "source": [ "def extract_drug_info_multithread(drug_id_df):\n", " with ThreadPoolExecutor(max_workers=10) as executor:\n", " future_to_drug_id = {executor.submit(db2text, drug_id): drug_id for drug_id in drug_id_df[0]}\n", " drug_texts = []\n", "\n", " for future in as_completed(future_to_drug_id):\n", " drug_id = future_to_drug_id[future]\n", " try:\n", " drug_text = future.result()\n", " drug_texts.append((drug_id, drug_text))\n", " except Exception as e:\n", " print(f\"Error processing {drug_id}: {e}\")\n", " drug_texts.append((drug_id, None))\n", "\n", " result_df = pd.DataFrame(drug_texts, columns=['DrugBank ID', 'Text'])\n", " return result_df" ] }, { "cell_type": "code", "execution_count": null, "id": "a9579a1c-3a3d-4075-8e42-8fde1bfdb41d", "metadata": {}, "outputs": [], "source": [ "db2text('DB00313')" ] }, { "cell_type": "code", "execution_count": null, "id": "49023929-8104-4fc7-8670-e135f84be2aa", "metadata": {}, "outputs": [], "source": [ "db2text('DB00010')" ] }, { "cell_type": "code", "execution_count": null, "id": "5997182d-ee03-43bf-80d4-f23dd9ec7ce1", "metadata": {}, "outputs": [], "source": [ "drug_id = pd.read_csv('Wrname.csv', header=None)\n", "drug_id.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "3c609816-acfa-4343-8b0d-2c1b8a45df2b", "metadata": {}, "outputs": [], "source": [ "# drug_id['text'] = drug_id[0].apply(db2text)\n", "# drug_id.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "7da0942f-cf7c-4e17-aa9d-5899e683b406", "metadata": { "scrolled": true }, "outputs": [], "source": [ "result_df = extract_drug_info_multithread(drug_id)\n", "result_df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "6306a80e-5c03-4dae-bb0e-5e364c6760ac", "metadata": {}, "outputs": [], "source": [ "result_df = result_df.sort_values('DrugBank ID', ignore_index=True)\n", "result_df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "4abc5d1a-32c1-49ee-b47e-d142f7b007d1", "metadata": {}, "outputs": [], "source": [ "result_df.shape" ] }, { "cell_type": "code", "execution_count": null, "id": "21b73b62-0947-40ab-85d8-6ef2189115a1", "metadata": {}, "outputs": [], "source": [ "result_df.to_csv('db2text.csv', index=None)" ] }, { "cell_type": "markdown", "id": "0928dcc6-a344-4efe-a391-67d8e5de0699", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "## Text2Emb" ] }, { "cell_type": "code", "execution_count": null, "id": "2bda4d23-f265-4527-8bf4-cd92148c96c2", "metadata": {}, "outputs": [], "source": [ "db2text = pd.read_csv('db2text.csv')\n", "db2text.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "afd92b27-a0d1-46ed-a928-66a66fc49043", "metadata": {}, "outputs": [], "source": [ "# # openai\n", "# @retry_request\n", "# def get_embedding(text, model=\"text-embedding-3-small\"):\n", "# text = text.replace(\"\\n\", \" \")\n", "# return client.embeddings.create(input = [text], model=model).data[0].embedding" ] }, { "cell_type": "code", "execution_count": null, "id": "f096e30e-e4a9-47c8-95ff-6b054d3d454a", "metadata": { "scrolled": true }, "outputs": [], "source": [ "len(embed_with_str(db2text['Text'][0]))" ] }, { "cell_type": "code", "execution_count": null, "id": "3366051e-d736-4d13-b0d6-63d921712341", "metadata": { "scrolled": true }, "outputs": [], "source": [ "result_df = generate_embeddings_multithread(db2text)\n", "result_df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "26a867ad-9904-4f87-b1e4-1c6b8d1c764e", "metadata": {}, "outputs": [], "source": [ "embeddings_expanded = pd.DataFrame(result_df['Embedding'].tolist())\n", "\n", "result_df = pd.concat([result_df.drop('Embedding', axis=1), embeddings_expanded], axis=1)" ] }, { "cell_type": "code", "execution_count": null, "id": "3e62604b-14bc-47b7-8c24-f73b95f4324f", "metadata": {}, "outputs": [], "source": [ "result_df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "6656d2d6-7a3a-48a1-87ab-aa48a3e5481a", "metadata": {}, "outputs": [], "source": [ "result_df.to_csv('db2emb.csv', index=None)" ] }, { "cell_type": "code", "execution_count": null, "id": "89de8136-c58b-4db6-9c53-8e50c4db2f66", "metadata": {}, "outputs": [], "source": [ "db2text[db2text['DrugBank ID'] == 'DB00015']" ] }, { "cell_type": "code", "execution_count": null, "id": "744b0406-8fce-4708-b229-506bf8975b6a", "metadata": { "scrolled": true }, "outputs": [], "source": [ "embed_with_str(db2text[db2text['DrugBank ID'] == 'DB00015']['Text'].values[0])" ] }, { "cell_type": "code", "execution_count": null, "id": "88d63e56-0697-4b44-8da7-92b9c5e6f000", "metadata": {}, "outputs": [], "source": [ "# result_df['embedding'] = result_df['Text'].apply(lambda x: get_embedding(x, model='text-embedding-3-small'))" ] }, { "cell_type": "markdown", "id": "5af04cde-9b48-4351-b2cf-daa9b320abcf", "metadata": {}, "source": [ "# OMIM" ] }, { "cell_type": "markdown", "id": "05def656-8101-4b7c-b679-a94d7a9c71fc", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "## ID2Text" ] }, { "cell_type": "code", "execution_count": null, "id": "01e8f5e5-4069-4962-8dbe-8c6b3f14b766", "metadata": {}, "outputs": [], "source": [ "wdname = pd.read_csv('Wdname.csv', header=None)\n", "wdname.columns = ['ID']\n", "wdname.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "209cef9d-6082-43cf-8844-9039bda78770", "metadata": {}, "outputs": [], "source": [ "wdname['MIM Number'] = wdname['ID'].apply(lambda x: int(x.split('D')[-1]))\n", "wdname.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "daea3834-e464-45de-ae46-91c8c827f5dd", "metadata": {}, "outputs": [], "source": [ "omim2title = pd.read_csv('mimTitles.txt', comment='#', sep='\\t', header=None)\n", "omim2title = omim2title.iloc[:, 1:3]\n", "omim2title.columns = ['MIM Number', 'Title']\n", "omim2title.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "3190ad8a-0e27-4de7-800d-3d1114edfc5b", "metadata": {}, "outputs": [], "source": [ "omim2title.dtypes" ] }, { "cell_type": "code", "execution_count": null, "id": "741f781b-7759-4e56-8691-f0bfff26f726", "metadata": {}, "outputs": [], "source": [ "wdname.dtypes" ] }, { "cell_type": "code", "execution_count": null, "id": "284890b8-0576-4aa0-8fd2-85c4596e92ff", "metadata": {}, "outputs": [], "source": [ "wdname = wdname.merge(omim2title)\n", "wdname.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "ceddeb30-259f-4934-aab4-f719caefeaae", "metadata": {}, "outputs": [], "source": [ "wdname.to_csv('omim2text.csv', index=None)" ] }, { "cell_type": "markdown", "id": "61f2f912-c560-425b-92d6-b1f412847ad2", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "## Text2Emb" ] }, { "cell_type": "code", "execution_count": null, "id": "4f5fdee0-06c6-4742-9a81-ec75ee4cfc7e", "metadata": {}, "outputs": [], "source": [ "omim2text = pd.read_csv('omim2text.csv')\n", "omim2text.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "72f78a78-f04d-4c15-bc9c-f4b523c90e13", "metadata": {}, "outputs": [], "source": [ "@retry_request\n", "def embed_with_str(text, model='text_embedding_v3'):\n", " resp = dashscope.TextEmbedding.call(\n", " model=eval(f'dashscope.TextEmbedding.Models.{model}'),\n", " input=text)\n", " return resp.output.get('embeddings')[0].get('embedding')" ] }, { "cell_type": "code", "execution_count": null, "id": "d887d9bd-e489-47b3-b919-265153fddef0", "metadata": { "scrolled": true }, "outputs": [], "source": [ "len(embed_with_str(omim2text['Title'][0]))" ] }, { "cell_type": "code", "execution_count": null, "id": "256e50bc-4869-4182-ad2a-ea99e4b446ca", "metadata": { "scrolled": true }, "outputs": [], "source": [ "result_df = generate_embeddings_multithread(omim2text, text_column='Title', embedding_column='Embedding')\n", "result_df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "5341a1a9-aa5f-4228-a6de-00174425e6c3", "metadata": {}, "outputs": [], "source": [ "embeddings_expanded = pd.DataFrame(result_df['Embedding'].tolist())\n", "\n", "result_df = pd.concat([result_df.drop('Embedding', axis=1), embeddings_expanded], axis=1)" ] }, { "cell_type": "code", "execution_count": null, "id": "f51f0ef8-458d-4d95-848c-f2e7e428a0eb", "metadata": {}, "outputs": [], "source": [ "result_df.to_csv('omim2emb.csv', index=None)" ] }, { "cell_type": "code", "execution_count": null, "id": "5d145e98-6007-4195-a89d-bd82b219b12d", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "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.2" } }, "nbformat": 4, "nbformat_minor": 5 }