-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
863 lines (731 loc) · 34.4 KB
/
Copy pathserver.py
File metadata and controls
863 lines (731 loc) · 34.4 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
"""Flask server for StrokeIndexr."""
from flask import Flask, request, jsonify, Response, send_from_directory
from database import (
init_db, insert_round, replace_round, find_duplicate,
get_rounds, get_round, delete_round,
update_notes, save_debrief, save_short_summary, set_handicap_excluded, set_notes_ai_excluded,
get_global_summary, save_global_summary,
get_latest_round_date, get_rounds_in_window,
get_stats_summary, get_trend_data,
get_courses, get_course, get_course_by_name, update_course_ratings,
get_rounds_for_course, get_all_rounds_with_course_ratings,
sync_courses, TEE_COLOURS,
get_courses_with_hierarchy, get_suggested_links,
link_courses, unlink_course,
load_config, save_config,
patch_round_fields, get_rounds_missing_fields,
)
from whs import current_index, index_history
from scraper import scrape_round
import prompts
import requests as _requests
import threading
import time
from version import __version__
app = Flask(__name__, static_folder="static", static_url_path="")
# ── Update check (cached) ─────────────────────────────────────────────────────
_update_cache = {"latest": None, "checked_at": 0}
_UPDATE_TTL = 6 * 3600 # 6 hours
_GITHUB_RELEASES = "https://api.github.com/repos/f0dders/strokeindexr/releases/latest"
def _backfill_missing_fields():
"""Silently fill in weather/tee_time for existing rounds that predate those features."""
from scraper import _fetch_weather
import json as _json
FIELDS = ["weather_temp_c", "tee_time"]
rounds = get_rounds_missing_fields(FIELDS)
if not rounds:
return
print(f" Backfilling {len(rounds)} round(s) with missing weather/tee-time data...")
for r in rounds:
try:
updates = {}
holes = _json.loads(r.get("holes_json") or "[]")
# Tee time
if not r.get("tee_time"):
from scraper import HEADERS as _H
import requests as _rq
from bs4 import BeautifulSoup as _BS
from datetime import datetime as _dt
resp = _rq.get(r["hole19_url"], headers=_H, timeout=15)
soup = _BS(resp.text, "html.parser")
for script in soup.find_all("script", {"type": "application/json"}):
if script.get("data-component-name") == "MyScorecard":
played = _json.loads(script.string).get("data", {}).get("played_date", "")
if played:
dt = _dt.fromisoformat(played.replace("Z", "+00:00"))
updates["tee_time"] = dt.astimezone().strftime("%H:%M")
break
# Weather
if not r.get("weather_temp_c") and holes:
h1 = holes[0]
lat = h1.get("hole_score", {}).get("tee_latitude")
lon = h1.get("hole_score", {}).get("tee_longitude")
date = r.get("date")
tee_time = updates.get("tee_time") or r.get("tee_time") or "08:00"
hour = int(tee_time.split(":")[0])
if lat and lon and date:
weather = _fetch_weather(lat, lon, date, hour)
updates.update(weather)
if updates:
patch_round_fields(r["id"], updates)
except Exception:
pass
print(" Backfill complete.")
def _fetch_latest_version():
try:
r = _requests.get(_GITHUB_RELEASES, timeout=5,
headers={"Accept": "application/vnd.github+json"})
if r.ok:
_update_cache["latest"] = r.json().get("tag_name")
except Exception:
pass
_update_cache["checked_at"] = time.time()
def _maybe_refresh():
if time.time() - _update_cache["checked_at"] > _UPDATE_TTL:
threading.Thread(target=_fetch_latest_version, daemon=True).start()
@app.route("/api/version", methods=["GET"])
def api_version():
_maybe_refresh()
latest = _update_cache["latest"]
update_available = bool(latest and latest != __version__)
return jsonify({
"local": __version__,
"latest": latest,
"update_available": update_available,
"release_url": "https://github.com/f0dders/strokeindexr/releases/latest",
})
# ── Static files ──────────────────────────────────────────────────────────────
@app.route("/")
def index():
return send_from_directory("static", "index.html")
# ── Rounds API ────────────────────────────────────────────────────────────────
@app.route("/api/rounds", methods=["GET"])
def api_get_rounds():
return jsonify(get_rounds())
@app.route("/api/rounds/<int:round_id>", methods=["GET"])
def api_get_round(round_id):
r = get_round(round_id)
if not r:
return jsonify({"error": "Not found"}), 404
return jsonify(r)
@app.route("/api/rounds/<int:round_id>", methods=["DELETE"])
def api_delete_round(round_id):
delete_round(round_id)
return jsonify({"ok": True})
@app.route("/api/rounds/<int:round_id>/notes", methods=["POST"])
def api_update_notes(round_id):
notes = request.json.get("notes", "")
update_notes(round_id, notes)
return jsonify({"ok": True})
@app.route("/api/import", methods=["POST"])
def api_import():
body = request.json or {}
url = body.get("url", "").strip()
overwrite = body.get("overwrite", False)
notes = body.get("notes", "").strip()
notes_ai_excluded = body.get("notes_ai_excluded", None)
if not url:
return jsonify({"error": "No URL provided"}), 400
if "hole19golf.com" not in url:
return jsonify({"error": "URL must be a Hole19 round URL"}), 400
try:
data = scrape_round(url)
# Apply global notes AI default — excluded=True when default is False
cfg = load_config()
if not overwrite:
data["notes_ai_excluded"] = 0 if cfg.get("notes_ai_default", True) else 1
# Per-import override takes precedence over global default
if notes_ai_excluded is not None:
data["notes_ai_excluded"] = 1 if notes_ai_excluded else 0
existing = find_duplicate(data)
if existing and not overwrite:
return jsonify({"duplicate": True, "existing": {
"id": existing["id"], "course": existing["course"],
"date": existing["date"], "score": existing["score"],
}}), 409
if existing and overwrite:
rid = replace_round(existing["id"], data)
else:
rid = insert_round(data)
if notes:
update_notes(rid, notes)
sync_courses()
course = get_course_by_name(data.get("course", ""))
return jsonify({"ok": True, "id": rid, "data": data, "course_id": course["id"] if course else None})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/import/email", methods=["POST"])
def api_import_email():
"""Parse a pasted Hole19 email. Uses structured parser first, AI as fallback."""
import json as _json, re as _re
from email_parser import parse_hole19_email
body = request.json or {}
text = body.get("text", "").strip()
overwrite = body.get("overwrite", False)
notes = body.get("notes", "").strip()
notes_ai_excluded = body.get("notes_ai_excluded", None)
if not text:
return jsonify({"error": "No email text provided"}), 400
# ── Primary: structured parser (instant, no API cost) ────────────────────
try:
data = parse_hole19_email(text)
method = "structured"
except Exception as parse_err:
# ── Fallback: AI extraction ───────────────────────────────────────────
try:
provider = _build_provider()
raw = "".join(provider.stream(prompts.parse_email(text)))
m = _re.search(r"```(?:json)?\s*(\{.*?\})\s*```", raw, _re.S)
if not m:
m = _re.search(r"(\{[^{}]{50,}\})", raw, _re.S)
if not m:
return jsonify({"error": f"Structured parser failed ({parse_err}) and AI could not extract data either"}), 422
data = _json.loads(m.group(1))
method = "ai"
except Exception as ai_err:
return jsonify({"error": f"Structured parse failed: {parse_err}. AI fallback failed: {ai_err}"}), 500
if not data.get("date") or not data.get("course"):
return jsonify({"error": "Could not extract date or course from email"}), 422
try:
cfg = load_config()
if not overwrite:
data["notes_ai_excluded"] = 0 if cfg.get("notes_ai_default", True) else 1
if notes_ai_excluded is not None:
data["notes_ai_excluded"] = 1 if notes_ai_excluded else 0
existing = find_duplicate(data)
if existing and not overwrite:
return jsonify({"duplicate": True, "existing": {
"id": existing["id"], "course": existing["course"],
"date": existing["date"], "score": existing["score"],
}}), 409
if existing and overwrite:
rid = replace_round(existing["id"], data)
else:
rid = insert_round(data)
if notes:
update_notes(rid, notes)
sync_courses()
course = get_course_by_name(data.get("course", ""))
return jsonify({"ok": True, "id": rid, "data": data, "method": method, "course_id": course["id"] if course else None})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ── Courses API ──────────────────────────────────────────────────────────────
@app.route("/api/courses/suggestions", methods=["GET"])
def api_course_suggestions():
return jsonify(get_suggested_links())
@app.route("/api/courses/link", methods=["POST"])
def api_link_courses():
body = request.json or {}
child_ids = body.get("child_ids", [])
parent_name = body.get("parent_name", "")
if not child_ids or not parent_name:
return jsonify({"error": "child_ids and parent_name required"}), 400
try:
parent_id = link_courses(child_ids, parent_name)
except ValueError as e:
return jsonify({"error": str(e)}), 400
return jsonify({"ok": True, "parent_id": parent_id})
@app.route("/api/courses/<int:course_id>/unlink", methods=["POST"])
def api_unlink_course(course_id):
unlink_course(course_id)
return jsonify({"ok": True})
@app.route("/api/courses", methods=["GET"])
def api_get_courses():
courses = get_courses_with_hierarchy()
# Annotate each with aggregate stats from rounds
import json as _json
def annotate(c):
own_rounds = get_rounds_for_course(c["name"])
child_rounds = []
for child in c.get("children", []):
child_rounds += get_rounds_for_course(child["name"])
rounds = own_rounds + child_rounds
c["has_own_rounds"] = len(own_rounds) > 0
scores_vs_par = [r["score_vs_par"] for r in rounds if r.get("score_vs_par") is not None]
c["times_played"] = len(rounds)
c["best_vs_par"] = min(scores_vs_par) if scores_vs_par else None
c["avg_vs_par"] = round(sum(scores_vs_par) / len(scores_vs_par), 1) if scores_vs_par else None
putts = [r["putts"] for r in rounds if r.get("putts") and not r.get("putts_unreliable")]
c["avg_putts"] = round(sum(putts) / len(putts), 1) if putts else None
gir = [r["gir_hit_pct"] for r in rounds if r.get("gir_hit_pct") is not None]
c["avg_gir"] = round(sum(gir) / len(gir), 1) if gir else None
fir = [r["fairway_hit_pct"] for r in rounds if r.get("fairway_hit_pct") is not None]
c["avg_fir"] = round(sum(fir) / len(fir), 1) if fir else None
return c
for c in courses:
annotate(c)
for child in c.get("children", []):
annotate(child)
return jsonify(courses)
@app.route("/api/courses/<int:course_id>", methods=["GET"])
def api_get_course(course_id):
from database import get_courses_with_hierarchy
c = get_course(course_id)
if not c:
return jsonify({"error": "Not found"}), 404
# Attach children if this is a parent course
all_courses = get_courses_with_hierarchy()
for entry in all_courses:
if entry["id"] == course_id:
c["children"] = entry.get("children", [])
break
else:
c["children"] = []
# Gather rounds: own rounds + all children's rounds
own_rounds = get_rounds_for_course(c["name"])
child_rounds = []
for child in c["children"]:
child["rounds"] = get_rounds_for_course(child["name"])
child["times_played"] = len(child["rounds"])
child_rounds += child["rounds"]
all_rounds = own_rounds + child_rounds
# Split by hole count for the breakdown
rounds_18 = [r for r in all_rounds if (r.get("holes") or 0) > 9]
rounds_9 = [r for r in all_rounds if (r.get("holes") or 0) <= 9]
rounds = all_rounds
# Per-hole averages: only meaningful for a single physical layout. A parent
# course's children may be different physical 9s (front/back), so "hole 1"
# would mean different things — restrict this to the course's own rounds.
per_hole_rounds = own_rounds if c["children"] else all_rounds
# Per-hole averages across all rounds that have holes_json
import json as _json
hole_totals = {} # seq -> {strokes, putts, gir_hits, gir_total, fir_hits, fir_total, count}
for r in per_hole_rounds:
if not r.get("holes_json"):
continue
try:
holes = _json.loads(r["holes_json"])
except Exception:
continue
for h in holes:
seq = h.get("sequence")
hs = h.get("hole_score", {})
ht = h.get("hole_tee", {})
if seq is None:
continue
if seq not in hole_totals:
hole_totals[seq] = {"par": ht.get("par"), "strokes": 0, "putts": 0,
"gir_hits": 0, "gir_total": 0,
"fir_hits": 0, "fir_total": 0, "count": 0}
t = hole_totals[seq]
t["strokes"] += hs.get("total_of_strokes") or 0
t["putts"] += hs.get("total_of_putts") or 0
t["count"] += 1
if hs.get("green_in_regulation") is not None:
t["gir_total"] += 1
if hs["green_in_regulation"]:
t["gir_hits"] += 1
par = ht.get("par", 4)
if par >= 4 and hs.get("fairway_hit") is not None:
t["fir_total"] += 1
if hs["fairway_hit"] in ("target", "center"):
t["fir_hits"] += 1
per_hole = []
for seq in sorted(hole_totals):
t = hole_totals[seq]
n = t["count"]
per_hole.append({
"hole": seq,
"par": t["par"],
"avg_score": round(t["strokes"] / n, 2) if n else None,
"avg_putts": round(t["putts"] / n, 2) if n else None,
"gir_pct": round(t["gir_hits"] / t["gir_total"] * 100, 1) if t["gir_total"] else None,
"fir_pct": round(t["fir_hits"] / t["fir_total"] * 100, 1) if t["fir_total"] else None,
"rounds": n,
})
return jsonify({
**c,
"rounds": rounds,
"rounds_18": rounds_18,
"rounds_9": rounds_9,
"per_hole": per_hole,
})
@app.route("/api/courses/<int:course_id>/ratings-status", methods=["GET"])
def api_course_ratings_status(course_id):
"""Return whether a course has CR/Slope stored for a given tee and hole count."""
tee = request.args.get("tee", "yellow").lower()
holes = int(request.args.get("holes", 18))
suffix = "9" if holes <= 9 else "18"
c = get_course(course_id)
if not c:
return jsonify({"error": "Course not found"}), 404
cr_key = f"{tee}_cr_{suffix}"
slope_key = f"{tee}_slope_{suffix}"
has = bool(c.get(cr_key) and c.get(slope_key))
return jsonify({
"has_ratings": has,
"cr": c.get(cr_key),
"slope": c.get(slope_key),
})
@app.route("/api/courses/ai-lookup-ratings", methods=["POST"])
def api_ai_lookup_ratings():
"""Ask the configured AI provider for CR/Slope for a course + tee + holes."""
body = request.json or {}
course = body.get("course", "").strip()
tee_colour = body.get("tee_colour", "Yellow")
holes = int(body.get("holes", 18))
if not course:
return jsonify({"error": "course name required"}), 400
try:
provider = _build_provider()
except Exception as e:
return jsonify({"error": f"AI not configured: {e}"}), 503
hole_str = "9-hole" if holes <= 9 else "18-hole"
prompt = (
f"I need the official WHS Course Rating (CR) and Slope Rating for the {tee_colour} tees "
f"at {course} ({hole_str} round) in the UK. "
f"If you have web search available, please search for the current official ratings from England Golf, "
f"the R&A, the course's own website, or a reputable source such as Golfshake or The Social Golfer. "
f"If you cannot search, use your training knowledge but note the limitation. "
f"Reply with ONLY a JSON object in this exact format with no extra text:\n"
f'{{ "cr": <number>, "slope": <integer>, "confidence": "high"|"medium"|"low", "note": "<source used or caveat>" }}\n'
f"Set confidence to 'high' only if you found the values from an authoritative source. "
f"Set 'medium' if you are fairly sure from training data. "
f"Set 'low' if you are guessing. "
f"Do not refuse — always return the JSON with your best estimate."
)
try:
raw = "".join(provider.stream(prompt))
import re as _re, json as _json
m = _re.search(r'\{[^{}]+\}', raw, _re.S)
if not m:
return jsonify({"error": "AI did not return valid JSON", "raw": raw}), 502
result = _json.loads(m.group(0))
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/courses/<int:course_id>", methods=["PUT"])
def api_update_course(course_id):
from database import _UNSET
body = request.json or {}
notes = body.pop("notes", _UNSET)
description = body.pop("description", _UNSET)
try:
update_course_ratings(course_id, ratings=body, notes=notes, description=description)
except ValueError as e:
return jsonify({"error": str(e)}), 400
return jsonify({"ok": True})
@app.route("/api/courses/<int:course_id>/ai-description", methods=["POST"])
def api_ai_course_description(course_id):
"""Ask the configured AI to write a short description of a golf course."""
c = get_course(course_id)
if not c:
return jsonify({"error": "Course not found"}), 404
try:
provider = _build_provider()
except Exception as e:
return jsonify({"error": f"AI not configured: {e}"}), 503
prompt = (
f"Write a short description (2-3 sentences) of {c['name']} golf course in the UK. "
f"Cover the course style (parkland/links/heathland/etc.), any notable features or history, "
f"and the general challenge level. If you have web search available, use it to find accurate details. "
f"Be factual and concise. If you are not confident this course exists or have no reliable information, "
f"say so honestly in 1 sentence rather than inventing details."
)
try:
description = "".join(provider.stream(prompt)).strip()
return jsonify({"description": description})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/rounds/<int:round_id>/handicap-exclude", methods=["POST"])
def api_handicap_exclude(round_id):
excluded = (request.json or {}).get("excluded", False)
set_handicap_excluded(round_id, excluded)
return jsonify({"ok": True})
@app.route("/api/rounds/<int:round_id>/notes-ai-exclude", methods=["POST"])
def api_notes_ai_exclude(round_id):
excluded = (request.json or {}).get("excluded", False)
set_notes_ai_excluded(round_id, excluded)
return jsonify({"ok": True})
@app.route("/api/rounds/<int:round_id>/tee", methods=["POST"])
def api_set_tee(round_id):
tee = (request.json or {}).get("tee_colour", "Yellow")
if tee not in TEE_COLOURS:
return jsonify({"error": "Invalid tee colour"}), 400
from database import get_conn
with get_conn() as conn:
conn.execute("UPDATE rounds SET tee_colour = ? WHERE id = ?", (tee, round_id))
conn.commit()
return jsonify({"ok": True})
# ── WHS API ───────────────────────────────────────────────────────────────────
@app.route("/api/whs", methods=["GET"])
def api_whs():
rounds = get_all_rounds_with_course_ratings()
return jsonify({
"current": current_index(rounds),
"history": index_history(rounds),
})
# ── Stats API ─────────────────────────────────────────────────────────────────
@app.route("/api/stats/summary", methods=["GET"])
def api_stats_summary():
return jsonify(get_stats_summary())
@app.route("/api/stats/trends", methods=["GET"])
def api_stats_trends():
return jsonify(get_trend_data())
# ── Config API (API keys stored server-side in data/config.json) ──────────────
@app.route("/api/config", methods=["GET"])
def api_get_config():
cfg = load_config()
# Mask the key so it never leaves the server in plain text after initial save
masked = {**cfg}
if masked.get("api_key"):
masked["api_key"] = "•" * 8
return jsonify(masked)
@app.route("/api/config", methods=["POST"])
def api_save_config():
incoming = request.json or {}
cfg = load_config()
# Only overwrite the key if it looks like a real key:
# - not empty, not the masked placeholder (••••••••)
# - not an obvious test/placeholder value
# - never overwrite a real existing key with a shorter/fake one
_TEST_PATTERNS = ("test", "placeholder", "example", "your-key", "sk-ant-test", "sk-test")
new_key = incoming.get("api_key", "").strip()
existing_key = cfg.get("api_key", "")
is_masked = not new_key.strip("•")
is_test = any(p in new_key.lower() for p in _TEST_PATTERNS)
has_real_key = bool(existing_key) and not any(p in existing_key.lower() for p in _TEST_PATTERNS)
if new_key and not is_masked and not is_test:
cfg["api_key"] = new_key
elif is_test and has_real_key:
pass # never overwrite a real key with a test value
cfg["provider"] = incoming.get("provider", cfg.get("provider", "claude"))
cfg["model"] = incoming.get("model", cfg.get("model", ""))
cfg["base_url"] = incoming.get("base_url", cfg.get("base_url", ""))
if "notes_ai_default" in incoming:
cfg["notes_ai_default"] = bool(incoming["notes_ai_default"])
save_config(cfg)
return jsonify({"ok": True})
# ── Profile API ───────────────────────────────────────────────────────────────
@app.route("/api/profile", methods=["GET"])
def api_get_profile():
cfg = load_config()
return jsonify(cfg.get("profile", {}))
_PROFILE_TEXT_FIELDS = {"name": 60, "weakness_notes": 1000, "physical_notes": 1000}
_PROFILE_INT_FIELDS = {"age": (10, 110), "first_played_year": (1900, 2100), "playing_since_year": (1900, 2100)}
_PROFILE_ENUM_FIELDS = {
"dominant_hand": {"", "left", "right"},
"practice_frequency": {"", "rarely", "occasional", "weekly", "frequent"},
"preferred_format": {"", "Stableford", "Stroke play", "Match play", "Mixed"},
}
_PROFILE_WEAKNESS_KEYS = {
"driving_accuracy", "driving_distance", "iron_play", "chipping",
"bunker", "putting", "course_management", "mental_game",
}
def _clean_profile(incoming: dict) -> dict:
"""Validate and coerce profile fields so malformed input can't crash prompt
generation or be rendered unescaped."""
if not isinstance(incoming, dict):
return {}
cleaned = {}
for field, max_len in _PROFILE_TEXT_FIELDS.items():
val = incoming.get(field)
if isinstance(val, str) and val.strip():
cleaned[field] = val.strip()[:max_len]
for field, (lo, hi) in _PROFILE_INT_FIELDS.items():
val = incoming.get(field)
try:
n = int(val)
except (TypeError, ValueError):
continue
if lo <= n <= hi:
cleaned[field] = n
for field, allowed in _PROFILE_ENUM_FIELDS.items():
val = incoming.get(field)
if val in allowed and val:
cleaned[field] = val
weaknesses = incoming.get("weaknesses")
if isinstance(weaknesses, list):
cleaned["weaknesses"] = [w for w in weaknesses if w in _PROFILE_WEAKNESS_KEYS]
if isinstance(incoming.get("has_lessons"), bool):
cleaned["has_lessons"] = incoming["has_lessons"]
if isinstance(incoming.get("ai_include"), bool):
cleaned["ai_include"] = incoming["ai_include"]
return cleaned
@app.route("/api/profile", methods=["POST"])
def api_save_profile():
cleaned = _clean_profile(request.json or {})
cfg = load_config()
cfg["profile"] = cleaned
save_config(cfg)
return jsonify({"ok": True})
@app.route("/api/profile/club-distances", methods=["GET"])
def api_profile_club_distances():
rounds = get_rounds(limit=500)
return jsonify(prompts._club_profile_data(rounds))
# ── AI API ────────────────────────────────────────────────────────────────────
def _safe_stream(provider, prompt, on_complete=None):
"""Wrap provider.stream() so errors mid-stream are surfaced to the client."""
try:
buf = []
for chunk in provider.stream(prompt):
buf.append(chunk)
yield chunk
if on_complete:
on_complete("".join(buf))
except Exception as e:
# Emit a sentinel the frontend can detect — double-newline then the error
yield f"\n\n__AI_ERROR__: {e}"
def _build_provider():
"""Build an AI provider from the saved server-side config."""
from providers import (
ClaudeProvider, OpenAIProvider, GeminiProvider,
GroqProvider, MistralProvider, OpenRouterProvider,
OllamaProvider, LMStudioProvider,
)
cfg = load_config()
name = cfg.get("provider", "claude")
model = cfg.get("model", "")
key = cfg.get("api_key", "")
url = cfg.get("base_url", "")
mapping = {
"claude": lambda: ClaudeProvider(api_key=key, model=model or ClaudeProvider.DEFAULT_MODEL),
"openai": lambda: OpenAIProvider(api_key=key, model=model or "gpt-4o"),
"gemini": lambda: GeminiProvider(api_key=key, model=model or "gemini-1.5-pro"),
"groq": lambda: GroqProvider(api_key=key, model=model or "llama3-70b-8192"),
"mistral": lambda: MistralProvider(api_key=key, model=model or "mistral-large-latest"),
"openrouter": lambda: OpenRouterProvider(api_key=key, model=model or "anthropic/claude-3.5-sonnet"),
"ollama": lambda: OllamaProvider(model=model or "llama3", base_url=url or "http://localhost:11434"),
"lmstudio": lambda: LMStudioProvider(model=model or "local-model", base_url=url or "http://localhost:1234"),
}
factory = mapping.get(name)
if not factory:
raise ValueError(f"Unknown provider: {name}")
return factory()
@app.route("/api/ai/round-debrief/<int:round_id>", methods=["POST"])
def api_ai_round_debrief(round_id):
r = get_round(round_id)
if not r:
return jsonify({"error": "Round not found"}), 404
try:
provider = _build_provider()
all_rounds = get_all_rounds_with_course_ratings()
hcp_history = index_history(all_rounds)
profile = load_config().get("profile", {})
prompt = prompts.round_debrief(r, hcp_history=hcp_history, profile=profile)
return Response(
_safe_stream(provider, prompt, on_complete=lambda text: save_debrief(round_id, text)),
mimetype="text/plain",
)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/ai/round-short-summary/<int:round_id>", methods=["POST"])
def api_ai_round_short_summary(round_id):
r = get_round(round_id)
if not r:
return jsonify({"error": "Round not found"}), 404
try:
provider = _build_provider()
profile = load_config().get("profile", {})
prompt = prompts.round_short_summary(r, profile=profile)
text = "".join(provider.stream(prompt))
if text.startswith("\n\n__AI_ERROR__"):
return jsonify({"error": text}), 500
save_short_summary(round_id, text)
return jsonify({"ok": True, "summary": text})
except Exception as e:
return jsonify({"error": str(e)}), 500
def _default_window():
"""Return (from_date, to_date) for the default 90-day window anchored to latest round."""
from datetime import date, timedelta
latest = get_latest_round_date()
if not latest:
return None, None
to_dt = date.fromisoformat(latest)
from_dt = to_dt - timedelta(days=90)
return from_dt.isoformat(), to_dt.isoformat()
@app.route("/api/ai/global-summary", methods=["GET"])
def api_get_global_summary():
from_date, to_date = _default_window()
return jsonify({
"performance": get_global_summary("performance"),
"practice": get_global_summary("practice"),
"default_from": from_date,
"default_to": to_date,
"latest_round_date": get_latest_round_date(),
})
@app.route("/api/ai/global-summary", methods=["POST"])
def api_gen_global_summary():
"""
Generate global summary for the requested date window.
Body: {from_date?, to_date?, type?, auto?}
Skips generation if the stored summary already covers the same window
and round count — unless `force` is true.
If `auto` is true (called from import flow), also skips if the new round
date is not newer than the stored latest_round_date watermark.
"""
body = request.json or {}
summary_type = body.get("type", "performance")
force = body.get("force", False)
auto = body.get("auto", False)
from_date = body.get("from_date")
to_date = body.get("to_date")
if not from_date or not to_date:
from_date, to_date = _default_window()
if not from_date:
return jsonify({"error": "No rounds in database"}), 400
rounds = get_rounds_in_window(from_date, to_date)
if not rounds:
return jsonify({"skipped": True, "reason": "no_rounds_in_window",
"from_date": from_date, "to_date": to_date}), 200
latest_round_date = get_latest_round_date()
# Auto-regen guard: skip if no new calendar rounds since last generation
stored = get_global_summary(summary_type)
if auto and not force and stored:
stored_watermark = stored.get("latest_round_date")
if stored_watermark and latest_round_date and latest_round_date <= stored_watermark:
return jsonify({"skipped": True, "reason": "no_new_rounds"}), 200
# Manual regen guard: skip if same window and same round count
if not auto and not force and stored:
if (stored.get("from_date") == from_date and
stored.get("to_date") == to_date and
stored.get("round_count") == len(rounds)):
return jsonify({"skipped": True, "reason": "window_unchanged"}), 200
try:
provider = _build_provider()
# Get WHS index and history for richer prompts
all_rounds_whs = get_all_rounds_with_course_ratings()
whs = current_index(all_rounds_whs)
whs_index = whs.get("index")
hcp_history = index_history(all_rounds_whs)
profile = load_config().get("profile", {})
short_text = "".join(provider.stream(
prompts.global_short_summary(rounds, whs_index=whs_index,
from_date=from_date, to_date=to_date, profile=profile)
))
round_count = len(rounds)
prompt_fn = prompts.performance_summary if summary_type == "performance" else prompts.practice_plan
def generate():
yield from _safe_stream(
provider,
prompt_fn(rounds, whs_index=whs_index, hcp_history=hcp_history, from_date=from_date, to_date=to_date, profile=profile),
on_complete=lambda full: save_global_summary(
summary_type, short_text, full,
round_count=round_count,
from_date=from_date, to_date=to_date,
latest_round_date=latest_round_date,
),
)
return Response(generate(), mimetype="text/plain")
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/ai/practice-plan", methods=["POST"])
def api_ai_practice_plan():
rounds = get_rounds(limit=50)
if not rounds:
return jsonify({"error": "No rounds to analyse"}), 400
try:
provider = _build_provider()
profile = load_config().get("profile", {})
prompt = prompts.practice_plan(rounds, profile=profile)
return Response(_safe_stream(provider, prompt), mimetype="text/plain")
except Exception as e:
return jsonify({"error": str(e)}), 500
# ── Provider list ─────────────────────────────────────────────────────────────
@app.route("/api/providers", methods=["GET"])
def api_providers():
from model_tier import PROVIDER_TIERS
return jsonify(PROVIDER_TIERS)
if __name__ == "__main__":
init_db()
app.run(host="127.0.0.1", port=5050, debug=False)