修改为东南天坐标系

This commit is contained in:
2026-01-20 09:49:52 +08:00
parent 9538757047
commit 333fad40ac
7201 changed files with 1030888 additions and 85410 deletions

View File

@@ -160,6 +160,8 @@ class InferenceClient:
follow the same pattern as `openai.OpenAI` client. Cannot be used if `token` is set. Defaults to None.
"""
provider: Optional[PROVIDER_OR_POLICY_T]
@validate_hf_hub_args
def __init__(
self,
@@ -227,7 +229,7 @@ class InferenceClient:
)
# Configure provider
self.provider = provider
self.provider = provider # type: ignore[assignment]
self.cookies = cookies
self.timeout = timeout
@@ -1030,6 +1032,8 @@ class InferenceClient:
prompt_name: Optional[str] = None,
truncate: Optional[bool] = None,
truncation_direction: Optional[Literal["left", "right"]] = None,
dimensions: Optional[int] = None,
encoding_format: Optional[Literal["float", "base64"]] = None,
model: Optional[str] = None,
) -> "np.ndarray":
"""
@@ -1056,6 +1060,12 @@ class InferenceClient:
Only available on server powered by Text-Embedding-Inference.
truncation_direction (`Literal["left", "right"]`, *optional*):
Which side of the input should be truncated when `truncate=True` is passed.
dimensions (`int`, *optional*):
The number of dimensions the resulting output embeddings should have.
Only available on OpenAI-compatible embedding endpoints.
encoding_format (`Literal["float", "base64"]`, *optional*):
The format of the output embeddings. Either "float" or "base64".
Only available on OpenAI-compatible embedding endpoints.
Returns:
`np.ndarray`: The embedding representing the input text as a float32 numpy array.
@@ -1086,6 +1096,8 @@ class InferenceClient:
"prompt_name": prompt_name,
"truncate": truncate,
"truncation_direction": truncation_direction,
"dimensions": dimensions,
"encoding_format": encoding_format,
},
headers=self.headers,
model=model_id,

View File

@@ -151,6 +151,8 @@ class AsyncInferenceClient:
follow the same pattern as `openai.OpenAI` client. Cannot be used if `token` is set. Defaults to None.
"""
provider: Optional[PROVIDER_OR_POLICY_T]
@validate_hf_hub_args
def __init__(
self,
@@ -218,7 +220,7 @@ class AsyncInferenceClient:
)
# Configure provider
self.provider = provider
self.provider = provider # type: ignore[assignment]
self.cookies = cookies
self.timeout = timeout
@@ -1057,6 +1059,8 @@ class AsyncInferenceClient:
prompt_name: Optional[str] = None,
truncate: Optional[bool] = None,
truncation_direction: Optional[Literal["left", "right"]] = None,
dimensions: Optional[int] = None,
encoding_format: Optional[Literal["float", "base64"]] = None,
model: Optional[str] = None,
) -> "np.ndarray":
"""
@@ -1083,6 +1087,12 @@ class AsyncInferenceClient:
Only available on server powered by Text-Embedding-Inference.
truncation_direction (`Literal["left", "right"]`, *optional*):
Which side of the input should be truncated when `truncate=True` is passed.
dimensions (`int`, *optional*):
The number of dimensions the resulting output embeddings should have.
Only available on OpenAI-compatible embedding endpoints.
encoding_format (`Literal["float", "base64"]`, *optional*):
The format of the output embeddings. Either "float" or "base64".
Only available on OpenAI-compatible embedding endpoints.
Returns:
`np.ndarray`: The embedding representing the input text as a float32 numpy array.
@@ -1114,6 +1124,8 @@ class AsyncInferenceClient:
"prompt_name": prompt_name,
"truncate": truncate,
"truncation_direction": truncation_direction,
"dimensions": dimensions,
"encoding_format": encoding_format,
},
headers=self.headers,
model=model_id,

View File

@@ -77,6 +77,18 @@ from .image_segmentation import (
ImageSegmentationParameters,
ImageSegmentationSubtask,
)
from .image_text_to_image import (
ImageTextToImageInput,
ImageTextToImageOutput,
ImageTextToImageParameters,
ImageTextToImageTargetSize,
)
from .image_text_to_video import (
ImageTextToVideoInput,
ImageTextToVideoOutput,
ImageTextToVideoParameters,
ImageTextToVideoTargetSize,
)
from .image_to_image import ImageToImageInput, ImageToImageOutput, ImageToImageParameters, ImageToImageTargetSize
from .image_to_text import (
ImageToTextEarlyStoppingEnum,

View File

@@ -0,0 +1,67 @@
# Inference code generated from the JSON schema spec in @huggingface/tasks.
#
# See:
# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
from typing import Any, Optional
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extra
class ImageTextToImageTargetSize(BaseInferenceType):
"""The size in pixels of the output image. This parameter is only supported by some
providers and for specific models. It will be ignored when unsupported.
"""
height: int
width: int
@dataclass_with_extra
class ImageTextToImageParameters(BaseInferenceType):
"""Additional inference parameters for Image Text To Image"""
guidance_scale: Optional[float] = None
"""For diffusion models. A higher guidance scale value encourages the model to generate
images closely linked to the text prompt at the expense of lower image quality.
"""
negative_prompt: Optional[str] = None
"""One prompt to guide what NOT to include in image generation."""
num_inference_steps: Optional[int] = None
"""For diffusion models. The number of denoising steps. More denoising steps usually lead to
a higher quality image at the expense of slower inference.
"""
prompt: Optional[str] = None
"""The text prompt to guide the image generation. Either this or inputs (image) must be
provided.
"""
seed: Optional[int] = None
"""Seed for the random number generator."""
target_size: Optional[ImageTextToImageTargetSize] = None
"""The size in pixels of the output image. This parameter is only supported by some
providers and for specific models. It will be ignored when unsupported.
"""
@dataclass_with_extra
class ImageTextToImageInput(BaseInferenceType):
"""Inputs for Image Text To Image inference. Either inputs (image) or prompt (in parameters)
must be provided, or both.
"""
inputs: Optional[str] = None
"""The input image data as a base64-encoded string. If no `parameters` are provided, you can
also provide the image data as a raw bytes payload. Either this or prompt must be
provided.
"""
parameters: Optional[ImageTextToImageParameters] = None
"""Additional inference parameters for Image Text To Image"""
@dataclass_with_extra
class ImageTextToImageOutput(BaseInferenceType):
"""Outputs of inference for the Image Text To Image task"""
image: Any
"""The generated image returned as raw bytes in the payload."""

View File

@@ -0,0 +1,65 @@
# Inference code generated from the JSON schema spec in @huggingface/tasks.
#
# See:
# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
from typing import Any, Optional
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extra
class ImageTextToVideoTargetSize(BaseInferenceType):
"""The size in pixel of the output video frames."""
height: int
width: int
@dataclass_with_extra
class ImageTextToVideoParameters(BaseInferenceType):
"""Additional inference parameters for Image Text To Video"""
guidance_scale: Optional[float] = None
"""For diffusion models. A higher guidance scale value encourages the model to generate
videos closely linked to the text prompt at the expense of lower image quality.
"""
negative_prompt: Optional[str] = None
"""One prompt to guide what NOT to include in video generation."""
num_frames: Optional[float] = None
"""The num_frames parameter determines how many video frames are generated."""
num_inference_steps: Optional[int] = None
"""The number of denoising steps. More denoising steps usually lead to a higher quality
video at the expense of slower inference.
"""
prompt: Optional[str] = None
"""The text prompt to guide the video generation. Either this or inputs (image) must be
provided.
"""
seed: Optional[int] = None
"""Seed for the random number generator."""
target_size: Optional[ImageTextToVideoTargetSize] = None
"""The size in pixel of the output video frames."""
@dataclass_with_extra
class ImageTextToVideoInput(BaseInferenceType):
"""Inputs for Image Text To Video inference. Either inputs (image) or prompt (in parameters)
must be provided, or both.
"""
inputs: Optional[str] = None
"""The input image data as a base64-encoded string. If no `parameters` are provided, you can
also provide the image data as a raw bytes payload. Either this or prompt must be
provided.
"""
parameters: Optional[ImageTextToVideoParameters] = None
"""Additional inference parameters for Image Text To Video"""
@dataclass_with_extra
class ImageTextToVideoOutput(BaseInferenceType):
"""Outputs of inference for the Image Text To Video task"""
video: Any
"""The generated video returned as raw bytes in the payload."""

View File

@@ -56,7 +56,7 @@ from .wavespeed import (
WavespeedAITextToImageTask,
WavespeedAITextToVideoTask,
)
from .zai_org import ZaiConversationalTask
from .zai_org import ZaiConversationalTask, ZaiTextToImageTask
logger = logging.get_logger(__name__)
@@ -208,6 +208,7 @@ PROVIDERS: dict[PROVIDER_T, dict[str, TaskProviderHelper]] = {
},
"zai-org": {
"conversational": ZaiConversationalTask(),
"text-to-image": ZaiTextToImageTask(),
},
}

View File

@@ -0,0 +1,10 @@
from huggingface_hub.inference._providers._common import BaseConversationalTask
_PROVIDER = "ovhcloud"
_BASE_URL = "https://oai.endpoints.kepler.ai.cloud.ovh.net"
class OVHcloudConversationalTask(BaseConversationalTask):
def __init__(self):
super().__init__(provider=_PROVIDER, base_url=_BASE_URL)

View File

@@ -1,13 +1,35 @@
from typing import Any, Dict
import time
from abc import ABC
from typing import Any, Optional, Union
from huggingface_hub.inference._providers._common import BaseConversationalTask
from huggingface_hub.hf_api import InferenceProviderMapping
from huggingface_hub.inference._common import RequestParameters, _as_dict
from huggingface_hub.inference._providers._common import BaseConversationalTask, TaskProviderHelper, filter_none
from huggingface_hub.utils import get_session
_PROVIDER = "zai-org"
_BASE_URL = "https://api.z.ai"
_POLLING_INTERVAL = 5 # seconds
_MAX_POLL_ATTEMPTS = 60
class ZaiTask(TaskProviderHelper, ABC):
def __init__(self, task: str):
super().__init__(provider=_PROVIDER, base_url=_BASE_URL, task=task)
def _prepare_headers(self, headers: dict, api_key: str) -> dict[str, Any]:
headers = super()._prepare_headers(headers, api_key)
headers["Accept-Language"] = "en-US,en"
headers["x-source-channel"] = "hugging_face"
return headers
class ZaiConversationalTask(BaseConversationalTask):
def __init__(self):
super().__init__(provider="zai-org", base_url="https://api.z.ai")
super().__init__(provider=_PROVIDER, base_url=_BASE_URL)
def _prepare_headers(self, headers: Dict, api_key: str) -> Dict[str, Any]:
def _prepare_headers(self, headers: dict, api_key: str) -> dict[str, Any]:
headers = super()._prepare_headers(headers, api_key)
headers["Accept-Language"] = "en-US,en"
headers["x-source-channel"] = "hugging_face"
@@ -15,3 +37,91 @@ class ZaiConversationalTask(BaseConversationalTask):
def _prepare_route(self, mapped_model: str, api_key: str) -> str:
return "/api/paas/v4/chat/completions"
class ZaiTextToImageTask(ZaiTask):
"""Text-to-image task for ZAI provider using async API."""
def __init__(self):
super().__init__("text-to-image")
def _prepare_route(self, mapped_model: str, api_key: str) -> str:
return "/api/paas/v4/async/images/generations"
def _prepare_payload_as_dict(
self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping
) -> Optional[dict]:
width = parameters.pop("width", None)
height = parameters.pop("height", None)
size = None
if width is not None and height is not None:
size = f"{width}x{height}"
payload: dict[str, Any] = {
"model": provider_mapping_info.provider_id,
"prompt": inputs,
}
if size is not None:
payload["size"] = size
payload.update(filter_none(parameters))
return payload
def get_response(
self,
response: Union[bytes, dict],
request_params: Optional[RequestParameters] = None,
) -> Any:
"""Handle async response by polling for results."""
response_dict = _as_dict(response)
task_id = response_dict.get("id")
if task_id is None:
raise ValueError("No task_id in response from ZAI API")
task_status = response_dict.get("task_status")
if task_status == "FAIL":
raise ValueError(f"ZAI image generation failed for request {task_id}")
if task_status == "PROCESSING" and request_params is not None:
return self._poll_for_result(task_id, request_params)
return self._extract_image(response_dict)
def _poll_for_result(self, task_id: str, request_params: RequestParameters) -> bytes:
"""Poll the async-result endpoint until completion."""
session = get_session()
base_url = request_params.url.rsplit("/api/paas/v4/async/images/generations", 1)[0]
poll_url = f"{base_url}/api/paas/v4/async-result/{task_id}"
for _ in range(_MAX_POLL_ATTEMPTS):
poll_response = session.get(poll_url, headers=request_params.headers)
poll_response.raise_for_status()
result = poll_response.json()
task_status = result.get("task_status")
if task_status == "SUCCESS":
return self._extract_image(result)
elif task_status == "FAIL":
raise ValueError(f"Zai text-to-image generation failed for request {task_id}")
time.sleep(_POLLING_INTERVAL)
raise ValueError(
f"Timed out while waiting for the result from Zai API - aborting after {_MAX_POLL_ATTEMPTS} attempts"
)
def _extract_image(self, result: dict) -> bytes:
"""Extract and download the image from the result."""
image_result = result.get("image_result")
if not image_result or not isinstance(image_result, list) or len(image_result) == 0:
raise ValueError("No image_result in response from ZAI API")
image_url = image_result[0].get("url")
if not image_url:
raise ValueError("No image URL in response from ZAI API")
session = get_session()
image_response = session.get(image_url)
image_response.raise_for_status()
return image_response.content