worker.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """由 service 在可超时终止的独立进程中运行。"""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. import json
  5. import sys
  6. def main() -> int:
  7. import cv2
  8. import numpy as np
  9. from .service import MAX_IMAGE_PIXELS
  10. from .vendor.chart_axis_detector.current_image_pipeline import (
  11. CurrentImagePipelineConfig, process_new_image,
  12. )
  13. cv2.setNumThreads(1)
  14. image_path, result_dir = Path(sys.argv[1]), Path(sys.argv[2])
  15. try:
  16. image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), cv2.IMREAD_COLOR)
  17. except cv2.error:
  18. return 2
  19. if image is None or min(image.shape[:2]) < 32 or image.shape[0] * image.shape[1] > MAX_IMAGE_PIXELS:
  20. return 2
  21. del image
  22. def stage(name):
  23. if len(sys.argv) > 4:
  24. path = Path(sys.argv[4])
  25. temporary = path.with_suffix(".tmp")
  26. temporary.write_text(json.dumps({"stage": name}), encoding="utf-8")
  27. temporary.replace(path)
  28. try:
  29. process_new_image(image_path, result_dir, CurrentImagePipelineConfig(detailed=sys.argv[3] == "1"), on_stage=stage)
  30. except ValueError as exc:
  31. print(str(exc), file=sys.stderr)
  32. return 3
  33. return 0
  34. if __name__ == "__main__":
  35. sys.exit(main())