convert_json.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from pathlib import Path
  2. import requests
  3. import json
  4. import base64
  5. from itertools import chain
  6. url = 'http://localhost:8080'
  7. def send_request(img_path, image_type=0):
  8. with open(img_path, 'rb') as f:
  9. img_str: str = base64.encodebytes(f.read()).decode('utf-8')
  10. data = {
  11. 'image': img_str,
  12. 'image_type': image_type
  13. }
  14. r = requests.post(f'{url}/ocr_system/idcard', json=data)
  15. print(r.json())
  16. return r.json()
  17. def _parse_result(r):
  18. if r['status'] == '000':
  19. r = r['result']
  20. if r:
  21. del r['confidence']
  22. res = {}
  23. for k, v in r.items():
  24. if isinstance(v, dict):
  25. res[k] = v['text']
  26. else:
  27. res[k] = v
  28. return res
  29. elif r['status'] == '101':
  30. return "101"
  31. if __name__ == '__main__':
  32. # 0
  33. root = Path(__file__).parent
  34. print(root)
  35. img_paths = chain(*[Path(root / 'images/all/7.20/new/').rglob(f'*.{ext}') for ext in ['jpeg', 'jpg', 'png', 'JPG', 'PNG']])
  36. for img_path in img_paths:
  37. print(img_path)
  38. r = send_request(img_path, 1)
  39. res = _parse_result(r)
  40. print(res)
  41. img_path: Path = img_path
  42. d = img_path.parent
  43. fn = 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)