Spaces:
Runtime error
Runtime error
Deploy FastAPI+WebSocket+Gradio microservice (Etapes 1-6)
Browse files- README.md +21 -8
- requirements.txt +21 -0
- src/service/app.py +137 -0
- src/service/gradio_ui.py +99 -0
- src/service/pipeline.py +257 -0
- src/service/runner.py +85 -0
- src/service/ws_protocol.py +55 -0
README.md
CHANGED
|
@@ -1,13 +1,26 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
|
| 9 |
-
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Object Removal VLM Diffusion
|
| 3 |
+
emoji: 🖼️
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.50.0
|
| 8 |
+
app_file: src/service/app.py
|
|
|
|
| 9 |
pinned: false
|
| 10 |
+
short_description: Zero-shot object removal via Florence-2, SAM2 and diffusion
|
| 11 |
+
preload_from_hub:
|
| 12 |
+
- microsoft/Florence-2-base
|
| 13 |
+
- openai/clip-vit-base-patch32
|
| 14 |
+
- facebook/sam2.1-hiera-base-plus
|
| 15 |
+
- philschmid/stable-diffusion-2-inpainting-endpoint
|
| 16 |
---
|
| 17 |
|
| 18 |
+
# Suppression d'objet assistee par VLM et diffusion
|
| 19 |
+
|
| 20 |
+
Pipeline zero-shot : decrire un objet en langage naturel -> il disparait de l'image, remplace par un contenu genere coherent.
|
| 21 |
+
|
| 22 |
+
**Architecture** : Florence-2 (grounding texte->boite) -> CLIP (reclassement/desambiguisation) -> SAM2 (masque precis) -> dilatation du masque -> Stable Diffusion Inpainting (generation), servi par un microservice FastAPI + WebSocket avec une UI Gradio montee dans le meme process.
|
| 23 |
+
|
| 24 |
+
**Optimisations** : cache d'embeddings texte (negative_prompt fixe). `torch.compile` (UNet, -88% de latence mesure) est desactive automatiquement sous ZeroGPU (incompatible - cache de compilation non persistant entre les process ephemeres), actif sur un GPU dedie.
|
| 25 |
+
|
| 26 |
+
Detail complet du developpement (blocages rencontres, methodes testees, benchmarks qualite en 4 cas, decisions d'architecture) : voir le depot source du projet.
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Versions figees a l'issue des Etapes 1-6 (voir projet_2_avancement.md pour
|
| 2 |
+
# le detail des conflits de dependances resolus - transformers/diffusers,
|
| 3 |
+
# gradio/huggingface-hub). Ne pas mettre a jour sans revalider ces conflits.
|
| 4 |
+
torch==2.13.0
|
| 5 |
+
torchvision
|
| 6 |
+
transformers==4.49.0
|
| 7 |
+
diffusers==0.31.0
|
| 8 |
+
huggingface_hub<1.0
|
| 9 |
+
accelerate
|
| 10 |
+
safetensors
|
| 11 |
+
gradio==5.50.0
|
| 12 |
+
spaces
|
| 13 |
+
fastapi
|
| 14 |
+
uvicorn[standard]
|
| 15 |
+
websockets
|
| 16 |
+
python-multipart
|
| 17 |
+
pydantic
|
| 18 |
+
numpy
|
| 19 |
+
pillow
|
| 20 |
+
opencv-python-headless
|
| 21 |
+
SAM-2 @ git+https://github.com/facebookresearch/sam2.git@2b90b9f5ceec907a1c18123530e92e794ad901a4
|
src/service/app.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Point d'entree du microservice : une app FastAPI unique qui
|
| 3 |
+
1. expose un endpoint WebSocket /ws/edit (protocole reutilisable par
|
| 4 |
+
n'importe quel client - pas seulement l'UI de demo),
|
| 5 |
+
2. monte l'UI Gradio sur "/" dans le MEME process Python.
|
| 6 |
+
|
| 7 |
+
Pourquoi le meme process (et pas deux services separes) : le decorateur
|
| 8 |
+
@spaces.GPU (Hugging Face Spaces + ZeroGPU) attend d'etre appele depuis le
|
| 9 |
+
process reconnu comme le Space. Monter Gradio sur FastAPI via
|
| 10 |
+
`gradio.mount_gradio_app` garde tout dans un seul process ASGI, donc
|
| 11 |
+
@spaces.GPU fonctionne pour les deux points d'entree (WebSocket ET UI
|
| 12 |
+
Gradio), qui partagent le meme pipeline et la meme file GPU (gpu_queue) -
|
| 13 |
+
un utilisateur Gradio et un client WebSocket externe ne peuvent donc jamais
|
| 14 |
+
lancer deux inferences GPU en concurrence.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import asyncio
|
| 18 |
+
import base64
|
| 19 |
+
import io
|
| 20 |
+
import json
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 24 |
+
from PIL import Image
|
| 25 |
+
from pydantic import ValidationError
|
| 26 |
+
|
| 27 |
+
import runner
|
| 28 |
+
from gradio_ui import build_ui
|
| 29 |
+
from ws_protocol import ConfirmRequest, LocateRequest
|
| 30 |
+
|
| 31 |
+
app = FastAPI(title="genai-image-editor")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _b64_to_image(b64: str) -> Image.Image:
|
| 35 |
+
return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _image_to_b64(img: Image.Image) -> str:
|
| 39 |
+
buf = io.BytesIO()
|
| 40 |
+
img.save(buf, format="PNG")
|
| 41 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@app.websocket("/ws/edit")
|
| 45 |
+
async def ws_edit(websocket: WebSocket):
|
| 46 |
+
await websocket.accept()
|
| 47 |
+
|
| 48 |
+
# Etat de session : le contexte (image + masque valide) vit le temps de
|
| 49 |
+
# cette connexion, entre la phase "locate" et la phase "confirm".
|
| 50 |
+
session = {"image": None, "dilated_mask": None}
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
while True:
|
| 54 |
+
raw = await websocket.receive_text()
|
| 55 |
+
try:
|
| 56 |
+
payload = json.loads(raw)
|
| 57 |
+
except json.JSONDecodeError:
|
| 58 |
+
await websocket.send_json({"type": "error", "message": "JSON invalide."})
|
| 59 |
+
continue
|
| 60 |
+
|
| 61 |
+
msg_type = payload.get("type")
|
| 62 |
+
|
| 63 |
+
if msg_type == "locate":
|
| 64 |
+
try:
|
| 65 |
+
req = LocateRequest.model_validate(payload)
|
| 66 |
+
except ValidationError as e:
|
| 67 |
+
await websocket.send_json({"type": "error", "message": str(e)})
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
image = _b64_to_image(req.image_b64)
|
| 71 |
+
session["image"] = image
|
| 72 |
+
try:
|
| 73 |
+
result = await runner.run_locate(image, req.text_query)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
await websocket.send_json({"type": "error", "message": str(e)})
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
session["dilated_mask"] = Image.open(io.BytesIO(result.dilated_mask_png)).convert("L")
|
| 79 |
+
await websocket.send_json({
|
| 80 |
+
"type": "mask_ready",
|
| 81 |
+
"mask_b64": base64.b64encode(result.dilated_mask_png).decode(),
|
| 82 |
+
"box": result.box,
|
| 83 |
+
"clip_confidence": result.clip_confidence,
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
elif msg_type == "confirm":
|
| 87 |
+
try:
|
| 88 |
+
req = ConfirmRequest.model_validate(payload)
|
| 89 |
+
except ValidationError as e:
|
| 90 |
+
await websocket.send_json({"type": "error", "message": str(e)})
|
| 91 |
+
continue
|
| 92 |
+
|
| 93 |
+
if session["image"] is None or session["dilated_mask"] is None:
|
| 94 |
+
await websocket.send_json({
|
| 95 |
+
"type": "error",
|
| 96 |
+
"message": "Aucun masque en attente - envoyer 'locate' d'abord.",
|
| 97 |
+
})
|
| 98 |
+
continue
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
async for kind, *rest in runner.run_inpaint_stream(
|
| 102 |
+
session["image"], session["dilated_mask"],
|
| 103 |
+
req.prompt, req.negative_prompt,
|
| 104 |
+
req.steps, req.guidance_scale, req.seed,
|
| 105 |
+
):
|
| 106 |
+
if kind == "progress":
|
| 107 |
+
step, total = rest
|
| 108 |
+
await websocket.send_json({
|
| 109 |
+
"type": "progress", "stage": "diffusion", "step": step, "total": total,
|
| 110 |
+
})
|
| 111 |
+
elif kind == "result":
|
| 112 |
+
(image_result,) = rest
|
| 113 |
+
await websocket.send_json({
|
| 114 |
+
"type": "result", "image_b64": _image_to_b64(image_result),
|
| 115 |
+
})
|
| 116 |
+
except Exception as e:
|
| 117 |
+
await websocket.send_json({"type": "error", "message": str(e)})
|
| 118 |
+
|
| 119 |
+
else:
|
| 120 |
+
await websocket.send_json({"type": "error", "message": f"Type de message inconnu : {msg_type}"})
|
| 121 |
+
|
| 122 |
+
except WebSocketDisconnect:
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# UI Gradio montee sur le meme process/app FastAPI (cf. docstring en tete de fichier)
|
| 127 |
+
gr.mount_gradio_app(app, build_ui(), path="/")
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
# Point d'entree attendu par le SDK Gradio de Hugging Face Spaces
|
| 131 |
+
# (execution directe "python app.py", port 7860 par convention). En dev
|
| 132 |
+
# local on lance plutot `uvicorn app:app --port 8000` (voir README pod),
|
| 133 |
+
# ce bloc ne sert qu'au deploiement Spaces.
|
| 134 |
+
import os
|
| 135 |
+
import uvicorn
|
| 136 |
+
|
| 137 |
+
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
|
src/service/gradio_ui.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
UI Gradio de demonstration. Montee sur l'app FastAPI (cf. app.py) : ne parle
|
| 3 |
+
PAS au endpoint WebSocket (inutile de faire boucler un client sur son propre
|
| 4 |
+
serveur), mais appelle directement `runner.run_locate` / `runner.run_inpaint_stream` -
|
| 5 |
+
les memes fonctions, passant par la MEME gpu_queue que le WebSocket, donc un
|
| 6 |
+
utilisateur Gradio et un client externe restent bien serialises sur le seul
|
| 7 |
+
GPU disponible.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
import runner
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _overlay_mask(image: Image.Image, mask: Image.Image) -> Image.Image:
|
| 17 |
+
image_np = np.array(image.convert("RGB"))
|
| 18 |
+
mask_np = np.array(mask) > 127
|
| 19 |
+
overlay = image_np.copy()
|
| 20 |
+
overlay[mask_np] = (overlay[mask_np] * 0.5 + np.array([255, 0, 0]) * 0.5).astype(np.uint8)
|
| 21 |
+
return Image.fromarray(overlay)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
async def on_locate(image: Image.Image, text_query: str, state: dict):
|
| 25 |
+
import gradio as gr
|
| 26 |
+
|
| 27 |
+
if image is None or not text_query.strip():
|
| 28 |
+
raise gr.Error("Fournir une image et une description de l'objet a retirer.")
|
| 29 |
+
|
| 30 |
+
result = await runner.run_locate(image, text_query)
|
| 31 |
+
dilated_mask = Image.open(__import__("io").BytesIO(result.dilated_mask_png)).convert("L")
|
| 32 |
+
|
| 33 |
+
state = {"image": image, "dilated_mask": dilated_mask}
|
| 34 |
+
overlay = _overlay_mask(image, dilated_mask)
|
| 35 |
+
confidence_msg = f"Confiance CLIP : {result.clip_confidence:.1%} (sur {len(result.all_boxes)} boite(s) candidate(s))"
|
| 36 |
+
return overlay, confidence_msg, state
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
async def on_confirm(prompt: str, negative_prompt: str, steps: int, guidance_scale: float, seed: int, state: dict):
|
| 40 |
+
import gradio as gr
|
| 41 |
+
|
| 42 |
+
if not state or state.get("dilated_mask") is None:
|
| 43 |
+
raise gr.Error("Lancer d'abord 'Localiser et segmenter'.")
|
| 44 |
+
|
| 45 |
+
progress = gr.Progress()
|
| 46 |
+
result_image = None
|
| 47 |
+
async for kind, *rest in runner.run_inpaint_stream(
|
| 48 |
+
state["image"], state["dilated_mask"], prompt, negative_prompt, steps, guidance_scale, seed
|
| 49 |
+
):
|
| 50 |
+
if kind == "progress":
|
| 51 |
+
step, total = rest
|
| 52 |
+
progress(step / total, desc=f"Debruitage {step}/{total}")
|
| 53 |
+
elif kind == "result":
|
| 54 |
+
(result_image,) = rest
|
| 55 |
+
return result_image
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def build_ui():
|
| 59 |
+
import gradio as gr
|
| 60 |
+
|
| 61 |
+
with gr.Blocks(title="Object Removal - VLM + SAM2 + Diffusion") as demo:
|
| 62 |
+
gr.Markdown(
|
| 63 |
+
"## Suppression d'objet assistee par VLM et diffusion\n"
|
| 64 |
+
"**Etape 1** : decrire l'objet a retirer -> valider le masque propose. "
|
| 65 |
+
"**Etape 2** : decrire le contenu de remplacement -> generer."
|
| 66 |
+
)
|
| 67 |
+
state = gr.State({})
|
| 68 |
+
|
| 69 |
+
with gr.Row():
|
| 70 |
+
with gr.Column():
|
| 71 |
+
image_in = gr.Image(type="pil", label="Image source")
|
| 72 |
+
text_query = gr.Textbox(label="Objet a retirer", placeholder="ex: the cat on the right")
|
| 73 |
+
locate_btn = gr.Button("1. Localiser et segmenter")
|
| 74 |
+
with gr.Column():
|
| 75 |
+
mask_preview = gr.Image(label="Masque propose (apercu avant generation)")
|
| 76 |
+
confidence_out = gr.Textbox(label="Diagnostic", interactive=False)
|
| 77 |
+
|
| 78 |
+
with gr.Row():
|
| 79 |
+
with gr.Column():
|
| 80 |
+
prompt_in = gr.Textbox(label="Contenu de remplacement", value="plain pink fabric sofa cushion, solid color, soft blanket texture, photo")
|
| 81 |
+
negative_prompt_in = gr.Textbox(label="Negative prompt", value="cat, animal, fur, tail, paws, ears, whiskers, shoes, pattern, objects, clutter")
|
| 82 |
+
with gr.Row():
|
| 83 |
+
steps_in = gr.Slider(10, 50, value=30, step=1, label="Pas de debruitage")
|
| 84 |
+
guidance_in = gr.Slider(1.0, 15.0, value=7.5, step=0.5, label="Guidance scale")
|
| 85 |
+
seed_in = gr.Number(value=42, precision=0, label="Seed")
|
| 86 |
+
confirm_btn = gr.Button("2. Generer")
|
| 87 |
+
with gr.Column():
|
| 88 |
+
result_out = gr.Image(label="Resultat")
|
| 89 |
+
|
| 90 |
+
locate_btn.click(
|
| 91 |
+
on_locate, inputs=[image_in, text_query, state], outputs=[mask_preview, confidence_out, state]
|
| 92 |
+
)
|
| 93 |
+
confirm_btn.click(
|
| 94 |
+
on_confirm,
|
| 95 |
+
inputs=[prompt_in, negative_prompt_in, steps_in, guidance_in, seed_in, state],
|
| 96 |
+
outputs=[result_out],
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
return demo
|
src/service/pipeline.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pipeline d'edition d'image : Florence-2 (localisation) -> CLIP (reclassement)
|
| 3 |
+
-> SAM2 (masque precis + dilatation) -> Stable Diffusion Inpainting (generation).
|
| 4 |
+
|
| 5 |
+
Les modeles sont charges UNE SEULE FOIS au chargement de ce module (pattern
|
| 6 |
+
recommande pour Hugging Face Spaces + ZeroGPU : le modele reste sur le device
|
| 7 |
+
en permanence, seul l'ACCES au GPU physique est arbitre par le decorateur
|
| 8 |
+
@spaces.GPU au moment de l'appel, pas le chargement du modele lui-meme).
|
| 9 |
+
|
| 10 |
+
Chaque fonction couteuse (locate_and_segment, generate_inpaint) est decoree
|
| 11 |
+
@spaces.GPU. Hors d'un environnement HF Spaces/ZeroGPU (ex: ce pod de dev),
|
| 12 |
+
`spaces.GPU` se comporte comme un decorateur transparent (no-op) - meme code
|
| 13 |
+
utilisable en dev et en production.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import io
|
| 17 |
+
import time
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Callable, Optional
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
from transformers import AutoProcessor, AutoModelForCausalLM, CLIPModel, CLIPProcessor
|
| 25 |
+
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 26 |
+
from diffusers import StableDiffusionInpaintPipeline
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
import spaces
|
| 30 |
+
from spaces.config import Config as _SpacesConfig
|
| 31 |
+
GPU = spaces.GPU
|
| 32 |
+
IS_ZERO_GPU = _SpacesConfig.zero_gpu
|
| 33 |
+
except Exception:
|
| 34 |
+
def GPU(func):
|
| 35 |
+
return func
|
| 36 |
+
IS_ZERO_GPU = False
|
| 37 |
+
|
| 38 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 39 |
+
|
| 40 |
+
FLORENCE_ID = "microsoft/Florence-2-base"
|
| 41 |
+
CLIP_ID = "openai/clip-vit-base-patch32"
|
| 42 |
+
SAM2_ID = "facebook/sam2.1-hiera-base-plus"
|
| 43 |
+
SD_INPAINT_ID = "philschmid/stable-diffusion-2-inpainting-endpoint"
|
| 44 |
+
|
| 45 |
+
print("[pipeline] Chargement des modeles (Florence-2, CLIP, SAM2, SD Inpainting)...")
|
| 46 |
+
|
| 47 |
+
florence_model = AutoModelForCausalLM.from_pretrained(
|
| 48 |
+
FLORENCE_ID, torch_dtype=torch.float16, trust_remote_code=True
|
| 49 |
+
).to(DEVICE)
|
| 50 |
+
florence_processor = AutoProcessor.from_pretrained(FLORENCE_ID, trust_remote_code=True)
|
| 51 |
+
|
| 52 |
+
clip_model = CLIPModel.from_pretrained(CLIP_ID).to(DEVICE)
|
| 53 |
+
clip_processor = CLIPProcessor.from_pretrained(CLIP_ID)
|
| 54 |
+
|
| 55 |
+
sam2_predictor = SAM2ImagePredictor.from_pretrained(SAM2_ID, device=DEVICE)
|
| 56 |
+
|
| 57 |
+
sd_pipe = StableDiffusionInpaintPipeline.from_pretrained(
|
| 58 |
+
SD_INPAINT_ID, torch_dtype=torch.float16
|
| 59 |
+
).to(DEVICE)
|
| 60 |
+
|
| 61 |
+
# torch.compile sur le UNet uniquement : c'est la seule partie du pipeline
|
| 62 |
+
# appelee en boucle (30x par generation), donc la seule ou l'overhead de
|
| 63 |
+
# dispatch Python/CUDA amorti par la compilation a un vrai retour. Florence-2
|
| 64 |
+
# (generation autoregressive a longueur variable) et SAM2 (un seul forward)
|
| 65 |
+
# ont ete ecartes de la compilation - shapes trop instables ou gain marginal
|
| 66 |
+
# trop faible pour justifier le cout de compilation (voir benchmark dedie,
|
| 67 |
+
# src/test_torch_compile_unet.py, documente dans projet_2_avancement.md).
|
| 68 |
+
#
|
| 69 |
+
# mode="reduce-overhead" utilise des CUDA graphs : la forme des tenseurs
|
| 70 |
+
# d'entree doit rester stable d'un appel a l'autre, sinon une recompilation
|
| 71 |
+
# silencieuse se declenche. Cas limite connu ici : guidance_scale == 1.0
|
| 72 |
+
# desactive le classifier-free guidance dans diffusers (batch UNet 1 au lieu
|
| 73 |
+
# de 2), ce qui provoque une recompilation ponctuelle - sans consequence sur
|
| 74 |
+
# la justesse du resultat, juste une latence plus elevee sur cet appel precis.
|
| 75 |
+
#
|
| 76 |
+
# INCOMPATIBLE AVEC ZeroGPU (verifie dans la doc officielle HF, Etape 6) :
|
| 77 |
+
# ZeroGPU alloue le GPU via des process ephemeres/forkes a chaque appel - le
|
| 78 |
+
# cache de compilation ne survit pas d'un appel a l'autre, donc torch.compile
|
| 79 |
+
# y recompilerait a CHAQUE requete (~74s a chaque fois, mesure a l'Etape 4)
|
| 80 |
+
# au lieu d'une fois au demarrage. Resultat : plus lent qu'en eager, jamais
|
| 81 |
+
# amorti. L'alternative documentee par HF est la compilation "ahead-of-time"
|
| 82 |
+
# (spaces.aoti_compile/aoti_apply), non implementee ici (gain rapporte plus
|
| 83 |
+
# modeste, 1.3x-1.8x, contre -88% mesure avec reduce-overhead sur GPU
|
| 84 |
+
# persistant) - decision explicite de ne pas l'implementer pour ce projet,
|
| 85 |
+
# le gain de reduce-overhead restant valide et documente pour un deploiement
|
| 86 |
+
# a GPU dedie (le pod, ou un Space GPU classique hors ZeroGPU).
|
| 87 |
+
if IS_ZERO_GPU:
|
| 88 |
+
print("[pipeline] Environnement ZeroGPU detecte : torch.compile desactive (incompatible, cf. projet_2_avancement.md).")
|
| 89 |
+
else:
|
| 90 |
+
print("[pipeline] Compilation du UNet (torch.compile, reduce-overhead)...")
|
| 91 |
+
sd_pipe.unet = torch.compile(sd_pipe.unet, mode="reduce-overhead")
|
| 92 |
+
|
| 93 |
+
print("[pipeline] Modeles charges sur", DEVICE)
|
| 94 |
+
|
| 95 |
+
# Cache des embeddings texte (CLIP text encoder de SD) : le negative_prompt
|
| 96 |
+
# est fixe dans l'UI et le prompt de remplacement est souvent reutilise
|
| 97 |
+
# (l'utilisateur ajuste seed/steps sans changer le texte) - inutile de
|
| 98 |
+
# ré-encoder le meme texte a chaque generation. Cle = (prompt, negative_prompt)
|
| 99 |
+
# car les deux sont encodes ensemble dans un seul appel a encode_prompt.
|
| 100 |
+
_text_embed_cache: dict = {}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _get_text_embeddings(prompt: str, negative_prompt: str):
|
| 104 |
+
key = (prompt, negative_prompt)
|
| 105 |
+
if key not in _text_embed_cache:
|
| 106 |
+
prompt_embeds, negative_prompt_embeds = sd_pipe.encode_prompt(
|
| 107 |
+
prompt=prompt,
|
| 108 |
+
device=DEVICE,
|
| 109 |
+
num_images_per_prompt=1,
|
| 110 |
+
do_classifier_free_guidance=True,
|
| 111 |
+
negative_prompt=negative_prompt,
|
| 112 |
+
)
|
| 113 |
+
_text_embed_cache[key] = (prompt_embeds, negative_prompt_embeds)
|
| 114 |
+
return _text_embed_cache[key]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@dataclass
|
| 118 |
+
class LocateResult:
|
| 119 |
+
box: list # [x1, y1, x2, y2]
|
| 120 |
+
all_boxes: list
|
| 121 |
+
clip_confidence: float
|
| 122 |
+
mask_png: bytes
|
| 123 |
+
dilated_mask_png: bytes
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _dilate_mask(mask_np: np.ndarray, size: int = 31) -> np.ndarray:
|
| 127 |
+
"""Casse la silhouette reconnaissable du masque (cf. Etape 3 - biais de
|
| 128 |
+
forme identifie : un masque pixel-precis en forme d'animal entre en
|
| 129 |
+
concurrence avec le guidage textuel pendant le debruitage)."""
|
| 130 |
+
try:
|
| 131 |
+
import cv2
|
| 132 |
+
kernel = np.ones((size, size), np.uint8)
|
| 133 |
+
return cv2.dilate(mask_np, kernel, iterations=1)
|
| 134 |
+
except ImportError:
|
| 135 |
+
mask_img = Image.fromarray(mask_np)
|
| 136 |
+
return np.array(mask_img.filter(ImageFilter.MaxFilter(size=size)))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _to_png_bytes(arr: np.ndarray) -> bytes:
|
| 140 |
+
buf = io.BytesIO()
|
| 141 |
+
Image.fromarray(arr).save(buf, format="PNG")
|
| 142 |
+
return buf.getvalue()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@GPU
|
| 146 |
+
def locate_and_segment(image: Image.Image, text_query: str) -> LocateResult:
|
| 147 |
+
"""Etape A+B du pipeline : Florence-2 propose des boites candidates pour
|
| 148 |
+
`text_query`, CLIP reclasse par similarite image-texte si plusieurs boites
|
| 149 |
+
sont retournees (desambiguisation, ex: qualificatifs spatiaux), puis SAM2
|
| 150 |
+
convertit la boite retenue en masque pixel-precis, dilate ensuite."""
|
| 151 |
+
image = image.convert("RGB")
|
| 152 |
+
task_prompt = "<CAPTION_TO_PHRASE_GROUNDING>"
|
| 153 |
+
inputs = florence_processor(
|
| 154 |
+
text=task_prompt + text_query, images=image, return_tensors="pt"
|
| 155 |
+
).to(DEVICE, torch.float16)
|
| 156 |
+
generated_ids = florence_model.generate(
|
| 157 |
+
input_ids=inputs["input_ids"],
|
| 158 |
+
pixel_values=inputs["pixel_values"],
|
| 159 |
+
max_new_tokens=1024,
|
| 160 |
+
num_beams=3,
|
| 161 |
+
)
|
| 162 |
+
generated_text = florence_processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
|
| 163 |
+
parsed = florence_processor.post_process_generation(
|
| 164 |
+
generated_text, task=task_prompt, image_size=(image.width, image.height)
|
| 165 |
+
)
|
| 166 |
+
boxes = parsed[task_prompt]["bboxes"]
|
| 167 |
+
if not boxes:
|
| 168 |
+
raise ValueError(f"Aucun objet trouve pour la description : '{text_query}'")
|
| 169 |
+
|
| 170 |
+
if len(boxes) == 1:
|
| 171 |
+
best_box, confidence = boxes[0], 1.0
|
| 172 |
+
else:
|
| 173 |
+
crops = [image.crop(box) for box in boxes]
|
| 174 |
+
clip_inputs = clip_processor(
|
| 175 |
+
text=[text_query], images=crops, return_tensors="pt", padding=True
|
| 176 |
+
).to(DEVICE)
|
| 177 |
+
with torch.no_grad():
|
| 178 |
+
scores = clip_model(**clip_inputs).logits_per_image.squeeze(-1)
|
| 179 |
+
probs = scores.softmax(dim=0)
|
| 180 |
+
best_idx = scores.argmax().item()
|
| 181 |
+
best_box, confidence = boxes[best_idx], probs[best_idx].item()
|
| 182 |
+
|
| 183 |
+
image_np = np.array(image)
|
| 184 |
+
sam2_predictor.set_image(image_np)
|
| 185 |
+
masks, _mask_scores, _logits = sam2_predictor.predict(
|
| 186 |
+
box=np.array(best_box)[None, :], multimask_output=False
|
| 187 |
+
)
|
| 188 |
+
mask_np = masks[0].astype(np.uint8) * 255
|
| 189 |
+
dilated_np = _dilate_mask(mask_np, size=31)
|
| 190 |
+
|
| 191 |
+
return LocateResult(
|
| 192 |
+
box=list(best_box),
|
| 193 |
+
all_boxes=[list(b) for b in boxes],
|
| 194 |
+
clip_confidence=float(confidence),
|
| 195 |
+
mask_png=_to_png_bytes(mask_np),
|
| 196 |
+
dilated_mask_png=_to_png_bytes(dilated_np),
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@GPU
|
| 201 |
+
def generate_inpaint(
|
| 202 |
+
image: Image.Image,
|
| 203 |
+
dilated_mask: Image.Image,
|
| 204 |
+
prompt: str,
|
| 205 |
+
negative_prompt: str,
|
| 206 |
+
steps: int = 30,
|
| 207 |
+
guidance_scale: float = 7.5,
|
| 208 |
+
seed: int = 42,
|
| 209 |
+
step_callback: Optional[Callable[[int, int], None]] = None,
|
| 210 |
+
) -> Image.Image:
|
| 211 |
+
"""Etape C : inpainting par diffusion. `step_callback(step_index, total)`
|
| 212 |
+
est appele apres chaque pas de debruitage - utilise pour streamer la
|
| 213 |
+
progression (WebSocket ou Gradio) pendant que cette fonction bloque le
|
| 214 |
+
thread GPU."""
|
| 215 |
+
generator = torch.Generator(device=DEVICE).manual_seed(seed)
|
| 216 |
+
prompt_embeds, negative_prompt_embeds = _get_text_embeddings(prompt, negative_prompt)
|
| 217 |
+
|
| 218 |
+
def _diffusers_callback(pipe, step_index, timestep, callback_kwargs):
|
| 219 |
+
if step_callback is not None:
|
| 220 |
+
step_callback(step_index + 1, steps)
|
| 221 |
+
return callback_kwargs
|
| 222 |
+
|
| 223 |
+
result = sd_pipe(
|
| 224 |
+
prompt_embeds=prompt_embeds,
|
| 225 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 226 |
+
image=image.convert("RGB"),
|
| 227 |
+
mask_image=dilated_mask.convert("L"),
|
| 228 |
+
num_inference_steps=steps,
|
| 229 |
+
guidance_scale=guidance_scale,
|
| 230 |
+
generator=generator,
|
| 231 |
+
callback_on_step_end=_diffusers_callback,
|
| 232 |
+
).images[0]
|
| 233 |
+
return result
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# Warmup : le premier appel au UNet compile paie le cout de tracing/CUDA
|
| 237 |
+
# graphs (~74s mesures, cf. src/test_torch_compile_unet.py) - on le paie ICI,
|
| 238 |
+
# au demarrage du process, plutot que de le faire subir a la premiere requete
|
| 239 |
+
# utilisateur reelle. Image/masque factices (512x512, forme identique a un
|
| 240 |
+
# vrai appel) suffisent a declencher la compilation ; 2 pas suffisent car le
|
| 241 |
+
# graphe capture est celui d'UN forward du UNet, pas de la boucle entiere.
|
| 242 |
+
#
|
| 243 |
+
# Non pertinent sous ZeroGPU : torch.compile y est desactive (voir plus haut),
|
| 244 |
+
# donc il n'y a rien a "prechauffer" - et un warmup y coherait en plus du
|
| 245 |
+
# quota GPU (facture) a chaque redemarrage de process, plus frequent sous le
|
| 246 |
+
# modele ephemere de ZeroGPU que sur un GPU dedie.
|
| 247 |
+
def _warmup_compiled_unet():
|
| 248 |
+
print("[pipeline] Warmup du UNet compile (paie le cout de compilation au demarrage)...")
|
| 249 |
+
dummy_image = Image.new("RGB", (512, 512), color=(128, 128, 128))
|
| 250 |
+
dummy_mask = Image.new("L", (512, 512), color=255)
|
| 251 |
+
t0 = time.perf_counter()
|
| 252 |
+
generate_inpaint(dummy_image, dummy_mask, "plain fabric", "", steps=2, guidance_scale=7.5, seed=0)
|
| 253 |
+
print(f"[pipeline] Warmup termine en {time.perf_counter() - t0:.1f}s")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if not IS_ZERO_GPU:
|
| 257 |
+
_warmup_compiled_unet()
|
src/service/runner.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Couche d'orchestration partagee entre le endpoint WebSocket (FastAPI) et
|
| 3 |
+
l'interface Gradio, montes dans le MEME process (cf. decision d'architecture :
|
| 4 |
+
mount_gradio_app sur l'app FastAPI, pour que @spaces.GPU reste valide).
|
| 5 |
+
|
| 6 |
+
Contient :
|
| 7 |
+
- GPUQueue : serialise les appels GPU concurrents. Un seul GPU physique est
|
| 8 |
+
partage entre toutes les connexions - pas de vrai batching dynamique
|
| 9 |
+
possible sous ZeroGPU (decision documentee dans projet_2_avancement.md),
|
| 10 |
+
donc on implemente une file FIFO simple plutot qu'un faux "batching".
|
| 11 |
+
Un ThreadPoolExecutor a 1 worker traite les jobs strictement dans l'ordre
|
| 12 |
+
de soumission (FIFO garanti), en dehors de la boucle asyncio (les appels
|
| 13 |
+
modele sont bloquants/synchrones).
|
| 14 |
+
- run_inpaint_stream : pont entre le callback synchrone de diffusion (appele
|
| 15 |
+
depuis le thread GPU) et la boucle asyncio, sous forme de generateur async
|
| 16 |
+
consommable aussi bien par le handler WebSocket que par un callback Gradio
|
| 17 |
+
(Gradio accepte nativement les fonctions generatrices comme gestionnaires
|
| 18 |
+
d'evenements - meme mecanisme de streaming des deux cotes).
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import asyncio
|
| 22 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 23 |
+
from typing import Any, AsyncGenerator, Callable
|
| 24 |
+
|
| 25 |
+
from PIL import Image
|
| 26 |
+
|
| 27 |
+
import pipeline
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class GPUQueue:
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self._executor = ThreadPoolExecutor(max_workers=1)
|
| 33 |
+
|
| 34 |
+
async def run(self, func: Callable, *args, **kwargs) -> Any:
|
| 35 |
+
loop = asyncio.get_running_loop()
|
| 36 |
+
return await loop.run_in_executor(self._executor, lambda: func(*args, **kwargs))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
gpu_queue = GPUQueue()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
async def run_locate(image: Image.Image, text_query: str) -> pipeline.LocateResult:
|
| 43 |
+
return await gpu_queue.run(pipeline.locate_and_segment, image, text_query)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
async def run_inpaint_stream(
|
| 47 |
+
image: Image.Image,
|
| 48 |
+
dilated_mask: Image.Image,
|
| 49 |
+
prompt: str,
|
| 50 |
+
negative_prompt: str,
|
| 51 |
+
steps: int = 30,
|
| 52 |
+
guidance_scale: float = 7.5,
|
| 53 |
+
seed: int = 42,
|
| 54 |
+
) -> AsyncGenerator[tuple, None]:
|
| 55 |
+
"""Yield ("progress", step, total) pendant le debruitage, puis
|
| 56 |
+
("result", PIL.Image) une fois la generation terminee."""
|
| 57 |
+
loop = asyncio.get_running_loop()
|
| 58 |
+
progress_queue: asyncio.Queue = asyncio.Queue()
|
| 59 |
+
|
| 60 |
+
def step_callback(step_index: int, total: int):
|
| 61 |
+
# Appele depuis le thread GPU (executor) : on ne peut pas toucher
|
| 62 |
+
# directement a une asyncio.Queue depuis un autre thread, on planifie
|
| 63 |
+
# donc le put() sur la boucle via call_soon_threadsafe.
|
| 64 |
+
loop.call_soon_threadsafe(progress_queue.put_nowait, (step_index, total))
|
| 65 |
+
|
| 66 |
+
task = asyncio.create_task(
|
| 67 |
+
gpu_queue.run(
|
| 68 |
+
pipeline.generate_inpaint,
|
| 69 |
+
image, dilated_mask, prompt, negative_prompt,
|
| 70 |
+
steps, guidance_scale, seed, step_callback,
|
| 71 |
+
)
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
while not task.done():
|
| 75 |
+
try:
|
| 76 |
+
step_index, total = await asyncio.wait_for(progress_queue.get(), timeout=0.2)
|
| 77 |
+
yield ("progress", step_index, total)
|
| 78 |
+
except asyncio.TimeoutError:
|
| 79 |
+
continue
|
| 80 |
+
|
| 81 |
+
result_image = await task
|
| 82 |
+
while not progress_queue.empty():
|
| 83 |
+
step_index, total = progress_queue.get_nowait()
|
| 84 |
+
yield ("progress", step_index, total)
|
| 85 |
+
yield ("result", result_image)
|
src/service/ws_protocol.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Schemas Pydantic du protocole WebSocket /ws/edit.
|
| 3 |
+
|
| 4 |
+
Deux messages client -> serveur (protocole a 2 phases, cf. decision UX
|
| 5 |
+
"apercu du masque avant generation") :
|
| 6 |
+
1. LocateRequest -> le serveur repond MaskReadyEvent (ou ErrorEvent)
|
| 7 |
+
2. ConfirmRequest -> le serveur repond une serie de ProgressEvent puis un
|
| 8 |
+
ResultEvent (ou ErrorEvent)
|
| 9 |
+
|
| 10 |
+
Une connexion WebSocket = une session d'edition (l'etat image+masque entre
|
| 11 |
+
les deux phases vit le temps de la connexion, cote serveur).
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from typing import List, Literal, Optional
|
| 15 |
+
|
| 16 |
+
from pydantic import BaseModel
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class LocateRequest(BaseModel):
|
| 20 |
+
type: Literal["locate"] = "locate"
|
| 21 |
+
image_b64: str
|
| 22 |
+
text_query: str
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ConfirmRequest(BaseModel):
|
| 26 |
+
type: Literal["confirm"] = "confirm"
|
| 27 |
+
prompt: str
|
| 28 |
+
negative_prompt: str = ""
|
| 29 |
+
steps: int = 30
|
| 30 |
+
guidance_scale: float = 7.5
|
| 31 |
+
seed: int = 42
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class MaskReadyEvent(BaseModel):
|
| 35 |
+
type: Literal["mask_ready"] = "mask_ready"
|
| 36 |
+
mask_b64: str
|
| 37 |
+
box: List[float]
|
| 38 |
+
clip_confidence: float
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ProgressEvent(BaseModel):
|
| 42 |
+
type: Literal["progress"] = "progress"
|
| 43 |
+
stage: Literal["diffusion"] = "diffusion"
|
| 44 |
+
step: int
|
| 45 |
+
total: int
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class ResultEvent(BaseModel):
|
| 49 |
+
type: Literal["result"] = "result"
|
| 50 |
+
image_b64: str
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ErrorEvent(BaseModel):
|
| 54 |
+
type: Literal["error"] = "error"
|
| 55 |
+
message: str
|