|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, Mapping, cast |
| 4 | + |
| 5 | +import httpx |
| 6 | +from typing_extensions import Literal |
| 7 | +from zai.core import ( |
| 8 | + BaseAPI, |
| 9 | + maybe_transform, |
| 10 | + NOT_GIVEN, |
| 11 | + Body, |
| 12 | + Headers, |
| 13 | + NotGiven, |
| 14 | + FileTypes, |
| 15 | + deepcopy_minimal, |
| 16 | + extract_files, |
| 17 | + make_request_options |
| 18 | +) |
| 19 | +from zai.types.ocr.handwriting_ocr_params import HandwritingOCRParams |
| 20 | +from zai.types.ocr.handwriting_ocr_resp import HandwritingOCRResp |
| 21 | + |
| 22 | +if TYPE_CHECKING: |
| 23 | + from zai._client import ZaiClient |
| 24 | + |
| 25 | +__all__ = ["HandwritingOCR"] |
| 26 | + |
| 27 | + |
| 28 | +class HandwritingOCR(BaseAPI): |
| 29 | + |
| 30 | + def __init__(self, client: "ZaiClient") -> None: |
| 31 | + super().__init__(client) |
| 32 | + |
| 33 | + def handwriting_ocr( |
| 34 | + self, |
| 35 | + *, |
| 36 | + file: FileTypes, |
| 37 | + tool_type: Literal["hand_write"], |
| 38 | + language_type: str = None, # optional, |
| 39 | + probability: bool = None, |
| 40 | + extra_headers: Headers | None = None, |
| 41 | + extra_body: Body | None = None, |
| 42 | + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, |
| 43 | + ) -> HandwritingOCRResp: |
| 44 | + if not file: |
| 45 | + raise ValueError("`file` must be provided.") |
| 46 | + if not tool_type: |
| 47 | + raise ValueError("`tool_type` must be provided.") |
| 48 | + body = deepcopy_minimal( |
| 49 | + { |
| 50 | + "file": file, |
| 51 | + "tool_type": tool_type, |
| 52 | + "language_type": language_type, |
| 53 | + "probability": probability |
| 54 | + } |
| 55 | + ) |
| 56 | + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) |
| 57 | + if files: |
| 58 | + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} |
| 59 | + return self._post( |
| 60 | + "/files/ocr", |
| 61 | + body=maybe_transform(body, HandwritingOCRParams), |
| 62 | + files=files, |
| 63 | + options=make_request_options( |
| 64 | + extra_headers=extra_headers, extra_body=extra_body, timeout=timeout |
| 65 | + ), |
| 66 | + cast_type=HandwritingOCRResp, |
| 67 | + ) |
0 commit comments