La integración de Aspose.OCR con Amazon S3 permite a los desarrolladores aprovechar el almacenamiento en la nube para guardar de manera eficiente los resultados de la Recogida de Caracteros Ópticos. Esta integracion no sólo simplifica la gestión de los datos de OCR, sino que también mejora la escalabilidad y la accesibilidad. En este tutorial, vamos a pasar por el proceso de configuración d’Apasse.ocR para trabajar sin problemas con AWS S3, proporcionando ejemplos detallados y mejores prácticas a lo largo del camino.

Ejemplo completo

Prerequisitos

  • .NET 8 (o .Net 6+) SDK está instalado.
  • Una cuenta AWS con acceso a Amazon S3.
  • Un cuchillo (por ejemplo, my-ocr-demo-bucketen su región preferida (exemplo de uso a continuación) ap-south-1).).
  • (Opcional) Aspose el archivo de licencia si desea correr más allá de la evaluación.

Paso 1: Configurar Aspose.OCR para .NET

Instalar una nueva aplicación de consola y agregar paquetes 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

Asposa proporciona los dos Aspose.OCR (CPU) y Aspose.OCR-GPU los paquetes a través de NuGet; sólo necesitas uno. (Documentación Asposa)

Paso 2: Configuración de AWS SDK para .NET

Configure su perfil de AWS y crea un bucket (skip si ya tienes uno).

# 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

Políticas mínimas recomendadas de IAM (adjunto a su usuario/rol) 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/*" }
  ]
}

El SDK de AWS para .NET utiliza la cadena de credencia predeterminada; AWS_PROFILE=ocr-s3 Los patrones Core S3 (create, upload, download) se documentan en los ejemplos oficiales de .NET de AWS. (Documentación AWS)

Paso 3: Iniciar la API de Aspose.OCR

Crear una base Program.cs También definiremos el inglés como lenguaje y detección del diseño de documentos. (Todos los tipos que se muestran a continuación están desde la superficie actual de la API Aspose.OCR.) (Sitio web.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 clave que utilizamos a continuación:

  • AsposeOcr.RecognizeImage(MemoryStream, RecognitionSettings) Regreso a RecognitionResult.
  • RecognitionResult.RecognitionText / GetJson(bool) / Save(...) Deja que los resultados sean exportados a TXT/JSON/PDF/DOCX. (Sitio web.aspose.com)

Paso 4: Cargar imágenes a S3

Puedes subir imágenes desde el disco a S3 con PutObjectAsync(También puedes cargar corrientes; ambos están apoyados 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}.");

Ver los ejemplos de .NET S3 de AWS para los patrones de descarga. (Documentación AWS)

Paso 5: Performan OCR en las imágenes cargadas

Streame el objeto S3 directamente en la memoria y pasa el MemoryStream En el caso 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);

El RecognizeImage sobrecarga y RecognitionResult.RecognitionText Es parte de la actual referencia API. (Sitio web.aspose.com)

Paso 6: Almacenar los resultados de OCR en S3

Puedes cargar texto claro, JSON, o incluso un PDF/DOCX producido por Aspose.OCR.

6.a) Salva 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) Salva los detalles de 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) Salva un PDF buscable (o DOCX) y coloca en 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}");

Exportaciones y métodos de ahorro (RecognitionResult.Save) y los formatos (TXT/PDF/DOCX) están en la referencia oficial de la API. ([reference.aspose.com][4])

Opcional: fin a fin Program.cs

Aquí está una versión compacta de fin a fin que puede caer en Program.cs (Combinaciones de los pasos 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.");
    }
}

Mejores Prácticas

La integración de Aspose.OCR con AWS S3 ofrece numerosos beneficios, incluyendo una mejor gestión de datos y una mejora de la escalabilidad.

  • • Seguridad*

  • Nunca los secretos de código duro. aws configure + AWS_PROFILE local; utilizar los roles de IAM en la producción.

  • Considere la criptografía del lado del servidor S3 (AES256 o KMS) en los objetos resultantes, y las políticas per-bucket con el menor privilegio (ver más arriba).Documentación AWS)

  • El rendimiento

  • Utilizar el paquete de GPU (Aspose.OCR-GPU) en hardware capaz de CUDA para acelerar OCR; el mismo código, ejecución más rápida. (Documentación Asposa)

  • Imágenes preprocesadas para la calidad (desqueo, denoise) utilizando RecognitionSettings / presets si es necesario, y elegir la derecha DetectAreasMode para los documentos. las opciones de API se muestran en la referencia. (Sitio web.aspose.com)

    • Escalabilidad *
  • Utilice los prefixos S3 como input/ y output/ por trabajo, y almacenar artefactos OCR (TXT/JSON/PDF) juntos para la rastreabilidad.

  • Permite la versión S3 si desea historias audibles y rolbacks.

  • Considere correr este flujo en contenedores o sin servidor (por ejemplo, AWS Batch/ECS/Lambda con EFS) para OCR paralelo a escala.

Al seguir estas directrices, puede integrar eficazmente Aspose.OCR con AWS S3 para simplificar su flujo de trabajo de OCR y mejorar el rendimiento general de su aplicación.

Referencias

Si quieres, también puedo añadir un pequeño Makefile o el guión PowerShell para ejecutar este fin a fin, además de un snippet CI (acciones de GitHub) para empujar los resultados a S3 en compromiso.

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

More in this category