File size: 2,710 Bytes
2e13a13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
import requests, json, redis, spacy
from pydantic import BaseModel
import os

# Initialize FastAPI app
app = FastAPI()

# Set up Redis client (update host/port as needed)
redis_client = redis.Redis(host='localhost', port=6379, db=0)

# Load SpaCy model for drug extraction
try:
    import spacy
    nlp = spacy.load("en_core_web_sm")
except Exception as e:
    raise Exception("SpaCy model 'en_core_web_sm' not found. Install it with: python -m spacy download en_core_web_sm") from e

class QueryRequest(BaseModel):
    query: str

def extract_drug_name(query: str):
    doc = nlp(query)
    for ent in doc.ents:
        if ent.label_ in ["DRUG", "PRODUCT", "CHEMICAL"]:
            return ent.text
    return None

def fetch_fda_data(drug_name: str):
    cache_key = f"fda:{drug_name.lower()}"
    cached = redis_client.get(cache_key)
    if cached:
        return json.loads(cached)
    url = f'https://api.fda.gov/drug/label.json?search=openfda.brand_name:"{drug_name}"&limit=1'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        if "results" in data:
            redis_client.setex(cache_key, 3600, json.dumps(data["results"][0]))
            return data["results"][0]
    return None

def format_text_to_markdown(text: str) -> str:
    # This function transforms raw text into Markdown format (simple conversion)
    return "### Formatted Information\n\n- " + text.replace(". ", ".\n\n- ")

@app.post("/query")
def process_query(request: QueryRequest):
    drug_name = extract_drug_name(request.query)
    if not drug_name:
        raise HTTPException(status_code=400, detail="No drug name detected in query.")
    drug_data = fetch_fda_data(drug_name)
    if not drug_data:
        raise HTTPException(status_code=404, detail="Drug data not found.")

    # Identify the relevant JSON field based on query keywords
    relevant_field = None
    keywords = {
        "side effects": "adverse_reactions",
        "warnings": "warnings",
        "dosage": "dosage_and_administration",
        "indications": "indications_and_usage",
        "contraindications": "contraindications",
        "interactions": "drug_interactions"
    }
    query_lower = request.query.lower()
    for k, field in keywords.items():
        if k in query_lower and field in drug_data:
            relevant_field = field
            break

    # Use the specific field if found, otherwise fallback to the whole JSON
    text_to_format = drug_data.get(relevant_field, json.dumps(drug_data, indent=4))
    formatted_text = format_text_to_markdown(text_to_format)
    return {"drug_name": drug_name, "formatted_text": formatted_text}