HUAWEI CLOUD GPU サーバーが PaddleOCR 中国語-英語認識サービスを導入

序文

最近、会社のプロジェクトで OCR サービスを利用しました。最初は Baidu Cloud の一般的なテキスト認識インターフェースを使用していました。その後、Baidu のオープンソースの fly-pulse プラットフォームの PaddleOCR モジュールに直接使用できる既製モデルがあることを偶然知りました。そこで、会社のサーバーに OCR 認識サービスの CPU バージョンをセットアップしました。会社のサーバーの性能と CPU バージョンの問題により、性能が要件を満たせなかったため、Huawei Cloud の GPU サーバーを購入しましたGPU バージョンの OCR サービスを展開します。

Huawei クラウドサーバー上に GPU バージョンの PaddlePaddle 環境を構築する方法については、次の記事を参照してください: https://blog.csdn.net/loutengyuan/article/details/126527326

パドルOCRをインストールする

PaddleOCR は、PaddlePaddle をベースにした Baidu のオープン ソース OCR テキスト認識サービスです。Github アドレス: https://github.com/PaddlePaddle/PaddleOCR/Install
で、次のコマンドを入力します。インストール後、コマンド ラインで OCR 認識サービスを体験できます。

pip install "paddleocr>=2.0." -i https://mirror.baidu.com/pypi/simple

テスト イメージ エクスペリエンス パックをダウンロードします。

wget https://paddleocr.bj.bcebos.com/dygraph_v2.1/ppocr_img.zip #下载
unzip ppocr_img.zip #解压

解凍したばかりのディレクトリに入り、OCR 認識を体験してください

cd ppocr_img #进入刚才下载解压的图片目录

OCR認識を実行する

paddleocr --image_dir ./imgs/11.jpg --use_angle_cls true --use_gpu true

実行するとエラーが報告される場合があります。ここでは、2 つのライブラリ libX11 と libXext をインストールする必要があります。

yum install -y libX11 
yum install -y libXext

これは認識です。GPU サーバーを使用して超高速の認識を行います。
ここに画像の説明を挿入

OCR認識APIサービスをデプロイする

デプロイメントについては、Paddle は PaddleHub と Paddle Serving の 2 つの方法を提供します。PaddleHub を使用するのが最も便利で、コマンド ラインから直接実行できます。Paddle Serving はデプロイ時により安定しており、C++ のコンパイルとデプロイメントをサポートしています。
PaddleHub と Paddle Serving Python デプロイメント (推奨または Paddle Serving デプロイメント) について話しましょう

PaddleHub が OCR 認識 API を導入

パドルハブをインストールする

pip install --upgrade paddlehub -i https://mirror.baidu.com/pypi/simple

APIサービスを開始する

# 前台启动
hub serving start -m ch_pp-ocrv3 --use_gpu   #会自动下载OCR模型
# 后台启动
nohup hub serving start -m ch_pp-ocrv3 --use_gpu > log.log 2>&1 &

OCR認識サービスが開始されます
ここに画像の説明を挿入

デフォルトの最大 GPU メモリ サイズは 8000M です。メソッドを変更する必要がある場合は、 を見つけて/root/.paddlehub/modules/ch_pp_ocrv3/module.py_set_config8000 を必要な値に変更します。

    def _set_config(self, pretrained_model_path):
        """
        predictor config path
        """
        model_file_path = pretrained_model_path + '.pdmodel'
        params_file_path = pretrained_model_path + '.pdiparams'

        config = paddle_infer.Config(model_file_path, params_file_path)
        try:
            _places = os.environ["CUDA_VISIBLE_DEVICES"]
            int(_places[0])
            use_gpu = True
        except:
            use_gpu = False

        if use_gpu:
        	# 原本最大显存是8000M,这里改成2000M。
            config.enable_use_gpu(2000, 0)
            # config.enable_use_gpu(8000, 0)
        else:
            config.disable_gpu()
            if self.enable_mkldnn:
                # cache 10 different shapes for mkldnn to avoid memory leak
                config.set_mkldnn_cache_capacity(10)
                config.enable_mkldnn()

        config.disable_glog_info()
        config.delete_pass("conv_transpose_eltwiseadd_bn_fuse_pass")
        config.switch_use_feed_fetch_ops(False)

        predictor = paddle_infer.create_predictor(config)

        input_names = predictor.get_input_names()
        input_handle = predictor.get_input_handle(input_names[0])
        output_names = predictor.get_output_names()
        output_handles = []
        for output_name in output_names:
            output_handle = predictor.get_output_handle(output_name)
            output_handles.append(output_handle)

        return predictor, input_handle, output_handles

プロセスを表示する

ps -ef|grep python

プロセスを閉じる

kill -9 19913

ビュー・ログ

tail -f 1000 log.log

ポート占有状況の確認方法

$: netstat -anp | grep 8888
tcp        0      0 127.0.0.1:8888          0.0.0.0:*               LISTEN      13404/python3       
tcp        0      1 172.17.0.10:34036       115.42.35.84:8888       SYN_SENT    14586/python3 

プロセスを強制的に強制終了します: pid によって

$: kill -9 13404
$: kill -9 14586
$: netstat -anp | grep 8888
$:
  • 郵便配達員テストのリクエスト

識別するときは、画像をbase64に変換し、jsonリクエストでパラメータを送信する必要があります。

リクエストアドレス: http://127.0.0.1:8866/predict/ch_pp-ocrv3
リクエストメソッド: json
リクエストパラメータ: {"images": ["イメージのbase64コンテンツ、以前のbase64ロゴは不要"]}

ここに画像の説明を挿入

  • Python テスト スクリプト
import requests
import json
import cv2
import base64

def cv2_to_base64(image):
    data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(data.tostring()).decode('utf8')

# 发送HTTP请求
data = {
    
    'images':[cv2_to_base64(cv2.imread("你的图片地址"))]}
headers = {
    
    "Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/ch_pp-ocrv3"
r = requests.post(url=url, headers=headers, data=json.dumps(data))

# 打印预测结果
print(r.json())

ここに画像の説明を挿入

  • カールテストリクエスト
curl --location --request POST 'http://127.0.0.1:8866/predict/ch_pp-ocrv3' \
--header 'Content-Type: application/json' \
--data-raw '{"images":["图片的base64内容,不需前面的base64标识"]}'

結果は以下を返します:

{
    
    "msg":[{
    
    "data":[{
    
    "confidence":0.9314630627632141,"text":"(paddle env][root@M-1-2-centos","text_box_position":[[6,10],[231,10],[231,23],[6,23]]},{
    
    "confidence":0.9092367887496948,"text":"ppocr imgl# hub serving start -m chpp-ocrv3 --use_gpu","text_box_position":[[227,10],[612,12],[612,25],[227,23]]},{
    
    "confidence":0.939938485622406,"text":"[2022-05-30 19:49:34 +0800]","text_box_position":[[5,25],[191,25],[191,38],[5,38]]},{
    
    "confidence":0.8236835598945618,"text":"[28320]","text_box_position":[[200,26],[246,26],[246,37],[200,37]]},{
    
    "confidence":0.6653339862823486,"text":"LINFO]","text_box_position":[[256,26],[295,26],[295,37],[256,37]]},{
    
    "confidence":0.842379093170166,"text":"starting gunicorn 2o.1.0","text_box_position":[[301,26],[474,26],[474,38],[301,38]]},{
    
    "confidence":0.939938485622406,"text":"[2022-05-30 19:49:34 +0800]","text_box_position":[[5,40],[191,40],[191,53],[5,53]]},{
    
    "confidence":0.8367705345153809,"text":"[28320]","text_box_position":[[200,41],[247,41],[247,52],[200,52]]},{
    
    "confidence":0.86468505859375,"text":"[INFO]","text_box_position":[[257,41],[297,41],[297,52],[257,52]]},{
    
    "confidence":0.9211856722831726,"text":"Listening at: http://0.0.0.0:8866 (28320)","text_box_position":[[302,40],[589,40],[589,53],[302,53]]},{
    
    "confidence":0.9346868395805359,"text":"[2022-05-3019:49:34+0800]","text_box_position":[[4,55],[191,54],[191,67],[4,68]]},{
    
    "confidence":0.9421297311782837,"text":"[28320]","text_box_position":[[199,55],[247,55],[247,68],[199,68]]},{
    
    "confidence":0.9394086003303528,"text":"[INFO]","text_box_position":[[256,55],[298,55],[298,68],[256,68]]},{
    
    "confidence":0.9321832656860352,"text":"Using worker: sync","text_box_position":[[302,56],[430,56],[430,68],[302,68]]},{
    
    "confidence":0.9334865808486938,"text":"[2022-05-30 19:49:34 +0800]","text_box_position":[[4,70],[191,70],[191,83],[4,83]]},{
    
    "confidence":0.8994974493980408,"text":"[INFO] ","text_box_position":[[256,70],[305,70],[305,84],[256,84]]},{
    
    "confidence":0.8855429887771606,"text":"[28324]","text_box_position":[[200,71],[246,71],[246,82],[200,82]]},{
    
    "confidence":0.9438435435295105,"text":"Booting worker with pid: 28324","text_box_position":[[300,70],[515,69],[515,83],[300,84]]}],"save_path":""}],"results":"","status":"000"}

このように普通に使えるのですが、認識速度は100~300ms程度と非常に速いです。
公式デプロイメントチュートリアル: https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.5/deploy/hubserving/readme.md

Paddle Serving による OCR 認識サービスの導入

Hubserving の展開と比較して、PaddleServing には次の利点があります。

  • クライアントとサーバー間の高い同時実行性と効率的な通信をサポートします。
  • モデル管理、オンライン読み込み、オンライン A/B テストなどの産業グレードのサービス機能をサポートします。
  • C++、Python、Java など、クライアントを開発するための複数のプログラミング言語をサポート

まず PaddleOCR 環境を準備します。ここで github コードをプルすると非常に時間がかかります。最初に科学的にダウンロードしてから、サーバーにアップロードできます。

git clone https://github.com/PaddlePaddle/PaddleOCR --depth=1

作業ディレクトリに

cd PaddleOCR/deploy/pdserving/

PaddleServing の動作環境をインストールします。手順は次のとおりです。

# 安装serving,用于启动服务
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/paddle_serving_server_gpu-0.8.3.post102-py3-none-any.whl
pip3 install paddle_serving_server_gpu-0.8.3.post102-py3-none-any.whl

# 安装client,用于向服务发送请求
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/paddle_serving_client-0.8.3-cp38-none-any.whl
pip3 install paddle_serving_client-0.8.3-cp38-none-any.whl

# 安装serving-app
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/paddle_serving_app-0.8.3-py3-none-any.whl
pip3 install paddle_serving_app-0.8.3-py3-none-any.whl
  • モデル変換

サービスのデプロイに PaddleServing を使用する場合、保存された推論モデルを、サービス用にデプロイしやすいモデルに変換する必要があります。

まずはPP-OCRの推論モデルをダウンロードします

# 下载并解压 OCR 文本检测模型
wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar -O ch_PP-OCRv3_det_infer.tar && tar -xf ch_PP-OCRv3_det_infer.tar
# 下载并解压 OCR 文本识别模型
wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_rec_infer.tar -O ch_PP-OCRv3_rec_infer.tar &&  tar -xf ch_PP-OCRv3_rec_infer.tar

次に、インストールされた paddle_serving_client を使用して、ダウンロードした推論モデルをサーバー デプロイしやすいモデル形式に変換します。

# 转换检测模型
python3 -m paddle_serving_client.convert --dirname ./ch_PP-OCRv3_det_infer/ \
                                         --model_filename inference.pdmodel          \
                                         --params_filename inference.pdiparams       \
                                         --serving_server ./ppocr_det_v3_serving/ \
                                         --serving_client ./ppocr_det_v3_client/

# 转换识别模型
python3 -m paddle_serving_client.convert --dirname ./ch_PP-OCRv3_rec_infer/ \
                                         --model_filename inference.pdmodel          \
                                         --params_filename inference.pdiparams       \
                                         --serving_server ./ppocr_rec_v3_serving/  \
                                         --serving_client ./ppocr_rec_v3_client/

検出モデルの変換が完了すると、現在のフォルダーに ppocr_det_v3_serving および ppocr_det_v3_client の追加フォルダーが次の形式で作成されます。

|- ppocr_det_v3_serving/
  |- __model__  
  |- __params__
  |- serving_server_conf.prototxt  
  |- serving_server_conf.stream.prototxt

|- ppocr_det_v3_client
  |- serving_client_conf.prototxt  
  |- serving_client_conf.stream.prototxt
  • Paddle Serving パイプラインのデプロイメント
# 启动服务,运行日志保存在log.txt
nohup python3 -u web_service.py > log.log 2>&1 &

ここに画像の説明を挿入
実行ログにエラーがなければ、起動は成功です。
ここに画像の説明を挿入
その後、提供されたクライアント コードを使用して、
ここに画像の説明を挿入
進行状況を表示するテストをリクエストできます。

ps -ef|grep python

プロセスを閉じる

kill -9 19913

ビュー・ログ

tail -f 1000 log.log

ポート占有状況の確認方法

$: netstat -anp | grep 8888
tcp        0      0 127.0.0.1:8888          0.0.0.0:*               LISTEN      13404/python3       
tcp        0      1 172.17.0.10:34036       115.42.35.84:8888       SYN_SENT    14586/python3 

プロセスを強制的に強制終了します: pid によって

$: kill -9 13404
$: kill -9 14586
$: netstat -anp | grep 8888
$:
  • HTTPリクエストテスト

リクエストアドレス:http://127.0.0.1:9998/ocr/
prediction リクエストメソッド:json
リクエストパラメータ:{"key": "image", "value": "画像のbase64"}

  • カールリクエストテスト
curl --location --request POST 'http://127.0.0.1:9998/ocr/prediction' \

--header 'Content-Type: application/json' \

--data-raw '{"key":"image","value":"图片的base64"}'

返されるデータ形式:

{
    
    
"err_no": 0,
"err_msg": "",
"key": [
    "result"
],
"value": [
    "[[('(padde env)[root@M-1-2-centoppocrimghub servingstart -m chpp-ocrv3--usegpu', 0.84638405), [[5.0, 10.0], [611.0, 12.0], [611.0, 24.0], [5.0, 22.0]]], [('[2022-05-3019:49:34+0800][28320】[INF0]Startingqunicorm20.1.', 0.81580645), [[5.0, 25.0], [472.0, 25.0], [472.0, 38.0], [5.0, 37.0]]], [('[2022-05-3019:49:34+0800][28320][INF0]Listeningat:http://0.0.0.0:8866(28320)', 0.84695405), [[5.0, 40.0], [589.0, 40.0], [589.0, 54.0], [5.0, 54.0]]], [('[2022-05-319:49:34+0800][28320】[INF0]Usingworker:sync', 0.7949861), [[5.0, 54.0], [430.0, 56.0], [430.0, 68.0], [5.0, 66.0]]], [('[2022-05-319:49:34+080】[28324】[INFO】Bootingworkerwith pid:28324', 0.85473406), [[4.0, 70.0], [515.0, 70.0], [515.0, 84.0], [4.0, 84.0]]]]"
],
"tensors": []
}

これで完了し、正常に使用できます。他の言語呼び出しを提供する場合は、その公式ドキュメントを確認できます。 公式
デプロイメント チュートリアル: https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.5/deploy/pdserving/README_CN.md

エピローグ

これの導入は比較的簡単で、Paddle の公式ドキュメントは非常に充実していますが、一部の特殊なテキスト認識については、自分でカスタマイズしてトレーニングする必要があります。

おすすめ

転載: blog.csdn.net/loutengyuan/article/details/126530740