#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ VOSK 模型本地服务器 用于在局域网中提供模型文件下载服务 """ import http.server import socketserver import os import sys from urllib.parse import urlparse # 配置 PORT = 8080 MODEL_DIR = os.path.join(os.path.dirname(__file__), 'static') class CORSRequestHandler(http.server.SimpleHTTPRequestHandler): """支持 CORS 的 HTTP 请求处理器""" def end_headers(self): # 添加 CORS 头,允许跨域访问 self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type') self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate') super().end_headers() def do_OPTIONS(self): """处理 OPTIONS 预检请求""" self.send_response(200) self.end_headers() def log_message(self, format, *args): """自定义日志输出""" print(f"[{self.log_date_time_string()}] {format % args}") def get_local_ip(): """获取本机局域网 IP 地址""" import socket try: # 连接到一个远程地址来获取本机 IP s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip except Exception: return "127.0.0.1" def main(): # 切换到模型文件目录 if not os.path.exists(MODEL_DIR): print(f"错误:模型目录不存在: {MODEL_DIR}") print(f"请确保 static 目录存在,并且包含 vosk-model-small-cn-0.22.zip 文件") sys.exit(1) os.chdir(MODEL_DIR) # 检查模型文件是否存在 model_file = os.path.join(MODEL_DIR, 'vosk-model-small-cn-0.22.zip') if not os.path.exists(model_file): print(f"警告:模型文件不存在: {model_file}") print("服务器仍会启动,但可能无法下载模型文件") # 启动服务器 try: with socketserver.TCPServer(("", PORT), CORSRequestHandler) as httpd: local_ip = get_local_ip() print("=" * 60) print("VOSK 模型服务器已启动") print("=" * 60) print(f"本地访问: http://localhost:{PORT}/vosk-model-small-cn-0.22.zip") print(f"局域网访问: http://{local_ip}:{PORT}/vosk-model-small-cn-0.22.zip") print("=" * 60) print("在 APP 中配置服务器地址为上述局域网地址") print("按 Ctrl+C 停止服务器") print("=" * 60) httpd.serve_forever() except KeyboardInterrupt: print("\n服务器已停止") except OSError as e: if e.errno == 98 or e.errno == 48: # Address already in use print(f"错误:端口 {PORT} 已被占用") print(f"请修改 PORT 变量或关闭占用该端口的程序") else: print(f"错误:{e}") sys.exit(1) if __name__ == "__main__": main()