-
Notifications
You must be signed in to change notification settings - Fork 479
/
LuisUtil.cs
194 lines (177 loc) · 7.7 KB
/
LuisUtil.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace Microsoft.Bot.Builder.AI.Luis
{
// Utility functions used to extract and transform data from Luis SDK
internal static class LuisUtil
{
internal const string MetadataKey = "$instance";
internal const string GeoV2 = "builtin.geographyV2.";
internal static readonly HashSet<string> _dateSubtypes = new HashSet<string> { "date", "daterange", "datetime", "datetimerange", "duration", "set", "time", "timerange" };
internal static string NormalizedIntent(string intent) => intent.Replace('.', '_').Replace(' ', '_');
internal static IDictionary<string, IntentScore> GetIntents(JObject luisResult)
{
var result = new Dictionary<string, IntentScore>();
var intents = (JObject)luisResult["intents"];
if (intents != null)
{
foreach (var intent in intents)
{
result.Add(NormalizedIntent(intent.Key), new IntentScore { Score = intent.Value["score"] == null ? 0.0 : intent.Value["score"].Value<double>() });
}
}
return result;
}
// Remove role and ensure that dot and space are not a part of entity names since we want to do JSON paths.
internal static string NormalizeEntity(string entity)
{
// Type::Role -> Role
var type = entity.Split(':').Last();
return type.Replace('.', '_').Replace(' ', '_');
}
// TODO: This code should be removed once V3.1 returns a geography object.
// It exists to find the type field in $instance if present in order to create
// a geography object with type and value.
internal static void FindGeographyTypes(JToken source, Dictionary<string, string> geoTypes)
{
if (source != null)
{
if (source is JObject obj)
{
if (obj.TryGetValue("type", out var type) && type.Type == JTokenType.String && type.Value<string>().StartsWith(GeoV2))
{
var path = type.Path.Replace(MetadataKey + ".", string.Empty);
path = path.Substring(0, path.LastIndexOf('.'));
geoTypes.Add(path, type.Value<string>().Substring(GeoV2.Length));
}
else
{
foreach (var property in obj.Properties())
{
FindGeographyTypes(property.Value, geoTypes);
}
}
}
else if (source is JArray arr)
{
foreach (var elt in arr)
{
FindGeographyTypes(elt, geoTypes);
}
}
}
}
internal static JToken MapProperties(JToken source, bool inInstance, Dictionary<string, string> geoTypes)
{
var result = source;
if (source is JObject obj)
{
var nobj = new JObject();
// Fix datetime by reverting to simple timex
if (!inInstance && obj.TryGetValue("type", out var type) && type.Type == JTokenType.String && _dateSubtypes.Contains(type.Value<string>()))
{
var timexs = obj["values"];
var arr = new JArray();
if (timexs != null)
{
var unique = new HashSet<string>();
foreach (var elt in timexs)
{
unique.Add(elt["timex"]?.Value<string>());
}
foreach (var timex in unique)
{
arr.Add(timex);
}
nobj["timex"] = arr;
}
nobj["type"] = type;
}
else
{
// Map or remove properties
foreach (var property in obj.Properties())
{
var name = NormalizeEntity(property.Name);
var isObj = property.Value.Type == JTokenType.Object;
var isArr = property.Value.Type == JTokenType.Array;
var isStr = property.Value.Type == JTokenType.String;
var isInt = property.Value.Type == JTokenType.Integer;
var val = MapProperties(property.Value, inInstance || property.Name == MetadataKey, geoTypes);
if (name == "datetime" && isArr)
{
nobj.Add("datetimeV1", val);
}
else if (name == "datetimeV2" && isArr)
{
nobj.Add("datetime", val);
}
else if (inInstance)
{
// Correct $instance issues
if (name == "length" && isInt)
{
nobj.Add("endIndex", property.Value.Value<int>() + property.Parent["startIndex"].Value<int>());
}
else if (!((isInt && name == "modelTypeId") ||
(isStr && name == "role")))
{
nobj.Add(name, val);
}
}
else
{
// Correct non-$instance values
if (name == "unit" && isStr)
{
nobj.Add("units", val);
}
else
{
nobj.Add(name, val);
}
}
}
}
result = nobj;
}
else if (source is JArray arr)
{
var narr = new JArray();
foreach (var elt in arr)
{
if (!inInstance && geoTypes.TryGetValue(elt.Path, out var geoType))
{
narr.Add(new JObject(new JProperty("location", elt.Value<string>()), new JProperty("type", geoType)));
}
else
{
narr.Add(MapProperties(elt, inInstance, geoTypes));
}
}
result = narr;
}
return result;
}
internal static JObject ExtractEntitiesAndMetadata(JObject prediction)
{
var entities = (JObject)JObject.FromObject(prediction["entities"]);
var geoTypes = new Dictionary<string, string>();
FindGeographyTypes(entities, geoTypes);
return (JObject)MapProperties(entities, false, geoTypes);
}
internal static void AddProperties(JObject luis, RecognizerResult result)
{
var sentiment = luis["sentiment"];
if (luis["sentiment"] != null)
{
result.Properties.Add("sentiment", new JObject(
new JProperty("label", sentiment["label"]),
new JProperty("score", sentiment["score"])));
}
}
}
}