diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ccabb3..2748a8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to this project will be documented in this file. See [standa ## Version 2026.11.01-it-tools-pro ### 📦 本次更新(2026-11-01) +- **顶栏排版修复**:「⚡ IPv6 直连」按钮改为顶栏内正常排列(不再绝对定位悬浮),与「授权应用」等控件不重叠;窄屏(≤900px)自动收缩为纯图标并收紧间距,任何窗口宽度都不溢出、不遮挡 +- **热门地点扩容 + 测速历史快照**:热门地点延迟新增「百度」与「本省·运营商门户」(按你的 IPv4 归属自动匹配联通 10010 / 电信 189 / 移动 10086 / 广电 10099,悬停显示完整运营商与省份,未知运营商不插行);测速历史表新增「热门地点延迟快照」列——每次测速自动附带当时全部地点延迟(百度/本省运营商/镜像站/海外),跨线路、跨时间直接对照 - **代理 / VPN 检测**(免费不授权):本机IP查询页新增检测区——出口 IP 归属判定(proxycheck.io 数据库,区分家庭宽带/VPN/代理/数据中心/企业网络,IPv4+IPv6 分别判定)+ WebRTC STUN 泄漏实测(浏览器实测公网候选地址,若与主 IP 不一致则提示可能的真实出口,另显示本机内网 IP);浏览器无法直读系统代理开关,判定仅供参考,可一键重新检测 - **本机IP查询**(`/my-ip`,免费不授权):打开即显示**用户自己设备**的公网 IPv4 / IPv6 地址与中文归属地(多源容错、一键复制、不显示任何服务器信息);自动测量到 9 个热门地点(本站/清华TUNA/阿里云/腾讯云/华为云/中科大/香港Fedora/日本JAIST/Cloudflare)的延迟 - **IPv6 直连通道**:新增 `itv6.88531.cn`(4443 端口,双栈 nginx + DDNS);支持 IPv6 的用户页面横幅一键切换直连,访问速度更快;不支持的用户给出五步开启教程 diff --git a/docker/it-tools-relay/server.py b/docker/it-tools-relay/server.py index a6a4a53..3f5c0a9 100644 --- a/docker/it-tools-relay/server.py +++ b/docker/it-tools-relay/server.py @@ -56,7 +56,7 @@ TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json") TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000 DAY_MS = 24 * 60 * 60 * 1000 TZ_OFFSET_MS = 8 * 60 * 60 * 1000 # 北京时间 UTC+8 —— 重置对齐自然日 0 点 -PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen"} +PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen", "ai-text-edit"} MACHINE_RE = re.compile(r"^\d{10,16}$") # verify() messages that unconditionally block activation @@ -433,6 +433,9 @@ def _reco_file() -> str: return os.path.join(DATA_DIR, "reco.json") +# 无痕改字可用的视觉理解模型(实测支持 image_url 输入) +VISION_MODELS = ["qwen3.8-max", "qwen3.7-plus", "kimi-k3", "deepseek-v4-flash-vision-exp", "minimax-m3.1-flash-free", "step-5-preview", "deepseek-v4.1-flash"] + # 首页推荐种子:新工具上线时的默认展示(管理后台可增删改) DEFAULT_RECO = [ {"path": "/ai-image-lab", "icon": "🪄", "name": "AI 图片实验室", "desc": "智能抠图去背景、AI 无损放大变清晰、一键证件照", "enabled": True}, @@ -1291,11 +1294,90 @@ def _req_machine(handler): return handler.headers.get("X-Machine-Id", "") if handler else "" +# ---- 本地图片验证码(替代 Cloudflare Turnstile:不依赖外网,服务端出图) ---- +try: + from PIL import Image, ImageDraw, ImageFont + _HAS_PIL = True +except Exception: # pragma: no cover + _HAS_PIL = False + +CAPTCHA_TTL = 300 # 验证码有效期(秒) +_CAPTCHA_MAX = 5000 # 内存上限(防撑爆) +_CAPTCHAS = {} # id -> (code, expire_ts),单次核销 +_CAPTCHA_LOCK = threading.Lock() +_CAPTCHA_CHARS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # 去掉易混字符 0/O/1/I/L + + +def _gen_captcha(): + """返回 (captcha_id, png_base64)。4 位干扰码,5 分钟过期,取用即销毁。""" + import base64 + import random + import uuid + + code = "".join(random.choice(_CAPTCHA_CHARS) for _ in range(4)) + cid = uuid.uuid4().hex + w, h = 148, 52 + img = Image.new("RGB", (w, h), (247, 248, 251)) + d = ImageDraw.Draw(img) + try: + font = ImageFont.load_default(size=36) + except TypeError: # pragma: no cover + font = ImageFont.load_default() + # 干扰线 + 噪点 + for _ in range(7): + d.line([random.randrange(w), random.randrange(h), + random.randrange(w), random.randrange(h)], + fill=(random.randint(160, 210), random.randint(160, 210), random.randint(160, 210)), + width=1) + for _ in range(60): + d.point((random.randrange(w), random.randrange(h)), + fill=(random.randint(150, 220), random.randint(150, 220), random.randint(150, 220))) + # 逐字带抖动绘制 + x = 14 + for ch in code: + d.text((x, 6 + random.randint(-4, 4)), ch, font=font, + fill=(random.randint(10, 90), random.randint(10, 90), random.randint(10, 90))) + x += 33 + buf = io.BytesIO() + img.save(buf, format="PNG") + now = time.time() + with _CAPTCHA_LOCK: + for k in [k for k, v in _CAPTCHAS.items() if v[1] < now]: + _CAPTCHAS.pop(k, None) + while len(_CAPTCHAS) >= _CAPTCHA_MAX: + _CAPTCHAS.pop(next(iter(_CAPTCHAS)), None) + _CAPTCHAS[cid] = (code, now + CAPTCHA_TTL) + return cid, base64.b64encode(buf.getvalue()).decode() + + +def verify_captcha(payload) -> bool: + """核销 captcha_id + captcha_code(单次有效,大小写不敏感)。""" + cid = str(payload.get("captcha_id") or "") + got = str(payload.get("captcha_code") or "").strip().upper() + if not cid or not got: + return False + with _CAPTCHA_LOCK: + entry = _CAPTCHAS.pop(cid, None) # 无论对错都销毁,防爆破 + if not entry: + return False + stored, exp = entry + if time.time() > exp: + return False + import secrets as _secrets + return _secrets.compare_digest(stored, got) + + def user_api(method, sub, payload, handler): """returns (status, body_dict)""" + if method == "GET" and sub == "/captcha": + if not _HAS_PIL: + return 503, {"code": 503, "message": "验证码组件未就绪"} + cid, img_b64 = _gen_captcha() + return 200, {"code": 200, "message": "ok", "data": {"id": cid, "img": img_b64}} + if method == "POST" and sub == "/register": - if not verify_turnstile(str(payload.get("cf_token") or "")): - return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"} + if not verify_captcha(payload): + return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"} username = str(payload.get("username") or "").strip() password = str(payload.get("password") or "") if not USER_NAME_RE.match(username): @@ -1318,10 +1400,10 @@ def user_api(method, sub, payload, handler): if method == "POST" and sub == "/login": username = str(payload.get("username") or "").strip() password = str(payload.get("password") or "") - # admin accounts skip the human check (admin panel login has no Turnstile widget) + # admin accounts skip the human check (admin panel login has no captcha widget) role, _disabled = _user_attr(username) - if role != "admin" and not verify_turnstile(str(payload.get("cf_token") or "")): - return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"} + if role != "admin" and not verify_captcha(payload): + return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"} conn = _db() row = conn.execute("SELECT salt, pw_hash FROM users WHERE username=?", (username,)).fetchone() conn.close() @@ -1509,8 +1591,60 @@ class Handler(BaseHTTPRequestHandler): status, body = admin_api(method, sub, payload, self) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") + # ---------- 网速测试(用户浏览器 <-> 本站服务器) ---------- + _SPEED_CHUNK = (os.urandom(65536) + bytes(range(256)) * 256) * 2 # 256KB 混合块 + + def _handle_speed_get(self, parsed): + """下载测速:吐 N 字节数据(上限 30MB/次),no-store 防缓存。""" + try: + qs = parse.parse_qs(parsed.query) + n = int((qs.get("bytes") or ["1048576"])[0]) + except Exception: + n = 1048576 + n = max(1024, min(n, 30 * 1024 * 1024)) + self.send_response(200) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Content-Length", str(n)) + self.send_header("Cache-Control", "no-store, no-cache, must-revalidate") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + chunk = self._SPEED_CHUNK + try: + left = n + while left > 0: + b = chunk if left >= len(chunk) else chunk[:left] + self.wfile.write(b) + left -= len(b) + except (BrokenPipeError, ConnectionResetError): + pass + + def _handle_speed_post(self): + """上传测速:收满数据丢弃,回报收到字节数。""" + try: + length = int(self.headers.get("Content-Length") or 0) + except Exception: + length = 0 + length = max(0, min(length, 60 * 1024 * 1024)) + got = 0 + try: + while got < length: + b = self.rfile.read(min(65536, length - got)) + if not b: + break + got += len(b) + except (BrokenPipeError, ConnectionResetError): + pass + body = json.dumps({"code": 200, "message": "ok", "data": {"received": got}}, ensure_ascii=False).encode("utf-8") + self._reply(200, body, "application/json") + def do_GET(self): parsed = parse.urlparse(self.path) + if parsed.path == "/speed": + self._handle_speed_get(parsed) + return + if parsed.path == "/ai/vision-models": + self._reply(200, json.dumps({"code": 200, "message": "ok", "data": VISION_MODELS}, ensure_ascii=False).encode("utf-8"), "application/json") + return if parsed.path == "/ai/image-models": self._handle_image_models() return @@ -1585,17 +1719,53 @@ class Handler(BaseHTTPRequestHandler): return if parsed.path == "/translate": - target = f"{UPSTREAM}?{parsed.query}" + # 本地翻译:走内网 NewAPI LLM,不再请求谷歌(网络不可达导致 JSON 解析失败) + qs = parse.parse_qs(parsed.query or "") + q = (qs.get("q") or [""])[0] + sl = (qs.get("sl") or ["auto"])[0] + tl = (qs.get("tl") or ["zh-CN"])[0] try: - with OPENER_PROXY.open(target, timeout=TIMEOUT) as resp: - body = resp.read() - ctype = resp.headers.get("Content-Type", "application/json; charset=utf-8") - self._reply(200, body, ctype) + translated, detected = _translate_local(q, sl, tl) + # 返回谷歌兼容结构:[[ [译文, 原文, ...] ], null, 检测语言],前端零改动 + payload = json.dumps( + [[[translated, q, None, None, 10]], None, detected], + ensure_ascii=False, + ).encode("utf-8") + self._reply(200, payload, "application/json; charset=utf-8") except Exception as exc: # noqa: BLE001 payload = f'{{"error":"relay error: {exc}"}}'.encode() self._reply(502, payload, "application/json") return + # ---- IP 归属地(仅 /ip-geo?ip= 指定查询)---- + # 安全红线(2026-10-30):/my-ip 已永久删除。本服务处于 frp/反代链路后, + # XFF/X-Real-IP 拿到的是服务器出口地址而非真实客户端 IP,任何"回显接入方 IP" + # 的端点都会泄露服务器 IP。客户端公网 IP 必须由浏览器侧直接查外部服务获得。 + if parsed.path == "/my-ip": + self._reply(404, json.dumps({"code": 404, "message": "已下线:客户端 IP 请在浏览器侧查询,服务端不提供回显(避免暴露服务器出口地址)"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + if parsed.path == "/ip-geo": + ipq = (parse.parse_qs(parsed.query or "").get("ip") or [""])[0].strip() + if not ipq: + self._reply(400, json.dumps({"code": 400, "message": "缺少 ip 参数:请先在浏览器侧获取客户端公网 IP 再查询归属地"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + if not _ip_valid(ipq): + self._reply(400, json.dumps({"code": 400, "message": "IP 格式错误"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + data = _ip_info(ipq) + self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json") + return + + # ---- 代理/VPN 判定(/ip-check?ip= 浏览器侧自己的公网 IP)---- + if parsed.path == "/ip-check": + ipq = (parse.parse_qs(parsed.query or "").get("ip") or [""])[0].strip() + if not ipq or not _ip_valid(ipq): + self._reply(400, json.dumps({"code": 400, "message": "缺少或非法 ip 参数"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + data = _ip_check(ipq) + self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json") + return + self._reply(404, b"not found") # ---------- POST ---------- @@ -1726,6 +1896,65 @@ class Handler(BaseHTTPRequestHandler): except Exception as e: # noqa: BLE001 self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json") + # ---------- 文档翻译:图片/扫描件 OCR ---------- + _DOC_IMG_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tiff", ".tif") + + def _doc_ocr_one(self, img_bytes): + """调用宿主 rapidocr 识别一张图,按阅读顺序(行聚类)拼成文本""" + import secrets as _sec + boundary = "----td" + _sec.token_hex(8) + parts = [] + parts.append(("--%s\r\nContent-Disposition: form-data; name=\"image_file\"; filename=\"page.png\"\r\nContent-Type: application/octet-stream\r\n\r\n" % boundary).encode()) + parts.append(img_bytes) + parts.append(("\r\n--%s--\r\n" % boundary).encode()) + url = os.environ.get("OCR_URL", "http://192.168.68.19:5000/ocr") + req = request.Request(url, data=b"".join(parts), headers={"Content-Type": "multipart/form-data; boundary=%s" % boundary}) + d = json.loads(request.urlopen(req, timeout=120).read()) + items = [] + for k in sorted(d.keys(), key=lambda x: int(x) if str(x).isdigit() else 0): + it = d[k] + txt = str(it.get("rec_txt") or "").strip() + pts = it.get("dt_boxes") + if not txt: + continue + y = 0.0 + if isinstance(pts, list) and pts: + y = sum(float(p[1]) for p in pts) / len(pts) + items.append((y, txt)) + items.sort(key=lambda t: t[0]) + lines, prev_y, line = [], None, [] + for y, txt in items: + if prev_y is None or abs(y - prev_y) <= 12: + line.append(txt) + prev_y = y if prev_y is None else (prev_y * (len(line) - 1) + y) / len(line) + else: + lines.append(" ".join(line)) + line, prev_y = [txt], y + if line: + lines.append(" ".join(line)) + return "\n".join(lines) + + def _doc_ocr_pdf(self, src, wd, max_pages=30): + """扫描版 PDF:pdftoppm 渲染成 PNG 后逐页 OCR;返回 (text, pages)""" + info = subprocess.run(["pdfinfo", src], capture_output=True, timeout=60) + pages_total = 0 + for ln in (info.stdout or b"").decode("utf-8", "ignore").splitlines(): + if ln.startswith("Pages:"): + pages_total = int(ln.split(":", 1)[1].strip() or 0) + if pages_total <= 0: + return "", 0 + capped = min(pages_total, max_pages) + subprocess.run(["pdftoppm", "-png", "-r", "150", "-f", "1", "-l", str(capped), src, os.path.join(wd, "pg")], capture_output=True, timeout=300) + imgs = [os.path.join(wd, f) for f in os.listdir(wd) if f.startswith("pg") and f.endswith(".png")] + imgs.sort(key=lambda p: int(re.search(r"-(\d+)\.png$", p).group(1)) if re.search(r"-(\d+)\.png$", p) else 0) + texts = [] + for p in imgs: + with open(p, "rb") as f: + t = self._doc_ocr_one(f.read()) + if t.strip(): + texts.append(t) + return "\n\n".join(texts), len(imgs) + # ---------- 文档翻译 ---------- def _handle_translate_doc(self): machine = self.headers.get("X-Machine-Id", "") @@ -1751,20 +1980,26 @@ class Handler(BaseHTTPRequestHandler): if fitem is None or not fitem.filename: self._reply(400, json.dumps({"code": 400, "message": "缺少文件"}, ensure_ascii=False).encode(), "application/json") return - to_lang = (fs["to"].value if "to" in fs.keys() else "") or "Chinese" + raw_to = (fs["to"].value if "to" in fs.keys() else "") or "zh-CN" # 新前端传语言码;旧前端传中文标签(下一步统一映射) fname = os.path.basename(fitem.filename or "doc") ext = os.path.splitext(fname)[1].lower() - allowed = {".txt", ".md", ".docx", ".doc", ".pdf", ".html", ".htm", ".epub", ".rtf", ".odt"} + allowed = {".txt", ".md", ".docx", ".doc", ".pdf", ".html", ".htm", ".epub", ".rtf", ".odt"} | set(self._DOC_IMG_EXTS) if ext not in allowed: - self._reply(400, json.dumps({"code": 400, "message": f"不支持的格式 {ext}(支持 txt/md/docx/pdf/html/epub/rtf/odt)"}, ensure_ascii=False).encode(), "application/json") + self._reply(400, json.dumps({"code": 400, "message": f"不支持的格式 {ext}(支持 txt/md/docx/pdf/html/epub/rtf/odt 与 png/jpg/webp 等图片,扫描件自动 OCR)"}, ensure_ascii=False).encode(), "application/json") return wd = "/tmp/tdoc-" + uuid.uuid4().hex[:12] os.makedirs(wd, exist_ok=True) src = os.path.join(wd, "in" + ext) with open(src, "wb") as f: f.write(fitem.file.read()) - # 提取纯文本 - if ext in (".txt", ".md"): + # 提取纯文本(非纯文字内容自动先 OCR 识别) + ocr_pages = 0 + if ext in self._DOC_IMG_EXTS: + # 图片/截图:直接 OCR 识别文字 + with open(src, "rb") as f: + text = self._doc_ocr_one(f.read()) + ocr_pages = 1 + elif ext in (".txt", ".md"): rawb = open(src, "rb").read() text = None for enc in ("utf-8", "gb18030", "utf-16", "latin-1"): @@ -1777,11 +2012,16 @@ class Handler(BaseHTTPRequestHandler): else: outtxt = os.path.join(wd, "out.txt") r = subprocess.run(["ebook-convert", src, outtxt], capture_output=True, timeout=180) - if r.returncode != 0 or not os.path.exists(outtxt): + text = open(outtxt, "r", encoding="utf-8", errors="ignore").read() if r.returncode == 0 and os.path.exists(outtxt) else "" + if ext == ".pdf" and len(text.strip()) < 50: + # 无可提取文字层 → 疑似扫描版/图片型 PDF:逐页渲染 OCR + ocr_text, ocr_pages = self._doc_ocr_pdf(src, wd) + if ocr_text.strip(): + text = ocr_text + if not text.strip(): shutil.rmtree(wd, ignore_errors=True) - self._reply(400, json.dumps({"code": 400, "message": "文档解析失败,请确认文件未加密/损坏"}, ensure_ascii=False).encode(), "application/json") + self._reply(400, json.dumps({"code": 400, "message": "文档解析失败或未能识别到文字(扫描件请确保图片清晰、未加密)"}, ensure_ascii=False).encode(), "application/json") return - text = open(outtxt, "r", encoding="utf-8", errors="ignore").read() text = re.sub(r"\n{4,}", "\n\n\n", text or "").strip() if not text: shutil.rmtree(wd, ignore_errors=True) @@ -1791,27 +2031,32 @@ class Handler(BaseHTTPRequestHandler): shutil.rmtree(wd, ignore_errors=True) self._reply(413, json.dumps({"code": 413, "message": "文档过长(≤6万字符)"}, ensure_ascii=False).encode(), "application/json") return - # 分块翻译(按段落聚合,每块约 1400 字) + # 目标语种 → 本地 LibreTranslate 码(仅加载 zh/en;不支持时报清晰错误,不再调 LLM) + to_code = _DOC_LANG_LABELS.get(raw_to.strip(), "") or _tr_norm_lang(raw_to) + if not _lt_code(to_code): + shutil.rmtree(wd, ignore_errors=True) + self._reply(400, json.dumps({"code": 400, "message": "文档翻译已切换本地开源引擎(不限流、不耗 AI 额度):当前支持中文/英文文档,其他语种暂未开放"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + # 分块翻译(按段落聚合,每块约 1100 字,交给本地 LibreTranslate) paras = text.split("\n") chunks = [] cur = "" for para in paras: - if len(cur) + len(para) + 1 > 1400 and cur: + if len(cur) + len(para) + 1 > 1100 and cur: chunks.append(cur) cur = para else: cur = cur + "\n" + para if cur else para if cur: chunks.append(cur) - # 并发翻译分块(大文档不再串行等待,几十块也能几十秒完成) + # 并发翻译分块(本地引擎,几十块也就几十秒) from concurrent.futures import ThreadPoolExecutor def _tr(item): idx, ch = item - out = self._llm_chat([ - {"role": "system", "content": f"你是专业文档翻译。把用户提供的文档片段翻译成{to_lang}:保留原有换行、段落结构、编号和列表格式;专有名词、数字、日期原样保留;只输出译文,不要解释。"}, - {"role": "user", "content": ch}, - ]) + # 目标英文时源语强制中文:中英混排文本 auto 检测常误判为 en,导致原样回显不翻译 + src = "zh" if to_code == "en" else "auto" + out, _det = _translate_local(ch, src, to_code) return idx, out.strip() workers = min(8, max(1, len(chunks))) @@ -1819,10 +2064,10 @@ class Handler(BaseHTTPRequestHandler): results = list(ex.map(_tr, list(enumerate(chunks)))) results.sort(key=lambda x: x[0]) translated = [t for _, t in results] - result_text = "\n\n".join(translated) + result_text = "\n".join(translated) shutil.rmtree(wd, ignore_errors=True) log_usage(machine, "translator") - self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"text": result_text, "chars": len(text), "blocks": len(chunks)}}, ensure_ascii=False).encode("utf-8"), "application/json") + self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"text": result_text, "chars": len(text), "blocks": len(chunks), "ocr": ocr_pages > 0, "ocr_pages": ocr_pages}}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": f"文档翻译失败: {e}"}, ensure_ascii=False).encode(), "application/json") @@ -2306,6 +2551,9 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self): parsed = parse.urlparse(self.path) + if parsed.path == "/speed": + self._handle_speed_post() + return if parsed.path.startswith("/admin"): self._handle_admin("POST") return @@ -2348,6 +2596,9 @@ class Handler(BaseHTTPRequestHandler): if parsed.path == "/ai/edit-image": self._handle_edit_image() return + if parsed.path == "/ai/seamless-edit": + self._handle_seamless_edit() + return if parsed.path == "/translate-doc": self._handle_translate_doc() return @@ -2540,6 +2791,352 @@ class Handler(BaseHTTPRequestHandler): print(f"[img] edit failed: {e}", flush=True) self._reply(502, json.dumps({"code": 502, "message": f"图生图失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json") + # ---------- 无痕改字:OCR 定位 + vision 选字块 + 本地像素引擎无缝重绘 ---------- + def _se_ocr(self, img_bytes): + """调用宿主 rapidocr 返回 [{text, box(4角)}]""" + boundary = "----se" + __import__("secrets").token_hex(8) + parts = [] + parts.append(f"--{boundary}\r\nContent-Disposition: form-data; name=\"image_file\"; filename=\"img.png\"\r\nContent-Type: application/octet-stream\r\n\r\n".encode()) + parts.append(img_bytes) + parts.append(f"\r\n--{boundary}--\r\n".encode()) + req = request.Request(os.environ.get("OCR_URL", "http://192.168.68.19:5000/ocr"), data=b"".join(parts), + headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) + d = json.loads(request.urlopen(req, timeout=90).read()) + out = [] + for k in sorted(d.keys(), key=lambda x: int(x) if str(x).isdigit() else 0): + it = d[k] + txt = str(it.get("rec_txt") or "").strip() + pts = it.get("dt_boxes") + if txt and isinstance(pts, list) and len(pts) >= 4: + out.append({"text": txt, "box": [[float(p[0]), float(p[1])] for p in pts[:4]]}) + return out + + def _se_vision_pick(self, model, img_bytes, ocr_items, prompt): + """vision 模型看图+OCR 清单+用户需求 → 选出要改的字块与新文字(JSON)""" + from PIL import Image as _Im + im = _Im.open(io.BytesIO(img_bytes)).convert("RGB") + if max(im.size) > 1024: + k = 1024 / max(im.size) + im = im.resize((int(im.width * k), int(im.height * k))) + buf = io.BytesIO() + im.save(buf, "JPEG", quality=85) + b64 = __import__("base64").b64encode(buf.getvalue()).decode() + listing = "\n".join(f"[{i}] {o['text']}" for i, o in enumerate(ocr_items)) + user = ( + f"图中OCR识别到的文字块(编号:内容):\n{listing}\n\n" + f"用户需求:{prompt}\n\n" + "请判断需要修改哪些文字块、新文字是什么。只输出JSON,不要其它内容:\n" + '{"edits":[{"idx":0,"new_text":"新文字"}],"note":"一句话说明"}\n' + "规则:idx为上面的编号;new_text为空字符串表示只删除不新增;无需修改时输出{\"edits\":[]};最多3处。" + ) + key = os.environ.get("NEWAPI_KEY", "") + body = json.dumps({ + "model": model, "max_tokens": 600, "temperature": 0.1, + "messages": [{"role": "user", "content": [ + {"type": "text", "text": user}, + {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}, + ]}], + }).encode() + req = request.Request(self._nm_base() + "/chat/completions", data=body, + headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}) + d = json.loads(request.urlopen(req, timeout=150).read()) + content = (d.get("choices") or [{}])[0].get("message", {}).get("content") or "" + m = re.search(r"\{.*\}", content, re.S) + if not m: + raise RuntimeError("模型未返回有效指令") + parsed = json.loads(m.group(0)) + edits = [] + for e in (parsed.get("edits") or [])[:3]: + try: + idx = int(e.get("idx")) + except Exception: + continue + if 0 <= idx < len(ocr_items): + edits.append({"idx": idx, "new_text": str(e.get("new_text") or "").strip()[:40]}) + return edits, str(parsed.get("note") or "").strip()[:120] + + @staticmethod + def _se_detect_style(im_arr, box): + """从框像素推断角度/字号/颜色/粗细(与前端 PsEditor.detectTextStyle 同算法)""" + import numpy as _np + import math as _math + (p0, p1, p2, p3) = box + angle = _math.degrees(_math.atan2(p1[1] - p0[1], p1[0] - p0[0])) + if angle > 90: + angle -= 180 + if angle <= -90: + angle += 180 + midT = ((p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2) + midB = ((p3[0] + p2[0]) / 2, (p3[1] + p2[1]) / 2) + bh = _math.hypot(midB[0] - midT[0], midB[1] - midT[1]) + bw = (_math.hypot(p1[0] - p0[0], p1[1] - p0[1]) + _math.hypot(p2[0] - p3[0], p2[1] - p3[1])) / 2 + cx = (p0[0] + p1[0] + p2[0] + p3[0]) / 4 + cy = (p0[1] + p1[1] + p2[1] + p3[1]) / 4 + size = max(10, int(round(bh * 0.82))) + H, W = im_arr.shape[:2] + x0 = max(0, int(min(p[0] for p in box))) + y0 = max(0, int(min(p[1] for p in box))) + x1 = min(W, int(max(p[0] for p in box)) + 1) + y1 = min(H, int(max(p[1] for p in box)) + 1) + if x1 - x0 < 4 or y1 - y0 < 4: + return None + crop = im_arr[y0:y1, x0:x1].astype(_np.float32) + hh, ww = crop.shape[:2] + a = _math.radians(angle) + ca, sa = _math.cos(a), _math.sin(a) + ys, xs = _np.mgrid[0:hh, 0:ww] + ox = xs + x0 + 0.5 - cx + oy = ys + y0 + 0.5 - cy + lx = ox * ca + oy * sa + ly = -ox * sa + oy * ca + ringR = max(bw / 2, bh / 2) + bh * 0.5 + inside = (_np.abs(lx) <= bw / 2) & (_np.abs(ly) <= bh / 2) + ring = (_np.abs(lx) <= ringR) & (_np.abs(ly) <= ringR) & ~inside + if inside.sum() < 20 or ring.sum() < 8: + return None + bg = _np.median(crop[ring], axis=0) # crop[ring] 已是 (N,3) + dist = _np.linalg.norm(crop - bg[None, None, :], axis=2) + ink = inside & (dist > 60) + if ink.sum() < 6 or ink.sum() / max(1, inside.sum()) < 0.008: + lum = 0.299 * bg[0] + 0.587 * bg[1] + 0.114 * bg[2] + color = (255, 255, 255) if lum < 110 else (0, 0, 0) + return {"size": size, "color": color, "bold": True, "angle": round(angle, 1), "cx": cx, "cy": cy, "bw": bw} + color = tuple(int(v) for v in _np.median(crop[ink], axis=0)) + # 粗细:中心行带墨迹横向行程中位数 + bold = False + band = ink & (_np.abs(ly) < bh * 0.14) + if band.sum() > 10: + runs = [] + for r in range(hh): + row = band[r] + c2 = 0 + for v in row: + if v: + c2 += 1 + elif c2: + runs.append(c2) + c2 = 0 + if c2: + runs.append(c2) + if runs: + runs.sort() + bold = runs[len(runs) // 2] / size > 0.11 + return {"size": size, "color": color, "bold": bold, "angle": round(angle, 1), "cx": cx, "cy": cy, "bw": bw} + + @staticmethod + def _se_inpaint(arr, box, style): + """框内文字笔画从周边背景扩散重建(Jacobi 迭代),返回新数组""" + import numpy as _np + H, W = arr.shape[:2] + padX = max(2, int(round(style["bw"] * 0.05))) + padY = max(2, int(round(style["size"] * 0.12))) + cx, cy = style["cx"], style["cy"] + x0 = max(0, int(cx - style["bw"] / 2) - padX) + y0 = max(0, int(cy - style["size"] * 0.9) - padY) + x1 = min(W, int(cx + style["bw"] / 2) + padX) + y1 = min(H, int(cy + style["size"] * 0.9) + padY) + if x1 - x0 < 4 or y1 - y0 < 4: + return arr + region = arr[y0:y1, x0:x1].astype(_np.float32) + # 蒙版:与框周边中位色距离>42 的笔画像素,外扩1px + border = _np.concatenate([region[0], region[-1], region[:, 0], region[:, -1]]) + bg = _np.median(border, axis=0) + mask = (_np.linalg.norm(region - bg[None, None, :], axis=2) > 42) + if not mask.any(): + mask = _np.ones(mask.shape, dtype=bool) # 实心底→整块重建 + m = mask.copy() + m[1:, :] |= mask[:-1, :] + m[:-1, :] |= mask[1:, :] + m[:, 1:] |= mask[:, :-1] + m[:, :-1] |= mask[:, 1:] + mask = m + out = region.copy() + known = ~mask + if not known.any(): + return arr + out[mask] = out[known].reshape(-1, 3).mean(0) + for _ in range(320): + padded = _np.pad(out, ((1, 1), (1, 1), (0, 0)), mode="edge") + avg = (padded[:-2, 1:-1] + padded[2:, 1:-1] + padded[1:-1, :-2] + padded[1:-1, 2:]) / 4.0 + out[mask] = avg[mask] + res = arr.copy() + res[y0:y1, x0:x1] = _np.clip(out, 0, 255).astype(_np.uint8) + return res + + @staticmethod + def _font(bold, size): + from PIL import ImageFont + base = "/hostfs/usr/share/fonts/opentype/noto/NotoSansCJK-%s.ttc" + name = "Bold" if bold else "Regular" + for idx in (2, 0): + try: + return ImageFont.truetype(base % name, size, index=idx) + except Exception: + continue + try: + return ImageFont.truetype(base % name, size) + except Exception: + return ImageFont.load_default() + + @classmethod + def _se_draw_text(cls, im, text, style, scale=1.0): + """按检测样式在原位重绘新字(含角度),过框宽自动缩号""" + from PIL import Image as _Im, ImageDraw as _Draw + import math as _math + size = max(8, int(round(style["size"] * scale))) + font = cls._font(style["bold"], size) + probe = _Im.new("RGBA", (8, 8), (0, 0, 0, 0)) + pd = _Draw.Draw(probe) + bb = pd.textbbox((0, 0), text, font=font) + tw, th = bb[2] - bb[0], bb[3] - bb[1] + if tw <= 0: + return im + pad = size + layer = _Im.new("RGBA", (tw + pad * 2, th + pad * 2), (0, 0, 0, 0)) + ld = _Draw.Draw(layer) + ld.text((pad - bb[0], pad - bb[1]), text, font=font, fill=style["color"] + (255,)) + # 新字过原框宽 1.15 倍 → 整体等比缩小 + avail = style["bw"] * 1.15 + if layer.width > avail and avail > 0: + k = avail / layer.width + layer = layer.resize((max(1, int(layer.width * k)), max(1, int(layer.height * k))), _Im.LANCZOS) + if abs(style["angle"]) > 0.05: + # 画布正角=顺时针;PIL 正角=逆时针 → 取负 + layer = layer.rotate(-style["angle"], expand=True, resample=_Im.BICUBIC) + x = int(round(style["cx"] - layer.width / 2)) + y = int(round(style["cy"] - layer.height / 2)) + im.paste(layer, (x, y), layer) + return im + + @staticmethod + def _se_fit_size(im, size_opt, custom_w, custom_h): + """默认保持原尺寸;比例/自定义 → 等比包含 + 边缘中位色补边""" + import numpy as _np + from PIL import Image as _ImX + ratios = {"4:3": 4 / 3, "3:4": 3 / 4, "1:1": 1.0} + tw = th = None + if size_opt in ratios: + r = ratios[size_opt] + cur = im.width / im.height + if abs(cur - r) < 0.01: + return im + if cur > r: + th = im.height + tw = int(round(th * r)) + else: + tw = im.width + th = int(round(tw / r)) + elif size_opt == "custom" and custom_w and custom_h: + tw, th = max(64, min(2048, custom_w)), max(64, min(2048, custom_h)) + if not tw: + return im + arr = _np.asarray(im.convert("RGB")) + edge = _np.concatenate([arr[0], arr[-1], arr[:, 0], arr[:, -1]]).astype(_np.float32) + col = tuple(int(v) for v in _np.median(edge, axis=0)) + canvas = _ImX.new("RGB", (tw, th), col) + k = min(tw / im.width, th / im.height) + im2 = im.resize((max(1, int(im.width * k)), max(1, int(im.height * k))), _ImX.LANCZOS) + canvas.paste(im2, ((tw - im2.width) // 2, (th - im2.height) // 2)) + return canvas + + def _handle_seamless_edit(self): + machine = self.headers.get("X-Machine-Id", "") + if check(machine, "ai-text-edit") != 200: + self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + ctype = self.headers.get("Content-Type", "") + if "multipart/form-data" not in ctype: + self._reply(400, json.dumps({"code": 400, "message": "需要 multipart 上传"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + try: + form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype}) + prompt = str(form.getvalue("prompt") or "").strip()[:200] + model = str(form.getvalue("model") or "qwen3.8-max")[:60] + size_opt = str(form.getvalue("size") or "default")[:10] + try: + count = max(1, min(3, int(form.getvalue("count") or 1))) + except Exception: + count = 1 + try: + custom_w = int(form.getvalue("custom_w") or 0) + custom_h = int(form.getvalue("custom_h") or 0) + except Exception: + custom_w = custom_h = 0 + if not prompt: + self._reply(400, json.dumps({"code": 400, "message": "请描述要修改的文字和样式"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + up = form["image"] if "image" in form else None + if up is None or not getattr(up, "filename", None): + self._reply(400, json.dumps({"code": 400, "message": "请上传图片"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + img = up.file.read() + if len(img) > 24 * 1024 * 1024: + self._reply(400, json.dumps({"code": 400, "message": "图片超过 24MB"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + from PIL import Image as _Im + base_im = _Im.open(io.BytesIO(img)).convert("RGB") + except Exception as e: # noqa: BLE001 + self._reply(400, json.dumps({"code": 400, "message": f"图片解析失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + + try: + ocr_items = self._se_ocr(img) + except Exception as e: # noqa: BLE001 + print(f"[se] ocr failed: {e}", flush=True) + self._reply(502, json.dumps({"code": 502, "message": f"文字识别失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + if not ocr_items: + self._reply(400, json.dumps({"code": 400, "message": "未识别到图中文字,可换更清晰的截图"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + + try: + edits, note = self._se_vision_pick(model, img, ocr_items, prompt) + except Exception as e: # noqa: BLE001 + print(f"[se] vision failed: {e}", flush=True) + self._reply(502, json.dumps({"code": 502, "message": f"AI 理解失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + if not edits: + self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"images": [], "edits": [], "note": note or "未找到需要修改的文字,请描述得更具体(写明原文和新文字)"}}, ensure_ascii=False).encode("utf-8"), "application/json") + return + + import numpy as _np + orig_arr = _np.asarray(base_im) + # 逐处改字:检测样式 → 无缝擦除 → 重绘新字 + results = [] + for e in edits: + o = ocr_items[e["idx"]] + st = self._se_detect_style(orig_arr, o["box"]) + if not st: + continue + results.append({"old": o["text"], "new": e["new_text"], "style": f"{st['size']}px · {'粗体' if st['bold'] else '常规'} · {st['angle']}°", "_box": o["box"], "_st": st}) + if not results: + self._reply(502, json.dumps({"code": 502, "message": "未能定位要修改的文字块"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + + scales = {1: [1.0], 2: [0.95, 1.06], 3: [0.9, 1.0, 1.08]}[count] + images = [] + try: + from PIL import Image as _Im + for s in scales: + work = base_im.copy() + for r in results: + arr = _np.asarray(work) + arr = self._se_inpaint(arr, r["_box"], r["_st"]) + work = _Im.fromarray(arr) + if r["new"]: + work = self._se_draw_text(work, r["new"], r["_st"], scale=s) + work = self._se_fit_size(work, size_opt, custom_w, custom_h) + buf = io.BytesIO() + work.save(buf, "PNG") + images.append({"b64": __import__("base64").b64encode(buf.getvalue()).decode(), "scale": s}) + except Exception as e: # noqa: BLE001 + print(f"[se] render failed: {e}", flush=True) + self._reply(502, json.dumps({"code": 502, "message": f"重绘失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + + pub = [{"old": r["old"], "new": r["new"] or "(仅删除)", "style": r["style"]} for r in results] + self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"images": images, "edits": pub, "note": note}}, ensure_ascii=False).encode("utf-8"), "application/json") + # ---------- conversion ---------- def _handle_convert(self): try: @@ -2861,6 +3458,233 @@ def _llm_chat_nm(messages: list, model: str = "", timeout: int = 120) -> str: return data["choices"][0]["message"]["content"] +# ---- 本地翻译(在线翻译 + 文档翻译):LibreTranslate(本机 Docker 离线模型,不限流不耗 LLM) ---- +# 文档翻译目标语种:旧前端传中文标签、新前端传语言码,两种都兼容 +_DOC_LANG_LABELS = { + "中文(简体)": "zh-CN", "中文(繁体)": "zh-TW", "英语": "en", "日语": "ja", + "韩语": "ko", "法语": "fr", "德语": "de", "西班牙语": "es", "俄语": "ru", + "葡萄牙语": "pt", "意大利语": "it", "阿拉伯语": "ar", "越南语": "vi", + "泰语": "th", "印尼语": "id", +} +_TR_LANG_NAMES = { + "zh-CN": "简体中文", "zh-TW": "繁体中文", "en": "英语", "ja": "日语", + "ko": "韩语", "fr": "法语", "de": "德语", "es": "西班牙语", "ru": "俄语", + "pt": "葡萄牙语", "it": "意大利语", "ar": "阿拉伯语", "vi": "越南语", + "th": "泰语", "id": "印尼语", +} +_TR_LANG_SET = set(_TR_LANG_NAMES) + +# LibreTranslate(本机 Docker,容器名 libretranslate,仅加载 zh/en 模型) +_LT_URL = os.environ.get("LT_URL", "http://libretranslate:5000/translate") +# 内网直连:显式禁用环境代理(relay 容器带 HTTPS_PROXY,会把内网请求也送进代理) +_LT_OPENER = request.build_opener(request.ProxyHandler({})) +_LT_SRC_MAP = { + "zh-cn": "zh", "zh-tw": "zh", "zh": "zh", "zh-hans": "zh", "zh-hant": "zh", + "en": "en", "en-us": "en", "en-gb": "en", +} + + +def _lt_code(gcode: str) -> str: + """谷歌系语言码 → LibreTranslate 码;未加载语种返回 ''(触发 MyMemory 兜底)。""" + return _LT_SRC_MAP.get((gcode or "").strip().lower(), "") + + +# Argos zh→en 偶发把整段输出成全大写(确定性引擎怪癖):转正常句式时保留缩写大写 +_LT_ACRONYMS = { + "JSON", "API", "HTML", "CSS", "HTTP", "HTTPS", "URL", "UUID", "PDF", "DOCX", + "SQL", "USB", "WIFI", "AI", "CSV", "ZIP", "IT", "PC", "GUI", "CLI", "CPU", + "GPU", "RAM", "SSD", "DVD", "VIP", "ID", "OK", "SDK", "APP", "IT-TOOLS-PRO", +} + + +def _lt_fixcase(s: str) -> str: + """译文中 >80% 字母为大写时转正常句式(句首大写,其余小写,缩写词保持大写)。""" + letters = [c for c in s if c.isalpha()] + if len(letters) < 10: + return s + if sum(1 for c in letters if c.isupper()) / len(letters) < 0.8: + return s + fixed = [] + for w in s.split(" "): + bare = w.strip(".,;:!?()[]{}\"'—-") + if bare and bare.isupper() and len(bare) >= 2 and bare in _LT_ACRONYMS: + fixed.append(w) + else: + fixed.append(w.lower() if bare else w) + out = " ".join(fixed) + return re.sub(r"(^|[\n.!?]\s*)([a-z])", lambda m: m.group(1) + m.group(2).upper(), out) + + +# ---------- 本机IP查询:IP 归属地(免费端点 /my-ip、/ip-geo 用) ---------- +_IPGEO_CACHE = {} + + +def _ip_valid(s: str) -> bool: + import ipaddress + try: + ipaddress.ip_address(s) + return True + except Exception: + return False + + +def _ip_info(ip): + """归属地查询:ip-api 中文数据 + 内存缓存;内网地址只标记 lan 不外查。""" + ip = (ip or "").strip() + if not ip: + return None + import ipaddress + try: + addr = ipaddress.ip_address(ip) + except Exception: + return None + lan = bool(addr.is_private or addr.is_loopback or addr.is_link_local) + cached = _IPGEO_CACHE.get(ip) + if cached is not None: + return cached + info = {"ip": ip, "lan": lan, "country": "", "region": "", "city": "", "isp": "", "as": ""} + if not lan: + try: + url = "http://ip-api.com/json/%s?lang=zh-CN&fields=status,country,regionName,city,isp,as" % ip + with request.urlopen(url, timeout=6) as resp: + d = json.loads(resp.read().decode("utf-8", "ignore")) + if d.get("status") == "success": + info = { + "ip": ip, "lan": False, + "country": d.get("country") or "", + "region": d.get("regionName") or "", + "city": d.get("city") or "", + "isp": d.get("isp") or "", + "as": d.get("as") or "", + } + except Exception: + pass + if len(_IPGEO_CACHE) > 1500: + _IPGEO_CACHE.clear() + _IPGEO_CACHE[ip] = info + return info + + +# ---------- 代理/VPN 判定(proxycheck.io 免 key,内存缓存) ---------- +_IPCHECK_CACHE = {} + + +def _ip_check(ip): + """出口 IP 代理/VPN/数据中心判定:proxycheck.io + 内存缓存;内网地址不外查。 + 返回 {ip, lan, proxy(bool|None), type, provider, hostname, asn}; + 查询失败 proxy=None(前端降级为“无法判定”)。""" + ip = (ip or "").strip() + if not ip or not _ip_valid(ip): + return None + import ipaddress + addr = ipaddress.ip_address(ip) + lan = bool(addr.is_private or addr.is_loopback or addr.is_link_local) + cached = _IPCHECK_CACHE.get(ip) + if cached is not None: + return cached + out = {"ip": ip, "lan": lan, "proxy": None, "type": "", "provider": "", "hostname": "", "asn": ""} + if not lan: + try: + url = "http://proxycheck.io/v2/%s?vpn=1&asn=1" % ip + with request.urlopen(url, timeout=8) as resp: + d = json.loads(resp.read().decode("utf-8", "ignore")) + if d.get("status") == "ok": + rec = d.get(ip) or {} + out = { + "ip": ip, "lan": False, + "proxy": str(rec.get("proxy") or "").lower() == "yes", + "type": rec.get("type") or "", + "provider": rec.get("provider") or rec.get("organisation") or "", + "hostname": rec.get("hostname") or "", + "asn": rec.get("asn") or "", + } + except Exception: + pass + if len(_IPCHECK_CACHE) > 1500: + _IPCHECK_CACHE.clear() + _IPCHECK_CACHE[ip] = out + return out + + +def _tr_chunks(text: str, limit: int = 1200): + """按行/长度切块,保留换行结构;返回 [(块文本, 块后是否接换行)]""" + lines = text.split("\n") + units = [] + for idx, ln in enumerate(lines): + nl = idx < len(lines) - 1 + while len(ln) > limit: # 超长单行硬切(切点不补换行) + units.append((ln[:limit], False)) + ln = ln[limit:] + units.append((ln, nl)) + chunks, cur, cur_nl = [], "", False + for frag, nl in units: + sep = "\n" if cur and cur_nl else "" + if len(cur) + len(sep) + len(frag) <= limit: + cur = cur + sep + frag + cur_nl = nl + else: + if cur: + chunks.append((cur, cur_nl)) + cur, cur_nl = frag, nl + if cur: + chunks.append((cur, cur_nl)) + return chunks or [("", False)] + + +def _tr_norm_lang(raw: str) -> str: + lang = (raw or "").strip().lower().replace("_", "-") + if lang in _TR_LANG_SET: + return lang + if lang in ("zh", "zh-cn", "zh-hans", "zh-hans-cn", "cmn"): + return "zh-CN" + if lang in ("zh-tw", "zh-hant", "zh-hant-tw"): + return "zh-TW" + for code in _TR_LANG_SET: + if lang.startswith(code.lower()[:2]): + return code + return "" + + +def _translate_local(q: str, sl: str, tl: str): + """本地开源翻译:LibreTranslate(本机 Docker,离线 Argos 模型),不消耗 LLM 额度。 + 返回 (译文, 检测到的源语言谷歌码)。语种未加载时抛错 → 前端自动转 MyMemory 兜底。""" + text = (q or "").strip() + if not text: + return "", ("" if sl == "auto" else sl) + tgt = _lt_code(tl) + if not tgt: + raise RuntimeError(f"local translate: target '{tl}' not loaded") + src = "auto" + if sl and sl != "auto": + src = _lt_code(sl) + if not src: + raise RuntimeError(f"local translate: source '{sl}' not loaded") + detected = "" if src == "auto" else src + parts = [] + for chunk, nl in _tr_chunks(text): + if not chunk: + parts.append(("", nl)) + continue + body = json.dumps( + {"q": chunk, "source": src, "target": tgt, "format": "text"} + ).encode("utf-8") + req_obj = request.Request( + _LT_URL, data=body, headers={"Content-Type": "application/json"} + ) + with _LT_OPENER.open(req_obj, timeout=120) as resp: + obj = json.loads(resp.read().decode("utf-8")) + if not isinstance(obj, dict) or "translatedText" not in obj: + raise RuntimeError(f"local translate: {obj}") + parts.append((_lt_fixcase(str(obj["translatedText"])), nl)) + if not detected: + dl = str((obj.get("detectedLanguage") or {}).get("language", "")) + detected = {"zh-Hans": "zh-CN", "zh-Hant": "zh-TW"}.get(dl, dl) + translated = "".join(t + ("\n" if nl else "") for t, nl in parts) + if sl != "auto": + detected = sl + return translated, detected + + def _is_urlish(s: str) -> bool: s = (s or "").strip().lower() return s.startswith("http") or "article url" in s diff --git a/locales/zh.yml b/locales/zh.yml index 45974fd..583abcf 100644 --- a/locales/zh.yml +++ b/locales/zh.yml @@ -381,7 +381,7 @@ tools: my-ip: title: 本机IP查询 - description: 查询你设备的公网IPv4/IPv6地址与所属地(IPv6不支持时提供开启教程),代理/VPN检测(出口IP归属判定+WebRTC泄漏实测),本站已支持IPv6直连,测连接热门地点延迟,一键测试你到本站服务器的下载/上传网速并自动记录历史。 + description: 查询你设备的公网IPv4/IPv6地址与所属地(IPv6不支持时提供开启教程),代理/VPN检测(出口IP归属判定+WebRTC泄漏实测),热门地点延迟实测(百度、本省运营商门户、全国镜像站与海外节点),测速历史自动记录延迟快照,本站已支持IPv6直连,一键测试你到本站服务器的下载/上传网速。 hash-text: title: Hash 文本 diff --git a/src/components/UserMenu.vue b/src/components/UserMenu.vue index 93e7071..a92f960 100644 --- a/src/components/UserMenu.vue +++ b/src/components/UserMenu.vue @@ -7,76 +7,34 @@ import { useCloudSync } from '@/composable/cloud-sync'; const { isLoggedIn, username, isAdmin, login, register, logout } = useUserAuth(); const { syncNow } = useCloudSync(); -// ---- Cloudflare Turnstile ---- -const CF_SITEKEY = '0x4AAAAAAFUO0U-CvL78Vr6y'; -const cfToken = ref(''); -const cfReady = ref(false); -let cfWidgetId = ''; +// ---- 本地图片验证码(服务端出图,不依赖外网) ---- +const captchaId = ref(''); +const captchaImg = ref(''); +const captchaCode = ref(''); -declare global { - interface Window { - turnstile?: any; - __cfOnload?: () => void; - } -} - -function loadTurnstileScript(): Promise { - if (window.turnstile) { - return Promise.resolve(); - } - return new Promise((resolve) => { - window.__cfOnload = () => resolve(); - const s = document.createElement('script'); - s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=__cfOnload&render=explicit'; - s.async = true; - document.head.appendChild(s); - }); -} - -function resetCf() { - cfToken.value = ''; - if (window.turnstile && cfWidgetId) { - try { - window.turnstile.reset(cfWidgetId); +async function loadCaptcha() { + captchaCode.value = ''; + try { + const res = await fetch('/relay/user/captcha'); + const body = await res.json().catch(() => ({} as any)); + if (body?.code === 200 && body.data?.id) { + captchaId.value = body.data.id; + captchaImg.value = `data:image/png;base64,${body.data.img}`; } - catch { /* ignore */ } } -} - -async function mountCf() { - await loadTurnstileScript(); - // wait until container is in DOM (modal just opened) - await new Promise(r => setTimeout(r, 80)); - const el = document.querySelector('.cf-container'); - if (!el || cfWidgetId) { - return; - } - cfWidgetId = window.turnstile.render(el as HTMLElement, { - sitekey: CF_SITEKEY, - theme: 'light', - size: 'flexible', - callback: (token: string) => { - cfToken.value = token; - }, - 'expired-callback': () => { - cfToken.value = ''; - }, - 'error-callback': () => { - cfToken.value = ''; - }, - }); - cfReady.value = true; + catch { /* 静默:提交时服务端会再校验 */ } } const showLogin = ref(false); watch(showLogin, (v) => { if (v) { - mountCf().catch(() => {}); + loadCaptcha().catch(() => {}); } else { - cfWidgetId = ''; - cfToken.value = ''; + captchaId.value = ''; + captchaImg.value = ''; + captchaCode.value = ''; } }); const mode = ref<'login' | 'register'>('login'); @@ -105,10 +63,10 @@ async function submit() { busy.value = true; try { if (mode.value === 'login') { - await login(formUser.value.trim(), formPass.value, cfToken.value); + await login(formUser.value.trim(), formPass.value, captchaId.value, captchaCode.value.trim()); } else { - await register(formUser.value.trim(), formPass.value, cfToken.value); + await register(formUser.value.trim(), formPass.value, captchaId.value, captchaCode.value.trim()); } showLogin.value = false; formPass.value = ''; @@ -119,7 +77,8 @@ async function submit() { } catch (e: any) { error.value = String(e?.message || e); - resetCf(); + // 验证码单次有效,失败后必须换一张 + loadCaptcha().catch(() => {}); } finally { busy.value = false; @@ -182,8 +141,10 @@ function switchMode() { -
-
+
@@ -198,7 +159,7 @@ function switchMode() { 取消 - + {{ busy ? '请稍候…' : (mode === 'login' ? '登录' : '注册并登录') }}
@@ -263,9 +224,30 @@ function switchMode() { } } -.cf-wrap { +.captcha-row { + display: flex; + gap: 8px; + align-items: center; margin: 2px 0 8px; - transition: opacity 0.2s; + + .captcha-input { + flex: 1; + margin: 0; + } + + .captcha-img { + height: 40px; + border-radius: 4px; + cursor: pointer; + flex-shrink: 0; + } + + .captcha-reload { + flex-shrink: 0; + font-size: 13px; + color: #18a058; + white-space: nowrap; + } } .user-mask { diff --git a/src/composable/user-auth.ts b/src/composable/user-auth.ts index 0fde790..b8894b1 100644 --- a/src/composable/user-auth.ts +++ b/src/composable/user-auth.ts @@ -52,11 +52,11 @@ export function useUserAuth() { const username = computed(() => state.value?.username ?? ''); const isAdmin = computed(() => state.value?.role === 'admin'); - async function login(u: string, p: string, cfToken = '') { + async function login(u: string, p: string, captchaId = '', captchaCode = '') { const { status, body } = await apiFetch('/user/login', { method: 'POST', headers: { 'Content-Type': 'application/json', ...licenseHeaders() }, - body: JSON.stringify({ username: u, password: p, cf_token: cfToken }), + body: JSON.stringify({ username: u, password: p, captcha_id: captchaId, captcha_code: captchaCode }), }); if (status !== 200) { throw new Error(body.message || '登录失败'); @@ -66,11 +66,11 @@ export function useUserAuth() { return body.data.username; } - async function register(u: string, p: string, cfToken = '') { + async function register(u: string, p: string, captchaId = '', captchaCode = '') { const { status, body } = await apiFetch('/user/register', { method: 'POST', headers: { 'Content-Type': 'application/json', ...licenseHeaders() }, - body: JSON.stringify({ username: u, password: p, cf_token: cfToken }), + body: JSON.stringify({ username: u, password: p, captcha_id: captchaId, captcha_code: captchaCode }), }); if (status !== 200) { throw new Error(body.message || '注册失败'); diff --git a/src/layouts/base.layout.vue b/src/layouts/base.layout.vue index 443da98..c8f08d5 100644 --- a/src/layouts/base.layout.vue +++ b/src/layouts/base.layout.vue @@ -49,6 +49,51 @@ const tools = computed(() => [ ...toolsByCategory.value, ]); +// ---- 全站 IPv6 切换(公网入口 it.88531.cn ⇄ itv6.88531.cn:4443) ---- +const V6_HOST = 'itv6.88531.cn'; +const V6_PORT = 4443; +const onV6Host = ref(location.hostname === V6_HOST); +const onPublicHost = ['it.88531.cn', V6_HOST].includes(location.hostname); +const v6ok = ref(false); +const v6Switching = ref(false); + +async function probeV6() { + // 结果缓存 10 分钟,避免每次开页都探测 + try { + const c = JSON.parse(localStorage.getItem('it_v6_probe') || 'null'); + if (c && typeof c.ok === 'boolean' && Date.now() - (c.ts || 0) < 600000) { + v6ok.value = c.ok; + return; + } + } + catch { /* 探测 */ } + let ok = false; + try { + const ctl = new AbortController(); + const timer = setTimeout(() => ctl.abort(), 4000); + // api6.ipify.org 仅 AAAA:能连通即说明本机有 IPv6 出口 + const r = await fetch('https://api6.ipify.org?format=json', { signal: ctl.signal, cache: 'no-store' }); + clearTimeout(timer); + const j = await r.json(); + ok = typeof j?.ip === 'string' && j.ip.includes(':'); + } + catch { ok = false; } + v6ok.value = ok; + try { localStorage.setItem('it_v6_probe', JSON.stringify({ ok, ts: Date.now() })); } + catch { /* ignore */ } +} + +function switchV6() { + if (v6Switching.value) { + return; + } + v6Switching.value = true; + const path = location.pathname + location.search + location.hash; + location.href = onV6Host.value + ? `https://it.88531.cn${path}` + : `https://${V6_HOST}:${V6_PORT}${path}`; +} + // 右下角回到顶部火箭 const showTop = ref(false); // 页面可能有多层 .n-layout-scroll-container(嵌套 n-layout),外层往往不滚、内层才滚; @@ -70,6 +115,9 @@ function bindTopScroll() { }); } onMounted(() => { + if (onPublicHost) { + probeV6().catch(() => {}); + } // 等布局渲染后再绑定滚动容器(内层容器可能晚于挂载出现,多试几次) let tries = 0; const timer = setInterval(() => { @@ -157,6 +205,24 @@ onBeforeUnmount(() => { + + + + + + + +
@@ -282,6 +348,27 @@ onBeforeUnmount(() => { } // 顶部导航:滚动时固定在最顶部(sticky),通栏贴顶遮挡滚动内容 +.v6-switch { + // 顶栏内正常排版(紧跟「授权应用」之后),不悬浮、不遮挡 + font-size: 13px; + white-space: nowrap; + flex-shrink: 0; +} + +@media (max-width: 900px) { + // 窄屏顶栏放不下完整文字时收缩为纯图标,并收紧间距,避免溢出右边缘 + .top-nav { + gap: 4px; + } + .v6-switch { + .v6-text { + display: none; + } + padding-left: 8px; + padding-right: 8px; + } +} + .top-nav { position: sticky; // -26px 抵消滚动容器 padding-top 内缩,使导航真正贴到视口最顶(0) diff --git a/src/pages/About.vue b/src/pages/About.vue index edbb13d..6e12415 100644 --- a/src/pages/About.vue +++ b/src/pages/About.vue @@ -35,7 +35,7 @@ const groups: { title: string; items: Item[] }[] = [ { title: '原创工具', items: [ - { name: '本机IP查询', icon: '网', desc: '仅显示你设备的公网IPv4/IPv6地址与所属地(多源容错+中文归属地+一键复制),代理/VPN检测(出口IP归属判定+WebRTC泄漏实测+内网IP),IPv6不支持时明示并给出开启教程,本站已支持IPv6直连(速度更快),网速测试为你的设备↔本站服务器真实收发计时并自动记录历史,进入页面自动测9个热门地点延迟', tag: '全新' }, + { name: '本机IP查询', icon: '网', desc: '仅显示你设备的公网IPv4/IPv6地址与所属地(多源容错+中文归属地+一键复制),代理/VPN检测(出口IP归属判定+WebRTC泄漏实测+内网IP),热门地点延迟实测(百度、本省运营商门户按归属自动匹配、全国镜像站+海外节点),测速历史自动记录各地点延迟快照(跨线路/跨时间对照),IPv6不支持时明示并给出开启教程,本站已支持IPv6直连(速度更快),网速测试为你的设备↔本站服务器真实收发计时', tag: '全新' }, { name: 'Base64图片互转', icon: 'B', desc: 'Base64转图片与图片转Base64合一页双 Tab:三种输入形态(裸串/data:URI/CSS url())自动识别、图片类型魔数嗅探、输出三档格式实时切换、互转按钮带结果闭环跳转,纯浏览器本地不上传', tag: '全新' }, { name: '批量条码生成', icon: '条', desc: 'EAN/UPC/Code128/Code39/DataMatrix 等 12 种码制,批量生成、打包下载,尺寸颜色字号可调', tag: '全新' }, { name: '二维码条码识别与生成', icon: '扫', desc: '识别:上传/拖拽/粘贴一键解码(多码混合批量输出,本地 WASM 不上传);生成:自定义前景/背景颜色、中间插入本地 Logo 图片,生成后自动自扫验证可下载 PNG', tag: '全新' }, diff --git a/src/tools/my-ip/my-ip.vue b/src/tools/my-ip/my-ip.vue index a75424e..6b49915 100644 --- a/src/tools/my-ip/my-ip.vue +++ b/src/tools/my-ip/my-ip.vue @@ -99,6 +99,7 @@ async function loadIps() { v4Geo.value = g4; v6Geo.value = g6; ipLoading.value = false; + ensureIspNode(); // 归属运营商已知 → 插入「本省运营商门户」延迟节点并补测 // 拿到地址后并行做代理/VPN 检测(不阻塞主卡片) runProxyCheck(); rtcProbe(); @@ -237,10 +238,11 @@ async function copyIp(text: string, key: string) { } // ---------- 热门地点延迟(你的浏览器到各地点的实测延迟) ---------- -type LatNode = { name: string; url: string; ms: number | null; st: 'wait' | 'run' | 'ok' | 'fail' }; +type LatNode = { name: string; url: string; ms: number | null; st: 'wait' | 'run' | 'ok' | 'fail'; note?: string }; const latTesting = ref(false); const nodes = ref([ { name: '本站服务器', url: `${location.origin}/favicon.ico`, ms: null, st: 'wait' }, + { name: '百度', url: 'https://www.baidu.com/favicon.ico', ms: null, st: 'wait' }, { name: '清华 TUNA(北京)', url: 'https://mirrors.tuna.tsinghua.edu.cn/', ms: null, st: 'wait' }, { name: '阿里云镜像(杭州)', url: 'https://mirrors.aliyun.com/', ms: null, st: 'wait' }, { name: '腾讯云镜像(广州)', url: 'https://mirrors.cloud.tencent.com/', ms: null, st: 'wait' }, @@ -251,6 +253,33 @@ const nodes = ref([ { name: 'Cloudflare(海外)', url: 'https://speed.cloudflare.com/__down?bytes=0', ms: null, st: 'wait' }, ]); +// 按用户 IPv4 归属运营商动态插入「本省运营商门户」节点(三大运营商+广电,无匹配则不插) +function ensureIspNode() { + if (nodes.value.some((n) => n.name.startsWith('本省'))) return; + const g = v4Geo.value; + const isp = `${g?.isp || ''} ${g?.as || ''}`; + const province = g?.regionName || ''; + let portal = ''; + let short = ''; + if (/联通|Unicom/i.test(isp)) { + portal = 'https://www.10010.com/favicon.ico'; // favicon 直链无 302;首页会被风控挂到超时 + short = '联通'; + } else if (/电信|Telecom/i.test(isp)) { + portal = 'https://www.189.cn/favicon.ico'; + short = '电信'; + } else if (/移动|Mobile|铁通|Tietong/i.test(isp)) { + portal = 'https://www.10086.cn/'; // 移动 favicon 不可达,用首页(200 稳定) + short = '移动'; + } else if (/广电|Broadnet/i.test(isp)) { + portal = 'https://www.10099.com.cn/favicon.ico'; + short = '广电'; + } + if (!portal) return; // 未知运营商(教育网/长城等)不插行 + const node: LatNode = { name: `本省·${short}`, url: portal, ms: null, st: 'wait', note: province ? `${g?.isp || short} · ${province}` : (g?.isp || '') }; + nodes.value.splice(1, 0, node); + ping(node); // 其余节点已在测,单独补测这一项 +} + const latSummary = computed(() => { const ok = nodes.value.filter((n) => n.st === 'ok' && n.ms != null); if (!ok.length) return ''; @@ -422,6 +451,7 @@ interface SpeedRec { ms: number; // 到本站延迟 route: 'IPv6 直连' | '公网中转'; // 测试时所走线路 host: string; // 测试时的访问域名 + lat?: string; // 测速时点的热门地点延迟快照:"百度5 本省联通6 清华12 …"(空串=当时未测完) } const speedHistory = ref([]); @@ -444,6 +474,14 @@ function saveSpeedHistory() { } } +// 把当前热门地点延迟压成短串快照(写入历史记录):"百度5 本省联通6 清华12 …" +function latSnapshot(): string { + return nodes.value + .filter((n) => n.st === 'ok' && n.ms != null) + .map((n) => `${n.name.replace(/([^)]*)/g, '').replace(/[\s·]/g, '')}${n.ms}`) + .join(' '); +} + function pushSpeedRec() { speedHistory.value.unshift({ t: Date.now(), @@ -452,6 +490,7 @@ function pushSpeedRec() { ms: serverMs.value ?? 0, route: onV6Host ? 'IPv6 直连' : '公网中转', host: location.host, + lat: latSnapshot(), }); speedHistory.value = speedHistory.value.slice(0, 20); saveSpeedHistory(); @@ -606,6 +645,7 @@ onMounted(() => { 下载 Mbps 上传 Mbps 延迟 ms + 热门地点延迟快照
{{ fmtTime(r.t) }} @@ -613,9 +653,10 @@ onMounted(() => { {{ r.down }} {{ r.up }} {{ r.ms }} + {{ r.lat || '—' }}
-
对比方法:在当前线路测一次 → 点横幅「切换 IPv6 直连」再测一次,两条线路的下载/上传/延迟直接在表里对照。
+
对比方法:在当前线路测一次 → 点横幅「切换 IPv6 直连」再测一次,下载/上传/延迟与各地点(百度/本省运营商/镜像站等)延迟直接在表里对照。
@@ -676,7 +717,7 @@ onMounted(() => {
- {{ n.name }} + {{ n.name }} {{ n.st === 'run' ? '测速中…' : n.st === 'fail' ? '超时' : n.st === 'ok' ? `${n.ms} ms` : '待测' }} @@ -1140,7 +1181,7 @@ onMounted(() => { .sp-hrow { display: grid; - grid-template-columns: 1.1fr 1.1fr 1fr 1fr 0.9fr; + grid-template-columns: 1.1fr 1.1fr 1fr 1fr 0.9fr 2.4fr; gap: 6px; padding: 6px 4px; align-items: center; @@ -1208,8 +1249,16 @@ onMounted(() => { } } .sp-hist-table .sp-hrow { - grid-template-columns: 1fr 1fr 1fr 1fr 0.8fr; + grid-template-columns: 0.9fr 1fr 0.8fr 0.8fr 0.7fr 2.6fr; font-size: 12.5px; } + + .sp-hist-table .c-lat { + font-family: monospace; + font-size: 11.5px; + opacity: 0.85; + line-height: 1.6; + word-break: break-all; + } }