Repository navigation
Expand file tree
/
Copy pathpatch_frontend.py
More file actions
113 lines (92 loc) · 3.16 KB
/
Copy pathpatch_frontend.py
File metadata and controls
113 lines (92 loc) · 3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
前端优化补丁脚本
自动更新 api_server.py,将嵌入的 HTML 改为加载外部模板
"""
import re
from pathlib import Path
def patch_api_server():
"""为 api_server.py 应用前端优化补丁"""
api_file = Path(__file__).parent / "api_server.py"
if not api_file.exists():
print(f"❌ 找不到 {api_file}")
return False
with open(api_file, 'r', encoding='utf-8') as f:
content = f.read()
# 模式 1:替换根路由函数
root_route_pattern = r'@app\.get\("/", response_class=HTMLResponse\)\s+async def root\(\):.*?(?=\n@app\.)'
new_root_route = '''@app.get("/", response_class=HTMLResponse)
async def root():
"""返回Web界面"""
template_file = Path(__file__).parent / "templates" / "index.html"
if template_file.exists():
with open(template_file, 'r', encoding='utf-8') as f:
return f.read()
else:
# 备用方案
return """
<!DOCTYPE html>
<html>
<head><title>错误</title></head>
<body>
<h1>前端模板未找到</h1>
<p>请确保 templates/index.html 存在</p>
</body>
</html>
"""
'''
try:
# 使用 DOTALL 标志让 . 匹配换行符
content_new = re.sub(root_route_pattern, new_root_route, content, flags=re.DOTALL)
if content_new == content:
print("⚠️ 没有找到匹配的根路由函数")
return False
with open(api_file, 'w', encoding='utf-8') as f:
f.write(content_new)
print("✅ api_server.py 已更新")
print("✅ 根路由函数已改为加载外部模板")
return True
except Exception as e:
print(f"❌ 更新失败: {e}")
return False
def check_frontend_files():
"""检查前端文件是否存在"""
base_dir = Path(__file__).parent
required_files = [
"templates/index.html",
"static/css/style.css",
"static/js/main.js"
]
print("\n📋 检查前端文件...")
all_exist = True
for file_path in required_files:
full_path = base_dir / file_path
exists = full_path.exists()
status = "✅" if exists else "❌"
print(f" {status} {file_path}")
all_exist = all_exist and exists
return all_exist
def main():
print("=" * 60)
print("多模态数据分析系统 - 前端优化补丁")
print("=" * 60)
# 检查文件
if not check_frontend_files():
print("\n⚠️ 某些前端文件未找到,请确保所有文件已创建")
return False
# 应用补丁
print("\n🔧 应用补丁...")
if patch_api_server():
print("\n✨ 补丁应用成功!")
print("\n下一步:")
print("1. 启动 api_server.py: python api_server.py")
print("2. 访问 http://localhost:8000")
print("3. 享受新的前端界面!")
return True
else:
print("\n❌ 补丁应用失败")
return False
if __name__ == "__main__":
success = main()
exit(0 if success else 1)