iamvishalksingh commited on
Commit
b0a393a
·
verified ·
1 Parent(s): 221cc28

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -29
app.py CHANGED
@@ -1,40 +1,35 @@
1
- import sys
2
- import os
 
 
3
  import torch
4
- import gradio as gr
5
- from fastapi import FastAPI, UploadFile, File
6
  import uvicorn
7
- from PIL import Image
8
- import io
9
-
10
- # Ensure the `basicsr` directory is in the system path
11
- current_dir = os.path.dirname(os.path.abspath(__file__))
12
- sys.path.append(os.path.join(current_dir, "basicsr"))
13
 
14
- # Import the inference function
15
- from inference_codeformer import inference
16
 
17
  app = FastAPI()
18
 
19
- # Load the CodeFormer model
20
- model_path = "weights/CodeFormer.pth"
21
- device = "cuda" if torch.cuda.is_available() else "cpu"
22
-
23
  @app.post("/enhance")
24
- async def enhance_image(file: UploadFile = File(...), upscale: int = 2, fidelity: float = 0.5):
25
- """API Endpoint to enhance images using CodeFormer"""
26
- image = Image.open(io.BytesIO(await file.read()))
27
- image.save("input.png")
 
 
 
 
 
 
 
 
28
 
29
- output_path = inference(
30
- input_path="input.png",
31
- upscale=upscale,
32
- fidelity=fidelity,
33
- model_path=model_path,
34
- device=device
35
- )
36
 
37
- return {"enhanced_image": f"https://your-space-name.hf.space/{output_path}"}
 
38
 
 
39
  if __name__ == "__main__":
40
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from fastapi.responses import Response
3
+ from io import BytesIO
4
+ from PIL import Image
5
  import torch
 
 
6
  import uvicorn
7
+ import os
 
 
 
 
 
8
 
9
+ # Import the CodeFormer model processing function
10
+ from codeformer_model import enhance_image # Make sure this function is defined
11
 
12
  app = FastAPI()
13
 
 
 
 
 
14
  @app.post("/enhance")
15
+ async def enhance_image_api(file: UploadFile = File(...)):
16
+ try:
17
+ # Load image
18
+ image = Image.open(file.file).convert("RGB")
19
+
20
+ # Process the image using the CodeFormer model
21
+ enhanced_image = enhance_image(image)
22
+
23
+ # Convert the processed image to bytes
24
+ img_byte_arr = BytesIO()
25
+ enhanced_image.save(img_byte_arr, format="PNG")
26
+ img_byte_arr = img_byte_arr.getvalue()
27
 
28
+ return Response(content=img_byte_arr, media_type="image/png")
 
 
 
 
 
 
29
 
30
+ except Exception as e:
31
+ return {"error": str(e)}
32
 
33
+ # Required to run on Hugging Face Spaces
34
  if __name__ == "__main__":
35
+ uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))