# coding: utf-8
#
# Copyright 2026 祁筱欣
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
from typing import Type
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkimage.v2 import *
from huaweicloudsdkimage.v2.region.image_region import ImageRegion
from .client import HuaweiCloudClient, ClientClass, RegionClass
class ImageClientManager(HuaweiCloudClient):
"""图像识别客户端管理器"""
def get_client_class(self) -> Type[ClientClass]:
return ImageClient
def get_region_class(self) -> Type[RegionClass]:
return ImageRegion
def get_cache_key(self) -> str:
return "image"
# 全局实例
_image_manager = ImageClientManager()
async def recognize_celebrity(
url: str = None,
image: str = None,
) -> dict:
"""使用华为云名人识别服务识别图片中的名人。
Args:
url (str, optional): 图片的 URL 地址(需可公开访问)。
image (str, optional): 图片的 Base64 编码。
Returns:
dict: 名人识别结果。
Note:
url 和 image 参数二选一。
"""
# 参数验证
if not url and not image:
return {"error": "必须提供 url 或 image 参数之一"}
if url and image:
return {"error": "url 和 image 参数不能同时提供"}
try:
client = _image_manager.get_client()
request = RunCelebrityRecognitionRequest()
# 构建请求参数
kwargs = {}
if url:
kwargs["url"] = url.strip()
else:
kwargs["image"] = image
request.body = CelebrityRecognitionReq(**kwargs)
response = client.run_celebrity_recognition(request) # type: ignore
# 将 Unicode 转义序列解码为实际字符
result = response.to_json_object()
return json.loads(json.dumps(result, ensure_ascii=False))
except exceptions.ClientRequestException as e:
return {
"error": {
"status_code": e.status_code,
"request_id": e.request_id,
"error_code": e.error_code,
"error_msg": e.error_msg,
}
}