Skip to content

Commit

Permalink
use fastapi to replace tornado
Browse files Browse the repository at this point in the history
  • Loading branch information
lewangdev committed Dec 15, 2021
1 parent 9c39301 commit 46fbce2
Show file tree
Hide file tree
Showing 11 changed files with 90 additions and 62 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
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)
10 changes: 4 additions & 6 deletions paddlewebocr/main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
from typing import Optional

import os
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
import uvicorn
import os

from route import router
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")
app.include_router(router)

if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
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)
40 changes: 0 additions & 40 deletions paddlewebocr/route.py

This file was deleted.

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'))))
Binary file added tests/img1.png
Loading
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'))
4 changes: 4 additions & 0 deletions webui/vue.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ module.exports = {
'/api':{
target: 'http://localhost:8000',
changeOrigin:true,
pathRewrite: {
'^/api': '/api' // rewrite path
}

}
}

Expand Down

0 comments on commit 46fbce2

Please sign in to comment.