MCPcopy Create free account
hub / github.com/VitoHowe/glm-coding / OcrService

Class OcrService

app/services/ocr_service.py:104–418  ·  view source on GitHub ↗

Run the vendored TenVision captcha OCR pipeline in this project.

Source from the content-addressed store, hash-verified

102 details={"missing_dependencies": missing},
103 )
104 self._bootstrap_engine_once()
105 executor = self._ensure_executor()
106 timeout = max(self.settings.tencent_ocr_timeout_seconds, 1)
107 # 首次启动先保证模型在主进程完整落地,再做单 worker 预热,
108 # 避免 Windows 下多个进程同时下载/加载同一个 onnx 文件导致文件占用和损坏竞争。
109 future = executor.submit(_warmup_worker, 0)
110 future.result(timeout=timeout)
111
112 def shutdown(self) -> None:
113 with self._executor_lock:
114 if self._executor is None:
115 return
116 self._executor.shutdown(wait=False, cancel_futures=True)
117 self._executor = None
118
119 def analyze_captcha_image(self, image_bytes: bytes, *, prompt_text: str) -> dict[str, Any]:
120 if not self.settings.tencent_ocr_enabled:
121 raise BadRequestError("本地 OCR 已关闭,请设置 TENCENT_OCR_ENABLED=1")
122
123 missing = self._missing_dependencies()
124 if missing:
125 raise BadRequestError(
126 "本地 OCR 依赖没装全,先运行 pip install -r requirements.txt,别让发动机缺缸还硬跑。",
127 details={"missing_dependencies": missing},
128 )
129
130 try:
131 result = self._run_worker(image_bytes, prompt_text)
132 except FuturesTimeoutError as exc:
133 raise BadRequestError(
134 "验证码 OCR 识别超时",
135 details={"timeout_seconds": self.settings.tencent_ocr_timeout_seconds},
136 ) from exc
137 except Exception as exc:
138 raise BadRequestError("验证码 OCR 识别失败", details={"reason": str(exc)}) from exc
139
140 return self._normalize_result(result)
141
142 def _run_worker(self, image_bytes: bytes, prompt_text: str) -> dict[str, Any]:
143 timeout = max(self.settings.tencent_ocr_timeout_seconds, 1)
144 payload_prompt = prompt_text or ""
145 self._bootstrap_engine_once()
146 for attempt in range(1, 3):
147 executor = self._ensure_executor()
148 future = executor.submit(
149 _worker_analyze,
150 image_bytes,
151 payload_prompt,
152 self.settings.tencent_ocr_include_debug,
153 )
154 try:
155 return future.result(timeout=timeout)
156 except FuturesTimeoutError:
157 future.cancel()
158 raise
159 except BrokenProcessPool:
160 self.shutdown()
161 if attempt >= 2:

Callers 1

get_ocr_serviceFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected