Initial commit for FastAPI backend
Browse files- Dockerfile +20 -0
- backend.py +75 -0
- build_index.py +34 -0
- fetch_data.py +37 -0
- requirements.txt +9 -0
Dockerfile
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use a lightweight base image with Python 3.11
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set the working directory inside the container
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
|
| 7 |
+
# Copy the requirements file to the container
|
| 8 |
+
COPY requirements.txt .
|
| 9 |
+
|
| 10 |
+
# Install the Python dependencies
|
| 11 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 12 |
+
|
| 13 |
+
# Copy all backend files into the container
|
| 14 |
+
COPY . .
|
| 15 |
+
|
| 16 |
+
# Expose port 8000 for the FastAPI backend
|
| 17 |
+
EXPOSE 8000
|
| 18 |
+
|
| 19 |
+
# Command to run the FastAPI backend using uvicorn
|
| 20 |
+
CMD ["uvicorn", "backend:app", "--host", "0.0.0.0", "--port", "8000"]
|
backend.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
import requests, json, redis, spacy
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# Initialize FastAPI app
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
# Set up Redis client (update host/port as needed)
|
| 10 |
+
redis_client = redis.Redis(host='localhost', port=6379, db=0)
|
| 11 |
+
|
| 12 |
+
# Load SpaCy model for drug extraction
|
| 13 |
+
try:
|
| 14 |
+
import spacy
|
| 15 |
+
nlp = spacy.load("en_core_web_sm")
|
| 16 |
+
except Exception as e:
|
| 17 |
+
raise Exception("SpaCy model 'en_core_web_sm' not found. Install it with: python -m spacy download en_core_web_sm") from e
|
| 18 |
+
|
| 19 |
+
class QueryRequest(BaseModel):
|
| 20 |
+
query: str
|
| 21 |
+
|
| 22 |
+
def extract_drug_name(query: str):
|
| 23 |
+
doc = nlp(query)
|
| 24 |
+
for ent in doc.ents:
|
| 25 |
+
if ent.label_ in ["DRUG", "PRODUCT", "CHEMICAL"]:
|
| 26 |
+
return ent.text
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
def fetch_fda_data(drug_name: str):
|
| 30 |
+
cache_key = f"fda:{drug_name.lower()}"
|
| 31 |
+
cached = redis_client.get(cache_key)
|
| 32 |
+
if cached:
|
| 33 |
+
return json.loads(cached)
|
| 34 |
+
url = f'https://api.fda.gov/drug/label.json?search=openfda.brand_name:"{drug_name}"&limit=1'
|
| 35 |
+
response = requests.get(url)
|
| 36 |
+
if response.status_code == 200:
|
| 37 |
+
data = response.json()
|
| 38 |
+
if "results" in data:
|
| 39 |
+
redis_client.setex(cache_key, 3600, json.dumps(data["results"][0]))
|
| 40 |
+
return data["results"][0]
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
def format_text_to_markdown(text: str) -> str:
|
| 44 |
+
# This function transforms raw text into Markdown format (simple conversion)
|
| 45 |
+
return "### Formatted Information\n\n- " + text.replace(". ", ".\n\n- ")
|
| 46 |
+
|
| 47 |
+
@app.post("/query")
|
| 48 |
+
def process_query(request: QueryRequest):
|
| 49 |
+
drug_name = extract_drug_name(request.query)
|
| 50 |
+
if not drug_name:
|
| 51 |
+
raise HTTPException(status_code=400, detail="No drug name detected in query.")
|
| 52 |
+
drug_data = fetch_fda_data(drug_name)
|
| 53 |
+
if not drug_data:
|
| 54 |
+
raise HTTPException(status_code=404, detail="Drug data not found.")
|
| 55 |
+
|
| 56 |
+
# Identify the relevant JSON field based on query keywords
|
| 57 |
+
relevant_field = None
|
| 58 |
+
keywords = {
|
| 59 |
+
"side effects": "adverse_reactions",
|
| 60 |
+
"warnings": "warnings",
|
| 61 |
+
"dosage": "dosage_and_administration",
|
| 62 |
+
"indications": "indications_and_usage",
|
| 63 |
+
"contraindications": "contraindications",
|
| 64 |
+
"interactions": "drug_interactions"
|
| 65 |
+
}
|
| 66 |
+
query_lower = request.query.lower()
|
| 67 |
+
for k, field in keywords.items():
|
| 68 |
+
if k in query_lower and field in drug_data:
|
| 69 |
+
relevant_field = field
|
| 70 |
+
break
|
| 71 |
+
|
| 72 |
+
# Use the specific field if found, otherwise fallback to the whole JSON
|
| 73 |
+
text_to_format = drug_data.get(relevant_field, json.dumps(drug_data, indent=4))
|
| 74 |
+
formatted_text = format_text_to_markdown(text_to_format)
|
| 75 |
+
return {"drug_name": drug_name, "formatted_text": formatted_text}
|
build_index.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, StorageContext, load_index_from_storage
|
| 3 |
+
from llama_index.embeddings.huggingface_embed import HuggingFaceEmbedding # Use the correct module path
|
| 4 |
+
|
| 5 |
+
# Ensure storage directory exists
|
| 6 |
+
storage_path = "./storage"
|
| 7 |
+
os.makedirs(storage_path, exist_ok=True)
|
| 8 |
+
|
| 9 |
+
# Load embedding model
|
| 10 |
+
embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 11 |
+
|
| 12 |
+
def build_index():
|
| 13 |
+
print("Indexing new drug data...")
|
| 14 |
+
if not os.path.exists("data") or not os.listdir("data"):
|
| 15 |
+
print("No new data found to index.")
|
| 16 |
+
return
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
# Load JSON documents from 'data/' folder
|
| 20 |
+
documents = SimpleDirectoryReader("data", file_extractor={".json": "json"}).load_data()
|
| 21 |
+
|
| 22 |
+
if not documents:
|
| 23 |
+
print("No valid documents found for indexing.")
|
| 24 |
+
return
|
| 25 |
+
|
| 26 |
+
# Create a vector index from the documents
|
| 27 |
+
index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)
|
| 28 |
+
index.storage_context.persist(persist_dir=storage_path)
|
| 29 |
+
print("Index successfully updated and saved to './storage'.")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"Error while building index: {e}")
|
| 32 |
+
|
| 33 |
+
build_index()
|
| 34 |
+
print("LlamaIndex is ready for querying!")
|
fetch_data.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
def fetch_drug_label(drug_name):
|
| 7 |
+
"""
|
| 8 |
+
Fetch FDA drug label information for the given drug name from the FDA Open Data API
|
| 9 |
+
and save it as a JSON file in the 'data/' folder.
|
| 10 |
+
"""
|
| 11 |
+
url = f'https://api.fda.gov/drug/label.json?search=openfda.brand_name:"{drug_name}"&limit=1'
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
response = requests.get(url)
|
| 15 |
+
response.raise_for_status() # Raise an error for HTTP issues
|
| 16 |
+
data = response.json()
|
| 17 |
+
|
| 18 |
+
if 'results' in data and data.get('results'):
|
| 19 |
+
result = data['results'][0] # Use the first result
|
| 20 |
+
|
| 21 |
+
# Create a safe filename for the drug
|
| 22 |
+
safe_drug_name = re.sub(r'\W+', '_', drug_name.lower())
|
| 23 |
+
os.makedirs("data", exist_ok=True)
|
| 24 |
+
json_file_path = f"data/{safe_drug_name}_label.json"
|
| 25 |
+
|
| 26 |
+
with open(json_file_path, "w", encoding="utf-8") as json_file:
|
| 27 |
+
json.dump(result, json_file, indent=4, ensure_ascii=False)
|
| 28 |
+
|
| 29 |
+
print(f"Drug label information saved for {drug_name} ({json_file_path})")
|
| 30 |
+
return json_file_path
|
| 31 |
+
else:
|
| 32 |
+
print(f"No data found for {drug_name}.")
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
except requests.exceptions.RequestException as e:
|
| 36 |
+
print(f"Error fetching data for {drug_name}: {e}")
|
| 37 |
+
return None
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
requests
|
| 4 |
+
redis
|
| 5 |
+
spacy
|
| 6 |
+
llama-index
|
| 7 |
+
llama-index-core
|
| 8 |
+
llama-index-embeddings-huggingface
|
| 9 |
+
pydantic
|