AIImageGenerationService.php 76 KB

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