AIImageGenerationService.php 76 KB

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