Skip to content

Commit

Permalink
Using Dart Frog with example
Browse files Browse the repository at this point in the history
  • Loading branch information
AseemWangoo authored Feb 2, 2023
1 parent 52ed597 commit 0f431a5
Show file tree
Hide file tree
Showing 79 changed files with 5,428 additions and 0 deletions.
16 changes: 16 additions & 0 deletions experiment_with_dartfrog/client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# client

A new Flutter project.

## Getting Started

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)

For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
29 changes: 29 additions & 0 deletions experiment_with_dartfrog/client/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml

linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at
# https://dart-lang.github.io/linter/lints/index.html.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
18 changes: 18 additions & 0 deletions experiment_with_dartfrog/client/client.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/lib" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Flutter Plugins" level="project" />
<orderEntry type="library" name="Dart Packages" level="project" />
</component>
</module>
7 changes: 7 additions & 0 deletions experiment_with_dartfrog/client/lib/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import 'package:flutter/material.dart';

import 'src/file_picker.dart';

void main() {
runApp(const FilePickerDemo());
}
61 changes: 61 additions & 0 deletions experiment_with_dartfrog/client/lib/src/client.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:http/http.dart';
import 'package:rekognition/rekognition.dart';

class ApiClient {
ApiClient({
required String baseUrl,
Client? client,
}) : _baseUrl = baseUrl,
_client = client ?? Client();

final String _baseUrl;
final Client _client;

Future<Map<String, String>> _getRequestHeaders() async {
return <String, String>{
HttpHeaders.contentTypeHeader: ContentType.json.value,
HttpHeaders.acceptHeader: ContentType.json.value,
};
}

Future<Map<String, dynamic>> rekognizeTest() async {
final uri = Uri.parse('$_baseUrl/api/v1/rekognizeTest');
final headers = await _getRequestHeaders();

final response = await _client.get(
uri,
headers: headers,
);

if (response.statusCode != HttpStatus.ok) {
throw Error();
}

final data = jsonDecode(response.body) as Map<String, dynamic>;
return data;
}

Future<List<CelebrityModel>?> recognizeIfCelebrity(
Uint8List imageBytes,
) async {
final uri = Uri.parse('$_baseUrl/api/v1/rekognizeIfCelebrity');
final imageData = base64Encode(imageBytes);

final response = await _client.post(
uri,
body: {'image': imageData},
);

if (response.statusCode != HttpStatus.ok) {
throw Error();
}

final data = jsonDecode(response.body) as Map<String, dynamic>;
final celebrityResp = CelebrityModelResponse.fromJson(data).data;
return celebrityResp;
}
}
206 changes: 206 additions & 0 deletions experiment_with_dartfrog/client/lib/src/file_picker.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rekognition/rekognition.dart' as aws;

import 'client.dart';

class FilePickerDemo extends StatefulWidget {
const FilePickerDemo({super.key});

@override
// ignore: library_private_types_in_public_api
_FilePickerDemoState createState() => _FilePickerDemoState();
}

class _FilePickerDemoState extends State<FilePickerDemo> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
String? _fileName;
String? _saveAsFileName;
List<PlatformFile>? _paths;
String? _directoryPath;
String? _extension;
bool _isLoading = false;
bool _userAborted = false;
List<aws.CelebrityModel>? celebrities = [];

final apiClient = ApiClient(baseUrl: 'http://localhost:8080');

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
scaffoldMessengerKey: _scaffoldMessengerKey,
title: 'DartFrog Client',
home: Scaffold(
key: _scaffoldKey,
appBar: AppBar(title: const Text('DartFrog Client')),
body: Center(
child: Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(top: 50.0, bottom: 20.0),
child: Column(
children: [
ElevatedButton(
onPressed: () => _pickFiles(),
child: const Text('Pick file'),
),
],
),
),
Builder(
builder: (context) => _isLoading
? const Padding(
padding: EdgeInsets.only(bottom: 10.0),
child: CircularProgressIndicator(),
)
: _userAborted
? const Padding(
padding: EdgeInsets.only(bottom: 10.0),
child: Text(
'User has aborted the dialog',
),
)
: _directoryPath != null
? ListTile(
title: const Text('Directory path'),
subtitle: Text(_directoryPath!),
)
: _paths != null
? Container(
padding:
const EdgeInsets.only(bottom: 30.0),
height:
MediaQuery.of(context).size.height *
0.50,
child: Scrollbar(
child: ListView.separated(
itemCount: _paths != null &&
_paths!.isNotEmpty
? _paths!.length
: 1,
itemBuilder: (context, index) {
final bool isMultiPath =
_paths != null &&
_paths!.isNotEmpty;
final String name =
'File $index: ${isMultiPath ? _paths!.map((e) => e.name).toList()[index] : _fileName ?? '...'}';
final path = kIsWeb
? null
: _paths!
.map((e) => e.path)
.toList()[index]
.toString();

return ListTile(
title: Text(name),
subtitle: Text(path ?? ''),
);
},
separatorBuilder:
(context, index) =>
const Divider(),
),
),
)
: _saveAsFileName != null
? ListTile(
title: const Text('Save file'),
subtitle: Text(_saveAsFileName!),
)
: const SizedBox(),
),
ListView.separated(
shrinkWrap: true,
itemCount: celebrities?.length ?? 0,
separatorBuilder: (context, index) => const Divider(),
itemBuilder: (context, index) {
final celebrity = celebrities![index];

return Card(
child: ListTile(
title: Text(celebrity.name ?? ''),
selected: true,
subtitle: Text(
'Matching : ${celebrity.matchConfidence?.truncateToDouble().toString()}'),
isThreeLine: true,
leading: Image.memory(_paths!.first.bytes!),
selectedTileColor: Colors.yellow.shade800,
selectedColor: Colors.white,
),
);
},
),
],
),
),
),
),
),
);
}

void _pickFiles() async {
_resetState();
try {
_directoryPath = null;
_paths = (await FilePicker.platform.pickFiles(
onFileLoading: (FilePickerStatus status) =>
debugPrint(status.toString()),
allowedExtensions: (_extension?.isNotEmpty ?? false)
? _extension?.replaceAll(' ', '').split(',')
: null,
withData: true,
))
?.files;

// Get the bytes and call the service
final imageBytes = _paths?.first.bytes;
celebrities = await apiClient.recognizeIfCelebrity(imageBytes!);
} on PlatformException catch (e) {
_logException('Unsupported operation $e');
} catch (e) {
_logException(e.toString());
}

if (!mounted) return;
setState(() {
_isLoading = false;
_fileName =
_paths != null ? _paths!.map((e) => e.name).toString() : '...';
_userAborted = _paths == null;
});
}

void _logException(String message) {
debugPrint(message);
_scaffoldMessengerKey.currentState?.hideCurrentSnackBar();
_scaffoldMessengerKey.currentState?.showSnackBar(
SnackBar(
content: Text(message),
),
);
}

void _resetState() {
if (!mounted) {
return;
}
setState(() {
_isLoading = true;
_directoryPath = null;
_fileName = null;
_paths = null;
_saveAsFileName = null;
_userAborted = false;
celebrities = [];
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig"
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig"
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//
// Generated file. Do not edit.
//

import FlutterMacOS
import Foundation


func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
}
Loading

0 comments on commit 0f431a5

Please sign in to comment.