feat(python-subprocess): 尝试字幕显示新解决方案

- 使用 python 子进程解析字幕
- 通过 websocket 通信将字幕传递给软件
This commit is contained in:
himeditator
2025-06-15 12:43:57 +08:00
parent f10530eb67
commit 8858189bf6
18 changed files with 572 additions and 64 deletions

View File

@@ -0,0 +1,66 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "4604aefd",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Received: {\"message\":\"Electron Initialized\"}\n",
"Received: {\"command\":\"process_data\",\"payload\":{\"some\":\"data\"}}\n",
"Client disconnected\n",
"Received: {\"message\":\"Electron Initialized\"}\n",
"Received: {\"command\":\"process_data\",\"payload\":{\"some\":\"data\"}}\n",
"Client disconnected\n"
]
}
],
"source": [
"import asyncio\n",
"import websockets\n",
"import nest_asyncio\n",
"\n",
"# 应用补丁,允许在 Jupyter 中运行嵌套事件循环\n",
"nest_asyncio.apply()\n",
"\n",
"async def handle_client(websocket, path=\"/\"):\n",
" try:\n",
" async for message in websocket:\n",
" print(f\"Received: {message}\")\n",
" await websocket.send(f\"Echo: {message}\")\n",
" except websockets.exceptions.ConnectionClosed:\n",
" print(\"Client disconnected\")\n",
"\n",
"start_server = websockets.serve(handle_client, \"localhost\", 8765)\n",
"\n",
"asyncio.get_event_loop().run_until_complete(start_server)\n",
"asyncio.get_event_loop().run_forever()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "mystd",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -0,0 +1,21 @@
import asyncio
import websockets
import json # 导入 json 模块
# WebSocket 服务器处理函数
async def echo(websocket):
async for message in websocket:
print(f"收到客户端消息: {message}")
# 发送响应给客户端
response = {"respond": "Hello, Client!"}
await websocket.send(json.dumps(response)) # 将字典转换为 JSON 字符串
print(f"已发送响应: {response}")
# 启动服务器
async def main():
async with websockets.serve(echo, "localhost", 8765):
await asyncio.Future() # 保持服务器运行
if __name__ == "__main__":
print("WebSocket 服务器已启动,监听 ws://localhost:8765")
asyncio.run(main())