Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,47 +1,78 @@
|
|
|
|
|
| 1 |
import torch
|
|
|
|
| 2 |
from PIL import Image
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
token = os.environ.get("HF_TOKEN")
|
| 10 |
-
|
| 11 |
-
processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct", token=token)
|
| 12 |
-
model = AutoModelForVision2Seq.from_pretrained(
|
| 13 |
-
"HuggingFaceTB/SmolVLM-Instruct",
|
| 14 |
-
torch_dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32,
|
| 15 |
-
_attn_implementation="flash_attention_2" if DEVICE == "cuda" else "eager",
|
| 16 |
-
token=token
|
| 17 |
-
).to(DEVICE)
|
| 18 |
-
|
| 19 |
-
def describe_image(image):
|
| 20 |
-
messages = [
|
| 21 |
-
{
|
| 22 |
-
"role": "user",
|
| 23 |
-
"content": [
|
| 24 |
-
{"type": "image"},
|
| 25 |
-
{"type": "text", "text": "Describe this image in detail."}
|
| 26 |
-
]
|
| 27 |
-
},
|
| 28 |
-
]
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import torch
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoProcessor
|
| 4 |
from PIL import Image
|
| 5 |
+
import numpy as np
|
| 6 |
+
from fastapi import FastAPI, UploadFile, File
|
| 7 |
+
from typing import List
|
| 8 |
+
import io
|
| 9 |
+
import uvicorn
|
| 10 |
+
from pyngrok import ngrok
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# Initialize FastAPI app
|
| 13 |
+
app = FastAPI()
|
| 14 |
|
| 15 |
+
# Load SmolVLM-Instruct model and processor
|
| 16 |
+
model_id = "HuggingFaceTB/SmolVLM-Instruct"
|
| 17 |
+
processor = AutoProcessor.from_pretrained(model_id, token=os.environ.get("HF_TOKEN"))
|
| 18 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16).to("cuda")
|
| 19 |
|
| 20 |
+
# Harmful objects list for detection
|
| 21 |
+
harmful_objects = ["knife", "gun", "weapon", "blood", "syringe"]
|
| 22 |
|
| 23 |
+
@app.post("/predict")
|
| 24 |
+
async def predict(files: List[UploadFile] = File(...)):
|
| 25 |
+
results = []
|
| 26 |
+
image_embeddings = []
|
| 27 |
+
|
| 28 |
+
for file in files:
|
| 29 |
+
# Read image
|
| 30 |
+
image_data = await file.read()
|
| 31 |
+
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
| 32 |
+
|
| 33 |
+
# Generate description
|
| 34 |
+
inputs = processor(text="Describe the image in detail.", images=image, return_tensors="pt").to("cuda")
|
| 35 |
+
outputs = model.generate(**inputs, max_length=100)
|
| 36 |
+
description = processor.decode(outputs[0], skip_special_tokens=True).replace("Describe the image in detail.", "").strip()
|
| 37 |
+
|
| 38 |
+
# Extract signs/number plates (OCR)
|
| 39 |
+
inputs_ocr = processor(text="Extract all text visible in the image.", images=image, return_tensors="pt").to("cuda")
|
| 40 |
+
ocr_outputs = model.generate(**inputs_ocr, max_length=100)
|
| 41 |
+
signs_text = processor.decode(ocr_outputs[0], skip_special_tokens=True).replace("Extract all text visible in the image.", "").strip()
|
| 42 |
+
|
| 43 |
+
# Detect harmful objects/blood
|
| 44 |
+
inputs_detect = processor(text="List all objects in the image.", images=image, return_tensors="pt").to("cuda")
|
| 45 |
+
detect_outputs = model.generate(**inputs_detect, max_length=100)
|
| 46 |
+
detected_objects = processor.decode(detect_outputs[0], skip_special_tokens=True).lower()
|
| 47 |
+
harmful_detected = any(obj in detected_objects for obj in harmful_objects) and "Detected" or "None detected"
|
| 48 |
+
|
| 49 |
+
# Get image embedding for similarity
|
| 50 |
+
inputs_emb = processor(images=image, return_tensors="pt").to("cuda")
|
| 51 |
+
with torch.no_grad():
|
| 52 |
+
emb = model.vision_tower(inputs_emb["pixel_values"]).last_hidden_state.mean(dim=1).cpu().numpy()
|
| 53 |
+
image_embeddings.append(emb)
|
| 54 |
+
|
| 55 |
+
results.append({
|
| 56 |
+
"description": description if description else "No description generated.",
|
| 57 |
+
"signs": signs_text if signs_text else "None detected",
|
| 58 |
+
"harmful": harmful_detected
|
| 59 |
+
})
|
| 60 |
+
|
| 61 |
+
# Compute similarity scores (cosine similarity to first image)
|
| 62 |
+
if len(image_embeddings) > 1:
|
| 63 |
+
base_embedding = image_embeddings[0]
|
| 64 |
+
for i in range(1, len(image_embeddings)):
|
| 65 |
+
sim = np.dot(base_embedding, image_embeddings[i].T) / (
|
| 66 |
+
np.linalg.norm(base_embedding) * np.linalg.norm(image_embeddings[i])
|
| 67 |
+
)
|
| 68 |
+
results[i]["similarity"] = float(sim[0][0])
|
| 69 |
+
|
| 70 |
+
return results
|
| 71 |
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
# Start ngrok tunnel
|
| 74 |
+
public_url = ngrok.connect(8000).public_url
|
| 75 |
+
print(f"Public URL: {public_url}")
|
| 76 |
+
|
| 77 |
+
# Run FastAPI server
|
| 78 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|