convert_json.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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:18060'
  7. imgs_path = '/Users/sxkj/to_md/img'
  8. def send_request(img_path):
  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. }
  14. # idc_header = {
  15. # 'Content-Type': 'application/json',
  16. # 'Authorization': 'Bearer 4e00c444-620b-4d3c-85f4-777e64276f0e'
  17. # }
  18. r = requests.post(f'{url}/ocr_system/regbook', json=data)
  19. print(r.json())
  20. return r.json()
  21. def _parse_result(r):
  22. if r['status'] == '000':
  23. r = r['result']
  24. if r:
  25. del r['confidence']
  26. return {k: v['text'] if isinstance(v, dict) else v for k, v in r.items()}
  27. elif r['status'] == '101':
  28. return "101"
  29. if __name__ == '__main__':
  30. # 0
  31. root = Path(__file__).parent
  32. print(root)
  33. # img_paths = chain(*[Path(root / imgs_path).rglob(f'*.{ext}') for ext in ['jpeg', 'jpg', 'png', 'JPG', 'PNG']])
  34. img_paths = chain(*[Path(root / imgs_path).rglob(f'*.{ext}') for ext in ['jpg']])
  35. for img_path in img_paths:
  36. print(img_path)
  37. r = send_request(img_path)
  38. res = _parse_result(r)
  39. print(res)
  40. img_path: Path = img_path
  41. d = img_path.parent
  42. fn = f'{img_path.stem}.json'
  43. with (d / fn).open('w', encoding='utf-8') as f:
  44. json.dump(res, f, ensure_ascii=False, indent=4)