"""Badak playstyle analyzer: Streamlit app.
streamlit run app.py
Upload Garmin .fit files recorded with the badak watch app -> stroke detection and
classification (badminsens) -> playstyle attributes, archetype and skill tier (src.model)
-> racket and string-tension recommendations (src.recommendation). Past analyses are kept
per browser in SQLite (server) and mirrored into the browser's IndexedDB.
"""
import json
import math
import os
import tempfile
from collections import Counter
from datetime import datetime
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from src import model as pmodel
from src.history import History, compact
from src.parser import FEATURES, parse_fit
from src.recommendation import racket_svg, recommend
ROOT = os.path.dirname(os.path.abspath(__file__))
CACHE = os.path.join(ROOT, ".cache", "sessions")
ATTRS = pmodel.ATTRS
STROKE_ORDER = [("smash", "Smash"), ("clear", "Clear"), ("drop", "Drop"), ("backhand", "Backhand clear"),
("other", "Other swings")]
st.set_page_config(page_title="Badak Playstyle", page_icon="🏸", layout="wide")
# ------------------------------------------------------------------ theme tokens
DARK = (getattr(st.context, "theme", None) is not None and st.context.theme.type == "dark")
C = {
"series": ["#3987e5", "#d95926", "#199e70", "#c98500", "#d55181"] if DARK
else ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4"],
"muted": "#75746f" if DARK else "#b5b4ae",
"ink": "#f0efec" if DARK else "#0b0b0b",
"ink2": "#c3c2b7" if DARK else "#52514e",
"grid": "#333331" if DARK else "#e4e3df",
}
STROKE_COLOR = dict(zip([k for k, _ in STROKE_ORDER], C["series"][:4] + [C["muted"]]))
st.markdown("""""", unsafe_allow_html=True)
# ------------------------------------------------------------------ browser bridge (id + IndexedDB mirror)
BRIDGE_JS = """
export default function(component) {
const { data, setStateValue } = component;
const last = (window.__badak = window.__badak || {});
const send = (k, v) => { const s = JSON.stringify(v); if (last[k] !== s) { last[k] = s; setStateValue(k, v); } };
let uid = null;
try { uid = localStorage.getItem('badak_uid');
if (!uid) { uid = crypto.randomUUID(); localStorage.setItem('badak_uid', uid); } } catch (e) {}
if (!uid) { uid = last.uid || (last.uid = crypto.randomUUID()); }
send('uid', uid);
if (!window.indexedDB) { send('ids', []); return; }
const req = indexedDB.open('badak', 1);
req.onupgradeneeded = () => req.result.createObjectStore('sessions', { keyPath: 'id' });
req.onerror = () => send('ids', []);
req.onsuccess = () => {
const db = req.result;
const tx = db.transaction('sessions', 'readwrite');
const store = tx.objectStore('sessions');
const d = data || {};
if (d.clear) store.clear();
(d.del || []).forEach((id) => store.delete(id));
(d.put || []).forEach((rec) => store.put(rec));
tx.oncomplete = () => {
const r = db.transaction('sessions').objectStore('sessions').getAll();
r.onsuccess = () => {
send('ids', r.result.map((x) => x.id).sort());
if (d.want) send('records', r.result);
};
};
};
}
"""
_bridge = st.components.v2.component("badak_bridge", js=BRIDGE_JS)
@st.cache_resource
def history():
return History()
@st.cache_resource
def playstyle():
return pmodel.load()
ss = st.session_state
ss.setdefault("pending_put", {})
ss.setdefault("pending_del", set())
ss.setdefault("clear_idb", False)
ss.setdefault("restored", False)
with st.sidebar:
bridge = _bridge(key="bridge", data={"put": list(ss.pending_put.values()), "del": sorted(ss.pending_del),
"clear": ss.clear_idb, "want": not ss.restored},
height=0, on_uid_change=lambda: None, on_ids_change=lambda: None,
on_records_change=lambda: None)
uid = bridge.get("uid") if bridge else None
idb_ids = set(bridge.get("ids") or []) if bridge else set()
# what IndexedDB now holds is no longer pending
ss.pending_put = {k: v for k, v in ss.pending_put.items() if k not in idb_ids}
ss.pending_del = {k for k in ss.pending_del if k in idb_ids}
if ss.clear_idb and not idb_ids:
ss.clear_idb = False
H = history()
M = playstyle()
if uid is None:
st.info("Connecting to your browser storage...")
st.stop()
# restore from IndexedDB when the server has nothing for this browser (e.g. after a redeploy)
if not ss.restored and bridge.get("records") is not None:
ss.restored = True
have = {r["id"] for r in H.all(uid)}
for rec in bridge.get("records") or []:
if rec.get("schema") == 1 and rec["id"] not in have:
H.save(uid, rec)
records = H.all(uid)
# mirror anything IndexedDB is missing
for r in records:
if r["id"] not in idb_ids and r["id"] not in ss.pending_put and r["id"] not in ss.pending_del:
ss.pending_put[r["id"]] = r
# ------------------------------------------------------------------ helpers
def label(rec):
t = rec.get("start_local")
when = datetime.fromisoformat(t).strftime("%a %d %b %Y, %H:%M") if t else rec["file_name"]
return f"{when} · {rec['activity_id']}"
def predict(features):
return M.predict(features)
def mean_features(recs):
keys = recs[0]["features"].keys()
out = {}
for k in keys:
v = [r["features"][k] for r in recs if r["features"].get(k) is not None and not _nan(r["features"][k])]
out[k] = float(np.mean(v)) if v else float("nan")
return out
def _nan(x):
return isinstance(x, float) and math.isnan(x)
def fmt(x, nd=1):
return "–" if x is None or _nan(x) else f"{x:,.{nd}f}"
def base_layout(fig, height=380, **kw):
fig.update_layout(height=height, margin=dict(l=10, r=10, t=30, b=10), paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)", font=dict(color=C["ink2"], size=13),
legend=dict(orientation="h", y=-0.12, x=0), hoverlabel=dict(font_size=13), **kw)
return fig
def analyze_uploads(files):
os.makedirs(os.path.join(ROOT, ".cache", "uploads"), exist_ok=True)
added, errors = [], []
prog = st.progress(0.0, text="Starting…")
for i, f in enumerate(files):
prog.progress(i / len(files), text=f"Analyzing {f.name} ({i + 1}/{len(files)}) — about 20 s per hour of play")
with tempfile.NamedTemporaryFile(suffix=".fit", dir=os.path.join(ROOT, ".cache", "uploads"),
prefix=os.path.splitext(f.name)[0] + "_", delete=False) as tmp:
tmp.write(f.getbuffer())
path = tmp.name
try:
s = parse_fit(path, cache_dir=CACHE)
s["file_name"] = f.name
s["activity_id"] = f.name.split("_")[0].split(".")[0]
if len(s["swings"]) < 20:
errors.append(f"{f.name}: only {len(s['swings'])} swings found — is this a badminton recording "
"with raw sensor logging on?")
continue
rec = compact(s, predict(s["features"]))
H.save(uid, rec)
ss.pending_put[rec["id"]] = rec
ss.pending_del.discard(rec["id"])
added.append(rec["id"])
except Exception as e: # noqa: BLE001 - shown to the user
errors.append(f"{f.name}: {e}")
finally:
os.remove(path)
prog.empty()
return added, errors
# ------------------------------------------------------------------ sidebar
with st.sidebar:
st.header("🏸 Badak Playstyle")
st.caption("Garmin .fit recordings from the [badak](https://github.com/omayib/badak) watch app "
"(raw accelerometer + gyroscope, racket wrist).")
up = st.file_uploader("Upload .fit files", type=["fit"], accept_multiple_files=True, key=f"up{ss.get('upn', 0)}")
if up and st.button(f"Analyze {len(up)} file{'s' * (len(up) > 1)}", type="primary", width="stretch"):
added, errors = analyze_uploads(up)
for e in errors:
st.error(e)
if added:
ss.focus = added[-1]
ss.upn = ss.get("upn", 0) + 1
st.rerun()
if records:
st.divider()
st.subheader(f"History ({len(records)})")
by_id = {r["id"]: r for r in records}
ids = [r["id"] for r in records]
if ss.get("focus") not in by_id:
ss.focus = ids[-1]
focus_id = st.selectbox("Focus session", ids[::-1], format_func=lambda i: label(by_id[i]), key="focus")
with st.expander(f"Sessions in trends and averages ({len(ss.get('compare', ids))} of {len(ids)})"):
compare = st.multiselect("Sessions", ids, default=ids, format_func=lambda i: label(by_id[i]),
key="compare", label_visibility="collapsed")
with st.expander("Manage history"):
st.download_button("Export history (.json)", json.dumps(records), "badak_history.json",
"application/json", width="stretch")
imp = st.file_uploader("Import history (.json)", type=["json"], key="imp")
if imp is not None and st.button("Import", width="stretch"):
n = 0
for rec in json.load(imp):
if isinstance(rec, dict) and rec.get("schema") == 1:
H.save(uid, rec)
n += 1
st.success(f"Imported {n} sessions")
st.rerun()
if st.button("Delete focus session", width="stretch"):
H.delete(uid, focus_id)
ss.pending_put.pop(focus_id, None)
ss.pending_del.add(focus_id)
del ss["focus"]
st.rerun()
if st.button("Delete all history", width="stretch"):
H.clear(uid)
ss.pending_put, ss.pending_del, ss.clear_idb = {}, set(), True
st.rerun()
st.caption("History is kept on this server for this browser and mirrored in your browser's IndexedDB.")
if not records:
st.title("Your badminton playstyle, from your watch")
st.markdown(
"Upload one or more Garmin `.fit` files in the sidebar. For each session the app\n\n"
"1. finds every swing and classifies the overhead strokes (smash, clear, drop, backhand clear),\n"
"2. scores **Power, Speed, Control, Endurance and Agility** and places you on the "
"Attacking / Defensive / Control / All-round map,\n"
"3. estimates a skill tier and suggests a **racket profile and string tension**.\n\n"
"Analyses are saved, so next time you can browse them without uploading again.")
st.stop()
focus = by_id[focus_id]
pred = predict(focus["features"])
sel = [by_id[i] for i in compare] or [focus]
# ------------------------------------------------------------------ header
st.title("Playstyle analysis")
f = focus["features"]
m = focus["meta"]
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Session", datetime.fromisoformat(focus["start_local"]).strftime("%d %b") if focus["start_local"] else "–",
help=f"{label(focus)} · {focus['file_name']}")
c2.metric("Active play", f"{f['active_min']:.0f} min", help=f"{len(focus['games'])} game block(s); rests excluded")
c3.metric("Swings", f"{len(focus['swings'])}", help=f"{f['swings_per_min']:.1f} per minute of play")
c4.metric("Avg heart rate", f"{m.get('avg_heart_rate') or '–'} bpm", help=f"max {m.get('max_heart_rate') or '–'} bpm")
c5.metric("Training effect", f"{fmt(m.get('total_training_effect'))} / {fmt(m.get('total_anaerobic_training_effect'))}",
help="Garmin aerobic / anaerobic training effect (0–5)")
tab_style, tab_trend, tab_gear, tab_sess, tab_about = st.tabs(
["Playstyle", "Trends", "Equipment", "Session details", "Method"])
# ------------------------------------------------------------------ playstyle
with tab_style:
left, right = st.columns([1.35, 1])
with left:
fig = go.Figure()
theta = ATTRS + [ATTRS[0]]
if len(sel) > 1:
avg = predict(mean_features(sel))["attributes"]
fig.add_trace(go.Scatterpolar(r=[avg[a] for a in theta], theta=theta, name=f"Average of {len(sel)} sessions",
line=dict(color=C["muted"], width=2, dash="dot"), fill="none",
hovertemplate="%{theta}: %{r:.0f}
| Balance | {r['balance']} |
| Balance point | {r['balance_mm'][0]}–{r['balance_mm'][1]} mm |
| Weight | {r['weight']} · {r['weight_g'][0]:.0f}–{r['weight_g'][1]:.0f} g |
| Shaft | {r['shaft']} |
| Head | {r['head']} |
| String at | {rec['tension_lbs'][0]}–{rec['tension_lbs'][1]} lbs |