d0tpy commited on
Commit
b5e6b91
·
verified ·
1 Parent(s): 928abbe

Create video_enhancer.py (#2)

Browse files

- Create video_enhancer.py (4a8a636b8a3755916d0c4b54ad83db16ec5a645f)
- Update app.py (d03c20e7b110f2709088eefd81cea548ab53945e)

Files changed (2) hide show
  1. app.py +25 -2
  2. video_enhancer.py +68 -0
app.py CHANGED
@@ -1,11 +1,13 @@
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.responses import StreamingResponse
3
  from ./image_enhancer import EnhancementMethod, Enhancer
 
4
  from pydantic import BaseModel
5
  from PIL import Image
6
  from io import BytesIO
7
  import base64
8
  import numpy as np
 
9
 
10
  class EnhancementRequest(BaseModel):
11
  method: EnhancementMethod = EnhancementMethod.gfpgan
@@ -23,7 +25,7 @@ app = FastAPI()
23
  def greet_json():
24
  return {"Initializing GlamApp Enhancer"}
25
 
26
- @app.post("/enhance")
27
  async def enhance_image(
28
  file: UploadFile = File(...),
29
  request: EnhancementRequest = EnhancementRequest()
@@ -48,4 +50,25 @@ async def enhance_image(
48
  return StreamingResponse(img_byte_arr, media_type="image/png")
49
 
50
  except Exception as e:
51
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.responses import StreamingResponse
3
  from ./image_enhancer import EnhancementMethod, Enhancer
4
+ from vidoe_enhancer import VideoEnhancer
5
  from pydantic import BaseModel
6
  from PIL import Image
7
  from io import BytesIO
8
  import base64
9
  import numpy as np
10
+ import magic
11
 
12
  class EnhancementRequest(BaseModel):
13
  method: EnhancementMethod = EnhancementMethod.gfpgan
 
25
  def greet_json():
26
  return {"Initializing GlamApp Enhancer"}
27
 
28
+ @app.post("/enhance/image/")
29
  async def enhance_image(
30
  file: UploadFile = File(...),
31
  request: EnhancementRequest = EnhancementRequest()
 
50
  return StreamingResponse(img_byte_arr, media_type="image/png")
51
 
52
  except Exception as e:
53
+ raise HTTPException(status_code=500, detail=str(e))
54
+
55
+ @app.post("/enhance/video/")
56
+ async def enhance_video(file: UploadFile = File(...)):
57
+ enhancer = VideoEnhancer()
58
+ file_header = await file.read(1024)
59
+ file.file.seek(0)
60
+ mime = magic.Magic(mime=True)
61
+ file_mime_type = mime.from_buffer(file_header)
62
+
63
+ accepted_mime_types = [
64
+ 'video/mp4',
65
+ 'video/mpeg',
66
+ 'video/x-msvideo',
67
+ 'video/quicktime',
68
+ 'video/x-matroska',
69
+ 'video/webm'
70
+ ]
71
+
72
+ if file_mime_type not in accepted_mime_types:
73
+ raise HTTPException(status_code=400, detail="Invalid file type. Please upload a video file.")
74
+ return await enhancer.stream_enhanced_video(file)
video_enhancer.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import torch
4
+ import io
5
+ import asyncio
6
+ from basicsr.archs.rrdbnet_arch import RRDBNet
7
+ from realesrgan import RealESRGANer
8
+ from huggingface_hub import hf_hub_download
9
+ from concurrent.futures import ThreadPoolExecutor
10
+
11
+ class VideoEnhancer:
12
+ def __init__(self, model_name="RealESRGAN_x4plus"):
13
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
14
+ self.model = self.load_model(model_name)
15
+ self.executor = ThreadPoolExecutor(max_workers=4)
16
+
17
+ def load_model(self, model_name):
18
+ if model_name == "RealESRGAN_x4plus":
19
+ model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
20
+ model_path = hf_hub_download("schwgHao/RealESRGAN_x4plus", "RealESRGAN_x4plus.pth")
21
+ return RealESRGANer(scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=True)
22
+ else:
23
+ raise ValueError(f"Unsupported model: {model_name}")
24
+
25
+ async def enhance_frame(self, frame):
26
+ loop = asyncio.get_running_loop()
27
+
28
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
29
+
30
+ enhanced, _ = await loop.run_in_executor(self.executor, self.model.enhance, frame_rgb)
31
+
32
+ return cv2.cvtColor(enhanced, cv2.COLOR_RGB2BGR)
33
+
34
+ async def process_video(self, input_bytes, output_bytes):
35
+ cap = cv2.VideoCapture(input_bytes)
36
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
37
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
38
+ fps = cap.get(cv2.CAP_PROP_FPS)
39
+
40
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
41
+ out = cv2.VideoWriter(output_bytes, fourcc, fps, (width * 4, height * 4))
42
+
43
+ while cap.isOpened():
44
+ ret, frame = cap.read()
45
+ if not ret:
46
+ break
47
+ enhanced_frame = await self.enhance_frame(frame)
48
+ out.write(enhanced_frame)
49
+
50
+ cap.release()
51
+ out.release()
52
+
53
+ async def stream_enhanced_video(self, video_file):
54
+ video_bytes = await video_file.read()
55
+ cap = cv2.VideoCapture(io.BytesIO(video_bytes).getvalue())
56
+
57
+ async def generate():
58
+ while cap.isOpened():
59
+ ret, frame = cap.read()
60
+ if not ret:
61
+ break
62
+ enhanced_frame = await self.enhance_frame(frame)
63
+ _, buffer = cv2.imencode('.jpg', enhanced_frame)
64
+ yield (b'--frame\r\n'
65
+ b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
66
+ cap.release()
67
+
68
+ return StreamingResponse(generate(), media_type="multipart/x-mixed-replace; boundary=frame")