flaskOcrDz.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # File : flaskOcrDz.py
  4. # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
  5. # Date : 2021/11/1
  6. import json
  7. from flask import Flask, jsonify, request,Response
  8. import requests
  9. import ddddocr
  10. ocr = ddddocr.DdddOcr()
  11. app = Flask(__name__)
  12. app.config["JSON_AS_ASCII"] = False # jsonify返回的中文正常显示
  13. @app.route("/",methods=['GET'])
  14. def index():
  15. return '欢迎使用简单验证码文字识别,海阔视界道长专用'
  16. def hexStringTobytes(str):
  17. str = str.replace(" ", "")
  18. print(str)
  19. return bytes.fromhex(str)
  20. def bytesToHexString(bs):
  21. return ''.join(['%02X ' % b for b in bs])
  22. class LocalOcr:
  23. def __init__(self,file=None,url='http://127.0.0.1:10000'):
  24. self.file = file
  25. self.url = url
  26. self.yzm = self.yzm_ocr(0)
  27. def read(self):
  28. return self.yzm
  29. def yzm_ocr(self,count=0):
  30. try:
  31. r = requests.post(self.url, data=self.file,timeout=(0.5,2))
  32. yzm = r.text
  33. return yzm
  34. except:
  35. if count < 3:
  36. count += 1
  37. return self.yzm_ocr(count)
  38. else:
  39. return ""
  40. def ocr2(hex):
  41. if type(hex) == list:
  42. hex = ''.join(hex)
  43. img_bytes = hexStringTobytes(hex)
  44. # print(img_bytes)
  45. # with open('1.png','wb+') as f:
  46. # f.write(img_bytes)
  47. dm_url = 'http://dm.mudery.com:10000'
  48. im_ocr = LocalOcr(img_bytes, dm_url)
  49. yzm = im_ocr.read()
  50. ret = {'msg': 'ok','ret':yzm,'code':0,'detail':'验证码识别成功'}
  51. print(ret)
  52. return jsonify(ret)
  53. def docr(hex):
  54. if type(hex) == list:
  55. hex = ''.join(hex)
  56. img_bytes = hexStringTobytes(hex)
  57. try:
  58. img_str = img_bytes.decode("latin1")
  59. if img_str.find('html') > -1:
  60. ret = {'msg': '拜托,我收到你传过来的数据是个网页而不是图片,麻烦解密后把图片的hex给我', 'ret': img_str[:500], 'code': -1, 'detail': '图片识别失败'}
  61. return jsonify(ret)
  62. else:
  63. res = ocr.classification(img_bytes)
  64. ret = {'msg': 'ok', 'ret': res, 'code': 0, 'detail': '图片识别成功'}
  65. # print(ret)
  66. return jsonify(ret)
  67. except Exception as e:
  68. # print(f'{e}')
  69. ret = {'msg': 'error', 'ret': f'{e}', 'code': -2, 'detail': '发生了意外的错误'}
  70. return ret
  71. @app.route("/api/ocr",methods=['GET', 'POST'])
  72. def ocr_fast():
  73. args = {}
  74. try:
  75. ctp = request.content_type
  76. if request.method == 'POST':
  77. if ctp.find('application/json') > -1:
  78. try:
  79. args = request.json
  80. except Exception as e:
  81. # args = request.get_data(as_text=True)
  82. args = {}
  83. else:
  84. args = request.form
  85. elif request.method == 'GET':
  86. args = request.args
  87. if not args.get('hex'):
  88. return '缺少必传参数:hex!'
  89. except Exception as e:
  90. return jsonify({'msg':'非法调用','code':'-1'})
  91. # print(args.get('hex'))
  92. # return ocr2(args.get('hex'))
  93. return docr(args.get('hex'))
  94. @app.route("/api/hex2img",methods=['GET'])
  95. def ocr_hex2img():
  96. try:
  97. args = request.args
  98. if not args.get('hex'):
  99. return '缺少必传参数:hex!'
  100. except Exception as e:
  101. return jsonify({'msg':'非法调用','code':'-1'})
  102. # print(args.get('hex'))
  103. # return ocr2(args.get('hex'))
  104. hex = args.get('hex')
  105. if type(hex) == list:
  106. hex = ''.join(hex)
  107. img_bytes = hexStringTobytes(hex)
  108. resp = Response(img_bytes, mimetype='image/jpeg')
  109. return resp
  110. @app.route("/api/ocr_img",methods=['POST'])
  111. def ocr_img_fast():
  112. # print(request.values)
  113. # print(request.files)
  114. # print(request.data)
  115. try:
  116. img_bytes = request.data
  117. ret = ocr.classification(img_bytes)
  118. return ret
  119. # return jsonify({'ret':ret,'code':0,'msg':'识别完毕'})
  120. except Exception as e:
  121. return ''
  122. # return jsonify({'msg':'请求出错','code':-1,'detail':f'{e}'})
  123. def test():
  124. pic = 'yzm1.png'
  125. # pic = '2.png'
  126. with open(pic, 'rb') as f:
  127. img_bytes = f.read()
  128. res = ocr.classification(img_bytes)
  129. print(res)
  130. if __name__ == '__main__':
  131. app.run(host="0.0.0.0", port=9000)
  132. # test()