-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
58 lines (48 loc) · 1.8 KB
/
app.py
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
from fastapi import FastAPI, File, UploadFile, HTTPException, Request
from fastapi.responses import StreamingResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from PIL import Image
import io
from src.main import FaceSwapper
from src.config import SOURCE_PATH, TARGET_PATH, HOST, PORT
app = FastAPI(
title="DeepFace img to img",
description="An advanced DeepFace system using AI",
version="1.0.0"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
face_swapper = FaceSwapper()
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/swap-face/")
async def swap_face(
source: UploadFile = File(...),
target: UploadFile = File(...),
full_generate: bool = True
):
try:
source_image = Image.open(io.BytesIO(await source.read()))
target_image = Image.open(io.BytesIO(await target.read()))
source_image.save(SOURCE_PATH)
target_image.save(TARGET_PATH)
result_image = face_swapper.swap_face(SOURCE_PATH, TARGET_PATH, full_generate)
img_byte_arr = io.BytesIO()
result_image.save(img_byte_arr, format='JPEG')
img_byte_arr = img_byte_arr.getvalue()
return StreamingResponse(io.BytesIO(img_byte_arr), media_type="image/jpeg")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host=HOST, port=PORT)