kovinar update code

This commit is contained in:
2026-10-31 15:27:32 +01:00
parent 9d9e0c77f2
commit df85d36c75
5 changed files with 967 additions and 456 deletions
+102 -17
View File
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:path_provider/path_provider.dart';
/// One saved target (a JSON file written by the preview screen).
@@ -45,42 +46,74 @@ class Session {
/// Aggregates over any set of sessions (trainings or tournaments of one format).
class ShooterStats {
static const int trendWindow = 5;
final int sessions;
final int targets;
final int shots;
final TargetRecord? best;
final Session? bestSession; // highest average per shot
final double? averageTarget;
final double? averagePerShot;
final double? trend; // last sessions minus the ones before them, per shot
const ShooterStats._({
required this.sessions,
required this.targets,
required this.shots,
required this.best,
required this.bestSession,
required this.averageTarget,
required this.averagePerShot,
required this.trend,
});
/// [sessions] newest first, as [TargetRepository.loadSessions] returns them.
factory ShooterStats.of(List<Session> sessions) {
final all = [for (final s in sessions) ...s.targets];
final shots = all.fold(0, (sum, t) => sum + t.shots);
final total = all.fold(0, (sum, t) => sum + t.score);
final ranked = [...all]..sort((a, b) => b.score.compareTo(a.score));
final mean = all.isEmpty ? null : total / all.length;
Session? bestSession;
for (final s in sessions) {
final avg = s.averagePerShot;
if (avg != null &&
(bestSession == null || avg > bestSession.averagePerShot!)) {
bestSession = s;
}
}
return ShooterStats._(
sessions: sessions.length,
targets: all.length,
shots: shots,
best: ranked.isEmpty ? null : ranked.first,
bestSession: bestSession,
averageTarget: mean,
averagePerShot: shots == 0 ? null : total / shots,
trend: _trend(sessions),
);
}
// Average per shot of the newest sessions minus the same number before them
static double? _trend(List<Session> newestFirst) {
final scored = newestFirst.where((s) => s.shots > 0).toList();
final n = min(trendWindow, scored.length ~/ 2);
if (n == 0) return null;
double avg(Iterable<Session> list) =>
list.fold(0, (a, s) => a + s.totalScore) /
list.fold(0, (a, s) => a + s.shots);
return avg(scored.take(n)) - avg(scored.skip(n).take(n));
}
}
/// Reads and edits the saved targets under <documents>/saved_images/<session>/.
///
/// Score and shots of every target are cached in <documents>/target_index.json,
/// keyed by the file's path with its size and last change, so loading reads one
/// file instead of every target. A new, edited or renamed target no longer
/// matches its entry and is read again; entries of deleted files are dropped.
class TargetRepository {
static Map<String, dynamic>? _index; // path in saved_images -> entry
static Future<Directory> _root() async {
final dir = Directory(
'${(await getApplicationDocumentsDirectory()).path}/saved_images');
@@ -88,15 +121,56 @@ class TargetRepository {
return dir;
}
/// Sessions, newest first. With [year], only that year's target files are read.
static Future<List<Session>> loadSessions({int? year}) async {
static Future<File> _indexFile() async => File(
'${(await getApplicationDocumentsDirectory()).path}/target_index.json');
static Future<Map<String, dynamic>> _loadIndex() async {
if (_index != null) return _index!;
try {
final file = await _indexFile();
_index = await file.exists()
? jsonDecode(await file.readAsString()) as Map<String, dynamic>
: {};
} catch (_) {
_index = {}; // unreadable: rebuild it from the targets
}
return _index!;
}
/// Sessions, newest first.
static Future<List<Session>> loadSessions() async {
final sessions = <Session>[];
final index = await _loadIndex();
final seen = <String>{};
var changed = false;
for (final folder in await _folders()) {
if (year != null && folder.date.year != year) continue;
final targets = <TargetRecord>[];
for (final file in folder.targetFiles) {
final record = await _readTarget(file);
final key = '${folder.name}/${file.uri.pathSegments.last}';
seen.add(key);
final stat = file.statSync();
final stamp = '${stat.size}:${stat.modified.millisecondsSinceEpoch}';
final cached = index[key];
TargetRecord? record;
if (cached is Map && cached['stamp'] == stamp) {
record = TargetRecord(
file: file,
shotAt: _timeFromFileName(file) ?? stat.modified,
score: cached['score'] as int,
shots: cached['shots'] as int,
);
} else {
record = await _readTarget(file);
if (record != null) {
index[key] = {
'stamp': stamp,
'score': record.score,
'shots': record.shots
};
changed = true;
}
}
if (record != null) targets.add(record);
}
targets.sort((a, b) => a.shotAt.compareTo(b.shotAt));
@@ -108,16 +182,20 @@ class TargetRepository {
));
}
final before = index.length;
index.removeWhere((key, _) => !seen.contains(key));
if (changed || index.length != before) {
try {
await (await _indexFile()).writeAsString(jsonEncode(index));
} catch (_) {
// Only a cache: the next load reads the targets again
}
}
sessions.sort((a, b) => b.date.compareTo(a.date));
return sessions;
}
/// Years that have at least one session, newest first. Reads only metadata.
static Future<List<int>> years() async {
final years = {for (final f in await _folders()) f.date.year}.toList();
return years..sort((a, b) => b.compareTo(a));
}
// Cheap pass over the folders: metadata + file names, no target files read
static Future<List<_FolderInfo>> _folders() async {
final root = await _root();
@@ -128,12 +206,15 @@ class TargetRepository {
for (final f in folder.listSync().whereType<File>())
if (f.path.endsWith('.json') && !f.path.endsWith('metadata.json')) f,
];
final fileTimes = files.map(_timeFromFileName).whereType<DateTime>().toList()..sort();
final fileTimes =
files.map(_timeFromFileName).whereType<DateTime>().toList()..sort();
result.add(_FolderInfo(
name: folder.path.split('/').last,
isTournament: meta['isTournament'] == true,
date: DateTime.tryParse(meta['createdAt'] ?? '') ??
(fileTimes.isNotEmpty ? fileTimes.first : folder.statSync().changed),
(fileTimes.isNotEmpty
? fileTimes.first
: folder.statSync().changed),
targetFiles: files,
));
}
@@ -213,5 +294,9 @@ class _FolderInfo {
final DateTime date;
final List<File> targetFiles;
const _FolderInfo({required this.name, required this.isTournament, required this.date, required this.targetFiles});
const _FolderInfo(
{required this.name,
required this.isTournament,
required this.date,
required this.targetFiles});
}