VelanAI / backend.py
dcsvelan's picture
Initial commit for FastAPI backend
2e13a13
Raw History Blame Contribute Delete
2.71 kB
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}