📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
clean the ocrweb folders
SWHLbfee26b609e8
diff --git a/ocrweb/main_redis.py b/ocrweb/main_redis.pydeleted file mode 100644index e7d9df4..0000000--- a/ocrweb/main_redis.py+++ /dev/null@@ -1,83 +0,0 @@-# !/usr/bin/env python-# -*- encoding: utf-8 -*--# @File: main.py-# @Author: Max-import base64-import json-import uuid-from pathlib import Path--import cv2-import numpy as np-import redis-from flask import Flask, render_template, request-from rq import Queue-from rq.job import Job---from task_redis import conn, detect_recognize---root_path = Path(__file__).resolve().parent---r = redis.Redis(host='localhost',- port=6379,- decode_responses=True)--# 建立与Redis server的连接并初始化一个队列-q = Queue(connection=conn, default_timeout=5000)--app = Flask(__name__)--# 设置上传文件大小-app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10M--[email protected]('/')-def index():- return render_template('index_redis.html')--[email protected]('/ocr', methods=['POST', 'GET'])-def ocr():- if request.method == 'POST':- # 获取图像数据- url_get = request.get_json()- url_get = str(url_get).split(',')[1]- image = base64.b64decode(url_get)- nparr = np.frombuffer(image, np.uint8)- image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)-- img_name = str(uuid.uuid4())-- image_directory = root_path / 'static' / 'images'- if not image_directory.exists():- image_directory.mkdir(parents=True, exist_ok=True)-- img_path = str(image_directory / f'{img_name}.jpg')- cv2.imwrite(img_path, image)-- # 压入队列- job = q.enqueue(detect_recognize,- args=(img_path, ),- result_ttl=5000)- return json.dumps({'job_id': job.get_id()})--[email protected]('/get_results', methods=['POST'])-def get_results():- job_id = request.get_json()- job = Job.fetch(job_id['job_id'], connection=conn)- if job.is_finished:- job_result = eval(job.result)- job_result['status'] = True- return json.dumps(job_result)- else:- return json.dumps({'status': False})---if __name__ == '__main__':- app.run(host='0.0.0.0', port=9003,- debug=False, processes=True,- threaded=True)diff --git a/ocrweb/readme.md b/ocrweb/readme.mdindex ec98dc5..1efc7df 100755--- a/ocrweb/readme.md+++ b/ocrweb/readme.md@@ -3,7 +3,6 @@```text.├── main.py-├── main_redis.py├── readme.md├── resources│ ├── bpocr.py@@ -17,10 +16,9 @@│ ├── css│ ├── images│ └── js-├── task.py # 单独开启rq worker时使用+├── task.py└── templates- ├── index.html- └── index_redis.html # 带有redis队列web界面+ └── index.html```#### Redis队列web界面使用步骤diff --git a/ocrweb/requirements.txt b/ocrweb/requirements.txtindex 57a6d87..b40ec4c 100644--- a/ocrweb/requirements.txt+++ b/ocrweb/requirements.txt@@ -1,11 +1,6 @@-onnxruntime==1.5.2-opencv-python==4.2.0.32-numpy-pyclipper-Shapely-imghdr-python==3.6.4-rq==1.7.0-redis==3.5.3-requests==2.25.1-Flask==1.1.2\ No newline at end of file+onnxruntime==1.7.0+opencv_python==4.5.1.48+six==1.15.0+pyclipper==1.2.1+numpy==1.19.1+Shapely==1.7.1diff --git a/ocrweb/task.py b/ocrweb/task.pyindex 80ae624..5449b9c 100644--- a/ocrweb/task.py+++ b/ocrweb/task.py@@ -13,7 +13,7 @@ import numpy as npfrom resources.bpocr import TextSystem, draw_text_det_res# 实例化模型-det_model_path = 'resources/models/ch_ppocr_server_v2.0_det_train.onnx'+det_model_path = 'resources/models/ch_ppocr_server_v2.0_det_infer.onnx'cls_model_path = 'resources/models/ch_ppocr_mobile_v2.0_cls_infer.onnx'rec_model_path = 'resources/models/ch_ppocr_mobile_v2.0_rec_infer.onnx'diff --git a/ocrweb/task_redis.py b/ocrweb/task_redis.pydeleted file mode 100644index d34c596..0000000--- a/ocrweb/task_redis.py+++ /dev/null@@ -1,71 +0,0 @@-# !/usr/bin/env python-# -*- encoding: utf-8 -*--# @File: worker.py-# @Time: 2021/03/07 20:29:32-# @Author: Max-import json-import base64-import cv2-import time-import numpy as np--import redis-from rq import Worker, Queue, Connection-from resources.bpocr import TextSystem, draw_text_det_res--listen = ['default']-redis_url = "redis://localhost:6379" # redis server 默认地址-conn = redis.from_url(redis_url)--# 实例化模型-det_model_path = 'resources/models/ch_ppocr_server_v2.0_det_infer.onnx'-cls_model_path = 'resources/models/ch_ppocr_mobile_v2.0_cls_infer.onnx'-rec_model_path = 'resources/models/ch_ppocr_mobile_v2.0_rec_infer.onnx'--text_sys = TextSystem(det_model_path,- rec_model_path,- use_angle_cls=True,- cls_model_path=cls_model_path)---def detect_recognize(image_path):- if isinstance(image_path, str):- image = cv2.imread(image_path)- elif isinstance(image_path, np.ndarray):- image = image_path-- t1 = time.time()- dt_boxes, rec_res, img = text_sys(image)- t2 = time.time()-- if dt_boxes is None or rec_res is None:- temp_rec_res = []- rec_res_data = json.dumps(temp_rec_res,- indent=2,- ensure_ascii=False)- elapse = 0- image = cv2.imencode('.jpg', img)[1]- img = str(base64.b64encode(image))[2:-1]- else:- temp_rec_res = []- for i, value in enumerate(rec_res):- temp_rec_res.append([i, value[0], value[1]])- temp_rec_res = np.array(temp_rec_res)- rec_res_data = json.dumps(temp_rec_res.tolist(),- indent=2,- ensure_ascii=False)-- det_im = draw_text_det_res(dt_boxes, img)- image = cv2.imencode('.jpg', det_im)[1]- img = str(base64.b64encode(image))[2:-1]-- elapse = f'{t2-t1:.3f}'- return json.dumps({'image': img,- 'elapse': elapse,- 'rec_res': rec_res_data})---if __name__ == '__main__':- with Connection(conn): # 建立与redis server的连接- worker = Worker(list(map(Queue, listen))) # 建立worker监听给定的队列- worker.work()\ No newline at end of filediff --git a/ocrweb/templates/index_redis.html b/ocrweb/templates/index_redis.htmldeleted file mode 100644index 8be5506..0000000--- a/ocrweb/templates/index_redis.html+++ /dev/null@@ -1,178 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <title>RapidOCR Demo</title>- <link rel=stylesheet type="text/css" href="{{url_for('static', filename='css/main.css')}}">-</head>-<body>- <h1 align="center">- RapidOCR Demo - <a href="https://github.com/znsoftm/RapidOCR" style="font-size: 14px;">欢迎Star</a>- </h1>- <div class="area">- <span class="uplodNote">图片文件类型支持PNG、JPG、JPEG、BMP,图片大小不超过10M。</span>- <span class="btn-gen" onclick="javascript:$('#upload_img').click();">点击上传</span>- <input type="file" style="display: none;" name="pic" id="upload_img"/>- <span id="status_upload" class="uplodNote"></span>- - <span class="btn-gen" onclick="javascript:$('#detect_recognize').click();" id="span_det_rec">开始识别</span>- <input type="button" style="display: none;" name="detect" id="detect_recognize"/>- </div>- <br/>- <div class="area">- <div class="leftarea" id="detectDiv">- <span class="span_title">文本检测结果:</span><br/><br/>- <div class="wrapper" id="wrapper" hidden></div>- <img id="detect_img" src=""/>- </div>-- <div class="rightarea" id="recogDiv">- <span id="rec_res" class="span_title">文本识别结果:</span>- <br/> <br/>- <table id="locTable" border="1" class="table" cellspacing="0" cellpadding="5"></table>- </div>- </div>- <script src="{{url_for('static', filename='js/jquery-3.0.0.min.js')}}"></script>- <script type="text/javascript">- // 页面加载时,执行- window.onload = function () {- $("#detect_img").attr("width", "");- $("#detect_img").attr("height", "");- $("#span_det_rec").hide();- }- let job_id;-- $("#upload_img").change(function(){- let file = document.getElementById("upload_img").files[0];-- // 判断图像格式是否匹配- let imageName = file.name;- let index = imageName.lastIndexOf(".");- let extName = imageName.substr(index + 1);- let imgArr = ["jpg", "bmp", "png", "jpeg"];- if (!(imgArr.includes(extName.toLocaleLowerCase()))){- alert("图像文件格式不支持!");- return;- }-- // 判断图像大小是否符合- let imageSize = file.size / 1024 / 1024;- if (imageSize >= 10) {- alert("图像大小超过10M!");- return;- }-- var reader = new FileReader();- reader.onload = function(e){- var upload_data = {"file": reader.result};- $.ajax(- {- url:"/ocr",- type:"POST",- data: JSON.stringify(upload_data),- contentType: "application/json; charset=UTF-8",- dataType: "json",-- beforeSend:function(){- $("#detect_img").attr("src", "");- $("#detect_img").hide();-- $("#status_upload").show();- $("#status_upload").html("上传中...");-- $("#rec_res").html("文本识别结果:");- $("#locTable").hide();- },- success:function (data) {- $("#detect_img").show();- $("#detect_img").attr("src", reader.result);- $("#detect_img").attr("width", "95%");- $("#detect_img").attr("height", "100%");-- $("#status_upload").hide();- $("#span_det_rec").show();-- job_id = data["job_id"];- }- }- );- }- reader.readAsDataURL(this.files[0])- });-- $("#detect_recognize").click(function() {- get_result();- })-- function get_result() {- $.ajax({- type: "POST",- url: "/get_results",- data: JSON.stringify({"job_id": job_id}),- contentType: "application/json; charset=UTF-8",- dataType: "json",- beforeSend:function(){- $("#wrapper").show();- },- success: function (data) {- if (data.status){- $("#wrapper").hide();- $("#span_det_rec").hide();-- if (data["image"]){- set_image(data["image"]);- }- if (data["elapse"]){- set_elapse(data["elapse"]);- }- if (data["rec_res"]){- set_result(data["rec_res"]);- $("#locTable").show();- }- }else{- $("#wrapper").show();- get_result();- }- }- })- }-- function set_image(image) {- $("#detect_img").attr("src", "data:image/jpeg;base64,"+ image);- $("#detect_img").show();- }-- function set_elapse(elapse) {- document.getElementById("rec_res").textContent = "文本识别结果(耗时:" + String(elapse) + "s):"- }-- function set_result(rec_res) {- var rec_res = JSON.parse(rec_res);- // 绘制整个结果表格- var data = "";- data += "<tr>" +- "<th bgcolor='#C0C0C0'>序号</th>" +- "<th bgcolor='#C0C0C0'>识别结果</th>" +- "<th bgcolor='#C0C0C0'>置信度</th>" +- "</tr>"- for (let i = 0; i < rec_res.length; i++) {- const element = rec_res[i];- let num = element[0];-- let rec_result = element[1];-- let score = Number(element[2]);- score = score.toFixed(4);-- data += "<tr>"- data += "<td>" + num + "</td>";- data += "<td align='left'>" + rec_result + "</td>";- data += "<td>" + score + "</td>";- data += "</tr>"- }- document.getElementById("locTable").innerHTML = data;- }- </script>-</body>-</html>\ No newline at end of file