Spaces:
Sleeping
Sleeping
Update api_clients/umls_client.py
Browse files- api_clients/umls_client.py +45 -0
api_clients/umls_client.py
CHANGED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# api_clients/umls_client.py
|
| 2 |
+
"""
|
| 3 |
+
Client for the NLM Unified Medical Language System (UMLS) API.
|
| 4 |
+
Handles the complex ticket-based authentication.
|
| 5 |
+
"""
|
| 6 |
+
import aiohttp
|
| 7 |
+
from lxml import html
|
| 8 |
+
from .config import UMLS_API_KEY, UMLS_AUTH_URL, UMLS_BASE_URL, REQUEST_HEADERS
|
| 9 |
+
|
| 10 |
+
class UMLSClient:
|
| 11 |
+
def __init__(self, session: aiohttp.ClientSession):
|
| 12 |
+
self.session = session
|
| 13 |
+
self.service_ticket = None
|
| 14 |
+
|
| 15 |
+
async def authenticate(self):
|
| 16 |
+
"""Gets a single-use service ticket for API requests."""
|
| 17 |
+
if not UMLS_API_KEY:
|
| 18 |
+
print("Warning: UMLS_API_KEY not found. UMLS features will be disabled.")
|
| 19 |
+
return False
|
| 20 |
+
params = {'apikey': UMLS_API_KEY}
|
| 21 |
+
async with self.session.post(UMLS_AUTH_URL, data=params, headers=REQUEST_HEADERS) as resp:
|
| 22 |
+
if resp.status == 201:
|
| 23 |
+
response_text = await resp.text()
|
| 24 |
+
self.service_ticket = html.fromstring(response_text).find('.//form').get('action')
|
| 25 |
+
return True
|
| 26 |
+
else:
|
| 27 |
+
print(f"Error authenticating with UMLS: {resp.status}")
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
async def get_cui_for_term(self, term: str):
|
| 31 |
+
"""Searches for a Concept Unique Identifier (CUI) for a given term."""
|
| 32 |
+
if not await self.authenticate():
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
query = {'string': term, 'ticket': self.service_ticket}
|
| 36 |
+
url = f"{UMLS_BASE_URL}/search/current"
|
| 37 |
+
|
| 38 |
+
async with self.session.get(url, params=query, headers=REQUEST_HEADERS) as resp:
|
| 39 |
+
if resp.status == 200:
|
| 40 |
+
data = await resp.json()
|
| 41 |
+
results = data.get('result', {}).get('results', [])
|
| 42 |
+
return results[0] if results else None
|
| 43 |
+
else:
|
| 44 |
+
print(f"Error searching UMLS for term '{term}': {resp.status}")
|
| 45 |
+
return None
|