Skip to content

Commit 71100d3

Browse files
committed
✨feat: Add async handling for file upload
- Refactor the `create_upload_file` function to use `async` and `await` - Read the contents of the uploaded file asynchronously using `await file.read()` - Open the image using `PIL.Image.open` and convert it to RGB - Generate the caption using `BlipInterrogator.generate_caption` - Return the caption as a JSON response This commit adds async handling for file uploads in the `app.py` file.
1 parent ccd25a0 commit 71100d3

File tree

2 files changed

+12
-16
lines changed

2 files changed

+12
-16
lines changed

app.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@
33
# @FileName: main.py
44
# @Software: PyCharm
55
# @Github :sudoskys
6-
import shutil
7-
import tempfile
8-
from typing import Optional
6+
import io
97

108
import rtoml
119
import uvicorn
1210
from PIL import Image
13-
from fastapi import FastAPI, UploadFile
11+
from fastapi import FastAPI, UploadFile, File
1412
from loguru import logger
13+
from starlette.responses import JSONResponse
1514

1615
from utils import Blip
1716

@@ -41,17 +40,14 @@
4140

4241

4342
@app.post("/upload/")
44-
def create_upload_file(file: Optional[UploadFile] = None):
45-
if not file.file:
46-
return {"code": 0, "message": "No upload file sent"}
47-
else:
48-
with tempfile.NamedTemporaryFile(suffix=".png") as buffer:
49-
shutil.copyfileobj(file.file, buffer)
50-
image_pil = Image.open(buffer.name).convert('RGB')
51-
if image_pil:
52-
BlipInterrogatorText = BlipInterrogator.generate_caption(
53-
pil_image=image_pil)
54-
return {"code": 1, "message": BlipInterrogatorText}
43+
async def create_upload_file(file: UploadFile = File(...)):
44+
contents = await file.read()
45+
image_pil = Image.open(io.BytesIO(contents)).convert('RGB')
46+
if image_pil:
47+
blip_interrogator_text = BlipInterrogator.generate_caption(pil_image=image_pil)
48+
return JSONResponse(
49+
content={"text": blip_interrogator_text}
50+
)
5551

5652

5753
if __name__ == '__main__':

config.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[blip]
22
low_vram = true
3-
device = "cpu" # cpu
3+
device = "cpu" # cuda or cpu
44

55
[server]
66
host = '127.0.0.1'

0 commit comments

Comments
 (0)