captcha_interface.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import base64
  2. import json
  3. import logging
  4. import os
  5. import sys
  6. import time
  7. import traceback
  8. from glob import glob
  9. import numpy as np
  10. import cv2
  11. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  12. from flask import Flask, request
  13. from utils import request_post, bytes2np, np2bytes
  14. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  15. bdr_url = "http://127.0.0.1:17055/bdr"
  16. chd_url = "http://127.0.0.1:17056/chd"
  17. chr_url = "http://127.0.0.1:17057/chr"
  18. cho_url = "http://127.0.0.1:17058/cho"
  19. pzd_url = "http://127.0.0.1:17059/pzd"
  20. captcha_url = "http://127.0.0.1:17054/captcha"
  21. # 接口配置
  22. app = Flask(__name__)
  23. @app.route('/captcha', methods=['POST'])
  24. def captcha():
  25. start_time = time.time()
  26. logging.info("into captcha_interface captcha")
  27. try:
  28. # 接收网络数据
  29. if not request.form:
  30. logging.info("captcha no data!")
  31. return json.dumps({"success": False, "cost": time.time()-start_time})
  32. base64_data = request.form.get("base64pic")
  33. base64_data2 = request.form.get("base64pic2")
  34. code = int(request.form.get("code"))
  35. logging.info("code " + str(code))
  36. logging.info("captcha_interface get data time" + str(time.time()-start_time))
  37. if base64_data2 is None:
  38. result = get_captcha_result([base64_data], code)
  39. else:
  40. result = get_captcha_result([base64_data, base64_data2], code)
  41. if result is None:
  42. return json.dumps({"success": False, "cost": time.time()-start_time})
  43. return json.dumps({"predict": result, "success": True, "cost": time.time()-start_time})
  44. except:
  45. traceback.print_exc()
  46. return json.dumps({"success": False, "cost": time.time()-start_time})
  47. finally:
  48. logging.info("captcha interface finish time " + str(time.time()-start_time))
  49. def get_captcha_result(base64_list, code):
  50. """
  51. 验证码类型:
  52. 1: 拖拽还原拼图
  53. 2: 拖拽还原图片
  54. 3: 点击中文(带提示)
  55. 4: 点击中文(按语序)
  56. 5:
  57. :param base64_list: base64格式图片列表
  58. :param code: 验证码类型
  59. :return:
  60. """
  61. if code == 1:
  62. result = json.loads(request_post(pzd_url, prepare_data(base64_list[0], "pzd")))
  63. if result.get("success"):
  64. predict = result.get("data")
  65. logging.info("code " + str(code) + " pzd " + "predict " + str(predict))
  66. return predict
  67. elif code == 2:
  68. result = json.loads(request_post(bdr_url, prepare_data(base64_list[0], "bdr")))
  69. if result.get("success"):
  70. predict = result.get("data")
  71. logging.info("code " + str(code) + " bdr " + "predict " + str(predict))
  72. return predict
  73. elif code == 3:
  74. # detect tips
  75. result = json.loads(request_post(chd_url, prepare_data(base64_list[1], "chd2")))
  76. if result.get("success"):
  77. box_list_tips = result.get("data")
  78. else:
  79. return None
  80. logging.info("code " + str(code) + " chd2 " + "predict " + str(box_list_tips))
  81. # recognize tips
  82. result = json.loads(request_post(chr_url, prepare_data([base64_list[1], box_list_tips], "chr")))
  83. if result.get("success"):
  84. char_list_tips = result.get("data")
  85. else:
  86. return None
  87. logging.info("code " + str(code) + " chr " + "predict " + str(char_list_tips))
  88. if len(char_list_tips) != len(box_list_tips):
  89. return None
  90. # detect
  91. result = json.loads(request_post(chd_url, prepare_data(base64_list[0], "chd")))
  92. if result.get("success"):
  93. box_list = result.get("data")
  94. else:
  95. return None
  96. logging.info("code " + str(code) + " chd " + "predict " + str(box_list))
  97. # recognize
  98. result = json.loads(request_post(chr_url, prepare_data([base64_list[0], box_list], "chr")))
  99. if result.get("success"):
  100. char_list = result.get("data")
  101. else:
  102. return None
  103. logging.info("code " + str(code) + " chr " + "predict " + str(char_list))
  104. if len(char_list) != len(box_list):
  105. return None
  106. for c in char_list_tips:
  107. if c not in char_list:
  108. return None
  109. _dict = {char_list[i]: box_list[i] for i in range(len(box_list))}
  110. predict = [_dict.get(x) for x in char_list_tips]
  111. return predict
  112. elif code == 4:
  113. # detect
  114. result = json.loads(request_post(chd_url, prepare_data(base64_list[0], "chd")))
  115. if result.get("success"):
  116. box_list = result.get("data")
  117. else:
  118. return None
  119. logging.info("code " + str(code) + " chd " + "predict " + str(box_list))
  120. # recognize
  121. result = json.loads(request_post(chr_url, prepare_data([base64_list[0], box_list], "chr")))
  122. if result.get("success"):
  123. char_list = result.get("data")
  124. else:
  125. return None
  126. logging.info("code " + str(code) + " chr " + "predict " + str(char_list))
  127. if len(char_list) != len(box_list):
  128. return None
  129. # order
  130. result = json.loads(request_post(cho_url, prepare_data(char_list, "cho")))
  131. if result.get("success"):
  132. ordered_char_list = result.get("data")
  133. else:
  134. return None
  135. logging.info("code " + str(code) + " cho " + "predict " + str(ordered_char_list))
  136. _dict = {char_list[i]: box_list[i] for i in range(len(box_list))}
  137. predict = [_dict.get(x) for x in ordered_char_list]
  138. return predict
  139. return None
  140. def prepare_data(data, _type):
  141. if _type in ['pzd', 'bdr', 'chd']:
  142. return {"data": data}
  143. elif _type in ['chd2']:
  144. return {"data": data, "tips": 1}
  145. elif _type in ['chr']:
  146. image_base64 = data[0]
  147. box_list = data[1]
  148. image_bytes = base64.b64decode(image_base64)
  149. image_np = bytes2np(image_bytes)
  150. str_list = []
  151. for box in box_list:
  152. file_bytes = np2bytes(image_np[box[1]:box[3], box[0]:box[2], :])
  153. file_base64 = base64.b64encode(file_bytes)
  154. file_str = file_base64.decode("utf-8")
  155. str_list.append(file_str)
  156. return {"data": json.dumps(str_list)}
  157. elif _type in ['cho']:
  158. return {"data": json.dumps(data)}
  159. else:
  160. raise
  161. def test_interface(from_remote=True):
  162. captcha_url = "http://192.168.2.103:17054/captcha"
  163. paths = glob("../dev/click_captcha/data/test/yolo_1.jpg")
  164. for file_path in paths:
  165. img_np = cv2.imread(file_path)
  166. file_bytes = np2bytes(img_np)
  167. file_base64 = base64.b64encode(file_bytes)
  168. code = 3
  169. if from_remote:
  170. if code in [1, 4]:
  171. file_json = {"base64pic": file_base64, "code": code}
  172. result = json.loads(request_post(captcha_url, file_json))
  173. print("result", result)
  174. if result.get("success"):
  175. out_boxes = result.get("predict")
  176. print("out_boxes", out_boxes)
  177. for box in out_boxes:
  178. cv2.rectangle(img_np, (box[0], box[1]), (box[2], box[3]), (0, 0, 255))
  179. cv2.imshow("img_np", img_np)
  180. cv2.waitKey(0)
  181. else:
  182. print("failed!")
  183. elif code in [2]:
  184. file_json = {"base64pic": file_base64, "code": code}
  185. result = json.loads(request_post(captcha_url, file_json))
  186. print("result", result)
  187. if result.get("success"):
  188. w = int(result.get("predict"))
  189. print("w", w)
  190. img_new = np.concatenate([img_np[:, w:, :], img_np[:, :w, :]], axis=1)
  191. cv2.imshow("img_np", img_np)
  192. cv2.imshow("img_new", img_new)
  193. cv2.waitKey(0)
  194. else:
  195. print("failed!")
  196. elif code in [3]:
  197. file_base64_2 = cv2.imread("../dev/click_captcha/data/test/yolo_3.jpg")
  198. cv2.imshow("file_base64_2", file_base64_2)
  199. cv2.waitKey(0)
  200. file_base64_2 = np2bytes(file_base64_2)
  201. file_base64_2 = base64.b64encode(file_base64_2)
  202. file_json = {"base64pic": file_base64, "base64pic2": file_base64_2, "code": code}
  203. result = json.loads(request_post(captcha_url, file_json))
  204. print("result", result)
  205. if result.get("success"):
  206. out_boxes = result.get("predict")
  207. print("out_boxes", out_boxes)
  208. for box in out_boxes:
  209. cv2.rectangle(img_np, (box[0], box[1]), (box[2], box[3]), (0, 0, 255))
  210. cv2.imshow("img_np", img_np)
  211. cv2.waitKey(0)
  212. else:
  213. print("failed!")
  214. if __name__ == "__main__":
  215. # app.run(host='127.0.0.1', port=17054, debug=False)
  216. test_interface()