WitUtteranceMatcher.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. using System.Text.RegularExpressions;
  9. using Meta.WitAi.Json;
  10. using Meta.WitAi.Utilities;
  11. using UnityEngine;
  12. namespace Meta.WitAi.CallbackHandlers
  13. {
  14. [AddComponentMenu("Wit.ai/Response Matchers/Utterance Matcher")]
  15. public class WitUtteranceMatcher : WitResponseHandler
  16. {
  17. [SerializeField] private string searchText;
  18. [SerializeField] private bool exactMatch = true;
  19. [SerializeField] private bool useRegex;
  20. [SerializeField] private StringEvent onUtteranceMatched = new StringEvent();
  21. private Regex regex;
  22. protected override string OnValidateResponse(WitResponseNode response, bool isEarlyResponse)
  23. {
  24. var text = response["text"].Value;
  25. if (!IsMatch(text))
  26. {
  27. return "Required utterance does not match";
  28. }
  29. return "";
  30. }
  31. protected override void OnResponseInvalid(WitResponseNode response, string error){}
  32. protected override void OnResponseSuccess(WitResponseNode response)
  33. {
  34. var text = response["text"].Value;
  35. onUtteranceMatched?.Invoke(text);
  36. }
  37. private bool IsMatch(string text)
  38. {
  39. if (useRegex)
  40. {
  41. if (null == regex)
  42. {
  43. regex = new Regex(searchText, RegexOptions.Compiled | RegexOptions.IgnoreCase);
  44. }
  45. var match = regex.Match(text);
  46. if (match.Success)
  47. {
  48. if (exactMatch && match.Value == text)
  49. {
  50. return true;
  51. }
  52. else
  53. {
  54. return true;
  55. }
  56. }
  57. }
  58. else if (exactMatch && text.ToLower() == searchText.ToLower())
  59. {
  60. return true;
  61. }
  62. else if (text.ToLower().Contains(searchText.ToLower()))
  63. {
  64. return true;
  65. }
  66. return false;
  67. }
  68. }
  69. }