Spaces:
Paused
Paused
Commit ·
b496d68
1
Parent(s): aa87c7c
fix
Browse files
app.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import StreamingResponse
|
| 3 |
from huggingface_hub import InferenceClient
|
|
@@ -51,17 +52,29 @@ def generate_stream(request: PredictionRequest):
|
|
| 51 |
yield f"Error: {str(e)}\n"
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
@app.post("/predict")
|
| 55 |
def predict(request: PredictionRequest):
|
| 56 |
"""
|
| 57 |
Endpoint REST avec réponse en streaming synchrone.
|
| 58 |
"""
|
| 59 |
-
return
|
| 60 |
generate_stream(request),
|
| 61 |
media_type="text/plain" # Peut être changé en JSON si nécessaire
|
| 62 |
)
|
| 63 |
|
| 64 |
|
|
|
|
| 65 |
# Pour le test en local
|
| 66 |
if __name__ == "__main__":
|
| 67 |
import uvicorn
|
|
|
|
| 1 |
+
from starlette.types import Message
|
| 2 |
from fastapi import FastAPI, HTTPException
|
| 3 |
from fastapi.responses import StreamingResponse
|
| 4 |
from huggingface_hub import InferenceClient
|
|
|
|
| 52 |
yield f"Error: {str(e)}\n"
|
| 53 |
|
| 54 |
|
| 55 |
+
class CustomStreamingResponse(StreamingResponse):
|
| 56 |
+
"""
|
| 57 |
+
Personnalisation de StreamingResponse pour s'assurer que chaque chunk est envoyé immédiatement.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
async def stream_response(self, send: Message):
|
| 61 |
+
async for chunk in self.body_iterator:
|
| 62 |
+
await send({"type": "http.response.body", "body": chunk, "more_body": True})
|
| 63 |
+
await send({"type": "http.response.body", "body": b"", "more_body": False})
|
| 64 |
+
|
| 65 |
+
|
| 66 |
@app.post("/predict")
|
| 67 |
def predict(request: PredictionRequest):
|
| 68 |
"""
|
| 69 |
Endpoint REST avec réponse en streaming synchrone.
|
| 70 |
"""
|
| 71 |
+
return CustomStreamingResponse(
|
| 72 |
generate_stream(request),
|
| 73 |
media_type="text/plain" # Peut être changé en JSON si nécessaire
|
| 74 |
)
|
| 75 |
|
| 76 |
|
| 77 |
+
|
| 78 |
# Pour le test en local
|
| 79 |
if __name__ == "__main__":
|
| 80 |
import uvicorn
|