Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import hf_hub_download
|
| 2 |
+
from transformers import ViTForImageClassification, AutoImageProcessor
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from fastapi import FastAPI, File, UploadFile
|
| 7 |
+
from transformers import ViTForImageClassification, AutoImageProcessor
|
| 8 |
+
import io
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
model_file = hf_hub_download(
|
| 13 |
+
repo_id="iwin10s/leak-detection-model",
|
| 14 |
+
filename="model.safetensors"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
processor_config = hf_hub_download(
|
| 18 |
+
repo_id="iwin10s/leak-detection-model",
|
| 19 |
+
filename="preprocessor_config.json"
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# Load model & processor
|
| 23 |
+
processor = AutoImageProcessor.from_pretrained("iwin10s/leak-detection-model")
|
| 24 |
+
model = ViTForImageClassification.from_pretrained(
|
| 25 |
+
pretrained_model_name_or_path="iwin10s/leak-detection-model",
|
| 26 |
+
local_files_only=False
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
app = FastAPI()
|
| 30 |
+
|
| 31 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 32 |
+
model.to(device)
|
| 33 |
+
model.eval()
|
| 34 |
+
|
| 35 |
+
@app.post("/predict")
|
| 36 |
+
async def predict(file: UploadFile = File(...)):
|
| 37 |
+
data = await file.read()
|
| 38 |
+
|
| 39 |
+
img = Image.open(io.BytesIO(data)).convert("RGB")
|
| 40 |
+
inputs = processor(images=img, return_tensors="pt")
|
| 41 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 42 |
+
|
| 43 |
+
with torch.no_grad():
|
| 44 |
+
outputs = model(**inputs)
|
| 45 |
+
probs = torch.softmax(outputs.logits, dim=-1).cpu().numpy()[0]
|
| 46 |
+
|
| 47 |
+
return {"leak_probability": float(probs[1])}
|