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

发布时间 2023-03-22 19:13:33作者: 绿荫阿广

前言

之前写过一篇基于ML.NET的手部关键点分类的博客,可以根据图片进行手部的提取分类,于是我就将手势分类和摄像头数据结合,集成到了我开发的电子脑壳软件里。

电子脑壳是一个为稚晖君开源的桌面机器人ElectronBot提供一些软件功能的桌面程序项目。它是由绿荫阿广也就是我开发的,使用了微软的WASDK框架。

电子脑壳算是本人学习WinUI开发的练习项目了,通过根据一些开源的项目的学习,将一些功能进行整合,比如手势识别触发语音转文本,然后接入ChatGPT结合文本转语音的方式,实现机器人的对话。

此博客算是实战记录了,替大家先踩坑。

下图链接为机器人的演示视频,通过对话,让ChatGPT给我讲了一个骆驼祥子的故事,只不过这个故事有点离谱,本来前部分还正常,后面就开始瞎编了,比如祥子有了一头驴,最后还成为了商人。

大家观看觉得不错的话给点个赞。

B站视频演示链接

具体的实现方案

1. 方案思路叙述

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

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

2. 所用技术说明

代码讲解

1. 项目介绍

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

project

2. 核心代码讲解

  • 实时视频流解析手势,通过命名空间Windows.Media.Capture下的MediaCapture类和Windows.Media.Capture.Frames命名空间下的MediaFrameReader类,创建对象并注册帧处理事件,在帧处理事件中处理视频画面并传出到手势识别服务里进行手势识别,主要代码如下。

    //帧处理结果订阅
    private void Current_SoftwareBitmapFrameCaptured(object? sender, SoftwareBitmapEventArgs e)
    {
        if (e.SoftwareBitmap is not null)
        {
    
            if (e.SoftwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                  e.SoftwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                e.SoftwareBitmap = SoftwareBitmap.Convert(
                    e.SoftwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }
            //手势识别服务获取
            var service = App.GetService<GestureClassificationService>();
            //调用手势分析代码
            _ = service.HandPredictResultUnUseQueueAsync(calculator, modelPath, e.SoftwareBitmap);
        }
    }
    

    涉及到的代码如下:

    MainViewModel

    CameraFrameService

  • 语音转文本的实现,WinUI(WASDK)继承了UWP的现代化的UI,也可以很好的使用WinRT的API进行操作。主要涉及的对象为命名空间Windows.Media.SpeechRecognition下的SpeechRecognizer对象。

    官网文档地址语音交互 定义自定义识别约束

    以下是语音转文本的部分代码 详细代码点击文字

    //创建识别为网络搜索
    var webSearchGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "webSearch", "sound");
            //webSearchGrammar.Probability = SpeechRecognitionConstraintProbability.Min;
            speechRecognizer.Constraints.Add(webSearchGrammar);
            SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();
    
            if (result.Status != SpeechRecognitionResultStatus.Success)
            {
                // Disable the recognition buttons.
            }
            else
            {
                // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
                // some recognized phrases occur, or the garbage rule is hit.
                //注册指定的事件
                speechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed;
                speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
            }
    
  • 语音转文本之后调用ChatGPT API进行对话回复获取,使用ChatGPTSharp封装库实现。

    代码如下:

    private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
    {
        // The garbage rule will not have a tag associated with it, the other rules will return a string matching the tag provided
        // when generating the grammar.
        var tag = "unknown";
    
        if (args.Result.Constraint != null && isListening)
        {
            tag = args.Result.Constraint.Tag;
    
            App.MainWindow.DispatcherQueue.TryEnqueue(() =>
            {
                ToastHelper.SendToast(tag, TimeSpan.FromSeconds(3));
            });
    
    
            Debug.WriteLine($"识别内容---{tag}");
        }
    
        // Developers may decide to use per-phrase confidence levels in order to tune the behavior of their 
        // grammar based on testing.
        if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
            args.Result.Confidence == SpeechRecognitionConfidence.High)
        {
            var result = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", args.Result.Text, tag, args.Result.Confidence.ToString());
    
    
            App.MainWindow.DispatcherQueue.TryEnqueue(() =>
            {
                ToastHelper.SendToast(result, TimeSpan.FromSeconds(3));
            });
    
    
            if (args.Result.Text.ToUpper() == "打开B站")
            {
                await Launcher.LaunchUriAsync(new Uri(@"https://www.bilibili.com/"));
            }
            else if (args.Result.Text.ToUpper() == "撒个娇")
            {
                ElectronBotHelper.Instance.ToPlayEmojisRandom();
            }
            else
            {
                try
                {
                    // 根据机器人客户端工厂创建指定类型的处理程序 可以支持多种聊天API
                    var chatBotClientFactory = App.GetService<IChatbotClientFactory>();
    
                    var chatBotClientName = (await App.GetService<ILocalSettingsService>()
                         .ReadSettingAsync<ComboxItemModel>(Constants.DefaultChatBotNameKey))?.DataKey;
    
                    if (string.IsNullOrEmpty(chatBotClientName))
                    {
                        throw new Exception("未配置语音提供程序机密数据");
                    }
    
                    var chatBotClient = chatBotClientFactory.CreateChatbotClient(chatBotClientName);
                    //调用指定的实现获取聊天返回结果
                    var resultText = await chatBotClient.AskQuestionResultAsync(args.Result.Text);
    
                    //isListening = false;
                    await ReleaseRecognizerAsync();
                    //调用文本转语音并进行播放方法
                    await ElectronBotHelper.Instance.MediaPlayerPlaySoundByTTSAsync(resultText, false);      
                }
                catch (Exception ex)
                {
                    App.MainWindow.DispatcherQueue.TryEnqueue(() =>
                    {
                        ToastHelper.SendToast(ex.Message, TimeSpan.FromSeconds(3));
                    });
    
                }
            }
        }
        else
        {
        }
    }
    
  • 结果文本转语音并进行播放,通过Windows.Media.SpeechSynthesis命名空间下的SpeechSynthesizer类,使用下面的代码可以将文本转化成Stream。

      using SpeechSynthesizer synthesizer = new();
                // Create a stream from the text. This will be played using a media element.
    
                //将文本转化为Stream
                var synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);
    

    然后使用MediaPlayer对象进行语音的播报。

    
     /// <summary>
    /// 播放声音
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public async Task MediaPlayerPlaySoundByTTSAsync(string content, bool isOpenMediaEnded = true)
    {
        _isOpenMediaEnded = isOpenMediaEnded;
        if (!string.IsNullOrWhiteSpace(content))
        {
            try
            {
                var localSettingsService = App.GetService<ILocalSettingsService>();
    
                var audioModel = await localSettingsService
                    .ReadSettingAsync<ComboxItemModel>(Constants.DefaultAudioNameKey);
    
                var audioDevs = await EbHelper.FindAudioDeviceListAsync();
    
                if (audioModel != null)
                {
                    var audioSelect = audioDevs.FirstOrDefault(c => c.DataValue == audioModel.DataValue) ?? new ComboxItemModel();
    
                    var selectedDevice = (DeviceInformation)audioSelect.Tag!;
    
                    if (selectedDevice != null)
                    {
                        mediaPlayer.AudioDevice = selectedDevice;
                    }
                }
                //获取TTS服务实例
                var speechAndTTSService = App.GetService<ISpeechAndTTSService>();
                //转化文本到Stream
                var stream = await speechAndTTSService.TextToSpeechAsync(content);
                //播放stream
                mediaPlayer.SetStreamSource(stream);
                mediaPlayer.Play();
                isTTS = true;
            }
            catch (Exception)
            {
            }
        }
    }
    

    至此一次完整的识别对话流程就结束了,软件的界面如下图,感兴趣的同学可以点击图片查看项目源码地址查看其他的功能:

    电子脑壳源码链接

个人感悟

个人觉得DotNET的生态还是差了些,尤其是ML.NET的轮子还是太少了,毕竟参与的人少,而且知识迁移也需要成本,熟悉其他机器学习框架的人可能不懂DotNET。

所以作为社区的一员,我觉得我们需要走出去,然后再回来,走出去就是先学习其他的机器学习框架,然后回来用DotNET进行应用,这样轮子多了,社区就会越来越繁荣。

我也能多多的复制粘贴大家的代码了。

参考推荐文档项目如下: