PaddleOCRHelper.cs 2.9 KB
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BLL
{
    public class PaddleOCRHelper
    {
        static string baseUrl = ConfigHelper.Config.Get("PaddleServiceBase", "http://192.168.101.12:8090/paddle/getOcr");
        /// <summary>
        /// 开始检测
        /// </summary>
        /// <param name="pythonExePath">python解释器路径</param>
        /// <param name="pythonFile">python文件</param>
        /// <param name="imgPath">图像文件路径</param>
        /// <returns></returns>
        public static string StartTest(string imgPath)
        {
            string ocr = StartCplusOcr(imgPath);
            if (!string.IsNullOrEmpty(ocr))
            {
                return ocr;
            }
            ocr= StartPythonOcr(imgPath);
            if (!AppIsRun())
            {
                var onnxexe = ".\\PaddleOCRSDK\\paddleOCR.exe";
                Process.Start(onnxexe);
            }
            return ocr;
        }

        [HandleProcessCorruptedStateExceptions]
        static string StartCplusOcr(string imgPath)
        {
            string json=Http.Get($"{baseUrl}?ver=cplus&imgPath={imgPath}");
            Result result= JsonConvert.DeserializeObject<Result>(json);
            return result?.data??"";
        }
        static string StartPythonOcr(string imgPath)
        {
            if (!AppIsRun())
            {
                var onnxexe = ".\\PaddleOCRSDK\\paddleOCR.exe";
                Process.Start(onnxexe);
                Thread.Sleep(2000);
            }
            string json = Http.Get($"{baseUrl}?ver=python&imgPath={imgPath}");
            Result result = JsonConvert.DeserializeObject<Result>(json);
            return result?.data ?? "";
        }
        static bool AppIsRun()
        {
            Process[] processes = Process.GetProcessesByName("paddleOCR");
            if (processes.Length > 0)
            {
                return true;
            }
            LogNet.log.Info("paddleOCR 未在运行,启动程序");
            return false;
        }
        public class Result
        {
            /// <summary>
            /// 状态码,0为正常
            /// </summary>
            public int code { get; set; } = 0;
            /// <summary>
            /// 返回数据
            /// </summary>
            public string data { get; set; } = "";
            /// <summary>
            /// 提示信息
            /// </summary>
            public string msg { get; set; } = "ok";
            /// <summary>
            /// 版本
            /// </summary>
            public string ver { get; set; } = "";

        }
    }
}