WinUI(WASDK)使用ChatGPT和摄像头手势识别结合TTS让机器人更智能 ...

打印 上一主题 下一主题

主题 1049|帖子 1049|积分 3147

前言

之前写过一篇基于ML.NET的手部关键点分类的博客,可以根据图片进行手部的提取分类,于是我就将手势分类和摄像头数据结合,集成到了我开发的电子脑壳软件里。
电子脑壳是一个为稚晖君开源的桌面机器人ElectronBot提供一些软件功能的桌面程序项目。它是由绿荫阿广也就是我开发的,使用了微软的WASDK框架。
电子脑壳算是本人学习WinUI开发的练习项目了,通过根据一些开源的项目的学习,将一些功能进行整合,比如手势识别触发语音转文本,然后接入ChatGPT结合文本转语音的方式,实现机器人的对话。
此博客算是实战记录了,替大家先踩坑。
下图链接为机器人的演示视频,通过对话,让ChatGPT给我讲了一个骆驼祥子的故事,只不过这个故事有点离谱,本来前部分还正常,后面就开始瞎编了,比如祥子有了一头驴,最后还成为了商人。
大家观看觉得不错的话给点个赞。

具体的实现方案

1. 方案思路叙述

整体的流程如下图,图画的不一定标准,但是大体如图所示:


  • 处理摄像头帧事件,通过将摄像头的帧数据处理进行手势的匹配。
  • 手势识别结果处理方法调用语音转文本逻辑。
  • 转的文本通过调用ChatGPT API实现智能回复。
  • 将回复结果文本通过TTS播放到机器人上的扬声器,完成一次对话。
2. 所用技术说明

代码讲解

1. 项目介绍

电子脑壳项目本身是一个标准的MVVM的WinUI项目,使用微软的轻量级DI容器管理对象的生命周期,MVVM使用的是社区工具包提供的框架,支持代码生成,简化VM的代码。

2. 核心代码讲解


  • 实时视频流解析手势,通过命名空间Windows.Media.Capture下的MediaCapture类和Windows.Media.Capture.Frames命名空间下的MediaFrameReader类,创建对象并注册帧处理事件,在帧处理事件中处理视频画面并传出到手势识别服务里进行手势识别,主要代码如下。
    1. //帧处理结果订阅
    2. private void Current_SoftwareBitmapFrameCaptured(object? sender, SoftwareBitmapEventArgs e)
    3. {
    4.     if (e.SoftwareBitmap is not null)
    5.     {
    6.         if (e.SoftwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
    7.               e.SoftwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
    8.         {
    9.             e.SoftwareBitmap = SoftwareBitmap.Convert(
    10.                 e.SoftwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
    11.         }
    12.         //手势识别服务获取
    13.         var service = App.GetService<GestureClassificationService>();
    14.         //调用手势分析代码
    15.         _ = service.HandPredictResultUnUseQueueAsync(calculator, modelPath, e.SoftwareBitmap);
    16.     }
    17. }
    复制代码
    涉及到的代码如下:
    MainViewModel
    CameraFrameService
  • 语音转文本的实现,WinUI(WASDK)继承了UWP的现代化的UI,也可以很好的使用WinRT的API进行操作。主要涉及的对象为命名空间Windows.Media.SpeechRecognition下的SpeechRecognizer对象。
    官网文档地址语音交互 定义自定义识别约束
    以下是语音转文本的部分代码 详细代码点击文字
    1. //创建识别为网络搜索
    2. var webSearchGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "webSearch", "sound");
    3.         //webSearchGrammar.Probability = SpeechRecognitionConstraintProbability.Min;
    4.         speechRecognizer.Constraints.Add(webSearchGrammar);
    5.         SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();
    6.         if (result.Status != SpeechRecognitionResultStatus.Success)
    7.         {
    8.             // Disable the recognition buttons.
    9.         }
    10.         else
    11.         {
    12.             // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
    13.             // some recognized phrases occur, or the garbage rule is hit.
    14.             //注册指定的事件
    15.             speechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed;
    16.             speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
    17.         }
    复制代码
  • 语音转文本之后调用ChatGPT API进行对话回复获取,使用ChatGPTSharp封装库实现。
    代码如下:
    1. private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
    2. {
    3.     // The garbage rule will not have a tag associated with it, the other rules will return a string matching the tag provided
    4.     // when generating the grammar.
    5.     var tag = "unknown";
    6.     if (args.Result.Constraint != null && isListening)
    7.     {
    8.         tag = args.Result.Constraint.Tag;
    9.         App.MainWindow.DispatcherQueue.TryEnqueue(() =>
    10.         {
    11.             ToastHelper.SendToast(tag, TimeSpan.FromSeconds(3));
    12.         });
    13.         Debug.WriteLine($"识别内容---{tag}");
    14.     }
    15.     // Developers may decide to use per-phrase confidence levels in order to tune the behavior of their
    16.     // grammar based on testing.
    17.     if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
    18.         args.Result.Confidence == SpeechRecognitionConfidence.High)
    19.     {
    20.         var result = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", args.Result.Text, tag, args.Result.Confidence.ToString());
    21.         App.MainWindow.DispatcherQueue.TryEnqueue(() =>
    22.         {
    23.             ToastHelper.SendToast(result, TimeSpan.FromSeconds(3));
    24.         });
    25.         if (args.Result.Text.ToUpper() == "打开B站")
    26.         {
    27.             await Launcher.LaunchUriAsync(new Uri(@"https://www.bilibili.com/"));
    28.         }
    29.         else if (args.Result.Text.ToUpper() == "撒个娇")
    30.         {
    31.             ElectronBotHelper.Instance.ToPlayEmojisRandom();
    32.         }
    33.         else
    34.         {
    35.             try
    36.             {
    37.                 // 根据机器人客户端工厂创建指定类型的处理程序 可以支持多种聊天API
    38.                 var chatBotClientFactory = App.GetService<IChatbotClientFactory>();
    39.                 var chatBotClientName = (await App.GetService<ILocalSettingsService>()
    40.                      .ReadSettingAsync<ComboxItemModel>(Constants.DefaultChatBotNameKey))?.DataKey;
    41.                 if (string.IsNullOrEmpty(chatBotClientName))
    42.                 {
    43.                     throw new Exception("未配置语音提供程序机密数据");
    44.                 }
    45.                 var chatBotClient = chatBotClientFactory.CreateChatbotClient(chatBotClientName);
    46.                 //调用指定的实现获取聊天返回结果
    47.                 var resultText = await chatBotClient.AskQuestionResultAsync(args.Result.Text);
    48.                 //isListening = false;
    49.                 await ReleaseRecognizerAsync();
    50.                 //调用文本转语音并进行播放方法
    51.                 await ElectronBotHelper.Instance.MediaPlayerPlaySoundByTTSAsync(resultText, false);      
    52.             }
    53.             catch (Exception ex)
    54.             {
    55.                 App.MainWindow.DispatcherQueue.TryEnqueue(() =>
    56.                 {
    57.                     ToastHelper.SendToast(ex.Message, TimeSpan.FromSeconds(3));
    58.                 });
    59.             }
    60.         }
    61.     }
    62.     else
    63.     {
    64.     }
    65. }
    复制代码
  • 结果文本转语音并进行播放,通过Windows.Media.SpeechSynthesis命名空间下的SpeechSynthesizer类,使用下面的代码可以将文本转化成Stream。
    1.   using SpeechSynthesizer synthesizer = new();
    2.             // Create a stream from the text. This will be played using a media element.
    3.             //将文本转化为Stream
    4.             var synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);
    复制代码
    然后使用MediaPlayer对象进行语音的播报。
    1. /// <summary>
    2. /// 播放声音
    3. /// </summary>
    4. /// <param name="content"></param>
    5. /// <returns></returns>
    6. public async Task MediaPlayerPlaySoundByTTSAsync(string content, bool isOpenMediaEnded = true)
    7. {
    8.     _isOpenMediaEnded = isOpenMediaEnded;
    9.     if (!string.IsNullOrWhiteSpace(content))
    10.     {
    11.         try
    12.         {
    13.             var localSettingsService = App.GetService<ILocalSettingsService>();
    14.             var audioModel = await localSettingsService
    15.                 .ReadSettingAsync<ComboxItemModel>(Constants.DefaultAudioNameKey);
    16.             var audioDevs = await EbHelper.FindAudioDeviceListAsync();
    17.             if (audioModel != null)
    18.             {
    19.                 var audioSelect = audioDevs.FirstOrDefault(c => c.DataValue == audioModel.DataValue) ?? new ComboxItemModel();
    20.                 var selectedDevice = (DeviceInformation)audioSelect.Tag!;
    21.                 if (selectedDevice != null)
    22.                 {
    23.                     mediaPlayer.AudioDevice = selectedDevice;
    24.                 }
    25.             }
    26.             //获取TTS服务实例
    27.             var speechAndTTSService = App.GetService<ISpeechAndTTSService>();
    28.             //转化文本到Stream
    29.             var stream = await speechAndTTSService.TextToSpeechAsync(content);
    30.             //播放stream
    31.             mediaPlayer.SetStreamSource(stream);
    32.             mediaPlayer.Play();
    33.             isTTS = true;
    34.         }
    35.         catch (Exception)
    36.         {
    37.         }
    38.     }
    39. }
    复制代码
    至此一次完整的识别对话流程就结束了,软件的界面如下图,感兴趣的同学可以点击图片查看项目源码地址查看其他的功能:

个人感悟

个人觉得DotNET的生态还是差了些,尤其是ML.NET的轮子还是太少了,毕竟参与的人少,而且知识迁移也需要成本,熟悉其他机器学习框架的人可能不懂DotNET。
所以作为社区的一员,我觉得我们需要走出去,然后再回来,走出去就是先学习其他的机器学习框架,然后回来用DotNET进行应用,这样轮子多了,社区就会越来越繁荣。
我也能多多的复制粘贴大家的代码了。
参考推荐文档项目如下:


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

美食家大橙子

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表