captcha_breaker.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import base64
  2. import os
  3. from openai import OpenAI
  4. QWEN_API_KEY = "sk-893e895724c6403d81374e515ffaf427"
  5. def encode_image_to_base64(image_path):
  6. with open(image_path, "rb") as image_file:
  7. return base64.b64encode(image_file.read()).decode('utf-8')
  8. def recognize_captcha_with_qwen(image_path, api_key):
  9. # 利用 OpenAI 的包,调用阿里云的兼容 API 接口
  10. client = OpenAI(
  11. api_key=api_key,
  12. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
  13. )
  14. base64_image = encode_image_to_base64(image_path)
  15. prompt = "你是一个精确的OCR机器人。请识别图片中的验证码字符。只输出验证码本身的内容,不要任何多余的汉字或标点符号。"
  16. try:
  17. response = client.chat.completions.create(
  18. model="qwen-vl-max", # 也可以用更便宜的 qwen-vl-plus
  19. messages=[
  20. {
  21. "role": "user",
  22. "content":[
  23. {"type": "text", "text": prompt},
  24. {
  25. "type": "image_url",
  26. "image_url": {
  27. "url": f"data:image/png;base64,{base64_image}"
  28. }
  29. }
  30. ]
  31. }
  32. ],
  33. temperature=0.0
  34. )
  35. return response.choices[0].message.content.strip()
  36. except Exception as e:
  37. print(f"Qwen 识别错误: {e}")
  38. return None
  39. def recognize_vfs_captcha_with_qwen(base64_image):
  40. # 利用 OpenAI 的包,调用阿里云的兼容 API 接口
  41. client = OpenAI(
  42. api_key=QWEN_API_KEY,
  43. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
  44. )
  45. prompt = "图片中有多组验证码,其中OTP箭头指向的验证码为真,其余为假。只输出真实验证码的内容,不要任何多余的汉字或标点符号。"
  46. try:
  47. response = client.chat.completions.create(
  48. model="qwen-vl-max", # 也可以用更便宜的 qwen-vl-plus
  49. messages=[
  50. {
  51. "role": "user",
  52. "content":[
  53. {"type": "text", "text": prompt},
  54. {
  55. "type": "image_url",
  56. "image_url": {
  57. "url": base64_image
  58. }
  59. }
  60. ]
  61. }
  62. ],
  63. temperature=0.0
  64. )
  65. return response.choices[0].message.content.strip()
  66. except Exception as e:
  67. print(f"Qwen 识别错误: {e}")
  68. return None
  69. if __name__ == "__main__":
  70. # 填入阿里云百炼 (DashScope) 的 API-KEY
  71. IMAGE_PATH = "/home/jerry/workspace/coordinator/data/275c31f009e612b65eb92cb52bb1d98.png"
  72. print(f"Qwen-VL 识别结果: {recognize_vfs_captcha_with_qwen(IMAGE_PATH, QWEN_API_KEY)}")