Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,73 +1,46 @@
|
|
| 1 |
import io
|
| 2 |
import time
|
| 3 |
-
import
|
| 4 |
import torch
|
| 5 |
-
import torch.nn.functional as F
|
| 6 |
from PIL import Image
|
| 7 |
-
from
|
| 8 |
-
from torchvision import transforms
|
| 9 |
from fastapi import FastAPI, HTTPException, UploadFile, File
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from contextlib import asynccontextmanager
|
| 12 |
|
| 13 |
-
|
| 14 |
-
SEG_CLASSES = [
|
| 15 |
-
"Background", "Apparel", "Face Neck", "Hair", "Left Foot",
|
| 16 |
-
"Left Hand", "Left Lower Arm", "Left Lower Leg", "Left Shoe",
|
| 17 |
-
"Left Sock", "Left Upper Arm", "Left Upper Leg", "Lower Clothing",
|
| 18 |
-
"Right Foot", "Right Hand", "Right Lower Arm", "Right Lower Leg",
|
| 19 |
-
"Right Shoe", "Right Sock", "Right Upper Arm", "Right Upper Leg",
|
| 20 |
-
"Torso", "Upper Clothing", "Lower Lip", "Upper Lip", "Lower Teeth",
|
| 21 |
-
"Upper Teeth", "Tongue"
|
| 22 |
-
]
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
|
| 27 |
MODEL_DATA = {}
|
| 28 |
|
| 29 |
-
def preprocess(image: Image.Image) -> torch.Tensor:
|
| 30 |
-
transform = transforms.Compose([
|
| 31 |
-
transforms.Resize((1024, 768)),
|
| 32 |
-
transforms.ToTensor(),
|
| 33 |
-
transforms.Normalize(
|
| 34 |
-
mean=[0.485, 0.456, 0.406],
|
| 35 |
-
std=[0.229, 0.224, 0.225]
|
| 36 |
-
)
|
| 37 |
-
])
|
| 38 |
-
return transform(image).unsqueeze(0)
|
| 39 |
-
|
| 40 |
-
def postprocess(output: torch.Tensor, original_size: tuple) -> np.ndarray:
|
| 41 |
-
# output shape: [1, 28, H, W]
|
| 42 |
-
seg_map = F.interpolate(
|
| 43 |
-
output, size=original_size, mode="bilinear", align_corners=False
|
| 44 |
-
)
|
| 45 |
-
seg_map = torch.argmax(seg_map, dim=1).squeeze(0).cpu().numpy()
|
| 46 |
-
return seg_map.astype(np.uint8)
|
| 47 |
-
|
| 48 |
@asynccontextmanager
|
| 49 |
async def lifespan(app: FastAPI):
|
| 50 |
-
print("๐ฅ
|
| 51 |
start = time.time()
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
)
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
| 65 |
yield
|
| 66 |
MODEL_DATA.clear()
|
| 67 |
|
| 68 |
app = FastAPI(
|
| 69 |
-
title="
|
| 70 |
-
description="
|
| 71 |
version="1.0.0",
|
| 72 |
lifespan=lifespan
|
| 73 |
)
|
|
@@ -84,6 +57,15 @@ app.add_middleware(
|
|
| 84 |
def health():
|
| 85 |
return {"status": "ok", "model_loaded": "model" in MODEL_DATA}
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
@app.post("/analyze")
|
| 88 |
async def analyze_image(file: UploadFile = File(...)):
|
| 89 |
|
|
@@ -91,54 +73,67 @@ async def analyze_image(file: UploadFile = File(...)):
|
|
| 91 |
raise HTTPException(status_code=400, detail="ุงูู
ูู ููุณ ุตูุฑุฉ")
|
| 92 |
|
| 93 |
try:
|
| 94 |
-
|
|
|
|
| 95 |
except Exception as e:
|
| 96 |
raise HTTPException(status_code=400, detail=f"ุฎุทุฃ ูู ูุฑุงุกุฉ ุงูุตูุฑุฉ: {str(e)}")
|
| 97 |
|
| 98 |
try:
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
# โโโ
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
if c in HUMAN_CLASSES
|
| 119 |
]
|
| 120 |
|
| 121 |
-
# โโโ
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
parts_coverage[SEG_CLASSES[c]] = f"{percentage}%"
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
return {
|
| 136 |
-
"
|
| 137 |
-
"
|
| 138 |
-
"
|
| 139 |
-
"
|
| 140 |
-
"execution_time":
|
| 141 |
-
"status":
|
| 142 |
}
|
| 143 |
|
| 144 |
except Exception as e:
|
|
|
|
| 1 |
import io
|
| 2 |
import time
|
| 3 |
+
import base64
|
| 4 |
import torch
|
|
|
|
| 5 |
from PIL import Image
|
| 6 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
|
|
|
| 7 |
from fastapi import FastAPI, HTTPException, UploadFile, File
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
|
| 11 |
+
MODEL_ID = "Qwen/Qwen3.5-0.8B"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
VQA_QUESTION = (
|
| 14 |
+
"Is there a woman or any part of a woman's body in this image? "
|
| 15 |
+
"Answer yes or no only. /no_think"
|
| 16 |
+
)
|
| 17 |
|
| 18 |
MODEL_DATA = {}
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
@asynccontextmanager
|
| 21 |
async def lifespan(app: FastAPI):
|
| 22 |
+
print(f"๐ฅ Loading {MODEL_ID}...")
|
| 23 |
start = time.time()
|
| 24 |
|
| 25 |
+
MODEL_DATA["processor"] = AutoProcessor.from_pretrained(
|
| 26 |
+
MODEL_ID,
|
| 27 |
+
trust_remote_code=True
|
| 28 |
)
|
| 29 |
+
MODEL_DATA["model"] = AutoModelForCausalLM.from_pretrained(
|
| 30 |
+
MODEL_ID,
|
| 31 |
+
torch_dtype=torch.float32,
|
| 32 |
+
trust_remote_code=True,
|
| 33 |
+
attn_implementation="eager",
|
| 34 |
+
device_map="cpu"
|
| 35 |
+
).eval()
|
| 36 |
+
|
| 37 |
+
print(f"โ
Model ready in {time.time()-start:.1f}s")
|
| 38 |
yield
|
| 39 |
MODEL_DATA.clear()
|
| 40 |
|
| 41 |
app = FastAPI(
|
| 42 |
+
title="Female Detection API - Qwen3.5-0.8B",
|
| 43 |
+
description="Qwen3.5-0.8B VLM | VQA",
|
| 44 |
version="1.0.0",
|
| 45 |
lifespan=lifespan
|
| 46 |
)
|
|
|
|
| 57 |
def health():
|
| 58 |
return {"status": "ok", "model_loaded": "model" in MODEL_DATA}
|
| 59 |
|
| 60 |
+
def decide(answer: str) -> tuple[str, str]:
|
| 61 |
+
a = answer.strip().lower()
|
| 62 |
+
if a == "no" or a.startswith("no"):
|
| 63 |
+
return "allow", "model_answered_no"
|
| 64 |
+
elif "yes" in a:
|
| 65 |
+
return "block", "model_answered_yes"
|
| 66 |
+
else:
|
| 67 |
+
return "block", "unexpected_answer_blocked_for_safety"
|
| 68 |
+
|
| 69 |
@app.post("/analyze")
|
| 70 |
async def analyze_image(file: UploadFile = File(...)):
|
| 71 |
|
|
|
|
| 73 |
raise HTTPException(status_code=400, detail="ุงูู
ูู ููุณ ุตูุฑุฉ")
|
| 74 |
|
| 75 |
try:
|
| 76 |
+
image_bytes = await file.read()
|
| 77 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 78 |
except Exception as e:
|
| 79 |
raise HTTPException(status_code=400, detail=f"ุฎุทุฃ ูู ูุฑุงุกุฉ ุงูุตูุฑุฉ: {str(e)}")
|
| 80 |
|
| 81 |
try:
|
| 82 |
+
processor = MODEL_DATA["processor"]
|
| 83 |
+
model = MODEL_DATA["model"]
|
| 84 |
+
|
| 85 |
+
# โโโ Qwen3.5 ูุณุชุฎุฏู
ููุณ ุทุฑููุฉ Qwen3-VL โโโโโโโโโโโโโโโโโโ
|
| 86 |
+
# ุงูุตูุฑุฉ ุชุฑุณู ูู type: "image" ู
ุจุงุดุฑุฉ ูู content
|
| 87 |
+
messages = [
|
| 88 |
+
{
|
| 89 |
+
"role": "user",
|
| 90 |
+
"content": [
|
| 91 |
+
{
|
| 92 |
+
"type": "image",
|
| 93 |
+
"image": image # PIL Image ู
ุจุงุดุฑุฉ
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"type": "text",
|
| 97 |
+
"text": VQA_QUESTION
|
| 98 |
+
}
|
| 99 |
+
]
|
| 100 |
+
}
|
|
|
|
| 101 |
]
|
| 102 |
|
| 103 |
+
# โโโ apply_chat_template โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 104 |
+
inputs = processor.apply_chat_template(
|
| 105 |
+
messages,
|
| 106 |
+
tokenize=True,
|
| 107 |
+
add_generation_prompt=True,
|
| 108 |
+
return_dict=True,
|
| 109 |
+
return_tensors="pt"
|
| 110 |
+
)
|
|
|
|
| 111 |
|
| 112 |
+
start_time = time.time()
|
| 113 |
+
with torch.no_grad():
|
| 114 |
+
generated_ids = model.generate(
|
| 115 |
+
**inputs,
|
| 116 |
+
max_new_tokens=20,
|
| 117 |
+
do_sample=False,
|
| 118 |
+
temperature=None,
|
| 119 |
+
top_p=None,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# โโโ ุงุณุชุฎุฑุงุฌ ุงูุฅุฌุงุจุฉ ุงูุฌุฏูุฏุฉ ููุท โโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 123 |
+
input_len = inputs["input_ids"].shape[1]
|
| 124 |
+
new_tokens = generated_ids[:, input_len:]
|
| 125 |
+
answer = processor.decode(new_tokens[0], skip_special_tokens=True).strip()
|
| 126 |
+
|
| 127 |
+
elapsed = round(time.time() - start_time, 2)
|
| 128 |
+
decision, reason = decide(answer)
|
| 129 |
|
| 130 |
return {
|
| 131 |
+
"decision": decision,
|
| 132 |
+
"reason": reason,
|
| 133 |
+
"vqa_answer": answer,
|
| 134 |
+
"question": VQA_QUESTION,
|
| 135 |
+
"execution_time": elapsed,
|
| 136 |
+
"status": "success"
|
| 137 |
}
|
| 138 |
|
| 139 |
except Exception as e:
|