# Q-36: Read a results file in the browser

Data-Driven Athletics tutorial · Week 12 · Chapter 12 · about 15 min · workflow steps: Gather, Cleanse

Web page: https://apopt.com/course/tutorials/q36-results-file/ · Data: https://apopt.com/data/tutorials/q36-results-file/

## The decision

Before a jump height from an app goes into the athlete record, check the receipt that came
with it: was the clip analyzed at the frame rate it was filmed at? If not, its times are wrong
even when its height looks right.

## The raw data

- `raw/results/`: SYNTHETIC: seven jump clips' results, each a `.json` receipt and a `.md` text result, written by the jump app's own results code for an invented athlete 1.75 m tall Book example data, Chapter 4 (`book/ch04-python/data/results/`). The format is exact; the jumps never happened.

The course's movement apps write their results next to the video, in your browser, with
nothing uploaded: a report (PDF), a highlight video, the measurements as text (`.md`) and a
**receipt** (`.json`), written last, that records how the analysis was run (Section 4.8).
A page you build can read the same files, also without uploading them: the user drops the
file on the page and the browser reads it locally.

The files here are the book's **synthetic** jump results: seven clips of an invented athlete
1.75 m tall, written by the jump app's own results code. One week-3 clip was filmed at 120
frames per second but analyzed at the 30 its file header claims.

### Open one receipt

*Predict first:* Which field tells you the frame rate the analysis actually used?

```python
import json

r = json.load(open("raw/results/results_jump_wk3_t3.json"))
print("fields:", list(r))
print("input:", r["input"], "| saved:", r["savedAt"])
print("options:", r["options"])
print(f"file says {r['sourceFps']} fps; analysis used {r['actualCaptureFps']} fps; "
      f"analyzed {r['analyzedRange']['start']} to {r['analyzedRange']['end']} s of video")
for w in r["warnings"]:
    print("warning:", w[:90] + "...")
```

Output:

```
fields: ['version', 'savedAt', 'id', 'state', 'stage', 'progress', 'input', 'options', 'warnings', 'outputs', 'sourceFps', 'actualCaptureFps', 'analyzedRange']
input: jump_wk3_t3.mp4 | saved: 2027-01-22T16:09:58.000Z
options: {'captureFps': 'auto', 'heightMeters': 1.75, 'model': 'movenet_thunder', 'outputFormat': 'vertical', 'metricCycleSeconds': 5}
file says 30 fps; analysis used 30 fps; analyzed 0 to 15.9 s of video
warning: This video is 30 fps, so quick moments can fall between frames. If it was filmed in slow m...
warning: The jump measured a 2.07 s flight, more than any person can jump, so the flight time and e...
```

Three frame-rate fields, and they mean different things (checked against the apps' shared
job code, `shared/automation-jobs.ts`): `options.captureFps` is what the user asked for
(`"auto"` means "trust the file"), `sourceFps` is the rate written in the video file, and
`actualCaptureFps` is the rate every time and speed was computed with. In a web page the same
fields are one line away:

```js
const r = JSON.parse(await file.text());   // file: the File the user dropped on the page
if (r.actualCaptureFps !== loggedFps) showWarning(`${r.input}: analyzed at ${r.actualCaptureFps} fps`);
```

### All seven receipts, checked against the session log

A receipt can only say what the app was told. Whether that was right is in your own log: the
week-1 clips were filmed at 30 frames per second, the week-3 clips at 120.

*Predict first:* How many clips will fail the check against the log?

```python
import glob
import pandas as pd

LOG_FPS = {"wk1": 30, "wk3": 120}                     # from the filming log sheet
rows = []
for path in sorted(glob.glob("raw/results/results_*.json")):
    r = json.load(open(path))
    week = r["input"].split("_")[1]
    rows.append({"clip": r["input"], "asked": r["options"]["captureFps"], "file_fps": r["sourceFps"],
                 "used_fps": r["actualCaptureFps"], "warnings": len(r["warnings"]),
                 "ok": r["actualCaptureFps"] == LOG_FPS[week], "md": path.replace(".json", ".md")})
receipts = pd.DataFrame(rows)
print(receipts.drop(columns="md").to_string(index=False))
```

Output:

```
           clip asked  file_fps  used_fps  warnings    ok
jump_wk1_t1.mp4  auto        30        30         1  True
jump_wk1_t2.mp4  auto        30        30         1  True
jump_wk1_t3.mp4  auto        30        30         1  True
jump_wk3_t1.mp4   120        30       120         0  True
jump_wk3_t2.mp4   120        30       120         0  True
jump_wk3_t3.mp4  auto        30        30         2 False
jump_wk3_t4.mp4   120        30       120         0  True
```

### Join the measurement, and draw it

The jump height is in the `.md` file's Metrics table, one row per metric with the unit in the
text (`31.2 cm / 12.3 in`).

```python
import re
import matplotlib.pyplot as plt

def jump_height(md_path):
    m = re.search(r"^\| Jump Outcome \| Jump Height \| ([\d.]+) cm", open(md_path, encoding="utf-8").read(), re.M)
    return float(m.group(1)) if m else None

receipts["height_cm"] = receipts["md"].map(jump_height)
receipts["week"] = receipts["clip"].str.split("_").str[1]
good = receipts[receipts["ok"]].groupby("week")["height_cm"].mean()
print(receipts[["clip", "ok", "height_cm"]].to_string(index=False))
print(f"week 1 mean {good['wk1']:.1f} cm, week 3 mean {good['wk3']:.1f} cm (wrong-rate clip left out)")

fig, ax = plt.subplots(figsize=(6.0, 3.0))
for (wk, ok), d in receipts.groupby(["week", "ok"]):
    style = dict(marker="x", ms=9, color="black") if not ok else dict(marker="o", ms=7, color="black", mfc="white" if wk == "wk1" else "black")
    ax.plot(d.index, d["height_cm"], ls="", label=f"{wk}{'' if ok else ', wrong frame rate'}", **style)
ax.set_xticks(receipts.index, receipts["clip"].str[5:11])
ax.set(xlabel="clip", ylabel="jump height (cm)", title="Week 3 is higher; one clip is left out")
ax.legend(fontsize=8)
plt.tight_layout()
```

Output:

```
           clip    ok  height_cm
jump_wk1_t1.mp4  True       31.2
jump_wk1_t2.mp4  True       29.8
jump_wk1_t3.mp4  True       32.1
jump_wk3_t1.mp4  True       33.5
jump_wk3_t2.mp4  True       34.1
jump_wk3_t3.mp4 False       32.9
jump_wk3_t4.mp4  True       33.8
week 1 mean 31.0 cm, week 3 mean 33.8 cm (wrong-rate clip left out)
```

![Jump height in centimeters for seven clips; week 1 clips as open circles, week 3 clips as filled circles, and the clip analyzed at the wrong frame rate as a cross.](https://apopt.com/course/tutorials/q36-results-file/c05-1.png)

The wrong-rate clip's height looks plausible, because the jump app scales height from the
body, not from the clock; only its times are wrong, which is why the app withheld them and
wrote two warnings. The receipt and your log together catch it; the height alone never would.

**For the athlete:** "Six of your seven clips were analyzed at the rate you filmed them; we
left the seventh out, and your week-3 jumps average about 3 cm higher than week 1."

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
