QOL: Mzansi AI Chat Look and Feel pt1

This commit is contained in:
2025-11-07 12:03:44 +02:00
parent 6a5b4f7f4b
commit d75da5389a
15 changed files with 1198 additions and 61 deletions

View File

@@ -1,12 +1,51 @@
import 'package:flutter/material.dart';
import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart';
import 'package:mzansi_innovation_hub/main.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_icons.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_providers/ollama_provider.dart';
import 'package:mzansi_innovation_hub/mih_config/mih_colors.dart';
import 'package:mzansi_innovation_hub/mih_config/mih_env.dart';
class MzansiAiProvider extends ChangeNotifier {
int toolIndex;
String? startUpQuestion;
late OllamaProvider ollamaProvider;
MzansiAiProvider({
this.toolIndex = 0,
});
}) {
ollamaProvider = OllamaProvider(
baseUrl: "${AppEnviroment.baseAiUrl}/api",
model: AppEnviroment.getEnv() == "Prod" ? 'gemma3n:e4b' : "gemma3:1b",
systemPrompt: "You are Mzansi AI, a helpful and friendly AI assistant running on the 'MIH App'.\n" +
"The MIH App was created by 'Mzansi Innovation Hub', a South African-based startup company." +
"Your primary purpose is to assist users by answering general questions and helping with creative writing tasks or any other task a user might have for you.\n" +
"Maintain a casual and friendly tone, but always remain professional.\n" +
"Strive for a balance between being empathetic and delivering factual information accurately.\n" +
"You may use lighthearted or playful language if the context is appropriate and enhances the user experience.\n" +
"You operate within the knowledge domain of the 'MIH App'.\n" +
"Here is a description of the MIH App and its features:\n" +
"MIH App Description: MIH is the first super app of Mzansi, designed to streamline both personal and business life. It's an all-in-one platform for managing professional profiles, teams, appointments, and quick calculations. \n" +
"Key Features:\n" +
"- Mzansi Profile: Central hub for managing personal and business information, including business team details." +
"- Mzansi Wallet: Digitally store loyalty cards.\n" +
"- Patient Manager (For Medical Practices): Seamless patient appointment scheduling and data management.\n" +
"- Mzansi AI: Your friendly AI assistant for quick answers and support (that's you!).\n" +
"- Mzansi Directory: A place to search and find out more about the people and businesses across Mzansi.\n" +
"- Calendar: Integrated calendar for managing personal and business appointments.\n" +
"- Calculator: Simple calculator with tip and forex calculation functionality.\n" +
"- MIH Access: Manage and view profile access security.\n" +
"**Core Rules and Guidelines:**\n" +
"- **Accuracy First:** Always prioritize providing correct information.\n" +
"- **Uncertainty Handling:** If you are unsure about an answer, politely respond with: 'Please bear with us as we are still learning and do not have all the answers.'\n" +
"- **Response Length:** Aim to keep responses under 250 words. If a more comprehensive answer is required, exceed this limit but offer to elaborate further (e.g., 'Would you like me to elaborate on this topic?').\n" +
"- **Language & Safety:** Never use offensive language or generate harmful content. If a user presses for information that is inappropriate or out of bounds, clearly state why you cannot provide it (e.g., 'I cannot assist with that request as it goes against my safety guidelines.').\n" +
"- **Out-of-Scope Questions:** - If a question is unclear, ask the user to rephrase or clarify it. - If a question is entirely out of your scope and you cannot provide a useful answer, admit you don't know. - If a user is unhappy with your response or needs further assistance beyond your capabilities, suggest they visit the 'Mzansi Innovation Hub Social Media Pages' for more direct support. Do not provide specific links, just refer to the pages generally.\n" +
"- **Target Audience:** Adapt your explanations to beginners and intermediate users, but be prepared for more complex questions from expert users. Ensure your language is clear and easy to understand.\n",
)..addListener(() {
notifyListeners(); // Forward OllamaProvider notifications
});
}
void reset() {
toolIndex = 0;
@@ -23,4 +62,186 @@ class MzansiAiProvider extends ChangeNotifier {
startUpQuestion = question;
notifyListeners();
}
LlmChatViewStyle? getChatStyle(BuildContext context) {
return LlmChatViewStyle(
backgroundColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
progressIndicatorColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
menuColor: Colors.black,
// MihColors.getGreenColor(
// MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
disabledButtonStyle: ActionButtonStyle(
icon: MihIcons.mzansiAi,
iconColor: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
iconDecoration: BoxDecoration(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
),
),
recordButtonStyle: ActionButtonStyle(
iconColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
iconDecoration: BoxDecoration(
color: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
),
textStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
submitButtonStyle: ActionButtonStyle(
icon: Icons.send,
iconColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
iconDecoration: BoxDecoration(
color: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
),
textStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
stopButtonStyle: ActionButtonStyle(
iconColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
iconDecoration: BoxDecoration(
color: MihColors.getRedColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
),
textStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
actionButtonBarDecoration: BoxDecoration(
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
),
// Mzansi AI Chat Style
llmMessageStyle: LlmMessageStyle(
icon: MihIcons.mzansiAi,
iconColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
iconDecoration: BoxDecoration(
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(25),
bottomLeft: Radius.circular(25),
bottomRight: Radius.circular(25),
),
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(76),
blurRadius: 8,
offset: Offset(2, 2),
),
],
),
),
// User Chat Style
userMessageStyle: UserMessageStyle(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25),
bottomLeft: Radius.circular(25),
bottomRight: Radius.circular(25),
),
color: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(76),
blurRadius: 8,
offset: Offset(2, 2),
),
],
),
textStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
// User Input Style
chatInputStyle: ChatInputStyle(
backgroundColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
decoration: BoxDecoration(
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(76),
blurRadius: 8,
offset: Offset(2, 2),
),
],
),
hintStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
hintText: "Ask Mzansi AI...",
),
// Suggestions Style
suggestionStyle: SuggestionStyle(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25),
bottomLeft: Radius.circular(25),
bottomRight: Radius.circular(25),
),
color: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(76),
blurRadius: 8,
offset: Offset(2, 2),
),
],
),
textStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
copyButtonStyle: ActionButtonStyle(
iconColor: MihColors.getSecondaryInvertedColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
editButtonStyle: ActionButtonStyle(
iconColor: MihColors.getSecondaryInvertedColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
cancelButtonStyle: ActionButtonStyle(
iconDecoration: BoxDecoration(
color: MihColors.getRedColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
borderRadius: BorderRadius.circular(25),
),
iconColor: MihColors.getSecondaryInvertedColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
textStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
)),
);
}
}

View File

@@ -0,0 +1,136 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart';
import 'package:ollama_dart/ollama_dart.dart';
class OllamaProvider extends LlmProvider with ChangeNotifier {
OllamaProvider({
String? baseUrl,
Map<String, String>? headers,
Map<String, String>? queryParams,
required String model,
String? systemPrompt,
}) : _client = OllamaClient(
baseUrl: baseUrl,
headers: headers,
queryParams: queryParams,
),
_model = model,
_systemPrompt = systemPrompt,
_history = [];
final OllamaClient _client;
final String _model;
final List<ChatMessage> _history;
final String? _systemPrompt;
@override
Stream<String> generateStream(
String prompt, {
Iterable<Attachment> attachments = const [],
}) async* {
final messages = _mapToOllamaMessages([
ChatMessage.user(prompt, attachments),
]);
yield* _generateStream(messages);
}
@override
Stream<String> sendMessageStream(
String prompt, {
Iterable<Attachment> attachments = const [],
}) async* {
final userMessage = ChatMessage.user(prompt, attachments);
final llmMessage = ChatMessage.llm();
_history.addAll([userMessage, llmMessage]);
notifyListeners();
final messages = _mapToOllamaMessages(_history);
final stream = _generateStream(messages);
yield* stream.map((chunk) {
llmMessage.append(chunk);
return chunk;
});
notifyListeners();
}
@override
Iterable<ChatMessage> get history => _history;
void resetChat() {
_history.clear();
notifyListeners();
}
@override
set history(Iterable<ChatMessage> history) {
_history.clear();
_history.addAll(history);
notifyListeners();
}
Stream<String> _generateStream(List<Message> messages) async* {
final allMessages = <Message>[];
if (_systemPrompt != null && _systemPrompt.isNotEmpty) {
allMessages.add(Message(
role: MessageRole.system,
content: _systemPrompt,
));
}
allMessages.addAll(messages);
final stream = _client.generateChatCompletionStream(
request: GenerateChatCompletionRequest(
model: _model,
messages: allMessages,
),
);
// final stream = _client.generateChatCompletionStream(
// request: GenerateChatCompletionRequest(
// model: _model,
// messages: messages,
// ),
// );
yield* stream.map((res) => res.message.content);
}
List<Message> _mapToOllamaMessages(List<ChatMessage> messages) {
return messages.map((message) {
switch (message.origin) {
case MessageOrigin.user:
if (message.attachments.isEmpty) {
return Message(
role: MessageRole.user,
content: message.text ?? '',
);
}
return Message(
role: MessageRole.user,
content: message.text ?? '',
images: [
for (final attachment in message.attachments)
if (attachment is ImageFileAttachment)
base64Encode(attachment.bytes)
else
throw LlmFailureException(
'Unsupported attachment type: $attachment',
),
],
);
case MessageOrigin.llm:
return Message(
role: MessageRole.assistant,
content: message.text ?? '',
);
}
}).toList(growable: false);
}
@override
void dispose() {
_client.endSession();
super.dispose();
}
}

View File

@@ -17,6 +17,14 @@ class MihColors {
}
}
static Color getSecondaryInvertedColor(bool darkMode) {
if (darkMode == true) {
return const Color(0XFF412301);
} else {
return const Color(0XFFc5bbab);
}
}
static Color getHighlightColor(bool darkMode) {
if (darkMode == true) {
return const Color(0XFF9bc7fa);

View File

@@ -35,48 +35,116 @@ class MihTheme {
ThemeData getData(bool bool) {
return ThemeData(
fontFamily: 'Segoe UI',
scaffoldBackgroundColor: MihColors.getPrimaryColor(mode == "Dark"),
// pageTransitionsTheme: PageTransitionsTheme(
// builders: Map<TargetPlatform, PageTransitionsBuilder>.fromIterable(
// TargetPlatform.values,
// value: (dynamic _) => const FadeUpwardsPageTransitionsBuilder(),
// ),
// ),
colorScheme: ColorScheme(
brightness: getBritness(),
primary: MihColors.getSecondaryColor(mode == "Dark"),
onPrimary: MihColors.getPrimaryColor(mode == "Dark"),
secondary: MihColors.getPrimaryColor(mode == "Dark"),
onSecondary: MihColors.getSecondaryColor(mode == "Dark"),
error: MihColors.getRedColor(mode == "Dark"),
onError: MihColors.getPrimaryColor(mode == "Dark"),
surface: MihColors.getPrimaryColor(mode == "Dark"),
onSurface: MihColors.getSecondaryColor(mode == "Dark"),
fontFamily: 'Segoe UI',
scaffoldBackgroundColor: MihColors.getPrimaryColor(mode == "Dark"),
// pageTransitionsTheme: PageTransitionsTheme(
// builders: Map<TargetPlatform, PageTransitionsBuilder>.fromIterable(
// TargetPlatform.values,
// value: (dynamic _) => const FadeUpwardsPageTransitionsBuilder(),
// ),
// ),
colorScheme: ColorScheme(
brightness: getBritness(),
primary: MihColors.getSecondaryColor(mode == "Dark"),
onPrimary: MihColors.getPrimaryColor(mode == "Dark"),
secondary: MihColors.getPrimaryColor(mode == "Dark"),
onSecondary: MihColors.getSecondaryColor(mode == "Dark"),
error: MihColors.getRedColor(mode == "Dark"),
onError: MihColors.getPrimaryColor(mode == "Dark"),
surface: MihColors.getPrimaryColor(mode == "Dark"),
onSurface: MihColors.getSecondaryColor(mode == "Dark"),
),
datePickerTheme: DatePickerThemeData(
backgroundColor: MihColors.getPrimaryColor(mode == "Dark"),
headerBackgroundColor: MihColors.getSecondaryColor(mode == "Dark"),
headerForegroundColor: MihColors.getPrimaryColor(mode == "Dark"),
),
appBarTheme: AppBarTheme(
color: MihColors.getSecondaryColor(mode == "Dark"),
foregroundColor: MihColors.getPrimaryColor(mode == "Dark"),
titleTextStyle: TextStyle(
color: MihColors.getPrimaryColor(mode == "Dark"),
fontSize: 25,
fontWeight: FontWeight.bold,
),
datePickerTheme: DatePickerThemeData(
backgroundColor: MihColors.getPrimaryColor(mode == "Dark"),
headerBackgroundColor: MihColors.getSecondaryColor(mode == "Dark"),
headerForegroundColor: MihColors.getPrimaryColor(mode == "Dark"),
),
appBarTheme: AppBarTheme(
),
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: MihColors.getSecondaryColor(mode == "Dark"),
foregroundColor: MihColors.getPrimaryColor(mode == "Dark"),
extendedTextStyle:
TextStyle(color: MihColors.getPrimaryColor(mode == "Dark")),
),
drawerTheme: DrawerThemeData(
backgroundColor: MihColors.getPrimaryColor(mode == "Dark"),
),
// Text selection / cursor color
textSelectionTheme: TextSelectionThemeData(
cursorColor: MihColors.getPrimaryColor(mode == "Dark"),
selectionColor:
MihColors.getPrimaryColor(mode == "Dark").withOpacity(0.25),
selectionHandleColor: MihColors.getPrimaryColor(mode == "Dark"),
),
tooltipTheme: TooltipThemeData(
decoration: BoxDecoration(
color: MihColors.getSecondaryColor(mode == "Dark"),
foregroundColor: MihColors.getPrimaryColor(mode == "Dark"),
titleTextStyle: TextStyle(
borderRadius: BorderRadius.circular(6),
border: Border.all(
width: 1.0,
color: MihColors.getPrimaryColor(mode == "Dark"),
fontSize: 25,
fontWeight: FontWeight.bold,
),
boxShadow: [
BoxShadow(
color:
MihColors.getPrimaryColor(mode == "Dark").withOpacity(0.18),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: MihColors.getSecondaryColor(mode == "Dark"),
foregroundColor: MihColors.getPrimaryColor(mode == "Dark"),
extendedTextStyle:
TextStyle(color: MihColors.getPrimaryColor(mode == "Dark")),
textStyle: TextStyle(
color: MihColors.getPrimaryColor(mode == "Dark"),
fontSize: 13,
height: 1.2,
),
drawerTheme: DrawerThemeData(
backgroundColor: MihColors.getPrimaryColor(mode == "Dark"),
));
waitDuration: const Duration(milliseconds: 500),
showDuration: const Duration(seconds: 3),
preferBelow: true,
verticalOffset: 24,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
triggerMode: TooltipTriggerMode.longPress,
),
// // Input decoration (text fields) theme
// inputDecorationTheme: InputDecorationTheme(
// filled: true,
// fillColor: mode == "Dark"
// ? MihColors.getPrimaryColor(true).withOpacity(0.06)
// : MihColors.getPrimaryColor(false).withOpacity(0.03),
// contentPadding:
// const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
// border: OutlineInputBorder(
// borderRadius: BorderRadius.circular(8),
// borderSide:
// BorderSide(color: MihColors.getSecondaryColor(mode == "Dark")),
// ),
// enabledBorder: OutlineInputBorder(
// borderRadius: BorderRadius.circular(8),
// borderSide: BorderSide(
// color:
// MihColors.getSecondaryColor(mode == "Dark").withOpacity(0.6)),
// ),
// focusedBorder: OutlineInputBorder(
// borderRadius: BorderRadius.circular(8),
// borderSide: BorderSide(
// color: MihColors.getSecondaryColor(mode == "Dark"), width: 2),
// ),
// hintStyle: TextStyle(
// color:
// MihColors.getSecondaryColor(mode == "Dark").withOpacity(0.7)),
// labelStyle:
// TextStyle(color: MihColors.getSecondaryColor(mode == "Dark")),
// errorStyle: TextStyle(color: MihColors.getRedColor(mode == "Dark")),
// ),
);
}
String getPlatform() {

View File

@@ -5,6 +5,7 @@ import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_
import 'package:mzansi_innovation_hub/mih_components/mih_providers/mzansi_ai_provider.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_ai/package_tools/ai_chat.dart';
import 'package:flutter/material.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_ai/package_tools/mih_ai_chat.dart';
import 'package:provider/provider.dart';
class MzansiAi extends StatefulWidget {
@@ -36,6 +37,9 @@ class _MzansiAiState extends State<MzansiAi> {
temp[const Icon(Icons.chat)] = () {
context.read<MzansiAiProvider>().setToolIndex(0);
};
temp[const Icon(Icons.chat)] = () {
context.read<MzansiAiProvider>().setToolIndex(1);
};
return MihPackageTools(
tools: temp,
@@ -46,6 +50,7 @@ class _MzansiAiState extends State<MzansiAi> {
List<Widget> getToolBody() {
List<Widget> toolBodies = [
AiChat(),
MihAiChat(),
];
return toolBodies;
}
@@ -53,6 +58,7 @@ class _MzansiAiState extends State<MzansiAi> {
List<String> getToolTitle() {
List<String> toolTitles = [
"Ask Mzansi",
"New Chat",
];
return toolTitles;
}

View File

@@ -598,9 +598,6 @@ class _AiChatState extends State<AiChat> {
_voicesString =
_voices.map((_voice) => _voice["name"] as String).toList();
_voicesString.sort();
// print(
// "=================== Voices ===================\n$_voicesString");
setTtsVoice(_voicesString.first);
});
} catch (e) {

View File

@@ -0,0 +1,286 @@
import 'package:flutter/material.dart';
import 'package:flutter_ai_toolkit/flutter_ai_toolkit.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:ken_logger/ken_logger.dart';
import 'package:mzansi_innovation_hub/main.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_floating_menu.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_icons.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_providers/mzansi_ai_provider.dart';
import 'package:mzansi_innovation_hub/mih_config/mih_colors.dart';
import 'package:provider/provider.dart';
class MihAiChat extends StatefulWidget {
const MihAiChat({super.key});
@override
State<MihAiChat> createState() => _MihAiChatState();
}
class _MihAiChatState extends State<MihAiChat> {
bool ttsOn = false;
final FlutterTts _flutterTts = FlutterTts();
Widget noMessagescDisplay() {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 50),
Icon(
MihIcons.mzansiAi,
size: 165,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
const SizedBox(height: 10),
Text(
"Mzansi AI is here to help",
textAlign: TextAlign.center,
overflow: TextOverflow.visible,
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
const SizedBox(height: 25),
Center(
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
children: [
TextSpan(
text:
"Send us a message and we'll try our best to assist you"),
],
),
),
),
Center(
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
children: [
TextSpan(text: "Press "),
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Icon(
Icons.menu,
size: 20,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
),
TextSpan(text: " to start a new chat or read last message"),
],
),
),
),
],
),
),
);
}
void resetChat(MzansiAiProvider aiProvider) {
aiProvider.ollamaProvider.resetChat();
}
void speakLastMessage(MzansiAiProvider aiProvider) {
final history = aiProvider.ollamaProvider.history;
if (history.isNotEmpty) {
final historyList = history.toList();
for (int i = historyList.length - 1; i >= 0; i--) {
if (historyList[i].origin == MessageOrigin.llm &&
historyList[i].text != null &&
historyList[i].text!.isNotEmpty) {
_flutterTts.speak(historyList[i].text!);
return;
}
}
}
}
void stopTTS() {
_flutterTts.stop();
}
Future<void> initTts() async {
List<Map> _voices = [];
List<String> _voicesString = [];
// await _flutterTts.setLanguage("en-US");
await _flutterTts.setSpeechRate(1);
_flutterTts.getVoices.then(
(data) {
try {
_voices = List<Map>.from(data);
setState(() {
_voices = _voices
.where(
(_voice) => _voice["name"].toLowerCase().contains("en-us"))
.toList();
_voicesString =
_voices.map((_voice) => _voice["name"] as String).toList();
_voicesString.sort();
_flutterTts.setVoice(
{
"name": _voicesString.first,
"locale": _voices
.where((_voice) =>
_voice["name"].contains(_voicesString.first))
.first["locale"]
},
);
});
} catch (e) {
print(e);
}
},
);
_flutterTts.setStartHandler(() {
setState(() {
ttsOn = true;
});
});
_flutterTts.setCompletionHandler(() {
setState(() {
ttsOn = false;
});
});
_flutterTts.setErrorHandler((message) {
setState(() {
ttsOn = false;
});
});
}
@override
void initState() {
super.initState();
initTts();
}
@override
void dispose() {
_flutterTts.stop();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Consumer<MzansiAiProvider>(
builder: (BuildContext context, MzansiAiProvider mzansiAiProvider,
Widget? child) {
bool hasHistory = mzansiAiProvider.ollamaProvider.history.isNotEmpty;
KenLogger.success("has history: $hasHistory");
KenLogger.success(
"length: ${mzansiAiProvider.ollamaProvider.history.length}");
return Stack(
children: [
LlmChatView(
provider: mzansiAiProvider.ollamaProvider,
// welcomeMessage:
// "Mzansi AI is here to help. Send us a messahe and we'll try our best to assist you.",
enableAttachments: false,
enableVoiceNotes: true,
style: mzansiAiProvider.getChatStyle(context),
// suggestions: [
// "What is mih all about?",
// "What are the features of MIH?"
// ],
),
if (hasHistory)
Positioned(
right: 10,
bottom: 80,
child: MihFloatingMenu(
animatedIcon: AnimatedIcons.menu_close,
children: [
SpeedDialChild(
child: Icon(
Icons.refresh,
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
label: "New Chat",
labelBackgroundColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
labelStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
fontWeight: FontWeight.bold,
),
backgroundColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
onTap: () {
resetChat(mzansiAiProvider);
},
),
SpeedDialChild(
child: Icon(
!ttsOn ? Icons.volume_up : Icons.volume_off,
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
label: !ttsOn ? "Read last Message" : "Stop Reading",
labelBackgroundColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
labelStyle: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
fontWeight: FontWeight.bold,
),
backgroundColor: !ttsOn
? MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark")
: MihColors.getRedColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
onTap: () {
KenLogger.success("Button pressed: TtsOn - $ttsOn");
if (!ttsOn) {
speakLastMessage(mzansiAiProvider);
} else {
stopTTS();
}
},
),
],
),
),
if (!hasHistory) noMessagescDisplay(),
],
);
},
);
}
}