-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
232 lines (197 loc) · 8.01 KB
/
index.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
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
/*
* Copyright (C) 2022 Aspose Pty Ltd. All Rights Reserved.
*
* Licensed under the MIT License (hereinafter the "License");
* you may not use this file except in accordance with the License.
* You can obtain a copy of the License at
*
* https://github.com/aspose-omr-cloud/aspose-omr-cloud-dotnet/blob/master/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import path from "path";
import fs from "fs";
import { Config } from "./src/model/Config";
import { GenerateTemplate } from "./src/api/generateTemplate";
import { ApiClient } from "./src/ApiClient";
import { PageSettings } from "./src/model/pageSettings";
import { OmrGenerateTask } from "./src/model/OMRGenerateTask";
import { OMRResponse } from "./src/model/OMRResponse";
import { OmrRecognizeTask } from "./src/model/OMRRecognizeTask";
import { RecognizeTemplate } from "./src/api/recognizeTemplate";
export abstract class Demo {
public static configFileName: string = "test_config.json";
public static demoDataSubmoduleName: string = "aspose-omr-cloud-demo-data";
public static templateGenerationFileName: string = "Aspose_test.txt";
public static templateImageName: string = "Aspose_test.jpg";
public static omrFileName: string = "Aspose_test.omr";
public static resultFileName: string = "Aspose_test.csv";
public static templateLogosImagesNames = [
"logo1.jpg",
"logo2.png",
];
public static config: Config;
public static apiClient: ApiClient;
public static generateApi: GenerateTemplate;
public static recognizeApi: RecognizeTemplate;
public static async init() {
let configFilePath: string = path.join(
__dirname,
"..",
this.demoDataSubmoduleName,
this.configFileName
);
this.config = Config.parseJson(await fs.readFileSync(configFilePath).toString());
if (!this.config.basePath) {
throw new Error("Unable to find file" + configFilePath);
}
this.config.dataFolder = path.join(__dirname,"..",this.demoDataSubmoduleName,this.config.dataFolder);
this.config.resultFolder = path.join(__dirname,"..",this.demoDataSubmoduleName,this.config.resultFolder);
this.apiClient = new ApiClient(this.config.basePath,this.config);
this.generateApi = new GenerateTemplate(this.apiClient);
this.recognizeApi = new RecognizeTemplate(this.apiClient);
}
public static async runDemo() {
await this.init();
/// <summary>
/// STEP 1: Queue the template source file for generation
/// </summary>
console.log("\t\tGenerate template...");
let templateId : string = await this.generateTemplate();
/// <summary>
/// STEP 2: Fetch generated printable form and recognition pattern
/// </summary>
console.log("\t\tGet generation result by ID...");
let generationResult: OMRResponse = await this.getGenerationResultById(templateId);
/// <summary>
/// STEP 3: Save the printable form and recognition pattern into result_folder
/// </summary>
console.log("\t\tSave generation result...");
await this.saveGenerationResult(generationResult);
/// <summary>
/// STEP 4: Queue the scan / photo of the filled form for recognition
/// </summary>
console.log("\t\tRecognize image...");
let recognizeTemplateId: string = await this.recognizeImage(
path.join(this.config.dataFolder, this.templateImageName),
path.join(this.config.resultFolder, this.omrFileName));
/// <summary>
/// STEP 5: Fetch recognition results
/// </summary>
console.log("\t\tGet recognition result by ID...");
let recognitionResponse:OMRResponse =
await this.getRecognitionResultById(recognizeTemplateId);
/// <summary>
/// STEP 6: Save the recognition results into result_folder
/// </summary>
console.log("\t\tSave recognition result...");
await this.saveRecognitionResult(recognitionResponse);
}
//#region Generate Temlate
public static async generateTemplate() : Promise<string> {
var markupFile =
fs.readFileSync(path.join(this.config.dataFolder, this.templateGenerationFileName));
let images:{ [key: string]: string; } = {};
for (let i = 0; i < this.templateLogosImagesNames.length; i++) {
let logo: string = fs.readFileSync(path.join(this.config.dataFolder, this.templateLogosImagesNames[i])).toString("base64");
images[this.templateLogosImagesNames[i]] = logo;
}
let settings:PageSettings = {
fontFamily: "Comic Sans MS",
fontStyle:"Italic",
fontSize:9,
paperSize:"A4",
bubbleColor:"Black",
pageMarginLeft:190,
pageMarginRight:190,
orientation:"Vertical",
bubbleSize:"Normal",
outputFormat:"Png"
};
let task: OmrGenerateTask = {
markupFile: markupFile.toString("base64"),
settings,
images,
};
return await this.generateApi.postGenerateTemplate(task);
}
public static async getGenerationResultById(id:string) : Promise<OMRResponse> {
let generationResult : OMRResponse = null;
while (true) {
generationResult = await this.generateApi.getGenerateTemplate(id);
if (generationResult.responseStatusCode == "Error"){
throw new Error(generationResult.error.messages[0]);
}
if (generationResult.responseStatusCode == "Ok") {
break;
}
console.log("Wait, please! Your request is still being processed");
await new Promise(r => setTimeout(r, 5000));
}
return generationResult;
}
public static async saveGenerationResult(generationResult:OMRResponse){
if (generationResult.error == null) {
for (let i = 0; i < generationResult.results.length; i++) {
let type:string = generationResult.results[i].type ?? "";
let name: string = "Aspose_test" + "." + type.toLowerCase();
let dirPath = path.join(this.config.resultFolder,name);
await fs.writeFileSync(dirPath, Buffer.from(generationResult.results[i].data,"base64"))
}
} else {
console.error("Error :" + generationResult.error.toString());
}
}
//#endregion
//#region Recognize Image
public static async recognizeImage(imagePath, omrFilePath) : Promise<string> {
// get the omr file
let omrFile = await fs.readFileSync(omrFilePath);
// set up recognition threshold
let recognitionThreshold = 30;
// get the filled template
let image = await fs.readFileSync(imagePath);
let images = [image.toString("base64")];
// Set up request
let task: OmrRecognizeTask = {
omrFile:omrFile.toString("base64"),
recognitionThreshold,
images
};
// call image recognition
return await this.recognizeApi.postRecognizeTemplate(task) ;
}
public static async getRecognitionResultById(id:string) : Promise<OMRResponse> {
let recognitionResult : OMRResponse = null;
while (true) {
recognitionResult = await this.recognizeApi.getRecognizeTemplate(id);
if (recognitionResult.responseStatusCode == "Error"){
throw new Error(recognitionResult.error.messages[0]);
}
if (recognitionResult.responseStatusCode == "Ok") {
break;
}
console.log("Wait, please! Your request is still being processed");
await new Promise(r => setTimeout(r, 5000));
}
return recognitionResult;
}
public static async saveRecognitionResult(recognitionResult:OMRResponse){
if (recognitionResult.error == null) {
let dirPath = path.join(this.config.resultFolder, this.resultFileName);
await fs.writeFileSync(dirPath, Buffer.from(recognitionResult.results[0].data,"base64"));
} else {
console.error("Error :" + recognitionResult.error.toString());
}
}
//#endregion
}
Demo.runDemo().then(()=>{
})
.catch((error)=>{
console.error("Exception: "+error);
});