Spaces:
Sleeping
Sleeping
update of hg space
Browse files- README.md +0 -11
- radio_check_app.py +67 -8
README.md
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Demoday Fastapi
|
| 3 |
-
emoji: 📊
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: blue
|
| 6 |
-
sdk: docker
|
| 7 |
-
pinned: false
|
| 8 |
-
license: apache-2.0
|
| 9 |
-
---
|
| 10 |
-
|
| 11 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
radio_check_app.py
CHANGED
|
@@ -1,5 +1,9 @@
|
|
| 1 |
import os
|
| 2 |
import io
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import torch
|
| 4 |
import torch.nn.functional as F
|
| 5 |
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
|
@@ -11,35 +15,38 @@ from health_multimodal.image.data.transforms import create_chest_xray_transform_
|
|
| 11 |
|
| 12 |
app = FastAPI(title="BioVil Cross-Attention+MLP Inference API")
|
| 13 |
|
| 14 |
-
# Global instances
|
| 15 |
device = None
|
| 16 |
tokenizer = None
|
| 17 |
text_model = None
|
| 18 |
image_model = None
|
| 19 |
image_transform = None
|
| 20 |
cross_att_classifier = None
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
#
|
| 23 |
@app.on_event("startup")
|
| 24 |
def load_all_models_and_assets():
|
| 25 |
-
global device, tokenizer, text_model, image_model, image_transform, cross_att_classifier
|
| 26 |
try:
|
| 27 |
# Setup device configuration
|
| 28 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 29 |
print(f"Using device: {device}")
|
| 30 |
|
|
|
|
|
|
|
|
|
|
| 31 |
# Load the comprehensive BioViL-T repo for Text
|
| 32 |
model_id = "microsoft/BiomedVLP-BioViL-T"
|
| 33 |
|
| 34 |
# Specialized CXR-BERT tokenizer and model
|
| 35 |
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 36 |
text_model = AutoModel.from_pretrained(model_id, trust_remote_code=True).to(device)
|
| 37 |
-
text_model.eval()
|
| 38 |
|
| 39 |
# Instantiate the BioViL-T Image Engine
|
| 40 |
image_model = get_biovil_t_image_encoder().to(device)
|
| 41 |
image_transform = create_chest_xray_transform_for_inference(resize=512, center_crop_size=448)
|
| 42 |
-
image_model.eval()
|
| 43 |
|
| 44 |
# Connect to Hugging Face MLflow instance and pull the Cross-Attention Classifier
|
| 45 |
mlflow.set_tracking_uri(os.environ.get("APP_URI"))
|
|
@@ -48,12 +55,51 @@ def load_all_models_and_assets():
|
|
| 48 |
cross_att_classifier = mlflow.pytorch.load_model(model_uri, map_location=torch.device('cpu'))
|
| 49 |
cross_att_classifier.to(device).eval()
|
| 50 |
|
| 51 |
-
print("
|
| 52 |
except Exception as e:
|
| 53 |
print(f"❌ Startup Error: {str(e)}")
|
| 54 |
raise e
|
| 55 |
|
| 56 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def get_text_embeddings(report_text):
|
| 58 |
inputs = tokenizer(
|
| 59 |
report_text,
|
|
@@ -80,9 +126,10 @@ def get_image_embeddings_from_pil(pil_image):
|
|
| 80 |
image_outputs = image_model(processed_tensor)
|
| 81 |
return image_outputs.projected_patch_embeddings
|
| 82 |
|
| 83 |
-
#
|
| 84 |
@app.post("/predict")
|
| 85 |
async def predict(
|
|
|
|
| 86 |
text_input: str = Form(...),
|
| 87 |
image_file: UploadFile = File(...)
|
| 88 |
):
|
|
@@ -105,6 +152,18 @@ async def predict(
|
|
| 105 |
probability = torch.sigmoid(outputs).item()
|
| 106 |
prediction = int(probability >= 0.5)
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
# Return JSON response back to Streamlit
|
| 109 |
return {
|
| 110 |
"status": "success",
|
|
|
|
| 1 |
import os
|
| 2 |
import io
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import boto3
|
| 5 |
+
import uuid
|
| 6 |
+
import json
|
| 7 |
import torch
|
| 8 |
import torch.nn.functional as F
|
| 9 |
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
|
|
|
| 15 |
|
| 16 |
app = FastAPI(title="BioVil Cross-Attention+MLP Inference API")
|
| 17 |
|
| 18 |
+
# Global instances
|
| 19 |
device = None
|
| 20 |
tokenizer = None
|
| 21 |
text_model = None
|
| 22 |
image_model = None
|
| 23 |
image_transform = None
|
| 24 |
cross_att_classifier = None
|
| 25 |
+
s3_client = None
|
| 26 |
+
S3_BUCKET_NAME = os.environ.get("S3_MONITORING_BUCKET", "smec-lead-fp-mlops-monitoring")
|
| 27 |
|
| 28 |
+
# Startup component
|
| 29 |
@app.on_event("startup")
|
| 30 |
def load_all_models_and_assets():
|
| 31 |
+
global device, tokenizer, text_model, image_model, image_transform, cross_att_classifier, s3_client
|
| 32 |
try:
|
| 33 |
# Setup device configuration
|
| 34 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 35 |
print(f"Using device: {device}")
|
| 36 |
|
| 37 |
+
# Initialize S3 Client
|
| 38 |
+
s3_client = boto3.client("s3")
|
| 39 |
+
|
| 40 |
# Load the comprehensive BioViL-T repo for Text
|
| 41 |
model_id = "microsoft/BiomedVLP-BioViL-T"
|
| 42 |
|
| 43 |
# Specialized CXR-BERT tokenizer and model
|
| 44 |
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 45 |
text_model = AutoModel.from_pretrained(model_id, trust_remote_code=True).to(device)
|
|
|
|
| 46 |
|
| 47 |
# Instantiate the BioViL-T Image Engine
|
| 48 |
image_model = get_biovil_t_image_encoder().to(device)
|
| 49 |
image_transform = create_chest_xray_transform_for_inference(resize=512, center_crop_size=448)
|
|
|
|
| 50 |
|
| 51 |
# Connect to Hugging Face MLflow instance and pull the Cross-Attention Classifier
|
| 52 |
mlflow.set_tracking_uri(os.environ.get("APP_URI"))
|
|
|
|
| 55 |
cross_att_classifier = mlflow.pytorch.load_model(model_uri, map_location=torch.device('cpu'))
|
| 56 |
cross_att_classifier.to(device).eval()
|
| 57 |
|
| 58 |
+
print("Models and processors loaded successfully!")
|
| 59 |
except Exception as e:
|
| 60 |
print(f"❌ Startup Error: {str(e)}")
|
| 61 |
raise e
|
| 62 |
|
| 63 |
+
# Background task for S3 logging
|
| 64 |
+
def save_production_data_to_s3(
|
| 65 |
+
request_id: str,
|
| 66 |
+
raw_text: str,
|
| 67 |
+
image_bytes: bytes,
|
| 68 |
+
prediction: int,
|
| 69 |
+
probability: float
|
| 70 |
+
):
|
| 71 |
+
try:
|
| 72 |
+
# 1. Save raw Image file to S3
|
| 73 |
+
image_s3_key = f"production_data/images/{request_id}.jpg"
|
| 74 |
+
s3_client.put_object(
|
| 75 |
+
Bucket=S3_BUCKET_NAME,
|
| 76 |
+
Key=image_s3_key,
|
| 77 |
+
Body=image_bytes,
|
| 78 |
+
ContentType="image/jpg"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# 2. Save Metadata & Text to S3 as JSON (for Evidently AI reading)
|
| 82 |
+
metadata = {
|
| 83 |
+
"request_id": request_id,
|
| 84 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 85 |
+
"raw_text": raw_text,
|
| 86 |
+
"image_s3_uri": f"s3://{S3_BUCKET_NAME}/{image_s3_key}",
|
| 87 |
+
"prediction": prediction,
|
| 88 |
+
"probability": probability
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
metadata_s3_key = f"production_data/reports_metadata/{request_id}.json"
|
| 92 |
+
s3_client.put_object(
|
| 93 |
+
Bucket=S3_BUCKET_NAME,
|
| 94 |
+
Key=metadata_s3_key,
|
| 95 |
+
Body=json.dumps(metadata),
|
| 96 |
+
ContentType="application/json"
|
| 97 |
+
)
|
| 98 |
+
print(f"Logged request {request_id} to S3 successfully.")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f" Failed to log to S3 for request {request_id}: {str(e)}")
|
| 101 |
+
|
| 102 |
+
# Preprocessing pipelines
|
| 103 |
def get_text_embeddings(report_text):
|
| 104 |
inputs = tokenizer(
|
| 105 |
report_text,
|
|
|
|
| 126 |
image_outputs = image_model(processed_tensor)
|
| 127 |
return image_outputs.projected_patch_embeddings
|
| 128 |
|
| 129 |
+
# Predict endpoint
|
| 130 |
@app.post("/predict")
|
| 131 |
async def predict(
|
| 132 |
+
background_tasks: BackgroundTasks,
|
| 133 |
text_input: str = Form(...),
|
| 134 |
image_file: UploadFile = File(...)
|
| 135 |
):
|
|
|
|
| 152 |
probability = torch.sigmoid(outputs).item()
|
| 153 |
prediction = int(probability >= 0.5)
|
| 154 |
|
| 155 |
+
# Generate unique ID for matching image and metadata in S3
|
| 156 |
+
request_id = str(uuid.uuid4())
|
| 157 |
+
|
| 158 |
+
# Schedule S3 upload in background (Executes AFTER function returns)
|
| 159 |
+
background_tasks.add_task(
|
| 160 |
+
save_production_data_to_s3,
|
| 161 |
+
request_id=request_id,
|
| 162 |
+
raw_text=text_input,
|
| 163 |
+
image_bytes=image_bytes,
|
| 164 |
+
prediction=prediction,
|
| 165 |
+
probability=probability
|
| 166 |
+
)
|
| 167 |
# Return JSON response back to Streamlit
|
| 168 |
return {
|
| 169 |
"status": "success",
|