Skip to content

Improved video generation , performance and quality #742

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ node_modules
./models/*

venv/
.venv
.venv
/.vs
2 changes: 1 addition & 1 deletion README-en.md
Original file line number Diff line number Diff line change
Expand Up @@ -386,4 +386,4 @@ Click to view the [`LICENSE`](LICENSE) file

## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=harry0703/MoneyPrinterTurbo&type=Date)](https://star-history.com/#harry0703/MoneyPrinterTurbo&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=harry0703/MoneyPrinterTurbo&type=Date)](https://star-history.com/#harry0703/MoneyPrinterTurbo&Date)
113 changes: 81 additions & 32 deletions app/controllers/v1/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import shutil
from typing import Union

from fastapi import BackgroundTasks, Depends, Path, Request, UploadFile
from fastapi import BackgroundTasks, Depends, Path, Query, Request, UploadFile
from fastapi.params import File
from fastapi.responses import FileResponse, StreamingResponse
from loguru import logger
Expand Down Expand Up @@ -41,7 +41,10 @@
_redis_password = config.app.get("redis_password", None)
_max_concurrent_tasks = config.app.get("max_concurrent_tasks", 5)

redis_url = f"redis://:{_redis_password}@{_redis_host}:{_redis_port}/{_redis_db}"
if _redis_password:
redis_url = f"redis://:{_redis_password}@{_redis_host}:{_redis_port}/{_redis_db}"
else:
redis_url = f"redis://{_redis_host}:{_redis_port}/{_redis_db}"
# 根据配置选择合适的任务管理器
if _enable_redis:
task_manager = RedisTaskManager(
Expand Down Expand Up @@ -94,8 +97,6 @@ def create_task(
task_id=task_id, status_code=400, message=f"{request_id}: {str(e)}"
)

from fastapi import Query

@router.get("/tasks", response_model=TaskQueryResponse, summary="Get all tasks")
def get_all_tasks(request: Request, page: int = Query(1, ge=1), page_size: int = Query(10, ge=1)):
request_id = base.get_task_id(request)
Expand Down Expand Up @@ -131,7 +132,7 @@ def get_task(

def file_to_uri(file):
if not file.startswith(endpoint):
_uri_path = v.replace(task_dir, "tasks").replace("\\", "/")
_uri_path = file.replace(task_dir, "tasks").replace("\\", "/")
_uri_path = f"{endpoint}/{_uri_path}"
else:
_uri_path = file
Expand Down Expand Up @@ -227,20 +228,44 @@ def upload_bgm_file(request: Request, file: UploadFile = File(...)):
async def stream_video(request: Request, file_path: str):
tasks_dir = utils.task_dir()
video_path = os.path.join(tasks_dir, file_path)

# Check if the file exists
if not os.path.exists(video_path):
raise HttpException(
"", status_code=404, message=f"File not found: {file_path}"
)

range_header = request.headers.get("Range")
video_size = os.path.getsize(video_path)
start, end = 0, video_size - 1

length = video_size
if range_header:
range_ = range_header.split("bytes=")[1]
start, end = [int(part) if part else None for part in range_.split("-")]
if start is None:
start = video_size - end
end = video_size - 1
if end is None:
end = video_size - 1
length = end - start + 1
try:
range_ = range_header.split("bytes=")[1]
start, end = [int(part) if part else None for part in range_.split("-")]

if start is None and end is not None:
# Format: bytes=-N (last N bytes)
start = max(0, video_size - end)
end = video_size - 1
elif end is None:
# Format: bytes=N- (from byte N to the end)
end = video_size - 1

# Ensure values are within valid range
start = max(0, min(start, video_size - 1))
end = min(end, video_size - 1)

if start > end:
# Invalid range, serve entire file
start, end = 0, video_size - 1

length = end - start + 1
except (ValueError, IndexError):
# On parsing error, serve entire content
start, end = 0, video_size - 1
length = video_size

def file_iterator(file_path, offset=0, bytes_to_read=None):
with open(file_path, "rb") as f:
Expand All @@ -258,30 +283,54 @@ def file_iterator(file_path, offset=0, bytes_to_read=None):
file_iterator(video_path, start, length), media_type="video/mp4"
)
response.headers["Content-Range"] = f"bytes {start}-{end}/{video_size}"
response.headers["Accept-Ranges"] = "bytes"
response.headers["Content-Length"] = str(length)
response.status_code = 206 # Partial Content

return response


@router.get("/download/{file_path:path}")
async def download_video(_: Request, file_path: str):
async def download_video(request: Request, file_path: str):
"""
download video
:param _: Request request
:param request: Request request
:param file_path: video file path, eg: /cd1727ed-3473-42a2-a7da-4faafafec72b/final-1.mp4
:return: video file
"""
tasks_dir = utils.task_dir()
video_path = os.path.join(tasks_dir, file_path)
file_path = pathlib.Path(video_path)
filename = file_path.stem
extension = file_path.suffix
headers = {"Content-Disposition": f"attachment; filename={filename}{extension}"}
return FileResponse(
path=video_path,
headers=headers,
filename=f"{filename}{extension}",
media_type=f"video/{extension[1:]}",
)
try:
tasks_dir = utils.task_dir()
video_path = os.path.join(tasks_dir, file_path)

# Check if the file exists
if not os.path.exists(video_path):
raise HttpException(
"", status_code=404, message=f"File not found: {file_path}"
)

# Check if the file is readable
if not os.access(video_path, os.R_OK):
logger.error(f"File not readable: {video_path}")
raise HttpException(
"", status_code=403, message=f"File not accessible: {file_path}"
)

# Get the filename and extension
path_obj = pathlib.Path(video_path)
filename = path_obj.stem
extension = path_obj.suffix

# Determine appropriate media type
media_type = "application/octet-stream"
if extension.lower() in ['.mp4', '.webm']:
media_type = f"video/{extension[1:]}"

headers = {"Content-Disposition": f"attachment; filename={filename}{extension}"}

logger.info(f"Sending file: {video_path}, size: {os.path.getsize(video_path)}")
return FileResponse(
path=video_path,
headers=headers,
filename=f"{filename}{extension}",
media_type=media_type,
)
except Exception as e:
logger.exception(f"Error downloading file: {str(e)}")
raise HttpException(
"", status_code=500, message=f"Failed to download file: {str(e)}"
)
1 change: 0 additions & 1 deletion app/services/utils/video_effects.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from moviepy import Clip, vfx


# FadeIn
def fadein_transition(clip: Clip, t: float) -> Clip:
return clip.with_effects([vfx.FadeIn(t)])
Expand Down
Loading