-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
MustacheFormatter.ts
64 lines (57 loc) · 2.24 KB
/
MustacheFormatter.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Neil Enns. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import Mustache from "mustache";
import path from "path";
import Trigger from "./Trigger";
import IDeepStackPrediction from "./types/IDeepStackPrediction";
export function formatPredictions(predictions: IDeepStackPrediction[]): string {
return predictions
.map(prediction => {
return `${prediction.label} (${(prediction.confidence * 100).toFixed(0)}%)`;
})
.join(", ");
}
export function formatStatistics(triggeredCount: number, analyzedFilesCount: number): string {
return `Triggered count: ${triggeredCount} Analyzed file count: ${analyzedFilesCount}`;
}
function optionallyEncode(value: string, urlEncode: boolean): string {
return urlEncode ? encodeURIComponent(value) : value;
}
/**
* Replaces mustache templates in a string with values
* @param template The template string to format
* @param fileName The filename of the image being analyzed
* @param trigger The trigger that was fired
* @param predictions The predictions returned by the AI system
*/
export function format(
template: string,
fileName: string,
trigger: Trigger,
predictions: IDeepStackPrediction[],
urlEncode = false,
): string {
// Populate the payload wih the mustache template
const view = {
fileName: optionallyEncode(fileName, urlEncode),
baseName: optionallyEncode(path.basename(fileName), urlEncode),
predictions: optionallyEncode(JSON.stringify(predictions), urlEncode),
analysisDurationMs: trigger.analysisDuration,
formattedPredictions: optionallyEncode(formatPredictions(predictions), urlEncode),
formattedStatistics: optionallyEncode(
formatStatistics(trigger.triggeredCount, trigger.analyzedFilesCount),
urlEncode,
),
triggeredCount: trigger.triggeredCount,
analyzedFilesCount: trigger.analyzedFilesCount,
state: "on",
name: trigger.name,
};
// Turn off escaping
Mustache.escape = text => {
return text;
};
return Mustache.render(template, view);
}