| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599 |
- <?php
- namespace App\Services\AIGeneration;
- use App\Models\MpGeneratePicTask;
- use App\Models\MpAsset;
- use App\Services\VolcEngineService;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\GuzzleException;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use App\Consts\BaseConst;
- class AIImageGenerationService
- {
- private $volcEngineService;
- private $httpClient;
- // 模型常量
- const MODEL_JIMENG_4 = 'jimeng_4.0';
- const MODEL_NANO_BANANA_2 = 'NanoBanana2';
- const MODEL_NANO_BANANA_PRO = 'NanoBananaPro';
- const MODEL_GPT_IMAGE_2 = 'GptImage2';
- public function __construct(VolcEngineService $volcEngineService)
- {
- $this->volcEngineService = $volcEngineService;
- $this->httpClient = new Client([
- 'timeout' => 300,
- ]);
- }
- /**
- * 异步创建图片生成任务
- *
- * @param array $params
- * @return MpGeneratePicTask
- */
- public function createImageGenerationTask(array $params): MpGeneratePicTask
- {
- // // 获取模型类型,默认使用即梦AI 4.0
- // $model = $params['model'] ?? self::MODEL_JIMENG_4;
- // 获取模型类型,默认使用即梦seedream5.0-lite
- $model = $params['model'] ?? 'doubao-seedream-5-0-lite-260128';
-
- // 检查是否有正在处理的任务(仅即梦AI需要排队)
- if ($model === self::MODEL_JIMENG_4 && $this->hasProcessingTask()) {
- // 如果有正在处理的任务,创建排队任务
- return $this->createQueuedTask($params);
- }
- // 生成唯一的任务ID
- $taskId = 'img_gen_' . time() . '_' . uniqid();
- // 创建任务记录
- $task = MpGeneratePicTask::create([
- 'task_id' => $taskId,
- 'alias_segment_id' => $params['alias_segment_id'] ?? 0,
- 'prompt' => $params['prompt'] ?? '',
- 'width' => $params['width'] ?? 1600,
- 'height' => $params['height'] ?? 2848,
- 'image_num' => $params['image_num'] ?? 1,
- 'scale' => $params['scale'] ?? 50,
- 'ref_img_url' => $params['ref_img_urls'] ?? null,
- 'mask_img_url' => $params['mask_img_url'] ?? null,
- 'extra_params' => $params['extra_params'] ?? null,
- 'status' => MpGeneratePicTask::STATUS_PENDING,
- 'model' => $model,
- ]);
- // 即梦AI和NanoBanana系列立即提交任务,火山API在定时任务中提交
- if ($model === self::MODEL_JIMENG_4) {
- $this->submitTaskToJimengApi($task);
- } elseif (in_array($model, BaseConst::NANO_BANANA_MODELS)) {
- $this->submitTaskToNanoBananaApi($task);
- }
- return $task;
- }
- /**
- * 检查是否有正在处理的任务
- *
- * @return bool
- */
- private function hasProcessingTask(): bool
- {
- return MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)
- ->exists();
- }
- /**
- * 创建排队任务
- *
- * @param array $params
- * @return MpGeneratePicTask
- */
- private function createQueuedTask(array $params): MpGeneratePicTask
- {
- // 生成唯一的任务ID
- $taskId = 'img_gen_' . time() . '_' . uniqid();
-
- // 获取模型类型
- $model = $params['model'] ?? self::MODEL_JIMENG_4;
- // 创建排队状态的任务记录
- return MpGeneratePicTask::create([
- 'task_id' => $taskId,
- 'alias_segment_id' => $params['alias_segment_id'] ?? 0,
- 'prompt' => $params['prompt'] ?? '',
- 'width' => $params['width'] ?? 1600,
- 'height' => $params['height'] ?? 2848,
- 'image_num' => $params['image_num'] ?? 1,
- 'scale' => $params['scale'] ?? 50,
- 'ref_img_url' => $params['ref_img_urls'] ?? null,
- 'mask_img_url' => $params['mask_img_url'] ?? null,
- 'extra_params' => $params['extra_params'] ?? null,
- 'status' => MpGeneratePicTask::STATUS_PENDING,
- 'model' => $model,
- ]);
- }
- /**
- * 提交任务到即梦AI API
- *
- * @param MpGeneratePicTask $task
- * @return void
- */
- private function submitTaskToJimengApi(MpGeneratePicTask $task): void
- {
- try {
- // 验证环境变量配置
- $accessKey = env('VOLC_AI_AK');
- $secretKey = env('VOLC_AI_SK');
-
- if (empty($accessKey) || empty($secretKey)) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '火山引擎访问密钥未配置,请检查环境变量AK和SK'
- ]);
- return;
- }
-
- //构建即梦AI 4.0 API请求参数
- $apiParams = [
- 'req_key' => 'jimeng_t2i_v40',
- 'prompt' => $task->prompt,
- 'scale' => $task->scale / 100, //为0-1范围
- ];
-
- // 添加可选参数
- if ($task->image_num > 1) {
- $apiParams['force_single'] = false;
- } else {
- $apiParams['force_single'] = true;
- }
-
- // 参考图片
- if ($task->ref_img_url) {
- $apiParams['image_urls'] = $task->ref_img_url;
- }
-
- // if ($task->mask_img_url) {
- // $apiParams['image_urls'] = $task->mask_img_url;
- // }
-
- // 尺寸参数
- $area = $task->width * $task->height; //计算面积
- if ($area >= 1024*1024 && $area <= 4096*4096) {
- $apiParams['size'] = (int)$area;
- }
- dLog('generate')->info('即梦AI文生图参数: ', $apiParams);
- logDB('generate', 'info', '即梦AI文生图任务提交', ['task_id' => $task->task_id, 'params' => $apiParams]);
-
- //调用即梦AI 4.0 API提交任务
- $response = $this->volcEngineService->request(
- 'POST',
- 'visual.volcengineapi.com', //即梦AI API域名
- '/', // 使用根路径
- [], // Query参数
- json_encode($apiParams),
- $accessKey,
- $secretKey,
- 'cv', // 服务标识
- 'cn-north-1', //区域
- 'CVSync2AsyncSubmitTask',
- '2022-08-31',
- 'application/json'
- );
-
- $responseData = json_decode($response['body'], true);
- dLog('generate')->info('即梦AI 4.0 API提交任务响应: ', $responseData);
- logDB('generate', 'info', '即梦AI 4.0 API提交任务响应', ['task_id' => $task->task_id, 'response' => $responseData]);
-
- if ($responseData['code'] !== 10000) {
- // API返回错误
- logDB('generate', 'error', '即梦AI任务提交失败', ['task_id' => $task->task_id, 'error' => $responseData['message'] ?? 'API Error']);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => $responseData['message'] ?? 'API Error',
- 'extra_params' => $responseData['data'] ?? []
- ]);
- } else {
- // 任务提交成功,更新状态为处理中
- $updateData = [];
- //存储API返回的任务ID
- if (isset($responseData['data']['task_id'])) {
- $updateData['task_id'] = $responseData['data']['task_id'];
- $updateData['extra_params'] = $responseData ?? [];
- }
-
- $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING, $updateData);
- }
- } catch (\Exception $e) {
- // 记录错误
- logDB('generate', 'error', '即梦AI任务提交异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => 'API请求失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 提交任务到GPT-Image2 API
- *
- * @param MpGeneratePicTask $task
- * @return void
- */
- public function submitTaskToGptImage2Api(MpGeneratePicTask $task): void
- {
- try {
- // 验证环境变量配置
- $apiKey = env('GPT_IMAGE2_API_KEY');
-
- if (empty($apiKey)) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => 'GPT-Image2 API KEY未配置,请检查环境变量GPT_IMAGE2_API_KEY'
- ]);
- return;
- }
-
- // 更新状态为处理中
- $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING);
-
- // $api_url = 'https://token.ithinkai.cn/v1/images/generations';
- $api_url = 'https://api.nonelinear.com/v1/images/generations';
- $isEditMode = false;
-
- // 参考图片 - 如果有参考图则使用 /edits 接口
- if ($task->ref_img_url) {
- // $api_url = 'https://token.ithinkai.cn/v1/images/edits';
- // $isEditMode = true;
- $api_url = 'https://api.nonelinear.com/v1/images/generations';
- }
-
- dLog('generate')->info('开始调用GPT-Image2 API', ['task_id' => $task->task_id, 'mode' => $isEditMode ? 'edit' : 'generation']);
- logDB('generate', 'info', '开始调用GPT-Image2 API', ['task_id' => $task->task_id, 'mode' => $isEditMode ? 'edit' : 'generation']);
-
- // 创建专用客户端,优化配置
- $gptClient = new Client([
- 'timeout' => 600, // 10分钟超时
- 'connect_timeout' => 30, // 连接超时10秒
- 'http_errors' => false, // 不自动抛出HTTP错误
- 'verify' => false, // 禁用SSL验证(如果有证书问题)
- 'allow_redirects' => true,
- ]);
-
- // 根据是否有参考图选择不同的请求方式
- if ($isEditMode) {
- // 使用原生 cURL 处理 multipart/form-data 格式
- $imageUrl = is_array($task->ref_img_url) ? $task->ref_img_url[0] : $task->ref_img_url;
-
- dLog('generate')->info('下载参考图片', ['image_url' => $imageUrl]);
-
- // 下载图片内容
- $imageContent = @file_get_contents($imageUrl);
- if ($imageContent === false) {
- throw new \Exception('下载参考图片失败: ' . $imageUrl);
- }
-
- dLog('generate')->info('参考图片下载完成', ['size' => strlen($imageContent)]);
-
- // 保存为临时文件(cURL 需要真实文件路径)
- $extension = pathinfo(parse_url($imageUrl, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'png';
- $tempFile = tempnam(sys_get_temp_dir(), 'gpt_img_') . '.' . $extension;
- file_put_contents($tempFile, $imageContent);
-
- dLog('generate')->info('临时文件创建成功', ['file' => $tempFile, 'size' => filesize($tempFile)]);
-
- // 构建 POST 字段
- $postFields = [
- 'image' => new \CURLFile($tempFile, 'image/' . $extension, 'image.' . $extension),
- 'prompt' => $task->prompt,
- 'model' => 'gpt-image-2',
- 'n' => (int)$task->image_num,
- ];
-
- // 尺寸参数
- if ($task->width && $task->height) {
- $postFields['size'] = $task->width . 'x' . $task->height;
- }
-
- dLog('generate')->info('GPT-Image2 API参数(编辑模式-cURL)', ['api_url' => $api_url, 'prompt' => $task->prompt, 'size' => ($task->width . 'x' . $task->height), 'n' => (int)$task->image_num]);
- logDB('generate', 'info', 'GPT-Image2任务提交(编辑模式)', ['task_id' => $task->task_id, 'api_url' => $api_url, 'image_url' => $imageUrl, 'prompt' => $task->prompt]);
-
- $startTime = microtime(true);
-
- // 使用原生 cURL
- $ch = curl_init();
- curl_setopt_array($ch, [
- CURLOPT_URL => $api_url,
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_POST => true,
- CURLOPT_POSTFIELDS => $postFields,
- CURLOPT_HTTPHEADER => [
- 'Authorization: Bearer ' . $apiKey,
- 'Accept: application/json',
- 'Expect:', // 移除 Expect: 100-continue,避免等待
- ],
- CURLOPT_TIMEOUT => 600,
- CURLOPT_CONNECTTIMEOUT => 30,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, // 强制使用 HTTP/1.1
- ]);
-
- dLog('generate')->info('开始发送cURL请求');
-
- $responseBody = curl_exec($ch);
- $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $curlError = curl_error($ch);
- $curlErrno = curl_errno($ch);
- curl_close($ch);
-
- // 删除临时文件
- @unlink($tempFile);
-
- $elapsed = round(microtime(true) - $startTime, 2);
- dLog('generate')->info('cURL请求完成', ['elapsed' => $elapsed . 's', 'http_code' => $statusCode, 'curl_errno' => $curlErrno]);
-
- if ($curlErrno !== 0) {
- throw new \Exception('cURL错误: ' . $curlError . ' (错误码: ' . $curlErrno . ')');
- }
-
- if (empty($responseBody)) {
- throw new \Exception('API返回空响应,HTTP状态码: ' . $statusCode);
- }
- } else {
- // 使用 JSON 格式 (原有的文生图模式)
- $apiParams = [
- 'model' => 'gpt-image-2',
- 'prompt' => $task->prompt,
- 'n' => (int)$task->image_num,
- ];
-
- // 尺寸参数
- if ($task->width && $task->height) {
- $apiParams['size'] = $task->width . 'x' . $task->height;
- }
- if ($task->ref_img_url) {
- $imageUrl = is_array($task->ref_img_url) ? $task->ref_img_url[0] : $task->ref_img_url;
- if ($imageUrl) {
- $apiParams['image'] = $imageUrl;
- }
- }
-
- dLog('generate')->info('GPT-Image2 API参数', $apiParams);
- logDB('generate', 'info', 'GPT-Image2任务提交', ['task_id' => $task->task_id, 'api_url' => $api_url, 'params' => $apiParams]);
-
- $startTime = microtime(true);
-
- // 调用GPT-Image2 API
- $response = $gptClient->post($api_url, [
- 'headers' => [
- 'Authorization' => 'Bearer ' . $apiKey,
- 'Content-Type' => 'application/json',
- ],
- 'json' => $apiParams,
- ]);
-
- $statusCode = $response->getStatusCode();
- $responseBody = $response->getBody()->getContents();
-
- $elapsed = round(microtime(true) - $startTime, 2);
- dLog('generate')->info('Guzzle请求完成', ['elapsed' => $elapsed . 's', 'http_code' => $statusCode]);
-
- if (empty($responseBody)) {
- throw new \Exception('API返回空响应,HTTP状态码: ' . $statusCode);
- }
- }
-
- // 解析响应
- dLog('generate')->info('响应数据长度', ['length' => strlen($responseBody)]);
-
- $responseData = json_decode($responseBody, true);
-
- if (json_last_error() !== JSON_ERROR_NONE) {
- dLog('generate')->error('JSON解析失败', ['error' => json_last_error_msg(), 'body' => substr($responseBody, 0, 500)]);
- throw new \Exception('JSON解析失败: ' . json_last_error_msg());
- }
-
- dLog('generate')->info('GPT-Image2 API响应', $responseData);
- logDB('generate', 'info', 'GPT-Image2 API响应', ['task_id' => $task->task_id, 'response' => $responseData]);
-
- if (isset($responseData['error'])) {
- // API返回错误
- logDB('generate', 'error', 'GPT-Image2任务失败', ['task_id' => $task->task_id, 'error' => $responseData['error']['message'] ?? 'API Error']);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => $responseData['error']['message'] ?? 'API Error',
- 'result_json' => $responseData
- ]);
- } else {
- // 任务提交成功,直接处理结果
- dLog('generate')->info('开始处理GPT-Image2响应结果');
- $this->processGptImage2ApiResponse($task, $responseData);
- }
- } catch (\Exception $e) {
- // 记录错误
- dLog('generate')->error('GPT-Image2 API请求失败: ' . $e->getMessage(), [
- 'task_id' => $task->task_id,
- 'trace' => $e->getTraceAsString()
- ]);
- logDB('generate', 'error', 'GPT-Image2任务异常', [
- 'task_id' => $task->task_id,
- 'error' => $e->getMessage(),
- 'file' => $e->getFile(),
- 'line' => $e->getLine()
- ]);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => 'API请求失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 处理GPT-Image2 API响应结果
- *
- * @param MpGeneratePicTask $task
- * @param array $responseData
- * @return void
- */
- private function processGptImage2ApiResponse(MpGeneratePicTask $task, array $responseData): void
- {
- try {
- if (!isset($responseData['data']) || empty($responseData['data'])) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '未返回图片数据',
- 'result_json' => $responseData
- ]);
- return;
- }
- $result_urls = [];
- foreach ($responseData['data'] as $imageData) {
- if (isset($imageData['url'])) {
- $url = $imageData['url'];
- $pic_name = 'ai_generation_gpt_' . time() . '_' . uniqid();
- $pic_ext = getImgExtFromUrl($url);
- $pic_name = $pic_name . $pic_ext;
-
- if ($pic_ext === '.png') {
- $comporessed_data = compressRemoteImageUrlToSize($url);
- $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
- } else {
- // 将图片另存到tos
- $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
- }
-
- $result_urls[] = $url;
- }
- }
- if (empty($result_urls)) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '所有图片生成失败',
- 'result_json' => $responseData
- ]);
- return;
- }
- // 更新任务状态为成功
- $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
- 'result_url' => $result_urls,
- 'result_json' => $responseData
- ]);
- // 同步调整分镜图片状态和结果
- $segment_id = getProp($task, 'alias_segment_id');
- if ($segment_id) {
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'img_url' => $result_urls[0],
- 'pic_task_status' => '已完成',
- ]);
-
- // 如果是首帧图ID则更新anime表
- if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
- $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
- DB::table('mp_animes')->where('id', $anime_id)->update(['first_frame_url' => $result_urls[0], 'updated_at' => date('Y-m-d H:i:s')]);
- Redis::srem('anime_first_frame_urls', $segment_id);
- }
- }
- } catch (\Exception $e) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '处理响应失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 提交任务到火山图片生成API
- *
- * @param MpGeneratePicTask $task
- * @return void
- */
- public function submitTaskToVolcApi(MpGeneratePicTask $task): void
- {
- try {
- // 验证环境变量配置
- $apiKey = env('VOLC_AI_API_KEY');
-
- if (empty($apiKey)) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '火山引擎API KEY未配置,请检查环境变量VOLC_AI_API_KEY'
- ]);
- return;
- }
-
- // 更新状态为处理中
- $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING);
-
- // 构建火山图片生成API请求参数
- $apiParams = [
- 'model' => isset(BaseConst::MODELS_MAP[$task->model]) ? BaseConst::MODELS_MAP[$task->model] : $task->model,
- 'prompt' => $task->prompt,
- 'watermark' => false,
- ];
-
- // 尺寸参数
- if ($task->width && $task->height) {
- $apiParams['size'] = $task->width . 'x' . $task->height;
- }
-
- // 参考图片
- if ($task->ref_img_url) {
- if (is_array($task->ref_img_url)) {
- // $apiParams['image'] = count($task->ref_img_url) === 1 ? $task->ref_img_url[0] : $task->ref_img_url;
- $apiParams['image'] = $task->ref_img_url;
- } else {
- $apiParams['image'] = $task->ref_img_url;
- }
- }
- // 生成多图或者单图
- if ((int)$task->image_num === 1) {
- $apiParams['sequential_image_generation'] = 'disabled';
- }else if ($task->image_num > 1) {
- $apiParams['sequential_image_generation'] = 'auto';
- $apiParams['sequential_image_generation_options']['max_images'] = $task->image_num;
- }
- dLog('generate')->info('火山图片生成API参数: ', $apiParams);
- logDB('generate', 'info', '火山图片生成任务提交', ['task_id' => $task->task_id, 'params' => $apiParams]);
-
- // 调用火山图片生成API
- $response = $this->httpClient->post('https://ark.cn-beijing.volces.com/api/v3/images/generations', [
- 'headers' => [
- 'Authorization' => 'Bearer ' . $apiKey,
- 'Content-Type' => 'application/json',
- ],
- 'json' => $apiParams,
- ]);
-
- $responseData = json_decode($response->getBody()->getContents(), true);
- dLog('generate')->info('火山图片生成API响应: ', $responseData);
- logDB('generate', 'info', '火山图片生成API响应', ['task_id' => $task->task_id, 'response' => $responseData]);
-
- if (isset($responseData['error'])) {
- // API返回错误
- logDB('generate', 'error', '火山图片生成任务失败', ['task_id' => $task->task_id, 'error' => $responseData['error']['message'] ?? 'API Error']);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => $responseData['error']['message'] ?? 'API Error',
- 'result_json' => $responseData
- ]);
- } else {
- // 任务提交成功,直接处理结果
- $this->processVolcApiResponse($task, $responseData);
- }
- } catch (\Exception $e) {
- // 记录错误
- dLog('generate')->error('火山API请求失败: ' . $e->getMessage());
- logDB('generate', 'error', '火山图片生成任务异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => 'API请求失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 处理火山API响应结果
- *
- * @param MpGeneratePicTask $task
- * @param array $responseData
- * @return void
- */
- private function processVolcApiResponse(MpGeneratePicTask $task, array $responseData): void
- {
- try {
- if (!isset($responseData['data']) || empty($responseData['data'])) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '未返回图片数据',
- 'result_json' => $responseData
- ]);
- return;
- }
- $result_urls = [];
- foreach ($responseData['data'] as $imageData) {
- if (isset($imageData['error'])) {
- // 单张图片生成失败
- dLog('generate')->warning('单张图片生成失败: ', $imageData['error']);
- continue;
- }
- if (isset($imageData['url'])) {
- $url = $imageData['url'];
- $pic_name = 'ai_generation_' . time() . '_' . uniqid();
- $pic_ext = getImgExtFromUrl($url);
- $pic_name = $pic_name . $pic_ext;
-
- if ($pic_ext === '.png') {
- $comporessed_data = compressRemoteImageUrlToSize($url);
- $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
- } else {
- // 将图片另存到tos
- $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
- }
-
- $result_urls[] = $url;
- }
- }
- if (empty($result_urls)) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '所有图片生成失败',
- 'result_json' => $responseData
- ]);
- return;
- }
- // 更新任务状态为成功
- $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
- 'result_url' => $result_urls,
- 'result_json' => $responseData
- ]);
- // 同步调整分镜图片状态和结果
- $segment_id = getProp($task, 'alias_segment_id');
- if ($segment_id) {
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'img_url' => $result_urls[0],
- 'pic_task_status' => '已完成',
- ]);
-
- // 如果是首帧图ID则更新anime表
- if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
- $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
- DB::table('mp_animes')->where('id', $anime_id)->update(['first_frame_url' => $result_urls[0], 'updated_at' => date('Y-m-d H:i:s')]);
- Redis::srem('anime_first_frame_urls', $segment_id);
- }
- }
- } catch (\Exception $e) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '处理响应失败: ' . $e->getMessage()
- ]);
- }
- }
- public function getTaskList($data)
- {
- $task_id = getProp($data, 'task_id');
- $status = getProp($data, 'status');
- $query = MpGeneratePicTask::select('*');
- if ($task_id) {
- $query->where('id', $task_id);
- }
- if ($status) {
- $query->where('status', $status);
- }
- return $query->orderBy('created_at', 'desc')->paginate();
- }
- /**
- * 查询任务状态
- *
- * @param MpGeneratePicTask $task
- * @return array
- */
- public function queryTaskStatus(MpGeneratePicTask $task): array
- {
- // 根据模型类型调用不同的查询方法
- if ($task->model === self::MODEL_JIMENG_4) {
- return $this->queryJimengTaskStatus($task);
- } elseif (in_array($task->model, BaseConst::NANO_BANANA_MODELS)) {
- return $this->queryNanoBananaTaskStatus($task);
- } else {
- // 火山API是同步返回结果,不需要查询
- return [
- 'status' => $task->status === MpGeneratePicTask::STATUS_SUCCESS ? 'success' : 'failed',
- 'error_message' => $task->error_message,
- 'result_url' => $task->result_url,
- 'result_json' => $task->result_json ?? []
- ];
- }
- }
- /**
- * 查询即梦AI任务状态
- *
- * @param MpGeneratePicTask $task
- * @return array
- */
- private function queryJimengTaskStatus(MpGeneratePicTask $task): array
- {
- try {
- // 获取API任务ID
- $apiTaskId = $task->task_id ?? null;
-
- if (!$apiTaskId) {
- return [
- 'status' => 'failed',
- 'error_message' => 'API任务ID不存在',
- 'result_url' => null
- ];
- }
-
- //构建查询参数
- $apiParams = [
- 'req_key' => 'jimeng_t2i_v40',
- 'task_id' => $apiTaskId,
- 'req_json' => '{"return_url":true}' // 返回URL格式
- ];
-
- //调用即梦AI 4.0 API查询任务状态
- $response = $this->volcEngineService->request(
- 'POST',
- 'visual.volcengineapi.com',
- '/', // 使用根路径
- [], // Query参数
- json_encode($apiParams),
- env('VOLC_AI_AK'),
- env('VOLC_AI_SK'),
- 'cv',
- 'cn-north-1',
- 'CVSync2AsyncGetResult',
- '2022-08-31',
- 'application/json'
- );
-
- $responseData = json_decode($response['body'], true);
- dLog('generate')->info('即梦AI 4.0 API查询任务状态响应: ', $responseData);
- logDB('generate', 'info', '即梦AI任务状态查询', ['task_id' => $apiTaskId, 'response' => $responseData]);
-
- if ($responseData['code'] !== 10000) {
- // API返回错误
- logDB('generate', 'error', '即梦AI任务状态查询失败', ['task_id' => $apiTaskId, 'error' => $responseData['message'] ?? 'API Error']);
- return [
- 'status' => 'failed',
- 'error_message' => $responseData['message'] ?? 'API Error',
- 'result_url' => null,
- 'result_json' => $responseData ?? []
- ];
- }
-
- // 解析API响应
- $result = $responseData['data'] ?? [];
- $taskStatus = $result['status'] ?? 'failed';
-
- $returnData = [
- 'status' => $taskStatus,
- 'error_message' => null,
- 'result_url' => null,
- 'result_json' => $responseData ?? []
- ];
-
- // 如果任务成功,获取结果URL
- if ($taskStatus === 'done' && isset($result['image_urls']) && count($result['image_urls']) > 0) {
- $result_urls = [];
- foreach ($result['image_urls'] as $url) {
- $pic_name = 'ai_generation_' . time() . '_' . uniqid();
- $pic_ext = getImgExtFromUrl($url);
- $pic_name = $pic_name . $pic_ext;
-
- if ($pic_ext === '.png') {
- $comporessed_data = compressRemoteImageUrlToSize($url);
- $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
- }else {
- // 将图片另存到tos
- $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
- }
-
- $result_urls[] = $url;
- }
- $returnData['result_url'] = $result_urls;
- $returnData['status'] = 'success';
- } elseif (in_array($taskStatus, ['not_found', 'expired'])) {
- $returnData['status'] = 'failed';
- $returnData['error_message'] = '任务未找到或已过期';
- } elseif ($taskStatus === 'failed') {
- $returnData['status'] = 'failed';
- $returnData['error_message'] = '任务执行失败';
- }
- // in_queue 或 generating状态保持原status
-
- return $returnData;
- } catch (\Exception $e) {
- return [
- 'status' => 'failed',
- 'error_message' => $e->getMessage(),
- 'result_url' => null
- ];
- }
- }
- /**
- * 提交任务到NanoBanana API
- *
- * @param MpGeneratePicTask $task
- * @return void
- */
- private function submitTaskToNanoBananaApi(MpGeneratePicTask $task): void
- {
- try {
- // 验证环境变量配置
- $apiKey = env('NANO_BANANA_API_KEY');
-
- if (empty($apiKey)) {
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => 'NanoBanana API KEY未配置,请检查环境变量NANO_BANANA_API_KEY'
- ]);
- return;
- }
-
- // 根据模型选择API地址
- switch ($task->model) {
- case self::MODEL_NANO_BANANA_2:
- $apiUrl = 'https://api.wuyinkeji.com/api/async/image_nanoBanana2';
- break;
- case self::MODEL_NANO_BANANA_PRO:
- $apiUrl = 'https://api.wuyinkeji.com/api/async/image_nanoBanana_pro';
- break;
- case self::MODEL_GPT_IMAGE_2:
- $apiUrl = 'https://api.wuyinkeji.com/api/async/image_gpt';
- break;
- default:
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '不支持的模型类型: ' . $task->model
- ]);
- logDB('generate', 'error', '模型类型错误', ['task_id' => $task->task_id, 'model' => $task->model]);
- return;
- }
-
- // 构建API请求参数
- $apiParams = [
- 'key' => $apiKey,
- 'prompt' => $task->prompt,
- ];
- if ($task->model == self::MODEL_GPT_IMAGE_2) {
- // 该模型下,size需设置为9:16类似的数值,请根据如下比例反推
- $apiParams['size'] = $this->getRatioFromSize($task->width, $task->height);
- }else {
- // 尺寸参数(根据宽高判断)
- $area = $task->width * $task->height;
- if ($area >= 1024*1024 && $area < 2048*2048) {
- $apiParams['size'] = '1k';
- } elseif ($area >= 2048*2048) {
- $apiParams['size'] = '2k';
- } else {
- $apiParams['size'] = '1k'; // 默认1k
- }
-
- // 画面比例
- if ($task->width && $task->height) {
- $ratio = $task->width . ':' . $task->height;
- // 简化比例
- $gcd = $this->gcd($task->width, $task->height);
- $ratio = ($task->width / $gcd) . ':' . ($task->height / $gcd);
- $apiParams['aspectRatio'] = $ratio;
- }
- }
-
- // 参考图片
- if ($task->ref_img_url) {
- $apiParams['urls'] = is_array($task->ref_img_url) ? $task->ref_img_url : [$task->ref_img_url];
- }
- dLog('generate')->info('NanoBanana API参数: ', $apiParams);
- logDB('generate', 'info', 'NanoBanana任务提交', ['task_id' => $task->task_id, 'model' => $task->model, 'params' => $apiParams]);
-
- // 调用NanoBanana API
- $response = $this->httpClient->post($apiUrl, [
- 'query' => ['key' => $apiKey],
- 'json' => $apiParams,
- ]);
-
- $responseData = json_decode($response->getBody()->getContents(), true);
- dLog('generate')->info('NanoBanana API响应: ', $responseData);
- logDB('generate', 'info', 'NanoBanana API响应', ['task_id' => $task->task_id, 'response' => $responseData]);
-
- if ($responseData['code'] !== 200) {
- // API返回错误
- logDB('generate', 'error', 'NanoBanana任务提交失败', ['task_id' => $task->task_id, 'error' => $responseData['msg'] ?? 'API Error']);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => $responseData['msg'] ?? 'API Error',
- 'extra_params' => $responseData
- ]);
- } else {
- // 任务提交成功,更新状态为处理中
- $updateData = [];
- // 存储API返回的任务ID
- if (isset($responseData['data']['id'])) {
- $updateData['task_id'] = $responseData['data']['id'];
- $updateData['extra_params'] = $responseData;
- }
-
- $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING, $updateData);
- }
- } catch (\Exception $e) {
- // 记录错误
- logDB('generate', 'error', 'NanoBanana任务提交异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => 'API请求失败: ' . $e->getMessage()
- ]);
- }
- }
- /**
- * 查询NanoBanana任务状态
- *
- * @param MpGeneratePicTask $task
- * @return array
- */
- private function queryNanoBananaTaskStatus(MpGeneratePicTask $task): array
- {
- try {
- // 获取API任务ID
- $apiTaskId = $task->task_id ?? null;
- $apiKey = env('NANO_BANANA_API_KEY');
-
- if (!$apiTaskId) {
- return [
- 'status' => 'failed',
- 'error_message' => 'API任务ID不存在',
- 'result_url' => null
- ];
- }
-
- if (empty($apiKey)) {
- return [
- 'status' => 'failed',
- 'error_message' => 'NanoBanana API KEY未配置',
- 'result_url' => null
- ];
- }
-
- // 调用统一查询接口
- $response = $this->httpClient->get('https://api.wuyinkeji.com/api/async/detail', [
- 'query' => [
- 'key' => $apiKey,
- 'id' => $apiTaskId
- ]
- ]);
-
- $responseData = json_decode($response->getBody()->getContents(), true);
- dLog('generate')->info('NanoBanana任务状态查询响应: ', $responseData);
- logDB('generate', 'info', 'NanoBanana任务状态查询', ['task_id' => $apiTaskId, 'response' => $responseData]);
-
- if ($responseData['code'] !== 200) {
- // API返回错误
- logDB('generate', 'error', 'NanoBanana任务状态查询失败', ['task_id' => $apiTaskId, 'error' => $responseData['msg'] ?? 'API Error']);
- return [
- 'status' => 'failed',
- 'error_message' => $responseData['msg'] ?? 'API Error',
- 'result_url' => null,
- 'result_json' => $responseData
- ];
- }
-
- // 解析API响应
- $data = $responseData['data'] ?? [];
- $taskStatus = $data['status'] ?? 0;
-
- $returnData = [
- 'status' => 'processing',
- 'error_message' => null,
- 'result_url' => null,
- 'result_json' => $responseData
- ];
-
- // status: 2表示成功
- if ($taskStatus === 2 && isset($data['result']) && !empty($data['result'])) {
- $result_urls = [];
- foreach ($data['result'] as $url) {
- $pic_name = 'ai_generation_nanobanana_' . time() . '_' . uniqid();
- $pic_ext = getImgExtFromUrl($url);
- $pic_name = $pic_name . $pic_ext;
-
- if ($pic_ext === '.png') {
- $comporessed_data = compressRemoteImageUrlToSize($url);
- $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
- } else {
- // 将图片另存到tos
- $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
- }
-
- $result_urls[] = $url;
- }
- $returnData['result_url'] = $result_urls;
- $returnData['status'] = 'success';
- } elseif ($taskStatus === 3) {
- // status: 3表示失败
- $returnData['status'] = 'failed';
- $returnData['error_message'] = $data['message'] ?? '任务执行失败';
- }
- // status: 0或1表示处理中,保持processing状态
-
- return $returnData;
- } catch (\Exception $e) {
- return [
- 'status' => 'failed',
- 'error_message' => $e->getMessage(),
- 'result_url' => null
- ];
- }
- }
- /**
- * 计算最大公约数(用于简化比例)
- *
- * @param int $a
- * @param int $b
- * @return int
- */
- private function gcd(int $a, int $b): int
- {
- while ($b != 0) {
- $temp = $b;
- $b = $a % $b;
- $a = $temp;
- }
- return $a;
- }
- /**
- * 创建素材
- *
- * @param array $params
- * @return array
- */
- public function createAsset(array $params): array
- {
- try {
- // 验证必填参数
- if (empty($params['url'])) {
- return [
- 'code' => 1,
- 'msg' => '素材URL不能为空',
- 'data' => null
- ];
- }
- // 先获取表中是否已有该url
- $asset = DB::table('mp_assets')->where('url', $params['url'])->first();
- if ($asset) {
- return [
- 'code' => 0,
- 'msg' => '创建成功',
- 'data' => [
- 'id' => $asset->id,
- 'asset_id' => $asset->asset_id,
- 'group_id' => $asset->group_id,
- 'group_name' => $asset->group_name,
- ]
- ];
- }
- // 获取API配置
- $apiKey = env('ZHIZHEN_AI_SK');
- $apiUrl = 'https://model-relay.zzengine.net';
-
- if (empty($apiKey)) {
- return [
- 'code' => 1002,
- 'msg' => '智真AI API KEY未配置,请检查环境变量ZHIZHEN_AI_SK',
- 'data' => null
- ];
- }
- // 构建请求参数
- $requestData = [
- 'url' => $params['url'],
- 'asset_type' => $params['asset_type'] ?? MpAsset::TYPE_IMAGE,
- ];
- // 可选参数
- if (!empty($params['name'])) {
- $requestData['name'] = $params['name'];
- }
- if (!empty($params['group_id'])) {
- $requestData['group_id'] = $params['group_id'];
- }
- dLog('generate')->info('智真AI创建素材请求参数: ', $requestData);
- // 调用智真AI API
- $response = $this->httpClient->post($apiUrl . '/api/v1/asset/create', [
- 'headers' => [
- 'X-Api-Key' => $apiKey,
- 'Content-Type' => 'application/json',
- ],
- 'json' => $requestData,
- ]);
- $responseData = json_decode($response->getBody()->getContents(), true);
- dLog('generate')->info('智真AI创建素材响应: ', $responseData);
- logDB('generate', 'info', '智真AI创建素材', ['params' => $requestData, 'response' => $responseData]);
- if ($responseData['code'] !== 0) {
- return [
- 'code' => $responseData['code'],
- 'msg' => $responseData['msg'] ?? '创建素材失败',
- 'data' => null
- ];
- }
- // 保存素材记录到数据库
- $assetData = $responseData['data'] ?? [];
- $asset = MpAsset::create([
- 'asset_id' => $assetData['asset_id'] ?? '',
- 'group_id' => $assetData['group_id'] ?? null,
- 'group_name' => $assetData['group_name'] ?? null,
- 'name' => $params['name'] ?? null,
- 'url' => $params['url'],
- 'asset_type' => $params['asset_type'] ?? MpAsset::TYPE_IMAGE,
- 'status' => MpAsset::STATUS_PROCESSING,
- 'extra_params' => $responseData,
- ]);
- return [
- 'code' => 0,
- 'msg' => '创建成功',
- 'data' => [
- 'id' => $asset->id,
- 'asset_id' => $asset->asset_id,
- 'group_id' => $asset->group_id,
- 'group_name' => $asset->group_name,
- ]
- ];
- } catch (\Exception $e) {
- dLog('generate')->error('创建素材异常: ' . $e->getMessage());
- logDB('generate', 'error', '创建素材异常', ['params' => $params, 'error' => $e->getMessage()]);
-
- return [
- 'code' => 20003,
- 'msg' => '创建素材失败: ' . $e->getMessage(),
- 'data' => null
- ];
- }
- }
- /**
- * 查询素材
- *
- * @param string $assetId
- * @return array
- */
- public function getAsset(string $assetId): array
- {
- try {
- // 验证参数
- if (empty($assetId)) {
- return [
- 'code' => 20003,
- 'msg' => '素材ID不能为空',
- 'data' => null
- ];
- }
- // 先获取表中是否已有该url
- $assetInfo = DB::table('mp_assets')->where('asset_id', $assetId)->first();
- if ($assetInfo) {
- $assetInfo = (array)$assetInfo;
- $status = getProp($assetInfo, 'status');
- if (in_array($status, ['Active', 'Failed'])) {
- $assetInfo['id'] = $assetInfo['asset_id'];
- return [
- 'code' => 0,
- 'msg' => '查询成功',
- 'data' => [
- 'asset' => $assetInfo
- ]
- ];
- }
- }
- // 获取API配置
- $apiKey = env('ZHIZHEN_AI_SK');
- $apiUrl = 'https://model-relay.zzengine.net';
-
- if (empty($apiKey)) {
- return [
- 'code' => 1002,
- 'msg' => '智真AI API KEY未配置,请检查环境变量ZHIZHEN_AI_SK',
- 'data' => null
- ];
- }
- dLog('generate')->info('智真AI查询素材: ' . $assetId);
- // 调用智真AI API
- $response = $this->httpClient->post($apiUrl . '/api/v1/asset/get', [
- 'headers' => [
- 'X-Api-Key' => $apiKey,
- 'Content-Type' => 'application/json',
- ],
- 'json' => [
- 'asset_id' => $assetId,
- ],
- ]);
- $responseData = json_decode($response->getBody()->getContents(), true);
- dLog('generate')->info('智真AI查询素材响应: ', $responseData);
- logDB('generate', 'info', '智真AI查询素材', ['asset_id' => $assetId, 'response' => $responseData]);
- if ($responseData['code'] !== 0) {
- return [
- 'code' => $responseData['code'],
- 'msg' => $responseData['msg'] ?? '查询素材失败',
- 'data' => null
- ];
- }
- $assetInfo = $responseData['data']['asset'] ?? [];
- // 更新本地数据库记录
- $localAsset = MpAsset::where('asset_id', $assetId)->first();
- if ($localAsset) {
- $localAsset->update([
- 'status' => $assetInfo['status'] ?? MpAsset::STATUS_PROCESSING,
- 'cover_url' => $assetInfo['url'] ?? null,
- 'extra_params' => $responseData,
- ]);
- }
- return [
- 'code' => 0,
- 'msg' => '查询成功',
- 'data' => [
- 'asset' => $assetInfo
- ]
- ];
- } catch (\Exception $e) {
- dLog('generate')->error('查询素材异常: ' . $e->getMessage());
- logDB('generate', 'error', '查询素材异常', ['asset_id' => $assetId, 'error' => $e->getMessage()]);
-
- return [
- 'code' => 20003,
- 'msg' => '查询素材失败: ' . $e->getMessage(),
- 'data' => null
- ];
- }
- }
- /**
- * 更新所有待处理任务的状态
- *
- * @return void
- */
- public function updatePendingTasks(): void
- {
- dLog('generate')->info('更新图片状态ing');
-
- // 1. 处理火山API的pending任务(批量提交到队列)
- $volcPendingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
- ->whereIn('model', BaseConst::VOLC_PIC_MODELS)
- ->orderBy('created_at', 'asc')
- ->limit(50) // 每次最多处理50个任务,避免超时
- ->get();
- foreach ($volcPendingTasks as $task) {
- dLog('generate')->info('开始分发火山API任务到队列: ' . $task->task_id);
-
- // 分发到队列
- \App\Jobs\ProcessVolcImageGenerationJob::dispatch($task->id)->onConnection('redis');
- }
-
- // 2. 处理GPT-Image2的pending任务(批量提交到队列)
- $gptImage2PendingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
- ->whereIn('model', BaseConst::GPT_IMAGE2_MODELS)
- ->orderBy('created_at', 'asc')
- ->limit(50) // 每次最多处理50个任务,避免超时
- ->get();
- foreach ($gptImage2PendingTasks as $task) {
- dLog('generate')->info('开始分发GPT-Image2任务到队列: ' . $task->task_id);
-
- // 分发到队列
- \App\Jobs\ProcessGptImage2GenerationJob::dispatch($task->id)->onConnection('redis');
- }
-
- // 3. 获取所有处理中的任务(即梦AI和NanoBanana系列需要查询状态)
- $processingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)
- ->whereIn('model', array_merge([self::MODEL_JIMENG_4], BaseConst::NANO_BANANA_MODELS))
- ->get();
- foreach ($processingTasks as $task) {
- $statusInfo = $this->queryTaskStatus($task);
- if ($statusInfo['status'] === 'success') {
- logDB('generate', 'info', '即梦AI图片生成任务成功', ['task_id' => $task->task_id, 'result_url' => $statusInfo['result_url']]);
- $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- // 同步调整分镜图片状态和结果
- $segment_id = getProp($task, 'alias_segment_id');
- if ($segment_id) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'img_url' => $statusInfo['result_url'][0],
- 'pic_task_status' => '已完成',
- ]);
-
- // 如果是首帧图ID则更新anime表
- if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
- $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
- DB::table('mp_animes')->where('id', $anime_id)->update(['first_frame_url'=>$statusInfo['result_url'][0], 'updated_at'=>date('Y-m-d H:i:s')]);
- Redis::srem('anime_first_frame_urls', $segment_id);
- }
- }
- } elseif ($statusInfo['status'] === 'failed') {
- logDB('generate', 'error', '即梦AI图片生成任务失败', ['task_id' => $task->task_id, 'error' => $statusInfo['error_message']]);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- if (getProp($task, 'alias_segment_id')) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'pic_task_status' => '失败',
- ]);
- }
- }
- // 如果仍然是处理中状态,不做任何操作
-
- //处理:如果任务处理超过12小时,标记为失败
- $processingTime = now()->diffInHours($task->created_at);
- if ($processingTime > 12) {
- logDB('generate', 'warning', '即梦AI图片生成任务超时', ['task_id' => $task->task_id, 'processing_hours' => $processingTime]);
- $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
- 'error_message' => '任务处理超时(超过12小时)'
- ]);
- }
- }
- // 4. 检查是否有任务完成,如果有则处理下一个排队任务(仅即梦AI)
- $this->processNextQueuedTask();
- }
- /**
- * 处理下一个排队的任务
- *
- * @return void
- */
- public function processNextQueuedTask(): void
- {
- // 检查是否还有正在处理的任务(仅即梦AI)
- if ($this->hasProcessingTask()) {
- return; // 如果还有处理中的任务,不处理新任务
- }
- // 获取最早的待处理任务(仅即梦AI)
- $nextTask = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
- ->where('model', self::MODEL_JIMENG_4)
- ->orderBy('created_at', 'asc')
- ->first();
- if ($nextTask) {
- dLog('generate')->info('开始处理排队任务: ' . $nextTask->task_id);
- logDB('generate', 'info', '开始处理即梦AI排队任务', ['task_id' => $nextTask->task_id]);
- $this->submitTaskToJimengApi($nextTask);
- }
- }
- /**
- * 获取任务队列状态
- *
- * @return array
- */
- public function getQueueStatus(): array
- {
- $processingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)->count();
- $pendingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)->count();
-
- return [
- 'processing_count' => $processingCount,
- 'pending_count' => $pendingCount,
- 'can_submit_new_task' => $processingCount === 0
- ];
- }
- /**
- * 处理智真AI的参考图片转素材
- *
- * @param array $referenceImages 参考图片URL数组
- * @param string &$fullPrompt 完整提示词(引用传递,用于删除失败图片的标记)
- * @return array 返回素材ID数组
- */
- public function processReferenceImagesToAssets(array $referenceImages, string &$fullPrompt): array
- {
- $assetIds = [];
- $failedIndexes = []; // 记录失败的图片序号
-
- foreach ($referenceImages as $index => $imageUrl) {
- $imageIndex = $index + 1; // 图片序号从1开始
-
- try {
- dLog('generate')->info("开始处理参考图片 {$imageIndex}: {$imageUrl}");
-
- // 1. 创建素材
- $createResult = $this->createAsset([
- 'url' => $imageUrl,
- 'asset_type' => MpAsset::TYPE_IMAGE,
- 'name' => "参考图片_{$imageIndex}_" . time(),
- ]);
-
- if ($createResult['code'] !== 0) {
- dLog('generate')->warning("图片 {$imageIndex} 创建素材失败: " . $createResult['msg']);
- logDB('generate', 'warning', '创建素材失败', [
- 'image_url' => $imageUrl,
- 'index' => $imageIndex,
- 'error' => $createResult['msg']
- ]);
- $failedIndexes[] = $imageIndex;
- continue;
- }
-
- $assetId = $createResult['data']['asset_id'];
- dLog('generate')->info("图片 {$imageIndex} 素材创建成功,asset_id: {$assetId},开始轮询查询状态");
-
- // 2. 轮询查询素材状态(每3秒查询一次,最多查询100次即5分钟)
- $maxAttempts = 100;
- $attempt = 0;
- $assetStatus = null;
-
- while ($attempt < $maxAttempts) {
- sleep(3); // 等待3秒
- $attempt++;
-
- $getResult = $this->getAsset($assetId);
-
- if ($getResult['code'] !== 0) {
- dLog('generate')->warning("图片 {$imageIndex} 查询素材状态失败: " . $getResult['msg']);
- continue;
- }
-
- $assetStatus = $getResult['data']['asset']['status'] ?? null;
- dLog('generate')->info("图片 {$imageIndex} 素材状态查询第 {$attempt} 次,状态: {$assetStatus}");
-
- if ($assetStatus === 'Active') {
- // 素材可用
- $assetIds[] = $assetId;
- dLog('generate')->info("图片 {$imageIndex} 素材处理成功,asset_id: {$assetId}");
- logDB('generate', 'info', '素材转换成功', [
- 'image_url' => $imageUrl,
- 'index' => $imageIndex,
- 'asset_id' => $assetId
- ]);
- break;
- } elseif ($assetStatus === 'Failed') {
- // 素材处理失败
- dLog('generate')->warning("图片 {$imageIndex} 素材处理失败");
- logDB('generate', 'warning', '素材处理失败', [
- 'image_url' => $imageUrl,
- 'index' => $imageIndex,
- 'asset_id' => $assetId
- ]);
- $failedIndexes[] = $imageIndex;
- break;
- }
- // 其他状态(Processing等)继续等待
- }
-
- // 如果超时还未成功
- if ($attempt >= $maxAttempts && $assetStatus !== 'Active') {
- dLog('generate')->warning("图片 {$imageIndex} 素材处理超时");
- logDB('generate', 'warning', '素材处理超时', [
- 'image_url' => $imageUrl,
- 'index' => $imageIndex,
- 'asset_id' => $assetId,
- 'last_status' => $assetStatus
- ]);
- $failedIndexes[] = $imageIndex;
- }
-
- } catch (\Exception $e) {
- dLog('generate')->error("图片 {$imageIndex} 处理异常: " . $e->getMessage());
- logDB('generate', 'error', '素材转换异常', [
- 'image_url' => $imageUrl,
- 'index' => $imageIndex,
- 'error' => $e->getMessage()
- ]);
- $failedIndexes[] = $imageIndex;
- }
- }
-
- // 处理失败的图片:从 fullPrompt 中删除对应的标记并调整序号
- if (!empty($failedIndexes)) {
- dLog('generate')->info('开始处理失败图片的提示词调整,失败序号: ' . implode(',', $failedIndexes));
-
- // 按序号从大到小排序,避免删除时影响后续序号
- rsort($failedIndexes);
-
- foreach ($failedIndexes as $failedIndex) {
- // 删除失败图片的标记,例如 <图片1>、<图片2> 等
- $pattern = "/<图片{$failedIndex}>/u";
- $fullPrompt = preg_replace($pattern, '', $fullPrompt);
- dLog('generate')->info("已从提示词中删除 <图片{$failedIndex}>");
- }
-
- // 重新调整剩余图片的序号
- // 例如:如果图片2失败,图片3、图片4需要改为图片2、图片3
- $needAdjust = false;
- foreach ($failedIndexes as $failedIndex) {
- $needAdjust = true;
- // 将所有大于失败序号的图片标记序号减1
- for ($i = $failedIndex + 1; $i <= count($referenceImages); $i++) {
- $oldPattern = "/<图片{$i}>/u";
- $newTag = "<图片" . ($i - 1) . ">";
- $fullPrompt = preg_replace($oldPattern, $newTag, $fullPrompt);
- }
- }
-
- if ($needAdjust) {
- dLog('generate')->info('提示词图片序号调整完成');
- logDB('generate', 'info', '提示词调整', [
- 'failed_indexes' => $failedIndexes,
- 'adjusted_prompt' => $fullPrompt
- ]);
- }
- }
-
- dLog('generate')->info('参考图片转素材完成,成功数量: ' . count($assetIds) . ',失败数量: ' . count($failedIndexes));
- // 格式化为可直接在API接口中使用的数组
- foreach($assetIds as &$assetId) {
- $assetId = "asset://{$assetId}";
- }
-
- return $assetIds;
- }
- /**
- * 根据宽高反推图片比例
- * @param int $width 宽度
- * @param int $height 高度
- * @return string 比例字符串,如 "9:16",匹配不到则返回 "auto"
- */
- private function getRatioFromSize($width, $height)
- {
- if (!$width || !$height) {
- return 'auto';
- }
- // 遍历所有预定义的比例,查找匹配的
- foreach (BaseConst::IMAGE_RATIOS as $ratio => $size) {
- if ($size['width'] == $width && $size['height'] == $height) {
- return $ratio;
- }
- }
- // 没有精确匹配,尝试通过计算比例匹配
- $gcd = $this->gcd($width, $height);
- $simplifiedRatio = ($width / $gcd) . ':' . ($height / $gcd);
- // 检查简化后的比例是否在预定义列表中
- if (isset(BaseConst::IMAGE_RATIOS[$simplifiedRatio])) {
- return $simplifiedRatio;
- }
- return 'auto';
- }
- }
|