File size: 59,667 Bytes
87a2e39 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 |
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:typed_data';
import 'dart:convert';
import 'dart:async';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:mime/mime.dart';
import 'package:path/path.dart' as path;
import 'package:http_parser/http_parser.dart';
import 'dart:math' as math;
import 'package:file_picker/file_picker.dart';
// Modèles de données pour l'API
class AnalysisResult {
final bool isTuberculosis;
final double confidence;
final String stage;
final String stageDescription;
final int noduleCount;
final String analyzedImageBase64;
final List<String> recommendations;
AnalysisResult({
required this.isTuberculosis,
required this.confidence,
required this.stage,
required this.stageDescription,
required this.noduleCount,
required this.analyzedImageBase64,
required this.recommendations,
});
factory AnalysisResult.fromJson(Map<String, dynamic> json) {
return AnalysisResult(
isTuberculosis: json['is_tuberculosis'] ?? false,
confidence: (json['confidence'] ?? 0.0).toDouble(),
stage: json['stage'] ?? 'unknown',
stageDescription: json['stage_description'] ?? '',
noduleCount: json['nodule_count'] ?? 0,
analyzedImageBase64: json['analyzed_image_base64'] ?? '',
recommendations: List<String>.from(json['recommendations'] ?? []),
);
}
}
// Service pour interagir avec l'API - VERSION CORRIGÉE
class TuberculosisApiService {
// URL de votre API déployée sur Render - VÉRIFIEZ CETTE URL
static const String baseUrl = 'https://tuberculose-k708.onrender.com';
// IMPORTANT: Assurez-vous que cette URL correspond exactement à votre déploiement Render
// Formats d'image acceptés
static const List<String> allowedFormats = ['jpg', 'jpeg', 'png', 'bmp'];
// Configuration des timeouts pour les services cloud
static const Duration apiTimeout = Duration(seconds: 120);
static const Duration healthTimeout = Duration(seconds: 30);
static const Duration wakeupTimeout = Duration(seconds: 60);
// Méthode pour vérifier et afficher l'URL actuelle
static void debugApiUrl() {
debugPrint('=== CONFIGURATION API ===');
debugPrint('URL de base: $baseUrl');
debugPrint('URL health: $baseUrl/health');
debugPrint('URL analyze: $baseUrl/analyze');
debugPrint('URL model-info: $baseUrl/model-info');
debugPrint('========================');
}
static Future<AnalysisResult> analyzeImage(File imageFile) async {
try {
debugPrint('=== DÉBUT ANALYSE IMAGE ===');
debugApiUrl(); // Afficher l'URL pour debugging
// Vérification de l'existence du fichier
if (!await imageFile.exists()) {
throw Exception('Le fichier image n\'existe pas');
}
// Vérification de la taille du fichier (max 10MB)
final fileSize = await imageFile.length();
if (fileSize > 10 * 1024 * 1024) {
throw Exception('Le fichier est trop volumineux (max 10MB)');
}
// Vérification du format de fichier par extension
final extension =
path.extension(imageFile.path).toLowerCase().replaceFirst('.', '');
if (!allowedFormats.contains(extension)) {
throw Exception(
'Format de fichier non supporté. Utilisez: ${allowedFormats.join(', ')}');
}
debugPrint('Chemin du fichier: ${imageFile.path}');
debugPrint('Taille du fichier: $fileSize bytes');
debugPrint('Extension: $extension');
// S'assurer que le service est réveillé avant l'analyse
await wakeUpService();
// Lire les bytes du fichier
final bytes = await imageFile.readAsBytes();
if (bytes.isEmpty) {
throw Exception('Le fichier image est vide');
}
debugPrint('Bytes lus: ${bytes.length}');
// Détection du type MIME
final mimeType = lookupMimeType(imageFile.path) ??
_getMimeTypeFromExtension(extension);
debugPrint('Type MIME détecté: $mimeType');
// Création de l'URL complète
final analyzeUrl = '$baseUrl/analyze';
debugPrint('URL complète pour l\'analyse: $analyzeUrl');
// Création de la requête multipart
var request = http.MultipartRequest(
'POST',
Uri.parse(analyzeUrl),
);
// Ajout des en-têtes
request.headers.addAll({
'Accept': 'application/json',
'User-Agent': 'TuberculosisAnalyzer/1.0',
'Connection': 'keep-alive',
});
// Création du fichier multipart
var multipartFile = http.MultipartFile.fromBytes(
'file', // Nom du champ attendu par l'API
bytes,
filename: path.basename(imageFile.path),
contentType: MediaType.parse(mimeType),
);
request.files.add(multipartFile);
debugPrint('Envoi de la requête vers: ${request.url}');
debugPrint('Nom du fichier: ${multipartFile.filename}');
debugPrint('Content-Type: ${multipartFile.contentType}');
// Envoi avec timeout adapté pour les services cloud
var streamedResponse = await request.send().timeout(
apiTimeout,
onTimeout: () {
throw TimeoutException('Timeout: L\'analyse prend trop de temps');
},
);
var response = await http.Response.fromStream(streamedResponse);
debugPrint('Code de réponse: ${response.statusCode}');
debugPrint('En-têtes de réponse: ${response.headers}');
debugPrint(
'Début du corps de la réponse: ${response.body.substring(0, math.min(200, response.body.length))}...');
if (response.statusCode == 200) {
try {
var jsonData = json.decode(response.body);
debugPrint('Parsing JSON réussi');
return AnalysisResult.fromJson(jsonData);
} catch (e) {
debugPrint('Erreur de parsing JSON: $e');
throw Exception('Erreur de parsing JSON: $e');
}
} else {
// Gestion des erreurs avec plus de détails
String errorMessage = 'Erreur ${response.statusCode}';
try {
var errorData = json.decode(response.body);
if (errorData is Map<String, dynamic>) {
errorMessage =
errorData['detail'] ?? errorData['message'] ?? errorMessage;
}
} catch (_) {
errorMessage =
response.body.isNotEmpty ? response.body : errorMessage;
}
debugPrint('Erreur API: $errorMessage');
throw Exception('Erreur API: $errorMessage');
}
} on SocketException catch (e) {
debugPrint('Erreur de socket: $e');
throw Exception(
'Erreur de connexion réseau: Impossible de contacter le serveur à $baseUrl. Vérifiez votre connexion internet.');
} on TimeoutException catch (e) {
debugPrint('Timeout: $e');
throw Exception(
'Timeout: Le serveur met trop de temps à répondre. Les services cloud peuvent être lents au démarrage.');
} on HandshakeException catch (e) {
debugPrint('Erreur SSL/TLS: $e');
throw Exception(
'Erreur de sécurité SSL: Problème avec le certificat du serveur');
} on FormatException catch (e) {
debugPrint('Erreur de format: $e');
throw Exception('Erreur de format de données: $e');
} catch (e) {
debugPrint('Erreur générale: $e');
if (e.toString().contains('Exception:')) {
rethrow;
}
throw Exception('Erreur inattendue: $e');
}
}
// Méthode utilitaire pour obtenir le type MIME depuis l'extension
static String _getMimeTypeFromExtension(String extension) {
switch (extension.toLowerCase()) {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'gif':
return 'image/gif';
case 'bmp':
return 'image/bmp';
case 'webp':
return 'image/webp';
case 'tiff':
case 'tif':
return 'image/tiff';
default:
return 'image/jpeg'; // Par défaut
}
}
static Future<Map<String, dynamic>> getHealthStatus() async {
try {
debugPrint('=== VÉRIFICATION SANTÉ API ===');
debugApiUrl(); // Afficher l'URL pour debugging
final healthUrl = '$baseUrl/health';
debugPrint('URL health check: $healthUrl');
var response = await http.get(
Uri.parse(healthUrl),
headers: {
'Accept': 'application/json',
'User-Agent': 'TuberculosisAnalyzer/1.0',
'Connection': 'keep-alive',
},
).timeout(healthTimeout);
debugPrint('Health check - Code: ${response.statusCode}');
debugPrint('Health check - Body: ${response.body}');
if (response.statusCode == 200) {
try {
return json.decode(response.body);
} catch (e) {
debugPrint('Erreur parsing JSON health: $e');
// Si le JSON n'est pas valide mais que le serveur répond 200
return {'status': 'ok', 'message': 'Service disponible'};
}
} else {
throw Exception('API non disponible (Code: ${response.statusCode})');
}
} on SocketException catch (e) {
debugPrint('Health check - Erreur socket: $e');
throw Exception(
'Serveur non accessible à $baseUrl: Vérifiez l\'URL et votre connexion internet');
} on TimeoutException catch (e) {
debugPrint('Health check - Timeout: $e');
throw Exception(
'Timeout: Le service cloud peut être en cours de démarrage (cela peut prendre 1-2 minutes)');
} on HandshakeException catch (e) {
debugPrint('Health check - Erreur SSL: $e');
throw Exception('Erreur de sécurité SSL');
} catch (e) {
debugPrint('Health check - Erreur: $e');
if (e.toString().contains('Exception:')) {
rethrow;
}
throw Exception('Erreur de connexion: $e');
}
}
static Future<Map<String, dynamic>> getModelInfo() async {
try {
debugPrint('=== RÉCUPÉRATION INFOS MODÈLE ===');
debugApiUrl(); // Afficher l'URL pour debugging
final modelInfoUrl = '$baseUrl/model-info';
debugPrint('URL model info: $modelInfoUrl');
var response = await http.get(
Uri.parse(modelInfoUrl),
headers: {
'Accept': 'application/json',
'User-Agent': 'TuberculosisAnalyzer/1.0',
'Connection': 'keep-alive',
},
).timeout(healthTimeout);
debugPrint('Model info - Code: ${response.statusCode}');
debugPrint('Model info - Body: ${response.body}');
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception(
'Impossible d\'obtenir les infos du modèle (Code: ${response.statusCode})');
}
} on SocketException catch (e) {
debugPrint('Model info - Erreur socket: $e');
throw Exception(
'Serveur non accessible à $baseUrl: Vérifiez votre connexion internet');
} on TimeoutException catch (e) {
debugPrint('Model info - Timeout: $e');
throw Exception('Timeout lors de la récupération des infos du modèle');
} on HandshakeException catch (e) {
debugPrint('Model info - Erreur SSL: $e');
throw Exception('Erreur de sécurité SSL');
} catch (e) {
debugPrint('Model info - Erreur: $e');
if (e.toString().contains('Exception:')) {
rethrow;
}
throw Exception('Erreur: $e');
}
}
// Méthode pour réveiller le service (utile pour les services cloud qui se mettent en veille)
static Future<void> wakeUpService() async {
try {
debugPrint('=== RÉVEIL DU SERVICE ===');
debugPrint('Tentative de réveil du service...');
final wakeupUrl = '$baseUrl/health';
debugPrint('URL de réveil: $wakeupUrl');
await http.get(
Uri.parse(wakeupUrl),
headers: {
'Accept': 'application/json',
'User-Agent': 'TuberculosisAnalyzer/1.0',
'Connection': 'keep-alive',
},
).timeout(wakeupTimeout);
debugPrint('Service réveillé avec succès');
} catch (e) {
debugPrint('Erreur lors du réveil du service (non critique): $e');
// Ne pas lever d'exception car c'est juste pour réveiller le service
}
}
// Méthode pour tester la connectivité
static Future<bool> testConnectivity() async {
try {
debugPrint('=== TEST DE CONNECTIVITÉ ===');
debugApiUrl(); // Afficher l'URL pour debugging
final testUrl = '$baseUrl/health';
debugPrint('URL de test: $testUrl');
final response = await http.get(
Uri.parse(testUrl),
headers: {
'Accept': 'application/json',
'User-Agent': 'TuberculosisAnalyzer/1.0',
},
).timeout(Duration(seconds: 10));
debugPrint('Test connectivité - Code: ${response.statusCode}');
return response.statusCode == 200;
} catch (e) {
debugPrint('Test connectivité - Erreur: $e');
return false;
}
}
// Méthode pour valider l'URL de l'API
static bool validateApiUrl() {
try {
final uri = Uri.parse(baseUrl);
final isValid = uri.scheme == 'https' &&
uri.host.isNotEmpty &&
!uri.host.contains('localhost') &&
!uri.host.contains('127.0.0.1');
debugPrint('=== VALIDATION URL ===');
debugPrint('URL: $baseUrl');
debugPrint('Scheme: ${uri.scheme}');
debugPrint('Host: ${uri.host}');
debugPrint('Valid: $isValid');
debugPrint('==================');
return isValid;
} catch (e) {
debugPrint('Erreur de validation URL: $e');
return false;
}
}
}
// Ajout des imports nécessaires en haut du fichier
// Ajout des imports nécessaires en haut du fichier
// Widget principal de l'application
class TuberculosisAnalyzerApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Analyseur de Tuberculose',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
// Page d'accueil
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? _selectedImage;
AnalysisResult? _analysisResult;
bool _isAnalyzing = false;
String? _errorMessage;
bool _isApiHealthy = false;
bool _isCheckingHealth = false;
String _healthStatus = 'Vérification...';
@override
void initState() {
super.initState();
_checkApiHealth();
}
Future<void> _checkApiHealth() async {
setState(() {
_isCheckingHealth = true;
_healthStatus = 'Vérification en cours...';
});
try {
debugPrint('=== DIAGNOSTIC DE CONNEXION ===');
// Étape 0: Validation de l'URL
setState(() {
_healthStatus = 'Validation de l\'URL...';
});
if (!TuberculosisApiService.validateApiUrl()) {
throw Exception(
'URL de l\'API invalide: ${TuberculosisApiService.baseUrl}');
}
// Étape 1: Test de connectivité basique
setState(() {
_healthStatus = 'Test de connectivité...';
});
final isConnected = await TuberculosisApiService.testConnectivity();
if (!isConnected) {
throw Exception(
'Impossible de contacter le serveur à l\'adresse: ${TuberculosisApiService.baseUrl}');
}
// Étape 2: Réveil du service
setState(() {
_healthStatus = 'Réveil du service cloud...';
});
await TuberculosisApiService.wakeUpService();
// Étape 3: Vérification complète
setState(() {
_healthStatus = 'Vérification des services...';
});
final healthData = await TuberculosisApiService.getHealthStatus();
setState(() {
_isApiHealthy = true;
_errorMessage = null;
_healthStatus = 'Service connecté et fonctionnel ✓';
});
// Afficher les informations du service si disponibles
if (healthData.containsKey('status')) {
debugPrint('Statut du service: ${healthData['status']}');
}
// Afficher un message de succès
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Connexion à l\'API établie avec succès !'),
backgroundColor: Colors.green,
duration: Duration(seconds: 2),
),
);
} catch (e) {
debugPrint('Erreur lors de la vérification: $e');
setState(() {
_isApiHealthy = false;
_errorMessage = e.toString();
// Messages d'erreur plus informatifs
if (e.toString().contains('localhost') ||
e.toString().contains('127.0.0.1')) {
_healthStatus = 'ERREUR: Configuration localhost détectée !';
} else if (e.toString().contains('URL de l\'API invalide')) {
_healthStatus = 'Configuration d\'URL incorrecte';
} else if (e.toString().contains('Failed to fetch')) {
_healthStatus = 'Service non accessible - Vérifiez le déploiement';
} else if (e.toString().contains('Timeout')) {
_healthStatus = 'Service en cours de démarrage (services cloud)';
} else if (e.toString().contains('SocketException')) {
_healthStatus = 'Problème de connexion réseau';
} else {
_healthStatus = 'Service temporairement indisponible';
}
});
// Afficher une alerte avec plus de détails
if (e.toString().contains('localhost')) {
_showLocalhostWarning();
}
} finally {
setState(() {
_isCheckingHealth = false;
});
}
}
void _showLocalhostWarning() {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Row(
children: [
Icon(Icons.warning, color: Colors.red),
SizedBox(width: 8),
Text('Configuration Localhost'),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'PROBLÈME DÉTECTÉ:',
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
),
SizedBox(height: 8),
Text(
'Votre application essaie de se connecter à localhost, mais vous devez utiliser l\'URL de votre API déployée sur Render.'),
SizedBox(height: 16),
Text(
'URL ACTUELLE:',
style: TextStyle(fontWeight: FontWeight.bold),
),
Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.red[50],
borderRadius: BorderRadius.circular(4),
),
child: Text(
TuberculosisApiService.baseUrl,
style: TextStyle(fontFamily: 'monospace', color: Colors.red),
),
),
SizedBox(height: 16),
Text(
'SOLUTION:',
style:
TextStyle(fontWeight: FontWeight.bold, color: Colors.green),
),
SizedBox(height: 8),
Text('1. Vérifiez que votre API est déployée sur Render'),
Text('2. Copiez l\'URL de votre déploiement Render'),
Text('3. Remplacez l\'URL dans le code source'),
Text('4. Recompilez l\'application'),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Compris'),
),
],
),
);
}
Widget _buildApiStatusCard() {
return Card(
color: _isApiHealthy
? Colors.green[50]
: _isCheckingHealth
? Colors.blue[50]
: Colors.red[50],
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (_isCheckingHealth)
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
else
Icon(
_isApiHealthy ? Icons.check_circle : Icons.error,
color: _isApiHealthy ? Colors.green : Colors.red,
),
SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_healthStatus,
style: TextStyle(
color: _isApiHealthy
? Colors.green[800]
: _isCheckingHealth
? Colors.blue[800]
: Colors.red[800],
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 4),
Text(
'API: ${TuberculosisApiService.baseUrl}',
style: TextStyle(
color: Colors.grey[600],
fontSize: 11,
fontFamily: 'monospace',
),
),
],
),
),
],
),
if (!_isApiHealthy && !_isCheckingHealth) ...[
SizedBox(height: 12),
Text(
'Problèmes possibles:',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red[700],
),
),
SizedBox(height: 4),
Text(
'• Vérifiez votre connexion internet\n'
'• Le service cloud peut prendre 1-2 minutes à démarrer\n'
'• L\'URL de l\'API est-elle correcte?\n'
'• Le service est-il déployé et actif?',
style: TextStyle(
color: Colors.red[600],
fontSize: 12,
),
),
SizedBox(height: 8),
Row(
children: [
ElevatedButton.icon(
onPressed: _checkApiHealth,
icon: Icon(Icons.refresh),
label: Text('Réessayer'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red[100],
foregroundColor: Colors.red[800],
),
),
SizedBox(width: 8),
TextButton(
onPressed: () => _showConnectionDiagnostic(),
child: Text('Diagnostic'),
),
],
),
],
],
),
),
);
}
// Méthode pour afficher le diagnostic de connexion
void _showConnectionDiagnostic() {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Diagnostic de connexion'),
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text('Configuration actuelle:',
style: TextStyle(fontWeight: FontWeight.bold)),
SizedBox(height: 8),
Container(
padding: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(4),
),
child: Text(
'URL API: ${TuberculosisApiService.baseUrl}',
style: TextStyle(fontFamily: 'monospace', fontSize: 12),
),
),
SizedBox(height: 16),
Text('Vérifications:',
style: TextStyle(fontWeight: FontWeight.bold)),
SizedBox(height: 8),
Text('✓ L\'URL ne contient pas "localhost"'),
Text('✓ L\'URL utilise HTTPS'),
Text('✓ L\'URL se termine par ".onrender.com"'),
SizedBox(height: 16),
Text('Si le problème persiste:',
style: TextStyle(fontWeight: FontWeight.bold)),
SizedBox(height: 8),
Text(
'1. Vérifiez que votre API est déployée sur Render\n'
'2. Vérifiez que le service est actif\n'
'3. Testez l\'URL dans un navigateur\n'
'4. Les services cloud gratuits peuvent se mettre en veille',
style: TextStyle(fontSize: 12),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Fermer'),
),
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
_checkApiHealth();
},
child: Text('Retester'),
),
],
),
);
}
Future<void> _selectImageFromGallery() async {
try {
final file = await ImageSelectionHelper.pickImageFromGallery();
if (file != null) {
setState(() {
_selectedImage = file;
_analysisResult = null;
_errorMessage = null;
});
}
} catch (e) {
setState(() {
_errorMessage = e.toString();
});
}
}
Future<void> _takePhoto() async {
try {
final file = await ImageSelectionHelper.takePhoto();
if (file != null) {
setState(() {
_selectedImage = file;
_analysisResult = null;
_errorMessage = null;
});
}
} catch (e) {
setState(() {
_errorMessage = e.toString();
});
}
}
Future<void> _analyzeImage() async {
if (_selectedImage == null) return;
setState(() {
_isAnalyzing = true;
_errorMessage = null;
_analysisResult = null;
});
try {
// Afficher un message d'information pour les services cloud
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text('Analyse en cours... Cela peut prendre jusqu\'à 2 minutes.'),
duration: Duration(seconds: 5),
),
);
final result = await TuberculosisApiService.analyzeImage(_selectedImage!);
setState(() {
_analysisResult = result;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Analyse terminée avec succès!'),
backgroundColor: Colors.green,
),
);
} catch (e) {
setState(() {
_errorMessage = e.toString();
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erreur lors de l\'analyse'),
backgroundColor: Colors.red,
),
);
} finally {
setState(() {
_isAnalyzing = false;
});
}
}
Future<void> _shareResults() async {
if (_analysisResult == null) return;
try {
// Créer un rapport textuel
String report = 'Rapport d\'analyse - Tuberculose\n\n';
report +=
'Résultat: ${_analysisResult!.isTuberculosis ? "Tuberculose détectée" : "Pas de tuberculose détectée"}\n';
report +=
'Confiance: ${(_analysisResult!.confidence * 100).toStringAsFixed(1)}%\n';
report += 'Stade: ${_analysisResult!.stage}\n';
report += 'Description: ${_analysisResult!.stageDescription}\n';
report += 'Nombre de nodules: ${_analysisResult!.noduleCount}\n\n';
if (_analysisResult!.recommendations.isNotEmpty) {
report += 'Recommandations:\n';
for (int i = 0; i < _analysisResult!.recommendations.length; i++) {
report += '${i + 1}. ${_analysisResult!.recommendations[i]}\n';
}
}
// Sauvegarder l'image analysée si disponible
if (_analysisResult!.analyzedImageBase64.isNotEmpty) {
try {
final bytes = base64Decode(_analysisResult!.analyzedImageBase64);
final tempDir = await getTemporaryDirectory();
final imageFile = File('${tempDir.path}/analyzed_image.png');
await imageFile.writeAsBytes(bytes);
// Utiliser shareXFiles pour partager des fichiers avec du texte
await Share.shareXFiles(
[XFile(imageFile.path)],
text: report,
subject: 'Rapport d\'analyse - Tuberculose',
);
} catch (e) {
// Si l'image ne peut pas être partagée, partager seulement le texte
await Share.share(
report,
subject: 'Rapport d\'analyse - Tuberculose',
);
}
} else {
await Share.share(
report,
subject: 'Rapport d\'analyse - Tuberculose',
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erreur lors du partage: $e')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Analyseur de Tuberculose'),
actions: [
IconButton(
icon: Icon(Icons.refresh),
onPressed: _checkApiHealth,
),
IconButton(
icon: Icon(Icons.info),
onPressed: () => _showInfoDialog(context),
),
],
),
body: SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Statut de l'API
_buildApiStatusCard(),
Card(
color: _isApiHealthy ? Colors.green[50] : Colors.red[50],
child: Padding(
padding: EdgeInsets.all(16.0),
child: Row(
children: [
if (_isCheckingHealth)
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
else
Icon(
_isApiHealthy ? Icons.check_circle : Icons.error,
color: _isApiHealthy ? Colors.green : Colors.red,
),
SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_healthStatus,
style: TextStyle(
color: _isApiHealthy
? Colors.green[800]
: Colors.red[800],
fontWeight: FontWeight.bold,
),
),
if (!_isApiHealthy && !_isCheckingHealth)
Text(
'Les services cloud peuvent prendre du temps à démarrer',
style: TextStyle(
color: Colors.grey[600],
fontSize: 12,
),
),
],
),
),
],
),
),
),
SizedBox(height: 16),
// Boutons de sélection d'image
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: _selectImageFromGallery,
icon: Icon(Icons.photo_library),
label: Text('Galerie'),
),
),
SizedBox(width: 16),
Expanded(
child: ElevatedButton.icon(
onPressed: _takePhoto,
icon: Icon(Icons.camera_alt),
label: Text('Appareil photo'),
),
),
],
),
SizedBox(height: 16),
// Affichage de l'image sélectionnée
if (_selectedImage != null) ...[
Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
Text(
'Image sélectionnée',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(height: 8),
Container(
height: 200,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey[300]!),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(
_selectedImage!,
fit: BoxFit.contain,
),
),
),
SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _isAnalyzing || !_isApiHealthy
? null
: _analyzeImage,
icon: _isAnalyzing
? SizedBox(
width: 16,
height: 16,
child:
CircularProgressIndicator(strokeWidth: 2),
)
: Icon(Icons.analytics),
label: Text(
_isAnalyzing ? 'Analyse en cours...' : 'Analyser'),
),
if (_isAnalyzing)
Padding(
padding: EdgeInsets.only(top: 8),
child: Text(
'Patience, l\'analyse peut prendre jusqu\'à 2 minutes...',
style: TextStyle(
color: Colors.grey[600],
fontSize: 12,
),
),
),
],
),
),
),
SizedBox(height: 16),
],
// Affichage des erreurs
if (_errorMessage != null) ...[
Card(
color: Colors.red[50],
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.error, color: Colors.red),
SizedBox(width: 8),
Text(
'Erreur',
style: TextStyle(
color: Colors.red[800],
fontWeight: FontWeight.bold,
),
),
],
),
SizedBox(height: 8),
Text(
_errorMessage!,
style: TextStyle(color: Colors.red[700]),
),
SizedBox(height: 8),
ElevatedButton(
onPressed: _checkApiHealth,
child: Text('Réessayer'),
),
],
),
),
),
SizedBox(height: 16),
],
// Affichage des résultats
if (_analysisResult != null) ...[
ResultsWidget(
result: _analysisResult!,
onShare: _shareResults,
),
],
],
),
),
);
}
void _showInfoDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('À propos'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Analyseur de Tuberculose'),
SizedBox(height: 8),
Text(
'Cette application utilise l\'intelligence artificielle pour analyser les radiographies pulmonaires et détecter la présence de tuberculose.'),
SizedBox(height: 8),
Text(
'Le service est hébergé sur Render Cloud et peut prendre du temps à démarrer s\'il n\'a pas été utilisé récemment.'),
SizedBox(height: 8),
Text(
'⚠️ Attention: Cette application est à des fins éducatives uniquement et ne remplace pas un diagnostic médical professionnel.'),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Fermer'),
),
],
),
);
}
}
// Helper pour la sélection d'images
class ImageSelectionHelper {
static final ImagePicker _picker = ImagePicker();
/// Sélectionner une image depuis la galerie
static Future<File?> pickImageFromGallery() async {
try {
// Vérifier les permissions de stockage
final hasPermission = await PermissionHelper.requestStoragePermission();
if (!hasPermission) {
throw Exception('Permission d\'accès au stockage refusée');
}
// Sélectionner l'image
final XFile? pickedFile = await _picker.pickImage(
source: ImageSource.gallery,
maxWidth: 1920,
maxHeight: 1920,
imageQuality: 85,
);
if (pickedFile == null) return null;
// Validation du fichier
final file = File(pickedFile.path);
await _validateImageFile(file);
return file;
} catch (e) {
throw Exception('Erreur lors de la sélection d\'image: $e');
}
}
/// Prendre une photo avec l'appareil photo
static Future<File?> takePhoto() async {
try {
// Vérifier les permissions de caméra
final hasPermission = await PermissionHelper.requestCameraPermission();
if (!hasPermission) {
throw Exception('Permission d\'accès à la caméra refusée');
}
// Prendre la photo
final XFile? pickedFile = await _picker.pickImage(
source: ImageSource.camera,
maxWidth: 1920,
maxHeight: 1920,
imageQuality: 85,
preferredCameraDevice: CameraDevice.rear,
);
if (pickedFile == null) return null;
// Validation du fichier
final file = File(pickedFile.path);
await _validateImageFile(file);
return file;
} catch (e) {
throw Exception('Erreur lors de la prise de photo: $e');
}
}
/// Sélectionner une image avec FilePicker (alternative)
static Future<File?> pickImageWithFilePicker() async {
try {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'jpeg', 'png', 'bmp'],
allowMultiple: false,
);
if (result == null || result.files.isEmpty) return null;
final file = File(result.files.single.path!);
await _validateImageFile(file);
return file;
} catch (e) {
throw Exception('Erreur lors de la sélection de fichier: $e');
}
}
/// Validation du fichier image
static Future<void> _validateImageFile(File file) async {
// Vérifier l'existence du fichier
if (!await file.exists()) {
throw Exception('Le fichier sélectionné n\'existe pas');
}
// Vérifier la taille du fichier
final fileSize = await file.length();
if (!ImageValidator.isValidSize(fileSize)) {
throw Exception(
'Fichier trop volumineux: ${ImageValidator.getFileSizeString(fileSize)}. '
'Taille maximale: ${ImageValidator.getFileSizeString(ImageValidator.maxFileSize)}');
}
// Vérifier l'extension
if (!ImageValidator.isValidExtension(file.path)) {
throw Exception('Format de fichier non supporté. '
'Formats acceptés: ${ImageValidator.allowedExtensions.join(', ')}');
}
// Vérifier que le fichier n'est pas vide
if (fileSize == 0) {
throw Exception('Le fichier image est vide');
}
}
/// Redimensionner une image si nécessaire
static Future<File> resizeImageIfNeeded(
File imageFile, {
int maxWidth = 1920,
int maxHeight = 1920,
int quality = 85,
}) async {
try {
// Cette méthode peut être étendue avec une bibliothèque comme image
// Pour l'instant, on retourne le fichier original
return imageFile;
} catch (e) {
throw Exception('Erreur lors du redimensionnement: $e');
}
}
/// Obtenir les informations sur l'image
static Future<Map<String, dynamic>> getImageInfo(File imageFile) async {
try {
final fileSize = await imageFile.length();
final fileName = path.basename(imageFile.path);
final extension = path.extension(imageFile.path);
final mimeType = lookupMimeType(imageFile.path) ?? 'unknown';
return {
'fileName': fileName,
'filePath': imageFile.path,
'fileSize': fileSize,
'fileSizeString': ImageValidator.getFileSizeString(fileSize),
'extension': extension,
'mimeType': mimeType,
'isValid': ImageValidator.isValidSize(fileSize) &&
ImageValidator.isValidExtension(imageFile.path),
};
} catch (e) {
throw Exception('Erreur lors de l\'obtention des informations: $e');
}
}
}
// Widget pour afficher les résultats
class ResultsWidget extends StatelessWidget {
final AnalysisResult result;
final VoidCallback onShare;
const ResultsWidget({
Key? key,
required this.result,
required this.onShare,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
result.isTuberculosis ? Icons.warning : Icons.check_circle,
color: result.isTuberculosis ? Colors.orange : Colors.green,
size: 32,
),
SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Résultat de l\'analyse',
style: Theme.of(context).textTheme.titleLarge,
),
Text(
result.isTuberculosis
? 'Tuberculose détectée'
: 'Pas de tuberculose détectée',
style: TextStyle(
color: result.isTuberculosis
? Colors.orange[700]
: Colors.green[700],
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
],
),
),
],
),
SizedBox(height: 16),
// Informations détaillées
_buildInfoRow('Confiance',
'${(result.confidence * 100).toStringAsFixed(1)}%'),
_buildInfoRow('Stade', result.stage),
if (result.stageDescription.isNotEmpty)
_buildInfoRow('Description', result.stageDescription),
_buildInfoRow('Nombre de nodules', result.noduleCount.toString()),
SizedBox(height: 16),
// Image analysée
if (result.analyzedImageBase64.isNotEmpty) ...[
Text(
'Image analysée',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(height: 8),
Container(
height: 200,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey[300]!),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.memory(
base64Decode(result.analyzedImageBase64),
fit: BoxFit.contain,
),
),
),
SizedBox(height: 16),
],
// Recommandations
if (result.recommendations.isNotEmpty) ...[
Text(
'Recommandations',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(height: 8),
...result.recommendations
.map((rec) => Padding(
padding: EdgeInsets.only(bottom: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('• ',
style: TextStyle(fontWeight: FontWeight.bold)),
Expanded(child: Text(rec)),
],
),
))
.toList(),
SizedBox(height: 16),
],
// Bouton de partage
Center(
child: ElevatedButton.icon(
onPressed: onShare,
icon: Icon(Icons.share),
label: Text('Partager les résultats'),
),
),
// Disclaimer médical
SizedBox(height: 16),
Container(
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.amber[50],
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.amber[200]!),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.warning, color: Colors.amber[700], size: 20),
SizedBox(width: 8),
Expanded(
child: Text(
'Attention: Ces résultats sont à des fins éducatives uniquement. '
'Consultez toujours un professionnel de santé pour un diagnostic médical.',
style: TextStyle(
color: Colors.amber[800],
fontSize: 12,
),
),
),
],
),
),
],
),
),
);
}
Widget _buildInfoRow(String label, String value) {
return Padding(
padding: EdgeInsets.only(bottom: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 100,
child: Text(
'$label:',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
child: Text(value),
),
],
),
);
}
}
// Widget pour afficher les informations du modèle
class ModelInfoWidget extends StatefulWidget {
@override
_ModelInfoWidgetState createState() => _ModelInfoWidgetState();
}
class _ModelInfoWidgetState extends State<ModelInfoWidget> {
Map<String, dynamic>? _modelInfo;
bool _isLoading = false;
String? _errorMessage;
@override
void initState() {
super.initState();
_loadModelInfo();
}
Future<void> _loadModelInfo() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final info = await TuberculosisApiService.getModelInfo();
setState(() {
_modelInfo = info;
});
} catch (e) {
setState(() {
_errorMessage = e.toString();
});
} finally {
setState(() {
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return Center(
child: CircularProgressIndicator(),
);
}
if (_errorMessage != null) {
return Card(
color: Colors.red[50],
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
Icon(Icons.error, color: Colors.red),
SizedBox(height: 8),
Text(
'Erreur lors du chargement des informations du modèle',
style: TextStyle(color: Colors.red[700]),
),
SizedBox(height: 8),
Text(
_errorMessage!,
style: TextStyle(color: Colors.red[600], fontSize: 12),
),
SizedBox(height: 8),
ElevatedButton(
onPressed: _loadModelInfo,
child: Text('Réessayer'),
),
],
),
),
);
}
if (_modelInfo == null) {
return SizedBox.shrink();
}
return Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Informations du modèle',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(height: 8),
if (_modelInfo!['model_name'] != null)
_buildInfoRow('Nom du modèle', _modelInfo!['model_name']),
if (_modelInfo!['model_version'] != null)
_buildInfoRow('Version', _modelInfo!['model_version']),
if (_modelInfo!['accuracy'] != null)
_buildInfoRow('Précision', '${_modelInfo!['accuracy']}%'),
if (_modelInfo!['last_updated'] != null)
_buildInfoRow(
'Dernière mise à jour', _modelInfo!['last_updated']),
if (_modelInfo!['input_size'] != null)
_buildInfoRow('Taille d\'entrée', _modelInfo!['input_size']),
],
),
),
);
}
Widget _buildInfoRow(String label, String value) {
return Padding(
padding: EdgeInsets.only(bottom: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 120,
child: Text(
'$label:',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
child: Text(value),
),
],
),
);
}
}
// Page des paramètres
class SettingsPage extends StatefulWidget {
@override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
bool _showDetailedResults = true;
bool _saveAnalysisHistory = false;
double _imageQuality = 85.0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Paramètres'),
),
body: ListView(
padding: EdgeInsets.all(16.0),
children: [
Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Affichage des résultats',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(height: 8),
SwitchListTile(
title: Text('Afficher les résultats détaillés'),
subtitle: Text('Inclure les informations techniques'),
value: _showDetailedResults,
onChanged: (value) {
setState(() {
_showDetailedResults = value;
});
},
),
],
),
),
),
SizedBox(height: 16),
Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Qualité d\'image',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(height: 8),
Text('Qualité: ${_imageQuality.round()}%'),
Slider(
value: _imageQuality,
min: 50.0,
max: 100.0,
divisions: 10,
label: '${_imageQuality.round()}%',
onChanged: (value) {
setState(() {
_imageQuality = value;
});
},
),
Text(
'Une qualité plus élevée améliore la précision mais augmente la taille du fichier',
style: TextStyle(
color: Colors.grey[600],
fontSize: 12,
),
),
],
),
),
),
SizedBox(height: 16),
Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Historique',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(height: 8),
SwitchListTile(
title: Text('Sauvegarder l\'historique'),
subtitle: Text('Conserver les analyses précédentes'),
value: _saveAnalysisHistory,
onChanged: (value) {
setState(() {
_saveAnalysisHistory = value;
});
},
),
],
),
),
),
SizedBox(height: 16),
ModelInfoWidget(),
],
),
);
}
}
// Point d'entrée de l'application
void main() {
runApp(TuberculosisAnalyzerApp());
}
// Extension pour ajouter des méthodes utilitaires
extension AnalysisResultExtension on AnalysisResult {
String get severityText {
if (confidence >= 0.8) return 'Haute';
if (confidence >= 0.6) return 'Moyenne';
return 'Faible';
}
Color get severityColor {
if (confidence >= 0.8) return Colors.red;
if (confidence >= 0.6) return Colors.orange;
return Colors.green;
}
String get formattedConfidence {
return '${(confidence * 100).toStringAsFixed(1)}%';
}
}
// Helper pour la gestion des permissions
class PermissionHelper {
static Future<bool> requestCameraPermission() async {
// Cette méthode peut être étendue avec permission_handler
// Pour l'instant, on suppose que les permissions sont gérées par le système
return true;
}
static Future<bool> requestStoragePermission() async {
// Cette méthode peut être étendue avec permission_handler
// Pour l'instant, on suppose que les permissions sont gérées par le système
return true;
}
}
// Utilitaires pour la validation des images
class ImageValidator {
static const int maxFileSize = 10 * 1024 * 1024; // 10MB
static const List<String> allowedExtensions = [
'.jpg',
'.jpeg',
'.png',
'.bmp'
];
static bool isValidSize(int size) {
return size > 0 && size <= maxFileSize;
}
static bool isValidExtension(String filePath) {
final extension = path.extension(filePath).toLowerCase();
return allowedExtensions.contains(extension);
}
static String getFileSizeString(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
}
|