webserver_recognize_api.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # -*- coding: UTF-8 -*-
  2. """
  3. 通过服务接口方式识别验证码
  4. 构建flask接口服务
  5. 接收 files={'image_file': ('captcha.jpg', BytesIO(bytes), 'application')} 参数识别验证码
  6. 需要配置参数:
  7. image_height = 40
  8. image_width = 80
  9. max_captcha = 4
  10. """
  11. import json
  12. from io import BytesIO
  13. import os
  14. from cnnlib.recognition_object import Recognizer
  15. import time
  16. from flask import Flask, request, jsonify, Response
  17. from PIL import Image
  18. from log_ware import LogWare
  19. logger = LogWare().get_logger()
  20. # 默认使用CPU
  21. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  22. os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
  23. with open("conf/sample_config.json", "r") as f:
  24. sample_conf = json.load(f)
  25. # 配置参数
  26. env = sample_conf["env"] # 环境
  27. image_height = sample_conf["image_height"]
  28. image_width = sample_conf["image_width"]
  29. max_captcha = sample_conf["max_captcha"]
  30. api_image_dir = sample_conf["api_image_dir"]
  31. model_save_dir = sample_conf["model_save_dir"]
  32. image_suffix = sample_conf["image_suffix"] # 文件后缀
  33. use_labels_json_file = sample_conf['use_labels_json_file']
  34. webserver_recognize_url = sample_conf['webserver_recognize_url'] # 识别服务器IP
  35. webserver_recognize_port = sample_conf['webserver_recognize_port'] # 识别服务器端口
  36. if use_labels_json_file:
  37. with open("tools/labels.json", "r") as f:
  38. char_set = f.read().strip()
  39. else:
  40. char_set = sample_conf["char_set"]
  41. # Flask对象
  42. app = Flask(__name__)
  43. basedir = os.path.abspath(os.path.dirname(__file__))
  44. # 生成识别对象,需要配置参数
  45. recognizer = Recognizer(image_height, image_width, max_captcha, char_set, model_save_dir)
  46. # 如果你需要使用多个模型,可以参照原有的例子配置路由和编写逻辑
  47. # Q = Recognizer(image_height, image_width, max_captcha, char_set, model_save_dir)
  48. def response_headers(content):
  49. resp = Response(content)
  50. resp.headers['Access-Control-Allow-Origin'] = '*'
  51. return resp
  52. @app.route('/b', methods=['POST'])
  53. def up_image():
  54. if request.method == 'POST' and request.files.get('image_file'):
  55. timec = str(time.time()).replace(".", "")
  56. file = request.files.get('image_file')
  57. img = file.read()
  58. img = BytesIO(img)
  59. img = Image.open(img, mode="r")
  60. # username = request.form.get("name")
  61. logger.debug("接收图片尺寸: %s", img.size)
  62. s = time.time()
  63. value = recognizer.rec_image(img)
  64. e = time.time()
  65. logger.debug("识别结果: %s", value)
  66. if env.lower() == 'dev':
  67. # 保存图片
  68. logger.debug("保存图片: %s%s_%s.%s", api_image_dir, value, timec, image_suffix)
  69. file_name = "{}_{}.{}".format(value, timec, image_suffix)
  70. file_path = os.path.join(api_image_dir + file_name)
  71. img.save(file_path)
  72. result = {
  73. 'time': timec, # 时间戳
  74. 'value': value, # 预测的结果
  75. 'speed_time(ms)': int((e - s) * 1000) # 识别耗费的时间
  76. }
  77. img.close()
  78. return jsonify(result)
  79. else:
  80. content = json.dumps({"error_code": "1001", "error_msg": "验证码识别出错"})
  81. resp = response_headers(content)
  82. return resp
  83. if __name__ == '__main__':
  84. app.run(
  85. host=webserver_recognize_url,
  86. port=webserver_recognize_port,
  87. debug=True
  88. )