Refactor DocumentIntelligenceService and related classes to comment out code for future reference; update AuthenticationRepository to remove splash screen on app start.
This commit is contained in:
parent
6a85f75e3c
commit
1908318769
|
@ -1,19 +1,22 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:flutter_native_splash/flutter_native_splash.dart';
|
||||
import 'package:get_storage/get_storage.dart';
|
||||
import 'package:mapbox_maps_flutter/mapbox_maps_flutter.dart';
|
||||
import 'package:sigap/app.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
final widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
// Make sure status bar is properly set
|
||||
SystemChrome.setSystemUIOverlayStyle(
|
||||
const SystemUiOverlayStyle(statusBarColor: Colors.transparent),
|
||||
);
|
||||
|
||||
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
|
||||
|
||||
// Load environment variables from the .env file
|
||||
await dotenv.load(fileName: ".env");
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,286 +1,286 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:http/http.dart' as http;
|
||||
// import 'dart:convert';
|
||||
// import 'dart:io';
|
||||
// import 'package:http/http.dart' as http;
|
||||
|
||||
class DocumentIntelligenceService {
|
||||
final String endpoint;
|
||||
final String key;
|
||||
final http.Client _client = http.Client();
|
||||
// class DocumentIntelligenceService {
|
||||
// final String endpoint;
|
||||
// final String key;
|
||||
// final http.Client _client = http.Client();
|
||||
|
||||
DocumentIntelligenceService({
|
||||
required this.endpoint,
|
||||
required this.key,
|
||||
});
|
||||
// DocumentIntelligenceService({
|
||||
// required this.endpoint,
|
||||
// required this.key,
|
||||
// });
|
||||
|
||||
// Generator function equivalent for getting text of spans
|
||||
List<String> getTextOfSpans(String content, List<Map<String, dynamic>> spans) {
|
||||
List<String> textList = [];
|
||||
for (var span in spans) {
|
||||
int offset = span['offset'];
|
||||
int length = span['length'];
|
||||
textList.add(content.substring(offset, offset + length));
|
||||
}
|
||||
return textList;
|
||||
}
|
||||
// // Generator function equivalent for getting text of spans
|
||||
// List<String> getTextOfSpans(String content, List<Map<String, dynamic>> spans) {
|
||||
// List<String> textList = [];
|
||||
// for (var span in spans) {
|
||||
// int offset = span['offset'];
|
||||
// int length = span['length'];
|
||||
// textList.add(content.substring(offset, offset + length));
|
||||
// }
|
||||
// return textList;
|
||||
// }
|
||||
|
||||
Future<Map<String, dynamic>> analyzeDocument(String documentUrl) async {
|
||||
try {
|
||||
// Initial request to start document analysis
|
||||
final initialResponse = await _client.post(
|
||||
Uri.parse('$endpoint/documentModels/prebuilt-read:analyze'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Ocp-Apim-Subscription-Key': key,
|
||||
},
|
||||
body: jsonEncode({
|
||||
'urlSource': documentUrl,
|
||||
}),
|
||||
);
|
||||
// Future<Map<String, dynamic>> analyzeDocument(String documentUrl) async {
|
||||
// try {
|
||||
// // Initial request to start document analysis
|
||||
// final initialResponse = await _client.post(
|
||||
// Uri.parse('$endpoint/documentModels/prebuilt-read:analyze'),
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// 'Ocp-Apim-Subscription-Key': key,
|
||||
// },
|
||||
// body: jsonEncode({
|
||||
// 'urlSource': documentUrl,
|
||||
// }),
|
||||
// );
|
||||
|
||||
if (initialResponse.statusCode != 202) {
|
||||
throw Exception('Failed to start analysis: ${initialResponse.body}');
|
||||
}
|
||||
// if (initialResponse.statusCode != 202) {
|
||||
// throw Exception('Failed to start analysis: ${initialResponse.body}');
|
||||
// }
|
||||
|
||||
// Get operation location from response headers
|
||||
String? operationLocation = initialResponse.headers['operation-location'];
|
||||
if (operationLocation == null) {
|
||||
throw Exception('Operation location not found in response headers');
|
||||
}
|
||||
// // Get operation location from response headers
|
||||
// String? operationLocation = initialResponse.headers['operation-location'];
|
||||
// if (operationLocation == null) {
|
||||
// throw Exception('Operation location not found in response headers');
|
||||
// }
|
||||
|
||||
// Poll for results
|
||||
return await _pollForResults(operationLocation);
|
||||
} catch (e) {
|
||||
throw Exception('Error analyzing document: $e');
|
||||
}
|
||||
}
|
||||
// // Poll for results
|
||||
// return await _pollForResults(operationLocation);
|
||||
// } catch (e) {
|
||||
// throw Exception('Error analyzing document: $e');
|
||||
// }
|
||||
// }
|
||||
|
||||
Future<Map<String, dynamic>> _pollForResults(String operationLocation) async {
|
||||
const int maxAttempts = 60; // Maximum polling attempts
|
||||
const Duration pollInterval = Duration(seconds: 2);
|
||||
// Future<Map<String, dynamic>> _pollForResults(String operationLocation) async {
|
||||
// const int maxAttempts = 60; // Maximum polling attempts
|
||||
// const Duration pollInterval = Duration(seconds: 2);
|
||||
|
||||
for (int attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
final response = await _client.get(
|
||||
Uri.parse(operationLocation),
|
||||
headers: {
|
||||
'Ocp-Apim-Subscription-Key': key,
|
||||
},
|
||||
);
|
||||
// for (int attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
// final response = await _client.get(
|
||||
// Uri.parse(operationLocation),
|
||||
// headers: {
|
||||
// 'Ocp-Apim-Subscription-Key': key,
|
||||
// },
|
||||
// );
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Failed to get operation status: ${response.body}');
|
||||
}
|
||||
// if (response.statusCode != 200) {
|
||||
// throw Exception('Failed to get operation status: ${response.body}');
|
||||
// }
|
||||
|
||||
final responseData = jsonDecode(response.body);
|
||||
final String status = responseData['status'];
|
||||
// final responseData = jsonDecode(response.body);
|
||||
// final String status = responseData['status'];
|
||||
|
||||
if (status == 'succeeded') {
|
||||
return responseData['analyzeResult'];
|
||||
} else if (status == 'failed') {
|
||||
throw Exception('Document analysis failed: ${responseData['error']}');
|
||||
}
|
||||
// if (status == 'succeeded') {
|
||||
// return responseData['analyzeResult'];
|
||||
// } else if (status == 'failed') {
|
||||
// throw Exception('Document analysis failed: ${responseData['error']}');
|
||||
// }
|
||||
|
||||
// Wait before next poll
|
||||
await Future.delayed(pollInterval);
|
||||
}
|
||||
// // Wait before next poll
|
||||
// await Future.delayed(pollInterval);
|
||||
// }
|
||||
|
||||
throw Exception('Operation timed out after $maxAttempts attempts');
|
||||
}
|
||||
// throw Exception('Operation timed out after $maxAttempts attempts');
|
||||
// }
|
||||
|
||||
Future<void> processDocument(String documentUrl) async {
|
||||
try {
|
||||
final analyzeResult = await analyzeDocument(documentUrl);
|
||||
// Future<void> processDocument(String documentUrl) async {
|
||||
// try {
|
||||
// final analyzeResult = await analyzeDocument(documentUrl);
|
||||
|
||||
final String? content = analyzeResult['content'];
|
||||
final List<dynamic>? pages = analyzeResult['pages'];
|
||||
final List<dynamic>? languages = analyzeResult['languages'];
|
||||
final List<dynamic>? styles = analyzeResult['styles'];
|
||||
// final String? content = analyzeResult['content'];
|
||||
// final List<dynamic>? pages = analyzeResult['pages'];
|
||||
// final List<dynamic>? languages = analyzeResult['languages'];
|
||||
// final List<dynamic>? styles = analyzeResult['styles'];
|
||||
|
||||
// Process pages
|
||||
if (pages == null || pages.isEmpty) {
|
||||
print('No pages were extracted from the document.');
|
||||
} else {
|
||||
print('Pages:');
|
||||
for (var page in pages) {
|
||||
print('- Page ${page['pageNumber']} (unit: ${page['unit']})');
|
||||
print(' ${page['width']}x${page['height']}, angle: ${page['angle']}');
|
||||
// // Process pages
|
||||
// if (pages == null || pages.isEmpty) {
|
||||
// print('No pages were extracted from the document.');
|
||||
// } else {
|
||||
// print('Pages:');
|
||||
// for (var page in pages) {
|
||||
// print('- Page ${page['pageNumber']} (unit: ${page['unit']})');
|
||||
// print(' ${page['width']}x${page['height']}, angle: ${page['angle']}');
|
||||
|
||||
final List<dynamic> lines = page['lines'] ?? [];
|
||||
final List<dynamic> words = page['words'] ?? [];
|
||||
// final List<dynamic> lines = page['lines'] ?? [];
|
||||
// final List<dynamic> words = page['words'] ?? [];
|
||||
|
||||
print(' ${lines.length} lines, ${words.length} words');
|
||||
// print(' ${lines.length} lines, ${words.length} words');
|
||||
|
||||
if (lines.isNotEmpty) {
|
||||
print(' Lines:');
|
||||
for (var line in lines) {
|
||||
print(' - "${line['content']}"');
|
||||
}
|
||||
}
|
||||
// if (lines.isNotEmpty) {
|
||||
// print(' Lines:');
|
||||
// for (var line in lines) {
|
||||
// print(' - "${line['content']}"');
|
||||
// }
|
||||
// }
|
||||
|
||||
if (words.isNotEmpty) {
|
||||
print(' Words:');
|
||||
for (var word in words) {
|
||||
print(' - "${word['content']}"');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (words.isNotEmpty) {
|
||||
// print(' Words:');
|
||||
// for (var word in words) {
|
||||
// print(' - "${word['content']}"');
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// Process languages
|
||||
if (languages == null || languages.isEmpty) {
|
||||
print('No language spans were extracted from the document.');
|
||||
} else {
|
||||
print('Languages:');
|
||||
for (var languageEntry in languages) {
|
||||
print('- Found language: ${languageEntry['locale']} '
|
||||
'(confidence: ${languageEntry['confidence']})');
|
||||
// // Process languages
|
||||
// if (languages == null || languages.isEmpty) {
|
||||
// print('No language spans were extracted from the document.');
|
||||
// } else {
|
||||
// print('Languages:');
|
||||
// for (var languageEntry in languages) {
|
||||
// print('- Found language: ${languageEntry['locale']} '
|
||||
// '(confidence: ${languageEntry['confidence']})');
|
||||
|
||||
if (content != null && languageEntry['spans'] != null) {
|
||||
final spans = List<Map<String, dynamic>>.from(languageEntry['spans']);
|
||||
final textList = getTextOfSpans(content, spans);
|
||||
// if (content != null && languageEntry['spans'] != null) {
|
||||
// final spans = List<Map<String, dynamic>>.from(languageEntry['spans']);
|
||||
// final textList = getTextOfSpans(content, spans);
|
||||
|
||||
for (var text in textList) {
|
||||
final escapedText = text
|
||||
.replaceAll(RegExp(r'\r?\n'), '\\n')
|
||||
.replaceAll('"', '\\"');
|
||||
print(' - "$escapedText"');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// for (var text in textList) {
|
||||
// final escapedText = text
|
||||
// .replaceAll(RegExp(r'\r?\n'), '\\n')
|
||||
// .replaceAll('"', '\\"');
|
||||
// print(' - "$escapedText"');
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// Process styles
|
||||
if (styles == null || styles.isEmpty) {
|
||||
print('No text styles were extracted from the document.');
|
||||
} else {
|
||||
print('Styles:');
|
||||
for (var style in styles) {
|
||||
final bool isHandwritten = style['isHandwritten'] ?? false;
|
||||
final double confidence = style['confidence'] ?? 0.0;
|
||||
// // Process styles
|
||||
// if (styles == null || styles.isEmpty) {
|
||||
// print('No text styles were extracted from the document.');
|
||||
// } else {
|
||||
// print('Styles:');
|
||||
// for (var style in styles) {
|
||||
// final bool isHandwritten = style['isHandwritten'] ?? false;
|
||||
// final double confidence = style['confidence'] ?? 0.0;
|
||||
|
||||
print('- Handwritten: ${isHandwritten ? "yes" : "no"} '
|
||||
'(confidence=$confidence)');
|
||||
// print('- Handwritten: ${isHandwritten ? "yes" : "no"} '
|
||||
// '(confidence=$confidence)');
|
||||
|
||||
if (content != null && style['spans'] != null) {
|
||||
final spans = List<Map<String, dynamic>>.from(style['spans']);
|
||||
final textList = getTextOfSpans(content, spans);
|
||||
// if (content != null && style['spans'] != null) {
|
||||
// final spans = List<Map<String, dynamic>>.from(style['spans']);
|
||||
// final textList = getTextOfSpans(content, spans);
|
||||
|
||||
for (var text in textList) {
|
||||
print(' - "$text"');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print('An error occurred: $e');
|
||||
}
|
||||
}
|
||||
// for (var text in textList) {
|
||||
// print(' - "$text"');
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// } catch (e) {
|
||||
// print('An error occurred: $e');
|
||||
// }
|
||||
// }
|
||||
|
||||
void dispose() {
|
||||
_client.close();
|
||||
}
|
||||
}
|
||||
// void dispose() {
|
||||
// _client.close();
|
||||
// }
|
||||
// }
|
||||
|
||||
// Example usage in a Flutter app
|
||||
class DocumentAnalyzerApp {
|
||||
static const String endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT";
|
||||
static const String key = "YOUR_FORM_RECOGNIZER_KEY";
|
||||
static const String formUrl =
|
||||
"https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png";
|
||||
// // Example usage in a Flutter app
|
||||
// class DocumentAnalyzerApp {
|
||||
// static const String endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT";
|
||||
// static const String key = "YOUR_FORM_RECOGNIZER_KEY";
|
||||
// static const String formUrl =
|
||||
// "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png";
|
||||
|
||||
static Future<void> main() async {
|
||||
final service = DocumentIntelligenceService(
|
||||
endpoint: endpoint,
|
||||
key: key,
|
||||
);
|
||||
// static Future<void> main() async {
|
||||
// final service = DocumentIntelligenceService(
|
||||
// endpoint: endpoint,
|
||||
// key: key,
|
||||
// );
|
||||
|
||||
try {
|
||||
await service.processDocument(formUrl);
|
||||
} finally {
|
||||
service.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
// try {
|
||||
// await service.processDocument(formUrl);
|
||||
// } finally {
|
||||
// service.dispose();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// Flutter Widget Example
|
||||
import 'package:flutter/material.dart';
|
||||
// // Flutter Widget Example
|
||||
// import 'package:flutter/material.dart';
|
||||
|
||||
class DocumentAnalyzerWidget extends StatefulWidget {
|
||||
const DocumentAnalyzerWidget({super.key});
|
||||
// class DocumentAnalyzerWidget extends StatefulWidget {
|
||||
// const DocumentAnalyzerWidget({super.key});
|
||||
|
||||
@override
|
||||
_DocumentAnalyzerWidgetState createState() => _DocumentAnalyzerWidgetState();
|
||||
}
|
||||
// @override
|
||||
// _DocumentAnalyzerWidgetState createState() => _DocumentAnalyzerWidgetState();
|
||||
// }
|
||||
|
||||
class _DocumentAnalyzerWidgetState extends State<DocumentAnalyzerWidget> {
|
||||
final DocumentIntelligenceService _service = DocumentIntelligenceService(
|
||||
endpoint: "YOUR_FORM_RECOGNIZER_ENDPOINT",
|
||||
key: "YOUR_FORM_RECOGNIZER_KEY",
|
||||
);
|
||||
// class _DocumentAnalyzerWidgetState extends State<DocumentAnalyzerWidget> {
|
||||
// final DocumentIntelligenceService _service = DocumentIntelligenceService(
|
||||
// endpoint: "YOUR_FORM_RECOGNIZER_ENDPOINT",
|
||||
// key: "YOUR_FORM_RECOGNIZER_KEY",
|
||||
// );
|
||||
|
||||
bool _isLoading = false;
|
||||
String _result = '';
|
||||
// bool _isLoading = false;
|
||||
// String _result = '';
|
||||
|
||||
Future<void> _analyzeDocument() async {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_result = '';
|
||||
});
|
||||
// Future<void> _analyzeDocument() async {
|
||||
// setState(() {
|
||||
// _isLoading = true;
|
||||
// _result = '';
|
||||
// });
|
||||
|
||||
try {
|
||||
const String documentUrl =
|
||||
"https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png";
|
||||
// try {
|
||||
// const String documentUrl =
|
||||
// "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png";
|
||||
|
||||
await _service.processDocument(documentUrl);
|
||||
setState(() {
|
||||
_result = 'Document analysis completed successfully!';
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_result = 'Error: $e';
|
||||
});
|
||||
} finally {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
// await _service.processDocument(documentUrl);
|
||||
// setState(() {
|
||||
// _result = 'Document analysis completed successfully!';
|
||||
// });
|
||||
// } catch (e) {
|
||||
// setState(() {
|
||||
// _result = 'Error: $e';
|
||||
// });
|
||||
// } finally {
|
||||
// setState(() {
|
||||
// _isLoading = false;
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_service.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
// @override
|
||||
// void dispose() {
|
||||
// _service.dispose();
|
||||
// super.dispose();
|
||||
// }
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('Document Intelligence'),
|
||||
),
|
||||
body: Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: _isLoading ? null : _analyzeDocument,
|
||||
child: _isLoading
|
||||
? CircularProgressIndicator(color: Colors.white)
|
||||
: Text('Analyze Document'),
|
||||
),
|
||||
SizedBox(height: 20),
|
||||
if (_result.isNotEmpty)
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
_result,
|
||||
style: TextStyle(fontSize: 14),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
// @override
|
||||
// Widget build(BuildContext context) {
|
||||
// return Scaffold(
|
||||
// appBar: AppBar(
|
||||
// title: Text('Document Intelligence'),
|
||||
// ),
|
||||
// body: Padding(
|
||||
// padding: EdgeInsets.all(16.0),
|
||||
// child: Column(
|
||||
// crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
// children: [
|
||||
// ElevatedButton(
|
||||
// onPressed: _isLoading ? null : _analyzeDocument,
|
||||
// child: _isLoading
|
||||
// ? CircularProgressIndicator(color: Colors.white)
|
||||
// : Text('Analyze Document'),
|
||||
// ),
|
||||
// SizedBox(height: 20),
|
||||
// if (_result.isNotEmpty)
|
||||
// Expanded(
|
||||
// child: SingleChildScrollView(
|
||||
// child: Text(
|
||||
// _result,
|
||||
// style: TextStyle(fontSize: 14),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// ),
|
||||
// );
|
||||
// }
|
||||
// }
|
|
@ -1,5 +1,6 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_native_splash/flutter_native_splash.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:get_storage/get_storage.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
|
@ -36,10 +37,8 @@ class AuthenticationRepository extends GetxController {
|
|||
// ---------------------------------------------------------------------------
|
||||
@override
|
||||
void onReady() {
|
||||
// Delay the redirect to avoid issues during build
|
||||
Future.delayed(Duration.zero, () {
|
||||
FlutterNativeSplash.remove();
|
||||
screenRedirect();
|
||||
});
|
||||
}
|
||||
|
||||
// Check for biometric login on app start
|
||||
|
|
Loading…
Reference in New Issue