Ashrafb commited on
Commit
f0c148a
·
verified ·
1 Parent(s): cdb8162

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +46 -2
main.py CHANGED
@@ -1,4 +1,48 @@
1
- import os
 
 
 
 
 
 
 
 
2
 
 
3
 
4
- exec(os.environ.get('CODE'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, Form
2
+ from fastapi.responses import StreamingResponse
3
+ from fastapi.staticfiles import StaticFiles
4
+ import torch
5
+ import shutil
6
+ import cv2
7
+ import numpy as np
8
+ import io
9
+ from io import BytesIO
10
 
11
+ app = FastAPI()
12
 
13
+ # Load model and necessary components
14
+ from vtoonify_model import Model
15
+ model = Model(device='cuda' if torch.cuda.is_available() else 'cpu')
16
+ model.load_model('cartoon1-d')
17
+
18
+ from fastapi.middleware.cors import CORSMiddleware
19
+
20
+ app.add_middleware(
21
+ CORSMiddleware,
22
+ allow_origins=["*"], # Adjust as needed, '*' allows requests from any origin
23
+ allow_credentials=True,
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ @app.post("/upload/")
29
+ async def process_image(file: UploadFile = File(...), top: int = Form(...), bottom: int = Form(...), left: int = Form(...), right: int = Form(...)):
30
+ # Read the uploaded image file
31
+ contents = await file.read()
32
+
33
+ # Convert the uploaded image to numpy array
34
+ nparr = np.frombuffer(contents, np.uint8)
35
+ frame_rgb = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
36
+
37
+ # Process the uploaded image
38
+ aligned_face, instyle, message = model.detect_and_align_image(frame_rgb, top, bottom, left, right)
39
+ processed_image, message = model.image_toonify(aligned_face, instyle, model.exstyle, style_degree=0.5, style_type='cartoon1-d')
40
+
41
+ # Convert BGR to RGB
42
+ processed_image_rgb = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)
43
+
44
+ # Convert processed image to bytes
45
+ _, encoded_image = cv2.imencode('.jpg', processed_image_rgb)
46
+
47
+ # Return the processed image as a streaming response
48
+ return StreamingResponse(BytesIO(encoded_image.tobytes()), media_type="image/jpeg")