Fu01978 commited on
Commit
9ec034b
·
verified ·
1 Parent(s): d1dfac7

Upload app (3).py

Browse files
Files changed (1) hide show
  1. app (3).py +77 -0
app (3).py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, Response, jsonify, stream_with_context
2
+ import json
3
+ import queue
4
+ import threading
5
+ import uuid
6
+
7
+ from analyzer import analyze_game
8
+
9
+ app = Flask(__name__)
10
+
11
+ # In-memory job store (fine for a local tool)
12
+ _jobs: dict[str, dict] = {}
13
+
14
+
15
+ @app.route("/")
16
+ def index():
17
+ return render_template("index.html")
18
+
19
+
20
+ @app.route("/api/analyze", methods=["POST"])
21
+ def submit():
22
+ """Accept a PGN + depth, queue the job, return a job_id."""
23
+ data = request.get_json(force=True)
24
+ pgn = data.get("pgn", "").strip()
25
+ depth = max(6, min(int(data.get("depth", 12)), 24))
26
+
27
+ if not pgn:
28
+ return jsonify({"error": "No PGN provided"}), 400
29
+
30
+ job_id = str(uuid.uuid4())
31
+ _jobs[job_id] = {"pgn": pgn, "depth": depth}
32
+ return jsonify({"job_id": job_id})
33
+
34
+
35
+ @app.route("/api/stream/<job_id>")
36
+ def stream(job_id: str):
37
+ """SSE stream: progress updates followed by the complete result."""
38
+ job = _jobs.pop(job_id, None)
39
+ if not job:
40
+ return "Job not found", 404
41
+
42
+ pgn = job["pgn"]
43
+ depth = job["depth"]
44
+ q: queue.Queue = queue.Queue()
45
+
46
+ def run():
47
+ def cb(evt):
48
+ q.put(evt)
49
+ try:
50
+ analyze_game(pgn, depth, cb)
51
+ except Exception as exc:
52
+ q.put({"type": "error", "message": str(exc)})
53
+ finally:
54
+ q.put(None) # sentinel
55
+
56
+ threading.Thread(target=run, daemon=True).start()
57
+
58
+ def generate():
59
+ while True:
60
+ item = q.get()
61
+ if item is None:
62
+ break
63
+ yield f"data: {json.dumps(item)}\n\n"
64
+
65
+ return Response(
66
+ stream_with_context(generate()),
67
+ mimetype="text/event-stream",
68
+ headers={
69
+ "Cache-Control": "no-cache",
70
+ "X-Accel-Buffering": "no",
71
+ "Connection": "keep-alive",
72
+ },
73
+ )
74
+
75
+
76
+ if __name__ == "__main__":
77
+ app.run(debug=True, threaded=True)