Ejemplo n.º 1
0
        /// <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);
        }
Ejemplo n.º 2
0
        /// <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 (Omr.Cloud.Sdk.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);
        }
Ejemplo n.º 3
0
 /// <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);
     }
 }
Ejemplo n.º 4
0
        /// <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);
        }
Ejemplo n.º 5
0
        /// <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}");
                }
            }
        }
Ejemplo n.º 6
0
        /// <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);
        }
Ejemplo n.º 7
0
        /// <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)
        {
            string packedTemplate = PackTemplate(imageName, templateData);

            OmrResponse response = RunOmrTask(OmrFunctions.CorrectTemplate, imageName, imageData, packedTemplate,
                                              wasUploaded, false, additionalParams);

            OmrResponseContent responseResult = response.Payload.Result;

            CheckTaskResult(response.Payload.Result);

            byte[] correctedTemplateData = responseResult.ResponseFiles
                                           .First(x => x.Name.Contains(".omrcr"))
                                           .Data;

            TemplateViewModel templateViewModel = TemplateSerializer.JsonToTemplate(Encoding.UTF8.GetString(correctedTemplateData));

            templateViewModel.TemplateId = responseResult.TemplateId;

            return(templateViewModel);
        }
Ejemplo n.º 8
0
        /// <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);

            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);

            var         request  = new PostRunOmrTaskRequest(fileName, action.ToString(), param);
            OmrResponse response = omrApi.PostRunOmrTask(request);

            CheckForError(response);
            return(response);
        }