예제 #1
0
        public async static void Run([BlobTrigger("kyccontainer/{name}", Connection = "AzureWebJobsStorage")] Stream blob, string name, TraceWriter log)
        {
            try
            {
                log.Info($"Azure blob function triggered for the passport image: {name}");

                // Resolve assembly
                FunctionsAssemblyResolver.StaticInstance();

                // Using AbbyyCloudOCR to extract Passport details
                RestServiceClient restClient = new RestServiceClient();

                // Convert stream into image stream
                MemoryStream streamOut = ImageStream.GetImageStream(blob);
                OcrSdkTask   task      = restClient.ProcessMrz(streamOut);

                // Get Passport details
                AbbyyCloudOCRResponse abbyyCloudOCRResponse = restClient.WaitAndGetAbbyyCloudOCRResponse(task);

                // Using Trulioo API for Passport verification
                Transaction transaction = await Verify.VerifyPassport(abbyyCloudOCRResponse, streamOut);

                // Save the AbbyyCloudOCR response and transaction response into the database
                DataLayer.KYCDbContext.Save(abbyyCloudOCRResponse, transaction);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex, "KYC blob function");
            }
        }
예제 #2
0
        public void ProcessFile(string sourceFilePath, string outputFileBase, ProcessingSettings settings)
        {
            Console.WriteLine("Uploading..");
            OcrSdkTask 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");
            }
        }
예제 #3
0
        public void ProcessTextField(string sourceFilePath, string outputFilePath, TextFieldProcessingSettings settings)
        {
            Console.WriteLine("Uploading..");
            OcrSdkTask task = restClient.ProcessTextField(sourceFilePath, settings);

            waitAndDownload(task, outputFilePath);
        }
예제 #4
0
        public void ProcessMrz(string sourceFilePath, string outputFilePath)
        {
            Console.WriteLine("Uploading");
            OcrSdkTask task = restClient.ProcessMrz(sourceFilePath);

            Console.WriteLine("Processing..");

            waitAndDownload(task, outputFilePath);
        }
예제 #5
0
        public void ProcessFields(string sourceFilePath, string xmlSettingsPath, string outputFilePath)
        {
            Console.WriteLine("Uploading");
            OcrSdkTask task = restClient.UploadAndAddFileToTask(sourceFilePath, null);

            Console.WriteLine("Processing..");
            task = restClient.ProcessFields(task, xmlSettingsPath);

            waitAndDownload(task, outputFilePath);
        }
예제 #6
0
 internal DocumentRequest WaitAndDownload(OcrSdkTask task, DocumentRequest request)
 {
     task = WaitForTask(task);
     if (task.Status == TaskStatus.Completed)
     {
         _restClient.DownloadResult(task, request.Document.TargetFilePath);
         request.IsSuccessed = true;
     }
     return(request);
 }
예제 #7
0
 internal OcrSdkTask WaitForTask(OcrSdkTask task)
 {
     _logger.LogTrace(string.Format("Task status: {0}", task.Status));
     while (task.IsTaskActive())
     {
         System.Threading.Thread.Sleep(5000);
         task = _restClient.GetTaskStatus(task.Id);
         _logger.LogTrace(string.Format("Task status: {0}", task.Status));
     }
     return(task);
 }
예제 #8
0
        /// <summary>
        /// Get task data from xml node "task"
        /// </summary>
        private static OcrSdkTask getTaskInfo(XElement xTask)
        {
            TaskId id = new TaskId(xTask.Attribute("id").Value);
            TaskStatus status = statusFromString(xTask.Attribute("status").Value);

            OcrSdkTask task = new OcrSdkTask();
            task.Id = id;
            task.Status = status;

            XAttribute xRegistrationTime = xTask.Attribute("registrationTime");
            if (xRegistrationTime != null)
            {
                DateTime time;
                if (DateTime.TryParse(xRegistrationTime.Value, out time))
                    task.RegistrationTime = time;
            }

            XAttribute xStatusChangeTime = xTask.Attribute("statusChangeTime");
            if (xStatusChangeTime != null)
            {
                DateTime time;
                if (DateTime.TryParse(xStatusChangeTime.Value, out time))
                    task.StatusChangeTime = time;
            }

            XAttribute xPagesCount = xTask.Attribute("filesCount");
            if (xPagesCount != null)
            {
                int pagesCount;
                if (Int32.TryParse(xPagesCount.Value, out pagesCount))
                    task.PagesCount = pagesCount;
            }

            XAttribute xCredits = xTask.Attribute("credits");
            if (xCredits != null)
            {
                int credits;
                if( Int32.TryParse( xCredits.Value, out credits ))
                    task.Credits = credits;
            }

            XAttribute xDescription = xTask.Attribute("description");
            if (xDescription != null)
                task.Description = xDescription.Value;

            XAttribute xResultUrl = xTask.Attribute("resultUrl");
            if (xResultUrl != null)
            {
                task.DownloadUrl = xResultUrl.Value;
            }

            return task;
        }
예제 #9
0
        public UserTask(OcrSdkTask task)
        {
            SourceFilePath   = null;
            TaskId           = task.Id.ToString();
            TaskStatus       = task.Status.ToString();
            PagesCount       = task.PagesCount;
            Description      = task.Description;
            RegistrationTime = task.RegistrationTime;
            StatusChangeTime = task.StatusChangeTime;

            SourceIsTempFile = false;
        }
예제 #10
0
 internal DocumentRequest ProcessMrz(DocumentRequest request)
 {
     try
     {
         OcrSdkTask task = _restClient.ProcessMrz(request.Document.SourceFilePath);
         WaitAndDownload(task, request);
     }
     catch (Exception e)
     {
         Log($"KO :Exception: {e.Message}", true);
         request.IsSuccessed = false;
         throw;
     }
     return(request);
 }
예제 #11
0
        /// <summary>
        /// Wait until task finishes and download result
        /// </summary>
        private void waitAndDownload(OcrSdkTask task, string outputFilePath)
        {
            task = waitForTask(task);

            if (task.Status == TaskStatus.Completed)
            {
                Console.WriteLine("Processing completed.");
                restClient.DownloadResult(task, outputFilePath);
                Console.WriteLine("Download completed.");
            }
            else
            {
                Console.WriteLine("Error while processing the task");
            }
        }
예제 #12
0
 private OcrSdkTask waitForTask(OcrSdkTask task)
 {
     Console.WriteLine(String.Format("Task status: {0}", task.Status));
     while (task.IsTaskActive())
     {
         // Note: it's recommended that your application waits
         // at least 2 seconds before making the first getTaskStatus request
         // and also between such requests for the same task.
         // Making requests more often will not improve your application performance.
         // Note: if your application queues several files and waits for them
         // it's recommended that you use listFinishedTasks instead (which is described
         // at https://ocrsdk.com/documentation/apireference/listFinishedTasks/).
         System.Threading.Thread.Sleep(5000);
         task = restClient.GetTaskStatus(task.Id);
         Console.WriteLine(String.Format("Task status: {0}", task.Status));
     }
     return(task);
 }
예제 #13
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));

            OcrSdkTask 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..");
            task = restClient.StartProcessingTask(task.Id, 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
            {
                Console.WriteLine("Error while processing the task");
            }
        }
예제 #14
0
        private void ProcessingCompleted(object sender, TaskEventArgs e)
        {
            if (e.Error != null)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    displayMessage("Processing error: " + e.Error.Message);
                }
                                       );
                return;
            }

            Dispatcher.BeginInvoke(() =>
            {
                displayMessage("Processing completed. Downloading..");
            }
                                   );

            // Download a file
            string     outputPath = "result.txt";
            OcrSdkTask task       = e.Result;

            abbyyClient.DownloadFileAsync(task, outputPath, outputPath);
        }
예제 #15
0
 public ListTaskEventArgs( OcrSdkTask[] tasks,
     Exception e, bool canceled, object state)
     : base(e, canceled, state)
 {
     _tasks = tasks;
 }
예제 #16
0
 public TaskEventArgs(OcrSdkTask task,
     Exception e, bool canceled, object state)
     : base(e, canceled, state)
 {
     _task = task;
 }
예제 #17
0
        private void downloadCompletionMethod(
            OcrSdkTask task,
            Exception exception,
            bool canceled,
            AsyncOperation asyncOp)
        {
            if (!canceled)
            {
                lock (downloadJobs)
                {
                    downloadJobs.Remove(asyncOp.UserSuppliedState);
                }
            }

            TaskEventArgs e = new TaskEventArgs(task, exception, canceled, asyncOp.UserSuppliedState);

            asyncOp.PostOperationCompleted(onDownloadCompletedDelegate, e);
        }
예제 #18
0
        // This is the method that the underlying, free-threaded 
        // asynchronous behavior will invoke.  This will happen on
        // a worker thread
        private void processCompletionMethod(
            OcrSdkTask task,
            Exception exception,
            bool canceled,
            AsyncOperation asyncOp)
        {
            // If the task was not previously canceled,
            // remove the task from the lifetime collection.
            if (!canceled)
            {
                lock (processJobs)
                {
                    processJobs.Remove(asyncOp.UserSuppliedState);
                }
            }

            // Package the results of the operation in EventArgs
            TaskEventArgs e = new TaskEventArgs(task, exception, canceled, asyncOp.UserSuppliedState);

            // End the task. The asyncOp object is responsible 
            // for marshaling the call.
            asyncOp.PostOperationCompleted(onProcessingCompleteDelegate, e);

            // Note that after the call to OperationCompleted, 
            // asyncOp is no longer usable, and any attempt to use it
            // will cause an exception to be thrown.
        }
예제 #19
0
        private void downloadFileWorker(OcrSdkTask task, string outputFilePath,
            AsyncOperation asyncOp)
        {
            Exception e = null;

            try
            {
                _syncClient.DownloadResult(task, outputFilePath);
            }
            catch (Exception ex)
            {
                e = ex;
            }

            downloadCompletionMethod(task, e, false, asyncOp);
        }
예제 #20
0
        private void processFieldWorker(string filePath, IProcessingSettings settings,
            AsyncOperation asyncOp)
        {
            Exception e = null;

            OcrSdkTask task = new OcrSdkTask();
            try
            {
                if (settings is TextFieldProcessingSettings)
                {
                    task = _syncClient.ProcessTextField(filePath, settings as TextFieldProcessingSettings);
                }
                else if (settings is BarcodeFieldProcessingSettings)
                {
                    task = _syncClient.ProcessBarcodeField(filePath, settings as BarcodeFieldProcessingSettings);
                }
                else if (settings is CheckmarkFieldProcessingSettings)
                {
                    task = _syncClient.ProcessCheckmarkField(filePath, settings as CheckmarkFieldProcessingSettings);
                }
                else
                {
                    throw new ArgumentException("Invalid type of processing settings");
                }

                // Notify that upload was completed
                OcrSdkTask uploadedTask = new OcrSdkTask(task.Id, TaskStatus.Submitted);
                UploadCompletedEventArgs uploadCompletedEventArgs = new UploadCompletedEventArgs(uploadedTask, asyncOp.UserSuppliedState);
                asyncOp.Post(onUploadCompletedDelegate, uploadCompletedEventArgs);

                // Wait until task finishes
                startTaskMonitorIfNecessary();

                _taskList.AddTask(task);
                task = waitUntilTaskFinishes(task);
            }
            catch (Exception ex)
            {
                e = ex;
            }

            lock (processJobs)
            {
                processJobs.Remove(asyncOp.UserSuppliedState);
            }

            bool canceled = false;

            // Package the results of the operation in EventArgs
            TaskEventArgs ev = new TaskEventArgs(task, e, canceled, asyncOp.UserSuppliedState);

            // End the task. The asyncOp object is responsible 
            // for marshaling the call.
            asyncOp.PostOperationCompleted(onProcessingCompleteDelegate, ev);
        }
예제 #21
0
 public UploadCompletedEventArgs(OcrSdkTask task, object userState) :
     base( 50, userState )
 {
     _task = task;
 }
예제 #22
0
        // This method performs the actual file processing.
        // It is executed on the worker thread.
        private void processFileWorker(string filePath, IProcessingSettings settings,
            AsyncOperation asyncOp)
        {
            Exception e = null;

            // Check that the task is still active.
            // The operation may have been canceled before
            // the thread was scheduled.

            OcrSdkTask task = null;
            try
            {
                if (settings is ProcessingSettings)
                {
                    task = _syncClient.ProcessImage(filePath, settings as ProcessingSettings);
                }
                else if (settings is BusCardProcessingSettings)
                {
                    task = _syncClient.ProcessBusinessCard(filePath, settings as BusCardProcessingSettings);
                }
                else if (settings is ProcessMrzSettings)
                {
                    task = _syncClient.ProcessMrz(filePath);
                }

                // Notify subscriber that upload completed
                OcrSdkTask uploadedTask = new OcrSdkTask(task.Id, TaskStatus.Submitted);
                UploadCompletedEventArgs uploadCompletedEventArgs = new UploadCompletedEventArgs(uploadedTask, asyncOp.UserSuppliedState);
                asyncOp.Post(onUploadCompletedDelegate, uploadCompletedEventArgs);

                startTaskMonitorIfNecessary();

                _taskList.AddTask(task);

                task = waitUntilTaskFinishes(task); // task is modified on server
            }
            catch (Exception ex)
            {
                e = ex;
            }

            processCompletionMethod(task, e, false, asyncOp);
        }
예제 #23
0
 public void AddTask(OcrSdkTask task)
 {
     lock (allTasks)
     {
         allTasks.Add(task.Id, task);
     }
 }
예제 #24
0
        /// <summary>
        /// Download file asynchronously
        /// Performs DownloadFileCompleted callback
        /// </summary>
        public void DownloadFileAsync(OcrSdkTask task, string outputPath, object userTaskId)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userTaskId);

            lock (downloadJobs)
            {
                if (downloadJobs.ContainsKey(userTaskId))
                {
                    throw new ArgumentException("Task ID parameter must be unique", "userTaskId");
                }
                downloadJobs[userTaskId] = asyncOp;
            }

            // Start the asynchronous operation.
            downloadWorkerEventHandler workerDelegate = new downloadWorkerEventHandler(downloadFileWorker);
            workerDelegate.BeginInvoke(task, outputPath, asyncOp,
                null, null);
        }
예제 #25
0
        public UserTask(OcrSdkTask task)
        {
            SourceFilePath = null;
            TaskId = task.Id.ToString();
            TaskStatus = task.Status.ToString();
            PagesCount = task.PagesCount;
            Description = task.Description;
            RegistrationTime = task.RegistrationTime;
            StatusChangeTime = task.StatusChangeTime;

            SourceIsTempFile = false;
        }
예제 #26
0
        /// <summary>
        /// Enter infinite loop and wait for task to complete
        /// </summary>
        /// <returns>Details about completed task</returns>
        private OcrSdkTask waitUntilTaskFinishes(OcrSdkTask task)
        {
            
            while (true)
            {
                if (_taskList.Error != null)
                {
                    _taskList.DeleteTask(task.Id);
                    throw new Exception(_taskList.Error.Message, _taskList.Error);
                }

                TaskStatus taskStatus = _taskList.GetTaskStatus(task.Id);
                if (_taskList.IsTaskFinished(task.Id))
                {
                    OcrSdkTask result = _taskList.GetTask(task.Id);
                    _taskList.DeleteTask(task.Id);

                    return result;
                }

                Thread.Sleep(1000);
            }
        }
예제 #27
0
파일: Test.cs 프로젝트: miuzel/ocrsdk.com
        /// <summary>
        /// Wait until task finishes and download result
        /// </summary>
        private void waitAndDownload(OcrSdkTask task, string outputFilePath)
        {
            task = waitForTask(task);

            if (task.Status == TaskStatus.Completed)
            {
                Console.WriteLine("Processing completed.");
                restClient.DownloadResult(task, outputFilePath);
                Console.WriteLine("Download completed.");
            }
            else
            {
                Console.WriteLine("Error while processing the task");
            }
        }
예제 #28
0
 private OcrSdkTask waitForTask(OcrSdkTask task)
 {
     Console.WriteLine(String.Format("Task status: {0}", task.Status));
     while (task.IsTaskActive())
     {
         // Note: it's recommended that your application waits
         // at least 2 seconds before making the first getTaskStatus request
         // and also between such requests for the same task.
         // Making requests more often will not improve your application performance.
         // Note: if your application queues several files and waits for them
         // it's recommended that you use listFinishedTasks instead (which is described
         // at http://ocrsdk.com/documentation/apireference/listFinishedTasks/).
         System.Threading.Thread.Sleep(5000);
         task = restClient.GetTaskStatus(task.Id);
         Console.WriteLine(String.Format("Task status: {0}", task.Status));
     }
     return task;
 }
예제 #29
0
        /// <summary>
        /// Download file asynchronously
        /// Performs DownloadFileCompleted callback
        /// </summary>
        public void DownloadFileAsync(OcrSdkTask task, string outputPath, object userState)
        {
            BackgroundWorker w = new BackgroundWorker();
            w.DoWork += new DoWorkEventHandler((sender, e) =>
                {
                    try
                    {
                        _syncClient.DownloadResult(task, outputPath);
                        TaskEventArgs taskArgs = new TaskEventArgs(task, null, false, userState);
                        onDownloadFileCompleted(sender, taskArgs);
                    }
                    catch (Exception ex)
                    {
                        TaskEventArgs taskArgs = new TaskEventArgs(task, ex, false, userState);
                        onDownloadFileCompleted(sender, taskArgs);
                    }
                }
                );

            w.RunWorkerAsync();
        }