PaddleSharp

repository·master·Indexed 23 days ago

https://github.com/sdcb/paddlesharp

A .NET wrapper for the PaddleInference C API providing high-performance machine learning capabilities for Windows and Linux. It includes components for PaddleOCR (supporting 14 languages and table recognition), PaddleDetection (PPYolo and PicoDet), RotationDetection, and PaddleNLP ChineseSegmenter. The library supports multiple execution devices including Mkldnn, Openblas, Onnx, and Gpu (CUDA), with specific native runtime NuGet packages for x64 and ARM64 architectures across Windows, Linux, and macOS.

Tokens
7.5K
Snippets
21
Records
35
Agent score
81%

What's inside PaddleSharp

  1. Overview of PaddleSharp components

    master

    PaddleSharp is a .NET wrapper for the PaddleInference C API, supporting Windows (x64) and Linux (Ubuntu-22.04 x64). It provides high-level components for various computer vision and NLP tasks:

    • PaddleOCR: Supports 14 OCR languages with on-demand model downloading, rotated text angle detection, 180-degree detection, and table recognition.
    • PaddleDetection: Supports PPYolo and PicoDet detection models.
    • RotationDetection: Uses Baidu's text_image_orientation_infer model to detect text image rotation angles (0, 90, 180, 270).
    • PaddleNLP ChineseSegmenter: Supports the PaddleNLP Lac Chinese segmenter model with tagging and customized word support.
    • Paddle2Onnx: Allows exporting ONNX models using C#.
  2. Prepare PaddleDetection inference models

    master

    PaddleDetection requires models to be in the inference model format. A valid model directory must contain the following files:

    • infer_cfg.yml
    • model.pdiparams
    • model.pdiparams.info
    • model.pdmodel

    Note: If your model files end in .pdparams, they are training checkpoints and not inference models. You must export them to the inference format before use. You can refer to the official PaddleDetection deployment documentation for export instructions.

  3. Perform full OCR (Detection and Recognition) using local models on Windows

    master

    To perform full OCR using local V5 models on Windows, install the following NuGet packages:

    Sdcb.PaddleInference
    Sdcb.PaddleOCR
    Sdcb.PaddleOCR.Models.Local
    Sdcb.PaddleInference.runtime.win64.mkl
    OpenCvSharp4.runtime.win

    Use LocalFullModels to select a model and PaddleOcrAll to execute the OCR process. You can configure rotation detection and 180-degree classification via the PaddleOcrAll constructor/initializer.

    FullOcrModel model = LocalFullModels.ChineseV5;
    
    // ... (image loading code) ...
    
    using (PaddleOcrAll all = new PaddleOcrAll(model, PaddleDevice.Mkldnn())
    {
        AllowRotateDetection = true, /* Allow detection of angled text */ 
        Enable180Classification = false, /* Allow detection of text rotated > 90 degrees */
    })
    {
        using (Mat src = Cv2.ImDecode(sampleImageData, ImreadModes.Color))
        {
            PaddleOcrResult result = all.Run(src);
            Console.WriteLine("Detected all texts: \n" + result.Text);
            foreach (PaddleOcrResultRegion region in result.Regions)
            {
                Console.WriteLine($"Text: {region.Text}, Score: {region.Score}, RectCenter: {region.Rect.Center}, RectSize:    {region.Rect.Size}, Angle: {region.Rect.Angle}");
            }
        }
    }
  4. Install Sdcb.Paddle2Onnx

    master

    Sdcb.Paddle2Onnx is a .NET wrapper for Paddle2Onnx used to convert PaddlePaddle models to ONNX models.

    Note: This project is only supported on Windows.

    To use the library, you must install both the API binding and the win-x64 runtime via NuGet. You need .NET standard 2.0 or later.

    Install-Package Sdcb.Paddle2Onnx
    Install-Package Sdcb.Paddle2Onnx.runtime.win64
  5. Enable TensorRT acceleration for PaddleOCR

    master

    You can accelerate GPU inference using TensorRT by using the .And() method on PaddleDevice.Gpu() and providing a path to a shape information text file.

    Important Considerations:

    • Model Specificity: Shape info files (**.txt) are bound to specific models. If you are using a complex setup like PaddleOcrAll, you must provide different shape info files for the Detection, Classification, and Recognition models respectively.
    • Cache Generation: The first run with TensorRT will generate a cache in %AppData%\Sdcb.PaddleInference\TensorRtCache. This initial run can take approximately 100 seconds. Subsequent runs will be significantly faster.
    • Troubleshooting: If you encounter issues (e.g., using the wrong shape info for a model), delete the %AppData%\Sdcb.PaddleInference\TensorRtCache folder to force a regeneration of the cache.
    using PaddleOcrAll all = new(model,
       PaddleDevice.Gpu().And(PaddleDevice.TensorRt("det.txt")),
       PaddleDevice.Gpu().And(PaddleDevice.TensorRt("cls.txt")),
       PaddleDevice.Gpu().And(PaddleDevice.TensorRt("rec.txt")))
    {
       Enable180Classification = true,
       AllowRotateDetection = true,
    };
  6. Perform full OCR (Detection and Recognition) using online models on Windows

    master

    To use online models that download on demand, install these NuGet packages:

    Sdcb.PaddleInference
    Sdcb.PaddleOCR
    Sdcb.PaddleOCR.Models.Online
    Sdcb.PaddleInference.runtime.win64.mkl
    OpenCvSharp4.runtime.win

    Use OnlineFullModels.[Language].DownloadAsync() to retrieve the model before running PaddleOcrAll.

  7. Integrate Sdcb.PaddleOCR into ASP.NET Core

    master

    To use Sdcb.PaddleOCR in an ASP.NET Core application, register QueuedPaddleOcrAll as a Singleton in your service builder. This allows you to manage OCR requests through a queue, which is useful for controlling concurrency.

    In your controller, inject the QueuedPaddleOcrAll instance and use the .Run() method to process images. Note that you will likely need to use OpenCvSharp (e.g., Cv2.ImDecode) to convert uploaded files into a format suitable for the OCR engine.

    // 1. Register in Service Collection
    builder.Services.AddSingleton(s =>
    {
        Action<PaddleConfig> device = builder.Configuration["PaddleDevice"] == "GPU" ? PaddleDevice.Gpu() : PaddleDevice.Mkldnn();
        return new QueuedPaddleOcrAll(() => new PaddleOcrAll(LocalFullModels.ChineseV5, device)
        {
            Enable180Classification = true,
            AllowRotateDetection = true,
        }, consumerCount: 1);
    });
    
    // 2. Use in Controller
    public class OcrController : Controller
    {
        private readonly QueuedPaddleOcrAll _ocr;
    
        public OcrController(QueuedPaddleOcrAll ocr) { _ocr = ocr; }
    
        [Route("ocr")]
        public async Task<OcrResponse> Ocr(IFormFile file)
        {
            using MemoryStream ms = new();
            using Stream stream = file.OpenReadStream();
            stream.CopyTo(ms);
            using Mat src = Cv2.ImDecode(ms.ToArray(), ImreadModes.Color);
            double scale = 1;
            using Mat scaled = src.Resize(default, scale, scale);
    
            Stopwatch sw = Stopwatch.StartNew();
            string textResult = (await _ocr.Run(scaled)).Text;
            sw.Stop();
    
            return new OcrResponse(textResult, sw.ElapsedMilliseconds);
        }
    }
  8. Install Sdcb.PaddleOCR packages

    master

    Depending on your requirements for model storage and availability, choose from the following NuGet packages:

    • Sdcb.PaddleOCR: The core library based on Sdcb.PaddleInference.
    • Sdcb.PaddleOCR.Models.Local: Recommended for the default local OCR experience. It contains maintained V5 models.
    • Sdcb.PaddleOCR.Models.Online: Provides online models that are downloaded automatically upon first use.
  9. Install Sdcb.RotationDetector NuGet packages

    master

    To use rotation detection, you need to install the core library, the runtime dependencies for PaddleInference, and the OpenCV runtime. For a Windows environment using MKL, install the following packages:

    dotnet add package Sdcb.RotationDetector
    dotnet add package Sdcb.PaddleInference.runtime.win64.mkl
    dotnet add package OpenCvSharp4.runtime.win
    Sdcb.PaddleInference.runtime.win64.mkl
    Sdcb.RotationDetector
    OpenCvSharp4.runtime.win
  10. Enable GPU support in PaddleSharp

    master

    To improve throughput and lower CPU usage, you can enable GPU support.

    Windows Setup

    1. Install correct NuGet package: Install Sdcb.PaddleInference.runtime.win64.cu120* (replace * with your version). Important: Do not install both the .cu120 package and the .mkl package.
    2. NVIDIA Drivers: Install CUDA, cuDNN, and TensorRT from NVIDIA.
    3. Environment Variables: Ensure CUDA, cuDNN, and TensorRT are added to your PATH.

    Linux Setup

    On Linux, you must compile your own OpenCvSharp4 environment. Follow the provided docker build scripts and complete the CUDA/cuDNN/TensorRT configuration tasks.

    Usage

    Once configured, specify PaddleDevice.Gpu() in your paddle device configuration parameter.

  11. Install Sdcb.PaddleDetection NuGet packages

    master

    To use PaddleDetection in your project, you need to install the following NuGet packages:

    • Sdcb.PaddleDetection
    • Sdcb.PaddleInference
    • Sdcb.PaddleInference.runtime.win64.mkl (or the appropriate runtime for your platform)
    • OpenCvSharp4
    • OpenCvSharp4.runtime.win (or the appropriate runtime for your platform)