Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix(material): isolate malformed results (#1424)

Rudy Mizrahi Celekli68ca5623d9f7
diff --git a/app/services/material.py b/app/services/material.py
index ecb2654b..58afa472 100644
--- a/app/services/material.py
+++ b/app/services/material.py
@@ -263,7 +263,7 @@ def _matches_video_aspect(
try:
normalized_width = int(float(width))
normalized_height = int(float(height))
- except (TypeError, ValueError):
+ except (OverflowError, TypeError, ValueError):
normalized_width = 0
normalized_height = 0
@@ -338,21 +338,40 @@ def search_videos_pexels(
)
response = r.json()
video_items = []
- if "videos" not in response:
+ if not isinstance(response, dict) or not isinstance(
+ response.get("videos"), list
+ ):
logger.error("pexels video search returned an unsupported response")
return video_items
videos = response["videos"]
# loop through each video in the result
for v in videos:
- duration = v["duration"]
+ if not isinstance(v, dict):
+ continue
+ duration = v.get("duration")
# check if video has desired minimum duration
- if duration < minimum_duration:
+ if (
+ isinstance(duration, bool)
+ or not isinstance(duration, (int, float))
+ or not math.isfinite(duration)
+ or duration < minimum_duration
+ ):
+ continue
+ video_files = v.get("video_files")
+ if not isinstance(video_files, list):
continue
- video_files = v["video_files"]
# loop through each url to determine the best quality
for video in video_files:
- w = int(video["width"])
- h = int(video["height"])
+ if not isinstance(video, dict):
+ continue
+ try:
+ w = int(video.get("width"))
+ h = int(video.get("height"))
+ except (OverflowError, TypeError, ValueError):
+ continue
+ video_url = video.get("link")
+ if not isinstance(video_url, str) or not video_url:
+ continue
if (
_matches_video_aspect(w, h, aspect)
and w == video_width
@@ -360,7 +379,7 @@ def search_videos_pexels(
):
item = MaterialInfo()
item.provider = "pexels"
- item.url = video["link"]
+ item.url = video_url
item.duration = duration
item.source_info = {
"provider": "pexels",
@@ -457,24 +476,39 @@ def search_videos_pixabay(
return []
video_items = []
- if "hits" not in response:
+ if not isinstance(response, dict) or not isinstance(
+ response.get("hits"), list
+ ):
logger.error("pixabay video search returned an unsupported response")
return video_items
videos = response["hits"]
# loop through each video in the result
for v in videos:
- duration = v["duration"]
+ if not isinstance(v, dict):
+ continue
+ duration = v.get("duration")
# check if video has desired minimum duration
- if duration < minimum_duration:
+ if (
+ isinstance(duration, bool)
+ or not isinstance(duration, (int, float))
+ or not math.isfinite(duration)
+ or duration < minimum_duration
+ ):
+ continue
+ video_files = v.get("videos")
+ if not isinstance(video_files, dict):
continue
- video_files = v["videos"]
# loop through each url to determine the best quality
- for video_type in video_files:
- video = video_files[video_type]
+ for video_type, video in video_files.items():
+ if not isinstance(video, dict):
+ continue
try:
w = int(video["width"])
h = int(video["height"])
- except (KeyError, TypeError, ValueError):
+ except (KeyError, OverflowError, TypeError, ValueError):
+ continue
+ video_url = video.get("url")
+ if not isinstance(video_url, str) or not video_url:
continue
# Pixabay 很少返回原生方形视频;1:1 输出继续接受满足分辨率的
# 候选并由合成阶段裁剪。横竖屏则必须严格匹配目标方向。
@@ -484,7 +518,7 @@ def search_videos_pixabay(
if orientation_matches and w >= video_width:
item = MaterialInfo()
item.provider = "pixabay"
- item.url = video["url"]
+ item.url = video_url
item.duration = duration
item.source_info = {
"provider": "pixabay",
@@ -570,22 +604,33 @@ def search_videos_coverr(
response = r.json()
video_items: List[MaterialInfo] = []
- if not isinstance(response, dict) or "hits" not in response:
+ if not isinstance(response, dict) or not isinstance(
+ response.get("hits"), list
+ ):
logger.error("coverr video search returned an unsupported response")
return video_items
for v in response["hits"]:
+ if not isinstance(v, dict):
+ continue
# duration 在不同响应里可能是 number(11.625) 或 string("10.500000")
try:
duration = int(float(v.get("duration") or 0))
- except (TypeError, ValueError):
+ except (OverflowError, TypeError, ValueError):
continue
if duration < minimum_duration:
continue
video_id = v.get("id")
- mp4_download_url = (v.get("urls") or {}).get("mp4_download")
- if not video_id or not mp4_download_url:
+ urls = v.get("urls")
+ if not isinstance(urls, dict):
+ continue
+ mp4_download_url = urls.get("mp4_download")
+ if (
+ not video_id
+ or not isinstance(mp4_download_url, str)
+ or not mp4_download_url
+ ):
continue
if aspect != VideoAspect.square and not _matches_video_aspect(
v.get("max_width"),
diff --git a/test/services/test_material.py b/test/services/test_material.py
index 8ee46409..0e01866c 100644
--- a/test/services/test_material.py
+++ b/test/services/test_material.py
@@ -92,6 +92,139 @@ class TestMaterialTlsVerification(unittest.TestCase):
)
self.assertEqual(results[0].source_info["rendition"]["id"], "987")
+ def test_search_pexels_skips_malformed_entries_without_losing_good_videos(self):
+ config.app["pexels_api_keys"] = ["pexels-key"]
+ fake_response = SimpleNamespace(
+ json=lambda: {
+ "videos": [
+ {"id": 1, "duration": "unknown", "video_files": []},
+ {
+ "id": 10,
+ "duration": 8,
+ "video_files": [
+ {
+ "width": float("inf"),
+ "height": 1920,
+ "link": "https://example.com/overflow.mp4",
+ }
+ ],
+ },
+ {
+ "id": 2,
+ "duration": 8,
+ "video_files": [
+ {"width": None, "height": 1920, "link": "bad"},
+ {
+ "id": 22,
+ "width": 1080,
+ "height": 1920,
+ "link": "https://example.com/first.mp4",
+ },
+ ],
+ },
+ {
+ "id": 3,
+ "duration": 8,
+ "video_files": [
+ {
+ "id": 33,
+ "width": 1080,
+ "height": 1920,
+ "link": "https://example.com/second.mp4",
+ }
+ ],
+ },
+ ]
+ }
+ )
+
+ with patch("app.services.material.requests.get", return_value=fake_response):
+ results = material.search_videos_pexels("cat", minimum_duration=1)
+
+ self.assertEqual(
+ [item.url for item in results],
+ ["https://example.com/first.mp4", "https://example.com/second.mp4"],
+ )
+
+ def test_search_pixabay_skips_malformed_hit_without_losing_good_video(self):
+ config.app["pixabay_api_keys"] = ["pixabay-key"]
+ fake_response = SimpleNamespace(
+ status_code=200,
+ headers={"content-type": "application/json"},
+ text="",
+ json=lambda: {
+ "hits": [
+ {"duration": "unknown", "videos": {}},
+ {
+ "id": 10,
+ "duration": 8,
+ "videos": {
+ "large": {
+ "width": float("inf"),
+ "height": 1920,
+ "url": "https://example.com/overflow.mp4",
+ }
+ },
+ },
+ {
+ "id": 2,
+ "duration": 8,
+ "videos": {
+ "large": {
+ "width": 1080,
+ "height": 1920,
+ "url": "https://example.com/pixabay-good.mp4",
+ }
+ },
+ },
+ ]
+ },
+ )
+
+ with patch("app.services.material.requests.get", return_value=fake_response):
+ results = material.search_videos_pixabay("cat", minimum_duration=1)
+
+ self.assertEqual(
+ [item.url for item in results],
+ ["https://example.com/pixabay-good.mp4"],
+ )
+
+ def test_search_coverr_skips_malformed_hit_without_losing_good_video(self):
+ config.app["coverr_api_keys"] = ["coverr-key"]
+ fake_response = SimpleNamespace(
+ json=lambda: {
+ "hits": [
+ {"id": "bad", "duration": 8, "urls": ["unexpected"]},
+ {
+ "id": "overflow",
+ "duration": 8,
+ "max_width": float("inf"),
+ "max_height": 1920,
+ "urls": {
+ "mp4_download": "https://example.com/overflow.mp4"
+ },
+ },
+ {
+ "id": "good",
+ "duration": 8,
+ "max_width": 1080,
+ "max_height": 1920,
+ "urls": {
+ "mp4_download": "https://example.com/coverr-good.mp4"
+ },
+ },
+ ]
+ }
+ )
+
+ with patch("app.services.material.requests.get", return_value=fake_response):
+ results = material.search_videos_coverr("cat", minimum_duration=1)
+
+ self.assertEqual(
+ [item.url for item in results],
+ ["https://example.com/coverr-good.mp4"],
+ )
+
def test_search_pixabay_allows_explicit_tls_disable_for_proxy(self):
"""
少数企业代理会使用自签证书。该场景必须显式配置关闭 TLS 校验,
@@ -318,6 +451,11 @@ class TestMaterialTlsVerification(unittest.TestCase):
material.VideoAspect.square,
)
)
+ self.assertFalse(
+ material._matches_video_aspect(
+ float("inf"), 1920, material.VideoAspect.portrait
+ )
+ )
def test_coverr_passes_orientation_filter_to_remote_search(self):
"""Coverr 横竖屏搜索应在服务端筛选,方形素材继续使用本地尺寸校验。"""