A integração da Aspose.OCR com a Amazon S3 permite que os desenvolvedores aproveitem o armazenamento em nuvem para guardar os resultados de reconhecimento de caráter óptico (OCR) de forma eficiente. Esta integración não só simplifica a gestão dos dados da OCR, mas também melhora a escalabilidade e a acessibilidade. Neste tutorial, vamos passar pelo processo de configuração de Asposa.ocR para trabalhar sem problemas com AWS S3, fornecendo exemplos detalhados e melhores práticas ao longo do caminho.

Exemplo completo

Pré-requisitos

  • .NET 8 (ou .Net 6+) SDK instalado.
  • Uma conta AWS com acesso à Amazon S3.
  • Um pedaço (por exemplo, my-ocr-demo-bucket) em sua região preferida (exemplo abaixo usados ap-south-1).
  • (Opcional) Aspose o arquivo de licença se você quiser executar além da avaliação.

Passo 1: Configurar Aspose.OCR para .NET

Instale um novo aplicativo de console e adicione pacotes NuGet.

# Create project
dotnet new console -n OcrS3Demo -f net8.0
cd OcrS3Demo

# Add Aspose.OCR (CPU) OR Aspose.OCR-GPU (pick exactly one)
dotnet add package Aspose.OCR
# dotnet add package Aspose.OCR-GPU   # if you prefer GPU build

# Add AWS S3 SDK
dotnet add package AWSSDK.S3

A Aspose fornece os dois Aspose.OCR CPU e Aspose.OCR-GPU pacotes através de NuGet; você só precisa de um. (Documentação Aspose)

Passo 2: Configuração do AWS SDK para .NET

Configure o seu perfil da AWS e crie um bucket (skip se você já tiver um).

# Configure credentials (creates ~/.aws/credentials and config)
aws configure --profile ocr-s3
# AWS Access Key ID: AKIA****************
# AWS Secret Access Key: ************************
# Default region name: ap-south-1
# Default output format: json

# Create a bucket in that region (bucket name must be globally unique)
aws s3api create-bucket \
  --bucket my-ocr-demo-bucket \
  --region ap-south-1 \
  --create-bucket-configuration LocationConstraint=ap-south-1

A política mínima recomendada do IAM (atende-se ao seu usuário/rolo) para este tutorial:

{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": "arn:aws:s3:::my-ocr-demo-bucket" },
    { "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": "arn:aws:s3:::my-ocr-demo-bucket/*" }
  ]
}

O AWS SDK para .NET usa a cadeia de credenciamento padrão; configuração AWS_PROFILE=ocr-s3 Os padrões Core S3 (create, upload, download) são documentados em exemplos oficiais de .NET da AWS. (Documentação AWS)

Passo 3: Iniciar o Aspose.OCR API

Crie uma base Program.cs Nós também definiremos o Inglês como linguagem e detecção de layout de documentos. (Todos os tipos mostrados abaixo são da superfície atual Aspose.OCR API.) (Referência.aspose.com)

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Aspose.OCR;

class Program
{
    static async Task Main(string[] args)
    {
        // Optional: load license if you have one
        // new License().SetLicense("Aspose.Total.lic");

        var ocr = new AsposeOcr();

        var settings = new RecognitionSettings
        {
            // pick your language(s); can combine if needed
            Language = Language.Eng,
            DetectAreasMode = DetectAreasMode.DOCUMENT
        };

        // We'll fill in S3 + OCR steps next...
    }
}

APIs chave vamos usar a seguir:

  • AsposeOcr.RecognizeImage(MemoryStream, RecognitionSettings) Retornando a RecognitionResult.
  • RecognitionResult.RecognitionText / GetJson(bool) / Save(...) Deixe que os resultados sejam exportados para TXT/JSON/PDF/DOCX. (Referência.aspose.com)

Passo 4: Carregar imagens para o S3

Você pode carregar imagens do disco para o S3 com PutObjectAsync(Você também pode carregar fluxos; ambos são suportados por AWS SDK.)

// Configure S3 client (uses your AWS_PROFILE locally)
var region = RegionEndpoint.APSouth1; // change if needed
using var s3 = new AmazonS3Client(region);

// Local image you want to OCR:
string localImagePath = @"D:\samples\invoices\invoice-001.png";
string bucket = "my-ocr-demo-bucket";
string objectKey = "input/invoice-001.png";

// Upload the image to S3
await s3.PutObjectAsync(new PutObjectRequest
{
    BucketName = bucket,
    Key = objectKey,
    FilePath = localImagePath,
    ContentType = "image/png",
    // Optional: enable server-side encryption
    // ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256
});
Console.WriteLine($"Uploaded {objectKey} to s3://{bucket}.");

Veja os exemplos do .NET S3 da AWS para padrões de upload. (Documentação AWS)

Passo 5: Performar o OCR em imagens carregadas

Stream o objeto S3 diretamente para a memória e passem pela MemoryStream Apresentação de Aspose.OCR

// Download S3 object and OCR in-memory (no temp files)
var get = await s3.GetObjectAsync(bucket, objectKey);
await using var s3Stream = get.ResponseStream;
using var ms = new MemoryStream();
await s3Stream.CopyToAsync(ms);
ms.Position = 0;

// Run OCR (with settings → structured result)
RecognitionResult result = ocr.RecognizeImage(ms, settings);

// Or: if you just need plain text and defaults
// string textFast = ocr.RecognizeImage(ms);

string recognizedText = result.RecognitionText;
Console.WriteLine("=== OCR TEXT ===");
Console.WriteLine(recognizedText);

O que RecognizeImage sobrecarga e RecognitionResult.RecognitionText são parte da referência API atual. (Referência.aspose.com)

Passo 6: Armazenar os resultados do OCR em S3

Você pode carregar texto plano, JSON, ou até mesmo um PDF/DOCX produzido pela Aspose.OCR.

6. a) Salvar como texto claro

var textKey = "output/invoice-001.txt";
var textBytes = Encoding.UTF8.GetBytes(recognizedText);
await s3.PutObjectAsync(new PutObjectRequest
{
    BucketName = bucket,
    Key = textKey,
    InputStream = new MemoryStream(textBytes),
    ContentType = "text/plain"
});
Console.WriteLine($"Saved OCR text to s3://{bucket}/{textKey}");

6.b) Salvar detalhes JSON

var json = result.GetJson(true); // include additional data
var jsonKey = "output/invoice-001.json";
await s3.PutObjectAsync(new PutObjectRequest
{
    BucketName = bucket,
    Key = jsonKey,
    InputStream = new MemoryStream(Encoding.UTF8.GetBytes(json)),
    ContentType = "application/json"
});
Console.WriteLine($"Saved OCR JSON to s3://{bucket}/{jsonKey}");

6.c) Salvar um PDF (ou DOCX) e colocar em S3

// Export to PDF in-memory, then upload
using var outPdf = new MemoryStream();
result.Save(outPdf, SaveFormat.Pdf, "Arial", PdfOptimizationMode.Basic);
outPdf.Position = 0;

var pdfKey = "output/invoice-001.pdf";
await s3.PutObjectAsync(new PutObjectRequest
{
    BucketName = bucket,
    Key = pdfKey,
    InputStream = outPdf,
    ContentType = "application/pdf"
});
Console.WriteLine($"Saved OCR PDF to s3://{bucket}/{pdfKey}");

Métodos de exportação e poupança (RecognitionResult.Save) e os formatos (TXT/PDF/DOCX) estão na referência API oficial. ([reference.aspose.com][4])

Opção: End-to-end Program.cs

Aqui está uma versão compacta end-to-end que você pode cair em Program.cs (combinação de passos 3 a 6):

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Aspose.OCR;

class Program
{
    static async Task Main()
    {
        // new License().SetLicense("Aspose.Total.lic"); // optional

        string bucket = "my-ocr-demo-bucket";
        string regionSystemName = "ap-south-1";
        string localImagePath = @"D:\samples\invoices\invoice-001.png";
        string imageKey = "input/invoice-001.png";

        var ocr = new AsposeOcr();
        var settings = new RecognitionSettings
        {
            Language = Language.Eng,
            DetectAreasMode = DetectAreasMode.DOCUMENT
        };

        using var s3 = new AmazonS3Client(RegionEndpoint.GetBySystemName(regionSystemName));

        // Upload original
        await s3.PutObjectAsync(new PutObjectRequest
        {
            BucketName = bucket,
            Key = imageKey,
            FilePath = localImagePath,
            ContentType = "image/png"
        });

        // Get image as stream
        var get = await s3.GetObjectAsync(bucket, imageKey);
        await using var s3Stream = get.ResponseStream;
        using var ms = new MemoryStream();
        await s3Stream.CopyToAsync(ms);
        ms.Position = 0;

        // OCR
        RecognitionResult result = ocr.RecognizeImage(ms, settings);
        string text = result.RecognitionText;

        // Upload text
        await s3.PutObjectAsync(new PutObjectRequest
        {
            BucketName = bucket,
            Key = "output/invoice-001.txt",
            InputStream = new MemoryStream(Encoding.UTF8.GetBytes(text)),
            ContentType = "text/plain"
        });

        // Upload JSON
        string json = result.GetJson(true);
        await s3.PutObjectAsync(new PutObjectRequest
        {
            BucketName = bucket,
            Key = "output/invoice-001.json",
            InputStream = new MemoryStream(Encoding.UTF8.GetBytes(json)),
            ContentType = "application/json"
        });

        // Upload PDF
        using var outPdf = new MemoryStream();
        result.Save(outPdf, SaveFormat.Pdf, "Arial", PdfOptimizationMode.Basic);
        outPdf.Position = 0;
        await s3.PutObjectAsync(new PutObjectRequest
        {
            BucketName = bucket,
            Key = "output/invoice-001.pdf",
            InputStream = outPdf,
            ContentType = "application/pdf"
        });

        Console.WriteLine("OCR complete and results stored in S3.");
    }
}

Melhores Práticas

A integração da Aspose.OCR com a AWS S3 oferece inúmeros benefícios, incluindo melhor gestão de dados e melhor escalabilidade.

    • Segurança *
  • Nunca usar o código rígido. aws configure + AWS_PROFILE local; utilizar os papéis IAM na produção.

  • Considere a criptografia do lado do servidor S3 (AES256 ou KMS) sobre objetos resultantes, e as políticas per-bucket com o menor privilégio (mostrado acima).Documentação AWS)

  • Desempenho

  • Utilize o pacote GPU (Aspose.OCR-GPU) em hardware capaz de CUDA para acelerar OCR; mesmo código, execução mais rápida. (Documentação Aspose)

  • Imagens pré-processadas para qualidade (desquew, denoise) usando RecognitionSettings / presets se necessário, e escolha o direito DetectAreasMode para documentos. as opções API são mostradas na referência. (Referência.aspose.com)

    • Escalabilidade *
  • Use prefixos S3 como input/ e output/ por trabalho, e armazenar arquivos OCR (TXT/JSON/PDF) juntos para rastreabilidade.

  • Ativar a versão S3 se você quiser histórias auditivas e rollbacks.

  • Considere executar esse fluxo em recipientes ou sem servidor (por exemplo, AWS Batch/ECS/Lambda com EFS) para OCR paralelo em escala.

Ao seguir estas diretrizes, você pode integrar efetivamente Aspose.OCR com a AWS S3 para simplificar o seu fluxo de trabalho OCR e melhorar o desempenho geral da sua aplicação.

Referências

Se você quiser, eu também posso adicionar um pequeno Makefile ou o script PowerShell para executar este end-to-end, além de um snippet CI (Acções do GitHub) para empurrar os resultados para o S3 em compromisso.

[4]: https://reference.aspose.com/ocr/net/aspose.ocr/recognitionresult/ “RecognitionResult

More in this category