File size: 1,579 Bytes
55bcd2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
from fastapi import APIRouter, File, HTTPException, UploadFile
from PIL import Image

from app.core.config import ALLOWED_IMAGE_MIMETYPES, MAX_FILE_SIZE
from app.pipelines import image as image_pipeline

try:
    from pillow_heif import register_heif_opener
    register_heif_opener()
except ImportError:
    pass

Image.MAX_IMAGE_PIXELS = 100_000_000

router = APIRouter()


def _validate_and_read(file: UploadFile, contents: bytes) -> Image.Image:
    content_type = getattr(file, "content_type", "")
    if content_type not in ALLOWED_IMAGE_MIMETYPES:
        raise HTTPException(
            status_code=400,
            detail=f"Format non supporté: {content_type}. Formats acceptés: JPEG, PNG, WEBP, HEIC.",
        )
    if len(contents) > MAX_FILE_SIZE:
        raise HTTPException(status_code=413, detail="Fichier trop volumineux (max 20 Mo).")
    try:
        return Image.open(io.BytesIO(contents)).convert("RGB")
    except Exception:
        raise HTTPException(status_code=400, detail="Fichier image corrompu ou illisible.")


@router.post("/analyze/image")
async def analyze_image(file: UploadFile = File(...)):
    contents = await file.read()
    img = _validate_and_read(file, contents)
    result = image_pipeline.run(img, contents)
    return {"status": "success", **result}


@router.post("/analyze/image/fast")
async def analyze_image_fast(file: UploadFile = File(...)):
    contents = await file.read()
    img = _validate_and_read(file, contents)
    result = image_pipeline.run_fast(img, contents)
    return {"status": "success", **result}