声明
本文章中所有内容仅供学习交流使用,不用于其他任何目的,抓包内容、敏感网址、数据接口 等均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关!
有相关问题请第一时间点击头像看简介或私信联系我删除博客!
部分python
# ==================== 翻译 ====================
def translate(query: str, from_lang: str = "auto", to_lang: str = "zh", verbose=True) -> str:
ts = str(int(time.time()))
body = {
**BODY_STATIC,
"timestamp": ts,
"query": query,
"from": from_lang,
"to": to_lang,
}
body["sign"] = make_sign({**URL_PARAMS, **body}, ts)
if verbose:
print(f"[query] {query}\n[ts] {ts}\n[sign] {body['sign']}")
resp = requests.post(URL, params=URL_PARAMS, headers=HEADERS,
data=body, stream=True, timeout=30)
ct = (resp.headers.get("Content-Type") or "").lower()
if verbose:
print(f"[resp] {resp.status_code} | {ct}")
if "text/event-stream" not in ct:
raise RuntimeError(f"非 SSE: {resp.text}")
final_text, last_event = "", ""
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
if line.startswith("event:"):
last_event = line[6:].strip()
continue
if not line.startswith("data:"):
continue
try:
obj = json.loads(line[5:].strip())
except Exception:
continue
d = obj.get("data") or {}
ev = d.get("event") or last_event
reply = d.get("reply")
if verbose and reply is not None:
print(f" <{ev}> {reply}")
if reply and ev in ("OnIntermediateResult", "OnTransUnitCompleted", "OnEventCompleted"):
final_text = reply
return final_text
if __name__ == "__main__":
print(translate("hello", from_lang="zh", to_lang="en"))
print("-----")
print(translate("hello world", from_lang="en", to_lang="zh"))