clean project

This commit is contained in:
Helar Jaadla
2022-03-07 17:52:41 +02:00
parent a174b45bd2
commit cbeb10ec35
5100 changed files with 837159 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
Copyright (c) 2021, Wit.ai, Inc. All rights reserved.
You are hereby granted a non-exclusive, worldwide, royalty-free license to
use, copy, modify, and distribute this software in source code or binary
form for use in connection with the web services and APIs provided by
Wit.ai.
As with any software that integrates with the Wit.ai platform, your use
of this software is subject to the Wit.ai Terms of Service
[https://wit.ai/terms]. This copyright notice shall be included in all
copies or substantial portions of the software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: ca52cefa5d9be7643968c328c2c55512
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 13bc28f0ddcf2524286888da398e2c5a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,120 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &2494780024417762855
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2494780024417762853}
- component: {fileID: 2494780024417762852}
m_Layer: 0
m_Name: Wit
m_TagString: Untagged
m_Icon: {fileID: 2800000, guid: d3b5ac4c8b01ef14a8a66d7e2a4991cc, type: 3}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &2494780024417762853
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2494780024417762855}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &2494780024417762852
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2494780024417762855}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 89cc923dc7c7b4f0b91a7df096c80b00, type: 3}
m_Name:
m_EditorClassIdentifier:
configuration: {fileID: 0}
minKeepAliveVolume: 0.01
minKeepAliveTime: 2
maxRecordingTime: 10
events:
OnResponse:
m_PersistentCalls:
m_Calls: []
OnError:
m_PersistentCalls:
m_Calls:
- m_Target: {fileID: 0}
m_MethodName:
m_Mode: 1
m_Arguments:
m_ObjectArgument: {fileID: 0}
m_ObjectArgumentAssemblyTypeName:
m_IntArgument: 0
m_FloatArgument: 0
m_StringArgument:
m_BoolArgument: 0
m_CallState: 2
OnMicLevelChanged:
m_PersistentCalls:
m_Calls:
- m_Target: {fileID: 0}
m_MethodName: set_fillAmount
m_Mode: 0
m_Arguments:
m_ObjectArgument: {fileID: 0}
m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine
m_IntArgument: 0
m_FloatArgument: 0
m_StringArgument:
m_BoolArgument: 0
m_CallState: 2
OnStartListening:
m_PersistentCalls:
m_Calls:
- m_Target: {fileID: 0}
m_MethodName: set_text
m_Mode: 5
m_Arguments:
m_ObjectArgument: {fileID: 0}
m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine
m_IntArgument: 0
m_FloatArgument: 0
m_StringArgument: Deactivate
m_BoolArgument: 0
m_CallState: 2
OnStoppedListening:
m_PersistentCalls:
m_Calls:
- m_Target: {fileID: 0}
m_MethodName: set_text
m_Mode: 5
m_Arguments:
m_ObjectArgument: {fileID: 0}
m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine
m_IntArgument: 0
m_FloatArgument: 0
m_StringArgument: Activate
m_BoolArgument: 0
m_CallState: 2
- m_Target: {fileID: 0}
m_MethodName: set_fillAmount
m_Mode: 4
m_Arguments:
m_ObjectArgument: {fileID: 0}
m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine
m_IntArgument: 0
m_FloatArgument: 0
m_StringArgument:
m_BoolArgument: 0
m_CallState: 2

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: dc847e9f83e1d68469a4741be4840ccf
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5b027aeb22062344bac09580e2a41e81
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

View File

@@ -0,0 +1,116 @@
fileFormatVersion: 2
guid: 2ed0be21c4a8bce4fadffab71d5b6e85
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 11
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
applyGammaDecoding: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -0,0 +1,116 @@
fileFormatVersion: 2
guid: 6a61dbb599169b64ca5584c8eebeb69e
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 11
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
applyGammaDecoding: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

View File

@@ -0,0 +1,116 @@
fileFormatVersion: 2
guid: d3b5ac4c8b01ef14a8a66d7e2a4991cc
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 11
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
applyGammaDecoding: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0c637df927b25624d9774400db7b0d1a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 16a820272b4003349b419acb053e0bca
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,156 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Data.Configuration;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi
{
public abstract class BaseWitWindow : EditorWindow
{
protected static WitConfiguration[] witConfigs = Array.Empty<WitConfiguration>();
protected static string[] witConfigNames = Array.Empty<string>();
protected int witConfigIndex = -1;
protected WitConfiguration witConfiguration;
public static WitConfiguration[] WitConfigs => witConfigs;
public static string[] WitConfigNames => witConfigNames;
protected virtual string HeaderLink => null;
protected virtual void OnEnable()
{
RefreshConfigList();
}
protected virtual void OnDisable()
{
}
protected virtual void OnProjectChange()
{
RefreshConfigList();
}
protected void RefreshContent()
{
if (witConfiguration) witConfiguration.UpdateData();
}
protected static void RefreshConfigList()
{
string[] guids = AssetDatabase.FindAssets("t:WitConfiguration");
witConfigs = new WitConfiguration[guids.Length];
witConfigNames = new string[guids.Length];
for (int i = 0; i < guids.Length; i++) //probably could get optimized
{
string path = AssetDatabase.GUIDToAssetPath(guids[i]);
witConfigs[i] = AssetDatabase.LoadAssetAtPath<WitConfiguration>(path);
witConfigNames[i] = witConfigs[i].name;
}
}
protected virtual void OnGUI()
{
minSize = new Vector2(450, 300);
DrawHeader();
GUILayout.BeginVertical(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
OnDrawContent();
GUILayout.EndVertical();
}
protected abstract void OnDrawContent();
protected void DrawHeader()
{
DrawHeader(HeaderLink);
}
public static void DrawHeader(string headerLink = null, Texture2D header = null)
{
GUILayout.BeginVertical();
GUILayout.Space(16);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (!header) header = WitStyles.MainHeader;
var headerWidth = Mathf.Min(header.width, EditorGUIUtility.currentViewWidth - 64);
var headerHeight =
header.height * headerWidth / header.width;
if (GUILayout.Button(header, "Label", GUILayout.Width(headerWidth), GUILayout.Height(headerHeight)))
{
Application.OpenURL(!string.IsNullOrEmpty(headerLink)
? headerLink
: "https://wit.ai");
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(16);
GUILayout.EndVertical();
}
protected bool DrawWitConfigurationPopup()
{
if (null == witConfigs) return false;
bool changed = false;
if (witConfigs.Length == 1)
{
GUILayout.BeginHorizontal();
GUILayout.Label("Wit Configuration");
EditorGUILayout.LabelField(witConfigNames[0], EditorStyles.popup);
GUILayout.EndHorizontal();
}
else
{
var selectedConfig = EditorGUILayout.Popup("Wit Configuration", witConfigIndex, witConfigNames);
if (selectedConfig != witConfigIndex)
{
witConfigIndex = selectedConfig;
changed = true;
}
}
if (changed || witConfigs.Length > 0 && !witConfiguration)
{
if (witConfigIndex < 0 || witConfigIndex >= witConfigs.Length)
{
witConfigIndex = 0;
}
witConfiguration = witConfigs[witConfigIndex];
RefreshContent();
}
return changed;
}
public static void BeginCenter(int width = -1)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (width > 0)
{
GUILayout.BeginVertical(GUILayout.Width(width));
}
else
{
GUILayout.BeginVertical();
}
}
public static void EndCenter()
{
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
}
}

View File

@@ -0,0 +1,15 @@
fileFormatVersion: 2
guid: cb1fb949657a24a43bce2710d35ef1df
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- m_ViewDataDictionary: {instanceID: 0}
- witIcon: {fileID: 2800000, guid: d3b5ac4c8b01ef14a8a66d7e2a4991cc, type: 3}
- mainHeader: {fileID: 2800000, guid: 6a61dbb599169b64ca5584c8eebeb69e, type: 3}
- continueButton: {fileID: 2800000, guid: 2ed0be21c4a8bce4fadffab71d5b6e85, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 26754a049aa53d445a323de4dcb955e3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using System.Linq;
using Facebook.WitAi.Data.Configuration;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.CallbackHandlers
{
public class SimpleIntentHandlerEditor : Editor
{
private SimpleIntentHandler handler;
private string[] intentNames;
private int intentIndex;
private void OnEnable()
{
handler = target as SimpleIntentHandler;
}
public override void OnInspectorGUI()
{
if (!handler.wit)
{
GUILayout.Label(
"Wit component is not present in the scene. Add wit to scene to get intent and entity suggestions.",
EditorStyles.helpBox);
}
if (handler && handler.wit && null == intentNames)
{
if (handler.wit is IWitRuntimeConfigProvider provider && null != provider.RuntimeConfiguration && provider.RuntimeConfiguration.witConfiguration)
{
provider.RuntimeConfiguration.witConfiguration.UpdateData();
intentNames = provider.RuntimeConfiguration.witConfiguration.intents.Select(i => i.name).ToArray();
intentIndex = Array.IndexOf(intentNames, handler.intent);
}
}
WitEditorUI.FallbackPopup(serializedObject, "intent",
intentNames, ref intentIndex);
var confidenceProperty = serializedObject.FindProperty("confidence");
EditorGUILayout.PropertyField(confidenceProperty);
GUILayout.Space(16);
var eventProperty = serializedObject.FindProperty("onIntentTriggered");
EditorGUILayout.PropertyField(eventProperty);
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 10996c842bbaede43a73adef9cddba5a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,86 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using System.Linq;
using Facebook.WitAi.Data.Configuration;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.CallbackHandlers
{
public class SimpleStringEntityHandlerEditor : Editor
{
private SimpleStringEntityHandler handler;
private string[] intentNames;
private int intentIndex;
private string[] entityNames;
private int entityIndex;
private void OnEnable()
{
handler = target as SimpleStringEntityHandler;
if (handler && handler.wit && null == intentNames)
{
if (handler.wit is IWitRuntimeConfigProvider provider &&
null != provider.RuntimeConfiguration &&
provider.RuntimeConfiguration.witConfiguration)
{
provider.RuntimeConfiguration.witConfiguration.UpdateData();
intentNames = provider.RuntimeConfiguration.witConfiguration.intents.Select(i => i.name).ToArray();
intentIndex = Array.IndexOf(intentNames, handler.intent);
}
}
}
public override void OnInspectorGUI()
{
var handler = target as SimpleStringEntityHandler;
if (!handler) return;
if (!handler.wit)
{
GUILayout.Label("Wit component is not present in the scene. Add wit to scene to get intent and entity suggestions.", EditorStyles.helpBox);
}
var intentChanged = WitEditorUI.FallbackPopup(serializedObject,"intent", intentNames, ref intentIndex);
if (intentChanged ||
null != intentNames && intentNames.Length > 0 && null == entityNames)
{
if (handler && handler.wit && null == intentNames)
{
if (handler.wit is IWitRuntimeConfigProvider provider &&
null != provider.RuntimeConfiguration &&
provider.RuntimeConfiguration.witConfiguration)
{
var entities = provider.RuntimeConfiguration.witConfiguration.intents[intentIndex]?.entities;
if (null != entities)
{
entityNames = entities.Select((e) => e.name).ToArray();
entityIndex = Array.IndexOf(entityNames, handler.entity);
}
}
}
}
WitEditorUI.FallbackPopup(serializedObject, "entity", entityNames, ref entityIndex);
var confidenceProperty = serializedObject.FindProperty("confidence");
EditorGUILayout.PropertyField(confidenceProperty);
EditorGUILayout.Space(16);
var formatProperty = serializedObject.FindProperty("format");
EditorGUILayout.PropertyField(formatProperty);
GUILayout.Space(16);
var eventProperty = serializedObject.FindProperty("onIntentEntityTriggered");
EditorGUILayout.PropertyField(eventProperty);
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a303e99a01d07d54e9659f3b46adbe25
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,241 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System.Collections.Generic;
using Facebook.WitAi.Data;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.CallbackHandlers
{
public class ValuePathMatcherPropertyDrawer : PropertyDrawer
{
private string currentEditPath;
class Properties
{
public const string witValueRef = "witValueReference";
public const string path = "path";
public const string contentRequired = "contentRequired";
public const string matchMethod = "matchMethod";
public const string comparisonMethod = "comparisonMethod";
public const string matchValue = "matchValue";
public const string floatingPointComparisonTolerance =
"floatingPointComparisonTolerance";
}
private Dictionary<string, bool> foldouts =
new Dictionary<string, bool>();
private string GetPropertyPath(SerializedProperty property)
{
var valueRefProp = property.FindPropertyRelative(Properties.witValueRef);
if (valueRefProp.objectReferenceValue)
{
return ((WitValue) valueRefProp.objectReferenceValue).path;
}
return property.FindPropertyRelative(Properties.path).stringValue;
}
private bool IsEditingProperty(SerializedProperty property)
{
var path = GetPropertyPath(property);
return path == currentEditPath || string.IsNullOrEmpty(path);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
float height = 0;
// Path
height += EditorGUIUtility.singleLineHeight;
if (IsExpanded(property))
{
// Content Required
height += EditorGUIUtility.singleLineHeight;
// Match Method
height += EditorGUIUtility.singleLineHeight;
if (ComparisonMethodsVisible(property))
{
// Comparison Method
height += EditorGUIUtility.singleLineHeight;
}
if (ComparisonValueVisible(property))
{
// Comparison Value
height += EditorGUIUtility.singleLineHeight;
}
if (FloatingToleranceVisible(property))
{
// Floating Point Tolerance
height += EditorGUIUtility.singleLineHeight;
}
height += 4;
}
return height;
}
private bool IsExpanded(SerializedProperty property)
{
return foldouts.TryGetValue(GetPropertyPath(property), out bool value) && value;
}
private bool Foldout(Rect rect, SerializedProperty property)
{
var path = GetPropertyPath(property);
if (!foldouts.TryGetValue(path, out var value))
{
foldouts[path] = false;
}
foldouts[path] = EditorGUI.Foldout(rect, value, "");
return foldouts[path];
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var rect = new Rect(position);
rect.height = EditorGUIUtility.singleLineHeight;
var path = property.FindPropertyRelative(Properties.path);
var valueRefProp = property.FindPropertyRelative(Properties.witValueRef);
var editIconWidth = 24;
var pathRect = new Rect(rect);
pathRect.width -= editIconWidth;
var pathValue = GetPropertyPath(property);
if (IsEditingProperty(property))
{
if (!valueRefProp.objectReferenceValue)
{
pathRect.width -= WitStyles.IconButtonWidth;
var value = EditorGUI.TextField(pathRect, path.stringValue);
if (value != path.stringValue)
{
path.stringValue = value;
}
pathRect.width += WitStyles.IconButtonWidth;
var pickerRect = new Rect(pathRect);
pickerRect.x = pathRect.x + pathRect.width - 20;
pickerRect.width = 20;
if (GUI.Button(pickerRect, WitStyles.ObjectPickerIcon, "Label"))
{
var id = EditorGUIUtility.GetControlID(FocusType.Passive) + 100;
EditorGUIUtility.ShowObjectPicker<WitValue>(
(WitValue) valueRefProp.objectReferenceValue, false, "", id);
}
}
else
{
EditorGUI.PropertyField(pathRect, valueRefProp, new GUIContent());
}
if (Event.current.commandName == "ObjectSelectorClosed")
{
valueRefProp.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
}
pathValue = GetPropertyPath(property);
if (pathValue != currentEditPath && null != currentEditPath)
{
foldouts[currentEditPath] = false;
currentEditPath = GetPropertyPath(property);
foldouts[currentEditPath] = true;
}
}
else
{
if (valueRefProp.objectReferenceValue)
{
EditorGUI.LabelField(pathRect, valueRefProp.objectReferenceValue.name);
}
else
{
EditorGUI.LabelField(pathRect, path.stringValue);
}
}
var editRect = new Rect(rect);
editRect.x = pathRect.x + pathRect.width + 8;
if (Foldout(rect, property))
{
if (GUI.Button(editRect, WitStyles.EditIcon, "Label"))
{
if (currentEditPath == pathValue)
{
currentEditPath = null;
}
else
{
currentEditPath = pathValue;
}
}
rect.x += WitStyles.IconButtonWidth;
rect.width -= WitStyles.IconButtonWidth;
rect.y += rect.height;
EditorGUI.PropertyField(rect, property.FindPropertyRelative(Properties.contentRequired));
rect.y += rect.height;
EditorGUI.PropertyField(rect, property.FindPropertyRelative(Properties.matchMethod));
if (ComparisonMethodsVisible(property))
{
rect.y += rect.height;
EditorGUI.PropertyField(rect,
property.FindPropertyRelative(Properties.comparisonMethod));
}
if (ComparisonValueVisible(property))
{
rect.y += rect.height;
EditorGUI.PropertyField(rect,
property.FindPropertyRelative(Properties.matchValue));
}
if (FloatingToleranceVisible(property))
{
rect.y += rect.height;
EditorGUI.PropertyField(rect,
property.FindPropertyRelative(Properties.floatingPointComparisonTolerance));
}
}
}
private bool ComparisonMethodsVisible(SerializedProperty property)
{
var matchedMethodProperty = property.FindPropertyRelative(Properties.matchMethod);
return matchedMethodProperty.enumValueIndex > (int) MatchMethod.RegularExpression;
}
private bool ComparisonValueVisible(SerializedProperty property)
{
var matchedMethodProperty = property.FindPropertyRelative(Properties.matchMethod);
return matchedMethodProperty.enumValueIndex > 0;
}
private bool FloatingToleranceVisible(SerializedProperty property)
{
var matchedMethodProperty = property.FindPropertyRelative(Properties.matchMethod);
var comparisonMethodProperty =
property.FindPropertyRelative(Properties.comparisonMethod);
var comparisonMethod = comparisonMethodProperty.enumValueIndex;
return matchedMethodProperty.enumValueIndex >= (int) MatchMethod.FloatComparison &&
(comparisonMethod == (int) ComparisonMethod.Equals || comparisonMethod == (int) ComparisonMethod.NotEquals);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 70c91e08d884bfe4a99b40d2706b15d0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 817d0e10131c4339849a5c99f8fb082b
timeCreated: 1624319154

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d192dfd6dc3ff0240b7171d81525428b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
namespace Facebook.WitAi.Data.Configuration
{
public interface IApplicationDetailProvider
{
void DrawApplication(WitApplication application);
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7ed426c1b615d4b44a3c55c12850ce15
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using UnityEngine;
namespace Facebook.WitAi.Data.Configuration
{
public class WitApplicationDetailProvider : IApplicationDetailProvider
{
public void DrawApplication(WitApplication application)
{
if (string.IsNullOrEmpty(application.name))
{
GUILayout.Label("Loading...");
}
else
{
InfoField("Name", application.name);
InfoField("ID", application.id);
InfoField("Language", application.lang);
InfoField("Created", application.createdAt);
GUILayout.BeginHorizontal();
GUILayout.Label("Private", GUILayout.Width(100));
GUILayout.Toggle(application.isPrivate, "");
GUILayout.EndHorizontal();
}
}
private void InfoField(string name, string value)
{
GUILayout.BeginHorizontal();
GUILayout.Label(name, GUILayout.Width(100));
GUILayout.Label(value, "TextField");
GUILayout.EndHorizontal();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 394d4d63ba17f4ed5918eccdd3b7059f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,565 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Facebook.WitAi.Configuration;
using Facebook.WitAi.Data.Entities;
using Facebook.WitAi.Data.Intents;
using Facebook.WitAi.Data.Traits;
using Facebook.WitAi.Utilities;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Data.Configuration
{
public class WitConfigurationEditor : Editor
{
public IApplicationDetailProvider appDrawer = new WitApplicationDetailProvider();
private WitConfiguration configuration;
private Dictionary<string, bool> foldouts = new Dictionary<string, bool>();
private int selectedToolPanel;
private readonly string[] toolPanelNames = new[]
{
"Application",
"Intents",
"Entities",
"Traits"
};
private readonly string[] toolPanelNamesOnlyAppInfo = new[]
{
"Application"
};
private readonly string[] toolPanelNamesWithoutAppInfo = new[]
{
"Intents",
"Entities",
"Traits"
};
private const int TOOL_PANEL_APP = 0;
private const int TOOL_PANEL_INTENTS = 1;
private const int TOOL_PANEL_ENTITIES = 2;
private const int TOOL_PANEL_TRAITS = 3;
private Editor applicationEditor;
private Vector2 scroll;
private bool appConfigurationFoldout;
private bool initialized = false;
public bool drawHeader = true;
private string currentToken;
private bool endpointConfigurationFoldout;
private bool IsTokenValid => !string.IsNullOrEmpty(configuration.clientAccessToken) &&
configuration.clientAccessToken.Length == 32;
public void Initialize()
{
WitAuthUtility.InitEditorTokens();
configuration = target as WitConfiguration;
currentToken = WitAuthUtility.GetAppServerToken(configuration);
if (WitAuthUtility.IsServerTokenValid(currentToken) && !string.IsNullOrEmpty(configuration?.clientAccessToken))
{
configuration?.UpdateData(() =>
{
EditorUtility.SetDirty(configuration);
});
}
}
public override void OnInspectorGUI()
{
if (!initialized || configuration != target)
{
Initialize();
initialized = true;
}
if (drawHeader)
{
string link = null;
if (configuration && null != configuration.application &&
!string.IsNullOrEmpty(configuration.application.id))
{
link = $"https://wit.ai/apps/{configuration.application.id}/settings";
}
BaseWitWindow.DrawHeader(headerLink: link);
}
GUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.BeginHorizontal();
GUILayout.Space(16);
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
appConfigurationFoldout = EditorGUILayout.Foldout(appConfigurationFoldout,
"Application Configuration", true);
if (!string.IsNullOrEmpty(configuration?.application?.name))
{
GUILayout.FlexibleSpace();
GUILayout.Label(configuration?.application?.name);
}
GUILayout.EndHorizontal();
bool hasApplicationInfo = configuration && null != configuration.application;
if (appConfigurationFoldout || !IsTokenValid)
{
GUILayout.BeginHorizontal();
var token = EditorGUILayout.PasswordField("Server Access Token", currentToken);
if (token != currentToken)
{
currentToken = token;
ApplyToken(token);
}
if (configuration && GUILayout.Button("Refresh", GUILayout.Width(75)))
{
ApplyToken(currentToken);
}
if (GUILayout.Button(WitStyles.PasteIcon, WitStyles.ImageIcon))
{
currentToken = EditorGUIUtility.systemCopyBuffer;
ApplyToken(currentToken);
}
GUILayout.EndHorizontal();
if (configuration)
{
var clientToken =
EditorGUILayout.PasswordField("Client Access Token",
configuration.clientAccessToken);
if (clientToken != configuration.clientAccessToken)
{
configuration.clientAccessToken = clientToken;
EditorUtility.SetDirty(configuration);
}
var timeout = EditorGUILayout.IntField(new GUIContent("Request Timeout (ms)", "The amount of time a server request can take to respond to voice."), configuration.timeoutMS);
if (timeout != configuration.timeoutMS)
{
configuration.timeoutMS = timeout;
EditorUtility.SetDirty(configuration);
}
GUILayout.BeginHorizontal();
GUILayout.Space(16);
GUILayout.BeginVertical();
endpointConfigurationFoldout = EditorGUILayout.Foldout(endpointConfigurationFoldout,
"Endpoint Configuration", true);
GUILayout.BeginHorizontal();
GUILayout.Space(16);
GUILayout.BeginVertical();
if (endpointConfigurationFoldout)
{
if (null == configuration.endpointConfiguration)
{
configuration.endpointConfiguration = new WitEndpointConfig();
EditorUtility.SetDirty(configuration);
}
var confSerializedObject = new SerializedObject(configuration);
var epConfProp = confSerializedObject.FindProperty("endpointConfiguration");
EditorGUILayout.PropertyField(epConfProp);
confSerializedObject.ApplyModifiedProperties();
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
}
GUILayout.EndVertical();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
if (hasApplicationInfo)
{
if (configuration.application.id != null && !configuration.application.id.StartsWith("voice"))
{
selectedToolPanel = GUILayout.Toolbar(selectedToolPanel, toolPanelNames);
}
else
{
selectedToolPanel = GUILayout.Toolbar(selectedToolPanel, toolPanelNamesOnlyAppInfo);
}
}
else
{
selectedToolPanel = GUILayout.Toolbar(selectedToolPanel, toolPanelNamesWithoutAppInfo);
}
scroll = GUILayout.BeginScrollView(scroll);
switch (hasApplicationInfo ? selectedToolPanel : selectedToolPanel + 1)
{
case TOOL_PANEL_APP:
DrawApplication(configuration.application);
break;
case TOOL_PANEL_INTENTS:
DrawIntents();
break;
case TOOL_PANEL_ENTITIES:
DrawEntities();
break;
case TOOL_PANEL_TRAITS:
DrawTraits();
break;
}
GUILayout.EndScrollView();
if (GUILayout.Button("Open Wit.ai"))
{
if (!string.IsNullOrEmpty(configuration.application?.id))
{
Application.OpenURL($"https://wit.ai/apps/{configuration.application.id}");
}
else
{
Application.OpenURL("https://wit.ai");
}
}
}
private void ApplyToken(string token)
{
if (!string.IsNullOrEmpty(token) && WitAuthUtility.IsServerTokenValid(token))
{
RefreshAppData(WitAuthUtility.GetAppId(token), token);
}
}
private void RefreshAppData(string appId, string token = "")
{
var refreshToken = WitAuthUtility.GetAppServerToken(appId, token);
if (string.IsNullOrEmpty(refreshToken) &&
string.IsNullOrEmpty(appId) &&
!string.IsNullOrEmpty(configuration?.application?.id))
{
refreshToken = WitAuthUtility.GetAppServerToken(configuration.application.id,
WitAuthUtility.ServerToken);
appId = WitAuthUtility.GetAppId(refreshToken);
if (string.IsNullOrEmpty(appId))
{
UpdateTokenData(refreshToken, () =>
{
appId = WitAuthUtility.GetAppId(refreshToken);
if (appId == configuration.application.id)
{
configuration.FetchAppConfigFromServerToken(refreshToken, () =>
{
currentToken = refreshToken;
WitAuthUtility.SetAppServerToken(configuration.application.id, currentToken);
EditorUtility.SetDirty(configuration);
Repaint();
appConfigurationFoldout = false;
});
}
});
return;
}
if (appId == configuration.application.id)
{
refreshToken = WitAuthUtility.ServerToken;
}
}
if (currentToken != refreshToken)
{
currentToken = refreshToken;
}
configuration.FetchAppConfigFromServerToken(refreshToken, () =>
{
currentToken = refreshToken;
Repaint();
appConfigurationFoldout = false;
});
}
public static void UpdateTokenData(string serverToken, Action updateComplete = null)
{
if (!WitAuthUtility.IsServerTokenValid(serverToken)) return;
var listRequest = WitRequestFactory.ListAppsRequest(serverToken, 10000);
listRequest.onResponse = (r) =>
{
if (r.StatusCode == 200)
{
var applications = r.ResponseData.AsArray;
for (int i = 0; i < applications.Count; i++)
{
if (applications[i]["is_app_for_token"].AsBool)
{
var application = WitApplication.FromJson(applications[i]);
WitAuthUtility.SetAppServerToken(application.id, serverToken);
updateComplete?.Invoke();
break;
}
}
}
else
{
Debug.LogError(r.StatusDescription);
}
};
listRequest.Request();
}
private void DrawTraits()
{
var traits = configuration.traits;
if (null != traits)
{
var n = traits.Length;
if (n == 0)
{
GUILayout.Label("No traits available.");
}
else
{
BeginIndent();
for (int i = 0; i < n; i++)
{
var trait = traits[i];
if (null != trait && Foldout("t:", trait.name))
{
DrawTrait(trait);
}
}
EndIndent();
}
}
else
{
GUILayout.Label("Traits have not been loaded yet.", EditorStyles.helpBox);
}
}
private void DrawTrait(WitTrait trait)
{
InfoField("ID", trait.id);
InfoField("Name", trait.name);
GUILayout.BeginHorizontal();
GUILayout.Label("Values", GUILayout.Width(100));
GUILayout.EndHorizontal();
var values = trait.values;
var n = values.Length;
if (n == 0)
{
GUILayout.Label("No values available.");
}
else
{
BeginIndent();
for (int i = 0; i < n; i++)
{
var value = values[i];
if (null != value && Foldout("v:", value.value))
{
DrawTraitValue(value);
}
}
EndIndent();
}
}
private void DrawTraitValue(WitTraitValue traitValue)
{
InfoField("ID", traitValue.id);
InfoField("Value", traitValue.value);
}
private void DrawEntities()
{
var entities = configuration.entities;
if (null != entities)
{
var n = entities.Length;
if (n == 0)
{
GUILayout.Label("No entities available.");
}
else
{
BeginIndent();
for (int i = 0; i < n; i++)
{
var entity = entities[i];
if (null != entity && Foldout("e:", entity.name))
{
DrawEntity(entity);
}
}
EndIndent();
}
}
else
{
GUILayout.Label("Entities have not been loaded yet.", EditorStyles.helpBox);
}
}
private void DrawApplication(WitApplication application)
{
appDrawer.DrawApplication(application);
}
private void DrawEntity(WitEntity entity)
{
BeginIndent();
InfoField("ID", entity.id);
if (entity.roles != null && entity.roles.Length > 0)
{
var entityRoles = entity.roles.Select(e => e.name).ToArray();
DrawStringArray("Roles", entityRoles, entity.roles.GetHashCode().ToString());
}
DrawStringArray("Lookups", entity.lookups);
EndIndent();
}
private void DrawIntents()
{
var intents = configuration.intents;
if (null != intents)
{
var n = intents.Length;
if (n == 0)
{
GUILayout.Label("No intents available.");
}
else
{
BeginIndent();
for (int i = 0; i < n; i++)
{
var intent = intents[i];
if (null != intent && Foldout("i:", intent.name))
{
DrawIntent(intent);
}
}
EndIndent();
}
}
else
{
GUILayout.Label("Intents have not been loaded yet.", EditorStyles.helpBox);
}
}
private void DrawIntent(WitIntent intent)
{
BeginIndent();
InfoField("ID", intent.id);
var entities = intent.entities;
if (entities.Length > 0)
{
var entityNames = entities.Select(e => e.name).ToArray();
DrawStringArray("Entities", entityNames, intent.entities.GetHashCode().ToString());
}
EndIndent();
}
private void DrawStringArray(string displayName, string[] vals, string keybase = "")
{
if (vals != null && vals.Length > 0)
{
if (string.IsNullOrEmpty(keybase))
{
keybase = vals.GetHashCode().ToString();
}
if (Foldout(keybase, displayName))
{
BeginIndent();
BeginIndent();
for (int i = 0; i < vals.Length; i++)
{
GUILayout.Label(vals[i]);
}
EndIndent();
EndIndent();
}
}
}
#region UI Components
private void BeginIndent()
{
GUILayout.BeginHorizontal();
GUILayout.Space(10);
GUILayout.BeginVertical();
}
private void EndIndent()
{
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
private void InfoField(string name, string value)
{
GUILayout.BeginHorizontal();
GUILayout.Label(name, GUILayout.Width(100));
GUILayout.Label(value, "TextField");
GUILayout.EndHorizontal();
}
private bool Foldout(string keybase, string name)
{
string key = keybase + name;
bool show = false;
if (!foldouts.TryGetValue(key, out show))
{
foldouts[key] = false;
}
show = EditorGUILayout.Foldout(show, name, true);
foldouts[key] = show;
return show;
}
#endregion
public static WitConfiguration CreateWitConfiguration(string serverToken, Action onCreationComplete)
{
var path = EditorUtility.SaveFilePanel("Create Wit Configuration", Application.dataPath,
"WitConfiguration", "asset");
if (!string.IsNullOrEmpty(path) && path.StartsWith(Application.dataPath))
{
WitConfiguration asset = ScriptableObject.CreateInstance<WitConfiguration>();
asset.FetchAppConfigFromServerToken(serverToken, onCreationComplete);
path = path.Substring(Application.dataPath.Length - 6);
AssetDatabase.CreateAsset(asset, path);
AssetDatabase.SaveAssets();
return asset;
}
return null;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fda2e192978913c42af9533c9a0baa01
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,216 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Data.Entities;
using Facebook.WitAi.Data.Intents;
using Facebook.WitAi.Data.Traits;
using Facebook.WitAi.Lib;
using Facebook.WitAi.Utilities;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Data.Configuration
{
public static class WitConfigurationUtility
{
#if UNITY_EDITOR
public static void UpdateData(this WitConfiguration configuration,
Action onUpdateComplete = null)
{
DoUpdateData(configuration, onUpdateComplete);
}
private static void DoUpdateData(WitConfiguration configuration, Action onUpdateComplete)
{
if (!string.IsNullOrEmpty(
WitAuthUtility.GetAppServerToken(configuration.application.id)))
{
var intentsRequest = configuration.ListIntentsRequest();
intentsRequest.onResponse =
(r) => ListEntities(r, configuration, onUpdateComplete);
configuration.application?.UpdateData(intentsRequest.Request);
}
}
private static void ListEntities(WitRequest r, WitConfiguration configuration, Action onUpdateComplete)
{
var entitiesRequest = configuration.ListEntitiesRequest();
entitiesRequest.onResponse = (er) => ListTraits(er, configuration, onUpdateComplete);
OnUpdateData(r, (response) => UpdateIntentList(configuration, response),
entitiesRequest.Request);
}
private static void ListTraits(WitRequest er, WitConfiguration configuration, Action onUpdateComplete)
{
var traitsRequest = configuration.ListTraitsRequest();
traitsRequest.onResponse =
(tr) =>
{
OnUpdateData(tr,
(dataResponse) => UpdateTraitList(configuration, dataResponse),
onUpdateComplete);
};
OnUpdateData(er,
(entityResponse) => UpdateEntityList(configuration, entityResponse),
traitsRequest.Request);
}
private static void OnUpdateData(WitRequest request,
Action<WitResponseNode> updateComponent, Action onUpdateComplete)
{
if (request.StatusCode == 200)
{
updateComponent(request.ResponseData);
}
else
{
Debug.LogError($"Request for {request} failed: {request.StatusDescription}");
}
if (onUpdateComplete != null)
{
onUpdateComplete();
}
}
private static void UpdateIntentList(this WitConfiguration configuration,
WitResponseNode intentListWitResponse)
{
var intentList = intentListWitResponse.AsArray;
var n = intentList.Count;
configuration.intents = new WitIntent[n];
for (int i = 0; i < n; i++)
{
var intent = WitIntent.FromJson(intentList[i]);
intent.witConfiguration = configuration;
configuration.intents[i] = intent;
intent.UpdateData();
}
}
private static void UpdateEntityList(this WitConfiguration configuration,
WitResponseNode entityListWitResponse)
{
var entityList = entityListWitResponse.AsArray;
var n = entityList.Count;
configuration.entities = new WitEntity[n];
for (int i = 0; i < n; i++)
{
var entity = WitEntity.FromJson(entityList[i]);
entity.witConfiguration = configuration;
configuration.entities[i] = entity;
entity.UpdateData();
}
}
public static void UpdateTraitList(this WitConfiguration configuration,
WitResponseNode traitListWitResponse)
{
var traitList = traitListWitResponse.AsArray;
var n = traitList.Count;
configuration.traits = new WitTrait[n];
for (int i = 0; i < n; i++)
{
var trait = WitTrait.FromJson(traitList[i]);
trait.witConfiguration = configuration;
configuration.traits[i] = trait;
trait.UpdateData();
}
}
/// <summary>
/// Gets the app info and client id that is associated with the server token being used
/// </summary>
/// <param name="serverToken">The server token to use to get the app config</param>
/// <param name="action"></param>
public static void FetchAppConfigFromServerToken(this WitConfiguration configuration,
string serverToken, Action action)
{
if (WitAuthUtility.IsServerTokenValid(serverToken))
{
FetchApplicationFromServerToken(configuration, serverToken,
() =>
{
FetchClientToken(configuration,
() => { configuration.UpdateData(action); });
});
}
else
{
Debug.LogError($"No server token set for {configuration.name}.");
}
}
private static void FetchApplicationFromServerToken(WitConfiguration configuration,
string serverToken, Action response)
{
var listRequest = WitRequestFactory.ListAppsRequest(serverToken, 10000);
listRequest.onResponse = (r) =>
{
if (r.StatusCode == 200)
{
var applications = r.ResponseData.AsArray;
for (int i = 0; i < applications.Count; i++)
{
if (applications[i]["is_app_for_token"].AsBool)
{
if (null != configuration.application)
{
configuration.application.UpdateData(applications[i]);
}
else
{
configuration.application =
WitApplication.FromJson(applications[i]);
}
WitAuthUtility.SetAppServerToken(configuration.application.id, serverToken);
response?.Invoke();
break;
}
}
}
else
{
Debug.LogError(r.StatusDescription);
}
};
listRequest.Request();
}
private static void FetchClientToken(WitConfiguration configuration, Action action)
{
if (!string.IsNullOrEmpty(configuration.application?.id))
{
var tokenRequest = configuration.GetClientToken(configuration.application.id);
tokenRequest.onResponse = (r) =>
{
if (r.StatusCode == 200)
{
var token = r.ResponseData["client_token"];
SerializedObject so = new SerializedObject(configuration);
so.FindProperty("clientAccessToken").stringValue =
r.ResponseData["client_token"];
so.ApplyModifiedProperties();
configuration.clientAccessToken = token;
EditorUtility.SetDirty(configuration);
action?.Invoke();
}
else
{
Debug.LogError(r.StatusDescription);
}
};
tokenRequest.Request();
}
}
#endif
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 67da0cb4ba914f6cb2a97a343ff81db1
timeCreated: 1631316958

View File

@@ -0,0 +1,102 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Configuration
{
[CustomPropertyDrawer(typeof(WitEndpointConfig))]
public class WitEndpointConfigDrawer : PropertyDrawer
{
private string editing;
private Vector2 scroll;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return 0;
}
private void DrawProperty(SerializedProperty propery, string name,
string label, string defaultValue)
{
var propValue = propery.FindPropertyRelative(name);
GUILayout.BeginHorizontal();
if (editing == name)
{
EditorGUILayout.PropertyField(propValue, new GUIContent(label));
WitStyles.ResetIcon.tooltip = $"Reset to default values ({defaultValue})";
if (GUILayout.Button(WitStyles.ResetIcon, WitStyles.ImageIcon))
{
editing = string.Empty;
switch (propValue.type)
{
case "string":
propValue.stringValue = defaultValue;
break;
case "int":
propValue.intValue = int.Parse(defaultValue);
break;
}
}
if (GUILayout.Button(WitStyles.AcceptIcon, WitStyles.ImageIcon))
{
editing = string.Empty;
}
}
else
{
switch (propValue.type)
{
case "string":
defaultValue = string.IsNullOrEmpty(propValue.stringValue)
? defaultValue
: propValue.stringValue;
break;
case "int":
defaultValue = propValue.intValue.ToString();
break;
}
EditorGUI.BeginDisabledGroup(editing != name);
EditorGUILayout.TextField(label, defaultValue);
EditorGUI.EndDisabledGroup();
if (GUILayout.Button(WitStyles.EditIcon, WitStyles.ImageIcon))
{
if (editing == name)
{
editing = string.Empty;
}
else
{
editing = name;
}
}
}
GUILayout.EndHorizontal();
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
scroll = GUILayout.BeginScrollView(scroll, GUILayout.Height(100));
DrawProperty(property, "uriScheme", "Uri Scheme", WitRequest.URI_SCHEME);
DrawProperty(property, "authority", "Host", WitRequest.URI_AUTHORITY);
DrawProperty(property, "port", "Port", "80");
DrawProperty(property, "witApiVersion", "Wit Api Version", WitRequest.WIT_API_VERSION);
DrawProperty(property, "speech", "Speech", WitRequest.WIT_ENDPOINT_SPEECH);
DrawProperty(property, "message", "Message", WitRequest.WIT_ENDPOINT_MESSAGE);
GUILayout.EndScrollView();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5fff8addd8c86d94d9e793036f5e5538
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,88 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Data.Configuration
{
public class WitWelcomeWizard : ScriptableWizard
{
private Texture2D tex;
private bool manualToken;
protected WitConfigurationEditor witEditor;
protected string serverToken;
public Action successAction;
protected virtual void OnWizardCreate()
{
ValidateAndClose();
}
protected void ValidateAndClose()
{
WitAuthUtility.ServerToken = serverToken;
if (WitAuthUtility.IsServerTokenValid())
{
Close();
WitWindow.ShowWindow();
successAction?.Invoke();
}
else
{
throw new ArgumentException("Please enter a valid token before linking.");
}
}
protected override bool DrawWizardGUI()
{
maxSize = minSize = new Vector2(400, 375);
BaseWitWindow.DrawHeader("https://wit.ai/apps");
GUILayout.BeginHorizontal();
GUILayout.Space(16);
GUILayout.BeginVertical();
GUILayout.Label("Build Natural Language Experiences", WitStyles.LabelHeader);
GUILayout.Label(
"Empower people to use your product with voice and text",
WitStyles.LabelHeader2);
GUILayout.EndVertical();
GUILayout.Space(16);
GUILayout.EndHorizontal();
GUILayout.Space(32);
BaseWitWindow.BeginCenter(296);
GUILayout.BeginHorizontal();
GUILayout.Label("Paste your Server Access Token here", WitStyles.Label);
GUILayout.FlexibleSpace();
if (GUILayout.Button(WitStyles.PasteIcon, WitStyles.Label))
{
serverToken = EditorGUIUtility.systemCopyBuffer;
WitAuthUtility.ServerToken = serverToken;
ValidateAndClose();
}
GUILayout.EndHorizontal();
if (null == serverToken)
{
serverToken = WitAuthUtility.ServerToken;
}
serverToken = EditorGUILayout.PasswordField(serverToken, WitStyles.TextField);
BaseWitWindow.EndCenter();
return WitAuthUtility.IsServerTokenValid();
}
public static void ShowWizard(Action successAction)
{
var wizard =
ScriptableWizard.DisplayWizard<WitWelcomeWizard>("Welcome to Wit.ai", "Link");
wizard.successAction = successAction;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 842ab427b28d8450597f95ef8c8689f7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,222 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Data.Configuration
{
public class WitWindow : BaseWitWindow
{
public static void ShowWindow()
{
if (WitAuthUtility.IsServerTokenValid())
{
GetWindow<WitWindow>("Wit Settings");
}
else
{
WitWelcomeWizard.ShowWizard(ShowWindow);
}
}
protected override string HeaderLink
{
get
{
if (null != witConfiguration && null != witConfiguration.application &&
!string.IsNullOrEmpty(witConfiguration.application.id))
{
return $"https://wit.ai/apps/{witConfiguration.application.id}/settings";
}
return null;
}
}
private Texture2D tex;
private bool manualToken;
protected Vector2 scroll;
protected WitConfigurationEditor witEditor;
protected string serverToken;
protected bool welcomeSizeSet;
protected override void OnDrawContent()
{
if (!WitAuthUtility.IsServerTokenValid())
{
DrawWelcome();
}
else
{
DrawWit();
}
}
protected virtual void SetWitEditor()
{
if (witConfiguration)
{
witEditor = (WitConfigurationEditor) Editor.CreateEditor(witConfiguration);
witEditor.drawHeader = false;
witEditor.Initialize();
}
}
protected override void OnEnable()
{
WitAuthUtility.InitEditorTokens();
SetWitEditor();
RefreshConfigList();
}
protected virtual void DrawWit()
{
// Recommended max size based on EditorWindow.maxSize doc for resizable window.
if (welcomeSizeSet)
{
welcomeSizeSet = false;
maxSize = new Vector2(4000, 4000);
}
titleContent = new GUIContent("Wit Configuration");
GUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.BeginHorizontal();
if (null == serverToken)
{
serverToken = WitAuthUtility.ServerToken;
}
serverToken = EditorGUILayout.PasswordField("Server Access Token", serverToken);
if (GUILayout.Button(WitStyles.PasteIcon, WitStyles.ImageIcon))
{
serverToken = EditorGUIUtility.systemCopyBuffer;
WitAuthUtility.ServerToken = serverToken;
RefreshContent();
}
if (GUILayout.Button("Relink", GUILayout.Width(75)))
{
if (WitAuthUtility.IsServerTokenValid(serverToken))
{
WitConfigurationEditor.UpdateTokenData(serverToken, RefreshContent);
}
WitAuthUtility.ServerToken = serverToken;
RefreshContent();
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
var configChanged = DrawWitConfigurationPopup();
if (GUILayout.Button("Create", GUILayout.Width(75)))
{
CreateConfiguration();
}
GUILayout.EndHorizontal();
if (witConfiguration && (configChanged || !witEditor))
{
WitConfiguration config = (WitConfiguration) witConfiguration;
SetWitEditor();
}
if(witConfiguration && witEditor) witEditor.OnInspectorGUI();
GUILayout.EndVertical();
}
protected virtual void CreateConfiguration()
{
var asset = WitConfigurationEditor.CreateWitConfiguration(serverToken, Repaint);
if (asset)
{
RefreshConfigList();
witConfigIndex = Array.IndexOf(witConfigs, asset);
witConfiguration = asset;
SetWitEditor();
}
}
protected virtual void DrawWelcome()
{
titleContent = WitStyles.welcomeTitleContent;
if (!welcomeSizeSet)
{
minSize = new Vector2(450, 686);
maxSize = new Vector2(450, 686);
welcomeSizeSet = true;
}
scroll = GUILayout.BeginScrollView(scroll);
GUILayout.Label("Build Natural Language Experiences", WitStyles.LabelHeader);
GUILayout.Label(
"Enable people to interact with your products using voice and text.",
WitStyles.LabelHeader2);
GUILayout.Space(32);
BeginCenter(296);
GUILayout.BeginHorizontal();
GUILayout.Label("Paste your Server Access Token here", WitStyles.Label);
GUILayout.FlexibleSpace();
if (GUILayout.Button(WitStyles.PasteIcon, WitStyles.Label))
{
serverToken = EditorGUIUtility.systemCopyBuffer;
WitAuthUtility.ServerToken = serverToken;
if (WitAuthUtility.IsServerTokenValid())
{
RefreshContent();
}
}
GUILayout.EndHorizontal();
if (null == serverToken)
{
serverToken = WitAuthUtility.ServerToken;
}
GUILayout.BeginHorizontal();
serverToken = EditorGUILayout.PasswordField(serverToken, WitStyles.TextField);
if (GUILayout.Button("Link", GUILayout.Width(75)))
{
WitAuthUtility.ServerToken = serverToken;
if (WitAuthUtility.IsServerTokenValid())
{
RefreshContent();
}
}
GUILayout.EndHorizontal();
EndCenter();
BeginCenter();
GUILayout.Label("or", WitStyles.Label);
EndCenter();
BeginCenter();
if (GUILayout.Button(WitStyles.ContinueButton, WitStyles.Label, GUILayout.Height(50),
GUILayout.Width(296)))
{
Application.OpenURL("https://wit.ai");
}
GUILayout.Label(
"Please connect with Facebook login to continue using Wit.ai by clicking on the “Continue with Github Login” and following the instructions provided.",
WitStyles.Label,
GUILayout.Width(296));
EndCenter();
BeginCenter();
GUILayout.Space(16);
EndCenter();
GUILayout.EndScrollView();
}
}
}

View File

@@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: 15c29f496a2443b4aa5e0ab283126a83
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- m_ViewDataDictionary: {instanceID: 0}
- witIcon: {fileID: 2800000, guid: d3b5ac4c8b01ef14a8a66d7e2a4991cc, type: 3}
- mainHeader: {fileID: 2800000, guid: 6a61dbb599169b64ca5584c8eebeb69e, type: 3}
- continueButton: {fileID: 2800000, guid: 2ed0be21c4a8bce4fadffab71d5b6e85, type: 3}
- witConfiguration: {instanceID: 0}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,117 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System.Globalization;
using System.Text.RegularExpressions;
using Facebook.WitAi.Configuration;
using Facebook.WitAi.Data.Configuration;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Data
{
public class WitDataCreation
{
const string PATH_KEY = "Facebook::Wit::ValuePath";
public static WitConfiguration FindDefaultWitConfig()
{
string[] guids = AssetDatabase.FindAssets("t:WitConfiguration");
if(guids.Length > 0)
{
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
return AssetDatabase.LoadAssetAtPath<WitConfiguration>(path);
}
return null;
}
public static void AddWitToScene()
{
var witGo = new GameObject();
witGo.name = "Wit";
var wit = witGo.AddComponent<Wit>();
var runtimeConfiguration = new WitRuntimeConfiguration()
{
witConfiguration = FindDefaultWitConfig()
};
wit.RuntimeConfiguration = runtimeConfiguration;
}
public static void WitStringValue()
{
CreateStringValue("");
}
public static WitStringValue CreateStringValue(string path)
{
var asset = ScriptableObject.CreateInstance<WitStringValue>();
CreateValueAsset("Create String Value", path, asset);
return asset;
}
public static void WitFloatValue()
{
CreateFloatValue("");
}
public static WitFloatValue CreateFloatValue(string path)
{
var asset = ScriptableObject.CreateInstance<WitFloatValue>();
CreateValueAsset("Create Float Value", path, asset);
return asset;
}
public static void WitIntValue()
{
CreateStringValue("");
}
public static WitIntValue CreateIntValue(string path)
{
var asset = ScriptableObject.CreateInstance<WitIntValue>();
CreateValueAsset("Create Int Value", path, asset);
return asset;
}
private static void CreateValueAsset(string label, string path, WitValue asset)
{
asset.path = path;
var saveDir = EditorPrefs.GetString(PATH_KEY, Application.dataPath);
string name;
if (!string.IsNullOrEmpty(path))
{
name = Regex.Replace(path, @"\[[\]0-9]+", "");
name = name.Replace(".", " ");
name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name);
}
else
{
name = asset.GetType().Name;
}
var filePath = EditorUtility.SaveFilePanel(label, saveDir, name, "asset");
if (!string.IsNullOrEmpty(filePath))
{
EditorPrefs.SetString(PATH_KEY, filePath);
if (filePath.StartsWith(Application.dataPath))
{
filePath = filePath.Substring(Application.dataPath.Length - 6);
}
AssetDatabase.CreateAsset(asset, filePath);
AssetDatabase.SaveAssets();
}
}
public static void CreateWitConfiguration()
{
WitConfigurationEditor.CreateWitConfiguration(WitAuthUtility.ServerToken, null);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 40da7661eee64aaa81d3a0886ce34911
timeCreated: 1624319178

View File

@@ -0,0 +1,17 @@
{
"name": "Facebook.Wit.Editor",
"references": [
"GUID:4504b1a6e0fdcc3498c30b266e4a63bf"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: fa958eb9f0171754fb207d563a15ddfa
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8bd8be981a6845f186f01908998f57e8
timeCreated: 1626727424

View File

@@ -0,0 +1,108 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Inspectors
{
public class WitInspector : Editor
{
private string activationMessage;
private VoiceService wit;
private float micMin;
private float micMax;
private string lastTranscription;
private float micCurrent;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (Application.isPlaying)
{
wit = (VoiceService) target;
if (wit.Active)
{
if (GUILayout.Button("Deactivate"))
{
wit.Deactivate();
}
if (wit.MicActive)
{
GUILayout.Label("Listening...");
}
else
{
GUILayout.Label("Processing...");
}
}
else
{
if (GUILayout.Button("Activate"))
{
InitializeActivationLogging();
wit.Activate();
}
GUILayout.BeginHorizontal();
activationMessage = GUILayout.TextField(activationMessage);
if (GUILayout.Button("Send", GUILayout.Width(50)))
{
InitializeActivationLogging();
wit.Activate(activationMessage);
}
GUILayout.EndHorizontal();
}
GUILayout.Label("Last Transcription", EditorStyles.boldLabel);
GUILayout.TextArea(lastTranscription);
GUILayout.Label("Mic Status", EditorStyles.boldLabel);
GUILayout.Label($"Mic range: {micMin.ToString("F5")} - {micMax.ToString("F5")}");
GUILayout.Label($"Mic current: {micCurrent.ToString("F5")}");
}
}
private void InitializeActivationLogging()
{
wit.events.OnFullTranscription.AddListener(UpdateTranscription);
wit.events.OnPartialTranscription.AddListener(UpdateTranscription);
wit.events.OnMicLevelChanged.AddListener(OnMicLevelChanged);
micMin = Mathf.Infinity;
micMax = Mathf.NegativeInfinity;
EditorApplication.update += UpdateWhileActive;
}
private void OnMicLevelChanged(float volume)
{
micCurrent = volume;
micMin = Mathf.Min(volume, micMin);
micMax = Mathf.Max(volume, micMax);
}
private void UpdateTranscription(string transcription)
{
lastTranscription = transcription;
}
private void UpdateWhileActive()
{
Repaint();
if (!wit.Active)
{
EditorApplication.update -= UpdateWhileActive;
wit.events.OnFullTranscription.RemoveListener(UpdateTranscription);
wit.events.OnPartialTranscription.RemoveListener(UpdateTranscription);
wit.events.OnMicLevelChanged.RemoveListener(OnMicLevelChanged);
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 55ca91fb24174b4db43031a3ab4b0214
timeCreated: 1626727432

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4f4bf1d9c20d66943bc5dab13c5d8d58
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fc134e9335ed3814184f8a12b011b172
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,28 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using UnityEditor;
namespace Facebook.WitAi.Lib
{
[CustomEditor(typeof(Mic))]
public class MicEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var mic = (Mic) target;
int index = EditorGUILayout.Popup("Input", mic.CurrentDeviceIndex, mic.Devices.ToArray());
if (index != mic.CurrentDeviceIndex)
{
mic.ChangeDevice(index);
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 342830ab77bbe9c47a0f68027cc80da4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1aae00c8b15744747a605c719bafd378
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,521 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using System.Collections.Generic;
using Facebook.WitAi.CallbackHandlers;
using Facebook.WitAi.Configuration;
using Facebook.WitAi.Data;
using Facebook.WitAi.Data.Configuration;
using Facebook.WitAi.Lib;
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi.Utilities
{
public class WitUnderstandingViewer : BaseWitWindow
{
[SerializeField] private Texture2D witHeader;
[SerializeField] private string responseText;
private string utterance;
private WitResponseNode response;
private Dictionary<string, bool> foldouts;
private Vector2 scroll;
private DateTime submitStart;
private TimeSpan requestLength;
private string status;
private VoiceService wit;
private int responseCode;
private WitRequest request;
public bool HasWit => null != wit;
class Content
{
public static GUIContent copyPath;
public static GUIContent copyCode;
public static GUIContent createStringValue;
public static GUIContent createIntValue;
public static GUIContent createFloatValue;
static Content()
{
createStringValue = new GUIContent("Create Value Reference/Create String");
createIntValue = new GUIContent("Create Value Reference/Create Int");
createFloatValue = new GUIContent("Create Value Reference/Create Float");
copyPath = new GUIContent("Copy Path to Clipboard");
copyCode = new GUIContent("Copy Code to Clipboard");
}
}
static void Init()
{
BaseWitWindow.RefreshConfigList();
bool hasConfig = false;
for (int i = 0; i < witConfigs.Length; i++)
{
if (!string.IsNullOrEmpty(witConfigs[i].clientAccessToken))
{
hasConfig = true;
break;
}
}
if (hasConfig)
{
WitUnderstandingViewer window =
EditorWindow.GetWindow(
typeof(WitUnderstandingViewer)) as WitUnderstandingViewer;
window.titleContent = new GUIContent("Understanding Viewer", WitStyles.WitIcon);
window.autoRepaintOnSceneChange = true;
window.Show();
}
else
{
WitWelcomeWizard.ShowWizard(Init);
}
}
protected override void OnEnable()
{
base.OnEnable();
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
SetWit(GameObject.FindObjectOfType<VoiceService>());
if (!string.IsNullOrEmpty(responseText))
{
response = WitResponseNode.Parse(responseText);
}
status = "Enter an utterance and hit Send to see what your app will return.";
}
protected override void OnDisable()
{
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
}
private void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.EnteredPlayMode && !HasWit)
{
SetWit(FindObjectOfType<VoiceService>());
}
}
private void OnSelectionChange()
{
if (Selection.activeGameObject)
{
wit = Selection.activeGameObject.GetComponent<VoiceService>();
SetWit(wit);
}
}
private void SetWit(VoiceService wit)
{
if (HasWit)
{
wit.events.OnRequestCreated.RemoveListener(OnRequestCreated);
wit.events.OnError.RemoveListener(OnError);
wit.events.OnResponse.RemoveListener(ShowResponse);
wit.events.OnFullTranscription.RemoveListener(ShowTranscription);
wit.events.OnPartialTranscription.RemoveListener(ShowTranscription);
}
if (null != wit)
{
this.wit = wit;
wit.events.OnRequestCreated.AddListener(OnRequestCreated);
wit.events.OnError.AddListener(OnError);
wit.events.OnResponse.AddListener(ShowResponse);
wit.events.OnFullTranscription.AddListener(ShowTranscription);
wit.events.OnPartialTranscription.AddListener(ShowTranscription);
// We will be measuring perceived request time since the actual request starts
// as soon as the mic goes active and the user says something.
wit.events.OnStoppedListening.AddListener(ResetStartTime);
Repaint();
}
}
private void ResetStartTime()
{
submitStart = System.DateTime.Now;
}
private void OnError(string title, string message)
{
status = message;
}
private void OnRequestCreated(WitRequest request)
{
this.request = request;
ResetStartTime();
}
private void ShowTranscription(string transcription)
{
utterance = transcription;
Repaint();
}
protected override void OnDrawContent()
{
if (!witConfiguration || witConfigs.Length > 1)
{
DrawWitConfigurationPopup();
if (!witConfiguration)
{
GUILayout.Label(
"A Wit configuration must be available and selected to test utterances.", EditorStyles.helpBox);
return;
}
}
if (string.IsNullOrEmpty(witConfiguration.clientAccessToken))
{
GUILayout.Label(
"Your wit configuration has not yet been linked to a wit application. Make sure you have linked your account with Wit.ai.", WitStyles.WordwrappedLabel);
if (GUILayout.Button("Select Configuration"))
{
EditorGUIUtility.PingObject(witConfiguration);
Selection.activeObject = witConfiguration;
}
return;
}
utterance = EditorGUILayout.TextField("Utterance", utterance);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Send", GUILayout.Width(75)) && (null == request || !request.IsActive))
{
responseText = "";
if (!string.IsNullOrEmpty(utterance))
{
SubmitUtterance();
}
else
{
response = null;
}
}
if (EditorApplication.isPlaying && wit)
{
if (!wit.Active && GUILayout.Button("Activate", GUILayout.Width(75)))
{
wit.Activate();
}
if (wit.Active && GUILayout.Button("Deactivate", GUILayout.Width(75)))
{
wit.Deactivate();
}
if (wit.Active && GUILayout.Button("Abort", GUILayout.Width(75)))
{
wit.DeactivateAndAbortRequest();
}
}
GUILayout.EndHorizontal();
if (wit && wit.MicActive)
{
BeginCenter();
GUILayout.Label("Listening...");
EndCenter();
}
else if (wit && wit.IsRequestActive)
{
BeginCenter();
GUILayout.Label("Loading...");
EndCenter();
}
else if (null != response)
{
GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.ExpandHeight(true));
DrawResponse();
GUILayout.EndVertical();
}
else
{
GUILayout.BeginVertical(EditorStyles.helpBox);
if (!string.IsNullOrEmpty(responseText))
{
GUILayout.Label(responseText);
}
else
{
GUILayout.Label(
"Enter an utterance and hit Send to see what your app will return.");
}
GUILayout.EndVertical();
}
GUILayout.FlexibleSpace();
GUILayout.Label(status, WitStyles.BackgroundBlack25P);
}
private void SubmitUtterance()
{
if (Application.isPlaying && !HasWit)
{
SetDefaultWit();
}
if (wit && Application.isPlaying)
{
wit.Activate(utterance);
// Hack to watch for loading to complete. Response does not
// come back on the main thread so Repaint in onResponse in
// the editor does nothing.
EditorApplication.update += WatchForWitResponse;
}
else
{
// Hack to watch for loading to complete. Response does not
// come back on the main thread so Repaint in onResponse in
// the editor does nothing.
EditorApplication.update += WatchForResponse;
submitStart = System.DateTime.Now;
request = witConfiguration.MessageRequest(utterance, new WitRequestOptions());
request.onResponse = OnResponse;
request.Request();
}
}
private void SetDefaultWit()
{
SetWit(FindObjectOfType<VoiceService>());
}
private void OnResponse(WitRequest request)
{
responseCode = request.StatusCode;
if (null != request.ResponseData)
{
ShowResponse(request.ResponseData);
}
else if (!string.IsNullOrEmpty(request.StatusDescription))
{
responseText = request.StatusDescription;
}
else
{
responseText = "No response. Status: " + request.StatusCode;
}
Repaint();
}
private void ShowResponse(WitResponseNode r)
{
response = r;
responseText = response.ToString();
requestLength = DateTime.Now - submitStart;
status = $"Response time: {requestLength}";
}
private void WatchForResponse()
{
if (null == request || !request.IsActive)
{
Repaint();
EditorApplication.update -= WatchForResponse;
}
}
private void WatchForWitResponse()
{
if (wit && !wit.Active)
{
Repaint();
EditorApplication.update -= WatchForResponse;
}
}
private void DrawResponse()
{
scroll = GUILayout.BeginScrollView(scroll);
DrawResponseNode(response);
GUILayout.EndScrollView();
}
private void DrawResponseNode(WitResponseNode witResponseNode, string path = "")
{
if (null == witResponseNode?.AsObject) return;
if(string.IsNullOrEmpty(path)) DrawNode(witResponseNode["text"], "text", path);
var names = witResponseNode.AsObject.ChildNodeNames;
Array.Sort(names);
foreach (string child in names)
{
if (!(string.IsNullOrEmpty(path) && child == "text"))
{
var childNode = witResponseNode[child];
DrawNode(childNode, child, path);
}
}
}
private void DrawNode(WitResponseNode childNode, string child, string path, bool isArrayElement = false)
{
string childPath;
if (path.Length > 0)
{
childPath = isArrayElement ? $"{path}[{child}]" : $"{path}.{child}";
}
else
{
childPath = child;
}
if (!string.IsNullOrEmpty(childNode.Value))
{
GUILayout.BeginHorizontal();
GUILayout.Space(15 * EditorGUI.indentLevel);
if (GUILayout.Button($"{child} = {childNode.Value}", "Label"))
{
ShowNodeMenu(childNode, childPath);
}
GUILayout.EndHorizontal();
}
else
{
var childObject = childNode.AsObject;
var childArray = childNode.AsArray;
if ((null != childObject || null != childArray) && Foldout(childPath, child))
{
EditorGUI.indentLevel++;
if (null != childObject)
{
DrawResponseNode(childNode, childPath);
}
if (null != childArray)
{
DrawArray(childArray, childPath);
}
EditorGUI.indentLevel--;
}
}
}
private void ShowNodeMenu(WitResponseNode node, string path)
{
GenericMenu menu = new GenericMenu();
menu.AddItem(Content.createStringValue, false, () => WitDataCreation.CreateStringValue(path));
menu.AddItem(Content.createIntValue, false, () => WitDataCreation.CreateIntValue(path));
menu.AddItem(Content.createFloatValue, false, () => WitDataCreation.CreateFloatValue(path));
menu.AddSeparator("");
menu.AddItem(Content.copyPath, false, () =>
{
EditorGUIUtility.systemCopyBuffer = path;
});
menu.AddItem(Content.copyCode, false, () =>
{
EditorGUIUtility.systemCopyBuffer = WitResultUtilities.GetCodeFromPath(path);
});
if (Selection.activeGameObject)
{
menu.AddSeparator("");
var label =
new GUIContent($"Add response matcher to {Selection.activeObject.name}");
menu.AddItem(label, false, () =>
{
var valueHandler = Selection.activeGameObject.AddComponent<WitResponseMatcher>();
valueHandler.intent = response.GetIntentName();
valueHandler.valueMatchers = new ValuePathMatcher[]
{
new ValuePathMatcher() { path = path }
};
});
AddMultiValueUpdateItems(path, menu);
}
menu.ShowAsContext();
}
private void AddMultiValueUpdateItems(string path, GenericMenu menu)
{
string name = path;
int index = path.LastIndexOf('.');
if (index > 0)
{
name = name.Substring(index + 1);
}
var mvhs = Selection.activeGameObject.GetComponents<WitResponseMatcher>();
if (mvhs.Length > 1)
{
for (int i = 0; i < mvhs.Length; i++)
{
var handler = mvhs[i];
menu.AddItem(
new GUIContent($"Add {name} matcher to {Selection.activeGameObject.name}/Handler {(i + 1)}"),
false, (h) => AddNewEventHandlerPath((WitResponseMatcher) h, path), handler);
}
}
else if (mvhs.Length == 1)
{
var handler = mvhs[0];
menu.AddItem(
new GUIContent($"Add {name} matcher to {Selection.activeGameObject.name}'s Response Matcher"),
false, (h) => AddNewEventHandlerPath((WitResponseMatcher) h, path), handler);
}
}
private void AddNewEventHandlerPath(WitResponseMatcher handler, string path)
{
Array.Resize(ref handler.valueMatchers, handler.valueMatchers.Length + 1);
handler.valueMatchers[handler.valueMatchers.Length - 1] = new ValuePathMatcher()
{
path = path
};
}
private void DrawArray(WitResponseArray childArray, string childPath)
{
for (int i = 0; i < childArray.Count; i++)
{
DrawNode(childArray[i], i.ToString(), childPath, true);
}
}
private bool Foldout(string path, string label)
{
if (null == foldouts) foldouts = new Dictionary<string, bool>();
if (!foldouts.TryGetValue(path, out var state))
{
state = false;
foldouts[path] = state;
}
var newState = EditorGUILayout.Foldout(state, label);
if (newState != state)
{
foldouts[path] = newState;
}
return newState;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 18eb340e3f39b0a4f8f9e9749e97f9b1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using UnityEditor;
namespace Facebook.WitAi
{
public class WitEditorUI
{
public static bool FallbackPopup(SerializedObject serializedObject, string propertyName,
string[] names, ref int index)
{
var property = serializedObject.FindProperty(propertyName);
string intent;
if (null != names && names.Length > 0)
{
index = EditorGUILayout.Popup(property.displayName, index, names);
if (index >= 0)
{
intent = names[index];
}
else
{
intent = EditorGUILayout.TextField(property.stringValue);
}
}
else
{
intent = EditorGUILayout.TextField(property.displayName, property.stringValue);
}
if (intent != property.stringValue)
{
property.stringValue = intent;
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 600660e3443571c47bdf56e955806c73
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,131 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using UnityEditor;
using UnityEngine;
namespace Facebook.WitAi
{
public class WitStyles
{
public static Texture2D WitIcon;
public static Texture2D MainHeader;
public static Texture2D ContinueButton;
public static Texture2D TextureWhite;
public static Texture2D TextureWhite25P;
public static Texture2D TextureBlack25P;
public static Texture2D TextureFBBlue;
public static Texture2D TextureTextField;
public static Texture2D TextureWitDark;
public static GUIStyle BackgroundWhite;
public static GUIStyle BackgroundWhite25P;
public static GUIStyle BackgroundBlack25P;
public static GUIStyle BackgroundWitDark;
public static GUIStyle LabelHeader;
public static GUIStyle LabelHeader2;
public static GUIStyle Label;
public static GUIStyle WordwrappedLabel;
public static GUIStyle FacebookButton;
public static GUIStyle TextField;
public static Color ColorFB = new Color(0.09f, 0.47f, 0.95f);
public static GUIStyle Link;
public static GUIContent titleContent;
public static GUIContent welcomeTitleContent;
public static GUIContent PasteIcon;
public static GUIContent EditIcon;
public static GUIContent ResetIcon;
public static GUIContent AcceptIcon;
public static GUIContent ObjectPickerIcon;
public static GUIStyle ImageIcon;
public const int IconButtonWidth = 20;
static WitStyles()
{
WitIcon = (Texture2D) Resources.Load("witai");
MainHeader = (Texture2D) Resources.Load("wit-ai-title");
ContinueButton = (Texture2D) Resources.Load("continue-with-fb");
TextureWhite = new Texture2D(1, 1);
TextureWhite.SetPixel(0, 0, Color.white);
TextureWhite.Apply();
TextureWhite25P = new Texture2D(1, 1);
TextureWhite25P.SetPixel(0, 0, new Color(1, 1, 1, .25f));
TextureWhite25P.Apply();
TextureBlack25P = new Texture2D(1, 1);
TextureBlack25P.SetPixel(0, 0, new Color(0, 0, 0, .25f));
TextureBlack25P.Apply();
TextureFBBlue = new Texture2D(1, 1);
TextureFBBlue.SetPixel(0, 0, ColorFB);
TextureFBBlue.Apply();
TextureTextField = new Texture2D(1, 1);
TextureTextField.SetPixel(0, 0, new Color(.85f, .85f, .95f));
TextureTextField.Apply();
TextureWitDark = new Texture2D(1, 1);
TextureWitDark.SetPixel(0,0, new Color(0.267f, 0.286f, 0.31f));
TextureWitDark.Apply();
BackgroundWhite = new GUIStyle();
BackgroundWhite.normal.background = TextureWhite;
BackgroundWhite25P = new GUIStyle();
BackgroundWhite25P.normal.background = TextureWhite25P;
BackgroundBlack25P = new GUIStyle();
BackgroundBlack25P.normal.background = TextureBlack25P;
BackgroundBlack25P.normal.textColor = Color.white;
BackgroundWitDark = new GUIStyle();
BackgroundWitDark.normal.background = TextureWitDark;
FacebookButton = new GUIStyle(EditorStyles.miniButton);
Label = new GUIStyle(EditorStyles.label);
Label.richText = true;
Label.wordWrap = true;
WordwrappedLabel = new GUIStyle(EditorStyles.label);
WordwrappedLabel.wordWrap = true;
LabelHeader = new GUIStyle(Label);
LabelHeader.fontSize = 24;
LabelHeader2 = new GUIStyle(Label);
LabelHeader2.fontSize = 14;
Link = new GUIStyle(Label);
Link.normal.textColor = ColorFB;
TextField = new GUIStyle(EditorStyles.textField);
TextField.normal.background = TextureTextField;
TextField.normal.textColor = Color.black;
ImageIcon = new GUIStyle(EditorStyles.label);
ImageIcon.fixedWidth = 16;
ImageIcon.fixedHeight = 16;
titleContent = new GUIContent("Wit.ai", WitIcon);
welcomeTitleContent = new GUIContent("Welcome to Wit.ai", WitIcon);
PasteIcon = EditorGUIUtility.IconContent("Clipboard");
EditIcon = EditorGUIUtility.IconContent("editicon.sml");
ResetIcon = EditorGUIUtility.IconContent("TreeEditor.Trash");
AcceptIcon = EditorGUIUtility.IconContent("FilterSelectedOnly");
ObjectPickerIcon = EditorGUIUtility.IconContent("d_Record Off");
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f3a6f90ff4b18ab4aa8d5ff65b45d1c9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 735aff1d159a06444a21509d7f24921b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d054f5543f909634a88982d2b2dc8e55
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,32 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using Facebook.WitAi.Lib;
using UnityEngine;
using UnityEngine.Events;
namespace Facebook.WitAi.CallbackHandlers
{
public class SimpleIntentHandler : WitResponseHandler
{
[SerializeField] public string intent;
[Range(0, 1f)]
[SerializeField] public float confidence = .9f;
[SerializeField] private UnityEvent onIntentTriggered = new UnityEvent();
public UnityEvent OnIntentTriggered => onIntentTriggered;
protected override void OnHandleResponse(WitResponseNode response)
{
var intentNode = WitResultUtilities.GetFirstIntent(response);
if (intent == intentNode["name"].Value && intentNode["confidence"].AsFloat > confidence)
{
onIntentTriggered.Invoke();
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8d2d3ff93ff48bd40ab5bca3cf4e6d2c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Lib;
using UnityEngine;
using UnityEngine.Events;
namespace Facebook.WitAi.CallbackHandlers
{
public class SimpleStringEntityHandler : WitResponseHandler
{
[SerializeField] public string intent;
[SerializeField] public string entity;
[Range(0, 1f)] [SerializeField] public float confidence = .9f;
[SerializeField] public string format;
[SerializeField] private StringEntityMatchEvent onIntentEntityTriggered
= new StringEntityMatchEvent();
public StringEntityMatchEvent OnIntentEntityTriggered => onIntentEntityTriggered;
protected override void OnHandleResponse(WitResponseNode response)
{
var intentNode = WitResultUtilities.GetFirstIntent(response);
if (intent == intentNode["name"].Value && intentNode["confidence"].AsFloat > confidence)
{
var entityValue = WitResultUtilities.GetFirstEntityValue(response, entity);
if (!string.IsNullOrEmpty(format))
{
onIntentEntityTriggered.Invoke(format.Replace("{value}", entityValue));
}
else
{
onIntentEntityTriggered.Invoke(entityValue);
}
}
}
}
[Serializable]
public class StringEntityMatchEvent : UnityEvent<string> {}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 77dceeee73817ec4c844564714e05c77
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using Facebook.WitAi.Lib;
using UnityEngine;
namespace Facebook.WitAi.CallbackHandlers
{
public abstract class WitResponseHandler : MonoBehaviour
{
[SerializeField] public VoiceService wit;
private void OnValidate()
{
if (!wit) wit = FindObjectOfType<VoiceService>();
}
private void OnEnable()
{
if (!wit) wit = FindObjectOfType<VoiceService>();
if (!wit)
{
Debug.LogError("Wit not found in scene. Disabling " + GetType().Name + " on " +
name);
enabled = false;
}
else
{
wit.events.OnResponse.AddListener(OnHandleResponse);
}
}
private void OnDisable()
{
wit.events.OnResponse.RemoveListener(OnHandleResponse);
}
protected abstract void OnHandleResponse(WitResponseNode response);
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 097381abbd7a3364f80ac4460551a2cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,304 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Facebook.WitAi.Data;
using Facebook.WitAi.Lib;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Serialization;
namespace Facebook.WitAi.CallbackHandlers
{
public class WitResponseMatcher : WitResponseHandler
{
[Header("Intent")]
[SerializeField] public string intent;
[FormerlySerializedAs("confidence")]
[Range(0, 1f), SerializeField] public float confidenceThreshold = .6f;
[FormerlySerializedAs("valuePaths")]
[Header("Value Matching")]
[SerializeField] public ValuePathMatcher[] valueMatchers;
[Header("Output")]
[SerializeField] private FormattedValueEvents[] formattedValueEvents;
[SerializeField] private MultiValueEvent onMultiValueEvent = new MultiValueEvent();
private static Regex valueRegex = new Regex(Regex.Escape("{value}"), RegexOptions.Compiled);
protected override void OnHandleResponse(WitResponseNode response)
{
if (IntentMatches(response))
{
if (ValueMatches(response))
{
for (int j = 0; j < formattedValueEvents.Length; j++)
{
var formatEvent = formattedValueEvents[j];
var result = formatEvent.format;
for (int i = 0; i < valueMatchers.Length; i++)
{
var reference = valueMatchers[i].Reference;
var value = reference.GetStringValue(response);
if (!string.IsNullOrEmpty(formatEvent.format))
{
if (!string.IsNullOrEmpty(value))
{
result = valueRegex.Replace(result, value, 1);
result = result.Replace("{" + i + "}", value);
}
else if (result.Contains("{" + i + "}"))
{
result = "";
break;
}
}
}
if (!string.IsNullOrEmpty(result))
{
formatEvent.onFormattedValueEvent?.Invoke(result);
}
}
}
List<string> values = new List<string>();
for (int i = 0; i < valueMatchers.Length; i++)
{
var value = valueMatchers[i].Reference.GetStringValue(response);
values.Add(value);
}
onMultiValueEvent.Invoke(values.ToArray());
}
}
private bool ValueMatches(WitResponseNode response)
{
bool matches = true;
for (int i = 0; i < valueMatchers.Length && matches; i++)
{
var matcher = valueMatchers[i];
var value = matcher.Reference.GetStringValue(response);
matches &= !matcher.contentRequired || !string.IsNullOrEmpty(value);
switch (matcher.matchMethod)
{
case MatchMethod.RegularExpression:
matches &= Regex.Match(value, matcher.matchValue).Success;
break;
case MatchMethod.Text:
matches &= value == matcher.matchValue;
break;
case MatchMethod.IntegerComparison:
matches &= CompareInt(value, matcher);
break;
case MatchMethod.FloatComparison:
matches &= CompareFloat(value, matcher);
break;
case MatchMethod.DoubleComparison:
matches &= CompareDouble(value, matcher);
break;
}
}
return matches;
}
private bool CompareDouble(string value, ValuePathMatcher matcher)
{
double dValue;
// This one is freeform based on the input so we will retrun false if it is not parsable
if (!double.TryParse(value, out dValue)) return false;
// We will throw an exception if match value is not a numeric value. This is a developer
// error.
double dMatchValue = double.Parse(matcher.matchValue);
switch (matcher.comparisonMethod)
{
case ComparisonMethod.Equals:
return Math.Abs(dValue - dMatchValue) < matcher.floatingPointComparisonTolerance;
case ComparisonMethod.NotEquals:
return Math.Abs(dValue - dMatchValue) > matcher.floatingPointComparisonTolerance;
case ComparisonMethod.Greater:
return dValue > dMatchValue;
case ComparisonMethod.Less:
return dValue < dMatchValue;
case ComparisonMethod.GreaterThanOrEqualTo:
return dValue >= dMatchValue;
case ComparisonMethod.LessThanOrEqualTo:
return dValue <= dMatchValue;
}
return false;
}
private bool CompareFloat(string value, ValuePathMatcher matcher)
{
float dValue;
// This one is freeform based on the input so we will retrun false if it is not parsable
if (!float.TryParse(value, out dValue)) return false;
// We will throw an exception if match value is not a numeric value. This is a developer
// error.
float dMatchValue = float.Parse(matcher.matchValue);
switch (matcher.comparisonMethod)
{
case ComparisonMethod.Equals:
return Math.Abs(dValue - dMatchValue) <
matcher.floatingPointComparisonTolerance;
case ComparisonMethod.NotEquals:
return Math.Abs(dValue - dMatchValue) >
matcher.floatingPointComparisonTolerance;
case ComparisonMethod.Greater:
return dValue > dMatchValue;
case ComparisonMethod.Less:
return dValue < dMatchValue;
case ComparisonMethod.GreaterThanOrEqualTo:
return dValue >= dMatchValue;
case ComparisonMethod.LessThanOrEqualTo:
return dValue <= dMatchValue;
}
return false;
}
private bool CompareInt(string value, ValuePathMatcher matcher)
{
int dValue;
// This one is freeform based on the input so we will retrun false if it is not parsable
if (!int.TryParse(value, out dValue)) return false;
// We will throw an exception if match value is not a numeric value. This is a developer
// error.
int dMatchValue = int.Parse(matcher.matchValue);
switch (matcher.comparisonMethod)
{
case ComparisonMethod.Equals:
return dValue == dMatchValue;
case ComparisonMethod.NotEquals:
return dValue != dMatchValue;
case ComparisonMethod.Greater:
return dValue > dMatchValue;
case ComparisonMethod.Less:
return dValue < dMatchValue;
case ComparisonMethod.GreaterThanOrEqualTo:
return dValue >= dMatchValue;
case ComparisonMethod.LessThanOrEqualTo:
return dValue <= dMatchValue;
}
return false;
}
private bool IntentMatches(WitResponseNode response)
{
var intentNode = response.GetFirstIntent();
if (string.IsNullOrEmpty(intent))
{
return true;
}
if (intent == intentNode["name"].Value)
{
var actualConfidence = intentNode["confidence"].AsFloat;
if (actualConfidence >= confidenceThreshold)
{
return true;
}
Debug.Log($"{intent} matched, but confidence ({actualConfidence.ToString("F")}) was below threshold ({confidenceThreshold.ToString("F")})");
}
return false;
}
}
[Serializable]
public class MultiValueEvent : UnityEvent<string[]>
{
}
[Serializable]
public class ValueEvent : UnityEvent<string>
{ }
[Serializable]
public class FormattedValueEvents
{
[Tooltip("Modify the string output, values can be inserted with {value} or {0}, {1}, {2}")]
public string format;
public ValueEvent onFormattedValueEvent = new ValueEvent();
}
[Serializable]
public class ValuePathMatcher
{
[Tooltip("The path to a value within a WitResponseNode")]
public string path;
[Tooltip("A reference to a wit value object")]
public WitValue witValueReference;
[Tooltip("Does this path need to have text in the value to be considered a match")]
public bool contentRequired = true;
[Tooltip("If set the match value will be treated as a regular expression.")]
public MatchMethod matchMethod;
[Tooltip("The operator used to compare the value with the match value. Ex: response.value > matchValue")]
public ComparisonMethod comparisonMethod;
[Tooltip("Value used to compare with the result when Match Required is set")]
public string matchValue;
[Tooltip("The variance allowed when comparing two floating point values for equality")]
public double floatingPointComparisonTolerance = .0001f;
private WitResponseReference pathReference;
public WitResponseReference Reference
{
get
{
if (witValueReference) return witValueReference.Reference;
if (null == pathReference || pathReference.path != path)
{
pathReference = WitResultUtilities.GetWitResponseReference(path);
}
return pathReference;
}
}
}
public enum ComparisonMethod
{
Equals,
NotEquals,
Greater,
GreaterThanOrEqualTo,
Less,
LessThanOrEqualTo
}
public enum MatchMethod
{
None,
Text,
RegularExpression,
IntegerComparison,
FloatComparison,
DoubleComparison
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 591c3d6f017c11b4faa41506d75635b9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System.Text.RegularExpressions;
using Facebook.WitAi.Lib;
using Facebook.WitAi.Utilities;
using UnityEngine;
namespace Facebook.WitAi.CallbackHandlers
{
public class WitUtteranceMatcher : WitResponseHandler
{
[SerializeField] private string searchText;
[SerializeField] private bool exactMatch = true;
[SerializeField] private bool useRegex;
[SerializeField] private StringEvent onUtteranceMatched = new StringEvent();
private Regex regex;
protected override void OnHandleResponse(WitResponseNode response)
{
var text = response["text"].Value;
if (useRegex)
{
if (null == regex)
{
regex = new Regex(searchText, RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
var match = regex.Match(text);
if (match.Success)
{
if (exactMatch && match.Value == text)
{
onUtteranceMatched?.Invoke(text);
}
else
{
onUtteranceMatched?.Invoke(text);
}
}
}
else if (exactMatch && text.ToLower() == searchText.ToLower())
{
onUtteranceMatched?.Invoke(text);
}
else if (text.ToLower().Contains(searchText.ToLower()))
{
onUtteranceMatched?.Invoke(text);
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d0a93535f06eabe47bf93b4b504873c8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5c9bc9136c8441e48996d814209d4c2e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
namespace Facebook.WitAi.Data
{
[Serializable]
public class AudioEncoding
{
public enum Endian
{
Big,
Little
}
/// <summary>
/// The expected encoding of the mic pcm data
/// </summary>
public string encoding = "signed-integer";
/// <summary>
/// The number of bits per sample
/// </summary>
public int bits = 16;
/// <summary>
/// The sample rate used to capture audio
/// </summary>
public int samplerate = 16000;
/// <summary>
/// The endianess of the data
/// </summary>
public Endian endian = Endian.Little;
public override string ToString()
{
return $"audio/raw;bits={bits};rate={samplerate / 1000}k;encoding={encoding};endian={endian.ToString().ToLower()}";
;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 991b11599dd41ac448cf8d6114e29d36
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d99f42b1387bffe4b845b1bf9f9cf5cb
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Configuration;
using Facebook.WitAi.Lib;
using UnityEngine;
namespace Facebook.WitAi.Data.Configuration
{
[Serializable]
public class WitApplication : WitConfigurationData
{
[SerializeField] public string name;
[SerializeField] public string id;
[SerializeField] public string lang;
[SerializeField] public bool isPrivate;
[SerializeField] public string createdAt;
#if UNITY_EDITOR
protected override WitRequest OnCreateRequest()
{
return witConfiguration.GetAppRequest(id);
}
public override void UpdateData(WitResponseNode appWitResponse)
{
id = appWitResponse["id"].Value;
name = appWitResponse["name"].Value;
lang = appWitResponse["lang"].Value;
isPrivate = appWitResponse["private"].AsBool;
createdAt = appWitResponse["created_at"].Value;
}
public static WitApplication FromJson(WitResponseNode appWitResponse)
{
var app = new WitApplication();
app.UpdateData(appWitResponse);
return app;
}
#endif
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7ca958861dc343789f31f1d597fd24cf
timeCreated: 1621351239

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Configuration;
using Facebook.WitAi.Data.Entities;
using Facebook.WitAi.Data.Intents;
using Facebook.WitAi.Data.Traits;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Facebook.WitAi.Data.Configuration
{
public class WitConfiguration : ScriptableObject
{
[HideInInspector]
[SerializeField] public WitApplication application;
[HideInInspector] [SerializeField] public string configId;
/// <summary>
/// Access token used in builds to make requests for data from Wit.ai
/// </summary>
[Tooltip("Access token used in builds to make requests for data from Wit.ai")]
[SerializeField] public string clientAccessToken;
[Tooltip("The number of milliseconds to wait before requests to Wit.ai will timeout")]
[SerializeField] public int timeoutMS = 10000;
/// <summary>
/// Configuration parameters to set up a custom endpoint for testing purposes and request forwarding. The default values here will work for most.
/// </summary>
[Tooltip("Configuration parameters to set up a custom endpoint for testing purposes and request forwarding. The default values here will work for most.")]
[SerializeField] public WitEndpointConfig endpointConfiguration = new WitEndpointConfig();
[SerializeField] public WitEntity[] entities;
[SerializeField] public WitIntent[] intents;
[SerializeField] public WitTrait[] traits;
public WitApplication Application => application;
private void OnEnable()
{
#if UNITY_EDITOR
if (string.IsNullOrEmpty(configId))
{
configId = GUID.Generate().ToString();
EditorUtility.SetDirty(this);
}
#endif
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ae5a46bda3295124c99b0e6537ac7252
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Data.Configuration;
using Facebook.WitAi.Lib;
using UnityEngine;
namespace Facebook.WitAi.Configuration
{
[Serializable]
public abstract class WitConfigurationData
{
[SerializeField] public WitConfiguration witConfiguration;
#if UNITY_EDITOR
public void UpdateData(Action onUpdateComplete = null)
{
if (!witConfiguration)
{
onUpdateComplete?.Invoke();
return;
}
var request = OnCreateRequest();
request.onResponse = (r) => OnUpdateData(r, onUpdateComplete);
request.Request();
}
protected abstract WitRequest OnCreateRequest();
private void OnUpdateData(WitRequest request, Action onUpdateComplete)
{
if (request.StatusCode == 200)
{
UpdateData(request.ResponseData);
}
else
{
Debug.LogError(request.StatusDescription);
}
onUpdateComplete?.Invoke();
}
public abstract void UpdateData(WitResponseNode data);
#endif
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 002ec29e2fc64951b9d57ab4cdbf659e
timeCreated: 1621354945

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Data.Configuration;
using UnityEngine;
namespace Facebook.WitAi.Configuration
{
[Serializable]
public class WitEndpointConfig
{
private static WitEndpointConfig defaultEndpointConfig = new WitEndpointConfig();
public string uriScheme;
public string authority;
public int port;
public string witApiVersion;
public string speech;
public string message;
public string UriScheme => string.IsNullOrEmpty(uriScheme) ? WitRequest.URI_SCHEME : uriScheme;
public string Authority =>
string.IsNullOrEmpty(authority) ? WitRequest.URI_AUTHORITY : authority;
public string WitApiVersion => string.IsNullOrEmpty(witApiVersion)
? WitRequest.WIT_API_VERSION
: witApiVersion;
public string Speech =>
string.IsNullOrEmpty(speech) ? WitRequest.WIT_ENDPOINT_SPEECH : speech;
public string Message =>
string.IsNullOrEmpty(message) ? WitRequest.WIT_ENDPOINT_MESSAGE : message;
public static WitEndpointConfig GetEndpointConfig(WitConfiguration witConfig)
{
return witConfig && null != witConfig.endpointConfiguration
? witConfig.endpointConfiguration
: defaultEndpointConfig;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 61a0415bfdfa4d64e89801fbc0b30ec7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using Facebook.WitAi.Interfaces;
namespace Facebook.WitAi.Configuration
{
public class WitRequestOptions
{
/// <summary>
/// An interface that provides a list of entities that should be used for nlu resolution.
/// </summary>
public IDynamicEntitiesProvider dynamicEntities;
/// <summary>
/// The maximum number of intent matches to return
/// </summary>
public int nBestIntents = -1;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a6834fd3c55fb41a1885302e6043f5d6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,64 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Data.Configuration;
using Facebook.WitAi.Interfaces;
using UnityEngine;
using UnityEngine.Serialization;
namespace Facebook.WitAi.Configuration
{
[Serializable]
public class WitRuntimeConfiguration
{
[Tooltip("Configuration for the application used in this instance of Wit.ai services")]
[SerializeField]
public WitConfiguration witConfiguration;
[Header("Keepalive")]
[Tooltip("The minimum volume from the mic needed to keep the activation alive")]
[SerializeField]
public float minKeepAliveVolume = .0005f;
[FormerlySerializedAs("minKeepAliveTime")]
[Tooltip(
"The amount of time in seconds an activation will be kept open after volume is under the keep alive threshold")]
[SerializeField]
public float minKeepAliveTimeInSeconds = 2f;
[FormerlySerializedAs("minTranscriptionKeepAliveTime")]
[Tooltip(
"The amount of time in seconds an activation will be kept open after words have been detected in the live transcription")]
[SerializeField]
public float minTranscriptionKeepAliveTimeInSeconds = 1f;
[Tooltip("The maximum amount of time in seconds the mic will stay active")]
[Range(0, 20f)]
[SerializeField]
public float maxRecordingTime = 20;
[Header("Sound Activation")]
[Tooltip("The minimum volume level needed to be heard to start collecting data from the audio source.")]
[SerializeField] public float soundWakeThreshold = .0005f;
[Tooltip("The length of the individual samples read from the audio source")]
[Range(10, 500)] [SerializeField] public int sampleLengthInMs = 10;
[Tooltip("The total audio data that should be buffered for lookback purposes on sound based activations.")]
[SerializeField] public float micBufferLengthInSeconds = 1;
[Header("Custom Transcription")]
[Tooltip(
"If true, the audio recorded in the activation will be sent to Wit.ai for processing. If a custom transcription provider is set and this is false, only the transcription will be sent to Wit.ai for processing")]
[SerializeField]
public bool sendAudioToWit = true;
[Tooltip("A custom provider that returns text to be used for nlu processing on activation instead of sending audio.")]
[SerializeField] public CustomTranscriptionProvider customTranscriptionProvider;
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bd8d40c9f75b44b5940fcc21769d6af0
timeCreated: 1629397017

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d92a289db3a8408dba9dd973090b1ade
timeCreated: 1632287743

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System.Collections.Generic;
using Facebook.WitAi.Interfaces;
using Facebook.WitAi.Lib;
namespace Facebook.WitAi.Data.Entities
{
public class WitDynamicEntities : IDynamicEntitiesProvider
{
public WitResponseClass entities;
public WitDynamicEntities()
{
entities = new WitResponseClass();
}
public void Add(WitSimpleDynamicEntity entity)
{
KeyValuePair<string, WitResponseArray> pair = entity.GetEntityPair();
entities.Add(pair.Key, pair.Value);
}
public void Add(WitDynamicEntity entity)
{
KeyValuePair<string, WitResponseArray> pair = entity.GetEntityPair();
entities.Add(pair.Key, pair.Value);
}
public string ToJSON()
{
return entities.ToString();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a296282c67dc244dd974baca4699c554
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System.Collections.Generic;
using Facebook.WitAi.Interfaces;
using Facebook.WitAi.Lib;
namespace Facebook.WitAi.Data.Entities
{
public class WitDynamicEntity : IDynamicEntitiesProvider
{
public string entity;
public Dictionary<string, List<string>> keywordsToSynonyms;
public WitDynamicEntity(string entity, Dictionary<string, List<string>> keywordsToSynonyms)
{
this.entity = entity;
this.keywordsToSynonyms = keywordsToSynonyms;
}
public KeyValuePair<string, WitResponseArray> GetEntityPair() {
var keywordEntries = new WitResponseArray();
foreach (var keywordToSynonyms in keywordsToSynonyms)
{
var synonyms = new WitResponseArray();
foreach (string synonym in keywordToSynonyms.Value)
{
synonyms.Add(new WitResponseData(synonym));
}
var keywordEntry = new WitResponseClass();
keywordEntry.Add("keyword", new WitResponseData(keywordToSynonyms.Key));
keywordEntry.Add("synonyms", synonyms);
keywordEntries.Add(keywordEntry);
}
return new KeyValuePair<string, WitResponseArray>(entity, keywordEntries);
}
public string ToJSON()
{
KeyValuePair<string, WitResponseArray> pair = this.GetEntityPair();
var root = new WitResponseClass();
root.Add(pair.Key, pair.Value);
return root.ToString();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: efe24d6c4ed424d25a19396c7a2eec38
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Configuration;
using Facebook.WitAi.Data.Keywords;
using Facebook.WitAi.Lib;
using UnityEngine;
namespace Facebook.WitAi.Data.Entities
{
[Serializable]
public class WitEntity : WitConfigurationData
{
[SerializeField] public string id;
[SerializeField] public string name;
[SerializeField] public string[] lookups;
[SerializeField] public WitEntityRole[] roles;
[SerializeField] public WitKeyword[] keywords;
#if UNITY_EDITOR
protected override WitRequest OnCreateRequest()
{
return witConfiguration.GetEntityRequest(name);
}
public override void UpdateData(WitResponseNode entityWitResponse)
{
id = entityWitResponse["id"].Value;
name = entityWitResponse["name"].Value;
lookups = entityWitResponse["lookups"].AsStringArray;
var roleArray = entityWitResponse["roles"].AsArray;
roles = new WitEntityRole[roleArray.Count];
for (int i = 0; i < roleArray.Count; i++)
{
roles[i] = WitEntityRole.FromJson(roleArray[i]);
}
var keywordArray = entityWitResponse["keywords"].AsArray;
keywords = new WitKeyword[keywordArray.Count];
for (int i = 0; i < keywordArray.Count; i++)
{
keywords[i] = WitKeyword.FromJson(keywordArray[i]);
}
}
public static WitEntity FromJson(WitResponseNode entityWitResponse)
{
var entity = new WitEntity();
entity.UpdateData(entityWitResponse);
return entity;
}
#endif
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8b8d1931ec6f428ba4f36da3ddcb15f3
timeCreated: 1621351104

View File

@@ -0,0 +1,31 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Lib;
using UnityEngine;
namespace Facebook.WitAi.Data.Keywords
{
[Serializable]
public class WitEntityRole
{
[SerializeField] public string id;
[SerializeField] public string name;
#if UNITY_EDITOR
public static WitEntityRole FromJson(WitResponseNode roleNode)
{
return new WitEntityRole()
{
id = roleNode["id"],
name = roleNode["name"]
};
}
#endif
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5f1cc15e5a59a854e837f452c8f4f4d6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,49 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System.Collections.Generic;
using Facebook.WitAi.Interfaces;
using Facebook.WitAi.Lib;
namespace Facebook.WitAi.Data.Entities
{
public class WitSimpleDynamicEntity : IDynamicEntitiesProvider
{
public List<string> keywords;
public string entity;
public WitSimpleDynamicEntity(string entityIdentifier, List<string> words)
{
entity = entityIdentifier;
keywords = words;
}
public KeyValuePair<string, WitResponseArray> GetEntityPair() {
var keywordEntries = new WitResponseArray();
foreach (string keyword in keywords)
{
var synonyms = new WitResponseArray();
synonyms.Add(new WitResponseData(keyword));
var keywordEntry = new WitResponseClass();
keywordEntry.Add("keyword", new WitResponseData(keyword));
keywordEntry.Add("synonyms", synonyms);
keywordEntries.Add(keywordEntry);
}
return new KeyValuePair<string, WitResponseArray>(entity, keywordEntries);
}
public string ToJSON()
{
KeyValuePair<string, WitResponseArray> pair = this.GetEntityPair();
var root = new WitResponseClass();
root.Add(pair.Key, pair.Value);
return root.ToString();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e15f31f7f3b6c49fb96d0553d125fe22
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7de07ce5d8884e15924606bffef7ed67
timeCreated: 1632287863

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Facebook.WitAi.Configuration;
using Facebook.WitAi.Data.Entities;
using Facebook.WitAi.Lib;
using UnityEngine;
namespace Facebook.WitAi.Data.Intents
{
[Serializable]
public class WitIntent : WitConfigurationData
{
[SerializeField] public string id;
[SerializeField] public string name;
[SerializeField] public WitEntity[] entities;
#if UNITY_EDITOR
protected override WitRequest OnCreateRequest()
{
return witConfiguration.GetIntentRequest(name);
}
public override void UpdateData(WitResponseNode intentWitResponse)
{
id = intentWitResponse["id"].Value;
name = intentWitResponse["name"].Value;
var entityArray = intentWitResponse["entities"].AsArray;
var n = entityArray.Count;
entities = new WitEntity[n];
for (int i = 0; i < n; i++)
{
entities[i] = WitEntity.FromJson(entityArray[i]);
entities[i].witConfiguration = witConfiguration;
}
}
public static WitIntent FromJson(WitResponseNode intentWitResponse)
{
var intent = new WitIntent();
intent.UpdateData(intentWitResponse);
return intent;
}
#endif
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5ce915454f6441089c0cc0ff88d57e00
timeCreated: 1621351293

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 90f74c8768a041f1803383e7c62e89e0
timeCreated: 1632287849

Some files were not shown because too many files have changed in this diff Show More