optimization of the detection algorithem.

BOOK update.
This commit is contained in:
Jan Pleterski
2026-11-27 09:43:25 +01:00
parent b22d7987e3
commit 5f9e2a3b86
11 changed files with 1209 additions and 542 deletions
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Fill the debug app on an emulator with realistic saved targets.
python3 tool/seed_debug_data.py # add the debug sessions
python3 tool/seed_debug_data.py --remove # remove them again
PACKAGE=si.sdkkovinar.app.test ANDROID_SERIAL=<device> python3 tool/seed_debug_data.py
Writes trainings and tournaments over 2025-2026 into the app's
app_flutter/saved_images/, in the same format preview_screen saves:
<session>/metadata.json {"isTournament", "createdAt"}
<session>/target_<y>-<m>-<d>_<h>-<m>-<s>.json {"date", "totalScore", "bulletCount", "bullets", "scores"}
Bullets are in the default target's 1200x1200 coordinates. Scoring and the
placement of hand-entered shots follow lib/utils/target_scoring.dart, so the
saved scores, the totals in Knjiga and the dots in the preview all agree.
camera - scattered around the centre, as detection finds them
manual - in the middle of the ring that gives the entered score, as the
missing-bullet dialog places them
mix - some of each; some targets also have a missed (unscored) shot
Needs a debug build (run-as) on the device adb talks to. Only touches the
session folders listed below; your other sessions stay as they are.
"""
import io
import json
import math
import os
import shlex
import random
import subprocess
import sys
import tarfile
import time
from datetime import datetime
# PACKAGE=si.sdkkovinar.app.test for the side-by-side test install;
# ANDROID_SERIAL=<id> picks the device when several are connected (adb reads it)
PACKAGE = os.environ.get('PACKAGE', 'si.sdkkovinar.app')
ADB = os.environ.get('ADB', os.path.expanduser('~/Android/Sdk/platform-tools/adb'))
ROOT = 'app_flutter/saved_images'
# Same geometry as lib/utils/target_scoring.dart (TargetScoring)
CENTER = (601, 598)
BULLET_RADIUS = 25
RINGS = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510]
# (date, name, tournament, shots per target, targets, mode, spread)
# spread = how far camera shots scatter (px); it shrinks over time, so the
# graph shows a shooter getting better.
SESSIONS = [
('2025-06-12 18:10', 'Trening 2', False, 5, 3, 'camera', 190),
('2025-09-20 09:30', 'Liga – 1. krog', True, 5, 4, 'mix', 175),
('2025-12-05 18:40', 'Trening 3', False, 3, 2, 'manual', 170),
('2026-01-15 18:05', 'Trening 4', False, 5, 3, 'camera', 165),
('2026-02-22 10:00', 'Liga – 2. krog', True, 5, 6, 'mix', 160),
('2026-03-18 18:20', 'Trening 5', False, 5, 2, 'manual', 155),
('2026-04-09 17:45', 'Trening 6', False, 1, 5, 'camera', 150),
('2026-05-30 09:15', 'Regijsko prvenstvo', True, 5, 4, 'camera', 140),
('2026-07-04 18:30', 'Trening 7', False, 5, 3, 'mix', 135),
('2026-08-21 18:00', 'Trening 8', False, 3, 3, 'camera', 130),
('2026-09-13 09:45', 'Liga – 3. krog', True, 5, 5, 'mix', 125),
('2026-10-02 18:15', 'Trening 9', False, 5, 3, 'camera', 120),
('2026-10-16 18:25', 'Trening 10', False, 5, 4, 'manual', 115),
('2026-10-29 18:05', 'Trening 11', False, 5, 3, 'mix', 110),
('2026-11-05 18:10', 'Trening 12', False, 5, 3, 'camera', 105),
('2026-11-19 18:35', 'Trening 13', False, 5, 4, 'mix', 100),
('2026-11-22 09:30', 'Liga – 4. krog', True, 5, 5, 'camera', 95),
('2026-11-24 18:20', 'Trening 14', False, 5, 3, 'manual', 90),
]
def score(x, y):
edge = math.dist((x, y), CENTER) - BULLET_RADIUS
for i, r in enumerate(RINGS):
if edge <= r:
return 10 - i
return 0
def camera_bullet(rng, spread):
# Gaussian scatter, kept on the 1200x1200 target
while True:
x = rng.gauss(CENTER[0], spread)
y = rng.gauss(CENTER[1], spread)
if 30 < x < 1170 and 30 < y < 1170:
return x, y
def manual_bullet(rng, index, shots, value):
# Same placement as TargetScoring.positionFor: middle of the band that
# scores [value], measured to the bullet's edge
if value == 10:
edge = (-BULLET_RADIUS + RINGS[0]) / 2
elif value == 0:
edge = RINGS[-1] + 30
else:
edge = (RINGS[9 - value] + RINGS[10 - value]) / 2
distance = edge + BULLET_RADIUS
step = 360 / shots
angle = math.radians(step * index + (rng.random() - 0.5) * step * 0.5)
return CENTER[0] + distance * math.cos(angle), CENTER[1] + distance * math.sin(angle)
def target(rng, shots, mode, spread):
bullets, scores = [], []
# A missed shot now and then: counted in bulletCount, absent from bullets
missed = 1 if mode == 'mix' and shots > 1 and rng.random() < 0.35 else 0
for i in range(shots - missed):
manual = mode == 'manual' or (mode == 'mix' and rng.random() < 0.4)
if manual:
value = max(4, min(10, round(rng.gauss(10 - spread / 35, 1.5))))
x, y = manual_bullet(rng, i, shots, value)
else:
x, y = camera_bullet(rng, spread)
# Round first, then score what is actually saved
x, y = round(x, 2), round(y, 2)
s = score(x, y)
if manual:
assert s == value, f'hand-entered {value} placed where it scores {s}'
bullets.append({'x': x, 'y': y})
scores.append(s)
return {'bullets': bullets, 'scores': scores, 'totalScore': sum(scores),
'bulletCount': shots}
def build_tar():
rng = random.Random(2026) # same data every run
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode='w') as tar:
def add(path, data):
raw = json.dumps(data).encode()
info = tarfile.TarInfo(path)
info.size = len(raw)
info.mtime = time.time()
tar.addfile(info, io.BytesIO(raw))
for when, name, tournament, shots, count, mode, spread in SESSIONS:
start = datetime.strptime(when, '%Y-%m-%d %H:%M')
add(f'{name}/metadata.json',
{'isTournament': tournament, 'createdAt': start.isoformat()})
for n in range(count):
t = datetime.fromtimestamp(start.timestamp() + n * 7 * 60 + rng.randint(0, 120))
data = target(rng, shots, mode, spread)
# File name and date exactly as preview_screen _performSave writes them
file = f'target_{t.year}-{t.month}-{t.day}_{t.hour}-{t.minute}-{t.second}.json'
add(f'{name}/{file}', {'date': t.strftime('%d/%m/%Y'), **data})
print(f'{name:22} {file:40} {data["totalScore"]:3} / {shots} shots'
f' ({len(data["bullets"])} bullets, {mode})')
return buf.getvalue()
DEVICE_TAR = '/data/local/tmp/kovinar_seed.tar'
def run_as(command):
# adb joins the arguments into one device command line, so quote the script
return subprocess.run([ADB, 'shell', 'run-as', PACKAGE, 'sh', '-c', shlex.quote(command)],
capture_output=True, check=True)
def main():
names = ' '.join(f"'{s[1]}'" for s in SESSIONS)
if '--remove' in sys.argv:
run_as(f'cd {ROOT} && rm -rf {names}')
print('Removed the debug sessions.')
return
archive = build_tar()
# Data piped into run-as does not arrive, so go through the shared temp
# folder: adb pushes the archive there and the app unpacks it.
local = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.seed.tar')
try:
with open(local, 'wb') as f:
f.write(archive)
subprocess.run([ADB, 'push', local, DEVICE_TAR], capture_output=True, check=True)
finally:
os.remove(local)
subprocess.run([ADB, 'shell', 'chmod', '644', DEVICE_TAR], check=True)
try:
# Replace earlier copies so re-running gives the same data
run_as(f'mkdir -p {ROOT} && cd {ROOT} && rm -rf {names} && tar xf {DEVICE_TAR}')
finally:
subprocess.run([ADB, 'shell', 'rm', '-f', DEVICE_TAR], check=True)
# adb does not always pass the device's exit code back: check the result
listing = run_as(f'ls {ROOT}').stdout.decode()
missing = [s[1] for s in SESSIONS if s[1] not in listing.splitlines()]
if missing:
sys.exit(f'\nPush failed, missing on the device: {", ".join(missing)}\n'
f'Is the debug build of {PACKAGE} installed?\n{listing.strip()}')
print(f'\nWrote {len(SESSIONS)} sessions. Reopen Knjiga (or pull to refresh) to see them.')
if __name__ == '__main__':
main()