Spaces:
Running
Running
import os | |
import shutil | |
from pathlib import Path | |
from flask import Flask, render_template, send_file | |
from update_predictions import Config as up_Config, main_task, get_business_info | |
app = Flask(__name__) | |
# 确保与update_predictions.py共享配置 | |
Config = up_Config | |
# 确保模板目录存在 | |
def initialize_html_template(): | |
# 创建templates目录(如果不存在) | |
template_dir = Path(__file__).parent / "templates" | |
template_dir.mkdir(parents=True, exist_ok=True) | |
# 目标模板路径 | |
dest_html = template_dir / "index.html" | |
# 如果模板不存在,创建基础模板 | |
if not dest_html.exists(): | |
base_html = """ | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>清华大学Kronos股票K型大模型上证指数预测</title> | |
<style> | |
body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; } | |
.metric { margin: 20px 0; padding: 10px; background: #f5f5f5; border-radius: 5px; } | |
.metric-label { font-weight: bold; color: #333; } | |
.metric-value { font-size: 1.5em; color: #2c3e50; } | |
#chart-container { margin-top: 30px; } | |
img { max-width: 100%; height: auto; } | |
</style> | |
</head> | |
<body> | |
<h1>清华大学Kronos股票K型大模型上证指数概率预测</h1> | |
<p>最后更新时间:<strong>{{ update_time }}</strong>(UTC)</p> | |
<p>同 步 网 站:<strong><a href="http://15115656.top" target="_blank">火狼工具站</a></strong></p> | |
<div class="metric"> | |
<p class="metric-label">24个交易日上涨概率:</p> | |
<p class="metric-value">{{ upside_prob }}%</p> | |
</div> | |
<div class="metric"> | |
<p class="metric-label">波动率放大概率:</p> | |
<p class="metric-value">{{ vol_amp_prob }}%</p> | |
</div> | |
<div id="chart-container"> | |
<img src="/prediction_chart.png" alt="上证指数预测图表"> | |
</div> | |
</body> | |
</html> | |
""" | |
with open(dest_html, 'w', encoding='utf-8') as f: | |
f.write(base_html) | |
print(f"已创建基础模板文件:{dest_html}") | |
# 初始化模型(全局一次) | |
from update_predictions import load_local_model as load_model | |
predictor = load_model() | |
# 初始化HTML模板 | |
initialize_html_template() | |
def index(): | |
# 获取当前业务日 | |
current_business_date, _ = get_business_info() | |
# 容错处理:检查配置键是否存在,不存在则执行主任务 | |
if ("LAST_INFERENCED_BUSINESS_DATE" not in Config | |
or Config["LAST_INFERENCED_BUSINESS_DATE"] != current_business_date): | |
main_task(predictor) | |
# 从配置中获取需要显示的数据 | |
update_time = Config.get("update_time", "未更新") | |
upside_prob = Config.get("upside_prob", "--") | |
vol_amp_prob = Config.get("vol_amp_prob", "--") | |
# 使用Jinja2模板渲染数据 | |
return render_template("index.html", | |
update_time=update_time, | |
upside_prob=upside_prob, | |
vol_amp_prob=vol_amp_prob) | |
def get_chart(): | |
# 提供图表访问 | |
chart_path = Path(Config["CHART_PATH"]) | |
if chart_path.exists(): | |
return send_file(chart_path, mimetype='image/png') | |
else: | |
return "预测图表生成中,请稍后刷新", 202 | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=7860) | |