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"); } }
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"); } }
public void ProcessTextField(string sourceFilePath, string outputFilePath, TextFieldProcessingSettings settings) { Console.WriteLine("Uploading.."); OcrSdkTask task = restClient.ProcessTextField(sourceFilePath, settings); waitAndDownload(task, outputFilePath); }
public void ProcessMrz(string sourceFilePath, string outputFilePath) { Console.WriteLine("Uploading"); OcrSdkTask task = restClient.ProcessMrz(sourceFilePath); Console.WriteLine("Processing.."); waitAndDownload(task, outputFilePath); }
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); }
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); }
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); }
/// <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; }
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; }
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); }
/// <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"); } }
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); }
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"); } }
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); }
public ListTaskEventArgs( OcrSdkTask[] tasks, Exception e, bool canceled, object state) : base(e, canceled, state) { _tasks = tasks; }
public TaskEventArgs(OcrSdkTask task, Exception e, bool canceled, object state) : base(e, canceled, state) { _task = task; }
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); }
// 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. }
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); }
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); }
public UploadCompletedEventArgs(OcrSdkTask task, object userState) : base( 50, userState ) { _task = task; }
// 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); }
public void AddTask(OcrSdkTask task) { lock (allTasks) { allTasks.Add(task.Id, task); } }
/// <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); }
/// <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); } }
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; }
/// <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(); }