vue页面axios上传图片到后台,python处理上传及识别,识别记录插入数据库。
代码还没拆分,后续优化时候再拆。
server.py
```python
#coding=utf8
import web,sys,os #引入web.py的包
class MyApplication(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
#定义web应用的路由规则
urls = (
'/discern/word', 'word' # 解析图片
)
class word:
def POST(self):
import time,random,json
from PIL import Image
from paddleocr import PaddleOCR, draw_ocr
from db_config import db_config
year = time.strftime('%Y',time.localtime(time.time()))
month = time.strftime('%m',time.localtime(time.time()))
aiBaseDir = os.path.realpath('./../../server/upload/ai/'+ year+'/'+ month) # 上传的原始图片基础路径 dir/ai/2020/12
aiResultDir = os.path.realpath('./../../server/upload/airesult/'+ year+'/'+ month) # 识别之后的结果图片基础路径 dir/airesult/2020/12
if not os.path.exists(aiBaseDir):
os.makedirs( aiBaseDir )
if not os.path.exists(aiResultDir):
os.makedirs( aiResultDir )
inp = web.input(myfile={},type="") # post的值
discernType = inp.type #识别的类型
#上传图片
filename = str(time.time()) + str(random.randint(11111,999999)) + inp['myfile'].filename[inp['myfile'].filename.rfind('.'):] # 文件名
dbImgUrl = '/' + year + '/' + month + '/' + filename # 数据库中存的图片路径 /2020/12/a.jpg
baseFullPath = aiBaseDir +'/'+ filename #上传的文件全路径
resultFullPath = aiResultDir +'/'+ filename #识别之后的文件全路径
fout = open(baseFullPath,'wb')
fout.write(inp.myfile.file.read())
fout.write(inp.myfile.value)
fout.close()
ocr = PaddleOCR(use_angle_cls=True, langs="ch")
result = ocr.ocr(baseFullPath, cls=True)
# for line in result:
# print(line)
# print(result)
image = Image.open(baseFullPath).convert('RGB')
boxes = [line[0] for line in result]
txts = [line[1][0] for line in result]
scores = [line[1][1] for line in result]
imShow = draw_ocr(image, boxes, txts, scores, font_path=os.path.realpath('./../ai/simfang.ttf'))
imShow = Image.fromarray(imShow)
imShow.save(resultFullPath)
web.header('Content-Type','text/json; charset=utf-8', unique=True) #防止中文乱码
web.header("Access-Control-Allow-Origin", "*", unique=True) #允许跨域
db = web.database(dbn=db_config['dbn'],host=db_config['host'], user=db_config['user'], pw=db_config['pwd'], db=db_config['database'])
content = []
for i in result:
a = {}
a['title'] = str(i[1][0])
a['percent'] = str(i[1][1])
a['position'] = i[0]
if a['title']:
content.append(a)
insertId = db.insert("T_AI_LOG",IMG = dbImgUrl,IMG_NAME=inp.myfile.filename,TYPE = discernType,CONTENT= json.dumps(content),DATE=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
if insertId:
return True
else:
return False
if __name__ == "__main__":
app = MyApplication(urls, globals())
app.run(port=6789)
```
安装nohup
yum install coreutils
后台启动脚本
nohup python3 server.py >/dev/null &