利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
feat(api): support artifact HEAD requests (#1636)
Rudy Mizrahi Celekli899d2946d1cc
diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.pyindex 401278f1..20539aba 100644--- a/app/controllers/v1/video.py+++ b/app/controllers/v1/video.py@@ -7,7 +7,7 @@ from urllib.parse import quotefrom fastapi import BackgroundTasks, Depends, Path, Query, Request, UploadFilefrom fastapi.params import File-from fastapi.responses import FileResponse, StreamingResponse+from fastapi.responses import FileResponse, Response, StreamingResponsefrom loguru import loggerfrom starlette.background import BackgroundTask@@ -501,6 +501,7 @@ def upload_video_material_file(request: Request, file: UploadFile = File(...)):return utils.get_response(200, response)@router.get("/stream/{file_path:path}")[email protected]("/stream/{file_path:path}", summary="Inspect video stream metadata")async def stream_video(request: Request, file_path: str):request_id = base.get_task_id(request)tasks_dir = utils.task_dir()@@ -519,6 +520,14 @@ async def stream_video(request: Request, file_path: str):) from exctry:video_size = os.fstat(video_file.fileno()).st_size+ if request.method == "HEAD":+ # Range applies to GET only. Close before returning metadata; no+ # generator or deferred background cleanup is needed for HEAD.+ video_file.close()+ return Response(+ media_type="video/mp4",+ headers={"Accept-Ranges": "bytes", "Content-Length": str(video_size)},+ )start, end = _parse_byte_range(range_header, video_size, request_id)except Exception:video_file.close()@@ -553,6 +562,7 @@ async def stream_video(request: Request, file_path: str):@router.get("/download/{file_path:path}")[email protected]("/download/{file_path:path}", summary="Inspect artifact download metadata")async def download_video(request: Request, file_path: str):"""download video@@ -566,8 +576,24 @@ async def download_video(request: Request, file_path: str):file_path = pathlib.Path(video_path)filename = file_path.namemedia_type, _ = mimetypes.guess_type(filename)- return FileResponse(+ stat_result = None+ if request.method == "HEAD":+ try:+ stat_result = os.stat(video_path)+ except FileNotFoundError as exc:+ raise HttpException(+ task_id=request_id,+ status_code=404,+ message=f"{request_id}: file no longer exists",+ ) from exc+ response = FileResponse(path=video_path,filename=filename,media_type=media_type or "application/octet-stream",+ stat_result=stat_result,)+ if request.method == "HEAD":+ # Reuse FileResponse's metadata without reading its body or applying+ # GET-only Range processing to this HEAD request.+ return Response(headers=response.headers)+ return responsediff --git a/docs/artifact-metadata.md b/docs/artifact-metadata.mdnew file mode 100644index 00000000..4e03ff36--- /dev/null+++ b/docs/artifact-metadata.md@@ -0,0 +1,17 @@+# Inspect artifact metadata++The artifact endpoints accept `HEAD` as well as `GET`:++```sh+curl --head http://localhost:8080/api/v1/stream/TASK_ID/final-1.mp4+curl --head http://localhost:8080/api/v1/download/TASK_ID/final-1.mp4+```++HEAD returns the full artifact's content length and media type without sending+its bytes. Downloads also return the existing attachment filename and file+metadata headers. Supply the same authentication as GET when an API key is+configured. Missing files and paths outside task storage retain their existing+error statuses. Range and If-Range do not select partial representations for+HEAD; send GET with Range to retrieve part of a stream. An empty artifact has+length zero. A successful metadata request does not validate video decoding or+guarantee that a subsequent request will see the same file.diff --git a/test/services/test_artifact_http_head.py b/test/services/test_artifact_http_head.pynew file mode 100644index 00000000..44bb8fcf--- /dev/null+++ b/test/services/test_artifact_http_head.py@@ -0,0 +1,85 @@+"""Real ASGI HEAD requests through the authenticated artifact router."""++from unittest.mock import patch++import pytest+from fastapi.testclient import TestClient++from app import asgi+from app.config import config+from app.controllers.v1 import video as controller+++def client(tmp_path):+ task = tmp_path / "task"+ task.mkdir()+ (task / "final.mp4").write_bytes(b"ten bytes!")+ (task / "empty.mp4").touch()+ with patch.dict(config.app, {"api_key": ""}), patch.object(+ controller.utils, "task_dir", return_value=str(tmp_path)+ ):+ yield TestClient(asgi.get_application())++[email protected]("endpoint", ["stream", "download"])+def test_metadata_without_body_matches_get(client, endpoint):+ url = f"/api/v1/{endpoint}/task/final.mp4"+ head = client.head(url)+ full = client.get(url)+ assert head.status_code == full.status_code == 200+ assert head.content == b""+ for key in ("content-length", "content-type", "accept-ranges"):+ assert head.headers[key] == full.headers[key]+ assert head.headers["content-length"] == "10"++[email protected]("endpoint", ["stream", "download"])[email protected]("range_header", ["bytes=1-3", "bytes=99-", "not a range"])+def test_head_ignores_range_for_metadata(client, endpoint, range_header):+ response = client.head(+ f"/api/v1/{endpoint}/task/final.mp4", headers={"Range": range_header}+ )+ assert response.status_code == 200+ assert response.headers["content-length"] == "10"+ assert "content-range" not in response.headers+ assert response.content == b""++[email protected]("endpoint", ["stream", "download"])+def test_empty_artifact_metadata(client, endpoint):+ response = client.head(f"/api/v1/{endpoint}/task/empty.mp4")+ assert response.status_code == 200+ assert response.headers["content-length"] == "0"+ assert response.content == b""++[email protected]("endpoint", ["stream", "download"])+def test_head_retains_authentication_and_missing_file_status(client, endpoint):+ with patch.dict(config.app, {"api_key": "head-test-key"}):+ assert client.head(f"/api/v1/{endpoint}/task/final.mp4").status_code == 401+ response = client.head(f"/api/v1/{endpoint}/task/missing.mp4")+ assert response.status_code == 404+ assert response.content == b""++[email protected]("endpoint", ["stream", "download"])+def test_head_retains_path_boundary(client, endpoint):+ response = client.head(f"/api/v1/{endpoint}/%2E%2E%2Foutside.mp4")+ assert response.status_code == 403+ assert response.content == b""+++def test_download_head_reports_task_deleted_after_resolution(client):+ resolve = controller._resolve_path_within_directory++ def deleting_resolver(*args):+ path = resolve(*args)+ controller.os.unlink(path)+ return path++ client.raise_server_exceptions = False+ with patch.object(controller, "_resolve_path_within_directory", deleting_resolver):+ response = client.head("/api/v1/download/task/final.mp4")+ assert response.status_code == 404+ assert response.content == b""diff --git a/test/services/test_controller_video.py b/test/services/test_controller_video.pyindex b94cc681..9fe93d8f 100644--- a/test/services/test_controller_video.py+++ b/test/services/test_controller_video.py@@ -35,7 +35,7 @@ class TestVideoControllerHelpers(unittest.TestCase):headers = {"x-task-id": "request-123"}if range_header is not None:headers["Range"] = range_header- return SimpleNamespace(headers=headers)+ return SimpleNamespace(headers=headers, method="GET")def test_sanitize_upload_filename_removes_client_path(self):"""Windows 和 POSIX 客户端路径都只能保留最后一段安全文件名。"""@@ -181,7 +181,7 @@ class TestVideoControllerHelpers(unittest.TestCase):class TestVideoControllerTasks(unittest.TestCase):@staticmethoddef _request():- return SimpleNamespace(headers={"x-task-id": "request-123"})+ return SimpleNamespace(headers={"x-task-id": "request-123"}, method="GET")def test_video_task_rejects_font_outside_font_directory_before_queueing(self):"""非法字体路径必须在任务入队前返回 400,不产生付费后台任务。"""@@ -676,7 +676,7 @@ class TestVideoControllerFiles(unittest.TestCase):headers = {"x-task-id": "request-123"}if range_header is not None:headers["Range"] = range_header- return SimpleNamespace(headers=headers)+ return SimpleNamespace(headers=headers, method="GET")def test_upload_video_material_validates_complete_extension(self):"""大写合法扩展名应接受,无点号伪扩展名应拒绝。"""