Ashrafb commited on
Commit
c0cfc30
·
verified ·
1 Parent(s): 408728b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +27 -2
main.py CHANGED
@@ -17,18 +17,43 @@ exstyle, message = model.load_model("cartoon1")
17
  class ImageRequest(BaseModel):
18
  image_file: UploadFile = File(...)
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  @app.post("/upload/")
21
  async def toonify_image(image_file: UploadFile = File(...)):
22
  try:
 
23
  contents = await image_file.read()
24
- filename = image_file.filename
 
 
 
 
 
25
  nparr = np.frombuffer(contents, np.uint8)
 
26
  img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
 
 
27
  aligned_face, instyle, message = model.detect_and_align_image(img, 200, 200, 200, 200) # Hardcoded values
28
  toonified_img, message = model.image_toonify(aligned_face, instyle, exstyle, style_degree=0.5, style_type="cartoon1")
 
 
29
  return {"toonified_image": toonified_img, "message": message, "filename": filename}
30
  except Exception as e:
31
- return {"error": str(e)}
 
32
 
33
  app.mount("/", StaticFiles(directory="AB", html=True), name="static")
34
 
 
17
  class ImageRequest(BaseModel):
18
  image_file: UploadFile = File(...)
19
 
20
+ from fastapi import FastAPI, File, UploadFile
21
+ from fastapi.responses import JSONResponse
22
+ import numpy as np
23
+ import cv2
24
+ import torch
25
+ from vtoonify_model import Model
26
+
27
+ app = FastAPI()
28
+
29
+ # Load the model
30
+ model = Model(device='cuda' if torch.cuda.is_available() else 'cpu')
31
+ exstyle, message = model.load_model("cartoon1")
32
+
33
  @app.post("/upload/")
34
  async def toonify_image(image_file: UploadFile = File(...)):
35
  try:
36
+ # Read the contents of the uploaded file
37
  contents = await image_file.read()
38
+ # Determine the file extension from the content type
39
+ ext = image_file.content_type.split("/")[-1]
40
+ # Construct a unique filename with the extension
41
+ filename = f"uploaded_image.{ext}"
42
+
43
+ # Convert the file contents to a numpy array
44
  nparr = np.frombuffer(contents, np.uint8)
45
+ # Decode the image using OpenCV
46
  img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
47
+
48
+ # Perform image processing with the model
49
  aligned_face, instyle, message = model.detect_and_align_image(img, 200, 200, 200, 200) # Hardcoded values
50
  toonified_img, message = model.image_toonify(aligned_face, instyle, exstyle, style_degree=0.5, style_type="cartoon1")
51
+
52
+ # Return the processed image and filename
53
  return {"toonified_image": toonified_img, "message": message, "filename": filename}
54
  except Exception as e:
55
+ # Return an error response if an exception occurs
56
+ return JSONResponse(status_code=500, content={"error": str(e)})
57
 
58
  app.mount("/", StaticFiles(directory="AB", html=True), name="static")
59