convert_json.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from pathlib import Path
  2. import requests
  3. import json
  4. import base64
  5. from itertools import chain
  6. url = 'http://192.168.199.27:18040'
  7. imgs_path = '../img'
  8. def send_request(img_path, image_type = 0):
  9. with open(img_path, 'rb') as f:
  10. img_str: str = base64.encodebytes(f.read()).decode('utf-8')
  11. data = {
  12. 'image': img_str,
  13. 'image_type': image_type
  14. }
  15. # idc_header = {
  16. # 'Content-Type': 'application/json',
  17. # 'Authorization': 'Bearer 4e00c444-620b-4d3c-85f4-777e64276f0e'
  18. # }
  19. r = requests.post(f'{url}/ocr_system/regbook', json=data)
  20. print(r.json())
  21. return r.json()
  22. def _parse_result(r):
  23. if r['status'] == '000':
  24. r = r['result']
  25. if r:
  26. del r['confidence']
  27. return {k: v['text'] if isinstance(v, dict) else v for k, v in r.items()}
  28. elif r['status'] == '101':
  29. return "101"
  30. if __name__ == '__main__':
  31. # 0
  32. root = Path(__file__).parent
  33. print(root)
  34. # img_paths = chain(*[Path(root / imgs_path).rglob(f'*.{ext}') for ext in ['jpeg', 'jpg', 'png', 'JPG', 'PNG']])
  35. img_paths = chain(*[Path(root / imgs_path).rglob(f'*.{ext}') for ext in ['jpg']])
  36. for img_path in img_paths:
  37. print(img_path)
  38. r = send_request(img_path)
  39. res = _parse_result(r)
  40. print(res)
  41. img_path: Path = img_path
  42. d = img_path.parent
  43. fn = f'{img_path.stem}.json'
  44. with (d / fn).open('w', encoding='utf-8') as f:
  45. json.dump(res, f, ensure_ascii=False, indent=4)