ibook / app.py
zhangl
Refactor index.html, README.md, and style.css for interactive English learning app. Updated HTML structure, added navigation and control features, enhanced styling, and improved documentation in README.
c7e7ea8
Raw
History Blame Contribute Delete
2.74 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
交互式英语学习应用 - Hugging Face Spaces Docker部署版本
在7860端口提供HTTP服务
"""
import http.server
import socketserver
import os
import sys
import threading
import time
class CORSHTTPRequestHandler(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')
self.send_header('Pragma', 'no-cache')
self.send_header('Expires', '0')
super().end_headers()
def do_OPTIONS(self):
# 处理预检请求
self.send_response(200)
self.end_headers()
def log_message(self, format, *args):
# 自定义日志格式
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
client_ip = self.address_string()
print(f"[{timestamp}] {client_ip} - {format % args}")
def check_required_files():
"""检查必要文件是否存在"""
required_files = ['index.html', 'style.css', 'script.js', 'book_104.json', 'FZKT_GBK.woff']
missing_files = []
for file in required_files:
if not os.path.exists(file):
missing_files.append(file)
if missing_files:
print(f"❌ 缺少必要文件: {', '.join(missing_files)}")
return False
print("✅ 所有必要文件检查完成")
return True
def main():
"""主函数 - 在7860端口启动HTTP服务器"""
print("🚀 交互式英语学习应用 - Hugging Face Spaces")
print("=" * 60)
# 检查必要文件
if not check_required_files():
return 1
# Hugging Face Spaces要求监听7860端口
port = int(os.environ.get('PORT', 7860))
try:
# 创建服务器
with socketserver.TCPServer(("0.0.0.0", port), CORSHTTPRequestHandler) as httpd:
print(f"📱 服务器启动成功")
print(f"🌐 监听端口: {port}")
print(f"📁 工作目录: {os.getcwd()}")
print("=" * 60)
print("🎉 应用已准备就绪!")
print("=" * 60)
# 启动服务器
httpd.serve_forever()
except KeyboardInterrupt:
print("\n\n🛑 服务器已停止")
return 0
except Exception as e:
print(f"❌ 服务器启动失败: {e}")
return 1
if __name__ == "__main__":
sys.exit(main())