1
0

recognize_local.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. """
  4. 使用自建的接口识别来自本地的验证码
  5. 需要配置参数:
  6. remote_url = "https://www.xxxxxxx.com/getImg" 验证码链接地址
  7. rec_times = 1 识别的次数
  8. """
  9. import datetime
  10. import requests
  11. from io import BytesIO
  12. import time
  13. import json
  14. import os
  15. from log_ware import LogWare
  16. logger = LogWare().get_logger()
  17. with open("conf/sample_config.json", "r") as f:
  18. sample_conf = json.load(f)
  19. # 配置参数
  20. env = sample_conf["env"] # 环境
  21. local_save_path = sample_conf["local_image_dir"] # 本地识别后的保存路径
  22. local_origin_image_dir = sample_conf["local_origin_image_dir"] # 本地待识别图片的路径
  23. image_suffix = sample_conf["image_suffix"] # 文件后缀
  24. webserver_recognize_url = sample_conf['webserver_recognize_url'] # 识别服务器IP
  25. webserver_recognize_port = sample_conf['webserver_recognize_port'] # 识别服务器端口
  26. def recognize_captcha(test_path, save_path, image_suffix):
  27. image_file_name = 'captcha.{}'.format(image_suffix)
  28. with open(test_path, "rb") as f:
  29. content = f.read()
  30. # 识别
  31. s = time.time()
  32. url = "http://{}:{}/b".format(webserver_recognize_url, str(webserver_recognize_port))
  33. files = {'image_file': (image_file_name, BytesIO(content), 'application')}
  34. r = requests.post(url=url, files=files)
  35. e = time.time()
  36. # 识别结果
  37. logger.debug("本地图片,调用本地识别服务,接口响应: %s", r.text)
  38. predict_text = json.loads(r.text)["value"]
  39. now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  40. logger.debug("【%s】 耗时:%s ms 预测结果:%s", now_time, int((e - s) * 1000), predict_text)
  41. if env.lower() == 'dev':
  42. # 保存文件
  43. img_name = "{}_{}.{}".format(predict_text, str(time.time()).replace(".", ""), image_suffix)
  44. path = os.path.join(save_path, img_name)
  45. with open(path, "wb") as f:
  46. f.write(content)
  47. logger.debug("============== local recognized end ==============")
  48. def main():
  49. files = os.listdir(local_origin_image_dir)
  50. if len(files) <= 0:
  51. logger.debug("%s,%s", local_origin_image_dir, "没有任何文件")
  52. logger.debug("...没有任何文件")
  53. return
  54. for file in files:
  55. test_path = "{}{}".format(local_origin_image_dir, file)
  56. logger.debug("test_path: %s", test_path)
  57. recognize_captcha(test_path, local_save_path, image_suffix)
  58. if __name__ == '__main__':
  59. main()