-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
56 lines (43 loc) · 1.33 KB
/
server.py
File metadata and controls
56 lines (43 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import json
from functools import lru_cache
import cv2
import easyocr
import numpy as np
from fastapi import FastAPI, File, Query, UploadFile
from fastapi.responses import JSONResponse
app = FastAPI(title='easyocr.js Python reference')
@lru_cache(maxsize=8)
def _get_reader(langs_key: str, gpu: bool) -> easyocr.Reader:
# Cache readers; init is expensive.
langs = json.loads(langs_key)
return easyocr.Reader(langs, gpu=gpu)
def _format_results(results):
return [
{
'box': [[float(pt[0]), float(pt[1])] for pt in bbox],
'text': text,
'confidence': float(prob),
}
for (bbox, text, prob) in results
]
@app.get('/health')
def health():
return {'ok': True}
@app.post('/readtext')
async def readtext(
image: UploadFile = File(...),
lang: list[str] = Query(default=['en']),
gpu: bool = Query(default=False),
):
content = await image.read()
arr = np.frombuffer(content, dtype=np.uint8)
mat = cv2.imdecode(arr, cv2.IMREAD_COLOR)
if mat is None:
return JSONResponse(status_code=400, content={'error': 'Unable to decode image'})
reader = _get_reader(json.dumps(lang), gpu)
results = reader.readtext(mat)
return {
'formatVersion': 1,
'image': image.filename,
'results': _format_results(results),
}