| 6 | from typing import List, Optional, Union |
| 7 | |
| 8 | class ChemicalPropAPI: |
| 9 | def __init__(self) -> None: |
| 10 | self._endpoint = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/" |
| 11 | |
| 12 | def get_name_by_cid(self, cid : str, top_k : Optional[int] = None) -> List[str]: |
| 13 | html_doc = requests.get(f"{self._endpoint}cid/{cid}/synonyms/XML").text |
| 14 | soup = BeautifulSoup(html_doc, "html.parser", from_encoding="utf-8") |
| 15 | syns = soup.find_all('synonym') |
| 16 | ans = [] |
| 17 | if top_k is None: |
| 18 | top_k = len(syns) |
| 19 | for syn in syns[:top_k]: |
| 20 | ans.append(syn.text) |
| 21 | return ans |
| 22 | |
| 23 | def get_cid_by_struct(self, smiles : str) -> List[str]: |
| 24 | html_doc = requests.get(f"{self._endpoint}smiles/{smiles}/cids/XML").text |
| 25 | soup = BeautifulSoup(html_doc,"html.parser",from_encoding="utf-8") |
| 26 | cids = soup.find_all('cid') |
| 27 | if cids is None: |
| 28 | return [] |
| 29 | ans = [] |
| 30 | for cid in cids: |
| 31 | ans.append(cid.text) |
| 32 | return ans |
| 33 | |
| 34 | def get_cid_by_name(self, name : str, name_type : Optional[str] = None) -> List[str]: |
| 35 | url = f"{self._endpoint}name/{name}/cids/XML" |
| 36 | if name_type is not None: |
| 37 | url += f"?name_type={name_type}" |
| 38 | html_doc = requests.get(url).text |
| 39 | soup = BeautifulSoup(html_doc,"html.parser",from_encoding="utf-8") |
| 40 | cids = soup.find_all('cid') |
| 41 | if cids is None: |
| 42 | return [] |
| 43 | ans = [] |
| 44 | for cid in cids: |
| 45 | ans.append(cid.text) |
| 46 | return ans |
| 47 | |
| 48 | def get_prop_by_cid(self, cid : str) -> str: |
| 49 | html_doc = requests.get(f"{self._endpoint}cid/{cid}/property/MolecularFormula,MolecularWeight,CanonicalSMILES,IsomericSMILES,IUPACName,XLogP,ExactMass,MonoisotopicMass,TPSA,Complexity,Charge,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount,CovalentUnitCount/json").text |
| 50 | return json.loads(html_doc)['PropertyTable']['Properties'][0] |
| 51 | |
| 52 | class GetNameResponse(BaseModel): |
| 53 | |