-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathNewSmartDocReq.cs
More file actions
310 lines (285 loc) · 16.3 KB
/
Copy pathNewSmartDocReq.cs
File metadata and controls
310 lines (285 loc) · 16.3 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
using Contoso.CognitivePipeline.BackgroundServices.Data;
using Contoso.CognitivePipeline.BackgroundServices.Services;
using Contoso.CognitivePipeline.SharedModels.Models;
using Contoso.CognitivePipeline.BackgroundServices.Functions.Utilities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Contoso.CognitivePipeline.BackgroundServices.Functions
{
public static class NewSmartDocReq
{
private const string CosmosDbNameSetting = "ContosoShopManagerDb";
private const string CosmosCollectionName = "smartdocs";
//Another option to implement Cosmos DB client
//private static string endpointUrl = GlobalSettings.GetKeyValue(""); //ConfigurationManager.AppSettings["cosmosDBAccountEndpoint"];
//private static string authorizationKey = GlobalSettings.GetKeyValue(""); //ConfigurationManager.AppSettings["cosmosDBAccountKey"];
//private static DocumentClient client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
//For performance consideration, we will create the cosmos db client repo as static so it can be shared across multiple functions calls
//Empty constructor to load configurations from the Functions settings
private static CosmosDBRepository<SmartDoc> smartDocsDbClient = new CosmosDBRepository<SmartDoc>();
private static CosmosDBRepository<CognitivePipeline.SharedModels.Models.User> usersDbClient = new CosmosDBRepository<CognitivePipeline.SharedModels.Models.User>();
private static ILogger log;
[FunctionName("NewSmartDocReq")]
public static async Task<IActionResult> Run(
//HTTP Trigger
//Sample of used typed input parameter
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "NewSmartDocReq/{docId}")]HttpRequestMessage newReq,
//Input
string docId,
//Output
[Queue("newreq", Connection = "NewRequestQueue")]ICollector<string> outputQueueItem,
//Logger
ILogger logger)
{
var newSmartDocRequestJson = await newReq.Content.ReadAsStringAsync();
var newSmartDocRequest = JsonConvert.DeserializeObject<NewRequest<SmartDoc>>(newSmartDocRequestJson);
log = logger;
log.LogInformation($"***NewSmartDocReq function http triggered for: {newSmartDocRequestJson}");
string result = "";
try
{
newSmartDocRequest.Status = SmartDocStatus.InProcessing.ToString();
//In case used strongly typed trigger paramater
//string newSmartDocRequestJson = JsonConvert.SerializeObject(newSmartDocRequest);
//Check if request is Async (a new queue item will be added) or Sync (direct call to functions)
//Async execution
if (newSmartDocRequest.IsAsync)
{
//TODO: Implement Async execution through durable functions and queues
//outputQueueItem.Add(JsonConvert.SerializeObject(newSmartDocRequest));
//result = newSmartDocRequestJson;
//return (ActionResult)new OkObjectResult(result);
return (ActionResult)new BadRequestObjectResult("NOT IMPLEMENTED YET :)");
}
else //Sync exection
{
//TODO: FUTURE IMPROVEMENT the processing here directly from here throw call to HTTP Orchestrator Function
//Assess what type of processing instruction needed and execute the relevant functions
return await CognitivePipelineSyncProcessing(newSmartDocRequest);
}
}
catch (Exception ex)
{
log.LogError($"***EXCEPTION*** in NewSmartDocReq: {ex.Message}, {ex.StackTrace}");
return new BadRequestObjectResult($"{ex.Message}");
}
}
public static async Task<IActionResult> CognitivePipelineSyncProcessing(NewRequest<SmartDoc> newSmartDocRequest)
{
log.LogInformation($"***Starting Sync CognitivePipelineSyncProcessing***");
IActionResult executionResult = null;
if (newSmartDocRequest.Instructions.Contains(InstructionFlag.AnalyzeText.ToString()))
{
var stepName = InstructionFlag.AnalyzeText.ToString();
log.LogInformation($"***Starting {stepName}***");
string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + "/NewCognitiveOCR";
var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
try
{
executionResult = await FunctionExecuter.CallFunction(funcUri, content);
if (executionResult is OkObjectResult)
{
//TODO: Update the request processing step
var result = executionResult as OkObjectResult;
string updatedDocJson = result.Value.ToString();
NewRequest<SmartDoc> updatedDoc = JsonConvert.DeserializeObject<NewRequest<SmartDoc>>(updatedDocJson);
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
}
else
{
//TODO: Better error information to be implemented
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
catch (Exception ex)
{
log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = InstructionFlag.AnalyzeText.ToString()
});
}
}
if (newSmartDocRequest.Instructions.Contains(InstructionFlag.FaceAuthentication.ToString()))
{
var stepName = InstructionFlag.FaceAuthentication.ToString();
log.LogInformation($"***Starting {stepName}***");
CognitivePipeline.SharedModels.Models.User owner = await usersDbClient.GetItemAsync(newSmartDocRequest.OwnerId);
string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveFaceAuth/{owner.FacePersonId}";
var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
try
{
executionResult = await FunctionExecuter.CallFunction(funcUri, content);
if (executionResult is OkObjectResult)
{
//TODO: Update the request processing step
var result = executionResult as OkObjectResult;
string updatedDocJson = result.Value.ToString();
NewRequest<SmartDoc> updatedDoc = JsonConvert.DeserializeObject<NewRequest<SmartDoc>>(updatedDocJson);
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
}
else
{
//TODO: Better error information to be implemented
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
catch (Exception ex)
{
log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
if (newSmartDocRequest.Instructions.Contains(InstructionFlag.ShelfCompliance.ToString()))
{
var stepName = InstructionFlag.ShelfCompliance.ToString();
log.LogInformation($"***Starting {stepName}***");
string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + "/NewCognitiveShelfCompliance";
var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
try
{
executionResult = await FunctionExecuter.CallFunction(funcUri, content);
if (executionResult is OkObjectResult)
{
//TODO: Update the request processing step
var result = executionResult as OkObjectResult;
string updatedDocJson = result.Value.ToString();
NewRequest<SmartDoc> updatedDoc = JsonConvert.DeserializeObject<NewRequest<SmartDoc>>(updatedDocJson);
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
}
else
{
//TODO: Better error information to be implemented
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
catch (Exception ex)
{
log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
if (newSmartDocRequest.Instructions.Contains(InstructionFlag.Thumbnail.ToString()))
{
var stepName = InstructionFlag.Thumbnail.ToString();
log.LogInformation($"***Starting {stepName}***");
//Currently the 2 Thumbnail sizes are loaded from Functions settings.
var thumbnailConfig = GlobalSettings.GetKeyValue("CognitiveServices-Thumbnail-Config").Split(',');
string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveThumbnail/{thumbnailConfig[0]}/{thumbnailConfig[1]}/{thumbnailConfig[2]}/{thumbnailConfig[3]}";
var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
try
{
executionResult = await FunctionExecuter.CallFunction(funcUri, content);
if (executionResult is OkObjectResult)
{
//TODO: Update the request processing step
var result = executionResult as OkObjectResult;
string updatedDocJson = result.Value.ToString();
NewRequest<SmartDoc> updatedDoc = JsonConvert.DeserializeObject<NewRequest<SmartDoc>>(updatedDocJson);
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
}
else
{
//TODO: Better error information to be implemented
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
catch (Exception ex)
{
log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
if (newSmartDocRequest.Instructions.Contains(InstructionFlag.AnalyzeImage.ToString()))
{
var stepName = InstructionFlag.AnalyzeImage.ToString();
log.LogInformation($"***Starting {stepName}***");
string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveAnalyzeImage";
var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
try
{
executionResult = await FunctionExecuter.CallFunction(funcUri, content);
if (executionResult is OkObjectResult)
{
//TODO: Update the request processing step
var result = executionResult as OkObjectResult;
string updatedDocJson = result.Value.ToString();
NewRequest<SmartDoc> updatedDoc = JsonConvert.DeserializeObject<NewRequest<SmartDoc>>(updatedDocJson);
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
}
else
{
//TODO: Better error information to be implemented
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = InstructionFlag.AnalyzeImage.ToString()
});
}
}
catch (Exception ex)
{
log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
{
LastUpdatedAt = DateTime.UtcNow,
Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
StepName = stepName
});
}
}
//Validate cognitive processing and return relevant details
log.LogInformation($"***Final Results Processing***");
var processedResult = await CognitivePipelineResultProcessor.ProcessFinalResult(newSmartDocRequest, smartDocsDbClient, usersDbClient);
if (!string.IsNullOrEmpty(processedResult))
return (ActionResult)new OkObjectResult(processedResult);
else
return (ActionResult)new BadRequestObjectResult(processedResult);
}
}
}