Skip to content

Commit

Permalink
Merge pull request PaddlePaddle#1 from lewangdev/fastapi
Browse files Browse the repository at this point in the history
Fastapi
  • Loading branch information
lewangdev committed Dec 15, 2021
2 parents 38590ff + 46fbce2 commit aa96398
Show file tree
Hide file tree
Showing 15 changed files with 109 additions and 155 deletions.
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ docker run -d -p 8080:8080 -v ${PWD}/logs:/app/logs --name paddlewebocr paddlewe

``` python
import requests
url = 'http://192.168.52.65:8080/api/ocr'
url = 'http://127.0.0.1:8080/api/ocr'
img1_file = {
'file': open('img1.png', 'rb')
'img_upload': open('img1.png', 'rb')
}
res = requests.post(url=url, data={'compress': 0}, files=img1_file)
```
Expand All @@ -97,14 +97,18 @@ res = requests.post(url=url, data={'compress': 0}, files=img1_file)
``` python
import requests
import base64


def img_to_base64(img_path):
with open(img_path, 'rb')as read:
b64 = base64.b64encode(read.read())
return b64

url = 'http://192.168.52.65:8080/api/ocr'


url = 'http://127.0.0.1:8080/api/ocr'
img_b64 = img_to_base64('./img1.png')
res = requests.post(url=url, data={'img': img_b64})
res = requests.post(url=url, data={'img_b64': img_b64})

```

## 效果展示
Expand Down
Empty file added paddlewebocr/__init__.py
Empty file.
4 changes: 2 additions & 2 deletions paddlewebocr/jsonencoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import numpy


class MyEncoder(json.JSONEncoder):
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, numpy.integer):
return int(obj)
Expand All @@ -11,4 +11,4 @@ def default(self, obj):
elif isinstance(obj, numpy.ndarray):
return obj.tolist()
else:
return super(MyEncoder, self).default(obj)
return super(NumpyEncoder, self).default(obj)
46 changes: 8 additions & 38 deletions paddlewebocr/main.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,13 @@
import log
import os
import sys
import logging
from tornado.options import define, options
import tornado.web
import tornado.httpserver
import tornado.ioloop
from tornado.web import StaticFileHandler
from webhandler import IndexHandler, OcrHandler
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
import uvicorn

BASE_PATH = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_PATH)


logger = logging.getLogger(log.LOGGER_ROOT_NAME + '.' + __name__)

current_path = os.path.dirname(__file__)
settings = dict(
static_path=os.path.join(current_path, "..", "webui", "dist")
)


def make_app():
return tornado.web.Application([
(r"/api/ocr", OcrHandler),
(r"/", IndexHandler),
(r"/(.*)", StaticFileHandler,
{"path": os.path.join(current_path, "..", "webui", "dist"), "default_filename": "index.html"}),

], **settings)
from router import router

app = FastAPI()
app.include_router(router, prefix="/api")
app.mount("/", StaticFiles(directory=os.path.join(".", "webui", "dist"), html=True), name="static")

if __name__ == "__main__":
define("addr", default='0.0.0.0', type=str, help='指定运行时绑定的地址')
define("port", default=8080, type=int, help='指定运行时端口号')
tornado.options.parse_command_line()
port = options.port
addr = options.addr
app = make_app()
app.listen(port, addr)
logger.info("Application is running on: http://%s:%s/" % (addr, port))
tornado.ioloop.IOLoop.current().start()
uvicorn.run(app, host="0.0.0.0", port=8080)
2 changes: 1 addition & 1 deletion paddlewebocr/ocr.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@
}


def text_ocr(img: Image, ocr_model: str):
def text_ocr(img: Image, ocr_model: str) -> list:
ocr = OCR.get(ocr_model, OCR["ch_ppocr_mobile_v2.0_xx"])
return ocr.ocr(np.array(img), cls=False)
39 changes: 39 additions & 0 deletions paddlewebocr/router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import time
import json
from fastapi import APIRouter, File, UploadFile, Form, Response, HTTPException
from jsonencoder import NumpyEncoder
from util import *
from ocr import text_ocr

router = APIRouter()


@router.post('/ocr', tags=['ocr'])
async def ocr(img_upload: UploadFile = File(None),
img_b64: str = Form(None),
compress_size: int = Form(None),
ocr_model: str = Form(None)):
start_time = time.time()

if img_upload is not None:
img = convert_bytes_to_image(img_upload.file.read())
elif img_b64 is not None:
img = convert_b64_to_image(img_b64)
else:
return Response(media_type="application/json", status_code=400,
content=json.dumps(dict(code=4001, msg='没有传入参数')))

img = rotate_image(img)
img = img.convert("RGB")
img = compress_image(img, compress_size)

texts = text_ocr(img, ocr_model)
img_drawed = draw_box_on_image(img.copy(), texts)
img_drawed_b64 = convert_image_to_b64(img_drawed)

data = {'code': 0, 'msg': '成功',
'data': {'img_detected': 'data:image/jpeg;base64,' + img_drawed_b64,
'raw_out': list(map(lambda x: [x[0], x[1][0], x[1][1]], texts)),
'speed_time': round(time.time() - start_time, 2)}}
json_str = json.dumps(data, cls=NumpyEncoder, ensure_ascii=False).encode('utf-8')
return Response(media_type="application/json", content=json_str)
16 changes: 8 additions & 8 deletions paddlewebocr/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
MAX_COMPRESS_SIZE = 1600


def compress_image(img: Image, compress_size: int):
def compress_image(img: Image, compress_size: int) -> Image:
if compress_size is None or compress_size <= 0:
return img

Expand All @@ -19,7 +19,7 @@ def compress_image(img: Image, compress_size: int):
return img


def rotate_image(img: Image):
def rotate_image(img: Image) -> Image:
if hasattr(img, '_getexif') and img._getexif() is not None:
orientation = 274
exif = dict(img._getexif().items())
Expand All @@ -33,7 +33,7 @@ def rotate_image(img: Image):
return img


def draw_box_on_image(img: Image, texts: list):
def draw_box_on_image(img: Image, texts: list) -> Image:
img_draw = ImageDraw.Draw(img)
colors = ['red', 'green', 'blue', "purple"]
for line in texts:
Expand All @@ -44,23 +44,23 @@ def draw_box_on_image(img: Image, texts: list):
return img


def convert_image_to_bytes(img: Image):
def convert_image_to_bytes(img: Image) -> bytes:
img_byte = BytesIO()
img.save(img_byte, format='JPEG')
return img_byte.getvalue()


def b64encode(bytes_data: bytes):
def b64encode(bytes_data: bytes) -> str:
return base64.b64encode(bytes_data).decode('utf8')


def convert_image_to_b64(img: Image):
def convert_image_to_b64(img: Image) -> str:
return b64encode(convert_image_to_bytes(img))


def convert_bytes_to_image(bytes_data: bytes):
def convert_bytes_to_image(bytes_data: bytes) -> Image:
return Image.open(BytesIO(bytes_data))


def convert_b64_to_image(b64_data: str):
def convert_b64_to_image(b64_data: str) -> Image:
return Image.open(BytesIO(base64.b64decode(b64_data.encode('utf8'))))
96 changes: 0 additions & 96 deletions paddlewebocr/webhandler.py

This file was deleted.

8 changes: 8 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
black
mypy
flake8
requests
pytest
pytest-cov
isort
autoflake
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
paddlepaddle==2.2.0
paddleocr==2.3.0.2
tornado==6.0.2
fastapi
python-multipart
uvicorn
Binary file added tests/img1.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions tests/test_img_b64.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import requests
import base64


def img_to_base64(img_path):
with open(img_path, 'rb')as read:
b64 = base64.b64encode(read.read())
return b64


url = 'http://127.0.0.1:8000/api/ocr'
img_b64 = img_to_base64('./img1.png')
res = requests.post(url=url, data={'img_b64': img_b64})

print(res.content.decode('utf-8'))
8 changes: 8 additions & 0 deletions tests/test_img_upload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import requests
url = 'http://127.0.0.1:8000/api/ocr'
img1_file = {
'img_upload': open('img1.png', 'rb')
}
res = requests.post(url=url, data={'compress': 0}, files=img1_file)

print(res.content.decode('utf-8'))
6 changes: 3 additions & 3 deletions webui/src/views/Index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,12 @@ export default {
const formData = new FormData()
this.fileList.forEach(file => {
formData.append('file', file)
formData.append('img_upload', file)
})
if (this.$data.hiddenCompressBox === true){
formData.append('compress',0)
formData.append('compress_size',0)
}else{
formData.append('compress',this.$data.comporessSize)
formData.append('compress_size',this.$data.comporessSize)
}
formData.append('ocr_model',this.$data.ocrModel)
Expand Down
6 changes: 5 additions & 1 deletion webui/vue.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ module.exports = {
devServer: {
proxy:{
'/api':{
target: 'http://localhost:8080',
target: 'http://localhost:8000',
changeOrigin:true,
pathRewrite: {
'^/api': '/api' // rewrite path
}

}
}

Expand Down

0 comments on commit aa96398

Please sign in to comment.