Yossefahmed68 commited on
Commit
4475814
1 Parent(s): 5f46f55
Files changed (1) hide show
  1. Daily med +73 -0
Daily med ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import re
3
+ import xml.etree.ElementTree as ET
4
+
5
+ # Documentation to follow: https://dailymed.nlm.nih.gov/dailymed/webservices-help/v2/spls_setid_api.cfm
6
+
7
+ # Set up the drug object
8
+ class Drug:
9
+ def __init__(self, name):
10
+ self.name = name
11
+ self.spl = self.request_spls(name_type='both', return_format='json')
12
+ self.spl_xml = self.request_spl_xml()
13
+
14
+ # Helper
15
+ def extract_text_in_parentheses(self, text):
16
+ pattern = r'\((.*?)\)' # Regular expression pattern to match text within parentheses
17
+ match = re.search(pattern, text)
18
+ if match:
19
+ return match.group(1)
20
+ return None
21
+
22
+ def request_spls(self, name_type='both', return_format='json'):
23
+ base_url = 'https://dailymed.nlm.nih.gov/dailymed/services/v2/spls'
24
+ endpoint = f'{base_url}.{return_format}'
25
+
26
+ params = {
27
+ 'drug_name': self.extract_text_in_parentheses(self.name),
28
+ 'name_type': name_type
29
+ }
30
+
31
+ response = requests.get(endpoint, params=params)
32
+
33
+ if response.status_code == 200:
34
+ return response.json() if return_format == 'json' else response.text
35
+ else:
36
+ print(f'Request failed with status code {response.status_code}.')
37
+ return None
38
+
39
+ def request_spl_xml(self):
40
+ if self.spl is None:
41
+ return None
42
+
43
+ set_id = self.spl['data'][0]['setid']
44
+
45
+ endpoint = f'https://dailymed.nlm.nih.gov/dailymed/services/v2/spls/{set_id}.xml'
46
+
47
+ response = requests.get(endpoint)
48
+
49
+ if response.status_code == 200:
50
+ return response.text
51
+ else:
52
+ print(f'Request failed with status code {response.status_code}.')
53
+ return None
54
+
55
+ def traverse_xml(self):
56
+ if self.spl_xml is None:
57
+ return None
58
+ root = ET.fromstring(self.request_spl_xml())
59
+ namespaces = {'ns': 'urn:hl7-org:v3'}
60
+ ingredients = root.findall('.//ns:ingredient', namespaces=namespaces)
61
+ ingredient_data = []
62
+ for ingredient in ingredients:
63
+ ingredient_data.append({
64
+ 'name': ingredient.find('.//ns:quantity/ns:ingredientSubstance', namespaces=namespaces),
65
+ #'strength': ingredient.find('.//ns:strength', namespaces=namespaces).text,
66
+ #'code': ingredient.find('.//ns:code', namespaces=namespaces).attrib['code']
67
+ })
68
+ return ingredient_data
69
+
70
+ ###### Testing the function outputs ######
71
+ # drug = Drug('drospirenone-ethinyl estradiol (YAZ) 3-0.02 MG per tablet')
72
+ # n = Drug.traverse_xml(drug)
73
+ # print(n)