| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import requests
- import os
- import sys
- def test_ocr_service(image_path, server_url="http://127.0.0.1:8085/predict/vfcode"):
- """
- 读取本地图片并发送给 OCR 服务进行识别
- """
- # 1. 检查文件是否存在
- if not os.path.exists(image_path):
- print(f"[错误] 找不到文件: {image_path}")
- return
- print(f"[INFO] 正在读取图片: {image_path}")
- print(f"[INFO] 目标服务器: {server_url}")
- try:
- # 2. 读取图片二进制数据
- with open(image_path, 'rb') as f:
- image_data = f.read()
- # 3. 发送 POST 请求
- # 注意:这里直接发送二进制流 (data=image_data),配合之前的 predict_server.py 使用
- # 如果服务端要求 multipart/form-data,则需要用 files={'file': f}
- start_time = time.time()
- response = requests.post(
- server_url,
- data=image_data,
- headers={"Content-Type": "application/octet-stream"}, # 标识为二进制流
- timeout=10
- )
- cost_time = (time.time() - start_time) * 1000
- # 4. 解析响应
- if response.status_code == 200:
- result = response.json()
- ocr_text = result.get('data', '').replace('$', '') # 去除可能存在的结束符
-
- print("-" * 40)
- print(f"✅ 识别成功")
- print(f"📸 结果: {ocr_text}")
- print(f"⏱️ 耗时: {cost_time:.2f} ms")
- print(f"📩 原始响应: {result}")
- print("-" * 40)
- else:
- print(f"[失败] 服务器返回状态码: {response.status_code}")
- print(f"响应内容: {response.text}")
- except requests.exceptions.ConnectionError:
- print("[错误] 无法连接到服务器。请确认 predict_server.py 正在运行且端口正确。")
- except Exception as e:
- print(f"[错误] 发生异常: {e}")
- if __name__ == "__main__":
- import time
-
- # --- 配置 ---
- SERVER_URL = "http://127.0.0.1:8085/predict/vfcode"
-
- # 默认测试图片路径 (请修改为你本地实际存在的验证码图片路径)
- # 你可以放一张图片在当前目录下,命名为 test.jpg
- DEFAULT_IMAGE = "output.png"
- # 支持命令行参数: python test_ocr_client.py my_image.png
- if len(sys.argv) > 1:
- image_file = sys.argv[1]
- else:
- image_file = DEFAULT_IMAGE
- # 如果默认图片不存在,尝试在 test 目录下找一个
- if not os.path.exists(image_file):
- if os.path.exists("test/562_xxxx.gif"): # 假设你的项目结构里有这个
- image_file = "test/562_xxxx.gif"
- elif os.path.exists("data/captcha.jpg"):
- image_file = "data/captcha.jpg"
- # 开始测试
- test_ocr_service(image_file, SERVER_URL)
|