File size: 4,766 Bytes
35cdf61 |
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
from fastapi import FastAPI, Request, Response, HTTPException, Query, UploadFile, File
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import io
from scripts.db_helper import insert_ban , search_ban
import uuid
from typing import Optional
import numpy as np
import cv2
import base64
from scripts.comfyui import ComfyUI
from scripts.liveportrait import LP
import os
ui = None
lp = None
def generate_response(response_message, response_status ,uuid_code, metadata):
response_dict = {
"response_message" : response_message,
"response_status" : response_status,
"data" :{
"UUID" : uuid_code,
"metadata" : metadata
}
}
return response_dict
def image_to_base64(image):
_, buffer = cv2.imencode('.png', image)
image_bytes = buffer.tobytes()
base64_image = base64.b64encode(image_bytes).decode('utf-8')
return base64_image
def base64_to_image(base64_string):
image_bytes = base64.b64decode(base64_string)
np_array = np.frombuffer(image_bytes, np.uint8)
image = cv2.imdecode(np_array, cv2.IMREAD_COLOR)
return image
app = FastAPI()
@app.on_event("startup")
async def startup_event():
print("Application is starting up...")
global ui
ui = ComfyUI()
for i in range(10):
if ui.UI():
break
global lp
lp = LP(port = ui.port)
@app.on_event("shutdown")
async def shutdown_event():
print("Application is shutting down...")
global ui
ui = None
global lp
lp = None
# api_key = '4b95dfe8-4644-46ce-a4fe-648d6d4860a4'
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
db_params = {
'dbname': 'API_DB',
'user': 'postgres',
'password': '4b95dfe8-4644-46ce-a4fe-648d6d4860a4',
'host': '44.208.52.100',
'port': '5432'
}
async def custom_middleware(request: Request, call_next):
request_api_key = request.headers.get("api_key")
client_ip = request.client.host
if search_ban(db_params, client_ip):
return JSONResponse(status_code=401, content={"detail": "Unauthorized"})
# if request_api_key != api_key:
# insert_ban(db_params, client_ip, "Access using wrong api_key")
# return JSONResponse(status_code=401, content={"detail": "Unauthorized: Invalid API Key"})
response = await call_next(request)
if (response.status_code == 404) or (response.status_code == 405):
insert_ban(db_params, client_ip, "Access using unapproved method/endpoint")
return JSONResponse(status_code=401, content={"detail": "Unauthorized"})
return response
app.middleware('http')(custom_middleware)
from scripts.db_helper import get_request_data
from scripts.s3 import upload_to_s3, generate_presigned_url
@app.post("/genrate_video")
async def genrate_video(request_id: uuid.UUID):
request_id = str(request_id)
request_data = get_request_data(
db_params=db_params,
request_id=request_id
)
if request_data is None:
return generate_response('Incorrect Request', False ,'', [])
print("update request status to processing")
video = None
try:
print(1)
lp = LP( port = ui.port)
video = lp.LP(request_id, request_data[0], f'/home/ubuntu/AI/videos/{request_data[1]}.mp4')
print(2)
except:
print(3)
server_url = f"http://127.0.0.1:{ui.port}"
if not ui.is_server_ready(server_url, 5):
ui.restart_if_down()
#global lp
lp = LP( port = ui.port)
print(4)
video = lp.LP(request_id, request_data[0], f'/home/ubuntu/AI/videos/{request_data[1]}.mp4')
if video is None:
if ui.is_server_ready(server_url, 5):
print("update request status to error")
bucket = 'app-faceanimate-s3'
local_file_path = f'/home/ubuntu/AI/ComfyUI/output/{video[0]}'
s3_key = f'{request_id}/video.mp4'
upload_to_s3(bucket, local_file_path, s3_key)#apply check and retry
for video_path in video[1]:
os.remove(video_path)
video_url = generate_presigned_url(bucket, s3_key)#apply check and retry
print("update request status to processed")
return generate_response('Video Genrated', True ,'', [video_url])
if __name__ == '__main__':
number_of_workers = 2
import uvicorn
from scripts.comfyui import setup_database
setup_database(number_of_workers)
uvicorn.run("main:app", host='0.0.0.0', port=3000, workers=number_of_workers )#, limit_max_requests=200 )#, timeout_keep_alive=5)
|