Files
AgentScript/agent/backend/app/services/vision_service.py
T

145 lines
4.9 KiB
Python
Raw Normal View History

"""
图片识别服务
============
【功能说明】调用智谱 GLM-4V-Flash 识别图片内容(Bug 截图、UI 稿、日志截图等),
供任务提交时自动分析图片附件,把图片内容附加到需求描述。
【技术选型理由】
1. 选智谱 GLM-4V-Flash:完全免费、中文效果好、OpenAI 兼容口;
2. 不依赖 langchain-openai:智谱走自己的 OpenAI 兼容协议,直接 httpx 调用更轻量。
【实现思路】
- analyze_image():base64 编码图片 → 调 GLM-4V-Flash → 返回文字描述;
- analyze_images():批量分析多张图片,合并结果。
【潜在风险与应对】
风险1:图片过大/格式不支持。
应对:前端限 10MB + 格式校验;后端 base64 编码前检查大小。
风险2:API 超时/限流。
应对:超时 30 秒 + 失败返回空字符串(不阻塞任务提交)。
"""
from __future__ import annotations
import base64
import logging
from pathlib import Path
import httpx
from app.config.settings import load_settings
logger = logging.getLogger("agent.vision")
def analyze_image(image_path: str | Path, prompt: str = "") -> str:
"""
识别图片内容。
【参数】
image_path:图片文件路径(需在 D 盘可访问范围内)
prompt:可选自定义提示词(默认让模型描述图片内容)
【返回】图片内容的文字描述(失败返回空字符串,不抛异常)
"""
path = Path(image_path)
if not path.exists():
logger.warning("图片文件不存在:%s", path)
return ""
# 检查大小(20MB 限制,base64 后更大)
if path.stat().st_size > 20 * 1024 * 1024:
logger.warning("图片过大:%s(%.1fMB)", path, path.stat().st_size / 1024 / 1024)
return ""
try:
image_b64 = base64.b64encode(path.read_bytes()).decode("utf-8")
except Exception as exc: # noqa: BLE001
logger.warning("图片读取失败:%s %s", path, exc)
return ""
# 根据扩展名确定 MIME 类型
ext = path.suffix.lower()
mime_map = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".bmp": "image/bmp",
".webp": "image/webp",
}
mime = mime_map.get(ext, "image/png")
settings = load_settings()
api_key = settings.zhipu_api_key
base_url = settings.zhipu_base_url
model = settings.zhipu_vision_model or "glm-4v-flash"
if not api_key:
logger.warning("未配置智谱 API Key,跳过图片识别")
return ""
user_prompt = prompt or (
"请完整识别并提取图片中的所有文字内容,逐字逐句转录,不要遗漏、不要总结、不要改写。"
"如果是报错截图,提取完整错误信息和堆栈;"
"如果是代码截图,逐行提取代码;"
"如果是表格/文档截图,按原格式完整转录;"
"如果是UI界面,提取所有可见的文字、标签、按钮文本。"
"保持原文,不做任何概括或省略。"
)
try:
resp = httpx.post(
f"{base_url}/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": model,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": user_prompt},
{
"type": "image_url",
"image_url": {
"url": f"data:{mime};base64,{image_b64}"
},
},
],
}
],
"max_tokens": 800,
},
timeout=30.0,
)
resp.raise_for_status()
data = resp.json()
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
logger.info("图片识别成功:%s(返回 %d 字符)", path.name, len(content))
return content.strip()
except httpx.HTTPStatusError as exc:
logger.warning("图片识别 HTTP 错误:%s %s", exc.response.status_code, exc.response.text[:200])
return ""
except Exception as exc: # noqa: BLE001
logger.warning("图片识别失败:%s %s", path.name, exc)
return ""
def analyze_images(image_paths: list[str], prompt: str = "") -> str:
"""
批量识别图片内容并合并结果。
【返回】合并后的文字描述(空行分隔各图),失败的跳过。
"""
results = []
for p in image_paths:
desc = analyze_image(p, prompt)
if desc:
path = Path(p)
results.append(f"【图片:{path.name}】\n{desc}")
return "\n\n".join(results)