Example #1
0
        private static ProcessingSettings buildSettings(string language, string outputFormat)
        {
            ProcessingSettings settings = new ProcessingSettings();

            settings.SetLanguage(language);
            switch (outputFormat.ToLower())
            {
            case "txt": settings.SetOutputFormat(OutputFormat.txt); break;

            case "rtf": settings.SetOutputFormat(OutputFormat.rtf); break;

            case "docx": settings.SetOutputFormat(OutputFormat.docx); break;

            case "xlsx": settings.SetOutputFormat(OutputFormat.xlsx); break;

            case "pptx": settings.SetOutputFormat(OutputFormat.pptx); break;

            case "pdfsearchable": settings.SetOutputFormat(OutputFormat.pdfSearchable); break;

            case "pdftextandimages": settings.SetOutputFormat(OutputFormat.pdfTextAndImages); break;

            case "xml": settings.SetOutputFormat(OutputFormat.xml); break;

            default:
                throw new ArgumentException("Invalid output format");
            }

            return(settings);
        }
        public static SvmrResults ProcessFileWithSettings(string filename, ProcessingSettings settings)
        {
            // Open file and load JObject from the file
            var content = File.ReadAllText(filename);
            var json    = JObject.Parse(content);

            TestDataJsonFormat_0_1.CheckSignature(json);

            var methodId = TestDataJsonFormat_0_1.GetMethodId(json);

            if (methodId != SvmrMethodId.MethodId)
            {
                throw new NotSupportedException($"Method with id '{methodId}' is not supported!");
            }

            // extract the method-specific json
            var testDataJson = TestDataJsonFormat_0_1.GetTestData(json);

            var hrvRawData = TestDataJsonFormat_0_1.GetTestData <SvmrRawData>(json);

            var dp = new SvmrDataProcessor();

            if (settings != null)
            {
                dp.Set(settings);
            }
            return((SvmrResults)dp.ProcessData(hrvRawData));
        }
        public void TestIdentityAndEquality()
        {
            var temp1 = new ProcessingSettings();

            temp1.Default();

            var temp2 = new ProcessingSettings();

            temp2.Default();

            ProcessingSettings temp3 = (ProcessingSettings)temp2.Clone();


            Assert.IsFalse(temp1.Equals(null));

            Assert.IsTrue(temp1.Equals(temp1));

            Assert.IsTrue(temp2.Equals(temp1));
            Assert.IsTrue(temp1.Equals(temp2));

            Assert.IsNotNull(temp3, "clone must return non-null reference!");
            Assert.AreNotSame(temp3, temp2, "clone must return new instance!");

            Assert.IsFalse(temp3 == temp2, "identy test failed");
            Assert.IsTrue(temp3 != temp2, "identy test failed");

            Assert.IsTrue(temp2.Equals(temp3));
            Assert.IsTrue(temp3.Equals(temp2));

            Assert.IsTrue(temp1.Equals(temp3));
            Assert.IsTrue(temp3.Equals(temp1));
        }
Example #4
0
        public void ProcessFile(string sourceFilePath, string outputFileBase, ProcessingSettings settings)
        {
            Console.WriteLine("Uploading..");
            Task task = restClient.ProcessImage(sourceFilePath, settings);

            task = waitForTask(task);

            if (task.Status == TaskStatus.Completed)
            {
                Console.WriteLine("Processing completed.");
                for (int i = 0; i < settings.OutputFormats.Count; i++)
                {
                    var    outputFormat = settings.OutputFormats[i];
                    string ext          = settings.GetOutputFileExt(outputFormat);
                    restClient.DownloadUrl(task.DownloadUrls[i], outputFileBase + ext);
                }
                Console.WriteLine("Download completed.");
            }
            else if (task.Status == TaskStatus.NotEnoughCredits)
            {
                Console.WriteLine("Not enough credits to process the file. Please add more pages to your application balance.");
            }
            else
            {
                Console.WriteLine("Error while processing the task");
            }
        }
Example #5
0
        private void Test_File_With_And_Without_Peaks_Rejection(string filename_in_unit_test_data_folder)
        {
            string full_data_file_name = FileHelpers.GetPathFromExecutingAssembly(
                Path.Combine("unit_test_data", filename_in_unit_test_data_folder));

            var output = Test_File_With_And_Without_Rejection(full_data_file_name);

            ProcessingSettings ps_ON  = output.rejection_ON_settings;
            ProcessingSettings ps_OFF = output.rejection_OFF_settings;

            HrvResults results_rejection_ON  = output.rejection_ON_results;
            HrvResults results_rejection_OFF = output.rejection_OFF_results;

            Assert.AreEqual(true, ps_ON.RejectUsingMinMaxNNTime);
            Assert.AreEqual(true, ps_ON.RejectUsingRelativeNNDelta);

            Assert.AreEqual(false, ps_OFF.RejectUsingMinMaxNNTime);
            Assert.AreEqual(false, ps_OFF.RejectUsingRelativeNNDelta);

            int count_of_rejected_hr_marks_rejection_OFF = GetCountOfRejectedHrMarks(results_rejection_OFF);
            int count_of_rejected_hr_marks_rejection_ON  = GetCountOfRejectedHrMarks(results_rejection_ON);

            log.InfoFormat("Finished testing of processing results from file '{0}' with rejection ON and OFF.", filename_in_unit_test_data_folder);
            log.InfoFormat("  Rejection ON:   {0} pulse waves rejected.", count_of_rejected_hr_marks_rejection_ON);
            log.InfoFormat("  Rejection OFF:  {0} pulse waves rejected.", count_of_rejected_hr_marks_rejection_OFF);

            Assert.IsTrue(
                count_of_rejected_hr_marks_rejection_ON > count_of_rejected_hr_marks_rejection_OFF,
                "Results obtained with rejection contain less rejected heart contraction marks than results obtained with no rejection."
                );

            log.Info("Checks finished OK.");
            log.Info("----------------------------------------------------------------------------------------------------");
        }
Example #6
0
        ProcessingSettings GetProcessingSettings()
        {
            ProcessingSettings result = new ProcessingSettings();

            result.SetLanguage(getLanguages());
            result.SetOutputFormat(getOutputFormat());
            return(result);
        }
Example #7
0
        ProcessingSettings GetProcessingSettings()
        {
            ProcessingSettings result = new ProcessingSettings();

            result.Language     = getLanguage();
            result.OutputFormat = getOutputFormat();
            return(result);
        }
Example #8
0
        private HrvResults ProcessFile(string filename, bool bPerformRejection)
        {
            var ps = new ProcessingSettings {
                RejectUsingMinMaxNNTime    = bPerformRejection,
                RejectUsingRelativeNNDelta = bPerformRejection
            };

            return(HrvFileProcessingHelper.ProcessFileWithSettings(filename, ps));
        }
        public void Test_Serialization_And_Deserialization()
        {
            var procSettings = new ProcessingSettings();
            // serialize
            var json       = JObject.FromObject(procSettings);
            var jsonString = json.ToString();

            Console.WriteLine(jsonString);
            // deserialize
            var deserialized = JObject.Parse(jsonString);
        }
Example #10
0
        private static ProcessingSettings buildSettings(string language,
                                                        string outputFormat, string profile)
        {
            ProcessingSettings settings = new ProcessingSettings();

            settings.SetLanguage(language);
            switch (outputFormat.ToLower())
            {
            case "txt": settings.SetOutputFormat(OutputFormat.txt); break;

            case "rtf": settings.SetOutputFormat(OutputFormat.rtf); break;

            case "docx": settings.SetOutputFormat(OutputFormat.docx); break;

            case "xlsx": settings.SetOutputFormat(OutputFormat.xlsx); break;

            case "pptx": settings.SetOutputFormat(OutputFormat.pptx); break;

            case "pdfsearchable": settings.SetOutputFormat(OutputFormat.pdfSearchable); break;

            case "pdftextandimages": settings.SetOutputFormat(OutputFormat.pdfTextAndImages); break;

            case "xml": settings.SetOutputFormat(OutputFormat.xml); break;

            default:
                throw new ArgumentException("Invalid output format");
            }
            if (profile != null)
            {
                switch (profile.ToLower())
                {
                case "documentconversion":
                    settings.Profile = Profile.documentConversion;
                    break;

                case "documentarchiving":
                    settings.Profile = Profile.documentArchiving;
                    break;

                case "textextraction":
                    settings.Profile = Profile.textExtraction;
                    break;

                default:
                    throw new ArgumentException("Invalid profile");
                }
            }

            return(settings);
        }
Example #11
0
        public void ProcessDocument(IEnumerable <string> _sourceFiles, string outputFileBase,
                                    ProcessingSettings settings)
        {
            string[] sourceFiles = _sourceFiles.ToArray();
            Console.WriteLine(String.Format("Recognizing {0} images as a document",
                                            sourceFiles.Length));

            Task task = null;

            for (int fileIndex = 0; fileIndex < sourceFiles.Length; fileIndex++)
            {
                string filePath = sourceFiles[fileIndex];
                Console.WriteLine("{0}: uploading {1}", fileIndex + 1, Path.GetFileName(filePath));

                task = restClient.UploadAndAddFileToTask(filePath, task == null ? null : task.Id);
            }

            // Start task
            Console.WriteLine("Starting task..");
            restClient.StartProcessingTask(task.Id, settings);

            while (true)
            {
                task = restClient.GetTaskStatus(task.Id);
                if (!Task.IsTaskActive(task.Status))
                {
                    break;
                }

                Console.WriteLine(String.Format("Task status: {0}", task.Status));
                System.Threading.Thread.Sleep(1000);
            }

            if (task.Status == TaskStatus.Completed)
            {
                Console.WriteLine("Processing completed.");
                for (int i = 0; i < settings.OutputFormats.Count; i++)
                {
                    var    outputFormat = settings.OutputFormats[i];
                    string ext          = settings.GetOutputFileExt(outputFormat);
                    restClient.DownloadUrl(task.DownloadUrls[i], outputFileBase + ext);
                }
                Console.WriteLine("Download completed.");
            }
            else
            {
                Console.WriteLine("Error while processing the task");
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="testDataFileName"></param>
        /// <param name="stateMatrixRow"></param>
        /// <param name="stateMatrixCol"></param>
        /// <param name="timeout">
        /// Если больше нуля то это время в миллисекундах, в течение которого форма отображается на экране.
        /// Если меньше или равен нулю -- форма отображается на экране, пока не будет закрыта (оператором).
        /// </param>
        void Test_Processing_Internal(string testDataFileName, int stateMatrixRow, int stateMatrixCol, int timeout)
        {
            var currentlyOpenDataProcessor = new SvmrDataProcessor();

            string full_filename = FileHelpers.GetPathFromExecutingAssembly(
                Path.Combine("unit_test_data", testDataFileName));

            var settings = new ProcessingSettings();

            SvmrFileProcessingHelper.ProcessFileWithSettings(full_filename, settings);

            if ((-1 != stateMatrixRow) && (-1 != stateMatrixCol))
            {
                currentlyOpenDataProcessor.UTest_SetStateMatrixState(stateMatrixRow, stateMatrixCol);
            }
        }
Example #13
0
        /// <summary>
        /// Process directory or file with given path
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="outputFilePath">Path to directory to store results
        /// Will be created if it doesn't exist
        /// </param>
        /// <param name="processAsDocument">If true, all images are processed as a single document</param>
        public void ProcessPath(string sourcePath, string outputPath, ProcessingSettings settings,
                                bool processAsDocument)
        {
            List <string> sourceFiles = new List <string>();

            if (Directory.Exists(sourcePath))
            {
                sourceFiles.AddRange(Directory.GetFiles(sourcePath));
                sourceFiles.Sort();
            }
            else if (File.Exists(sourcePath))
            {
                sourceFiles.Add(sourcePath);
            }
            else
            {
                Console.WriteLine("Invalid source path");
                return;
            }

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            if (!processAsDocument || sourceFiles.Count == 1)
            {
                foreach (string filePath in sourceFiles)
                {
                    string outputFileName = Path.GetFileNameWithoutExtension(filePath);
                    string ext            = settings.OutputFileExt;
                    string outputFilePath = Path.Combine(outputPath, outputFileName + ext);

                    Console.WriteLine("Processing " + Path.GetFileName(filePath));

                    ProcessFile(filePath, outputFilePath, settings);
                }
            }
            else
            {
                string outputFileName = "document";
                string ext            = settings.OutputFileExt;
                string outputFilePath = Path.Combine(outputPath, outputFileName + ext);

                ProcessDocument(sourceFiles, outputFilePath, settings);
            }
        }
Example #14
0
        private HrvResults ProcessFile(string filename, bool bPerformRejection, bool RejectLowQualitySignalAreas)
        {
            filename = PskOnline.Components.Util.FileHelpers.GetPathFromExecutingAssembly(
                Path.Combine("unit_test_data", Path.Combine("LowQualityStart", filename)));

            var ps = new ProcessingSettings
            {
                RejectUsingMinMaxNNTime    = bPerformRejection,
                RejectUsingRelativeNNDelta = bPerformRejection,
                // special setting for RusHydro
                // will remove initial 12 seconds of recorded signal
                // because it is mostly of some poor quality
                RejectLowQualitySignalAreas = RejectLowQualitySignalAreas
            };

            return(HrvFileProcessingHelper.ProcessFileWithSettings(filename, ps));
        }
        public OcrSdkTask StartProcessingTask(TaskId taskId, ProcessingSettings settings)
        {
            string url = String.Format("{0}/processDocument?taskId={1}&{2}", ServerUrl,
                                       Uri.EscapeDataString(taskId.ToString()),
                                       settings.AsUrlParams);

            if (!String.IsNullOrEmpty(settings.Description))
            {
                url = url + "&description=" + Uri.EscapeDataString(settings.Description);
            }

            // Build get request
            WebRequest request    = createGetRequest(url);
            XDocument  response   = performRequest(request);
            OcrSdkTask serverTask = ServerXml.GetTaskStatus(response);

            return(serverTask);
        }
        /// <summary>
        /// Upload a file to service synchronously and start processing
        /// </summary>
        /// <param name="filePath">Path to an image to process</param>
        /// <param name="settings">Language and output format</param>
        /// <returns>Id of the task. Check task status to see if you have enough units to process the task</returns>
        /// <exception cref="ProcessingErrorException">thrown when something goes wrong</exception>
        public OcrSdkTask ProcessImage(string filePath, ProcessingSettings settings)
        {
            string url = String.Format("{0}/processImage?{1}", ServerUrl, settings.AsUrlParams);

            if (!String.IsNullOrEmpty(settings.Description))
            {
                url = url + "&description=" + Uri.EscapeDataString(settings.Description);
            }

            // Build post request
            WebRequest request = createPostRequest(url);

            writeFileToRequest(filePath, request);

            XDocument  response = performRequest(request);
            OcrSdkTask task     = ServerXml.GetTaskStatus(response);

            return(task);
        }
Example #17
0
        void addFileTask(string filePath)
        {
            // Initialize output directory
            string outputDir = getOutputDir();

            // Different behavior for full-text recognition and business card recognition

            if (formatVCard.IsChecked == false)
            {
                ProcessingSettings settings = GetProcessingSettings();

                UserTask task = new UserTask(filePath);
                task.TaskStatus     = "Uploading";
                task.OutputFilePath = System.IO.Path.Combine(
                    outputDir,
                    System.IO.Path.GetFileNameWithoutExtension(filePath) + settings.OutputFileExt);

                _userTasks.Add(task);

                settings.Description = String.Format("{0} -> {1}",
                                                     System.IO.Path.GetFileName(filePath),
                                                     settings.OutputFileExt);

                restClientAsync.UploadFileAsync(filePath, settings, task);
            }
            else
            {
                // Business-card recognition
                BusCardProcessingSettings settings = GetBusCardProcessingSettings();

                UserTask task = new UserTask(filePath);
                task.TaskStatus     = "Uploading";
                task.OutputFilePath = System.IO.Path.Combine(
                    outputDir,
                    System.IO.Path.GetFileNameWithoutExtension(filePath) + ".vcf");

                _userTasks.Add(task);

                restClientAsync.ProcessBusinessCardAsync(filePath, settings, task);
            }
        }
Example #18
0
        public void ProcessFile(string sourceFilePath, string outputFilePath, ProcessingSettings settings)
        {
            Console.WriteLine("Uploading..");
            Task task = restClient.ProcessImage(sourceFilePath, settings);

            // For field-level

            /*
             * var flSettings = new TextFieldProcessingSettings();
             * TaskId taskId = restClient.ProcessTextField(sourceFilePath, flSettings);
             */

            TaskId taskId = task.Id;

            while (true)
            {
                task = restClient.GetTaskStatus(taskId);
                if (!Task.IsTaskActive(task.Status))
                {
                    break;
                }

                Console.WriteLine(String.Format("Task status: {0}", task.Status));
                System.Threading.Thread.Sleep(1000);
            }

            if (task.Status == TaskStatus.Completed)
            {
                Console.WriteLine("Processing completed.");
                restClient.DownloadResult(task, outputFilePath);
                Console.WriteLine("Download completed.");
            }
            else if (task.Status == TaskStatus.NotEnoughCredits)
            {
                Console.WriteLine("Not enough credits to process the file. Please add more pages to your application balance.");
            }
            else
            {
                Console.WriteLine("Error while processing the task");
            }
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            Stream imageStream = AppData.Instance.Image;

            if (imageStream == null)
            {
                return;
            }

            string localPath = "image.jpg";

            saveImageToFile(imageStream, localPath);

            ProcessingSettings settings = new ProcessingSettings();

            settings.SetLanguage("English,Russian");
            settings.OutputFormat = OutputFormat.txt;

            displayMessage("Uploading..");
            abbyyClient.ProcessImageAsync(localPath, settings, settings);
        }
Example #20
0
        public void ProcessFile(string sourceFilePath, string outputFileBase, ProcessingSettings settings)
        {
            Console.WriteLine("Uploading..");
            Task task = restClient.ProcessImage(sourceFilePath, settings);

            TaskId taskId = task.Id;

            while (Task.IsTaskActive(task.Status))
            {
                task = restClient.GetTaskStatus(taskId);
                if (!Task.IsTaskActive(task.Status))
                {
                    break;
                }

                Console.WriteLine(String.Format("Task status: {0}", task.Status));
                System.Threading.Thread.Sleep(1000);
            }

            if (task.Status == TaskStatus.Completed)
            {
                Console.WriteLine("Processing completed.");
                for (int i = 0; i < settings.OutputFormats.Count; i++)
                {
                    var    outputFormat = settings.OutputFormats[i];
                    string ext          = settings.GetOutputFileExt(outputFormat);
                    restClient.DownloadUrl(task.DownloadUrls[i], outputFileBase + ext);
                }
                Console.WriteLine("Download completed.");
            }
            else if (task.Status == TaskStatus.NotEnoughCredits)
            {
                Console.WriteLine("Not enough credits to process the file. Please add more pages to your application balance.");
            }
            else
            {
                Console.WriteLine("Error while processing the task");
            }
        }
        public void TestIdentityAndEquality()
        {
            var temp1 = new ProcessingSettings();

            temp1.Default();

            var temp2 = new ProcessingSettings();

            temp2.Default();

            temp2.RejectUsingMinMaxNNTime    = temp1.RejectUsingMinMaxNNTime = true;
            temp2.RejectUsingRelativeNNDelta = temp1.RejectUsingRelativeNNDelta = false;

            temp2.MaxIntervalDeltaRelative = temp1.MaxIntervalDeltaRelative = 20.0f;
            temp2.MaxIntervalMilliseconds  = temp1.MaxIntervalMilliseconds = 10.0f;
            temp2.MinIntervalMilliseconds  = temp1.MinIntervalMilliseconds = 15.0f;

            ProcessingSettings temp3 = (ProcessingSettings)temp2.Clone();

            Assert.IsFalse(temp1.Equals(null));

            Assert.IsTrue(temp1.Equals(temp1));

            Assert.IsTrue(temp2.Equals(temp1));
            Assert.IsTrue(temp1.Equals(temp2));

            Assert.IsNotNull(temp3, "clone must return non-null reference!");
            Assert.AreNotSame(temp3, temp2, "clone must return new instance!");

            Assert.IsFalse(temp3 == temp2, "identy test failed");
            Assert.IsTrue(temp3 != temp2, "identy test failed");

            Assert.IsTrue(temp2.Equals(temp3));
            Assert.IsTrue(temp3.Equals(temp2));

            Assert.IsTrue(temp1.Equals(temp3));
            Assert.IsTrue(temp3.Equals(temp1));
        }
Example #22
0
        private void Fire(string filePath)
        {
            txtEditor.Text = "Start";

            System.Drawing.Bitmap bitmap = GetBitMap(filePath);

            string tempFilePath = System.IO.Path.GetTempFileName();

            bitmap.Save(tempFilePath, System.Drawing.Imaging.ImageFormat.Tiff);

            string outputDir = getOutputDir();

            UserTask task = new UserTask(tempFilePath);

            task.TaskStatus       = "Uploading";
            task.SourceIsTempFile = true;
            task.IsFieldLevel     = true;
            task.SourceImage      = bitmap;

            //TextFieldProcessingSettings settings = new TextFieldProcessingSettings();
            //restClientAsync.ProcessTextFieldAsync(tempFilePath, settings, task);


            ///
            ProcessingSettings settings = new ProcessingSettings();

            task.OutputFilePath = System.IO.Path.Combine(
                outputDir,
                System.IO.Path.GetFileNameWithoutExtension(filePath) + settings.GetOutputFileExt(settings.OutputFormats[0]));

            settings.Description = String.Format("{0} -> {1}",
                                                 System.IO.Path.GetFileName(filePath),
                                                 settings.GetOutputFileExt(settings.OutputFormats[0]));

            restClientAsync.ProcessImageAsync(filePath, settings, task);
        }
Example #23
0
        void addFileTask(string filePath)
        {
            // Initialize output directory
            string outputDir = getOutputDir();

            // Different behavior for full-text recognition and business card recognition

            if (modeGeneral.IsChecked == true)
            {
                ProcessingSettings settings = GetProcessingSettings();

                UserTask task = new UserTask(filePath);
                task.TaskStatus     = "Uploading";
                task.OutputFilePath = System.IO.Path.Combine(
                    outputDir,
                    System.IO.Path.GetFileNameWithoutExtension(filePath) + settings.GetOutputFileExt(settings.OutputFormats[0]));

                _userTasks.Add(task);

                settings.Description = String.Format("{0} -> {1}",
                                                     Path.GetFileName(filePath),
                                                     settings.GetOutputFileExt(settings.OutputFormats[0]));

                restClientAsync.ProcessImageAsync(filePath, settings, task);
            }
            else if (modeBcr.IsChecked == true)
            {
                // Business-card recognition
                BusCardProcessingSettings settings = GetBusCardProcessingSettings();
                string ext;
                if (formatVCard.IsChecked == true)
                {
                    settings.OutputFormat = BusCardProcessingSettings.OutputFormatEnum.vCard;
                    ext = ".vcf";
                }
                else
                {
                    settings.OutputFormat = BusCardProcessingSettings.OutputFormatEnum.xml;
                    ext = ".xml";
                }


                UserTask task = new UserTask(filePath);
                task.TaskStatus     = "Uploading";
                task.OutputFilePath = System.IO.Path.Combine(
                    outputDir,
                    System.IO.Path.GetFileNameWithoutExtension(filePath) + ext);

                _userTasks.Add(task);

                restClientAsync.ProcessBusinessCardAsync(filePath, settings, task);
            }
            else
            {
                // Machine-readable zone recognition

                UserTask task = new UserTask(filePath);
                task.TaskStatus     = "Uploading";
                task.OutputFilePath = System.IO.Path.Combine(
                    outputDir,
                    System.IO.Path.GetFileNameWithoutExtension(filePath) + ".xml");

                _userTasks.Add(task);
                restClientAsync.ProcessMrzAsync(filePath, task);
            }
        }
Example #24
0
        /// <summary>
        /// Process directory or file with given path
        /// </summary>
        /// <param name="sourcePath">File or directory to be processed</param>
        /// <param name="outputPath">Path to directory to store results
        /// Will be created if it doesn't exist
        /// </param>
        /// <param name="processAsDocument">If true, all images are processed as a single document</param>
        public void ProcessPath(string sourcePath, string outputPath,
                                IProcessingSettings settings,
                                ProcessingModeEnum processingMode)
        {
            List <string> sourceFiles = new List <string>();

            if (Directory.Exists(sourcePath))
            {
                sourceFiles.AddRange(Directory.GetFiles(sourcePath));
                sourceFiles.Sort();
            }
            else if (File.Exists(sourcePath))
            {
                sourceFiles.Add(sourcePath);
            }
            else
            {
                Console.WriteLine("Invalid source path");
                return;
            }

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            if (processingMode == ProcessingModeEnum.SinglePage ||
                (processingMode == ProcessingModeEnum.MultiPage && sourceFiles.Count == 1))
            {
                ProcessingSettings fullTextSettings = settings as ProcessingSettings;
                foreach (string filePath in sourceFiles)
                {
                    string outputFileName = Path.GetFileNameWithoutExtension(filePath);
                    string outputFilePath = Path.Combine(outputPath, outputFileName);

                    Console.WriteLine("Processing " + Path.GetFileName(filePath));

                    ProcessFile(filePath, outputFilePath, fullTextSettings);
                }
            }
            else if (processingMode == ProcessingModeEnum.MultiPage)
            {
                ProcessingSettings fullTextSettings = settings as ProcessingSettings;
                string             outputFileName   = "document";
                string             outputFilePath   = Path.Combine(outputPath, outputFileName);

                ProcessDocument(sourceFiles, outputFilePath, fullTextSettings);
            }
            else if (processingMode == ProcessingModeEnum.ProcessTextField)
            {
                TextFieldProcessingSettings fieldSettings = settings as TextFieldProcessingSettings;
                foreach (string filePath in sourceFiles)
                {
                    string outputFileName = Path.GetFileNameWithoutExtension(filePath);
                    string ext            = ".xml";
                    string outputFilePath = Path.Combine(outputPath, outputFileName + ext);

                    Console.WriteLine("Processing " + Path.GetFileName(filePath));

                    ProcessTextField(filePath, outputFilePath, fieldSettings);
                }
            }
            else if (processingMode == ProcessingModeEnum.ProcessMrz)
            {
                foreach (string filePath in sourceFiles)
                {
                    string outputFileName = Path.GetFileNameWithoutExtension(filePath);
                    string ext            = ".xml";
                    string outputFilePath = Path.Combine(outputPath, outputFileName + ext);

                    Console.WriteLine("Processing " + Path.GetFileName(filePath));

                    ProcessMrz(filePath, outputFilePath);
                }
            }
        }
Example #25
0
        static void Main(string[] args)
        {
            bool processAsDocument = false;
            bool showHelp          = false;

            string outFormat = "pdfSearchable";
            string language  = "english";

            var p = new OptionSet()
            {
                { "asDocument", "Process given files as single multi-page document",
                  v => processAsDocument = true },
                { "out=", "Create output in specified {format}: txt, rtf, docx, xlsx, pptx, pdfSearchable, pdfTextAndImages, xml",
                  (string v) => outFormat = v },
                { "lang=", "Recognize with specified {language}",
                  (string v) => language = v },
                { "h|help", "Show this message and exit",
                  v => showHelp = v != null }
            };

            List <string> additionalArgs = null;

            try
            {
                additionalArgs = p.Parse(args);
            }
            catch (OptionException)
            {
                Console.WriteLine("Invalid arguments.");
                showHelp = true;
            }

            if (additionalArgs != null && additionalArgs.Count != 2)
            {
                showHelp = true;
            }

            ProcessingSettings settings = buildSettings(language, outFormat);

            if (showHelp)
            {
                Console.WriteLine("Process images with ABBYY Cloud OCR SDK");
                Console.WriteLine("Usage:");
                Console.WriteLine("ConsoleTest.exe [options] <input dir|file> <output dir>");
                Console.WriteLine("Options:");
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            string sourcePath = additionalArgs[0];
            string targetPath = additionalArgs[1];

            try
            {
                Test tester = new Test();
                tester.ProcessPath(sourcePath, targetPath, settings, processAsDocument);
            }
            catch (Abbyy.CloudOcrSdk.ProcessingErrorException e)
            {
                Console.WriteLine("Cannot process.");
                Console.WriteLine(e.ToString());
            }
        }
Example #26
0
        static void Main(string[] args)
        {
            try
            {
                Test tester = new Test();

                ProcessingModeEnum processingMode = ProcessingModeEnum.SinglePage;

                string outFormat     = null;
                string profile       = null;
                string language      = "english";
                string customOptions = "";

                var p = new OptionSet()
                {
                    { "asDocument", v => processingMode = ProcessingModeEnum.MultiPage },
                    { "asTextField", v => processingMode = ProcessingModeEnum.ProcessTextField },
                    { "asFields", v => processingMode = ProcessingModeEnum.ProcessFields },
                    { "asMRZ", var => processingMode = ProcessingModeEnum.ProcessMrz },
                    { "captureData", v => processingMode = ProcessingModeEnum.CaptureData },
                    { "out=", (string v) => outFormat = v },
                    { "profile=", (string v) => profile = v },
                    { "lang=", (string v) => language = v },
                    { "options=", (string v) => customOptions = v }
                };

                List <string> additionalArgs = null;
                try
                {
                    additionalArgs = p.Parse(args);
                }
                catch (OptionException)
                {
                    Console.WriteLine("Invalid arguments.");
                    displayHelp();
                    return;
                }

                string sourcePath   = null;
                string xmlPath      = null;
                string targetPath   = Directory.GetCurrentDirectory();
                string templateName = null;

                switch (processingMode)
                {
                case ProcessingModeEnum.SinglePage:
                case ProcessingModeEnum.MultiPage:
                case ProcessingModeEnum.ProcessTextField:
                case ProcessingModeEnum.ProcessMrz:
                    if (additionalArgs.Count != 2)
                    {
                        displayHelp();
                        return;
                    }

                    sourcePath = additionalArgs[0];
                    targetPath = additionalArgs[1];
                    break;

                case ProcessingModeEnum.ProcessFields:
                    if (additionalArgs.Count != 3)
                    {
                        displayHelp();
                        return;
                    }

                    sourcePath = additionalArgs[0];
                    xmlPath    = additionalArgs[1];
                    targetPath = additionalArgs[2];
                    break;

                case ProcessingModeEnum.CaptureData:
                    if (additionalArgs.Count != 3)
                    {
                        displayHelp();
                        return;
                    }

                    sourcePath   = additionalArgs[0];
                    templateName = additionalArgs[1];
                    targetPath   = additionalArgs[2];
                    break;
                }

                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }

                if (String.IsNullOrEmpty(outFormat))
                {
                    if (processingMode == ProcessingModeEnum.ProcessFields ||
                        processingMode == ProcessingModeEnum.ProcessTextField ||
                        processingMode == ProcessingModeEnum.ProcessMrz ||
                        processingMode == ProcessingModeEnum.CaptureData)
                    {
                        outFormat = "xml";
                    }
                    else
                    {
                        outFormat = "txt";
                    }
                }

                if (outFormat != "xml" &&
                    (processingMode == ProcessingModeEnum.ProcessFields ||
                     processingMode == ProcessingModeEnum.ProcessTextField) ||
                    processingMode == ProcessingModeEnum.CaptureData)
                {
                    Console.WriteLine("Only xml is supported as output format for field-level recognition.");
                    outFormat = "xml";
                }

                if (processingMode == ProcessingModeEnum.SinglePage || processingMode == ProcessingModeEnum.MultiPage)
                {
                    ProcessingSettings settings = buildSettings(language, outFormat, profile);
                    settings.CustomOptions = customOptions;
                    tester.ProcessPath(sourcePath, targetPath, settings, processingMode);
                }
                else if (processingMode == ProcessingModeEnum.ProcessTextField)
                {
                    TextFieldProcessingSettings settings = buildTextFieldSettings(language, customOptions);
                    tester.ProcessPath(sourcePath, targetPath, settings, processingMode);
                }
                else if (processingMode == ProcessingModeEnum.ProcessFields)
                {
                    string outputFilePath = Path.Combine(targetPath, Path.GetFileName(sourcePath) + ".xml");
                    tester.ProcessFields(sourcePath, xmlPath, outputFilePath);
                }
                else if (processingMode == ProcessingModeEnum.ProcessMrz)
                {
                    tester.ProcessPath(sourcePath, targetPath, null, processingMode);
                }
                else if (processingMode == ProcessingModeEnum.CaptureData)
                {
                    string outputFilePath = Path.Combine(targetPath, Path.GetFileName(sourcePath) + ".xml");
                    tester.CaptureData(sourcePath, templateName, outputFilePath);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: ");
                Console.WriteLine(e.Message);
            }
        }
Example #27
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (ValidationSettings == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "ValidationSettings");
     }
     if (FramingSettings == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "FramingSettings");
     }
     if (EnvelopeSettings == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "EnvelopeSettings");
     }
     if (AcknowledgementSettings == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "AcknowledgementSettings");
     }
     if (MessageFilter == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "MessageFilter");
     }
     if (SecuritySettings == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "SecuritySettings");
     }
     if (ProcessingSettings == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "ProcessingSettings");
     }
     if (SchemaReferences == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "SchemaReferences");
     }
     if (ValidationSettings != null)
     {
         ValidationSettings.Validate();
     }
     if (FramingSettings != null)
     {
         FramingSettings.Validate();
     }
     if (EnvelopeSettings != null)
     {
         EnvelopeSettings.Validate();
     }
     if (AcknowledgementSettings != null)
     {
         AcknowledgementSettings.Validate();
     }
     if (MessageFilter != null)
     {
         MessageFilter.Validate();
     }
     if (SecuritySettings != null)
     {
         SecuritySettings.Validate();
     }
     if (ProcessingSettings != null)
     {
         ProcessingSettings.Validate();
     }
     if (EnvelopeOverrides != null)
     {
         foreach (var element in EnvelopeOverrides)
         {
             if (element != null)
             {
                 element.Validate();
             }
         }
     }
     if (ValidationOverrides != null)
     {
         foreach (var element1 in ValidationOverrides)
         {
             if (element1 != null)
             {
                 element1.Validate();
             }
         }
     }
     if (MessageFilterList != null)
     {
         foreach (var element2 in MessageFilterList)
         {
             if (element2 != null)
             {
                 element2.Validate();
             }
         }
     }
     if (SchemaReferences != null)
     {
         foreach (var element3 in SchemaReferences)
         {
             if (element3 != null)
             {
                 element3.Validate();
             }
         }
     }
     if (X12DelimiterOverrides != null)
     {
         foreach (var element4 in X12DelimiterOverrides)
         {
             if (element4 != null)
             {
                 element4.Validate();
             }
         }
     }
 }