AIImageGenerationService.php 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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(仅限智真AI来源的素材)
  1010. $asset = DB::table('mp_assets')->where('url', $params['url'])->where('source_type', 'zhizhen')->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. 'source_type' => 'zhizhen',
  1074. 'status' => MpAsset::STATUS_PROCESSING,
  1075. 'extra_params' => $responseData,
  1076. ]);
  1077. return [
  1078. 'code' => 0,
  1079. 'msg' => '创建成功',
  1080. 'data' => [
  1081. 'id' => $asset->id,
  1082. 'asset_id' => $asset->asset_id,
  1083. 'group_id' => $asset->group_id,
  1084. 'group_name' => $asset->group_name,
  1085. ]
  1086. ];
  1087. } catch (\Exception $e) {
  1088. dLog('generate')->error('创建素材异常: ' . $e->getMessage());
  1089. logDB('generate', 'error', '创建素材异常', ['params' => $params, 'error' => $e->getMessage()]);
  1090. return [
  1091. 'code' => 20003,
  1092. 'msg' => '创建素材失败: ' . $e->getMessage(),
  1093. 'data' => null
  1094. ];
  1095. }
  1096. }
  1097. /**
  1098. * 查询素材
  1099. *
  1100. * @param string $assetId
  1101. * @return array
  1102. */
  1103. public function getAsset(string $assetId): array
  1104. {
  1105. try {
  1106. // 验证参数
  1107. if (empty($assetId)) {
  1108. return [
  1109. 'code' => 20003,
  1110. 'msg' => '素材ID不能为空',
  1111. 'data' => null
  1112. ];
  1113. }
  1114. // 先获取表中是否已有该素材(仅限智真AI来源的素材)
  1115. $assetInfo = DB::table('mp_assets')->where('asset_id', $assetId)->where('source_type', 'zhizhen')->first();
  1116. if ($assetInfo) {
  1117. $assetInfo = (array)$assetInfo;
  1118. $status = getProp($assetInfo, 'status');
  1119. if (in_array($status, ['Active', 'Failed'])) {
  1120. $assetInfo['id'] = $assetInfo['asset_id'];
  1121. return [
  1122. 'code' => 0,
  1123. 'msg' => '查询成功',
  1124. 'data' => [
  1125. 'asset' => $assetInfo
  1126. ]
  1127. ];
  1128. }
  1129. }
  1130. // 获取API配置
  1131. $apiKey = env('ZHIZHEN_AI_SK');
  1132. $apiUrl = 'https://model-relay.zzengine.net';
  1133. if (empty($apiKey)) {
  1134. return [
  1135. 'code' => 1002,
  1136. 'msg' => '智真AI API KEY未配置,请检查环境变量ZHIZHEN_AI_SK',
  1137. 'data' => null
  1138. ];
  1139. }
  1140. dLog('generate')->info('智真AI查询素材: ' . $assetId);
  1141. // 调用智真AI API
  1142. $response = $this->httpClient->post($apiUrl . '/api/v1/asset/get', [
  1143. 'headers' => [
  1144. 'X-Api-Key' => $apiKey,
  1145. 'Content-Type' => 'application/json',
  1146. ],
  1147. 'json' => [
  1148. 'asset_id' => $assetId,
  1149. ],
  1150. ]);
  1151. $responseData = json_decode($response->getBody()->getContents(), true);
  1152. dLog('generate')->info('智真AI查询素材响应: ', $responseData);
  1153. logDB('generate', 'info', '智真AI查询素材', ['asset_id' => $assetId, 'response' => $responseData]);
  1154. if ($responseData['code'] !== 0) {
  1155. return [
  1156. 'code' => $responseData['code'],
  1157. 'msg' => $responseData['msg'] ?? '查询素材失败',
  1158. 'data' => null
  1159. ];
  1160. }
  1161. $assetInfo = $responseData['data']['asset'] ?? [];
  1162. // 更新本地数据库记录
  1163. $localAsset = MpAsset::where('asset_id', $assetId)->first();
  1164. if ($localAsset) {
  1165. $localAsset->update([
  1166. 'status' => $assetInfo['status'] ?? MpAsset::STATUS_PROCESSING,
  1167. 'cover_url' => $assetInfo['url'] ?? null,
  1168. 'extra_params' => $responseData,
  1169. ]);
  1170. }
  1171. return [
  1172. 'code' => 0,
  1173. 'msg' => '查询成功',
  1174. 'data' => [
  1175. 'asset' => $assetInfo
  1176. ]
  1177. ];
  1178. } catch (\Exception $e) {
  1179. dLog('generate')->error('查询素材异常: ' . $e->getMessage());
  1180. logDB('generate', 'error', '查询素材异常', ['asset_id' => $assetId, 'error' => $e->getMessage()]);
  1181. return [
  1182. 'code' => 20003,
  1183. 'msg' => '查询素材失败: ' . $e->getMessage(),
  1184. 'data' => null
  1185. ];
  1186. }
  1187. }
  1188. /**
  1189. * 更新所有待处理任务的状态
  1190. *
  1191. * @return void
  1192. */
  1193. public function updatePendingTasks(): void
  1194. {
  1195. dLog('generate')->info('更新图片状态ing');
  1196. // 1. 处理火山API的pending任务(批量提交到队列)
  1197. $volcPendingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
  1198. ->whereIn('model', BaseConst::VOLC_PIC_MODELS)
  1199. ->orderBy('created_at', 'asc')
  1200. ->limit(50) // 每次最多处理50个任务,避免超时
  1201. ->get();
  1202. foreach ($volcPendingTasks as $task) {
  1203. dLog('generate')->info('开始分发火山API任务到队列: ' . $task->task_id);
  1204. // 分发到队列
  1205. \App\Jobs\ProcessVolcImageGenerationJob::dispatch($task->id)->onConnection('redis');
  1206. }
  1207. // 2. 处理GPT-Image2的pending任务(批量提交到队列)
  1208. $gptImage2PendingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
  1209. ->whereIn('model', BaseConst::GPT_IMAGE2_MODELS)
  1210. ->orderBy('created_at', 'asc')
  1211. ->limit(50) // 每次最多处理50个任务,避免超时
  1212. ->get();
  1213. foreach ($gptImage2PendingTasks as $task) {
  1214. dLog('generate')->info('开始分发GPT-Image2任务到队列: ' . $task->task_id);
  1215. // 分发到队列
  1216. \App\Jobs\ProcessGptImage2GenerationJob::dispatch($task->id)->onConnection('redis');
  1217. }
  1218. // 3. 获取所有处理中的任务(即梦AI和NanoBanana系列需要查询状态)
  1219. $processingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)
  1220. ->whereIn('model', array_merge([self::MODEL_JIMENG_4], BaseConst::NANO_BANANA_MODELS))
  1221. ->get();
  1222. foreach ($processingTasks as $task) {
  1223. $statusInfo = $this->queryTaskStatus($task);
  1224. if ($statusInfo['status'] === 'success') {
  1225. logDB('generate', 'info', '即梦AI图片生成任务成功', ['task_id' => $task->task_id, 'result_url' => $statusInfo['result_url']]);
  1226. $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
  1227. 'result_url' => $statusInfo['result_url'],
  1228. 'result_json' => $statusInfo['result_json'] ?? []
  1229. ]);
  1230. // 同步调整分镜图片状态和结果
  1231. $segment_id = getProp($task, 'alias_segment_id');
  1232. if ($segment_id) {
  1233. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  1234. 'img_url' => $statusInfo['result_url'][0],
  1235. 'pic_task_status' => '已完成',
  1236. ]);
  1237. // 如果是首帧图ID则更新anime表
  1238. if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
  1239. $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
  1240. 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')]);
  1241. Redis::srem('anime_first_frame_urls', $segment_id);
  1242. }
  1243. }
  1244. } elseif ($statusInfo['status'] === 'failed') {
  1245. logDB('generate', 'error', '即梦AI图片生成任务失败', ['task_id' => $task->task_id, 'error' => $statusInfo['error_message']]);
  1246. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  1247. 'error_message' => $statusInfo['error_message'],
  1248. 'result_json' => $statusInfo['result_json'] ?? []
  1249. ]);
  1250. if (getProp($task, 'alias_segment_id')) {
  1251. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  1252. 'pic_task_status' => '失败',
  1253. ]);
  1254. }
  1255. }
  1256. // 如果仍然是处理中状态,不做任何操作
  1257. //处理:如果任务处理超过12小时,标记为失败
  1258. $processingTime = now()->diffInHours($task->created_at);
  1259. if ($processingTime > 12) {
  1260. logDB('generate', 'warning', '即梦AI图片生成任务超时', ['task_id' => $task->task_id, 'processing_hours' => $processingTime]);
  1261. $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
  1262. 'error_message' => '任务处理超时(超过12小时)'
  1263. ]);
  1264. }
  1265. }
  1266. // 4. 检查是否有任务完成,如果有则处理下一个排队任务(仅即梦AI)
  1267. $this->processNextQueuedTask();
  1268. }
  1269. /**
  1270. * 处理下一个排队的任务
  1271. *
  1272. * @return void
  1273. */
  1274. public function processNextQueuedTask(): void
  1275. {
  1276. // 检查是否还有正在处理的任务(仅即梦AI)
  1277. if ($this->hasProcessingTask()) {
  1278. return; // 如果还有处理中的任务,不处理新任务
  1279. }
  1280. // 获取最早的待处理任务(仅即梦AI)
  1281. $nextTask = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
  1282. ->where('model', self::MODEL_JIMENG_4)
  1283. ->orderBy('created_at', 'asc')
  1284. ->first();
  1285. if ($nextTask) {
  1286. dLog('generate')->info('开始处理排队任务: ' . $nextTask->task_id);
  1287. logDB('generate', 'info', '开始处理即梦AI排队任务', ['task_id' => $nextTask->task_id]);
  1288. $this->submitTaskToJimengApi($nextTask);
  1289. }
  1290. }
  1291. /**
  1292. * 获取任务队列状态
  1293. *
  1294. * @return array
  1295. */
  1296. public function getQueueStatus(): array
  1297. {
  1298. $processingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)->count();
  1299. $pendingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)->count();
  1300. return [
  1301. 'processing_count' => $processingCount,
  1302. 'pending_count' => $pendingCount,
  1303. 'can_submit_new_task' => $processingCount === 0
  1304. ];
  1305. }
  1306. /**
  1307. * 处理智真AI的参考图片转素材
  1308. *
  1309. * @param array $referenceImages 参考图片URL数组
  1310. * @param string &$fullPrompt 完整提示词(引用传递,用于删除失败图片的标记)
  1311. * @return array 返回素材ID数组
  1312. */
  1313. public function processReferenceImagesToAssets(array $referenceImages, string &$fullPrompt): array
  1314. {
  1315. $assetIds = [];
  1316. $failedIndexes = []; // 记录失败的图片序号
  1317. foreach ($referenceImages as $index => $imageUrl) {
  1318. $imageIndex = $index + 1; // 图片序号从1开始
  1319. try {
  1320. dLog('generate')->info("开始处理参考图片 {$imageIndex}: {$imageUrl}");
  1321. // 1. 创建素材
  1322. $createResult = $this->createAsset([
  1323. 'url' => $imageUrl,
  1324. 'asset_type' => MpAsset::TYPE_IMAGE,
  1325. 'name' => "参考图片_{$imageIndex}_" . time(),
  1326. ]);
  1327. if ($createResult['code'] !== 0) {
  1328. dLog('generate')->warning("图片 {$imageIndex} 创建素材失败: " . $createResult['msg']);
  1329. logDB('generate', 'warning', '创建素材失败', [
  1330. 'image_url' => $imageUrl,
  1331. 'index' => $imageIndex,
  1332. 'error' => $createResult['msg']
  1333. ]);
  1334. $failedIndexes[] = $imageIndex;
  1335. continue;
  1336. }
  1337. $assetId = $createResult['data']['asset_id'];
  1338. dLog('generate')->info("图片 {$imageIndex} 素材创建成功,asset_id: {$assetId},开始轮询查询状态");
  1339. // 2. 轮询查询素材状态(每3秒查询一次,最多查询100次即5分钟)
  1340. $maxAttempts = 100;
  1341. $attempt = 0;
  1342. $assetStatus = null;
  1343. while ($attempt < $maxAttempts) {
  1344. sleep(3); // 等待3秒
  1345. $attempt++;
  1346. $getResult = $this->getAsset($assetId);
  1347. if ($getResult['code'] !== 0) {
  1348. dLog('generate')->warning("图片 {$imageIndex} 查询素材状态失败: " . $getResult['msg']);
  1349. continue;
  1350. }
  1351. $assetStatus = $getResult['data']['asset']['status'] ?? null;
  1352. dLog('generate')->info("图片 {$imageIndex} 素材状态查询第 {$attempt} 次,状态: {$assetStatus}");
  1353. if ($assetStatus === 'Active') {
  1354. // 素材可用
  1355. $assetIds[] = $assetId;
  1356. dLog('generate')->info("图片 {$imageIndex} 素材处理成功,asset_id: {$assetId}");
  1357. logDB('generate', 'info', '素材转换成功', [
  1358. 'image_url' => $imageUrl,
  1359. 'index' => $imageIndex,
  1360. 'asset_id' => $assetId
  1361. ]);
  1362. break;
  1363. } elseif ($assetStatus === 'Failed') {
  1364. // 素材处理失败
  1365. dLog('generate')->warning("图片 {$imageIndex} 素材处理失败");
  1366. logDB('generate', 'warning', '素材处理失败', [
  1367. 'image_url' => $imageUrl,
  1368. 'index' => $imageIndex,
  1369. 'asset_id' => $assetId
  1370. ]);
  1371. $failedIndexes[] = $imageIndex;
  1372. break;
  1373. }
  1374. // 其他状态(Processing等)继续等待
  1375. }
  1376. // 如果超时还未成功
  1377. if ($attempt >= $maxAttempts && $assetStatus !== 'Active') {
  1378. dLog('generate')->warning("图片 {$imageIndex} 素材处理超时");
  1379. logDB('generate', 'warning', '素材处理超时', [
  1380. 'image_url' => $imageUrl,
  1381. 'index' => $imageIndex,
  1382. 'asset_id' => $assetId,
  1383. 'last_status' => $assetStatus
  1384. ]);
  1385. $failedIndexes[] = $imageIndex;
  1386. }
  1387. } catch (\Exception $e) {
  1388. dLog('generate')->error("图片 {$imageIndex} 处理异常: " . $e->getMessage());
  1389. logDB('generate', 'error', '素材转换异常', [
  1390. 'image_url' => $imageUrl,
  1391. 'index' => $imageIndex,
  1392. 'error' => $e->getMessage()
  1393. ]);
  1394. $failedIndexes[] = $imageIndex;
  1395. }
  1396. }
  1397. // 处理失败的图片:从 fullPrompt 中删除对应的标记并调整序号
  1398. if (!empty($failedIndexes)) {
  1399. dLog('generate')->info('开始处理失败图片的提示词调整,失败序号: ' . implode(',', $failedIndexes));
  1400. // 按序号从大到小排序,避免删除时影响后续序号
  1401. rsort($failedIndexes);
  1402. foreach ($failedIndexes as $failedIndex) {
  1403. // 删除失败图片的标记,例如 <图片1>、<图片2> 等
  1404. $pattern = "/<图片{$failedIndex}>/u";
  1405. $fullPrompt = preg_replace($pattern, '', $fullPrompt);
  1406. dLog('generate')->info("已从提示词中删除 <图片{$failedIndex}>");
  1407. }
  1408. // 重新调整剩余图片的序号
  1409. // 例如:如果图片2失败,图片3、图片4需要改为图片2、图片3
  1410. $needAdjust = false;
  1411. foreach ($failedIndexes as $failedIndex) {
  1412. $needAdjust = true;
  1413. // 将所有大于失败序号的图片标记序号减1
  1414. for ($i = $failedIndex + 1; $i <= count($referenceImages); $i++) {
  1415. $oldPattern = "/<图片{$i}>/u";
  1416. $newTag = "<图片" . ($i - 1) . ">";
  1417. $fullPrompt = preg_replace($oldPattern, $newTag, $fullPrompt);
  1418. }
  1419. }
  1420. if ($needAdjust) {
  1421. dLog('generate')->info('提示词图片序号调整完成');
  1422. logDB('generate', 'info', '提示词调整', [
  1423. 'failed_indexes' => $failedIndexes,
  1424. 'adjusted_prompt' => $fullPrompt
  1425. ]);
  1426. }
  1427. }
  1428. dLog('generate')->info('参考图片转素材完成,成功数量: ' . count($assetIds) . ',失败数量: ' . count($failedIndexes));
  1429. // 格式化为可直接在API接口中使用的数组
  1430. foreach($assetIds as &$assetId) {
  1431. $assetId = "asset://{$assetId}";
  1432. }
  1433. return $assetIds;
  1434. }
  1435. /**
  1436. * 根据宽高反推图片比例
  1437. * @param int $width 宽度
  1438. * @param int $height 高度
  1439. * @return string 比例字符串,如 "9:16",匹配不到则返回 "auto"
  1440. */
  1441. private function getRatioFromSize($width, $height)
  1442. {
  1443. if (!$width || !$height) {
  1444. return 'auto';
  1445. }
  1446. // 遍历所有预定义的比例,查找匹配的
  1447. foreach (BaseConst::IMAGE_RATIOS as $ratio => $size) {
  1448. if ($size['width'] == $width && $size['height'] == $height) {
  1449. return $ratio;
  1450. }
  1451. }
  1452. // 没有精确匹配,尝试通过计算比例匹配
  1453. $gcd = $this->gcd($width, $height);
  1454. $simplifiedRatio = ($width / $gcd) . ':' . ($height / $gcd);
  1455. // 检查简化后的比例是否在预定义列表中
  1456. if (isset(BaseConst::IMAGE_RATIOS[$simplifiedRatio])) {
  1457. return $simplifiedRatio;
  1458. }
  1459. return 'auto';
  1460. }
  1461. /**
  1462. * 压缩图片流(针对PNG格式)
  1463. *
  1464. * @param string $imageStream 图片二进制数据
  1465. * @param int $maxBytes 最大字节数(默认3MB)
  1466. * @return string|null 压缩后的图片二进制数据,失败时返回原数据
  1467. */
  1468. private function compressImageStream(string $imageStream, int $maxBytes = 3 * 1024 * 1024): ?string
  1469. {
  1470. try {
  1471. // 检查图片类型
  1472. $imgInfo = @getimagesizefromstring($imageStream);
  1473. if (!$imgInfo) {
  1474. dLog('generate')->warning('无法识别图片类型,返回原始数据');
  1475. return $imageStream;
  1476. }
  1477. $mime = $imgInfo['mime'] ?? '';
  1478. // 只处理PNG,JPEG不做有损压缩
  1479. if ($mime === 'image/jpeg') {
  1480. return $imageStream;
  1481. }
  1482. // 如果已经小于最大限制,直接返回
  1483. if (strlen($imageStream) <= $maxBytes) {
  1484. return $imageStream;
  1485. }
  1486. // 载入图像对象
  1487. $srcImg = @imagecreatefromstring($imageStream);
  1488. if (!$srcImg) {
  1489. dLog('generate')->warning('无法创建图像资源,返回原始数据');
  1490. return $imageStream;
  1491. }
  1492. $origW = imagesx($srcImg);
  1493. $origH = imagesy($srcImg);
  1494. // 逐步降低质量直到满足大小要求
  1495. $quality = 9; // PNG压缩等级 0-9
  1496. $scaleFactor = 1.0;
  1497. $maxAttempts = 10;
  1498. $attempt = 0;
  1499. $compressedData = null;
  1500. while ($attempt < $maxAttempts) {
  1501. $attempt++;
  1502. // 如果需要缩放
  1503. if ($scaleFactor < 1.0) {
  1504. $newW = (int)($origW * $scaleFactor);
  1505. $newH = (int)($origH * $scaleFactor);
  1506. $resizedImg = imagecreatetruecolor($newW, $newH);
  1507. // 保持透明度
  1508. imagealphablending($resizedImg, false);
  1509. imagesavealpha($resizedImg, true);
  1510. imagecopyresampled($resizedImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $origW, $origH);
  1511. $targetImg = $resizedImg;
  1512. } else {
  1513. $targetImg = $srcImg;
  1514. }
  1515. // 输出到内存
  1516. ob_start();
  1517. imagepng($targetImg, null, $quality);
  1518. $compressedData = ob_get_clean();
  1519. if ($scaleFactor < 1.0) {
  1520. imagedestroy($targetImg);
  1521. }
  1522. // 检查大小
  1523. $size = strlen($compressedData);
  1524. dLog('generate')->info('图片压缩尝试', [
  1525. 'attempt' => $attempt,
  1526. 'quality' => $quality,
  1527. 'scale' => $scaleFactor,
  1528. 'size' => $size,
  1529. 'target' => $maxBytes
  1530. ]);
  1531. if ($size <= $maxBytes) {
  1532. break;
  1533. }
  1534. // 调整参数
  1535. if ($quality > 0) {
  1536. $quality--;
  1537. } else {
  1538. $scaleFactor *= 0.9; // 每次缩小10%
  1539. }
  1540. }
  1541. imagedestroy($srcImg);
  1542. return $compressedData ?: $imageStream;
  1543. } catch (\Exception $e) {
  1544. dLog('generate')->error('图片压缩失败', ['error' => $e->getMessage()]);
  1545. return $imageStream;
  1546. }
  1547. }
  1548. /**
  1549. * 从响应数据中移除 b64_json 字段
  1550. * 避免在日志和数据库中存储大量 Base64 数据
  1551. *
  1552. * @param array $responseData
  1553. * @return array
  1554. */
  1555. private function removeB64JsonFromResponse(array $responseData): array
  1556. {
  1557. $cleanedData = $responseData;
  1558. if (isset($cleanedData['data']) && is_array($cleanedData['data'])) {
  1559. foreach ($cleanedData['data'] as &$imageData) {
  1560. if (isset($imageData['b64_json'])) {
  1561. // 移除 b64_json 字段,可选择性保留数据长度信息
  1562. $b64Length = strlen($imageData['b64_json']);
  1563. unset($imageData['b64_json']);
  1564. $imageData['b64_json_removed'] = true;
  1565. $imageData['b64_json_length'] = $b64Length;
  1566. }
  1567. }
  1568. unset($imageData); // 解除引用
  1569. }
  1570. return $cleanedData;
  1571. }
  1572. }