feat: implement base architecture and core repositories for weapon tracking and target analysis functionality

This commit is contained in:
streaper2
2026-05-08 20:29:18 +02:00
parent 5dd58da51c
commit 774dbfcf40
37 changed files with 3687 additions and 2713 deletions

View File

@@ -1,4 +1,5 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:device_info_plus/device_info_plus.dart';
@@ -37,7 +38,7 @@ class AiExportService {
deviceData['os'] = 'Windows ${windowsInfo.majorVersion}.${windowsInfo.minorVersion}';
}
} catch (e) {
print('Erreur lors de la récupération des infos appareil: $e');
debugPrint('Erreur lors de la récupération des infos appareil: $e');
}
return deviceData;
@@ -131,15 +132,15 @@ class AiExportService {
if (response.statusCode == 200) {
final responseData = await response.stream.bytesToString();
print('Export réussi: $responseData');
debugPrint('Export réussi: $responseData');
return true;
} else {
final errorData = await response.stream.bytesToString();
print('Erreur d\'export: ${response.statusCode} - $errorData');
debugPrint('Erreur d\'export: ${response.statusCode} - $errorData');
return false;
}
} catch (e) {
print('Exception lors de l\'export: $e');
debugPrint('Exception lors de l\'export: $e');
return false;
}
}

View File

@@ -8,6 +8,7 @@ library;
import 'dart:io';
import 'dart:math' as math;
import 'package:image/image.dart' as img;
import 'package:flutter/foundation.dart';
import 'package:opencv_dart/opencv_dart.dart' as cv;
import 'package:path_provider/path_provider.dart';
@@ -562,8 +563,9 @@ class DistortionCorrectionService {
double maxArea = 0;
for (final contour in contours) {
if (contour.length < 5)
if (contour.length < 5) {
continue; // fitEllipse nécessite au moins 5 points
}
final area = cv.contourArea(contour);
if (area < 1000) continue; // Ignorer les trop petits bruits
@@ -636,7 +638,7 @@ class DistortionCorrectionService {
return outputPath;
} catch (e) {
// En cas d'erreur, retourner l'image originale
print('Erreur correction perspective cercles: $e');
debugPrint('Erreur correction perspective cercles: $e');
return imagePath;
}
}
@@ -761,7 +763,7 @@ class DistortionCorrectionService {
return outputPath;
} catch (e) {
print('Erreur correction perspective ovales: $e');
debugPrint('Erreur correction perspective ovales: $e');
return imagePath;
}
}
@@ -822,7 +824,7 @@ class DistortionCorrectionService {
}
if (concentricGroup.length < 2) {
print(
debugPrint(
"Pas assez de cercles concentriques pour le maillage, utilisation de la méthode simple.",
);
return await correctPerspectiveUsingOvals(imagePath);
@@ -950,7 +952,7 @@ class DistortionCorrectionService {
return outputPath;
} catch (e) {
print('Erreur correction perspective maillage concentrique: $e');
debugPrint('Erreur correction perspective maillage concentrique: $e');
return imagePath;
}
}
@@ -1012,7 +1014,7 @@ class DistortionCorrectionService {
// Fallback
if (bestQuad == null) {
print(
debugPrint(
"Aucun papier quadrilatère détecté, on utilise les cercles à la place.",
);
return await correctPerspectiveUsingCircles(imagePath);
@@ -1060,7 +1062,7 @@ class DistortionCorrectionService {
return outputPath;
} catch (e) {
print('Erreur correction perspective quadrilatère: $e');
debugPrint('Erreur correction perspective quadrilatère: $e');
// Fallback
return await correctPerspectiveUsingCircles(imagePath);
}

View File

@@ -1,4 +1,5 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'dart:math' as math;
import 'package:image/image.dart' as img;
@@ -189,7 +190,7 @@ class ImageProcessingService {
);
}).toList();
} catch (e) {
print('Error detecting impacts: $e');
debugPrint('Error detecting impacts: $e');
return [];
}
}
@@ -236,14 +237,14 @@ class ImageProcessingService {
final fillRatios = <double>[];
final thresholds = <double>[];
print('Analyzing ${references.length} reference impacts...');
debugPrint('Analyzing ${references.length} reference impacts...');
for (int refIndex = 0; refIndex < references.length; refIndex++) {
final ref = references[refIndex];
final centerX = (ref.x * width).round().clamp(0, width - 1);
final centerY = (ref.y * height).round().clamp(0, height - 1);
print('Reference $refIndex at ($centerX, $centerY)');
debugPrint('Reference $refIndex at ($centerX, $centerY)');
// AMÉLIORATION : Recherche du point le plus sombre dans une zone plus large
int darkestX = centerX;
@@ -275,7 +276,7 @@ class ImageProcessingService {
if (darkestLum < 50 && r > 5) break;
}
print(' Darkest point at ($darkestX, $darkestY), lum=$darkestLum');
debugPrint(' Darkest point at ($darkestX, $darkestY), lum=$darkestLum');
// Now find the blob at the darkest point using adaptive threshold
final blobResult = _findBlobAtPoint(blurred, darkestX, darkestY, width, height);
@@ -286,15 +287,15 @@ class ImageProcessingService {
circularities.add(blobResult.circularity);
fillRatios.add(blobResult.fillRatio);
thresholds.add(blobResult.threshold);
print(' Found blob: size=${blobResult.size}, circ=${blobResult.circularity.toStringAsFixed(2)}, '
debugPrint(' Found blob: size=${blobResult.size}, circ=${blobResult.circularity.toStringAsFixed(2)}, '
'fill=${blobResult.fillRatio.toStringAsFixed(2)}, threshold=${blobResult.threshold.toStringAsFixed(0)}');
} else {
print(' No valid blob found at this reference');
debugPrint(' No valid blob found at this reference');
}
}
if (luminances.isEmpty) {
print('ERROR: No valid blobs found from any reference!');
debugPrint('ERROR: No valid blobs found from any reference!');
return null;
}
@@ -329,11 +330,11 @@ class ImageProcessingService {
avgDarkThreshold: avgThreshold,
);
print('Learned characteristics: $result');
debugPrint('Learned characteristics: $result');
return result;
} catch (e) {
print('Error analyzing reference impacts: $e');
debugPrint('Error analyzing reference impacts: $e');
return null;
}
}
@@ -680,7 +681,7 @@ class ImageProcessingService {
// Calculate minimum fill ratio - impacts pleins
final minFillRatio = (characteristics.avgFillRatio - 0.2).clamp(0.35, 0.85);
print('Detection params: thresholds=$thresholds, size=$minSize-$maxSize, '
debugPrint('Detection params: thresholds=$thresholds, size=$minSize-$maxSize, '
'circ>=$effectiveMinCircularity, fill>=$minFillRatio');
// Détecter avec plusieurs seuils et combiner les résultats
@@ -722,7 +723,7 @@ class ImageProcessingService {
return true;
}).toList();
print('Found ${filteredBlobs.length} impacts after filtering (from ${mergedBlobs.length} merged)');
debugPrint('Found ${filteredBlobs.length} impacts after filtering (from ${mergedBlobs.length} merged)');
// Convert to relative coordinates
return filteredBlobs.map((blob) {
@@ -733,7 +734,7 @@ class ImageProcessingService {
);
}).toList();
} catch (e) {
print('Error detecting impacts from references: $e');
debugPrint('Error detecting impacts from references: $e');
return [];
}
}
@@ -776,50 +777,6 @@ class ImageProcessingService {
return merged;
}
/// Detect dark spots with adaptive luminance range
List<_Blob> _detectDarkSpotsAdaptive(
img.Image image,
int minLuminance,
int maxLuminance,
int minSize,
int maxSize, {
double minCircularity = 0.5,
double minFillRatio = 0.5,
}) {
final width = image.width;
final height = image.height;
// Create binary mask of pixels within luminance range
final mask = List.generate(height, (_) => List.filled(width, false));
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final pixel = image.getPixel(x, y);
final luminance = img.getLuminance(pixel);
mask[y][x] = luminance >= minLuminance && luminance <= maxLuminance;
}
}
// Find connected components
final visited = List.generate(height, (_) => List.filled(width, false));
final blobs = <_Blob>[];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (mask[y][x] && !visited[y][x]) {
final blob = _floodFill(mask, visited, x, y, width, height);
if (blob.size >= minSize &&
blob.size <= maxSize &&
blob.circularity >= minCircularity &&
blob.fillRatio >= minFillRatio) {
blobs.add(blob);
}
}
}
}
return _filterOverlappingBlobs(blobs);
}
/// Detect dark spots in a grayscale image using blob detection
List<_Blob> _detectDarkSpots(

View File

@@ -66,25 +66,12 @@ class PrecisionStats {
/// Standard deviation statistics
class StdDevStats {
/// Standard deviation of X positions
final double stdDevX;
/// Standard deviation of Y positions
final double stdDevY;
/// Combined standard deviation (radial)
final double stdDevRadial;
/// Standard deviation of scores
final double stdDevScore;
/// Mean X position
final double meanX;
/// Mean Y position
final double meanY;
/// Mean score
final double meanScore;
const StdDevStats({
@@ -98,18 +85,11 @@ class StdDevStats {
});
}
/// Regional distribution (quadrants or sectors)
/// Regional distribution
class RegionalStats {
/// Shot distribution by quadrant (top-left, top-right, bottom-left, bottom-right)
final Map<String, int> quadrantDistribution;
/// Shot distribution by sector (N, NE, E, SE, S, SW, W, NW, Center)
final Map<String, int> sectorDistribution;
/// Dominant direction (where most shots land)
final String dominantDirection;
/// Bias offset from center
final double biasX;
final double biasY;
@@ -157,16 +137,16 @@ class StatisticsService {
SessionStatistics calculateStatistics(
List<Session> sessions, {
StatsPeriod period = StatsPeriod.all,
double targetCenterX = 0.5,
double targetCenterY = 0.5,
}) {
// Filter sessions by period
final filteredSessions = _filterByPeriod(sessions, period);
// Collect all shots
// Collect all shots from all analyses in all sessions
final allShots = <Shot>[];
for (final session in filteredSessions) {
allShots.addAll(session.shots);
for (final analysis in session.analyses) {
allShots.addAll(analysis.shots);
}
}
if (allShots.isEmpty) {
@@ -183,14 +163,14 @@ class StatisticsService {
// Calculate heat map
final heatMap = _calculateHeatMap(allShots, gridSize: 5);
// Calculate precision
final precision = _calculatePrecision(allShots, targetCenterX, targetCenterY);
// Calculate precision (using relative center 0.5, 0.5)
final precision = _calculatePrecision(allShots, 0.5, 0.5);
// Calculate standard deviation
final stdDev = _calculateStdDev(allShots);
// Calculate regional distribution
final regional = _calculateRegional(allShots, targetCenterX, targetCenterY);
final regional = _calculateRegional(allShots, 0.5, 0.5);
return SessionStatistics(
totalShots: totalShots,
@@ -224,20 +204,13 @@ class StatisticsService {
/// Calculate heat map
HeatMap _calculateHeatMap(List<Shot> shots, {int gridSize = 5}) {
// Initialize grid
final grid = List.generate(
gridSize,
(_) => List.generate(gridSize, (_) => <Shot>[]),
);
// Assign shots to grid cells
final grid = List.generate(gridSize, (_) => List.generate(gridSize, (_) => <Shot>[]));
for (final shot in shots) {
final col = (shot.x * gridSize).floor().clamp(0, gridSize - 1);
final row = (shot.y * gridSize).floor().clamp(0, gridSize - 1);
grid[row][col].add(shot);
}
// Find max count for normalization
int maxCount = 0;
for (final row in grid) {
for (final cell in row) {
@@ -245,16 +218,12 @@ class StatisticsService {
}
}
// Create heat zones
final zones = <List<HeatZone>>[];
for (int row = 0; row < gridSize; row++) {
final rowZones = <HeatZone>[];
for (int col = 0; col < gridSize; col++) {
final cellShots = grid[row][col];
final avgScore = cellShots.isEmpty
? 0.0
: cellShots.fold<int>(0, (sum, s) => sum + s.score) / cellShots.length;
final avgScore = cellShots.isEmpty ? 0.0 : cellShots.fold<int>(0, (sum, s) => sum + s.score) / cellShots.length;
rowZones.add(HeatZone(
row: row,
col: col,
@@ -266,30 +235,15 @@ class StatisticsService {
zones.add(rowZones);
}
return HeatMap(
gridSize: gridSize,
zones: zones,
maxShotsInZone: maxCount,
totalShots: shots.length,
);
return HeatMap(gridSize: gridSize, zones: zones, maxShotsInZone: maxCount, totalShots: shots.length);
}
/// Calculate precision statistics
PrecisionStats _calculatePrecision(
List<Shot> shots,
double centerX,
double centerY,
) {
PrecisionStats _calculatePrecision(List<Shot> shots, double centerX, double centerY) {
if (shots.isEmpty) {
return const PrecisionStats(
avgDistanceFromCenter: 0,
groupingDiameter: 0,
precisionScore: 0,
consistencyScore: 0,
);
return const PrecisionStats(avgDistanceFromCenter: 0, groupingDiameter: 0, precisionScore: 0, consistencyScore: 0);
}
// Calculate distances from center
final distances = shots.map((shot) {
final dx = shot.x - centerX;
final dy = shot.y - centerY;
@@ -297,8 +251,6 @@ class StatisticsService {
}).toList();
final avgDistance = distances.reduce((a, b) => a + b) / distances.length;
// Calculate grouping (spread between shots)
double maxSpread = 0;
for (int i = 0; i < shots.length; i++) {
for (int j = i + 1; j < shots.length; j++) {
@@ -309,45 +261,29 @@ class StatisticsService {
}
}
// Calculate standard deviation of distances (consistency)
final meanDist = avgDistance;
double variance = 0;
for (final d in distances) {
variance += math.pow(d - meanDist, 2);
variance += math.pow(d - avgDistance, 2);
}
final stdDevDist = math.sqrt(variance / distances.length);
// Precision score: based on average distance from center (0-100)
// 0 distance = 100 score, 0.5 distance = 0 score
final precisionScore = math.max(0, (1 - avgDistance * 2) * 100);
// Consistency score: based on grouping tightness (0-100)
// Lower spread = higher consistency
final consistencyScore = math.max(0, (1 - stdDevDist * 5) * 100);
return PrecisionStats(
avgDistanceFromCenter: avgDistance.toDouble(),
groupingDiameter: maxSpread.toDouble(),
precisionScore: precisionScore.clamp(0.0, 100.0).toDouble(),
consistencyScore: consistencyScore.clamp(0.0, 100.0).toDouble(),
avgDistanceFromCenter: avgDistance,
groupingDiameter: maxSpread,
precisionScore: precisionScore.toDouble().clamp(0.0, 100.0),
consistencyScore: consistencyScore.toDouble().clamp(0.0, 100.0),
);
}
/// Calculate standard deviation statistics
StdDevStats _calculateStdDev(List<Shot> shots) {
if (shots.isEmpty) {
return const StdDevStats(
stdDevX: 0,
stdDevY: 0,
stdDevRadial: 0,
stdDevScore: 0,
meanX: 0.5,
meanY: 0.5,
meanScore: 0,
);
return const StdDevStats(stdDevX: 0, stdDevY: 0, stdDevRadial: 0, stdDevScore: 0, meanX: 0.5, meanY: 0.5, meanScore: 0);
}
// Calculate means
double sumX = 0, sumY = 0, sumScore = 0;
for (final shot in shots) {
sumX += shot.x;
@@ -358,7 +294,6 @@ class StatisticsService {
final meanY = sumY / shots.length;
final meanScore = sumScore / shots.length;
// Calculate variances
double varianceX = 0, varianceY = 0, varianceScore = 0;
for (final shot in shots) {
varianceX += math.pow(shot.x - meanX, 2);
@@ -369,18 +304,11 @@ class StatisticsService {
varianceY /= shots.length;
varianceScore /= shots.length;
final stdDevX = math.sqrt(varianceX);
final stdDevY = math.sqrt(varianceY);
final stdDevScore = math.sqrt(varianceScore);
// Radial standard deviation
final stdDevRadial = math.sqrt(varianceX + varianceY);
return StdDevStats(
stdDevX: stdDevX,
stdDevY: stdDevY,
stdDevRadial: stdDevRadial,
stdDevScore: stdDevScore,
stdDevX: math.sqrt(varianceX),
stdDevY: math.sqrt(varianceY),
stdDevRadial: math.sqrt(varianceX + varianceY),
stdDevScore: math.sqrt(varianceScore),
meanX: meanX,
meanY: meanY,
meanScore: meanScore,
@@ -388,42 +316,13 @@ class StatisticsService {
}
/// Calculate regional distribution
RegionalStats _calculateRegional(
List<Shot> shots,
double centerX,
double centerY,
) {
RegionalStats _calculateRegional(List<Shot> shots, double centerX, double centerY) {
if (shots.isEmpty) {
return const RegionalStats(
quadrantDistribution: {},
sectorDistribution: {},
dominantDirection: 'Centre',
biasX: 0,
biasY: 0,
);
return const RegionalStats(quadrantDistribution: {}, sectorDistribution: {}, dominantDirection: 'Centre', biasX: 0, biasY: 0);
}
// Quadrant distribution
final quadrants = <String, int>{
'Haut-Gauche': 0,
'Haut-Droite': 0,
'Bas-Gauche': 0,
'Bas-Droite': 0,
};
// Sector distribution (8 sectors + center)
final sectors = <String, int>{
'N': 0,
'NE': 0,
'E': 0,
'SE': 0,
'S': 0,
'SO': 0,
'O': 0,
'NO': 0,
'Centre': 0,
};
final quadrants = <String, int>{'Haut-Gauche': 0, 'Haut-Droite': 0, 'Bas-Gauche': 0, 'Bas-Droite': 0};
final sectors = <String, int>{'N': 0, 'NE': 0, 'E': 0, 'SE': 0, 'S': 0, 'SO': 0, 'O': 0, 'NO': 0, 'Centre': 0};
double sumDx = 0, sumDy = 0;
for (final shot in shots) {
@@ -432,16 +331,12 @@ class StatisticsService {
sumDx += dx;
sumDy += dy;
// Quadrant
if (dy < 0) {
quadrants[dx < 0 ? 'Haut-Gauche' : 'Haut-Droite'] =
quadrants[dx < 0 ? 'Haut-Gauche' : 'Haut-Droite']! + 1;
quadrants[dx < 0 ? 'Haut-Gauche' : 'Haut-Droite'] = quadrants[dx < 0 ? 'Haut-Gauche' : 'Haut-Droite']! + 1;
} else {
quadrants[dx < 0 ? 'Bas-Gauche' : 'Bas-Droite'] =
quadrants[dx < 0 ? 'Bas-Gauche' : 'Bas-Droite']! + 1;
quadrants[dx < 0 ? 'Bas-Gauche' : 'Bas-Droite'] = quadrants[dx < 0 ? 'Bas-Gauche' : 'Bas-Droite']! + 1;
}
// Sector
final distance = math.sqrt(dx * dx + dy * dy);
if (distance < 0.1) {
sectors['Centre'] = sectors['Centre']! + 1;
@@ -452,11 +347,6 @@ class StatisticsService {
}
}
// Calculate bias
final biasX = sumDx / shots.length;
final biasY = sumDy / shots.length;
// Find dominant direction
String dominant = 'Centre';
int maxCount = 0;
sectors.forEach((key, value) {
@@ -470,14 +360,12 @@ class StatisticsService {
quadrantDistribution: quadrants,
sectorDistribution: sectors,
dominantDirection: dominant,
biasX: biasX,
biasY: biasY,
biasX: sumDx / shots.length,
biasY: sumDy / shots.length,
);
}
String _angleToSector(double angle) {
// Angle is in degrees, -180 to 180
// 0 = East, 90 = South, -90 = North, 180/-180 = West
if (angle >= -22.5 && angle < 22.5) return 'E';
if (angle >= 22.5 && angle < 67.5) return 'SE';
if (angle >= 67.5 && angle < 112.5) return 'S';
@@ -491,41 +379,12 @@ class StatisticsService {
SessionStatistics _emptyStatistics(StatsPeriod period, List<Session> sessions) {
return SessionStatistics(
totalShots: 0,
totalScore: 0,
avgScore: 0,
maxScore: 0,
minScore: 0,
heatMap: const HeatMap(
gridSize: 5,
zones: [],
maxShotsInZone: 0,
totalShots: 0,
),
precision: const PrecisionStats(
avgDistanceFromCenter: 0,
groupingDiameter: 0,
precisionScore: 0,
consistencyScore: 0,
),
stdDev: const StdDevStats(
stdDevX: 0,
stdDevY: 0,
stdDevRadial: 0,
stdDevScore: 0,
meanX: 0.5,
meanY: 0.5,
meanScore: 0,
),
regional: const RegionalStats(
quadrantDistribution: {},
sectorDistribution: {},
dominantDirection: 'Centre',
biasX: 0,
biasY: 0,
),
sessions: sessions,
period: period,
totalShots: 0, totalScore: 0, avgScore: 0, maxScore: 0, minScore: 0,
heatMap: const HeatMap(gridSize: 5, zones: [], maxShotsInZone: 0, totalShots: 0),
precision: const PrecisionStats(avgDistanceFromCenter: 0, groupingDiameter: 0, precisionScore: 0, consistencyScore: 0),
stdDev: const StdDevStats(stdDevX: 0, stdDevY: 0, stdDevRadial: 0, stdDevScore: 0, meanX: 0.5, meanY: 0.5, meanScore: 0),
regional: const RegionalStats(quadrantDistribution: {}, sectorDistribution: {}, dominantDirection: 'Centre', biasX: 0, biasY: 0),
sessions: sessions, period: period,
);
}
}

View File

@@ -1,4 +1,5 @@
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import '../data/models/target_type.dart';
import 'image_processing_service.dart';
import 'opencv_impact_detection_service.dart';
@@ -320,7 +321,7 @@ class TargetDetectionService {
);
}).toList();
} catch (e) {
print('Erreur détection OpenCV: $e');
debugPrint('Erreur détection OpenCV: $e');
return [];
}
}
@@ -369,7 +370,7 @@ class TargetDetectionService {
);
}).toList();
} catch (e) {
print('Erreur détection OpenCV depuis références: $e');
debugPrint('Erreur détection OpenCV depuis références: $e');
return [];
}
}

View File

@@ -4,6 +4,7 @@ import 'package:crypto/crypto.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io';
import 'package:flutter/foundation.dart';
class WalletIdentityService {
static const String _prefsKey = 'wallet_identity_phrase';
@@ -86,7 +87,7 @@ class WalletIdentityService {
deviceId = windowsInfo.deviceId;
}
} catch (e) {
print('Erreur lecture device ID: $e');
debugPrint('Erreur lecture device ID: $e');
}
// Add a salt to the device ID