File size: 11,916 Bytes
682caaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import requests
import json
from typing import List, Dict, Optional
from datetime import datetime

class HAPIFHIRClient:
    """
    Client for connecting to HAPI FHIR Test Server
    """
    
    def __init__(self, base_url: str = "https://hapi.fhir.org/baseR4"):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/fhir+json',
            'Accept': 'application/fhir+json'
        })
    
    def get_patients(self, limit: int = 50) -> List[Dict]:
        """
        Fetch patients from HAPI FHIR Test Server
        """
        try:
            url = f"{self.base_url}/Patient"
            params = {
                '_count': limit,
                '_format': 'json'
            }
            
            response = self.session.get(url, params=params)
            response.raise_for_status()
            
            data = response.json()
            patients = []
            
            if 'entry' in data:
                for entry in data['entry']:
                    patient = self._parse_patient(entry['resource'])
                    if patient:
                        patients.append(patient)
            
            return patients
            
        except requests.RequestException as e:
            print(f"Error fetching patients: {e}")
            return []
    
    def get_patient_by_id(self, patient_id: str) -> Optional[Dict]:
        """
        Fetch a specific patient by ID
        """
        try:
            url = f"{self.base_url}/Patient/{patient_id}"
            response = self.session.get(url)
            response.raise_for_status()
            
            patient_data = response.json()
            return self._parse_patient(patient_data)
            
        except requests.RequestException as e:
            print(f"Error fetching patient {patient_id}: {e}")
            return None
    
    def get_patient_observations(self, patient_id: str) -> List[Dict]:
        """
        Fetch observations (vital signs, lab results) for a patient
        """
        try:
            url = f"{self.base_url}/Observation"
            params = {
                'subject': f"Patient/{patient_id}",
                '_count': 100,
                '_format': 'json'
            }
            
            response = self.session.get(url, params=params)
            response.raise_for_status()
            
            data = response.json()
            observations = []
            
            if 'entry' in data:
                for entry in data['entry']:
                    observation = self._parse_observation(entry['resource'])
                    if observation:
                        observations.append(observation)
            
            return observations
            
        except requests.RequestException as e:
            print(f"Error fetching observations for patient {patient_id}: {e}")
            return []
    
    def get_patient_medications(self, patient_id: str) -> List[Dict]:
        """
        Fetch medications for a patient
        """
        try:
            url = f"{self.base_url}/MedicationRequest"
            params = {
                'subject': f"Patient/{patient_id}",
                '_count': 100,
                '_format': 'json'
            }
            
            response = self.session.get(url, params=params)
            response.raise_for_status()
            
            data = response.json()
            medications = []
            
            if 'entry' in data:
                for entry in data['entry']:
                    medication = self._parse_medication(entry['resource'])
                    if medication:
                        medications.append(medication)
            
            return medications
            
        except requests.RequestException as e:
            print(f"Error fetching medications for patient {patient_id}: {e}")
            return []
    
    def get_patient_conditions(self, patient_id: str) -> List[Dict]:
        """
        Fetch conditions (diagnoses) for a patient
        """
        try:
            url = f"{self.base_url}/Condition"
            params = {
                'subject': f"Patient/{patient_id}",
                '_count': 100,
                '_format': 'json'
            }
            
            response = self.session.get(url, params=params)
            response.raise_for_status()
            
            data = response.json()
            conditions = []
            
            if 'entry' in data:
                for entry in data['entry']:
                    condition = self._parse_condition(entry['resource'])
                    if condition:
                        conditions.append(condition)
            
            return conditions
            
        except requests.RequestException as e:
            print(f"Error fetching conditions for patient {patient_id}: {e}")
            return []
    
    def _parse_patient(self, patient_data: Dict) -> Optional[Dict]:
        """
        Parse FHIR Patient resource into our format
        """
        try:
            # Extract basic demographics
            name = ""
            if 'name' in patient_data and patient_data['name']:
                name_parts = patient_data['name'][0]
                given = name_parts.get('given', [])
                family = name_parts.get('family', '')
                name = f"{' '.join(given)} {family}".strip()
            
            # Extract address
            address = ""
            if 'address' in patient_data and patient_data['address']:
                addr = patient_data['address'][0]
                line = addr.get('line', [])
                city = addr.get('city', '')
                state = addr.get('state', '')
                postal_code = addr.get('postalCode', '')
                address = f"{', '.join(line)}, {city}, {state} {postal_code}".strip()
            
            # Extract contact info
            phone = ""
            email = ""
            if 'telecom' in patient_data:
                for telecom in patient_data['telecom']:
                    if telecom.get('system') == 'phone':
                        phone = telecom.get('value', '')
                    elif telecom.get('system') == 'email':
                        email = telecom.get('value', '')
            
            return {
                'id': patient_data.get('id', ''),
                'fhir_id': patient_data.get('id', ''),
                'full_name': name,
                'gender': patient_data.get('gender', 'unknown'),
                'date_of_birth': patient_data.get('birthDate', ''),
                'address': address,
                'phone': phone,
                'email': email,
                'marital_status': self._get_marital_status(patient_data),
                'language': self._get_language(patient_data),
                'source': 'hapi_fhir',
                'status': 'active',
                'created_at': datetime.now().isoformat(),
                'updated_at': datetime.now().isoformat()
            }
            
        except Exception as e:
            print(f"Error parsing patient data: {e}")
            return None
    
    def _parse_observation(self, observation_data: Dict) -> Optional[Dict]:
        """
        Parse FHIR Observation resource
        """
        try:
            code = observation_data.get('code', {})
            coding = code.get('coding', [])
            code_text = code.get('text', '')
            
            if coding:
                code_text = coding[0].get('display', code_text)
            
            value = observation_data.get('valueQuantity', {})
            unit = value.get('unit', '')
            value_amount = value.get('value', '')
            
            return {
                'id': observation_data.get('id', ''),
                'code': code_text,
                'value': f"{value_amount} {unit}".strip(),
                'date': observation_data.get('effectiveDateTime', ''),
                'category': self._get_observation_category(observation_data)
            }
            
        except Exception as e:
            print(f"Error parsing observation: {e}")
            return None
    
    def _parse_medication(self, medication_data: Dict) -> Optional[Dict]:
        """
        Parse FHIR MedicationRequest resource
        """
        try:
            medication = medication_data.get('medicationCodeableConcept', {})
            coding = medication.get('coding', [])
            name = medication.get('text', '')
            
            if coding:
                name = coding[0].get('display', name)
            
            dosage = medication_data.get('dosageInstruction', [])
            dosage_text = ""
            if dosage:
                dosage_text = dosage[0].get('text', '')
            
            return {
                'id': medication_data.get('id', ''),
                'name': name,
                'dosage': dosage_text,
                'status': medication_data.get('status', 'active'),
                'prescribed_date': medication_data.get('authoredOn', ''),
                'requester': self._get_practitioner_name(medication_data)
            }
            
        except Exception as e:
            print(f"Error parsing medication: {e}")
            return None
    
    def _parse_condition(self, condition_data: Dict) -> Optional[Dict]:
        """
        Parse FHIR Condition resource
        """
        try:
            code = condition_data.get('code', {})
            coding = code.get('coding', [])
            name = code.get('text', '')
            
            if coding:
                name = coding[0].get('display', name)
            
            return {
                'id': condition_data.get('id', ''),
                'code': name,
                'status': condition_data.get('clinicalStatus', {}).get('coding', [{}])[0].get('code', 'active'),
                'onset_date': condition_data.get('onsetDateTime', ''),
                'recorded_date': condition_data.get('recordedDate', ''),
                'notes': condition_data.get('note', [{}])[0].get('text', '') if condition_data.get('note') else ''
            }
            
        except Exception as e:
            print(f"Error parsing condition: {e}")
            return None
    
    def _get_marital_status(self, patient_data: Dict) -> str:
        """Extract marital status from patient data"""
        if 'maritalStatus' in patient_data:
            coding = patient_data['maritalStatus'].get('coding', [])
            if coding:
                return coding[0].get('display', 'Unknown')
        return 'Unknown'
    
    def _get_language(self, patient_data: Dict) -> str:
        """Extract language from patient data"""
        if 'communication' in patient_data and patient_data['communication']:
            language = patient_data['communication'][0].get('language', {})
            coding = language.get('coding', [])
            if coding:
                return coding[0].get('display', 'English')
        return 'English'
    
    def _get_observation_category(self, observation_data: Dict) -> str:
        """Extract observation category"""
        category = observation_data.get('category', {})
        coding = category.get('coding', [])
        if coding:
            return coding[0].get('display', 'Unknown')
        return 'Unknown'
    
    def _get_practitioner_name(self, medication_data: Dict) -> str:
        """Extract practitioner name from medication request"""
        requester = medication_data.get('requester', {})
        reference = requester.get('reference', '')
        if reference.startswith('Practitioner/'):
            # In a real implementation, you'd fetch the practitioner details
            return 'Dr. Practitioner'
        return 'Unknown'