mannnon commited on
Commit
570a542
·
verified ·
1 Parent(s): f5175c5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +454 -0
app.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import streamlit as st
4
+ import matplotlib.pyplot as plt
5
+
6
+ from zebris_extractor import extract_zebris_csv
7
+
8
+ st.set_page_config(page_title="Zebris - Profil & Seuils", layout="wide")
9
+
10
+ st.title("Zebris — Profil biomécanique & seuils individualisés")
11
+ st.caption("Import d’un CSV Zebris brut → fiche profil + seuils personnalisés")
12
+
13
+ with st.sidebar:
14
+ st.header("Import")
15
+ uploaded_file = st.file_uploader(
16
+ "Importer un fichier CSV Zebris",
17
+ type=["csv"],
18
+ accept_multiple_files=False,
19
+ )
20
+
21
+ if uploaded_file is not None and uploaded_file.size > 20 * 1024 * 1024:
22
+ st.error("Fichier trop volumineux (>20 MB)")
23
+ st.stop()
24
+
25
+ st.header("Contexte athlète")
26
+ volume_horaire = st.number_input(
27
+ "Volume horaire / semaine",
28
+ min_value=0.5,
29
+ max_value=40.0,
30
+ value=5.0,
31
+ step=0.5,
32
+ )
33
+
34
+ if uploaded_file is None:
35
+ st.info("Importe un CSV Zebris brut pour afficher la fiche profil et les seuils.")
36
+ st.stop()
37
+
38
+ try:
39
+ df_std, debug = extract_zebris_csv(uploaded_file)
40
+ except Exception as e:
41
+ st.error(f"Erreur pendant l’extraction du CSV Zebris : {e}")
42
+ st.stop()
43
+
44
+ if df_std.empty:
45
+ st.error("Aucune ligne exploitable n’a été trouvée dans le CSV.")
46
+ st.stop()
47
+
48
+ # Choix sportif
49
+ athletes = sorted(df_std["Nom"].dropna().unique().tolist())
50
+ selected_athlete = st.selectbox("Sportif", athletes)
51
+ sub_df = df_std[df_std["Nom"] == selected_athlete].copy()
52
+
53
+ if sub_df.empty:
54
+ st.error("Aucune donnée trouvée pour ce sportif.")
55
+ st.stop()
56
+
57
+ # Choix allure
58
+ sub_df = sub_df.sort_values("Vitesse (km/h)")
59
+ speeds = sub_df["Vitesse (km/h)"].dropna().tolist()
60
+ selected_speed = st.selectbox("Allure analysée (km/h)", speeds)
61
+ row = sub_df[sub_df["Vitesse (km/h)"] == selected_speed].iloc[0]
62
+
63
+ # Poids
64
+ poids_csv = row["Poids (kg)"] if pd.notna(row["Poids (kg)"]) else np.nan
65
+ poids_kg = st.number_input(
66
+ "Poids du sportif (kg)",
67
+ min_value=30.0,
68
+ max_value=150.0,
69
+ value=float(poids_csv) if pd.notna(poids_csv) else 70.0,
70
+ step=0.1,
71
+ )
72
+ poids_n = poids_kg * 9.81
73
+
74
+ # ---------------------------
75
+ # Fonctions calcul
76
+ # ---------------------------
77
+ def avg(a, b):
78
+ if pd.isna(a) and pd.isna(b):
79
+ return np.nan
80
+ if pd.isna(a):
81
+ return float(b)
82
+ if pd.isna(b):
83
+ return float(a)
84
+ return (float(a) + float(b)) / 2
85
+
86
+ def asym(a, b):
87
+ m = avg(a, b)
88
+ if pd.isna(m) or m == 0 or pd.isna(a) or pd.isna(b):
89
+ return np.nan
90
+ return abs(float(a) - float(b)) / m * 100
91
+
92
+ def clamp_score(value, low, high, reverse=False):
93
+ if pd.isna(value):
94
+ return np.nan
95
+ score = (value - low) / (high - low) * 100
96
+ score = max(0, min(100, score))
97
+ return 100 - score if reverse else score
98
+
99
+ def compute_profile_metrics(row, poids_kg):
100
+ poids_n = poids_kg * 9.81
101
+
102
+ force_talon_moy = avg(row["Force talon G (N)"], row["Force talon D (N)"])
103
+ force_avant_moy = avg(row["Force avant-pied G (N)"], row["Force avant-pied D (N)"])
104
+ pression_talon_moy = avg(row["Pression talon G (N/cm²)"], row["Pression talon D (N/cm²)"])
105
+ cop_moy = avg(row["COP G (mm)"], row["COP D (mm)"])
106
+ transition_moy = avg(row["Transition G (s)"], row["Transition D (s)"])
107
+
108
+ asym_talon = asym(row["Force talon G (N)"], row["Force talon D (N)"])
109
+ asym_avant = asym(row["Force avant-pied G (N)"], row["Force avant-pied D (N)"])
110
+ asym_cop = asym(row["COP G (mm)"], row["COP D (mm)"])
111
+
112
+ diff_rotation = (
113
+ abs(float(row["Rotation G (°)"]) - float(row["Rotation D (°)"]))
114
+ if pd.notna(row["Rotation G (°)"]) and pd.notna(row["Rotation D (°)"])
115
+ else np.nan
116
+ )
117
+
118
+ force_talon_bw = force_talon_moy / poids_n if pd.notna(force_talon_moy) and poids_n else np.nan
119
+ ratio_talon_avant = (
120
+ force_talon_moy / force_avant_moy
121
+ if pd.notna(force_talon_moy) and pd.notna(force_avant_moy) and force_avant_moy != 0
122
+ else np.nan
123
+ )
124
+
125
+ impact = round(
126
+ np.nanmean([
127
+ 0.6 * clamp_score(force_talon_bw, 0.6, 1.1),
128
+ 0.4 * clamp_score(pression_talon_moy, 15, 30),
129
+ ])
130
+ ) if pd.notna(force_talon_bw) or pd.notna(pression_talon_moy) else np.nan
131
+
132
+ dynamique = round(
133
+ np.nanmean([
134
+ 0.6 * clamp_score(row["Cadence (pas/min)"], 150, 185),
135
+ 0.4 * clamp_score(row["Contact (%)"], 68, 76, reverse=True),
136
+ ])
137
+ ) if pd.notna(row["Cadence (pas/min)"]) or pd.notna(row["Contact (%)"]) else np.nan
138
+
139
+ sym_components = [x for x in [asym_talon, asym_avant, asym_cop, diff_rotation] if pd.notna(x)]
140
+ symetrie = round(100 - min(100, np.mean(sym_components) * 2.5)) if sym_components else np.nan
141
+
142
+ # On garde "déroulé" pour la fiche descriptive, sans l'appeler "technique"
143
+ deroule = round(
144
+ np.nanmean([
145
+ 0.5 * clamp_score(cop_moy, 210, 260),
146
+ 0.5 * clamp_score(transition_moy, 0.05, 0.09, reverse=True),
147
+ ])
148
+ ) if pd.notna(cop_moy) or pd.notna(transition_moy) else np.nan
149
+
150
+ attaque = "mixte"
151
+ if pd.notna(ratio_talon_avant):
152
+ if ratio_talon_avant > 1.05:
153
+ attaque = "talon"
154
+ elif ratio_talon_avant < 0.95:
155
+ attaque = "avant-pied"
156
+
157
+ return {
158
+ "force_talon_moy": force_talon_moy,
159
+ "force_avant_moy": force_avant_moy,
160
+ "pression_talon_moy": pression_talon_moy,
161
+ "cop_moy": cop_moy,
162
+ "transition_moy": transition_moy,
163
+ "asym_talon": asym_talon,
164
+ "asym_avant": asym_avant,
165
+ "asym_cop": asym_cop,
166
+ "diff_rotation": diff_rotation,
167
+ "force_talon_bw": force_talon_bw,
168
+ "ratio_talon_avant": ratio_talon_avant,
169
+ "impact": impact,
170
+ "dynamique": dynamique,
171
+ "symetrie": symetrie,
172
+ "deroule": deroule,
173
+ "attaque": attaque,
174
+ }
175
+
176
+ def build_summary(row, metrics):
177
+ impact_txt = "marqué" if pd.notna(metrics["impact"]) and metrics["impact"] >= 70 else "modéré" if pd.notna(metrics["impact"]) and metrics["impact"] >= 45 else "faible"
178
+ dyn_txt = "bonne" if pd.notna(metrics["dynamique"]) and metrics["dynamique"] >= 70 else "moyenne" if pd.notna(metrics["dynamique"]) and metrics["dynamique"] >= 45 else "faible"
179
+ sym_txt = "satisfaisante" if pd.notna(metrics["symetrie"]) and metrics["symetrie"] >= 70 else "perfectible"
180
+ der_txt = "favorable" if pd.notna(metrics["deroule"]) and metrics["deroule"] >= 70 else "intermédiaire" if pd.notna(metrics["deroule"]) and metrics["deroule"] >= 45 else "à surveiller"
181
+
182
+ return (
183
+ f"À {row['Vitesse (km/h)']} km/h, {row['Nom']} présente une attaque {metrics['attaque']}, "
184
+ f"un impact {impact_txt}, une dynamique {dyn_txt}, une symétrie {sym_txt} "
185
+ f"et un déroulé {der_txt}."
186
+ )
187
+
188
+ def draw_radar(metrics):
189
+ labels = ["Impact", "Dynamique", "Symétrie", "Déroulé"]
190
+ values = [
191
+ metrics["impact"] if pd.notna(metrics["impact"]) else 0,
192
+ metrics["dynamique"] if pd.notna(metrics["dynamique"]) else 0,
193
+ metrics["symetrie"] if pd.notna(metrics["symetrie"]) else 0,
194
+ metrics["deroule"] if pd.notna(metrics["deroule"]) else 0,
195
+ ]
196
+ values += values[:1]
197
+ angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False).tolist()
198
+ angles += angles[:1]
199
+
200
+ fig = plt.figure(figsize=(5, 5))
201
+ ax = plt.subplot(111, polar=True)
202
+ ax.plot(angles, values, linewidth=2)
203
+ ax.fill(angles, values, alpha=0.25)
204
+ ax.set_xticks(angles[:-1])
205
+ ax.set_xticklabels(labels)
206
+ ax.set_ylim(0, 100)
207
+ ax.set_yticks([25, 50, 75, 100])
208
+ ax.set_title("Radar biomécanique", pad=20)
209
+ return fig
210
+
211
+ def draw_evolution(df, poids_kg):
212
+ data = []
213
+ for _, r in df.sort_values("Vitesse (km/h)").iterrows():
214
+ m = compute_profile_metrics(r, poids_kg)
215
+ data.append({
216
+ "Vitesse": r["Vitesse (km/h)"],
217
+ "Impact": m["impact"],
218
+ "Dynamique": m["dynamique"],
219
+ "Symétrie": m["symetrie"],
220
+ "Déroulé": m["deroule"],
221
+ })
222
+
223
+ evo = pd.DataFrame(data)
224
+ fig, ax = plt.subplots(figsize=(8, 4))
225
+ for col in ["Impact", "Dynamique", "Symétrie", "Déroulé"]:
226
+ ax.plot(evo["Vitesse"], evo[col], marker="o", label=col)
227
+ ax.set_ylim(0, 100)
228
+ ax.set_xlabel("Vitesse (km/h)")
229
+ ax.set_ylabel("Score /100")
230
+ ax.set_title("Évolution avec l’allure")
231
+ ax.legend()
232
+ ax.grid(True, alpha=0.3)
233
+ return fig
234
+
235
+ def compute_thresholds(poids_kg, volume_horaire):
236
+ poids_n = poids_kg * 9.81
237
+
238
+ if volume_horaire <= 3:
239
+ charge = "faible"
240
+ force_bw_low, force_bw_high = 0.75, 1.00
241
+ pression_low, pression_high = 20, 26
242
+ cadence_low, cadence_high = 160, 172
243
+ contact_low, contact_high = 70, 74
244
+ flight_low, flight_high = 26, 30
245
+ asym_low, asym_high = 6, 10
246
+ rotation_low, rotation_high = 6, 10
247
+ elif volume_horaire <= 6:
248
+ charge = "modérée"
249
+ force_bw_low, force_bw_high = 0.70, 0.95
250
+ pression_low, pression_high = 20, 25
251
+ cadence_low, cadence_high = 165, 176
252
+ contact_low, contact_high = 69, 73
253
+ flight_low, flight_high = 27, 31
254
+ asym_low, asym_high = 5, 9
255
+ rotation_low, rotation_high = 5, 9
256
+ else:
257
+ charge = "élevée"
258
+ force_bw_low, force_bw_high = 0.65, 0.90
259
+ pression_low, pression_high = 20, 24
260
+ cadence_low, cadence_high = 168, 180
261
+ contact_low, contact_high = 68, 72
262
+ flight_low, flight_high = 28, 32
263
+ asym_low, asym_high = 4, 8
264
+ rotation_low, rotation_high = 4, 8
265
+
266
+ return {
267
+ "charge": charge,
268
+ "poids_n": poids_n,
269
+ "force_bw_low": force_bw_low,
270
+ "force_bw_high": force_bw_high,
271
+ "force_n_low": force_bw_low * poids_n,
272
+ "force_n_high": force_bw_high * poids_n,
273
+ "pression_low": pression_low,
274
+ "pression_high": pression_high,
275
+ "cadence_low": cadence_low,
276
+ "cadence_high": cadence_high,
277
+ "contact_low": contact_low,
278
+ "contact_high": contact_high,
279
+ "flight_low": flight_low,
280
+ "flight_high": flight_high,
281
+ "asym_low": asym_low,
282
+ "asym_high": asym_high,
283
+ "rotation_low": rotation_low,
284
+ "rotation_high": rotation_high,
285
+ }
286
+
287
+ metrics = compute_profile_metrics(row, poids_kg)
288
+ summary = build_summary(row, metrics)
289
+ thresholds = compute_thresholds(poids_kg, volume_horaire)
290
+
291
+ # ---------------------------
292
+ # Onglets
293
+ # ---------------------------
294
+ tab_profil, tab_seuils, tab_debug = st.tabs(["Profil biomécanique", "Seuils individualisés", "Debug extraction"])
295
+
296
+ with tab_profil:
297
+ c1, c2, c3, c4 = st.columns(4)
298
+ with c1:
299
+ st.metric("Impact", f"{metrics['impact']}/100" if pd.notna(metrics["impact"]) else "N/A")
300
+ with c2:
301
+ st.metric("Dynamique", f"{metrics['dynamique']}/100" if pd.notna(metrics["dynamique"]) else "N/A")
302
+ with c3:
303
+ st.metric("Symétrie", f"{metrics['symetrie']}/100" if pd.notna(metrics["symetrie"]) else "N/A")
304
+ with c4:
305
+ st.metric("Déroulé", f"{metrics['deroule']}/100" if pd.notna(metrics["deroule"]) else "N/A")
306
+
307
+ left, right = st.columns([1.2, 1])
308
+
309
+ with left:
310
+ st.subheader("Carte d’identité biomécanique")
311
+ st.write(summary)
312
+
313
+ indicators = pd.DataFrame(
314
+ {
315
+ "Indicateur": [
316
+ "Poids",
317
+ "Cadence",
318
+ "Contact",
319
+ "Flight",
320
+ "Force talon moyenne",
321
+ "Force talon normalisée",
322
+ "Asymétrie talon",
323
+ "COP moyen",
324
+ "Différence rotation",
325
+ "Attaque",
326
+ ],
327
+ "Valeur": [
328
+ f"{poids_kg:.1f} kg",
329
+ f"{row['Cadence (pas/min)']:.1f} pas/min" if pd.notna(row["Cadence (pas/min)"]) else "N/A",
330
+ f"{row['Contact (%)']:.1f} %" if pd.notna(row["Contact (%)"]) else "N/A",
331
+ f"{row['Flight (%)']:.1f} %" if pd.notna(row["Flight (%)"]) else "N/A",
332
+ f"{metrics['force_talon_moy']:.1f} N" if pd.notna(metrics["force_talon_moy"]) else "N/A",
333
+ f"{metrics['force_talon_bw']:.2f} BW" if pd.notna(metrics["force_talon_bw"]) else "N/A",
334
+ f"{metrics['asym_talon']:.1f} %" if pd.notna(metrics["asym_talon"]) else "N/A",
335
+ f"{metrics['cop_moy']:.1f} mm" if pd.notna(metrics["cop_moy"]) else "N/A",
336
+ f"{metrics['diff_rotation']:.1f}°" if pd.notna(metrics["diff_rotation"]) else "N/A",
337
+ metrics["attaque"],
338
+ ],
339
+ }
340
+ )
341
+ st.dataframe(indicators, hide_index=True, use_container_width=True)
342
+
343
+ with right:
344
+ st.subheader("Radar biomécanique")
345
+ st.pyplot(draw_radar(metrics), use_container_width=True)
346
+
347
+ st.subheader("Évolution avec l’allure")
348
+ st.pyplot(draw_evolution(sub_df, poids_kg), use_container_width=True)
349
+
350
+ with tab_seuils:
351
+ r1, r2, r3 = st.columns(3)
352
+ with r1:
353
+ st.metric("Poids", f"{poids_kg:.1f} kg")
354
+ with r2:
355
+ st.metric("Poids en Newton", f"{thresholds['poids_n']:.1f} N")
356
+ with r3:
357
+ st.metric("Charge", thresholds["charge"])
358
+
359
+ impact_df = pd.DataFrame({
360
+ "Variable": [
361
+ "Force talon normalisée",
362
+ "Force talon convertie",
363
+ "Pression talon",
364
+ ],
365
+ "Zone basse / faible": [
366
+ f"< {thresholds['force_bw_low']:.2f} BW",
367
+ f"< {thresholds['force_n_low']:.1f} N",
368
+ f"< {thresholds['pression_low']} N/cm²",
369
+ ],
370
+ "Zone attendue": [
371
+ f"{thresholds['force_bw_low']:.2f} à {thresholds['force_bw_high']:.2f} BW",
372
+ f"{thresholds['force_n_low']:.1f} à {thresholds['force_n_high']:.1f} N",
373
+ f"{thresholds['pression_low']} à {thresholds['pression_high']} N/cm²",
374
+ ],
375
+ "Zone haute / élevée": [
376
+ f"> {thresholds['force_bw_high']:.2f} BW",
377
+ f"> {thresholds['force_n_high']:.1f} N",
378
+ f"> {thresholds['pression_high']} N/cm²",
379
+ ],
380
+ })
381
+
382
+ dynamique_df = pd.DataFrame({
383
+ "Variable": [
384
+ "Cadence",
385
+ "Temps de contact",
386
+ "Temps de vol",
387
+ ],
388
+ "Zone basse / faible": [
389
+ f"< {thresholds['cadence_low']} pas/min",
390
+ f"< {thresholds['contact_low']} %",
391
+ f"< {thresholds['flight_low']} %",
392
+ ],
393
+ "Zone attendue": [
394
+ f"{thresholds['cadence_low']} à {thresholds['cadence_high']} pas/min",
395
+ f"{thresholds['contact_low']} à {thresholds['contact_high']} %",
396
+ f"{thresholds['flight_low']} à {thresholds['flight_high']} %",
397
+ ],
398
+ "Zone haute / élevée": [
399
+ f"> {thresholds['cadence_high']} pas/min",
400
+ f"> {thresholds['contact_high']} %",
401
+ f"> {thresholds['flight_high']} %",
402
+ ],
403
+ })
404
+
405
+ symetrie_df = pd.DataFrame({
406
+ "Variable": [
407
+ "Asymétrie force talon",
408
+ "Asymétrie force avant-pied",
409
+ "Asymétrie COP",
410
+ "Différence rotation G/D",
411
+ ],
412
+ "Zone faible": [
413
+ f"< {thresholds['asym_low']} %",
414
+ f"< {thresholds['asym_low']} %",
415
+ f"< {thresholds['asym_low']} %",
416
+ f"< {thresholds['rotation_low']}°",
417
+ ],
418
+ "Zone modérée": [
419
+ f"{thresholds['asym_low']} à {thresholds['asym_high']} %",
420
+ f"{thresholds['asym_low']} à {thresholds['asym_high']} %",
421
+ f"{thresholds['asym_low']} à {thresholds['asym_high']} %",
422
+ f"{thresholds['rotation_low']} à {thresholds['rotation_high']}°",
423
+ ],
424
+ "Zone marquée": [
425
+ f"> {thresholds['asym_high']} %",
426
+ f"> {thresholds['asym_high']} %",
427
+ f"> {thresholds['asym_high']} %",
428
+ f"> {thresholds['rotation_high']}°",
429
+ ],
430
+ })
431
+
432
+ s1, s2, s3 = st.tabs(["Impact", "Dynamique", "Symétrie"])
433
+ with s1:
434
+ st.dataframe(impact_df, hide_index=True, use_container_width=True)
435
+ with s2:
436
+ st.dataframe(dynamique_df, hide_index=True, use_container_width=True)
437
+ with s3:
438
+ st.dataframe(symetrie_df, hide_index=True, use_container_width=True)
439
+
440
+ st.write(
441
+ "Ces seuils sont individualisés à partir du poids et du volume horaire d’entraînement hebdomadaire. "
442
+ "Ils constituent une base de référence personnelle avant toute analyse ou recommandation."
443
+ )
444
+
445
+ with tab_debug:
446
+ st.subheader("Aide au mapping du CSV Zebris")
447
+ st.write("Colonnes reconnues par l’extracteur :")
448
+ st.json(debug.get("mapping", {}))
449
+ if debug.get("manquantes"):
450
+ st.warning("Colonnes non trouvées : " + ", ".join(debug["manquantes"]))
451
+ else:
452
+ st.success("Toutes les colonnes principales ont été reconnues.")
453
+ with st.expander("Aperçu du tableau standardisé"):
454
+ st.dataframe(df_std, use_container_width=True)