{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Data Manpulation\nIn this notebook i will show how to convert the labels to different represntations. As all of you know there is already a pretrained model https://github.com/Kohulan/DECIMER-Image-to-SMILES to Extract SMILES representation from images."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\nimport cv2\nimport requests","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/bms-molecular-translation/train_labels.csv')\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inchi = df['InChI'].iloc[0]\ninchi","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## you can send a direct request to get the SMILES representation \nHOST = \"http://www.chemspider.com\"\nOperation = \"/InChI.asmx/InChIToInChIKey?inchi=\"\n\nrequest = requests.get('{}{}{}'.format(HOST, Operation, inchi))\nif request.ok:\n    res = str(request.text.replace('<?xml version=\"1.0\" encoding=\"utf-8\"?>\\r\\n<string xmlns=\"http://www.chemspider.com/\">', '').replace('</string>', '').strip())\nelse:\n    print (\"provide a valid inchi!\")\nprint(res)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install bioservices","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#get information about the Molecular\nfrom bioservices import *\ninfo = UniChem()\ncid = info.get_src_compound_ids_from_inchikey(res)[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Now let us go to SMILES using another service for FUN \ndef get_smiles_from_inchikey(inchikey):\n    request = requests.get(f'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/inchikey/{inchikey}/property/CanonicalSMILES/JSON').json()\n    return request['PropertyTable']['Properties'][0]['CanonicalSMILES']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"smiles_pres=get_smiles_from_inchikey(res)\nprint(smiles_pres)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# new library ))\n!pip install -U chembl_webresource_client","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# go back from InChiKey to In Chi\nfrom chembl_webresource_client.unichem import unichem_client as unichem\nret = unichem.inchiFromKey(res)\nprint (ret[0]['standardinchi'])\nprint(inchi)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Let us Generate a good images"},{"metadata":{"trusted":true},"cell_type":"code","source":"!wget -c https://repo.continuum.io/miniconda/Miniconda3-py37_4.8.3-Linux-x86_64.sh\n!chmod +x Miniconda3-py37_4.8.3-Linux-x86_64.sh\n!time bash ./Miniconda3-py37_4.8.3-Linux-x86_64.sh -b -f -p /usr/local\n!time conda install -q -y -c conda-forge rdkit\n\nimport sys\nsys.path.append('/usr/local/lib/python3.7/site-packages/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from rdkit import Chem\nfrom rdkit.Chem import Draw\n\nimport matplotlib.pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# ref: https://www.kaggle.com/ihelon/molecular-translation-exploratory-data-analysis \ndef convert_image_id_2_path(image_id: str) -> str:\n    return \"../input/bms-molecular-translation/train/{}/{}/{}/{}.png\".format(\n        image_id[0], image_id[1], image_id[2], image_id \n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ref: https://www.kaggle.com/ihelon/molecular-translation-exploratory-data-analysis\ndef visualize_train_image(image_id, label):\n    plt.figure(figsize=(8, 8))\n    print(image_id)\n    image = cv2.imread(convert_image_id_2_path(image_id))\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    plt.imshow(image)\n    plt.title(f\"{label}\", fontsize=14)\n    plt.axis(\"off\")\n    \n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_row = df.iloc[0]\nvisualize_train_image(\n        sample_row[\"image_id\"], sample_row[\"InChI\"]\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"penicillin_g_smiles = smiles_pres\n\npenicillin_g = Chem.MolFromSmiles(penicillin_g_smiles)\n\nDraw.MolToMPL(penicillin_g, size=(200, 200))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install py3Dmol","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import py3Dmol","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Notebook ref: https://www.kaggle.com/maunish/bms-super-cool-eda\ndef show_3d_models(cid):\n    view = py3Dmol.view(width=600, height=1000, query=cid, viewergrid=(2,1), linked=False)\n    view.setStyle({'stick': {}}, viewer=(0,0))\n    view.setStyle({'sphere': {}}, viewer=(1,0))\n    view.setBackgroundColor('#1AD40D', viewer=(0,0))\n    view.setBackgroundColor('#1AD40D', viewer=(1,0))\n    view.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cid = 'cid:'+cid['src_compound_id']\nshow_3d_models(cid)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Note\nUsing DECIMER directly will give a really bad results the first step is to make image denoisying.\nHope it will be useful"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}