Create umls.py
Browse files- mcp/umls.py +34 -0
mcp/umls.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mcp/umls.py
|
| 2 |
+
|
| 3 |
+
import httpx
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
UMLS_API_KEY = os.environ.get("UMLS_KEY")
|
| 7 |
+
UMLS_AUTH = "https://utslogin.nlm.nih.gov/cas/v1/api-key"
|
| 8 |
+
UMLS_SEARCH = "https://uts-ws.nlm.nih.gov/rest/search/current"
|
| 9 |
+
|
| 10 |
+
async def _get_umls_ticket():
|
| 11 |
+
async with httpx.AsyncClient() as client:
|
| 12 |
+
resp = await client.post(UMLS_AUTH, data={"apikey": UMLS_API_KEY})
|
| 13 |
+
if resp.status_code != 201:
|
| 14 |
+
raise Exception("UMLS Authentication Failed")
|
| 15 |
+
tgt = resp.text.split('action="')[1].split('"')[0]
|
| 16 |
+
ticket_resp = await client.post(tgt, data={"service": "http://umlsks.nlm.nih.gov"})
|
| 17 |
+
return ticket_resp.text
|
| 18 |
+
|
| 19 |
+
async def lookup_umls(term: str):
|
| 20 |
+
ticket = await _get_umls_ticket()
|
| 21 |
+
params = {
|
| 22 |
+
"string": term,
|
| 23 |
+
"ticket": ticket,
|
| 24 |
+
"pageSize": 1,
|
| 25 |
+
}
|
| 26 |
+
async with httpx.AsyncClient() as client:
|
| 27 |
+
resp = await client.get(UMLS_SEARCH, params=params)
|
| 28 |
+
items = resp.json().get("result", {}).get("results", [])
|
| 29 |
+
if items:
|
| 30 |
+
cui = items[0].get("ui")
|
| 31 |
+
name = items[0].get("name")
|
| 32 |
+
definition = items[0].get("rootSource")
|
| 33 |
+
return {"term": term, "cui": cui, "name": name, "definition": definition}
|
| 34 |
+
return {"term": term, "cui": None, "name": None, "definition": None}
|