Commit a6360472 authored by 刘小敏's avatar 刘小敏

AI试戴生成图片接口添加AIService

parent 3a9b6798
<?php
namespace addons\shopro\service\user;
use addons\shopro\library\HttpClient as Http;
use think\Config;
use think\Log;
class Ai
{
// 火山引擎方舟配置
private $ark_host = 'https://ark.cn-beijing.volces.com';
private $api_key = ''; // 我的个人Key
public function __construct(){
$this->api_key = config('shopro.ai_api_key');
}
/**
* AI 生成图片
* @param string $param 入参
* @param string $userId 入参
* @return object|array
*/
public function generateImage($param = [], $userId = 0)
{
try {
$url = $this->ark_host . '/api/v3/images/generations';
$prompt = '严格保留图片1人物全部样貌、姿势、背景、光影不变,精准将图片2饰品自然佩戴在人物对应部位,饰品贴合皮肤、大小合适、位置标准,不偏移、不悬浮、不扭曲、不重复生成,整体真实自然,高清电商珠宝大片,原图质感不变';
$params = [
'headers' => [
'Authorization' => 'Bearer ' . $this->api_key,
'Content-Type' => 'application/json'
],
'json' => [
"model" => "doubao-seedream-5-0-260128",
"prompt" => $prompt,
"image" => [$param['person_image'], $param['jewelry_image']],
"sequential_image_generation" => "disabled",
"response_format" => "b64_json",
"size" => "2K",
"stream" => false,
"watermark" => true
],
'timeout' => 300,
'verify' => false, // 关闭 SSL 证书验证
'allow_redirects' => true
];
// 发送请求
$client = new Http();
$response = $client->post($url, $params);
$content = $response->getBody()->getContents();
$content = trim($content);
$content = preg_replace('/[^\x20-\x7E]/', '', $content);
$result = json_decode($content, true);
// 记录日志
Log::info('用户ID:'. $userId .' AI生成图片接口返回result:'.json_encode($result));
if (!$result || !isset($result['data'][0]['b64_json'])) {
return [
'code' => 0 ,
'msg' => 'AI图片解析失败,无返回图片'
];
}
if (isset($result['error']) && $result['error'] !== 0) {
return [
'code' => 0 ,
'msg' => $result['message'] ?? '生成失败'
];
}
return [
'code' => 1 ,
'msg' => '图片生成成功' ,
'data' => $result['data'][0]['b64_json'] ?? ''
];
} catch (\Exception $e) {
Log::error('用户ID:'. $userId .' AI生成图片异常:' . $e->getMessage());
return [
'code' => 0 ,
'msg' => '请求异常:' . $e->getMessage()
];
}
}
/**
* AI 生成视频
* @param string $image_url 图片地址
* @return array
*/
public function generateVideo($image_url = '')
{
try {
$url = $this->ark_host . '/api/v3/contents/generations';
$params = [
'image_url' => $image_url,
'motion' => 'medium',
'duration' => 5
];
$header = [
'Authorization: Bearer ' . $this->api_key,
'Content-Type: application/json'
];
$response = Http::header($header)
->postJson($url, $params);
$result = json_decode($response, true);
Log::info('AI生成视频返回:', $result);
if (isset($result['code']) && $result['code'] != 0) {
return [
'code' => 0,
'msg' => $result['message'] ?? '生成失败'
];
}
return [
'code' => 1,
'msg' => '生成成功',
'data' => $result['data']['video_url'] ?? ''
];
} catch (\Exception $e) {
Log::error('AI生成视频异常:' . $e->getMessage());
return [
'code' => 0,
'msg' => '请求异常:' . $e->getMessage()
];
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment