Zebra / backend /app.py
guoj5's picture
Add application file
8e80adf
raw
history blame
2.62 kB
# app.py
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import os
from puzzle_dataset import get_puzzle_by_index
from solver import solve_puzzle
app = Flask(__name__)
CORS(app) # 如果前后端分开端口,可能需要 CORS
# 读取 Example.txt 作为默认 sys_content(若用户没给就用默认)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
example_path = os.path.join(BASE_DIR, "Example.txt")
with open(example_path, "r", encoding="utf-8") as f:
DEFAULT_SYS_CONTENT = f.read()
app = Flask(__name__, static_folder='static', static_url_path='')
@app.route('/')
def index():
# 返回静态文件夹下编译好的 index.html
return send_from_directory(app.static_folder, 'index.html')
@app.route("/get_puzzle", methods=["GET"])
def get_puzzle():
"""
前端通过 query param ?index=xxx 获取 puzzle 内容和 expected_solution
"""
idx_str = request.args.get("index", "0")
try:
idx = int(idx_str)
except ValueError:
return jsonify({"success": False, "error": "Index must be an integer"}), 400
puzzle, solution = get_puzzle_by_index(idx)
if puzzle is None or solution is None:
return jsonify({"success": False, "error": "Invalid puzzle index"}), 404
return jsonify({
"success": True,
"index": idx,
"puzzle": puzzle,
"expected_solution": solution
})
@app.route("/solve", methods=["POST"])
def solve():
"""
前端 POST { index, puzzle, expected_solution, sysContent }
调用 solve_puzzle,并返回比对结果和执行的 python code
"""
data = request.get_json()
puzzle_index = data.get("index")
puzzle_text = data.get("puzzle")
expected_solution = data.get("expected_solution")
sys_content = data.get("sys_content", DEFAULT_SYS_CONTENT)
if puzzle_index is None or puzzle_text is None or expected_solution is None:
return jsonify({"success": False, "error": "Missing puzzle data"}), 400
result = solve_puzzle(puzzle_index, puzzle_text, expected_solution, sys_content)
# result 里包含: success, solution, attempts, generatedCode, modelResponse, etc.
return jsonify({
"success": True,
"result": result
})
@app.route("/default_sys_content", methods=["GET"])
def get_default_sys_content():
"""
返回默认的 sys_content (Example.txt) 给前端展示或编辑
"""
return jsonify({
"success": True,
"sysContent": DEFAULT_SYS_CONTENT
})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=False)