Skip to content

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

fix: harden external request security

Harry0eb267c527e2
diff --git a/app/services/llm.py b/app/services/llm.py
index a9e41050..e8c18956 100644
--- a/app/services/llm.py
+++ b/app/services/llm.py
@@ -4,7 +4,6 @@ import re
import requests
from typing import List
-import g4f
from loguru import logger
from openai import AzureOpenAI, OpenAI
from openai.types.chat import ChatCompletion
@@ -59,6 +58,28 @@ def _generate_response(prompt: str) -> str:
llm_provider = config.app.get("llm_provider", "openai")
logger.info(f"llm provider: {llm_provider}")
if llm_provider == "g4f":
+ if not config.app.get("enable_g4f", False):
+ raise ValueError(
+ "g4f provider is disabled by default because it relies on "
+ "reverse-engineered third-party endpoints. Set enable_g4f=true "
+ "in config.toml only if you understand and accept the security, "
+ "reliability, and legal risks."
+ )
+
+ logger.warning(
+ "g4f provider is enabled. This provider may be unstable and carries "
+ "supply-chain and terms-of-service risks. Prefer official providers, "
+ "OpenAI-compatible APIs, LiteLLM, Ollama, or local inference for production."
+ )
+ try:
+ import g4f
+ except ImportError as e:
+ raise ValueError(
+ "g4f package is not installed by default. Install the optional "
+ "dependency with `uv sync --extra g4f` only if you understand "
+ "and accept the provider risks."
+ ) from e
+
model_name = config.app.get("g4f_model_name", "")
if not model_name:
model_name = "gpt-3.5-turbo-16k-0613"
@@ -272,8 +293,12 @@ def _generate_response(prompt: str) -> str:
candidates = response.candidates
generated_text = candidates[0].content.parts[0].text
except (AttributeError, IndexError) as e:
- print("Gemini Error:", e)
- raise ValueError(f"[{llm_provider}] returned invalid response content")
+ logger.warning(
+ f"gemini returned invalid response content: {str(e)}"
+ )
+ raise ValueError(
+ f"[{llm_provider}] returned invalid response content"
+ )
return _normalize_text_response(generated_text, llm_provider)
@@ -532,8 +557,10 @@ Please note that you must use English for generating video search terms; Chinese
try:
search_terms = json.loads(match.group())
except Exception as e:
+ # 这里保留重试流程,但必须记录 LLM 返回的非标准 JSON,
+ # 否则后续排查搜索词为空时无法定位
+ # 是模型格式问题还是解析逻辑问题。
logger.warning(f"failed to generate video terms: {str(e)}")
- pass
if search_terms and len(search_terms) > 0:
break
diff --git a/app/services/material.py b/app/services/material.py
index 70ef4764..cbb81460 100644
--- a/app/services/material.py
+++ b/app/services/material.py
@@ -17,6 +17,23 @@ _api_key_counter = 0
_api_key_lock = threading.Lock()
+def _get_tls_verify() -> bool:
+ # 默认开启 TLS 证书校验,防止素材搜索和下载过程被中间人篡改。
+ # 仅在企业代理、自签证书等明确需要的场景下,允许用户通过
+ # `config.toml` 显式设置 `tls_verify = false` 临时关闭。
+ tls_verify = config.app.get("tls_verify", True)
+ if isinstance(tls_verify, str):
+ tls_verify = tls_verify.strip().lower() not in ("0", "false", "no", "off")
+
+ if not tls_verify:
+ logger.warning(
+ "TLS certificate verification is disabled by config.app.tls_verify=false. "
+ "Only use this in trusted proxy environments."
+ )
+
+ return bool(tls_verify)
+
+
def get_api_key(cfg_key: str):
api_keys = config.app.get(cfg_key)
if not api_keys:
@@ -58,7 +75,7 @@ def search_videos_pexels(
query_url,
headers=headers,
proxies=config.proxy,
- verify=False,
+ verify=_get_tls_verify(),
timeout=(30, 60),
)
response = r.json()
@@ -114,7 +131,7 @@ def search_videos_pixabay(
try:
r = requests.get(
- query_url, proxies=config.proxy, verify=False, timeout=(30, 60)
+ query_url, proxies=config.proxy, verify=_get_tls_verify(), timeout=(30, 60)
)
response = r.json()
video_items = []
@@ -176,7 +193,7 @@ def save_video(video_url: str, save_dir: str = "") -> str:
video_url,
headers=headers,
proxies=config.proxy,
- verify=False,
+ verify=_get_tls_verify(),
timeout=(60, 240),
).content
)
@@ -193,14 +210,18 @@ def save_video(video_url: str, save_dir: str = "") -> str:
logger.warning(f"invalid video file: {video_path} => {str(e)}")
try:
os.remove(video_path)
- except Exception:
- pass
+ except Exception as remove_error:
+ logger.warning(
+ f"failed to remove invalid video file: {video_path}, error: {str(remove_error)}"
+ )
finally:
if clip is not None:
try:
clip.close()
- except Exception:
- pass
+ except Exception as close_error:
+ logger.warning(
+ f"failed to close video clip: {video_path}, error: {str(close_error)}"
+ )
return ""
diff --git a/app/services/voice.py b/app/services/voice.py
index 665b58b7..8f61df85 100644
--- a/app/services/voice.py
+++ b/app/services/voice.py
@@ -1506,7 +1506,10 @@ def siliconflow_tts(
]
logger.success(f"siliconflow tts succeeded: {voice_file}")
- print("s", sub_maker.subs, sub_maker.offset)
+ logger.debug(
+ "siliconflow subtitle timeline generated, "
+ f"subs: {len(sub_maker.subs)}, offsets: {len(sub_maker.offset)}"
+ )
return sub_maker
else:
logger.error(
diff --git a/app/utils/utils.py b/app/utils/utils.py
index dc5ff3ee..c3f64933 100644
--- a/app/utils/utils.py
+++ b/app/utils/utils.py
@@ -6,13 +6,10 @@ import threading
from typing import Any
from uuid import uuid4
-import urllib3
from loguru import logger
from app.models import const
-urllib3.disable_warnings()
-
def get_response(status: int, data: Any = None, message: str = ""):
obj = {
diff --git a/config.example.toml b/config.example.toml
index 15db4912..07104418 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -4,6 +4,11 @@ video_source = "pexels" # "pexels" or "pixabay"
# 是否隐藏配置面板
hide_config = false
+# 是否校验外部 API 和素材下载的 TLS 证书。
+# 默认必须开启,避免 Pexels/Pixabay API key 和下载素材被中间人攻击篡改。
+# 只有在企业代理或自签证书环境明确需要时,才临时改为 false。
+tls_verify = true
+
# Pexels API Key
# Register at https://www.pexels.com/api/ to get your API key.
# You can use multiple keys to avoid rate limits.
@@ -26,7 +31,7 @@ pixabay_api_keys = []
# deepseek
# gemini
# ollama
-# g4f
+# g4f (disabled by default; set enable_g4f=true only after accepting its risks)
# oneapi
# cloudflare
# minimax
@@ -75,6 +80,12 @@ oneapi_base_url = ""
oneapi_model_name = ""
########## G4F
+# g4f relies on reverse-engineered third-party endpoints and is not recommended
+# for production. Prefer official APIs, OpenAI-compatible providers, LiteLLM,
+# Ollama, or local inference.
+# If you still need it, install the optional dependency with:
+# uv sync --extra g4f
+enable_g4f = false
# Visit https://github.com/xtekky/gpt4free to get more details
# Supported model list: https://github.com/xtekky/gpt4free/blob/main/g4f/models.py
g4f_model_name = "gpt-3.5-turbo"
diff --git a/pyproject.toml b/pyproject.toml
index 72611bb3..81645baf 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -23,7 +23,6 @@ dependencies = [
"loguru==0.7.3",
"google-generativeai==0.8.6",
"dashscope==1.20.14",
- "g4f==0.5.2.2",
"azure-cognitiveservices-speech==1.41.1",
"redis==5.2.0",
"python-multipart==0.0.19",
@@ -34,6 +33,11 @@ dependencies = [
"litellm==1.60.0",
]
+[project.optional-dependencies]
+g4f = [
+ "g4f==0.5.2.2",
+]
+
[tool.hatch.build.targets.wheel]
packages = ["app"]
diff --git a/test/services/test_llm.py b/test/services/test_llm.py
index bfe7b7b2..bfc2968b 100644
--- a/test/services/test_llm.py
+++ b/test/services/test_llm.py
@@ -85,6 +85,45 @@ class TestLiteLLMProvider(unittest.TestCase):
self.assertIn("api_key is not set", result)
self.assertNotIn("litellm", result.lower())
+ def test_g4f_provider_requires_explicit_opt_in(self):
+ """
+ g4f 存在供应链和稳定性风险,不能因为用户把 provider 写成 g4f
+ 就默认加载第三方包并访问逆向接口,必须显式启用。
+ """
+ config.app["llm_provider"] = "g4f"
+ config.app["enable_g4f"] = False
+
+ result = llm._generate_response("test")
+
+ self.assertIn("Error:", result)
+ self.assertIn("g4f provider is disabled", result)
+
+ def test_g4f_provider_uses_lazy_import_after_opt_in(self):
+ config.app["llm_provider"] = "g4f"
+ config.app["enable_g4f"] = True
+ config.app["g4f_model_name"] = "gpt-3.5-turbo"
+
+ fake_g4f = types.SimpleNamespace()
+ fake_g4f.ChatCompletion = types.SimpleNamespace(
+ create=lambda **kwargs: "hello from g4f"
+ )
+
+ with patch.dict(sys.modules, {"g4f": fake_g4f}):
+ result = llm._generate_response("test")
+
+ self.assertEqual(result, "hello from g4f")
+
+ def test_g4f_provider_reports_missing_optional_dependency(self):
+ config.app["llm_provider"] = "g4f"
+ config.app["enable_g4f"] = True
+ config.app["g4f_model_name"] = "gpt-3.5-turbo"
+
+ with patch.dict(sys.modules, {"g4f": None}):
+ result = llm._generate_response("test")
+
+ self.assertIn("Error:", result)
+ self.assertIn("g4f package is not installed by default", result)
+
FOUNDRY_KEY = os.environ.get("ANTHROPIC_FOUNDRY_API_KEY", "")
FOUNDRY_BASE = "https://amanrai-test-resource.services.ai.azure.com/anthropic"
diff --git a/test/services/test_material.py b/test/services/test_material.py
new file mode 100644
index 00000000..71a4e13b
--- /dev/null
+++ b/test/services/test_material.py
@@ -0,0 +1,118 @@
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from app.config import config
+from app.services import material
+
+
+class TestMaterialTlsVerification(unittest.TestCase):
+ def setUp(self):
+ self.original_app_config = dict(config.app)
+ self.original_proxy_config = dict(config.proxy)
+
+ def tearDown(self):
+ config.app.clear()
+ config.app.update(self.original_app_config)
+ config.proxy.clear()
+ config.proxy.update(self.original_proxy_config)
+
+ def test_search_pexels_uses_tls_verification_by_default(self):
+ """
+ 默认路径必须开启 TLS 校验,避免素材 API key 和返回的素材 URL
+ 在公共网络或不可信代理环境中被中间人攻击截获或篡改。
+ """
+ config.app["pexels_api_keys"] = ["pexels-key"]
+ config.app.pop("tls_verify", None)
+ config.proxy.clear()
+
+ fake_response = SimpleNamespace(
+ json=lambda: {
+ "videos": [
+ {
+ "duration": 8,
+ "video_files": [
+ {
+ "width": 1080,
+ "height": 1920,
+ "link": "https://example.com/video.mp4",
+ }
+ ],
+ }
+ ]
+ }
+ )
+
+ with patch("app.services.material.requests.get", return_value=fake_response) as get:
+ results = material.search_videos_pexels("cat", minimum_duration=1)
+
+ self.assertEqual(len(results), 1)
+ self.assertTrue(get.call_args.kwargs["verify"])
+
+ def test_search_pixabay_allows_explicit_tls_disable_for_proxy(self):
+ """
+ 少数企业代理会使用自签证书。该场景必须显式配置关闭 TLS 校验,
+ 不能再由代码硬编码默认关闭。
+ """
+ config.app["pixabay_api_keys"] = ["pixabay-key"]
+ config.app["tls_verify"] = False
+ config.proxy.clear()
+
+ fake_response = SimpleNamespace(
+ json=lambda: {
+ "hits": [
+ {
+ "duration": 8,
+ "videos": {
+ "large": {
+ "width": 1920,
+ "url": "https://example.com/video.mp4",
+ }
+ },
+ }
+ ]
+ }
+ )
+
+ with patch("app.services.material.requests.get", return_value=fake_response) as get:
+ results = material.search_videos_pixabay("cat", minimum_duration=1)
+
+ self.assertEqual(len(results), 1)
+ self.assertFalse(get.call_args.kwargs["verify"])
+
+ def test_save_video_uses_tls_verification_by_default(self):
+ config.app.pop("tls_verify", None)
+ config.proxy.clear()
+
+ fake_response = SimpleNamespace(content=b"fake-video")
+
+ class FakeVideoFileClip:
+ duration = 1
+ fps = 24
+
+ def __init__(self, path):
+ self.path = path
+
+ def close(self):
+ return None
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with patch(
+ "app.services.material.requests.get", return_value=fake_response
+ ) as get, patch("app.services.material.VideoFileClip", FakeVideoFileClip):
+ video_path = material.save_video(
+ "https://example.com/video.mp4?token=abc", save_dir=temp_dir
+ )
+
+ self.assertTrue(os.path.exists(video_path))
+ self.assertTrue(get.call_args.kwargs["verify"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/uv.lock b/uv.lock
index 46413722..f7095007 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1042,7 +1042,6 @@ dependencies = [
{ name = "edge-tts" },
{ name = "fastapi" },
{ name = "faster-whisper" },
- { name = "g4f" },
{ name = "google-generativeai" },
{ name = "litellm" },
{ name = "loguru" },
@@ -1058,6 +1057,11 @@ dependencies = [
{ name = "uvicorn" },
]
+[package.optional-dependencies]
+g4f = [
+ { name = "g4f" },
+]
+
[package.metadata]
requires-dist = [
{ name = "azure-cognitiveservices-speech", specifier = "==1.41.1" },
@@ -1065,7 +1069,7 @@ requires-dist = [
{ name = "edge-tts", specifier = "==7.2.7" },
{ name = "fastapi", specifier = "==0.115.6" },
{ name = "faster-whisper", specifier = "==1.1.0" },
- { name = "g4f", specifier = "==0.5.2.2" },
+ { name = "g4f", marker = "extra == 'g4f'", specifier = "==0.5.2.2" },
{ name = "google-generativeai", specifier = "==0.8.6" },
{ name = "litellm", specifier = "==1.60.0" },
{ name = "loguru", specifier = "==0.7.3" },
@@ -1080,6 +1084,7 @@ requires-dist = [
{ name = "streamlit", specifier = "==1.45.0" },
{ name = "uvicorn", specifier = "==0.32.1" },
]
+provides-extras = ["g4f"]
[[package]]
name = "moviepy"