Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import joblib
|
4 |
+
import torch
|
5 |
+
from transformers import AutoTokenizer, AutoModelForQuestionAnswering, AutoModelForSequenceClassification
|
6 |
+
from fastapi import FastAPI, HTTPException
|
7 |
+
from pydantic import BaseModel
|
8 |
+
|
9 |
+
app = FastAPI()
|
10 |
+
|
11 |
+
# Utility to download files if not present locally
|
12 |
+
def download_file(url, dest):
|
13 |
+
if not os.path.exists(dest):
|
14 |
+
print(f"Downloading {url} to {dest}")
|
15 |
+
r = requests.get(url)
|
16 |
+
r.raise_for_status()
|
17 |
+
with open(dest, 'wb') as f:
|
18 |
+
f.write(r.content)
|
19 |
+
else:
|
20 |
+
print(f"File {dest} already exists.")
|
21 |
+
|
22 |
+
# ----------- Setup for BERT QA model (Virtual Consultation) ------------
|
23 |
+
|
24 |
+
qa_model_dir = "./bert_mini_squadv2_finetuned"
|
25 |
+
os.makedirs(qa_model_dir, exist_ok=True)
|
26 |
+
|
27 |
+
qa_files = {
|
28 |
+
"pytorch_model.bin": "https://huggingface.co/your-username/your-files-path/resolve/main/bert_mini_squadv2_finetuned/pytorch_model.bin",
|
29 |
+
"config.json": "https://huggingface.co/your-username/your-files-path/resolve/main/bert_mini_squadv2_finetuned/config.json",
|
30 |
+
"tokenizer_config.json": "https://huggingface.co/your-username/your-files-path/resolve/main/bert_mini_squadv2_finetuned/tokenizer_config.json",
|
31 |
+
"vocab.txt": "https://huggingface.co/your-username/your-files-path/resolve/main/bert_mini_squadv2_finetuned/vocab.txt",
|
32 |
+
}
|
33 |
+
|
34 |
+
for fname, furl in qa_files.items():
|
35 |
+
download_file(furl, os.path.join(qa_model_dir, fname))
|
36 |
+
|
37 |
+
tokenizer_qa = AutoTokenizer.from_pretrained(qa_model_dir)
|
38 |
+
model_qa = AutoModelForQuestionAnswering.from_pretrained(qa_model_dir)
|
39 |
+
|
40 |
+
# ----------- Setup for Diabetes XGBoost Model (Risk Prediction) ------------
|
41 |
+
|
42 |
+
diabetes_pkl_url = "https://huggingface.co/your-username/your-files-path/resolve/main/diabetes_xgboost_model.pkl"
|
43 |
+
diabetes_pkl_path = "./diabetes_xgboost_model.pkl"
|
44 |
+
download_file(diabetes_pkl_url, diabetes_pkl_path)
|
45 |
+
diabetes_model = joblib.load(diabetes_pkl_path)
|
46 |
+
|
47 |
+
# ----------- Setup for other features: load pretrained models directly ------------
|
48 |
+
|
49 |
+
from transformers import pipeline
|
50 |
+
|
51 |
+
# Monitoring & Alerts - Summarization using bert-mini finetuned on squad_v2
|
52 |
+
monitoring_model_id = "prajjwal1/bert-mini"
|
53 |
+
summarizer = pipeline("summarization", model=monitoring_model_id)
|
54 |
+
|
55 |
+
# Personalized Simulation - Bio_ClinicalBERT sequence classifier
|
56 |
+
personalized_model_id = "emilyalsentzer/Bio_ClinicalBERT"
|
57 |
+
personalized_tokenizer = AutoTokenizer.from_pretrained(personalized_model_id)
|
58 |
+
personalized_model = AutoModelForSequenceClassification.from_pretrained(personalized_model_id)
|
59 |
+
|
60 |
+
# --- Pydantic models for request validation ---
|
61 |
+
|
62 |
+
class QARequest(BaseModel):
|
63 |
+
question: str
|
64 |
+
context: str
|
65 |
+
|
66 |
+
class RiskPredictionRequest(BaseModel):
|
67 |
+
features: list # example: [age, bmi, blood_pressure, ...]
|
68 |
+
|
69 |
+
# --- API endpoints ---
|
70 |
+
|
71 |
+
@app.post("/virtual_consultation")
|
72 |
+
def virtual_consultation(data: QARequest):
|
73 |
+
inputs = tokenizer_qa(data.question, data.context, return_tensors="pt")
|
74 |
+
with torch.no_grad():
|
75 |
+
outputs = model_qa(**inputs)
|
76 |
+
answer_start = torch.argmax(outputs.start_logits)
|
77 |
+
answer_end = torch.argmax(outputs.end_logits) + 1
|
78 |
+
answer = tokenizer_qa.convert_tokens_to_string(
|
79 |
+
tokenizer_qa.convert_ids_to_tokens(inputs.input_ids[0][answer_start:answer_end])
|
80 |
+
)
|
81 |
+
return {"answer": answer}
|
82 |
+
|
83 |
+
@app.post("/risk_prediction")
|
84 |
+
def risk_prediction(data: RiskPredictionRequest):
|
85 |
+
import numpy as np
|
86 |
+
features = np.array(data.features).reshape(1, -1)
|
87 |
+
pred = diabetes_model.predict(features)
|
88 |
+
return {"risk_prediction": int(pred[0])}
|
89 |
+
|
90 |
+
@app.post("/monitoring_alerts")
|
91 |
+
def monitoring_alerts(text: str):
|
92 |
+
summary = summarizer(text, max_length=50, min_length=20, do_sample=False)
|
93 |
+
return {"summary": summary[0]['summary_text']}
|
94 |
+
|
95 |
+
@app.post("/personalized_simulation")
|
96 |
+
def personalized_simulation(text: str):
|
97 |
+
inputs = personalized_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
98 |
+
outputs = personalized_model(**inputs)
|
99 |
+
logits = outputs.logits.detach().numpy()
|
100 |
+
pred_label = logits.argmax()
|
101 |
+
return {"predicted_label": int(pred_label)}
|
102 |
+
|