BioMike commited on
Commit
312ab92
1 Parent(s): 6ab8f21

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +70 -0
utils.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import requests
3
+ import os
4
+
5
+ query_templates = {
6
+ "SMILES": """query BySMILES($smiles: String!, $limit: Int = {}) {{
7
+ molecules(SMILES: $smiles, limit: $limit) {{
8
+ {}
9
+ }}
10
+ }}""",
11
+ "IUPAC": """query ByIUPAC($iupac: String!, $limit: Int = {}) {{
12
+ molecules(IUPAC: $iupac, limit: $limit) {{
13
+ {}
14
+ }}
15
+ }}""",
16
+ "NAME": """query ByName($name: String!, $limit: Int = {}) {{
17
+ molecules(name: $name, limit: $limit) {{
18
+ {}
19
+ }}
20
+ }}""",
21
+ "InChI": """query ByInChI($inchi: String!, $limit: Int = {}) {{
22
+ molecules(InChI: $inchi, limit: $limit) {{
23
+ {}
24
+ }}
25
+ }}""",
26
+ "InChIKey": """query ByInChIKey($inchikey: String!, $limit: Int = {}) {{
27
+ molecules(InChIKey: $inchikey, limit: $limit) {{
28
+ {}
29
+ }}
30
+ }}""",
31
+ "CID": """query ByCID($cid: Int!) {{
32
+ molecules(CID: $cid) {{
33
+ {}
34
+ }}
35
+ }}"""
36
+ }
37
+
38
+ SUPPORTED_RETURN_FIELDS = ["CID", "IUPAC", "SMILES", "InChI", "InChIKey", "synonyms"]
39
+ API_URL = os.getenv('API_URL')
40
+
41
+ class DbProcessor:
42
+ def __init__(self, url: str = API_URL) -> None:
43
+ self.url = url
44
+
45
+ def request_data(self, text_input: str, query_type: str, return_fields: List[str], limit: int = 1):
46
+ if query_type not in query_templates:
47
+ raise ValueError(f"Query type '{query_type}' is not supported.")
48
+
49
+ for field in return_fields:
50
+ if field not in SUPPORTED_RETURN_FIELDS:
51
+ raise RuntimeError(f"Field '{field}' is not supported, try to use one from {SUPPORTED_RETURN_FIELDS}")
52
+
53
+ return_fields_str = "\n".join(return_fields)
54
+
55
+ query = query_templates[query_type].format(limit, return_fields_str)
56
+ variables = {query_type.lower(): text_input}
57
+
58
+ payload = {
59
+ "query": query,
60
+ "variables": variables
61
+ }
62
+
63
+ response = requests.post(
64
+ url=f"{self.url}/{query_type.lower()}",
65
+ json=payload
66
+ )
67
+
68
+ response.raise_for_status()
69
+
70
+ return response.json()['molecules'][0]