Coder Social home page Coder Social logo

regulaforensics / documentreader-web-csharp-client Goto Github PK

View Code? Open in Web Editor NEW
8.0 5.0 3.0 6.47 MB

Regula Document Reader web API c# client compatible with .NET & .NET Core

Home Page: https://regulaforensics.com

C# 99.91% Shell 0.09%
ocr barcode barcode-scanner passport idcard-ocr idcard-check regula regulaforensics mrz document-reader

documentreader-web-csharp-client's Introduction

Regula.DocumentReader.WebClient - the C# library for the Regula Document Reader Web API

NuGet version (Regula.OpenApi.WebClient) OpenAPI documentation live

Documents recognition as easy as reading two bytes.

If you have any problems with or questions about this client, please contact us through a GitHub issue. You are invited to contribute new features, fixes, or updates, large or small. We are always thrilled to receive pull requests, and do our best to process them as fast as we can.

Frameworks supported

  • .NET Standard 2.0
  • .NET Framework 4.6.1 or later
  • .Net Core 2.0 or later

Install package

Regula.DocumentReader.WebClient is on the NuGet Package Index:

PM> Install-Package Regula.DocumentReader.WebClient -Version 5.2.0

Example

Performing request:

var imageBytes = File.ReadAllBytes("australia_passport.jpg");
var image = new ProcessRequestImage(new ImageData(imageBytes), Light.WHITE);

var requestParams = new RecognitionParams()
    .WithScenario(Scenario.FULL_PROCESS)
    .WithResultTypeOutput(new List<int> { Result.STATUS, Result.TEXT, Result.IMAGES, Result.DOCUMENT_TYPE });
var request = new RecognitionRequest(requestParams, image);

var api = licenseFromEnv != null 
    ? new DocumentReaderApi(apiBaseUrl).WithLicense(licenseFromEnv)
    : new DocumentReaderApi(apiBaseUrl).WithLicense(licenseFromFile);

var response = api.Process(request);

Parsing results:

var response = api.Process(request);

// status examples
var status = response.Status();
string docOverallStatus = status.OverallStatus == CheckResult.OK ? "valid" : "not valid";
string docOpticalTextStatus = status.DetailsOptical.Text == CheckResult.OK ? "valid" : "not valid";

// text fields examples
var docNumberField = response.Text().GetField(TextFieldType.DOCUMENT_NUMBER);
string docNumberVisual = docNumberField.GetValue(Source.VISUAL);
string docNumberMrz = docNumberField.GetValue(Source.MRZ);
int docNumberVisualValidity = docNumberField.SourceValidity(Source.VISUAL);
int docNumberMrzValidity = docNumberField.SourceValidity(Source.MRZ);
int docNumberMrzVisualMatching = docNumberField.CrossSourceComparison(Source.MRZ, Source.VISUAL);

// images fields examples
var documentImage = response.Images().GetField(GraphicFieldType.DOCUMENT_FRONT).GetValue();
var portraitField = response.Images().GetField(GraphicFieldType.PORTRAIT);
var portraitFromVisual = portraitField.GetValue(Source.VISUAL);

You can find this sample in the example.

documentreader-web-csharp-client's People

Contributors

actions-user avatar alexsatsukevich avatar andreipaulau avatar dangost avatar dependabot[bot] avatar gubinalexander avatar hleb-albau avatar ikliashchou avatar kirylkovaliov avatar regula-bot avatar vyakimchik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

documentreader-web-csharp-client's Issues

Generate initil charp client

В целом клиент на charp больше всего похож на java клиент. Из-застатической типизации, добавить методы в какую-нибудь сгенерируемую модель становится немногосложнее.
https://github.com/regulaforensics/DocumentReader-web-java-client/blob/master/dev.md разработка под java, генератор сейчас стоит брать 5.0.0-beta.2 версии
В целом нужно двигаться примерно так:

  • Сгенерировать версию как есть
  • Добавить example, где просто проверить, что клиент парсит результат
  • Сделать, чтобывместо enum генерились простые типы(строки, инты)
  • Добавить доп методы для классов Text, TextField, Images, ImageField( смотри тут https://github.com/regulaforensics/DocumentReader-web-java-client/tree/master/client/src/main/java/com/regula/documentreader/webclient/model и коммиты как это добавлялось в java)
  • Сделать модель для неизвестного типа контейнера (https://github.com/regulaforensics/DocumentReader-web-java-client/blob/master/client/src/main/java/com/regula/documentreader/webclient/RawResultItem.java)
  • Проверить, что работа с картинками происходит и в байтах(есть методы которые не только base64 принимают, но и bytes)
  • Привести пример, чтобы он выл точь-в-точь как в java(все названия доп методов и т.д. должны совпадать)
  • Настроить проверку выполнения примера на каждый коммит в githubactions
  • Настроить сборку и заливку либы по тэгу в githubactions
  • Общий ридми (такой же как в java)
  • Ридми запуска примера (такой же как в java)

DocumentReaderApi.Process() Throws ApiException - Error while copying content to a stream

I am closely following the example/quick start for 'Perform a request' provided in the README, but I am getting the following exception when calling api.Process():

Regula.DocumentReader.WebClient.Client.ApiException: Error calling ApiProcess: Error while copying content to a stream.

Note: Full stack trace and assoc. code snippet below.

I am calling this C# code as an Azure Function App and, as I suspect it's pertinent, the code runs well and does not throw any exceptions locally, but throws the above exception when deployed to and run in Azure.

From what I can determine, this exception is being thrown by the Regula Document Reader C# Web Client code (and the content it is failing to convert to a stream is the internalised request body, not any content handled by my code), hence reaching out here for some support.

This is using Regula.DocumentReader.WebClient version 6.9.2, installed via from NuGet dotnet package add.
I am using .NET 8 and running the function app in 'dotnet-isolated' mode if that is of any importance.

Any insights and feedback welcomed.

Full Details -

Code Snippet:

string blobBase64 = blobStream.ConvertToBase64();

// Prepare Regula Client & Request
string? regulaBaseUrl = _config.GetValue<string>("REGULA_BASE_URL");
string? regulaLicenseBase46 = _config.GetValue<string>("REGULA_LICENCE_BASE64");
if (String.IsNullOrWhiteSpace(regulaBaseUrl) || String.IsNullOrWhiteSpace(regulaLicenseBase46))
    throw new ApplicationException("Regula configuration is missing or incomplete");

ProcessRequestImage image = new ProcessRequestImage(
    new ImageData(blobBase64),
    Light.WHITE
);
RecognitionParams recognitionParams = new RecognitionParams()
    .WithScenario(Scenario.FULL_PROCESS)
    .WithResultTypeOutput(new List<int> {
        Result.STATUS,
        Result.TEXT,
        Result.IMAGES,
        Result.DOCUMENT_TYPE
    });
RecognitionRequest recognitionRequest = new RecognitionRequest(recognitionParams, image);

DocumentReaderApi api = new DocumentReaderApi(regulaBaseUrl)
    .WithLicense(regulaLicenseBase46);

RecognitionResponse response = api.Process(recognitionRequest);

Stack Trace:

Regula.DocumentReader.WebClient.Client.ApiException: Error calling ApiProcess: Error while copying content to a stream.
at Regula.DocumentReader.WebClient.Api.ProcessApi.ApiProcessWithHttpInfo(ProcessRequest processRequest, Dictionary2 headers, String xRequestID) at Regula.DocumentReader.WebClient.Api.ProcessApi.ApiProcess(ProcessRequest processRequest, Dictionary2 headers, String xRequestID)
at Regula.DocumentReader.WebClient.Api.DocumentReaderApi.Process(ProcessRequest processRequest, Dictionary`2 headers, String xRequestID)
at Regula.DocumentReader.WebClient.Api.DocumentReaderApi.Process(ProcessRequest processRequest)
at Vaiie.Intelligence.IdDocumentChecks.ProcessIdDocumentBlob(BlobClient idDocBlobClient, String idDocBlobName, BlobContainerClient resultsContainerClient, TableClient checksTableClient, TableClient regulaTableClient, TableClient billingTableClient, FunctionContext executionContext) in /Users/joe.harvey/Development/intelligence/IdDocumentChecks.cs:line 361

Are any plans to support async calls through a client?

Hi. I want to use a client to recognize document fields and document types in a high-load service. The problem is that the client does not support async calls and it will lock a thread for the request time. Are any plans to implement this feature?

var imageBytes = File.ReadAllBytes("australia_passport.jpg");
var image = new ProcessRequestImage(new ImageData(imageBytes), Light.WHITE);

var requestParams = new RecognitionParams()
    .WithScenario(Scenario.FULL_PROCESS)
    .WithResultTypeOutput(new List<int> { Result.STATUS, Result.TEXT, Result.IMAGES, Result.DOCUMENT_TYPE });
var request = new RecognitionRequest(requestParams, image);

var api = licenseFromEnv != null 
    ? new DocumentReaderApi(apiBaseUrl).WithLicense(licenseFromEnv)
    : new DocumentReaderApi(apiBaseUrl).WithLicense(licenseFromFile);

var response = api.Process(request); // should be available api.ProcessAsync(request)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.