from fastapi import FastAPI, HTTPException from fastapi.responses import HTMLResponse import sys import subprocess import yaml import os app = FastAPI() # 读取配置文件 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(BASE_DIR,"config/config.yaml"), "r", encoding="utf-8") as f: config = yaml.safe_load(f) PROJECT_DEFAULTS = { "JMJD01": { "lat": 22.555907, "lon": 113.135232, "capacity": 4050, }, "YUWEI": { "lat": 22.615142, "lon": 110.305066, "capacity": 3000, }, "ZHONGXIN": { "lat": 23.542156, "lon": 112.996233, "capacity": 2250, }, } API_HOME_PATH = os.path.join(BASE_DIR, "templates", "api_home.html") @app.get("/", response_class=HTMLResponse) def root(): with open(API_HOME_PATH, "r", encoding="utf-8") as f: return f.read() @app.get("/api/v1/power/short") def create_prediction( projs:str = 'JMJD01', init_time: str = "2026-11-25 08:00:00" ): if projs not in PROJECT_DEFAULTS: raise HTTPException( status_code=400, detail=f"不支持的场站代码: {projs}", ) cmd = [ sys.executable, config['model']['short_algorithm_file'], "--projs", projs , "--model_name", 'GRU', "--release", 'v24', "--lat", str(PROJECT_DEFAULTS[f'{projs}']['lat']), "--lon", str(PROJECT_DEFAULTS[f'{projs}']['lon']), "--short_term_seq", "288", "--medium_term_seq", "960", "--capacity", str(PROJECT_DEFAULTS[f'{projs}']['capacity']), "--saved_model_root", config['model']['saved_model_root'], "--saved_result_root", "-", "--init_time", init_time, ] result = subprocess.run( cmd, cwd=BASE_DIR, capture_output=True, text=True, ) if result.returncode != 0: raise HTTPException( status_code=500, detail={ "message": "预测失败", "return_code": result.returncode, "stdout": result.stdout, "stderr": result.stderr, }, ) return { "success": True, "message": "预测完成", "return_code": result.returncode, "stdout": result.stdout, } @app.get("/api/v1/power/medium") def create_prediction( projs:str = 'JMJD01', init_time: str = "2026-11-25 08:00:00" ): if projs not in PROJECT_DEFAULTS: raise HTTPException( status_code=400, detail=f"不支持的场站代码: {projs}", ) cmd = [ sys.executable, config['model']['medium_algorithm_file'], "--projs", projs , "--model_name", 'GRU', "--release", 'v24', "--lat", str(PROJECT_DEFAULTS[f'{projs}']['lat']), "--lon", str(PROJECT_DEFAULTS[f'{projs}']['lon']), "--short_term_seq", "288", "--medium_term_seq", "960", "--capacity", str(PROJECT_DEFAULTS[f'{projs}']['capacity']), "--saved_model_root", config['model']['saved_model_root'], "--saved_result_root", "-", "--init_time", init_time, ] result = subprocess.run( cmd, cwd=BASE_DIR, capture_output=True, text=True, ) if result.returncode != 0: raise HTTPException( status_code=500, detail={ "message": "预测失败", "return_code": result.returncode, "stdout": result.stdout, "stderr": result.stderr, }, ) return { "success": True, "message": "预测完成", "return_code": result.returncode, "stdout": result.stdout, } if __name__ == "__main__": import uvicorn uvicorn.run( app, host=config['FastAPI']['host'], port=config['FastAPI']['port'] )