feat: 第二梯队AI功能落地 — 文案工具箱(改写/降AIGC/标题/小红书/朋友圈5场景) & 截图理解(qwen多模态看图) & 视频字幕AI(Whisper本地转录SRT+AI翻译英日文), relay四接口, 受控授权, 全链路实测通过
This commit is contained in:
1 parent
b5a933600b
commit
6d1f0f80cb
11 files changed
+1221
-1
No files matched your search
@@ -44,7 +44,7 @@ AUTH_PASS = os.environ.get("AUTH_PASS", "")
|
||||
PROJECT_NAME = os.environ.get("PROJECT_NAME", "IT-Tools")
|
||||
TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json")
|
||||
TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
|
||||
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "ai-chat"}
|
||||
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "ai-chat", "copywriting", "screenshot-qa", "video-subtitle"}
|
||||
MACHINE_RE = re.compile(r"^\d{10,16}$")
|
||||
|
||||
# verify() messages that unconditionally block activation
|
||||
@@ -1527,6 +1527,154 @@ class Handler(BaseHTTPRequestHandler):
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._reply(500, json.dumps({"code": 500, "message": f"放大失败: {e}"}, ensure_ascii=False).encode(), "application/json")
|
||||
|
||||
# ---------- 共用 LLM 调用 ----------
|
||||
def _llm_chat(self, messages: list) -> str:
|
||||
key = os.environ.get("NEWAPI_KEY", "")
|
||||
upstream = os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions")
|
||||
model = os.environ.get("NEWAPI_MODEL", "qwen3.8-flash")
|
||||
if not key:
|
||||
raise RuntimeError("AI 服务未配置")
|
||||
body = json.dumps({"model": model, "messages": messages, "temperature": 0.7, "max_tokens": 4096}).encode()
|
||||
req = request.Request(upstream, data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
|
||||
resp = request.urlopen(req, timeout=180)
|
||||
data = json.loads(resp.read())
|
||||
if "error" in data:
|
||||
raise RuntimeError(data["error"].get("message", "upstream error"))
|
||||
return data["choices"][0]["message"]["content"]
|
||||
|
||||
# ---------- 文案工具箱 ----------
|
||||
COPY_SCENES = {
|
||||
"rewrite": "你是一名资深中文编辑。请改写用户提供的文字,保持原意但改变表达方式和句式结构,语言自然流畅,直接输出改写后的正文,不要解释。",
|
||||
"deaigc": "你是消除 AI 腔调的中文改写专家。把用户提供的文字改写得更像真人手写:加入口语化表达、长短句交错、具体细节,降低 AI 生成痕迹(避免排比、避免'首先其次最后'式结构、避免空洞套话),保持原意,直接输出改写后的正文。",
|
||||
"titles": "你是爆款标题专家。根据用户提供的主题,生成 10 个吸引点击的中文标题,要求:每行一个、不超过 30 字、风格多样(悬念/数字/痛点/对比/好奇),直接输出标题列表,不要其他文字。",
|
||||
"xhs": "你是小红书文案高手。根据用户提供的主题写一篇小红书笔记:开头抓人(1-2 句)、正文分段带 emoji、结尾加 5-8 个话题标签(#开头)。总字数 300-600 字,语气亲切接地气,直接输出笔记内容。",
|
||||
"moments": "你是朋友圈文案高手。根据用户提供的主题写 3 条不同风格的微信朋友圈短文案:一条文艺、一条幽默、一条简洁有梗,每条不超过 60 字、可带 1-2 个 emoji,直接输出 3 条文案(每条一行)。",
|
||||
}
|
||||
|
||||
def _handle_copy(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
if check(machine, "copywriting") != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
scene = str(payload.get("scene") or "")
|
||||
if scene not in self.COPY_SCENES:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "无效的场景"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
text = str(payload.get("text") or "").strip()[:8000]
|
||||
if not text:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "请输入内容"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
try:
|
||||
reply = self._llm_chat([
|
||||
{"role": "system", "content": self.COPY_SCENES[scene]},
|
||||
{"role": "user", "content": text},
|
||||
])
|
||||
log_usage(machine, "copywriting")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": reply}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json")
|
||||
|
||||
# ---------- 截图理解 ----------
|
||||
def _handle_vision(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
if check(machine, "screenshot-qa") != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
b64 = str(payload.get("image") or "")
|
||||
question = str(payload.get("question") or "").strip()[:1000] or "提取图片中的所有文字和关键信息,结构化整理输出。"
|
||||
if not b64:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "未收到图片"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
if len(b64) > 20 * 1024 * 1024:
|
||||
self._reply(413, json.dumps({"code": 413, "message": "图片过大(≤15MB)"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
try:
|
||||
reply = self._llm_chat([
|
||||
{"role": "system", "content": "你是截图理解助手,能看懂图片内容(截图、票据、合同、表格、报错)。用中文简洁准确地回答,涉及金额/日期/编号等关键信息必须原样保留。"},
|
||||
{"role": "user", "content": [
|
||||
{"type": "text", "text": question},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}},
|
||||
]},
|
||||
])
|
||||
log_usage(machine, "screenshot-qa")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": reply}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json")
|
||||
|
||||
# ---------- 视频字幕:转录 + 翻译 ----------
|
||||
def _handle_subtitle(self):
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
if check(machine, "video-subtitle") != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
ctype = self.headers.get("Content-Type", "")
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if length > 500 * 1024 * 1024:
|
||||
self._reply(413, json.dumps({"code": 413, "message": "视频超过 500MB 限制"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
if not raw:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "未收到视频数据"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
import cgi as _cgi
|
||||
import audio_ops
|
||||
wd = "/tmp/sub-" + uuid.uuid4().hex[:12]
|
||||
os.makedirs(wd, exist_ok=True)
|
||||
video_bytes = raw
|
||||
if "multipart" in ctype:
|
||||
env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)}
|
||||
fs = _cgi.FieldStorage(fp=__import__("io").BytesIO(raw), environ=env, keep_blank_values=True)
|
||||
fitem = fs["file"] if "file" in fs.keys() else None
|
||||
if fitem is not None and fitem.filename:
|
||||
video_bytes = fitem.file.read()
|
||||
vin = os.path.join(wd, "in.mp4")
|
||||
with open(vin, "wb") as f:
|
||||
f.write(video_bytes)
|
||||
wav = os.path.join(wd, "audio.wav")
|
||||
r = subprocess.run(
|
||||
["ffmpeg", "-y", "-i", vin, "-vn", "-ac", "1", "-ar", "16000", wav],
|
||||
capture_output=True, timeout=600,
|
||||
)
|
||||
if r.returncode != 0 or not os.path.exists(wav):
|
||||
shutil.rmtree(wd, ignore_errors=True)
|
||||
self._reply(400, json.dumps({"code": 400, "message": "视频无音轨或格式不支持"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
q = parse.parse_qs(parse.urlparse(self.path).query)
|
||||
lang = (q.get("lang") or [""])[0]
|
||||
result = audio_ops.run_asr(wav, lang)
|
||||
shutil.rmtree(wd, ignore_errors=True)
|
||||
log_usage(machine, "video-subtitle")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": result}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
except Exception as e: # noqa: BLE001
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
self._reply(500, json.dumps({"code": 500, "message": f"字幕生成失败: {e}"}, ensure_ascii=False).encode(), "application/json")
|
||||
|
||||
def _handle_translate_srt(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
if check(machine, "video-subtitle") != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
srt = str(payload.get("srt") or "").strip()
|
||||
target = str(payload.get("target") or "en")
|
||||
if not srt or len(srt) > 60000:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "字幕内容无效"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
tname = "英文" if target == "en" else "日文" if target == "ja" else "英文"
|
||||
try:
|
||||
reply = self._llm_chat([
|
||||
{"role": "system", "content": f"你是专业字幕翻译。把用户提供的 SRT 字幕翻译成{tname}:保留序号、时间轴和空行结构完全不变,只翻译每条字幕的文字部分;译文保持口语化、简洁(每行尽量不超过原长的 1.3 倍)。只输出翻译后的 SRT,不要解释。"},
|
||||
{"role": "user", "content": srt},
|
||||
])
|
||||
log_usage(machine, "video-subtitle")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": reply}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"翻译失败: {e}"}, ensure_ascii=False).encode(), "application/json")
|
||||
|
||||
# ---------- AI 问答 ----------
|
||||
def _handle_aichat(self):
|
||||
payload = self._read_payload()
|
||||
@@ -1826,6 +1974,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/chat":
|
||||
self._handle_aichat()
|
||||
return
|
||||
if parsed.path == "/ai/copy":
|
||||
self._handle_copy()
|
||||
return
|
||||
if parsed.path == "/ai/vision":
|
||||
self._handle_vision()
|
||||
return
|
||||
if parsed.path == "/subtitle":
|
||||
self._handle_subtitle()
|
||||
return
|
||||
if parsed.path == "/ai/translate-srt":
|
||||
self._handle_translate_srt()
|
||||
return
|
||||
if parsed.path == "/convert":
|
||||
self._handle_convert()
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user