AIImageGenerationService.php 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  1. <?php
  2. namespace App\Services\AIGeneration;
  3. use App\Models\MpGeneratePicTask;
  4. use App\Models\MpAsset;
  5. use App\Services\VolcEngineService;
  6. use GuzzleHttp\Client;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\Redis;
  11. use App\Consts\BaseConst;
  12. class AIImageGenerationService
  13. {
  14. private $volcEngineService;
  15. private $httpClient;
  16. // 模型常量
  17. const MODEL_JIMENG_4 = 'jimeng_4.0';
  18. const MODEL_NANO_BANANA_2 = 'NanoBanana2';
  19. const MODEL_NANO_BANANA_PRO = 'NanoBananaPro';
  20. const MODEL_GPT_IMAGE_2 = 'GptImage2';
  21. public function __construct(VolcEngineService $volcEngineService)
  22. {
  23. $this->volcEngineService = $volcEngineService;
  24. $this->httpClient = new Client([
  25. 'timeout' => 300,
  26. ]);
  27. }
  28. /**
  29. * 异步创建图片生成任务
  30. *
  31. * @param array $params
  32. * @return MpGeneratePicTask
  33. */
  34. public function createImageGenerationTask(array $params): MpGeneratePicTask
  35. {
  36. // // 获取模型类型,默认使用即梦AI 4.0
  37. // $model = $params['model'] ?? self::MODEL_JIMENG_4;
  38. // 获取模型类型,默认使用即梦seedream5.0-lite
  39. $model = $params['model'] ?? 'doubao-seedream-5-0-lite-260128';
  40. // 检查是否有正在处理的任务(仅即梦AI需要排队)
  41. if ($model === self::MODEL_JIMENG_4 && $this->hasProcessingTask()) {
  42. // 如果有正在处理的任务,创建排队任务
  43. return $this->createQueuedTask($params);
  44. }
  45. // 生成唯一的任务ID
  46. $taskId = 'img_gen_' . time() . '_' . uniqid();
  47. // 创建任务记录
  48. $task = MpGeneratePicTask::create([
  49. 'task_id' => $taskId,
  50. 'alias_segment_id' => $params['alias_segment_id'] ?? 0,
  51. 'prompt' => $params['prompt'] ?? '',
  52. 'width' => $params['width'] ?? 1600,
  53. 'height' => $params['height'] ?? 2848,
  54. 'image_num' => $params['image_num'] ?? 1,
  55. 'scale' => $params['scale'] ?? 50,
  56. 'ref_img_url' => $params['ref_img_urls'] ?? null,
  57. 'mask_img_url' => $params['mask_img_url'] ?? null,
  58. 'extra_params' => $params['extra_params'] ?? null,
  59. 'status' => MpGeneratePicTask::STATUS_PENDING,
  60. 'model' => $model,
  61. ]);
  62. // 即梦AI和NanoBanana系列立即提交任务,火山API在定时任务中提交
  63. if ($model === self::MODEL_JIMENG_4) {
  64. $this->submitTaskToJimengApi($task);
  65. } elseif (in_array($model, BaseConst::NANO_BANANA_MODELS)) {
  66. $this->submitTaskToNanoBananaApi($task);
  67. }
  68. return $task;
  69. }
  70. /**
  71. * 检查是否有正在处理的任务
  72. *
  73. * @return bool
  74. */
  75. private function hasProcessingTask(): bool
  76. {
  77. return MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)
  78. ->exists();
  79. }
  80. /**
  81. * 创建排队任务
  82. *
  83. * @param array $params
  84. * @return MpGeneratePicTask
  85. */
  86. private function createQueuedTask(array $params): MpGeneratePicTask
  87. {
  88. // 生成唯一的任务ID
  89. $taskId = 'img_gen_' . time() . '_' . uniqid();
  90. // 获取模型类型
  91. $model = $params['model'] ?? self::MODEL_JIMENG_4;
  92. // 创建排队状态的任务记录
  93. return MpGeneratePicTask::create([
  94. 'task_id' => $taskId,
  95. 'alias_segment_id' => $params['alias_segment_id'] ?? 0,
  96. 'prompt' => $params['prompt'] ?? '',
  97. 'width' => $params['width'] ?? 1600,
  98. 'height' => $params['height'] ?? 2848,
  99. 'image_num' => $params['image_num'] ?? 1,
  100. 'scale' => $params['scale'] ?? 50,
  101. 'ref_img_url' => $params['ref_img_urls'] ?? null,
  102. 'mask_img_url' => $params['mask_img_url'] ?? null,
  103. 'extra_params' => $params['extra_params'] ?? null,
  104. 'status' => MpGeneratePicTask::STATUS_PENDING,
  105. 'model' => $model,
  106. ]);
  107. }
  108. /**
  109. * 提交任务到即梦AI API
  110. *
  111. * @param MpGeneratePicTask $task
  112. * @return void
  113. */
  114. private function submitTaskToJimengApi(MpGeneratePicTask $task): void
  115. {
  116. try {
  117. // 验证环境变量配置
  118. $accessKey = env('VOLC_AI_AK');
  119. $secretKey = env('VOLC_AI_SK');
  120. if (empty($accessKey) || empty($secretKey)) {
  121. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  122. 'error_message' => '火山引擎访问密钥未配置,请检查环境变量AK和SK'
  123. ]);
  124. return;
  125. }
  126. //构建即梦AI 4.0 API请求参数
  127. $apiParams = [
  128. 'req_key' => 'jimeng_t2i_v40',
  129. 'prompt' => $task->prompt,
  130. 'scale' => $task->scale / 100, //为0-1范围
  131. ];
  132. // 添加可选参数
  133. if ($task->image_num > 1) {
  134. $apiParams['force_single'] = false;
  135. } else {
  136. $apiParams['force_single'] = true;
  137. }
  138. // 参考图片
  139. if ($task->ref_img_url) {
  140. $apiParams['image_urls'] = $task->ref_img_url;
  141. }
  142. // if ($task->mask_img_url) {
  143. // $apiParams['image_urls'] = $task->mask_img_url;
  144. // }
  145. // 尺寸参数
  146. $area = $task->width * $task->height; //计算面积
  147. if ($area >= 1024*1024 && $area <= 4096*4096) {
  148. $apiParams['size'] = (int)$area;
  149. }
  150. dLog('generate')->info('即梦AI文生图参数: ', $apiParams);
  151. logDB('generate', 'info', '即梦AI文生图任务提交', ['task_id' => $task->task_id, 'params' => $apiParams]);
  152. //调用即梦AI 4.0 API提交任务
  153. $response = $this->volcEngineService->request(
  154. 'POST',
  155. 'visual.volcengineapi.com', //即梦AI API域名
  156. '/', // 使用根路径
  157. [], // Query参数
  158. json_encode($apiParams),
  159. $accessKey,
  160. $secretKey,
  161. 'cv', // 服务标识
  162. 'cn-north-1', //区域
  163. 'CVSync2AsyncSubmitTask',
  164. '2022-08-31',
  165. 'application/json'
  166. );
  167. $responseData = json_decode($response['body'], true);
  168. dLog('generate')->info('即梦AI 4.0 API提交任务响应: ', $responseData);
  169. logDB('generate', 'info', '即梦AI 4.0 API提交任务响应', ['task_id' => $task->task_id, 'response' => $responseData]);
  170. if ($responseData['code'] !== 10000) {
  171. // API返回错误
  172. logDB('generate', 'error', '即梦AI任务提交失败', ['task_id' => $task->task_id, 'error' => $responseData['message'] ?? 'API Error']);
  173. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  174. 'error_message' => $responseData['message'] ?? 'API Error',
  175. 'extra_params' => $responseData['data'] ?? []
  176. ]);
  177. } else {
  178. // 任务提交成功,更新状态为处理中
  179. $updateData = [];
  180. //存储API返回的任务ID
  181. if (isset($responseData['data']['task_id'])) {
  182. $updateData['task_id'] = $responseData['data']['task_id'];
  183. $updateData['extra_params'] = $responseData ?? [];
  184. }
  185. $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING, $updateData);
  186. }
  187. } catch (\Exception $e) {
  188. // 记录错误
  189. logDB('generate', 'error', '即梦AI任务提交异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
  190. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  191. 'error_message' => 'API请求失败: ' . $e->getMessage()
  192. ]);
  193. }
  194. }
  195. /**
  196. * 提交任务到GPT-Image2 API
  197. *
  198. * @param MpGeneratePicTask $task
  199. * @return void
  200. */
  201. public function submitTaskToGptImage2Api(MpGeneratePicTask $task): void
  202. {
  203. try {
  204. // 验证环境变量配置
  205. $apiKey = env('GPT_IMAGE2_API_KEY');
  206. if (empty($apiKey)) {
  207. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  208. 'error_message' => 'GPT-Image2 API KEY未配置,请检查环境变量GPT_IMAGE2_API_KEY'
  209. ]);
  210. return;
  211. }
  212. // 更新状态为处理中
  213. $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING);
  214. // $api_url = 'https://token.ithinkai.cn/v1/images/generations'; // 备用地址1
  215. // $api_url = 'https://api.nonelinear.com/v1/images/generations'; // 备用地址2
  216. $api_url = 'https://ai-api.kkidc.com/v1/images/generations';
  217. $isEditMode = false;
  218. // 参考图片 - 如果有参考图则使用 /edits 接口
  219. if ($task->ref_img_url) {
  220. // $api_url = 'https://token.ithinkai.cn/v1/images/edits'; // 备用地址1
  221. // $api_url = 'https://api.nonelinear.com/v1/images/generations'; // 备用地址2
  222. $api_url = 'https://ai-api.kkidc.com/v1/images/edits';
  223. $isEditMode = true;
  224. }
  225. dLog('generate')->info('开始调用GPT-Image2 API', ['task_id' => $task->task_id, 'mode' => $isEditMode ? 'edit' : 'generation']);
  226. logDB('generate', 'info', '开始调用GPT-Image2 API', ['task_id' => $task->task_id, 'mode' => $isEditMode ? 'edit' : 'generation']);
  227. // 创建专用客户端,优化配置
  228. $gptClient = new Client([
  229. 'timeout' => 1800, // 超时
  230. 'connect_timeout' => 120, // 连接超时10秒
  231. 'http_errors' => false, // 不自动抛出HTTP错误
  232. 'verify' => false, // 禁用SSL验证(如果有证书问题)
  233. 'allow_redirects' => true,
  234. ]);
  235. // 根据是否有参考图选择不同的请求方式
  236. if ($isEditMode) {
  237. // 使用原生 cURL 处理 multipart/form-data 格式
  238. $imageUrls = is_array($task->ref_img_url) ? $task->ref_img_url : [$task->ref_img_url];
  239. // 限制最多4张参考图
  240. $imageUrls = array_slice($imageUrls, 0, 4);
  241. dLog('generate')->info('下载参考图片', ['image_urls' => $imageUrls, 'count' => count($imageUrls)]);
  242. // 下载所有参考图片并保存为临时文件
  243. $tempFiles = [];
  244. foreach ($imageUrls as $index => $imageUrl) {
  245. $imageContent = @file_get_contents($imageUrl);
  246. if ($imageContent === false) {
  247. dLog('generate')->warning('下载参考图片失败,跳过', ['image_url' => $imageUrl]);
  248. continue;
  249. }
  250. dLog('generate')->info('参考图片下载完成', ['index' => $index, 'size' => strlen($imageContent)]);
  251. // 保存为临时文件(cURL 需要真实文件路径)
  252. $extension = pathinfo(parse_url($imageUrl, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'png';
  253. $tempFile = tempnam(sys_get_temp_dir(), 'gpt_img_') . '.' . $extension;
  254. file_put_contents($tempFile, $imageContent);
  255. $tempFiles[] = [
  256. 'path' => $tempFile,
  257. 'extension' => $extension
  258. ];
  259. dLog('generate')->info('临时文件创建成功', ['file' => $tempFile, 'size' => filesize($tempFile)]);
  260. }
  261. if (empty($tempFiles)) {
  262. throw new \Exception('所有参考图片下载失败');
  263. }
  264. // 构建 POST 字段
  265. $postFields = [
  266. 'prompt' => $task->prompt,
  267. 'model' => 'gpt-image-2',
  268. 'n' => (string)$task->image_num, // 新接口要求字符串类型
  269. 'response_format' => 'b64_json', // 新接口必填参数
  270. ];
  271. // 尺寸参数(必填)
  272. if ($task->width && $task->height) {
  273. $postFields['size'] = $task->width . 'x' . $task->height;
  274. } else {
  275. $postFields['size'] = '1024x1024'; // 默认尺寸
  276. }
  277. // 添加参考图片文件(支持多图,新接口要求使用 image 字段名)
  278. foreach ($tempFiles as $index => $tempFile) {
  279. $fieldName = 'image'; // 新接口统一使用 image 字段名
  280. $postFields[$fieldName] = new \CURLFile(
  281. $tempFile['path'],
  282. 'image/' . $tempFile['extension'],
  283. 'image' . ($index + 1) . '.' . $tempFile['extension']
  284. );
  285. }
  286. dLog('generate')->info('GPT-Image2 API参数(编辑模式-cURL)', [
  287. 'api_url' => $api_url,
  288. 'prompt' => $task->prompt,
  289. 'size' => $postFields['size'],
  290. 'n' => $postFields['n'],
  291. 'response_format' => $postFields['response_format'],
  292. 'image_count' => count($tempFiles)
  293. ]);
  294. logDB('generate', 'info', 'GPT-Image2任务提交(编辑模式)', [
  295. 'task_id' => $task->task_id,
  296. 'api_url' => $api_url,
  297. 'image_urls' => $imageUrls,
  298. 'prompt' => $task->prompt
  299. ]);
  300. $startTime = microtime(true);
  301. // 使用原生 cURL
  302. $ch = curl_init();
  303. curl_setopt_array($ch, [
  304. CURLOPT_URL => $api_url,
  305. CURLOPT_RETURNTRANSFER => true,
  306. CURLOPT_POST => true,
  307. CURLOPT_POSTFIELDS => $postFields,
  308. CURLOPT_HTTPHEADER => [
  309. 'Authorization: Bearer ' . $apiKey,
  310. 'Accept: application/json',
  311. 'Expect:', // 移除 Expect: 100-continue,避免等待
  312. ],
  313. CURLOPT_TIMEOUT => 600,
  314. CURLOPT_CONNECTTIMEOUT => 30,
  315. CURLOPT_SSL_VERIFYPEER => false,
  316. CURLOPT_SSL_VERIFYHOST => false,
  317. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, // 强制使用 HTTP/1.1
  318. ]);
  319. dLog('generate')->info('开始发送cURL请求');
  320. $responseBody = curl_exec($ch);
  321. $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  322. $curlError = curl_error($ch);
  323. $curlErrno = curl_errno($ch);
  324. curl_close($ch);
  325. // 删除所有临时文件
  326. foreach ($tempFiles as $tempFile) {
  327. @unlink($tempFile['path']);
  328. }
  329. $elapsed = round(microtime(true) - $startTime, 2);
  330. dLog('generate')->info('cURL请求完成', ['elapsed' => $elapsed . 's', 'http_code' => $statusCode, 'curl_errno' => $curlErrno]);
  331. if ($curlErrno !== 0) {
  332. throw new \Exception('cURL错误: ' . $curlError . ' (错误码: ' . $curlErrno . ')');
  333. }
  334. if (empty($responseBody)) {
  335. throw new \Exception('API返回空响应,HTTP状态码: ' . $statusCode);
  336. }
  337. } else {
  338. // 使用 JSON 格式 (原有的文生图模式)
  339. $apiParams = [
  340. 'model' => 'gpt-image-2',
  341. 'prompt' => $task->prompt,
  342. 'n' => (int)$task->image_num,
  343. 'quality' => 'auto', // 新接口必填参数:图像质量等级
  344. 'response_format' => 'b64_json', // 新接口必填参数:返回格式
  345. ];
  346. // 尺寸参数
  347. if ($task->width && $task->height) {
  348. $apiParams['size'] = $task->width . 'x' . $task->height;
  349. } else {
  350. $apiParams['size'] = 'auto'; // 新接口必填参数
  351. }
  352. dLog('generate')->info('GPT-Image2 API参数', $apiParams);
  353. logDB('generate', 'info', 'GPT-Image2任务提交', ['task_id' => $task->task_id, 'api_url' => $api_url, 'params' => $apiParams]);
  354. $startTime = microtime(true);
  355. // 调用GPT-Image2 API
  356. $response = $gptClient->post($api_url, [
  357. 'headers' => [
  358. 'Authorization' => 'Bearer ' . $apiKey,
  359. 'Content-Type' => 'application/json',
  360. ],
  361. 'json' => $apiParams,
  362. ]);
  363. $statusCode = $response->getStatusCode();
  364. $responseBody = $response->getBody()->getContents();
  365. $elapsed = round(microtime(true) - $startTime, 2);
  366. dLog('generate')->info('Guzzle请求完成', ['elapsed' => $elapsed . 's', 'http_code' => $statusCode]);
  367. if (empty($responseBody)) {
  368. throw new \Exception('API返回空响应,HTTP状态码: ' . $statusCode);
  369. }
  370. }
  371. // 解析响应
  372. dLog('generate')->info('响应数据长度', ['length' => strlen($responseBody)]);
  373. $responseData = json_decode($responseBody, true);
  374. if (json_last_error() !== JSON_ERROR_NONE) {
  375. dLog('generate')->error('JSON解析失败', ['error' => json_last_error_msg(), 'body' => substr($responseBody, 0, 500)]);
  376. throw new \Exception('JSON解析失败: ' . json_last_error_msg());
  377. }
  378. // 移除 b64_json 字段用于日志记录,避免生成超大日志
  379. $logResponseData = $this->removeB64JsonFromResponse($responseData);
  380. dLog('generate')->info('GPT-Image2 API响应', $logResponseData);
  381. logDB('generate', 'info', 'GPT-Image2 API响应', ['task_id' => $task->task_id, 'response' => $logResponseData]);
  382. if (isset($responseData['error'])) {
  383. // API返回错误
  384. logDB('generate', 'error', 'GPT-Image2任务失败', ['task_id' => $task->task_id, 'error' => $responseData['error']['message'] ?? 'API Error']);
  385. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  386. 'error_message' => $responseData['error']['message'] ?? 'API Error',
  387. 'result_json' => $logResponseData
  388. ]);
  389. } else {
  390. // 任务提交成功,直接处理结果
  391. dLog('generate')->info('开始处理GPT-Image2响应结果');
  392. $this->processGptImage2ApiResponse($task, $responseData);
  393. }
  394. } catch (\Exception $e) {
  395. // 记录错误
  396. dLog('generate')->error('GPT-Image2 API请求失败: ' . $e->getMessage(), [
  397. 'task_id' => $task->task_id,
  398. 'trace' => $e->getTraceAsString()
  399. ]);
  400. logDB('generate', 'error', 'GPT-Image2任务异常', [
  401. 'task_id' => $task->task_id,
  402. 'error' => $e->getMessage(),
  403. 'file' => $e->getFile(),
  404. 'line' => $e->getLine()
  405. ]);
  406. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  407. 'error_message' => 'API请求失败: ' . $e->getMessage()
  408. ]);
  409. }
  410. }
  411. /**
  412. * 处理GPT-Image2 API响应结果
  413. *
  414. * @param MpGeneratePicTask $task
  415. * @param array $responseData
  416. * @return void
  417. */
  418. private function processGptImage2ApiResponse(MpGeneratePicTask $task, array $responseData): void
  419. {
  420. try {
  421. if (!isset($responseData['data']) || empty($responseData['data'])) {
  422. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  423. 'error_message' => '未返回图片数据',
  424. 'result_json' => $responseData
  425. ]);
  426. return;
  427. }
  428. $result_urls = [];
  429. foreach ($responseData['data'] as $index => $imageData) {
  430. // 优先处理 b64_json 格式(新接口返回格式)
  431. if (isset($imageData['b64_json']) && !empty($imageData['b64_json'])) {
  432. $base64Data = $imageData['b64_json'];
  433. $imageStream = base64_decode($base64Data);
  434. if ($imageStream === false) {
  435. dLog('generate')->error('Base64解码失败', ['task_id' => $task->task_id, 'index' => $index]);
  436. continue;
  437. }
  438. $pic_name = 'ai_generation_gpt_' . time() . '_' . uniqid() . '.png';
  439. // 压缩PNG图片流
  440. $compressedData = $this->compressImageStream($imageStream);
  441. $url = uploadStreamByTos('image', $compressedData, $pic_name);
  442. $result_urls[] = $url;
  443. // 记录优化后的提示词(如果有)
  444. if (isset($imageData['revised_prompt'])) {
  445. dLog('generate')->info('图片生成优化提示词', [
  446. 'task_id' => $task->task_id,
  447. 'index' => $index,
  448. 'revised_prompt' => $imageData['revised_prompt']
  449. ]);
  450. }
  451. } elseif (isset($imageData['url']) && !empty($imageData['url'])) {
  452. // 兼容旧的 url 格式(如果接口仍返回)
  453. $url = $imageData['url'];
  454. $pic_name = 'ai_generation_gpt_' . time() . '_' . uniqid();
  455. $pic_ext = getImgExtFromUrl($url);
  456. $pic_name = $pic_name . $pic_ext;
  457. if ($pic_ext === '.png') {
  458. $comporessed_data = compressRemoteImageUrlToSize($url);
  459. $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
  460. } else {
  461. $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
  462. }
  463. $result_urls[] = $url;
  464. }
  465. }
  466. if (empty($result_urls)) {
  467. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  468. 'error_message' => '所有图片生成失败',
  469. 'result_json' => $responseData
  470. ]);
  471. return;
  472. }
  473. // 移除 b64_json 字段以避免存储大量 Base64 数据
  474. $cleanedResponseData = $responseData;
  475. if (isset($cleanedResponseData['data'])) {
  476. foreach ($cleanedResponseData['data'] as &$imageData) {
  477. unset($imageData['b64_json']); // 移除 Base64 数据
  478. }
  479. unset($imageData); // 解除引用
  480. }
  481. // 更新任务状态为成功
  482. $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
  483. 'result_url' => $result_urls,
  484. 'result_json' => $cleanedResponseData // 保存清理后的数据
  485. ]);
  486. // 同步调整分镜图片状态和结果
  487. $segment_id = getProp($task, 'alias_segment_id');
  488. if ($segment_id) {
  489. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  490. 'img_url' => $result_urls[0],
  491. 'pic_task_status' => '已完成',
  492. ]);
  493. // 如果是首帧图ID则更新anime表
  494. if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
  495. $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
  496. DB::table('mp_animes')->where('id', $anime_id)->update(['first_frame_url' => $result_urls[0], 'updated_at' => date('Y-m-d H:i:s')]);
  497. Redis::srem('anime_first_frame_urls', $segment_id);
  498. }
  499. }
  500. } catch (\Exception $e) {
  501. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  502. 'error_message' => '处理响应失败: ' . $e->getMessage()
  503. ]);
  504. }
  505. }
  506. /**
  507. * 提交任务到火山图片生成API
  508. *
  509. * @param MpGeneratePicTask $task
  510. * @return void
  511. */
  512. public function submitTaskToVolcApi(MpGeneratePicTask $task): void
  513. {
  514. try {
  515. // 验证环境变量配置
  516. $apiKey = env('VOLC_AI_API_KEY');
  517. if (empty($apiKey)) {
  518. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  519. 'error_message' => '火山引擎API KEY未配置,请检查环境变量VOLC_AI_API_KEY'
  520. ]);
  521. return;
  522. }
  523. // 更新状态为处理中
  524. $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING);
  525. // 构建火山图片生成API请求参数
  526. $apiParams = [
  527. 'model' => isset(BaseConst::MODELS_MAP[$task->model]) ? BaseConst::MODELS_MAP[$task->model] : $task->model,
  528. 'prompt' => $task->prompt,
  529. 'watermark' => false,
  530. ];
  531. // 尺寸参数
  532. if ($task->width && $task->height) {
  533. $apiParams['size'] = $task->width . 'x' . $task->height;
  534. }
  535. // 参考图片
  536. if ($task->ref_img_url) {
  537. if (is_array($task->ref_img_url)) {
  538. // $apiParams['image'] = count($task->ref_img_url) === 1 ? $task->ref_img_url[0] : $task->ref_img_url;
  539. $apiParams['image'] = $task->ref_img_url;
  540. } else {
  541. $apiParams['image'] = $task->ref_img_url;
  542. }
  543. }
  544. // 生成多图或者单图
  545. if ((int)$task->image_num === 1) {
  546. $apiParams['sequential_image_generation'] = 'disabled';
  547. }else if ($task->image_num > 1) {
  548. $apiParams['sequential_image_generation'] = 'auto';
  549. $apiParams['sequential_image_generation_options']['max_images'] = $task->image_num;
  550. }
  551. dLog('generate')->info('火山图片生成API参数: ', $apiParams);
  552. logDB('generate', 'info', '火山图片生成任务提交', ['task_id' => $task->task_id, 'params' => $apiParams]);
  553. // 调用火山图片生成API
  554. $response = $this->httpClient->post('https://ark.cn-beijing.volces.com/api/v3/images/generations', [
  555. 'headers' => [
  556. 'Authorization' => 'Bearer ' . $apiKey,
  557. 'Content-Type' => 'application/json',
  558. ],
  559. 'json' => $apiParams,
  560. ]);
  561. $responseData = json_decode($response->getBody()->getContents(), true);
  562. dLog('generate')->info('火山图片生成API响应: ', $responseData);
  563. logDB('generate', 'info', '火山图片生成API响应', ['task_id' => $task->task_id, 'response' => $responseData]);
  564. if (isset($responseData['error'])) {
  565. // API返回错误
  566. logDB('generate', 'error', '火山图片生成任务失败', ['task_id' => $task->task_id, 'error' => $responseData['error']['message'] ?? 'API Error']);
  567. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  568. 'error_message' => $responseData['error']['message'] ?? 'API Error',
  569. 'result_json' => $responseData
  570. ]);
  571. } else {
  572. // 任务提交成功,直接处理结果
  573. $this->processVolcApiResponse($task, $responseData);
  574. }
  575. } catch (\Exception $e) {
  576. // 记录错误
  577. dLog('generate')->error('火山API请求失败: ' . $e->getMessage());
  578. logDB('generate', 'error', '火山图片生成任务异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
  579. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  580. 'error_message' => 'API请求失败: ' . $e->getMessage()
  581. ]);
  582. }
  583. }
  584. /**
  585. * 处理火山API响应结果
  586. *
  587. * @param MpGeneratePicTask $task
  588. * @param array $responseData
  589. * @return void
  590. */
  591. private function processVolcApiResponse(MpGeneratePicTask $task, array $responseData): void
  592. {
  593. try {
  594. if (!isset($responseData['data']) || empty($responseData['data'])) {
  595. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  596. 'error_message' => '未返回图片数据',
  597. 'result_json' => $responseData
  598. ]);
  599. return;
  600. }
  601. $result_urls = [];
  602. foreach ($responseData['data'] as $imageData) {
  603. if (isset($imageData['error'])) {
  604. // 单张图片生成失败
  605. dLog('generate')->warning('单张图片生成失败: ', $imageData['error']);
  606. continue;
  607. }
  608. if (isset($imageData['url'])) {
  609. $url = $imageData['url'];
  610. $pic_name = 'ai_generation_' . time() . '_' . uniqid();
  611. $pic_ext = getImgExtFromUrl($url);
  612. $pic_name = $pic_name . $pic_ext;
  613. if ($pic_ext === '.png') {
  614. $comporessed_data = compressRemoteImageUrlToSize($url);
  615. $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
  616. } else {
  617. // 将图片另存到tos
  618. $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
  619. }
  620. $result_urls[] = $url;
  621. }
  622. }
  623. if (empty($result_urls)) {
  624. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  625. 'error_message' => '所有图片生成失败',
  626. 'result_json' => $responseData
  627. ]);
  628. return;
  629. }
  630. // 更新任务状态为成功
  631. $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
  632. 'result_url' => $result_urls,
  633. 'result_json' => $responseData
  634. ]);
  635. // 同步调整分镜图片状态和结果
  636. $segment_id = getProp($task, 'alias_segment_id');
  637. if ($segment_id) {
  638. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  639. 'img_url' => $result_urls[0],
  640. 'pic_task_status' => '已完成',
  641. ]);
  642. // 如果是首帧图ID则更新anime表
  643. if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
  644. $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
  645. DB::table('mp_animes')->where('id', $anime_id)->update(['first_frame_url' => $result_urls[0], 'updated_at' => date('Y-m-d H:i:s')]);
  646. Redis::srem('anime_first_frame_urls', $segment_id);
  647. }
  648. }
  649. } catch (\Exception $e) {
  650. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  651. 'error_message' => '处理响应失败: ' . $e->getMessage()
  652. ]);
  653. }
  654. }
  655. public function getTaskList($data)
  656. {
  657. $task_id = getProp($data, 'task_id');
  658. $status = getProp($data, 'status');
  659. $query = MpGeneratePicTask::select('*');
  660. if ($task_id) {
  661. $query->where('id', $task_id);
  662. }
  663. if ($status) {
  664. $query->where('status', $status);
  665. }
  666. return $query->orderBy('created_at', 'desc')->paginate();
  667. }
  668. /**
  669. * 查询任务状态
  670. *
  671. * @param MpGeneratePicTask $task
  672. * @return array
  673. */
  674. public function queryTaskStatus(MpGeneratePicTask $task): array
  675. {
  676. // 根据模型类型调用不同的查询方法
  677. if ($task->model === self::MODEL_JIMENG_4) {
  678. return $this->queryJimengTaskStatus($task);
  679. } elseif (in_array($task->model, BaseConst::NANO_BANANA_MODELS)) {
  680. return $this->queryNanoBananaTaskStatus($task);
  681. } else {
  682. // 火山API是同步返回结果,不需要查询
  683. return [
  684. 'status' => $task->status === MpGeneratePicTask::STATUS_SUCCESS ? 'success' : 'failed',
  685. 'error_message' => $task->error_message,
  686. 'result_url' => $task->result_url,
  687. 'result_json' => $task->result_json ?? []
  688. ];
  689. }
  690. }
  691. /**
  692. * 查询即梦AI任务状态
  693. *
  694. * @param MpGeneratePicTask $task
  695. * @return array
  696. */
  697. private function queryJimengTaskStatus(MpGeneratePicTask $task): array
  698. {
  699. try {
  700. // 获取API任务ID
  701. $apiTaskId = $task->task_id ?? null;
  702. if (!$apiTaskId) {
  703. return [
  704. 'status' => 'failed',
  705. 'error_message' => 'API任务ID不存在',
  706. 'result_url' => null
  707. ];
  708. }
  709. //构建查询参数
  710. $apiParams = [
  711. 'req_key' => 'jimeng_t2i_v40',
  712. 'task_id' => $apiTaskId,
  713. 'req_json' => '{"return_url":true}' // 返回URL格式
  714. ];
  715. //调用即梦AI 4.0 API查询任务状态
  716. $response = $this->volcEngineService->request(
  717. 'POST',
  718. 'visual.volcengineapi.com',
  719. '/', // 使用根路径
  720. [], // Query参数
  721. json_encode($apiParams),
  722. env('VOLC_AI_AK'),
  723. env('VOLC_AI_SK'),
  724. 'cv',
  725. 'cn-north-1',
  726. 'CVSync2AsyncGetResult',
  727. '2022-08-31',
  728. 'application/json'
  729. );
  730. $responseData = json_decode($response['body'], true);
  731. dLog('generate')->info('即梦AI 4.0 API查询任务状态响应: ', $responseData);
  732. logDB('generate', 'info', '即梦AI任务状态查询', ['task_id' => $apiTaskId, 'response' => $responseData]);
  733. if ($responseData['code'] !== 10000) {
  734. // API返回错误
  735. logDB('generate', 'error', '即梦AI任务状态查询失败', ['task_id' => $apiTaskId, 'error' => $responseData['message'] ?? 'API Error']);
  736. return [
  737. 'status' => 'failed',
  738. 'error_message' => $responseData['message'] ?? 'API Error',
  739. 'result_url' => null,
  740. 'result_json' => $responseData ?? []
  741. ];
  742. }
  743. // 解析API响应
  744. $result = $responseData['data'] ?? [];
  745. $taskStatus = $result['status'] ?? 'failed';
  746. $returnData = [
  747. 'status' => $taskStatus,
  748. 'error_message' => null,
  749. 'result_url' => null,
  750. 'result_json' => $responseData ?? []
  751. ];
  752. // 如果任务成功,获取结果URL
  753. if ($taskStatus === 'done' && isset($result['image_urls']) && count($result['image_urls']) > 0) {
  754. $result_urls = [];
  755. foreach ($result['image_urls'] as $url) {
  756. $pic_name = 'ai_generation_' . time() . '_' . uniqid();
  757. $pic_ext = getImgExtFromUrl($url);
  758. $pic_name = $pic_name . $pic_ext;
  759. if ($pic_ext === '.png') {
  760. $comporessed_data = compressRemoteImageUrlToSize($url);
  761. $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
  762. }else {
  763. // 将图片另存到tos
  764. $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
  765. }
  766. $result_urls[] = $url;
  767. }
  768. $returnData['result_url'] = $result_urls;
  769. $returnData['status'] = 'success';
  770. } elseif (in_array($taskStatus, ['not_found', 'expired'])) {
  771. $returnData['status'] = 'failed';
  772. $returnData['error_message'] = '任务未找到或已过期';
  773. } elseif ($taskStatus === 'failed') {
  774. $returnData['status'] = 'failed';
  775. $returnData['error_message'] = '任务执行失败';
  776. }
  777. // in_queue 或 generating状态保持原status
  778. return $returnData;
  779. } catch (\Exception $e) {
  780. return [
  781. 'status' => 'failed',
  782. 'error_message' => $e->getMessage(),
  783. 'result_url' => null
  784. ];
  785. }
  786. }
  787. /**
  788. * 提交任务到NanoBanana API
  789. *
  790. * @param MpGeneratePicTask $task
  791. * @return void
  792. */
  793. private function submitTaskToNanoBananaApi(MpGeneratePicTask $task): void
  794. {
  795. try {
  796. // 验证环境变量配置
  797. $apiKey = env('NANO_BANANA_API_KEY');
  798. if (empty($apiKey)) {
  799. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  800. 'error_message' => 'NanoBanana API KEY未配置,请检查环境变量NANO_BANANA_API_KEY'
  801. ]);
  802. return;
  803. }
  804. // 根据模型选择API地址
  805. switch ($task->model) {
  806. case self::MODEL_NANO_BANANA_2:
  807. $apiUrl = 'https://api.wuyinkeji.com/api/async/image_nanoBanana2';
  808. break;
  809. case self::MODEL_NANO_BANANA_PRO:
  810. $apiUrl = 'https://api.wuyinkeji.com/api/async/image_nanoBanana_pro';
  811. break;
  812. case self::MODEL_GPT_IMAGE_2:
  813. $apiUrl = 'https://api.wuyinkeji.com/api/async/image_gpt';
  814. break;
  815. default:
  816. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  817. 'error_message' => '不支持的模型类型: ' . $task->model
  818. ]);
  819. logDB('generate', 'error', '模型类型错误', ['task_id' => $task->task_id, 'model' => $task->model]);
  820. return;
  821. }
  822. // 构建API请求参数
  823. $apiParams = [
  824. 'key' => $apiKey,
  825. 'prompt' => $task->prompt,
  826. ];
  827. if ($task->model == self::MODEL_GPT_IMAGE_2) {
  828. // 该模型下,size需设置为9:16类似的数值,请根据如下比例反推
  829. $apiParams['size'] = $this->getRatioFromSize($task->width, $task->height);
  830. }else {
  831. // 尺寸参数(根据宽高判断)
  832. $area = $task->width * $task->height;
  833. if ($area >= 1024*1024 && $area < 2048*2048) {
  834. $apiParams['size'] = '1k';
  835. } elseif ($area >= 2048*2048) {
  836. $apiParams['size'] = '2k';
  837. } else {
  838. $apiParams['size'] = '1k'; // 默认1k
  839. }
  840. // 画面比例
  841. if ($task->width && $task->height) {
  842. $ratio = $task->width . ':' . $task->height;
  843. // 简化比例
  844. $gcd = $this->gcd($task->width, $task->height);
  845. $ratio = ($task->width / $gcd) . ':' . ($task->height / $gcd);
  846. $apiParams['aspectRatio'] = $ratio;
  847. }
  848. }
  849. // 参考图片
  850. if ($task->ref_img_url) {
  851. $apiParams['urls'] = is_array($task->ref_img_url) ? $task->ref_img_url : [$task->ref_img_url];
  852. }
  853. dLog('generate')->info('NanoBanana API参数: ', $apiParams);
  854. logDB('generate', 'info', 'NanoBanana任务提交', ['task_id' => $task->task_id, 'model' => $task->model, 'params' => $apiParams]);
  855. // 调用NanoBanana API
  856. $response = $this->httpClient->post($apiUrl, [
  857. 'query' => ['key' => $apiKey],
  858. 'json' => $apiParams,
  859. ]);
  860. $responseData = json_decode($response->getBody()->getContents(), true);
  861. dLog('generate')->info('NanoBanana API响应: ', $responseData);
  862. logDB('generate', 'info', 'NanoBanana API响应', ['task_id' => $task->task_id, 'response' => $responseData]);
  863. if ($responseData['code'] !== 200) {
  864. // API返回错误
  865. logDB('generate', 'error', 'NanoBanana任务提交失败', ['task_id' => $task->task_id, 'error' => $responseData['msg'] ?? 'API Error']);
  866. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  867. 'error_message' => $responseData['msg'] ?? 'API Error',
  868. 'extra_params' => $responseData
  869. ]);
  870. } else {
  871. // 任务提交成功,更新状态为处理中
  872. $updateData = [];
  873. // 存储API返回的任务ID
  874. if (isset($responseData['data']['id'])) {
  875. $updateData['task_id'] = $responseData['data']['id'];
  876. $updateData['extra_params'] = $responseData;
  877. }
  878. $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING, $updateData);
  879. }
  880. } catch (\Exception $e) {
  881. // 记录错误
  882. logDB('generate', 'error', 'NanoBanana任务提交异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
  883. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  884. 'error_message' => 'API请求失败: ' . $e->getMessage()
  885. ]);
  886. }
  887. }
  888. /**
  889. * 查询NanoBanana任务状态
  890. *
  891. * @param MpGeneratePicTask $task
  892. * @return array
  893. */
  894. private function queryNanoBananaTaskStatus(MpGeneratePicTask $task): array
  895. {
  896. try {
  897. // 获取API任务ID
  898. $apiTaskId = $task->task_id ?? null;
  899. $apiKey = env('NANO_BANANA_API_KEY');
  900. if (!$apiTaskId) {
  901. return [
  902. 'status' => 'failed',
  903. 'error_message' => 'API任务ID不存在',
  904. 'result_url' => null
  905. ];
  906. }
  907. if (empty($apiKey)) {
  908. return [
  909. 'status' => 'failed',
  910. 'error_message' => 'NanoBanana API KEY未配置',
  911. 'result_url' => null
  912. ];
  913. }
  914. // 调用统一查询接口
  915. $response = $this->httpClient->get('https://api.wuyinkeji.com/api/async/detail', [
  916. 'query' => [
  917. 'key' => $apiKey,
  918. 'id' => $apiTaskId
  919. ]
  920. ]);
  921. $responseData = json_decode($response->getBody()->getContents(), true);
  922. dLog('generate')->info('NanoBanana任务状态查询响应: ', $responseData);
  923. logDB('generate', 'info', 'NanoBanana任务状态查询', ['task_id' => $apiTaskId, 'response' => $responseData]);
  924. if ($responseData['code'] !== 200) {
  925. // API返回错误
  926. logDB('generate', 'error', 'NanoBanana任务状态查询失败', ['task_id' => $apiTaskId, 'error' => $responseData['msg'] ?? 'API Error']);
  927. return [
  928. 'status' => 'failed',
  929. 'error_message' => $responseData['msg'] ?? 'API Error',
  930. 'result_url' => null,
  931. 'result_json' => $responseData
  932. ];
  933. }
  934. // 解析API响应
  935. $data = $responseData['data'] ?? [];
  936. $taskStatus = $data['status'] ?? 0;
  937. $returnData = [
  938. 'status' => 'processing',
  939. 'error_message' => null,
  940. 'result_url' => null,
  941. 'result_json' => $responseData
  942. ];
  943. // status: 2表示成功
  944. if ($taskStatus === 2 && isset($data['result']) && !empty($data['result'])) {
  945. $result_urls = [];
  946. foreach ($data['result'] as $url) {
  947. $pic_name = 'ai_generation_nanobanana_' . time() . '_' . uniqid();
  948. $pic_ext = getImgExtFromUrl($url);
  949. $pic_name = $pic_name . $pic_ext;
  950. if ($pic_ext === '.png') {
  951. $comporessed_data = compressRemoteImageUrlToSize($url);
  952. $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
  953. } else {
  954. // 将图片另存到tos
  955. $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
  956. }
  957. $result_urls[] = $url;
  958. }
  959. $returnData['result_url'] = $result_urls;
  960. $returnData['status'] = 'success';
  961. } elseif ($taskStatus === 3) {
  962. // status: 3表示失败
  963. $returnData['status'] = 'failed';
  964. $returnData['error_message'] = $data['message'] ?? '任务执行失败';
  965. }
  966. // status: 0或1表示处理中,保持processing状态
  967. return $returnData;
  968. } catch (\Exception $e) {
  969. return [
  970. 'status' => 'failed',
  971. 'error_message' => $e->getMessage(),
  972. 'result_url' => null
  973. ];
  974. }
  975. }
  976. /**
  977. * 计算最大公约数(用于简化比例)
  978. *
  979. * @param int $a
  980. * @param int $b
  981. * @return int
  982. */
  983. private function gcd(int $a, int $b): int
  984. {
  985. while ($b != 0) {
  986. $temp = $b;
  987. $b = $a % $b;
  988. $a = $temp;
  989. }
  990. return $a;
  991. }
  992. /**
  993. * 创建素材
  994. *
  995. * @param array $params
  996. * @return array
  997. */
  998. public function createAsset(array $params): array
  999. {
  1000. try {
  1001. // 验证必填参数
  1002. if (empty($params['url'])) {
  1003. return [
  1004. 'code' => 1,
  1005. 'msg' => '素材URL不能为空',
  1006. 'data' => null
  1007. ];
  1008. }
  1009. // 先获取表中是否已有该url
  1010. $asset = DB::table('mp_assets')->where('url', $params['url'])->first();
  1011. if ($asset) {
  1012. return [
  1013. 'code' => 0,
  1014. 'msg' => '创建成功',
  1015. 'data' => [
  1016. 'id' => $asset->id,
  1017. 'asset_id' => $asset->asset_id,
  1018. 'group_id' => $asset->group_id,
  1019. 'group_name' => $asset->group_name,
  1020. ]
  1021. ];
  1022. }
  1023. // 获取API配置
  1024. $apiKey = env('ZHIZHEN_AI_SK');
  1025. $apiUrl = 'https://model-relay.zzengine.net';
  1026. if (empty($apiKey)) {
  1027. return [
  1028. 'code' => 1002,
  1029. 'msg' => '智真AI API KEY未配置,请检查环境变量ZHIZHEN_AI_SK',
  1030. 'data' => null
  1031. ];
  1032. }
  1033. // 构建请求参数
  1034. $requestData = [
  1035. 'url' => $params['url'],
  1036. 'asset_type' => $params['asset_type'] ?? MpAsset::TYPE_IMAGE,
  1037. ];
  1038. // 可选参数
  1039. if (!empty($params['name'])) {
  1040. $requestData['name'] = $params['name'];
  1041. }
  1042. if (!empty($params['group_id'])) {
  1043. $requestData['group_id'] = $params['group_id'];
  1044. }
  1045. dLog('generate')->info('智真AI创建素材请求参数: ', $requestData);
  1046. // 调用智真AI API
  1047. $response = $this->httpClient->post($apiUrl . '/api/v1/asset/create', [
  1048. 'headers' => [
  1049. 'X-Api-Key' => $apiKey,
  1050. 'Content-Type' => 'application/json',
  1051. ],
  1052. 'json' => $requestData,
  1053. ]);
  1054. $responseData = json_decode($response->getBody()->getContents(), true);
  1055. dLog('generate')->info('智真AI创建素材响应: ', $responseData);
  1056. logDB('generate', 'info', '智真AI创建素材', ['params' => $requestData, 'response' => $responseData]);
  1057. if ($responseData['code'] !== 0) {
  1058. return [
  1059. 'code' => $responseData['code'],
  1060. 'msg' => $responseData['msg'] ?? '创建素材失败',
  1061. 'data' => null
  1062. ];
  1063. }
  1064. // 保存素材记录到数据库
  1065. $assetData = $responseData['data'] ?? [];
  1066. $asset = MpAsset::create([
  1067. 'asset_id' => $assetData['asset_id'] ?? '',
  1068. 'group_id' => $assetData['group_id'] ?? null,
  1069. 'group_name' => $assetData['group_name'] ?? null,
  1070. 'name' => $params['name'] ?? null,
  1071. 'url' => $params['url'],
  1072. 'asset_type' => $params['asset_type'] ?? MpAsset::TYPE_IMAGE,
  1073. 'status' => MpAsset::STATUS_PROCESSING,
  1074. 'extra_params' => $responseData,
  1075. ]);
  1076. return [
  1077. 'code' => 0,
  1078. 'msg' => '创建成功',
  1079. 'data' => [
  1080. 'id' => $asset->id,
  1081. 'asset_id' => $asset->asset_id,
  1082. 'group_id' => $asset->group_id,
  1083. 'group_name' => $asset->group_name,
  1084. ]
  1085. ];
  1086. } catch (\Exception $e) {
  1087. dLog('generate')->error('创建素材异常: ' . $e->getMessage());
  1088. logDB('generate', 'error', '创建素材异常', ['params' => $params, 'error' => $e->getMessage()]);
  1089. return [
  1090. 'code' => 20003,
  1091. 'msg' => '创建素材失败: ' . $e->getMessage(),
  1092. 'data' => null
  1093. ];
  1094. }
  1095. }
  1096. /**
  1097. * 查询素材
  1098. *
  1099. * @param string $assetId
  1100. * @return array
  1101. */
  1102. public function getAsset(string $assetId): array
  1103. {
  1104. try {
  1105. // 验证参数
  1106. if (empty($assetId)) {
  1107. return [
  1108. 'code' => 20003,
  1109. 'msg' => '素材ID不能为空',
  1110. 'data' => null
  1111. ];
  1112. }
  1113. // 先获取表中是否已有该url
  1114. $assetInfo = DB::table('mp_assets')->where('asset_id', $assetId)->first();
  1115. if ($assetInfo) {
  1116. $assetInfo = (array)$assetInfo;
  1117. $status = getProp($assetInfo, 'status');
  1118. if (in_array($status, ['Active', 'Failed'])) {
  1119. $assetInfo['id'] = $assetInfo['asset_id'];
  1120. return [
  1121. 'code' => 0,
  1122. 'msg' => '查询成功',
  1123. 'data' => [
  1124. 'asset' => $assetInfo
  1125. ]
  1126. ];
  1127. }
  1128. }
  1129. // 获取API配置
  1130. $apiKey = env('ZHIZHEN_AI_SK');
  1131. $apiUrl = 'https://model-relay.zzengine.net';
  1132. if (empty($apiKey)) {
  1133. return [
  1134. 'code' => 1002,
  1135. 'msg' => '智真AI API KEY未配置,请检查环境变量ZHIZHEN_AI_SK',
  1136. 'data' => null
  1137. ];
  1138. }
  1139. dLog('generate')->info('智真AI查询素材: ' . $assetId);
  1140. // 调用智真AI API
  1141. $response = $this->httpClient->post($apiUrl . '/api/v1/asset/get', [
  1142. 'headers' => [
  1143. 'X-Api-Key' => $apiKey,
  1144. 'Content-Type' => 'application/json',
  1145. ],
  1146. 'json' => [
  1147. 'asset_id' => $assetId,
  1148. ],
  1149. ]);
  1150. $responseData = json_decode($response->getBody()->getContents(), true);
  1151. dLog('generate')->info('智真AI查询素材响应: ', $responseData);
  1152. logDB('generate', 'info', '智真AI查询素材', ['asset_id' => $assetId, 'response' => $responseData]);
  1153. if ($responseData['code'] !== 0) {
  1154. return [
  1155. 'code' => $responseData['code'],
  1156. 'msg' => $responseData['msg'] ?? '查询素材失败',
  1157. 'data' => null
  1158. ];
  1159. }
  1160. $assetInfo = $responseData['data']['asset'] ?? [];
  1161. // 更新本地数据库记录
  1162. $localAsset = MpAsset::where('asset_id', $assetId)->first();
  1163. if ($localAsset) {
  1164. $localAsset->update([
  1165. 'status' => $assetInfo['status'] ?? MpAsset::STATUS_PROCESSING,
  1166. 'cover_url' => $assetInfo['url'] ?? null,
  1167. 'extra_params' => $responseData,
  1168. ]);
  1169. }
  1170. return [
  1171. 'code' => 0,
  1172. 'msg' => '查询成功',
  1173. 'data' => [
  1174. 'asset' => $assetInfo
  1175. ]
  1176. ];
  1177. } catch (\Exception $e) {
  1178. dLog('generate')->error('查询素材异常: ' . $e->getMessage());
  1179. logDB('generate', 'error', '查询素材异常', ['asset_id' => $assetId, 'error' => $e->getMessage()]);
  1180. return [
  1181. 'code' => 20003,
  1182. 'msg' => '查询素材失败: ' . $e->getMessage(),
  1183. 'data' => null
  1184. ];
  1185. }
  1186. }
  1187. /**
  1188. * 更新所有待处理任务的状态
  1189. *
  1190. * @return void
  1191. */
  1192. public function updatePendingTasks(): void
  1193. {
  1194. dLog('generate')->info('更新图片状态ing');
  1195. // 1. 处理火山API的pending任务(批量提交到队列)
  1196. $volcPendingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
  1197. ->whereIn('model', BaseConst::VOLC_PIC_MODELS)
  1198. ->orderBy('created_at', 'asc')
  1199. ->limit(50) // 每次最多处理50个任务,避免超时
  1200. ->get();
  1201. foreach ($volcPendingTasks as $task) {
  1202. dLog('generate')->info('开始分发火山API任务到队列: ' . $task->task_id);
  1203. // 分发到队列
  1204. \App\Jobs\ProcessVolcImageGenerationJob::dispatch($task->id)->onConnection('redis');
  1205. }
  1206. // 2. 处理GPT-Image2的pending任务(批量提交到队列)
  1207. $gptImage2PendingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
  1208. ->whereIn('model', BaseConst::GPT_IMAGE2_MODELS)
  1209. ->orderBy('created_at', 'asc')
  1210. ->limit(50) // 每次最多处理50个任务,避免超时
  1211. ->get();
  1212. foreach ($gptImage2PendingTasks as $task) {
  1213. dLog('generate')->info('开始分发GPT-Image2任务到队列: ' . $task->task_id);
  1214. // 分发到队列
  1215. \App\Jobs\ProcessGptImage2GenerationJob::dispatch($task->id)->onConnection('redis');
  1216. }
  1217. // 3. 获取所有处理中的任务(即梦AI和NanoBanana系列需要查询状态)
  1218. $processingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)
  1219. ->whereIn('model', array_merge([self::MODEL_JIMENG_4], BaseConst::NANO_BANANA_MODELS))
  1220. ->get();
  1221. foreach ($processingTasks as $task) {
  1222. $statusInfo = $this->queryTaskStatus($task);
  1223. if ($statusInfo['status'] === 'success') {
  1224. logDB('generate', 'info', '即梦AI图片生成任务成功', ['task_id' => $task->task_id, 'result_url' => $statusInfo['result_url']]);
  1225. $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
  1226. 'result_url' => $statusInfo['result_url'],
  1227. 'result_json' => $statusInfo['result_json'] ?? []
  1228. ]);
  1229. // 同步调整分镜图片状态和结果
  1230. $segment_id = getProp($task, 'alias_segment_id');
  1231. if ($segment_id) {
  1232. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  1233. 'img_url' => $statusInfo['result_url'][0],
  1234. 'pic_task_status' => '已完成',
  1235. ]);
  1236. // 如果是首帧图ID则更新anime表
  1237. if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
  1238. $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
  1239. 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')]);
  1240. Redis::srem('anime_first_frame_urls', $segment_id);
  1241. }
  1242. }
  1243. } elseif ($statusInfo['status'] === 'failed') {
  1244. logDB('generate', 'error', '即梦AI图片生成任务失败', ['task_id' => $task->task_id, 'error' => $statusInfo['error_message']]);
  1245. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  1246. 'error_message' => $statusInfo['error_message'],
  1247. 'result_json' => $statusInfo['result_json'] ?? []
  1248. ]);
  1249. if (getProp($task, 'alias_segment_id')) {
  1250. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  1251. 'pic_task_status' => '失败',
  1252. ]);
  1253. }
  1254. }
  1255. // 如果仍然是处理中状态,不做任何操作
  1256. //处理:如果任务处理超过12小时,标记为失败
  1257. $processingTime = now()->diffInHours($task->created_at);
  1258. if ($processingTime > 12) {
  1259. logDB('generate', 'warning', '即梦AI图片生成任务超时', ['task_id' => $task->task_id, 'processing_hours' => $processingTime]);
  1260. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  1261. 'error_message' => '任务处理超时(超过12小时)'
  1262. ]);
  1263. }
  1264. }
  1265. // 4. 检查是否有任务完成,如果有则处理下一个排队任务(仅即梦AI)
  1266. $this->processNextQueuedTask();
  1267. }
  1268. /**
  1269. * 处理下一个排队的任务
  1270. *
  1271. * @return void
  1272. */
  1273. public function processNextQueuedTask(): void
  1274. {
  1275. // 检查是否还有正在处理的任务(仅即梦AI)
  1276. if ($this->hasProcessingTask()) {
  1277. return; // 如果还有处理中的任务,不处理新任务
  1278. }
  1279. // 获取最早的待处理任务(仅即梦AI)
  1280. $nextTask = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
  1281. ->where('model', self::MODEL_JIMENG_4)
  1282. ->orderBy('created_at', 'asc')
  1283. ->first();
  1284. if ($nextTask) {
  1285. dLog('generate')->info('开始处理排队任务: ' . $nextTask->task_id);
  1286. logDB('generate', 'info', '开始处理即梦AI排队任务', ['task_id' => $nextTask->task_id]);
  1287. $this->submitTaskToJimengApi($nextTask);
  1288. }
  1289. }
  1290. /**
  1291. * 获取任务队列状态
  1292. *
  1293. * @return array
  1294. */
  1295. public function getQueueStatus(): array
  1296. {
  1297. $processingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)->count();
  1298. $pendingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)->count();
  1299. return [
  1300. 'processing_count' => $processingCount,
  1301. 'pending_count' => $pendingCount,
  1302. 'can_submit_new_task' => $processingCount === 0
  1303. ];
  1304. }
  1305. /**
  1306. * 处理智真AI的参考图片转素材
  1307. *
  1308. * @param array $referenceImages 参考图片URL数组
  1309. * @param string &$fullPrompt 完整提示词(引用传递,用于删除失败图片的标记)
  1310. * @return array 返回素材ID数组
  1311. */
  1312. public function processReferenceImagesToAssets(array $referenceImages, string &$fullPrompt): array
  1313. {
  1314. $assetIds = [];
  1315. $failedIndexes = []; // 记录失败的图片序号
  1316. foreach ($referenceImages as $index => $imageUrl) {
  1317. $imageIndex = $index + 1; // 图片序号从1开始
  1318. try {
  1319. dLog('generate')->info("开始处理参考图片 {$imageIndex}: {$imageUrl}");
  1320. // 1. 创建素材
  1321. $createResult = $this->createAsset([
  1322. 'url' => $imageUrl,
  1323. 'asset_type' => MpAsset::TYPE_IMAGE,
  1324. 'name' => "参考图片_{$imageIndex}_" . time(),
  1325. ]);
  1326. if ($createResult['code'] !== 0) {
  1327. dLog('generate')->warning("图片 {$imageIndex} 创建素材失败: " . $createResult['msg']);
  1328. logDB('generate', 'warning', '创建素材失败', [
  1329. 'image_url' => $imageUrl,
  1330. 'index' => $imageIndex,
  1331. 'error' => $createResult['msg']
  1332. ]);
  1333. $failedIndexes[] = $imageIndex;
  1334. continue;
  1335. }
  1336. $assetId = $createResult['data']['asset_id'];
  1337. dLog('generate')->info("图片 {$imageIndex} 素材创建成功,asset_id: {$assetId},开始轮询查询状态");
  1338. // 2. 轮询查询素材状态(每3秒查询一次,最多查询100次即5分钟)
  1339. $maxAttempts = 100;
  1340. $attempt = 0;
  1341. $assetStatus = null;
  1342. while ($attempt < $maxAttempts) {
  1343. sleep(3); // 等待3秒
  1344. $attempt++;
  1345. $getResult = $this->getAsset($assetId);
  1346. if ($getResult['code'] !== 0) {
  1347. dLog('generate')->warning("图片 {$imageIndex} 查询素材状态失败: " . $getResult['msg']);
  1348. continue;
  1349. }
  1350. $assetStatus = $getResult['data']['asset']['status'] ?? null;
  1351. dLog('generate')->info("图片 {$imageIndex} 素材状态查询第 {$attempt} 次,状态: {$assetStatus}");
  1352. if ($assetStatus === 'Active') {
  1353. // 素材可用
  1354. $assetIds[] = $assetId;
  1355. dLog('generate')->info("图片 {$imageIndex} 素材处理成功,asset_id: {$assetId}");
  1356. logDB('generate', 'info', '素材转换成功', [
  1357. 'image_url' => $imageUrl,
  1358. 'index' => $imageIndex,
  1359. 'asset_id' => $assetId
  1360. ]);
  1361. break;
  1362. } elseif ($assetStatus === 'Failed') {
  1363. // 素材处理失败
  1364. dLog('generate')->warning("图片 {$imageIndex} 素材处理失败");
  1365. logDB('generate', 'warning', '素材处理失败', [
  1366. 'image_url' => $imageUrl,
  1367. 'index' => $imageIndex,
  1368. 'asset_id' => $assetId
  1369. ]);
  1370. $failedIndexes[] = $imageIndex;
  1371. break;
  1372. }
  1373. // 其他状态(Processing等)继续等待
  1374. }
  1375. // 如果超时还未成功
  1376. if ($attempt >= $maxAttempts && $assetStatus !== 'Active') {
  1377. dLog('generate')->warning("图片 {$imageIndex} 素材处理超时");
  1378. logDB('generate', 'warning', '素材处理超时', [
  1379. 'image_url' => $imageUrl,
  1380. 'index' => $imageIndex,
  1381. 'asset_id' => $assetId,
  1382. 'last_status' => $assetStatus
  1383. ]);
  1384. $failedIndexes[] = $imageIndex;
  1385. }
  1386. } catch (\Exception $e) {
  1387. dLog('generate')->error("图片 {$imageIndex} 处理异常: " . $e->getMessage());
  1388. logDB('generate', 'error', '素材转换异常', [
  1389. 'image_url' => $imageUrl,
  1390. 'index' => $imageIndex,
  1391. 'error' => $e->getMessage()
  1392. ]);
  1393. $failedIndexes[] = $imageIndex;
  1394. }
  1395. }
  1396. // 处理失败的图片:从 fullPrompt 中删除对应的标记并调整序号
  1397. if (!empty($failedIndexes)) {
  1398. dLog('generate')->info('开始处理失败图片的提示词调整,失败序号: ' . implode(',', $failedIndexes));
  1399. // 按序号从大到小排序,避免删除时影响后续序号
  1400. rsort($failedIndexes);
  1401. foreach ($failedIndexes as $failedIndex) {
  1402. // 删除失败图片的标记,例如 <图片1>、<图片2> 等
  1403. $pattern = "/<图片{$failedIndex}>/u";
  1404. $fullPrompt = preg_replace($pattern, '', $fullPrompt);
  1405. dLog('generate')->info("已从提示词中删除 <图片{$failedIndex}>");
  1406. }
  1407. // 重新调整剩余图片的序号
  1408. // 例如:如果图片2失败,图片3、图片4需要改为图片2、图片3
  1409. $needAdjust = false;
  1410. foreach ($failedIndexes as $failedIndex) {
  1411. $needAdjust = true;
  1412. // 将所有大于失败序号的图片标记序号减1
  1413. for ($i = $failedIndex + 1; $i <= count($referenceImages); $i++) {
  1414. $oldPattern = "/<图片{$i}>/u";
  1415. $newTag = "<图片" . ($i - 1) . ">";
  1416. $fullPrompt = preg_replace($oldPattern, $newTag, $fullPrompt);
  1417. }
  1418. }
  1419. if ($needAdjust) {
  1420. dLog('generate')->info('提示词图片序号调整完成');
  1421. logDB('generate', 'info', '提示词调整', [
  1422. 'failed_indexes' => $failedIndexes,
  1423. 'adjusted_prompt' => $fullPrompt
  1424. ]);
  1425. }
  1426. }
  1427. dLog('generate')->info('参考图片转素材完成,成功数量: ' . count($assetIds) . ',失败数量: ' . count($failedIndexes));
  1428. // 格式化为可直接在API接口中使用的数组
  1429. foreach($assetIds as &$assetId) {
  1430. $assetId = "asset://{$assetId}";
  1431. }
  1432. return $assetIds;
  1433. }
  1434. /**
  1435. * 根据宽高反推图片比例
  1436. * @param int $width 宽度
  1437. * @param int $height 高度
  1438. * @return string 比例字符串,如 "9:16",匹配不到则返回 "auto"
  1439. */
  1440. private function getRatioFromSize($width, $height)
  1441. {
  1442. if (!$width || !$height) {
  1443. return 'auto';
  1444. }
  1445. // 遍历所有预定义的比例,查找匹配的
  1446. foreach (BaseConst::IMAGE_RATIOS as $ratio => $size) {
  1447. if ($size['width'] == $width && $size['height'] == $height) {
  1448. return $ratio;
  1449. }
  1450. }
  1451. // 没有精确匹配,尝试通过计算比例匹配
  1452. $gcd = $this->gcd($width, $height);
  1453. $simplifiedRatio = ($width / $gcd) . ':' . ($height / $gcd);
  1454. // 检查简化后的比例是否在预定义列表中
  1455. if (isset(BaseConst::IMAGE_RATIOS[$simplifiedRatio])) {
  1456. return $simplifiedRatio;
  1457. }
  1458. return 'auto';
  1459. }
  1460. /**
  1461. * 压缩图片流(针对PNG格式)
  1462. *
  1463. * @param string $imageStream 图片二进制数据
  1464. * @param int $maxBytes 最大字节数(默认3MB)
  1465. * @return string|null 压缩后的图片二进制数据,失败时返回原数据
  1466. */
  1467. private function compressImageStream(string $imageStream, int $maxBytes = 3 * 1024 * 1024): ?string
  1468. {
  1469. try {
  1470. // 检查图片类型
  1471. $imgInfo = @getimagesizefromstring($imageStream);
  1472. if (!$imgInfo) {
  1473. dLog('generate')->warning('无法识别图片类型,返回原始数据');
  1474. return $imageStream;
  1475. }
  1476. $mime = $imgInfo['mime'] ?? '';
  1477. // 只处理PNG,JPEG不做有损压缩
  1478. if ($mime === 'image/jpeg') {
  1479. return $imageStream;
  1480. }
  1481. // 如果已经小于最大限制,直接返回
  1482. if (strlen($imageStream) <= $maxBytes) {
  1483. return $imageStream;
  1484. }
  1485. // 载入图像对象
  1486. $srcImg = @imagecreatefromstring($imageStream);
  1487. if (!$srcImg) {
  1488. dLog('generate')->warning('无法创建图像资源,返回原始数据');
  1489. return $imageStream;
  1490. }
  1491. $origW = imagesx($srcImg);
  1492. $origH = imagesy($srcImg);
  1493. // 逐步降低质量直到满足大小要求
  1494. $quality = 9; // PNG压缩等级 0-9
  1495. $scaleFactor = 1.0;
  1496. $maxAttempts = 10;
  1497. $attempt = 0;
  1498. $compressedData = null;
  1499. while ($attempt < $maxAttempts) {
  1500. $attempt++;
  1501. // 如果需要缩放
  1502. if ($scaleFactor < 1.0) {
  1503. $newW = (int)($origW * $scaleFactor);
  1504. $newH = (int)($origH * $scaleFactor);
  1505. $resizedImg = imagecreatetruecolor($newW, $newH);
  1506. // 保持透明度
  1507. imagealphablending($resizedImg, false);
  1508. imagesavealpha($resizedImg, true);
  1509. imagecopyresampled($resizedImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $origW, $origH);
  1510. $targetImg = $resizedImg;
  1511. } else {
  1512. $targetImg = $srcImg;
  1513. }
  1514. // 输出到内存
  1515. ob_start();
  1516. imagepng($targetImg, null, $quality);
  1517. $compressedData = ob_get_clean();
  1518. if ($scaleFactor < 1.0) {
  1519. imagedestroy($targetImg);
  1520. }
  1521. // 检查大小
  1522. $size = strlen($compressedData);
  1523. dLog('generate')->info('图片压缩尝试', [
  1524. 'attempt' => $attempt,
  1525. 'quality' => $quality,
  1526. 'scale' => $scaleFactor,
  1527. 'size' => $size,
  1528. 'target' => $maxBytes
  1529. ]);
  1530. if ($size <= $maxBytes) {
  1531. break;
  1532. }
  1533. // 调整参数
  1534. if ($quality > 0) {
  1535. $quality--;
  1536. } else {
  1537. $scaleFactor *= 0.9; // 每次缩小10%
  1538. }
  1539. }
  1540. imagedestroy($srcImg);
  1541. return $compressedData ?: $imageStream;
  1542. } catch (\Exception $e) {
  1543. dLog('generate')->error('图片压缩失败', ['error' => $e->getMessage()]);
  1544. return $imageStream;
  1545. }
  1546. }
  1547. /**
  1548. * 从响应数据中移除 b64_json 字段
  1549. * 避免在日志和数据库中存储大量 Base64 数据
  1550. *
  1551. * @param array $responseData
  1552. * @return array
  1553. */
  1554. private function removeB64JsonFromResponse(array $responseData): array
  1555. {
  1556. $cleanedData = $responseData;
  1557. if (isset($cleanedData['data']) && is_array($cleanedData['data'])) {
  1558. foreach ($cleanedData['data'] as &$imageData) {
  1559. if (isset($imageData['b64_json'])) {
  1560. // 移除 b64_json 字段,可选择性保留数据长度信息
  1561. $b64Length = strlen($imageData['b64_json']);
  1562. unset($imageData['b64_json']);
  1563. $imageData['b64_json_removed'] = true;
  1564. $imageData['b64_json_length'] = $b64Length;
  1565. }
  1566. }
  1567. unset($imageData); // 解除引用
  1568. }
  1569. return $cleanedData;
  1570. }
  1571. }