/// <summary> /// Check response for error /// </summary> /// <param name="response">Response to check</param> private static void CheckForError(OMRResponse response) { if (response.ErrorCode != 0) { throw new Exception(response.ErrorText); } }
/// <summary> /// Calls Generate template function and processes result /// </summary> /// <param name="descriptionFileName">Name of the description file</param> /// <param name="descriptionData">Template description data in bytes</param> /// <param name="imagesPath">Cloud storage folder where images are located</param> /// <param name="additionalParams">Internal parameters</param> /// <returns>Generated content with template and image</returns> public static TemplateGenerationContent GenerateTemplate(string descriptionFileName, byte[] descriptionData, string imagesPath, string additionalParams) { imagesPath = @"{ ""ExtraStoragePath"":""" + imagesPath + @"""}"; OMRResponse response = RunOmrTask(OmrFunctions.GenerateTemplate, descriptionFileName, descriptionData, imagesPath, false, false, additionalParams); OmrResponseContent responseResult = response.Payload.Result; CheckTaskResult(response.Payload.Result); byte[] template = responseResult.ResponseFiles.First(x => x.Name.Contains(".omr")).Data; byte[] imageFile = responseResult.ResponseFiles.First(x => x.Name.Contains(".png")).Data; TemplateViewModel templateViewModel = TemplateSerializer.JsonToTemplate(Encoding.UTF8.GetString(template)); templateViewModel.ImageFileFormat = ".png"; TemplateGenerationContent generationContent = new TemplateGenerationContent(); generationContent.ImageData = imageFile; generationContent.Template = templateViewModel; return(generationContent); }
/// <summary> /// Performs OMR over single image /// </summary> /// <param name="imageName">Recognized image name</param> /// <param name="imageData">The image data</param> /// <param name="templateId">The template id</param> /// <param name="wasUploaded">Indicates if image was already uploaded on cloud</param> /// <param name="additionalParams">The additional parameters</param> /// <returns>Recognition results</returns> public static ImageRecognitionResult RecognizeImage(string imageName, byte[] imageData, string templateId, bool wasUploaded, string additionalParams) { OMRResponse response = RunOmrTask(OmrFunctions.RecognizeImage, imageName, imageData, templateId, wasUploaded, true, additionalParams); OmrResponseContent responseResult = response.Payload.Result; if (responseResult.Info.SuccessfulTasksCount < 1 || responseResult.Info.Details.RecognitionStatistics[0].TaskResult != "Pass") { StringBuilder builder = new StringBuilder(); builder.AppendLine("Error recognizing image " + "\"" + imageName + "\"."); foreach (string message in responseResult.Info.Details.RecognitionStatistics[0].TaskMessages) { builder.AppendLine(message); } throw new Exception(builder.ToString()); } ImageRecognitionResult recognitionResult = new ImageRecognitionResult(); foreach (Com.Aspose.Omr.Model.FileInfo file in responseResult.ResponseFiles) { if (file.Name.Contains(".dat")) { byte[] answersBytes = responseResult.ResponseFiles.First(x => x.Name.Contains(".dat")).Data; recognitionResult.RecognizedAnswers = Encoding.UTF8.GetString(answersBytes); } else if (file.Name.Contains(".jpg")) { recognitionResult.ClippedAreas.Add(new KeyValuePair <string, byte[]>(file.Name, file.Data)); } } return(recognitionResult); }
static void Main(string[] args) { // 0. Create template (using Aspose.OMR.Client) // 1. Run template correction OMRResponse response = RunOmrTask("CorrectTemplate", "AsposeTestExample.jpg", File.ReadAllText(path + "AsposeTestExample.omr")); // get template id, which will be used during finalization and recognition string templateId = response.Payload.Result.TemplateId; // save corrected template data to file File.WriteAllBytes(path + "AsposeTestCorrectedTemplate.omr", response.Payload.Result.ResponseFiles[0].Data); // 2. Run template Finalization RunOmrTask("FinalizeTemplate", "AsposeTestCorrectedTemplate.omr", templateId); // 3. Recognize image OMRResponse recognitionResponse = RunOmrTask("RecognizeImage", "1.jpg", templateId); // get recognition results as string string recognitionResults = Encoding.UTF8.GetString(recognitionResponse.Payload.Result.ResponseFiles[0].Data); Console.WriteLine(recognitionResults); Console.WriteLine("DONE"); Console.ReadLine(); }
/// <summary> /// Helper function that combines template correction and finalization /// </summary> /// <param name="templateImagePath">Path to template image</param> /// <param name="templateDataDir">The folder where Template Data will be stored</param> /// <returns>Template ID</returns> protected string ValidateTemplate(string templateImagePath, string templateDataDir) { OMRResponse correctReponse = this.CorrectTemplate(templateImagePath, templateDataDir); // save correction results and provide them to the template finalization string correctedTemplatePath = string.Empty; if (correctReponse.ErrorCode == 0) { foreach (var responseFile in correctReponse.Payload.Result.ResponseFiles) { Utility.DeserializeFile(responseFile, this.PathToOutput); if (responseFile.Name.ToLower().EndsWith(".omrcr")) { correctedTemplatePath = Utility.DeserializeFile(responseFile, this.PathToOutput); } } } else { throw new Exception($"Correct Template failed with error code {correctReponse.ErrorCode}, '{correctReponse.ErrorText}'"); } string templateId = correctReponse.Payload.Result.TemplateId; OMRResponse finalizeReponse = this.FinalizeTemplate(templateId, correctedTemplatePath); return(templateId); }
/// <summary> /// Runs all omr functions using sample data /// </summary> public void RunDemo() { // Step 1: Upload demo files on cloud and Generate template Console.WriteLine("\t\tUploading demo files..."); this.UploadDemoFiles(this.DataFolder); Console.WriteLine("\t\tGenerate template..."); OMRResponse generateReponse = this.GenerateTemplate(Path.Combine(this.DataFolder, this.TemplateGenerationFileName), this.LogosFolderName); if (generateReponse.ErrorCode == 0) { Utility.DeserializeFiles(generateReponse.Payload.Result.ResponseFiles, this.PathToOutput); } // Step 2: Validate template Console.WriteLine("\t\tValidate template..."); string templateId = this.ValidateTemplate(Path.Combine(this.PathToOutput, this.TemplateImageName), this.PathToOutput); // Step 3: Recognize photos and scans Console.WriteLine("\t\tRecognize image..."); foreach (var userImage in this.templateUserImagesNames) { var recognizeReponse = this.RecognizeImage(templateId, Path.Combine(this.DataFolder, userImage)); if (recognizeReponse.ErrorCode == 0) { var resultFile = Utility.DeserializeFiles(recognizeReponse.Payload.Result.ResponseFiles, this.PathToOutput)[0]; Console.WriteLine($"Result file {resultFile}"); } } }
/// <summary> /// Put files to the cloud and call OMR task /// </summary> /// <param name="actionName">The action name string</param> /// <param name="fileName">The file name</param> /// <param name="fileData">The file data</param> /// <param name="functionParam">The function parameters</param> /// <param name="wasUploaded">Indicates if image was already uploaded on cloud</param> /// <param name="trackFile">Track file so that it can be deleted from cloud</param> /// <param name="additionalParam">The additional (debug) parameters</param> /// <returns>Task response</returns> public static OMRResponse RunOmrTask(string actionName, string fileName, byte[] fileData, string functionParam, bool wasUploaded, bool trackFile, string additionalParam) { if (string.IsNullOrEmpty(AppKey) || string.IsNullOrEmpty(AppSid)) { throw new Exception("Please specify App Key and App SID in Settings->Credentials in order to use OMR functions."); } if (!wasUploaded) { BusyIndicatorManager.UpdateText("Uploading files..."); if (trackFile) { CloudStorageManager.TrackFileUpload(fileName); } StorageApi storageApi = new StorageApi(AppKey, AppSid, Basepath); storageApi.PutCreate(fileName, "", "", fileData); } OmrApi omrApi = new OmrApi(AppKey, AppSid, Basepath); OMRFunctionParam param = new OMRFunctionParam(); param.FunctionParam = functionParam; param.AdditionalParam = additionalParam; BusyIndicatorManager.UpdateText("Processing task..."); OMRResponse response = omrApi.PostRunOmrTask(fileName, actionName, param, null, null); CheckForError(response); return(response); }
/// <summary> /// Performs template finalization /// </summary> /// <param name="templateName">The template file name</param> /// <param name="templateData">The template data</param> /// <param name="templateId">The template id</param> /// <param name="additionalParams">The additional parameters</param> /// <returns>Finalization data containing warnings</returns> public static FinalizationData FinalizeTemplate(string templateName, byte[] templateData, string templateId, string additionalParams) { OMRResponse response = RunOmrTask(OmrFunctions.FinalizeTemplate, templateName, templateData, templateId, false, false, additionalParams); OmrResponseContent responseResult = response.Payload.Result; CheckTaskResult(response.Payload.Result); FinalizationData data = new FinalizationData(); data.Answers = Encoding.UTF8.GetString(responseResult.ResponseFiles[0].Data); data.Warnings = responseResult.Info.Details.TaskMessages.ToArray(); return(data); }
/// <summary> /// Performs template correction /// </summary> /// <param name="imageName">The name of the template image</param> /// <param name="imageData">The template image data</param> /// <param name="templateData">The template data</param> /// <param name="wasUploaded">Indicates if image was already uploaded on cloud</param> /// <param name="additionalParams">The additional parameters</param> /// <returns>Corrected template</returns> public static TemplateViewModel CorrectTemplate(string imageName, byte[] imageData, string templateData, bool wasUploaded, string additionalParams) { OMRResponse response = RunOmrTask("CorrectTemplate", imageName, imageData, templateData, wasUploaded, false, additionalParams); OmrResponseContent responseResult = response.Payload.Result; CheckTaskResult(response.Payload.Result); byte[] correctedTemplateData = responseResult.ResponseFiles .First(x => x.Name.Equals("corrected_template.dat")) .Data; TemplateViewModel templateViewModel = TemplateSerializer.JsonToTemplate(Encoding.UTF8.GetString(correctedTemplateData)); templateViewModel.TemplateId = responseResult.TemplateId; return(templateViewModel); }
/// <summary> /// Performs OMR over single image /// </summary> /// <param name="imageName">Recognized image name</param> /// <param name="imageData">The image data</param> /// <param name="templateId">The template id</param> /// <param name="wasUploaded">Indicates if image was already uploaded on cloud</param> /// <param name="additionalParams">The additional parameters</param> /// <returns>Recognition results</returns> public static string RecognizeImage(string imageName, byte[] imageData, string templateId, bool wasUploaded, string additionalParams) { OMRResponse response = RunOmrTask("RecognizeImage", imageName, imageData, templateId, wasUploaded, true, additionalParams); OmrResponseContent responseResult = response.Payload.Result; if (responseResult.Info.SuccessfulTasksCount < 1 || responseResult.Info.Details.RecognitionStatistics[0].TaskResult != "Pass") { StringBuilder builder = new StringBuilder(); foreach (string message in responseResult.Info.Details.RecognitionStatistics[0].TaskMessages) { builder.AppendLine(message); } throw new Exception(builder.ToString()); } string result = Encoding.UTF8.GetString(response.Payload.Result.ResponseFiles[0].Data); return(result); }
/// <summary> /// Put files to the cloud and call OMR task /// </summary> /// <param name="action">The executed OMR function</param> /// <param name="fileName">The file name</param> /// <param name="fileData">The file data</param> /// <param name="functionParam">The function parameters</param> /// <param name="wasUploaded">Indicates if image was already uploaded on cloud</param> /// <param name="trackFile">Track file so that it can be deleted from cloud</param> /// <param name="additionalParam">The additional (debug) parameters</param> /// <returns>Task response</returns> public static OMRResponse RunOmrTask(OmrFunctions action, string fileName, byte[] fileData, string functionParam, bool wasUploaded, bool trackFile, string additionalParam) { if (string.IsNullOrEmpty(AppKey) || string.IsNullOrEmpty(AppSid)) { throw new Exception("Please specify App Key and App SID in Settings->Credentials in order to use OMR functions."); } if (!wasUploaded) { BusyIndicatorManager.UpdateText("Uploading files..."); if (trackFile) { CloudStorageManager.TrackFileUpload(fileName); } try { string baseHost = new Uri(Basepath).GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped).ToString(); Configuration storageConfiguration = new Configuration(); storageConfiguration.AppKey = AppKey; storageConfiguration.AppSid = AppSid; storageConfiguration.ApiBaseUrl = baseHost; StorageApi storageApi = new StorageApi(storageConfiguration); using (Stream stream = new MemoryStream(fileData)) { storageApi.PutCreate(new PutCreateRequest(fileName, stream)); } } catch (ApiException e) { if (e.ErrorCode == 401) { // handle authentification exception throw new Exception("Aspose Cloud Authentification Failed! Please check App Key and App SID in Settings->Credentials."); } throw; } } OmrApi omrApi = new OmrApi(AppKey, AppSid, Basepath); OMRFunctionParam param = new OMRFunctionParam(); param.FunctionParam = functionParam; param.AdditionalParam = additionalParam; string busyMessage = ""; switch (action) { case OmrFunctions.CorrectTemplate: busyMessage = "Performing Template Correction..."; break; case OmrFunctions.FinalizeTemplate: busyMessage = "Performing Template Finalization..."; break; case OmrFunctions.RecognizeImage: busyMessage = "Performing Recognition..."; break; case OmrFunctions.GenerateTemplate: busyMessage = "Generating Template..."; break; } BusyIndicatorManager.UpdateText(busyMessage); OMRResponse response = omrApi.PostRunOmrTask(fileName, action.ToString(), param, null, null); CheckForError(response); return(response); }