#!/usr/bin/env python3 """Linghang SD video client: explicit paid submit, resumable polling/download.""" import argparse import json import os from pathlib import Path import re import sys import time from urllib.error import HTTPError, URLError from urllib.parse import quote, urljoin, urlsplit from urllib.request import HTTPRedirectHandler, Request, build_opener BASE = "https://api.tianjinlinghang.com" class SafeRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): if req.get_method() != "GET": raise RuntimeError("提交接口重定向;停止,未自动重发。") nxt = super().redirect_request(req, fp, code, msg, headers, newurl) if nxt is not None: nxt.remove_header("Authorization") return nxt OPENER = build_opener(SafeRedirect()) class APIError(RuntimeError): def __init__(self, status, message, code, request_id): self.details = {"http_status": status, "message": message, "code": code, "request_id": request_id} super().__init__(f"HTTP {status} [{code or 'api_error'}]: {message}" + (f";请求编号 {request_id}" if request_id else "")) def redact_error(value, key): text = str(value or "") if key: text = text.replace(key, "[REDACTED]") if key.startswith("sk-"): text = text.replace(key[3:], "[REDACTED]") text = re.sub(r"(?i)Bearer\s+[^\s\"'<>]+|sk-[A-Za-z0-9_-]+", "[REDACTED]", text) text = re.sub(r"https?://[^\s\"'<>]+", "[URL]", text) return text[:1500] def read_key(path): data = Path(path).read_text(encoding="utf-8-sig") keys = set(re.findall(r"(?m)^\s*(sk-[A-Za-z0-9_-]+)\s*$", data)) if len(keys) != 1 or "REPLACE" in next(iter(keys), ""): raise ValueError("TXT 必须包含唯一一行有效 sk-... 本站视频令牌。") return keys.pop() def api(key, path, payload=None): data = None if payload is None else json.dumps(payload, ensure_ascii=False).encode() headers = {"Content-Type": "application/json"} if key: headers["Authorization"] = "Bearer " + key req = Request(BASE + path, data=data, headers=headers) try: with OPENER.open(req, timeout=90 if payload is not None else 35) as response: return json.load(response) except HTTPError as exc: raw = exc.read(16384) exc.close() try: body = json.loads(raw) detail = body.get("error", body) if isinstance(body, dict) else {} if not isinstance(detail, dict): detail = {"message": detail} message = detail.get("message") or "接口未返回具体错误;请提供请求编号联系本站。" code = detail.get("code", "") except (ValueError, TypeError): message, code = "接口返回非 JSON 错误;请提供请求编号联系本站。", "" request_id = (exc.headers.get("X-Oneapi-Request-Id") or exc.headers.get("X-Request-Id") or "") if exc.headers else "" raise APIError(exc.code, redact_error(message, key), redact_error(code, key), redact_error(request_id, key)) from None except (URLError, TimeoutError): raise RuntimeError("网络超时或连接失败;未自动重发。若为 POST,结果未知,请先查本站任务记录。") from None def write_state(path, state): p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) temp = p.with_name(p.name + ".tmp") temp.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8") os.replace(temp, p) def result_url(data): for name in ("url", "video_url", "download_url", "output_url", "result_url", "final_url"): if isinstance(data.get(name), str) and data[name]: return data[name] video = data.get("video") return video.get("url") if isinstance(video, dict) else None def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--key-file", required=True) sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("models") sub.add_parser("pricing") submit = sub.add_parser("submit") submit.add_argument("--request", required=True) submit.add_argument("--state", required=True) submit.add_argument("--confirm-cost", action="store_true") wait = sub.add_parser("wait") wait.add_argument("--state", required=True) wait.add_argument("--timeout", type=int, default=3600) download = sub.add_parser("download") download.add_argument("--state", required=True) download.add_argument("--output", required=True) args = parser.parse_args() key = read_key(args.key_file) if args.command in ("models", "pricing"): data = api(key, "/v1/models") if args.command == "models" else api(None, "/docs/sd/pricing.json") if args.command == "pricing" and isinstance(data.get("data"), list): data["data"] = [x for x in data["data"] if "稳定seedance" in x.get("enable_groups", [])] print(json.dumps(data, ensure_ascii=False, indent=2)) return state_path = Path(args.state) if args.command == "submit": if not args.confirm_cost: raise ValueError("提交会产生费用;核对价格及用户授权后加 --confirm-cost。") payload = json.loads(Path(args.request).read_text(encoding="utf-8-sig")) if not payload.get("model") or not payload.get("prompt"): raise ValueError("request.json 必须包含 model 和 prompt。") state_path.parent.mkdir(parents=True, exist_ok=True) state = {"submission": "pending_or_unknown", "model": payload["model"], "created_at": int(time.time())} with state_path.open("x", encoding="utf-8") as f: json.dump(state, f, ensure_ascii=False) try: response = api(key, "/v1/videos", payload) except APIError as error: state["last_error"] = error.details write_state(state_path, state) raise tid = response.get("id") or response.get("task_id") if not isinstance(tid, str) or not tid: raise RuntimeError("未收到任务 ID;保留 state 文件,先查本站任务记录,不要自动重交。") state.update(task_id=tid, submission="accepted", response=response) write_state(state_path, state) print("已提交,task_id=" + tid) return state = json.loads(state_path.read_text(encoding="utf-8")) if not state.get("task_id"): raise ValueError("state 没有任务 ID;请先查本站任务记录核对提交结果。") if args.command == "wait": deadline = time.monotonic() + max(1, args.timeout) while time.monotonic() < deadline: response = api(key, "/v1/videos/" + quote(state["task_id"], safe="")) state["response"] = response write_state(state_path, state) status = response.get("status") print("status=" + str(status), flush=True) if status == "completed": print("任务完成;运行 download 保存成片。") return if status in ("failed", "cancelled"): raise RuntimeError("任务失败,详细错误保存在本地 state;请核对本站退款记录。") time.sleep(min(10, max(0, deadline-time.monotonic()))) raise RuntimeError("等待超时。任务未取消、未重新提交;稍后继续 wait。") response = state.get("response", {}) if response.get("status") != "completed": raise ValueError("请先 wait 到 completed。") url = result_url(response) if not url: raise ValueError("已完成但没有成片 URL;请保留任务 ID 联系客服。") url = urljoin(BASE, url) parts = urlsplit(url) if parts.scheme not in ("https", "http") or parts.username or parts.password: raise ValueError("成片链接协议不受支持。") headers = {} if parts.scheme == "https" and parts.netloc == urlsplit(BASE).netloc: headers["Authorization"] = "Bearer " + key output = Path(args.output) if output.exists(): raise ValueError("输出文件已存在,请指定新路径。") output.parent.mkdir(parents=True, exist_ok=True) partial = output.with_name(output.name + ".part") try: with partial.open("xb") as f, OPENER.open(Request(url, headers=headers), timeout=300) as r: if r.headers.get_content_type() in ("application/json", "text/html"): raise RuntimeError("下载结果不是视频") while True: chunk = r.read(1024*1024) if not chunk: break f.write(chunk) os.replace(partial, output) except Exception: raise RuntimeError("下载失败;保留任务 state,检查本地 .part 文件后重试。未重新生成。") from None print("已保存:" + str(output.resolve())) if __name__ == "__main__": try: main() except (ValueError, RuntimeError, OSError) as error: print(str(error), file=sys.stderr) sys.exit(1)