ariansyahdedy commited on
Commit
bdadf45
·
1 Parent(s): 4b00fa3
__init__.py ADDED
File without changes
__pycache__/main.cpython-310.pyc ADDED
Binary file (744 Bytes). View file
 
__pycache__/video.cpython-310.pyc ADDED
Binary file (3.37 kB). View file
 
app/__pycache__/main.cpython-310.pyc ADDED
Binary file (773 Bytes). View file
 
app/routers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (164 Bytes). View file
 
app/routers/__pycache__/video.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
main.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Depends, HTTPException, status, File, UploadFile
2
+ from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+
5
+ from typing import List
6
+
7
+ import video
8
+ from typing import Annotated
9
+ # from transparent_background import Remover
10
+
11
+
12
+ from datetime import timedelta
13
+
14
+ app = FastAPI()
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+
24
+ app.include_router(video.router)
output_frames/end (1)_first_frame.png ADDED
output_frames/end (2)_first_frame.png ADDED
requirements.txt ADDED
Binary file (2.42 kB). View file
 
video.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, UploadFile, File, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ import cv2
4
+ import numpy as np
5
+ # from PIL import Image
6
+ from transparent_background import Remover
7
+ import os
8
+ import uuid
9
+ import aiofiles
10
+ import logging
11
+ from fastapi.responses import JSONResponse, FileResponse
12
+ # from quart import Quart
13
+ # from quart_cors import cors
14
+
15
+ router = APIRouter(
16
+ tags=["video"],
17
+ responses = {404:{"description":"Not Found"}},)
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ @router.get("/")
22
+ async def test():
23
+ return ("test")
24
+
25
+ router = APIRouter(
26
+ tags=["upload"],
27
+ responses={404: {"description": "Not found"}},
28
+ )
29
+ @router.get("/static/storage/{filename}")
30
+ async def getfile(id: str, type: str, filename: str):
31
+
32
+ # Ensure the filename is concatenated correctly
33
+ file_path = fr"C:\Users\HiDigi\OneDrive\Desktop\WebDev\ChangeBackground\output_frames\{filename}"
34
+ # print(file_path)
35
+ # Check if the file exists
36
+ if not os.path.exists(file_path):
37
+ raise HTTPException(status_code=404, detail="File not found")
38
+
39
+ # Return the file as a FileResponse
40
+ return FileResponse(path=file_path, filename=filename)
41
+
42
+ async def save_first_frame(video_path, output_image_path):
43
+ """
44
+ Save the first frame of a video as an image.
45
+
46
+ Args:
47
+ video_path (str): Path to the input video file.
48
+ output_image_path (str): Path to save the output image file.
49
+
50
+ Returns:
51
+ bool: True if successful, False otherwise.
52
+ """
53
+ try:
54
+ # Load external library
55
+ # remover = Remover(device='cuda:0')
56
+ remover = Remover()
57
+
58
+ # Open the video file
59
+ cap = cv2.VideoCapture(video_path)
60
+ print(cap)
61
+ # Check if video opened successfully
62
+ if not cap.isOpened():
63
+ logger.error(f"Error: Cannot open video file {video_path}")
64
+ return False
65
+
66
+ # Read the first frame
67
+ ret, frame = cap.read()
68
+ print(ret)
69
+ print(frame)
70
+ # If a frame was read successfully, save it
71
+ if ret:
72
+ # out = remover.process(frame) # same as above
73
+ # Check if 'out' is a numpy array (which is expected)
74
+ if isinstance(frame, np.ndarray):
75
+ cv2.imwrite(output_image_path,frame)
76
+ logger.info(f"First frame saved to {output_image_path}")
77
+ success = True
78
+ else:
79
+ logger.error(f"Unexpected output type from remover.process: {type(out)}")
80
+ success = False
81
+
82
+ # cv2.imwrite(output_image_path, out)
83
+ # logger.info(f"First frame saved to {output_image_path}")
84
+ # success = True
85
+ else:
86
+ logger.error(f"Error: Cannot read the first frame of {video_path}")
87
+ success = False
88
+
89
+ cap.release()
90
+ return success
91
+ except Exception as e:
92
+ logger.error(f"Error processing video: {e}")
93
+ return False
94
+
95
+ async def process_video_and_return_url(video_file: UploadFile):
96
+ upload_dir = "uploaded_videos"
97
+ os.makedirs(upload_dir, exist_ok=True)
98
+ video_path = os.path.join(upload_dir, video_file.filename)
99
+ output_dir = "output_frames"
100
+ os.makedirs(output_dir, exist_ok=True)
101
+ output_image_path = (os.path.join(output_dir, f"{os.path.splitext(video_file.filename)[0]}_first_frame.png")).replace("\\", "/")
102
+
103
+ # Save the uploaded video file
104
+ try:
105
+ async with aiofiles.open(video_path, "wb") as f:
106
+ content = await video_file.read()
107
+ await f.write(content)
108
+ except Exception as e:
109
+ logger.error(f"Error saving uploaded video: {e}")
110
+ raise HTTPException(status_code=500, detail="Failed to save uploaded video")
111
+
112
+
113
+ # Process the video asynchronously
114
+ success = await save_first_frame(video_path, output_image_path)
115
+ if success:
116
+ os.remove(video_path)
117
+ return {"urlDownloaded": f"/static/storage/{os.path.splitext(video_file.filename)[0]}_first_frame.png"}
118
+ else:
119
+ return JSONResponse(status_code=400, content={"message": "Failed to process the video"})
120
+
121
+ @router.post("/extract_first_frame/")
122
+ async def upload_video_and_return_url(file: UploadFile = File(...)):
123
+ return await process_video_and_return_url(file)