moderation.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import os
  2. import tempfile
  3. from urllib.parse import urlparse
  4. import requests
  5. from fastapi import APIRouter, HTTPException
  6. from ..core.ark_client import get_ark_client
  7. from ..config.config import Config
  8. from ..schemas.chat import ModerationRequest, ModerationResponse
  9. from ..db.mongo import save_chat_log
  10. router = APIRouter()
  11. # 待审核文本最大长度限制(超出则拒绝,避免超长文本拖慢模型响应)
  12. MAX_CONTENT_LENGTH = 20000
  13. # 远程媒体下载大小限制(火山方舟视频上限 50MB)
  14. MAX_VIDEO_SIZE = 50 * 1024 * 1024
  15. MAX_IMAGE_SIZE = 20 * 1024 * 1024
  16. # 下载超时(连接超时, 读取超时)
  17. _DOWNLOAD_TIMEOUT = (10, 60)
  18. # 内容审核系统提示词:约束模型仅输出 true / false,降低解析歧义并提升响应速度
  19. _MODERATION_PROMPT = """你是严格的内容安全审核员。判断用户提供的内容(文本/图片/视频画面)是否违规。
  20. 违规类别(命中任一即违规):1.涉黄、低俗、性暗示、裸露;2.暴力、恐怖、血腥、极端主义;3.涉政敏感、反动、危害国家安全;4.违法犯罪、赌博、诈骗、毒品、辱骂、封建迷信;5.广告营销、引流、联系方式、二维码。
  21. 图片/视频结合画面主体、文字、场景综合判断;仅依据所给内容判断,不做联想或补全。
  22. 只输出一个单词:true(违规)或 false(合规),禁止输出任何其他字符。"""
  23. def _parse_moderation_result(text: str) -> bool:
  24. """将模型输出解析为布尔值:True=违规,False=合规"""
  25. cleaned = text.strip().lower()
  26. if cleaned.startswith("true"):
  27. return True
  28. if cleaned.startswith("false"):
  29. return False
  30. # 容错:模型可能附带少量多余字符,取首次出现的关键词
  31. has_true = "true" in cleaned
  32. has_false = "false" in cleaned
  33. if has_true and not has_false:
  34. return True
  35. if has_false and not has_true:
  36. return False
  37. # 无法明确解析时抛错,交由调用方重试,避免误判放行违规内容
  38. raise ValueError(f"无法解析审核结果: {text[:50]}")
  39. def _try_early_decide(accumulated: str) -> bool | None:
  40. """流式场景下的提前判定:true/false 首字母不同(t vs f),
  41. 读到第一个非空字符即可判定,无需等模型吐完整个单词。
  42. 返回 None 表示暂无法判定(如首字符是空白/不明字符)。"""
  43. stripped = accumulated.strip().lower()
  44. if not stripped:
  45. return None
  46. first = stripped[0]
  47. if first == "t":
  48. return True
  49. if first == "f":
  50. return False
  51. return None
  52. def _resolve_ext(url: str, content: bytes, default: str) -> str:
  53. """推断文件扩展名:优先取 URL 路径后缀,其次按文件魔数嗅探,最后用默认值。
  54. Files API 依据扩展名识别媒体类型,因此需给出正确后缀。"""
  55. ext = os.path.splitext(urlparse(url).path)[1].lower()
  56. known = (".mp4", ".mov", ".webm", ".mkv", ".avi", ".flv",
  57. ".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp")
  58. if ext in known:
  59. return ext
  60. # 文件魔数嗅探(URL 无有效后缀时,如 COS 的 ?imageMogr2 处理链接)
  61. if content[:3] == b"\xff\xd8\xff":
  62. return ".jpg"
  63. if content[:8] == b"\x89PNG\r\n\x1a\n":
  64. return ".png"
  65. if content[:4] == b"RIFF" and content[8:12] == b"WEBP":
  66. return ".webp"
  67. if content[:6] in (b"GIF87a", b"GIF89a"):
  68. return ".gif"
  69. if content[4:8] == b"ftyp":
  70. return ".mp4"
  71. return default
  72. def _upload_remote_to_ark(client, url: str, kind: str) -> str:
  73. """下载远程 URL 并上传到火山方舟 Files API,返回 file_id。
  74. 直接把 COS 等第三方 URL 传给模型时,若源站返回的 Content-Type 为
  75. application/octet-stream,方舟会因无法识别媒体类型而报 400。通过
  76. 下载 + Files API 上传(按扩展名识别类型)可彻底绕开该限制。
  77. kind: 'video' | 'image',用于大小限制与默认扩展名。
  78. """
  79. max_size = MAX_VIDEO_SIZE if kind == "video" else MAX_IMAGE_SIZE
  80. try:
  81. resp = requests.get(url, timeout=_DOWNLOAD_TIMEOUT, stream=True)
  82. resp.raise_for_status()
  83. content = b""
  84. for chunk in resp.iter_content(chunk_size=1 << 20):
  85. if not chunk:
  86. continue
  87. content += chunk
  88. if len(content) > max_size:
  89. raise HTTPException(
  90. status_code=400,
  91. detail=f"{kind}文件超过大小限制({max_size // 1024 // 1024}MB)",
  92. )
  93. except HTTPException:
  94. raise
  95. except Exception as e:
  96. raise HTTPException(status_code=400, detail=f"无法下载{kind}资源: {str(e)}")
  97. if not content:
  98. raise HTTPException(status_code=400, detail=f"{kind}资源内容为空")
  99. ext = _resolve_ext(url, content, ".mp4" if kind == "video" else ".jpg")
  100. filename = f"moderation_{kind}{ext}"
  101. tmp_path = None
  102. try:
  103. with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp:
  104. tmp.write(content)
  105. tmp_path = tmp.name
  106. with open(tmp_path, "rb") as f:
  107. uploaded = client.files.create(file=(filename, f), purpose="user_data")
  108. return uploaded.id
  109. except Exception as e:
  110. raise HTTPException(status_code=502, detail=f"上传{kind}到审核服务失败: {str(e)}")
  111. finally:
  112. if tmp_path and os.path.exists(tmp_path):
  113. os.unlink(tmp_path)
  114. def _resolve_type(request: ModerationRequest) -> str:
  115. """确定审核类型:优先使用显式 type,否则根据已传参数自动推断"""
  116. if request.type:
  117. t = request.type.strip().lower()
  118. if t not in ("text", "image", "video"):
  119. raise HTTPException(status_code=400, detail=f"不支持的审核类型: {request.type}")
  120. return t
  121. if request.video_url:
  122. return "video"
  123. if request.image_url:
  124. return "image"
  125. if request.content:
  126. return "text"
  127. raise HTTPException(status_code=400, detail="请提供待审核的内容(content / image_url / video_url)")
  128. def _build_input_content(mod_type: str, request: ModerationRequest, client) -> str | list:
  129. """根据审核类型构造 Chat Completions API 的 content 参数,并做参数校验。
  130. 文本审核返回字符串,图片/视频审核返回多模态 content 数组。"""
  131. if mod_type == "text":
  132. content = (request.content or "").strip()
  133. if not content:
  134. raise HTTPException(status_code=400, detail="待审核文本不能为空")
  135. if len(content) > MAX_CONTENT_LENGTH:
  136. raise HTTPException(
  137. status_code=400,
  138. detail=f"待审核文本超过长度限制({MAX_CONTENT_LENGTH} 字符),请分段提交",
  139. )
  140. return content
  141. if mod_type == "image":
  142. image_url = (request.image_url or "").strip()
  143. if not image_url:
  144. raise HTTPException(status_code=400, detail="图片审核需提供 image_url")
  145. return [
  146. {"type": "image_url", "image_url": {"url": image_url}},
  147. {"type": "text", "text": "请审核这张图片的画面内容是否违规。"},
  148. ]
  149. # video:对视频画面 + 封面图一起审核
  150. video_url = (request.video_url or "").strip()
  151. thumb_url = (request.thumb_url or "").strip()
  152. if not video_url:
  153. raise HTTPException(status_code=400, detail="视频审核需提供 video_url")
  154. if not thumb_url:
  155. raise HTTPException(status_code=400, detail="视频审核需提供封面图 thumb_url")
  156. video_file_id = _upload_remote_to_ark(client, video_url, "video")
  157. thumb_file_id = _upload_remote_to_ark(client, thumb_url, "image")
  158. return [
  159. {"type": "file", "file_id": video_file_id},
  160. {"type": "file", "file_id": thumb_file_id},
  161. {"type": "text", "text": "请综合审核这段视频的画面及封面图内容是否违规。"},
  162. ]
  163. # 火山方舟输入/输出安全护栏拦截时返回的错误码统一含该关键字
  164. _SENSITIVE_ERROR_KEYWORD = "SensitiveContentDetected"
  165. def _is_sensitive_block(error: Exception) -> bool:
  166. """判断异常是否为方舟安全护栏的敏感内容拦截。
  167. 当输入(文本/图片/视频)命中敏感信息时,方舟会在模型处理前直接返回
  168. 形如 InputTextSensitiveContentDetected 的 400 错误。对审核接口而言,
  169. 这本身即表明内容违规,应判定为 sensitive=true,而非当作服务异常报错。
  170. """
  171. code = getattr(error, "code", None)
  172. if code and _SENSITIVE_ERROR_KEYWORD in str(code):
  173. return True
  174. return _SENSITIVE_ERROR_KEYWORD in str(error)
  175. def _log_target(mod_type: str, request: ModerationRequest) -> str:
  176. """生成审核日志的目标标识(文本截断 / 媒体 URL)"""
  177. if mod_type == "text":
  178. return (request.content or "")[:500]
  179. if mod_type == "image":
  180. return f"[image] {request.image_url}"
  181. return f"[video] video={request.video_url} thumb={request.thumb_url}"
  182. @router.post("/check", response_model=ModerationResponse)
  183. async def moderate_content(request: ModerationRequest):
  184. """
  185. 公共内容审核接口(无需登录认证),供外部系统调用。
  186. 支持三种审核类型,利用 AI 模型检测是否包含涉黄、暴恐、涉政、其他不良、广告推广等违规内容:
  187. - text:审核文本内容(content)
  188. - image:审核图片(image_url)
  189. - video:审核视频画面 + 封面图(video_url + thumb_url)
  190. 图片/视频通过 Files API 上传换取 file_id 后送审,规避第三方 URL 的 mimetype 校验问题。
  191. 未显式传 type 时,根据已传参数自动推断(video_url > image_url > content)。
  192. 返回:sensitive=true 表示检测到违规内容,false 表示合规内容。
  193. """
  194. mod_type = _resolve_type(request)
  195. log_target = _log_target(mod_type, request)
  196. try:
  197. client = get_ark_client()
  198. except Exception as e:
  199. raise HTTPException(status_code=503, detail=f"审核服务初始化失败: {str(e)}")
  200. # 图片/视频会在此处下载远程资源并上传 Files API(可能抛 400/502)
  201. input_content = _build_input_content(mod_type, request, client)
  202. system_msg = {"role": "system", "content": _MODERATION_PROMPT}
  203. user_msg = {"role": "user", "content": input_content}
  204. accumulated = ""
  205. is_sensitive = None
  206. try:
  207. stream = client.chat.completions.create(
  208. model="doubao-seed-2-0-mini-260428",
  209. messages=[system_msg, user_msg],
  210. # service_tier="fast",
  211. stream=True,
  212. thinking={"type": "disabled"}, # 通过 extra_body 透传给火山方舟
  213. response_format={"type": "text"}
  214. )
  215. try:
  216. for event in stream:
  217. # 豆包API使用标准的OpenAI兼容格式:event.choices[0].delta.content
  218. # 检查是否命中内容过滤器(护栏拦截)
  219. if hasattr(event, 'choices') and event.choices:
  220. choice = event.choices[0]
  221. # 如果 finish_reason 是 content_filter,说明内容被护栏拦截
  222. if choice.finish_reason == 'content_filter':
  223. is_sensitive = True
  224. print("检测到内容过滤器拦截 (finish_reason=content_filter),判定为违规")
  225. break
  226. delta = choice.delta.content
  227. if delta:
  228. accumulated += delta
  229. # true/false 首字母不同,读到第一个非空字符即可判定
  230. is_sensitive = _try_early_decide(accumulated)
  231. if is_sensitive is not None:
  232. break
  233. finally:
  234. stream.close() # 提前判定后主动关闭连接,释放资源
  235. except Exception as e:
  236. # 护栏拦截即视为命中违规内容,直接返回 sensitive=true
  237. if _is_sensitive_block(e):
  238. save_chat_log(
  239. user_id="moderation",
  240. question=log_target,
  241. stream_mode=True,
  242. status="blocked",
  243. error=str(e),
  244. )
  245. return ModerationResponse(sensitive=True)
  246. save_chat_log(
  247. user_id="moderation",
  248. question=log_target,
  249. stream_mode=True,
  250. status="error",
  251. error=str(e),
  252. )
  253. raise HTTPException(status_code=500, detail=f"内容审核服务异常: {str(e)}")
  254. if is_sensitive is None:
  255. # 未能提前判定(如首字符异常),兜底解析已累积到的文本
  256. try:
  257. is_sensitive = _parse_moderation_result(accumulated)
  258. except ValueError as e:
  259. save_chat_log(
  260. user_id="moderation",
  261. question=log_target,
  262. stream_mode=True,
  263. raw_response=accumulated,
  264. status="error",
  265. error=str(e),
  266. )
  267. raise HTTPException(status_code=500, detail="内容审核结果解析失败,请重试")
  268. return ModerationResponse(sensitive=is_sensitive)
  269. router.tags = ["内容审核"]