Spaces:
Sleeping
Sleeping
File size: 6,010 Bytes
8b95053 dc9ded5 b7bc425 8b95053 b7bc425 8b95053 b7bc425 8b95053 b7bc425 8b95053 b7bc425 8b95053 b7bc425 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 dc9ded5 8b95053 b7bc425 8b95053 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
# app.py
from time import perf_counter
from io import BytesIO
from typing import List, Optional, Union
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from pydantic import BaseModel, Field, HttpUrl
from PIL import Image
import uvicorn
from util import get_runner, SmolVLMRunner
app = FastAPI(title="SmolVLM Inference API", version="1.2.0")
_runner: Optional[SmolVLMRunner] = None
# ----------------------- Pydantic models -----------------------
class URLRequest(BaseModel):
prompt: str = Field(..., description="Text prompt to accompany the images.")
image_urls: List[HttpUrl] = Field(..., description="List of image URLs.")
max_new_tokens: int = Field(300, ge=1, le=1024)
temperature: Optional[float] = Field(None, ge=0.0, le=2.0)
top_p: Optional[float] = Field(None, gt=0.0, le=1.0)
class DetectDescribeURLRequest(BaseModel):
image_url: HttpUrl
labels: Union[str, List[str]]
box_threshold: float = 0.40
text_threshold: float = 0.30
pad_frac: float = 0.06
max_new_tokens: int = 160
return_overlay: bool = True
temperature: Optional[float] = None
top_p: Optional[float] = None
# ----------------------- Startup / health -----------------------
@app.on_event("startup")
async def _load_model_on_startup():
global _runner
_runner = get_runner()
@app.get("/")
def health():
return {"status": "ok", "model": _runner.model_id if _runner else None}
# ----------------------- Core VLM endpoints -----------------------
@app.post("/generate")
async def generate_from_files(
prompt: str = Form(...),
images: List[UploadFile] = File(..., description="One or more image files."),
max_new_tokens: int = Form(300),
temperature: Optional[float] = Form(None),
top_p: Optional[float] = Form(None),
):
if not images:
raise HTTPException(status_code=400, detail="At least one image must be provided.")
t_req_start = perf_counter()
# Read files
t_load_start = perf_counter()
blobs = []
for f in images:
if not f.content_type or not f.content_type.startswith("image/"):
raise HTTPException(status_code=415, detail=f"Unsupported file type: {f.content_type}")
blobs.append(await f.read())
pil_images = _runner.load_pil_from_bytes(blobs)
t_load_end = perf_counter()
text, inner_metrics = _runner.generate(
prompt=prompt,
images=pil_images,
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
return_stats=True,
)
t_req_end = perf_counter()
metrics = {
**inner_metrics,
"request_ms": {
"image_load": round((t_load_end - t_load_start) * 1000.0, 2),
"end_to_end": round((t_req_end - t_req_start) * 1000.0, 2),
},
}
return {"text": text, "metrics": metrics}
@app.post("/generate_urls")
async def generate_from_urls(req: URLRequest):
t_req_start = perf_counter()
if len(req.image_urls) == 0:
raise HTTPException(status_code=400, detail="At least one image URL is required.")
t_load_start = perf_counter()
pil_images = _runner.load_pil_from_urls([str(u) for u in req.image_urls])
t_load_end = perf_counter()
text, inner_metrics = _runner.generate(
prompt=req.prompt,
images=pil_images,
max_new_tokens=req.max_new_tokens,
temperature=req.temperature,
top_p=req.top_p,
return_stats=True,
)
t_req_end = perf_counter()
metrics = {
**inner_metrics,
"request_ms": {
"image_load": round((t_load_end - t_load_start) * 1000.0, 2),
"end_to_end": round((t_req_end - t_req_start) * 1000.0, 2),
},
}
return {"text": text, "metrics": metrics}
# ----------------------- Detect & Describe endpoints -----------------------
@app.post("/detect_describe")
async def detect_describe(
image: UploadFile = File(..., description="One image file (image/*)"),
labels: str = Form(..., description='Comma-separated phrases, e.g. "a man,a dog"'),
box_threshold: float = Form(0.40),
text_threshold: float = Form(0.30),
pad_frac: float = Form(0.06),
max_new_tokens: int = Form(160),
temperature: Optional[float] = Form(None),
top_p: Optional[float] = Form(None),
return_overlay: bool = Form(True),
):
if not image.content_type or not image.content_type.startswith("image/"):
raise HTTPException(status_code=415, detail=f"Unsupported file type: {image.content_type}")
try:
raw = await image.read()
pil = Image.open(BytesIO(raw)).convert("RGB")
except Exception as e:
raise HTTPException(status_code=400, detail=f"Failed to read image: {e}")
out = _runner.detect_and_describe(
image=pil,
labels=labels, # comma-separated string OK
box_threshold=box_threshold,
text_threshold=text_threshold,
pad_frac=pad_frac,
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
return_overlay=return_overlay,
)
return out
@app.post("/detect_describe_url")
async def detect_describe_url(req: DetectDescribeURLRequest):
try:
pil = _runner.load_pil_from_urls([str(req.image_url)])[0]
except Exception as e:
raise HTTPException(status_code=400, detail=f"Failed to fetch image: {e}")
out = _runner.detect_and_describe(
image=pil,
labels=req.labels,
box_threshold=req.box_threshold,
text_threshold=req.text_threshold,
pad_frac=req.pad_frac,
max_new_tokens=req.max_new_tokens,
temperature=req.temperature,
top_p=req.top_p,
return_overlay=req.return_overlay,
)
return out
# ----------------------- Entrypoint -----------------------
if __name__ == "__main__":
# Run with: python app.py (or: uvicorn app:app --host 0.0.0.0 --port 8000)
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=False)
|