62 lines
2.1 KiB
Python
62 lines
2.1 KiB
Python
import json
|
||
|
||
import litserve as ls
|
||
import requests
|
||
from pydantic import BaseModel
|
||
|
||
from app.config import settings
|
||
|
||
|
||
class PredictRequest(BaseModel):
|
||
input_image_list: list[str] # 待换脸图片
|
||
input_face: str # 目标脸图片
|
||
threshold: float = 0.2 # 相似度 max:0.5
|
||
|
||
|
||
class ReFace(ls.LitAPI):
|
||
def decode_request(self, request: PredictRequest):
|
||
return request
|
||
|
||
def predict(self, request):
|
||
# 服务的 URL
|
||
url = f"http://{settings.RE_FACE_MODEL_URL}/predict"
|
||
|
||
# 请求头
|
||
headers = {
|
||
"accept": "application/json",
|
||
"Content-Type": "application/json"
|
||
}
|
||
|
||
# 请求体数据
|
||
# 这里的结构要和你的 LitServe 服务的 LitAPI.decode_request 预期的一致
|
||
data = {
|
||
"input_image_list": request.input_image_list,
|
||
"input_face": request.input_face,
|
||
"threshold": request.threshold
|
||
}
|
||
|
||
try:
|
||
# 使用 requests.post 发送请求
|
||
# 使用 json= 参数可以自动将 Python 字典转换为 JSON 格式,并设置 Content-Type 头部
|
||
response = requests.post(url, headers=headers, json=data)
|
||
|
||
# 检查 HTTP 响应状态码,如果不是 200/201 等成功状态,将抛出异常
|
||
response.raise_for_status()
|
||
|
||
# 打印返回的 JSON 结果
|
||
print("成功调用 LitServe 接口,返回结果:")
|
||
# .json() 方法将响应体解析为 Python 字典
|
||
print(json.dumps(response.json(), indent=4, ensure_ascii=False))
|
||
return response.json()
|
||
|
||
except requests.exceptions.RequestException as e:
|
||
# 处理请求失败、连接错误或 HTTP 错误状态
|
||
print(f"请求发生错误: {e}")
|
||
if 'response' in locals() and response is not None:
|
||
print(f"响应状态码: {response.status_code}")
|
||
try:
|
||
# 尝试打印服务器返回的错误详情
|
||
print(f"服务器错误详情: {response.json()}")
|
||
except:
|
||
print(f"服务器错误详情 (非 JSON 格式): {response.text}")
|