AnimeController.php 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  1. <?php
  2. namespace App\Http\Controllers\Anime;
  3. use App\Transformer\Anime\AnimeTransformer;
  4. use App\Facade\Site;
  5. use App\Consts\ErrorConst;
  6. use App\Exceptions\ApiException;
  7. use App\Libs\ApiResponse;
  8. use App\Libs\Utils;
  9. use App\Models\MpGenerateVideoTask;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\Anime\AnimeService;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Routing\Controller as BaseController;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Redis;
  17. use Illuminate\Support\Facades\Validator;
  18. class AnimeController extends BaseController
  19. {
  20. use ApiResponse;
  21. protected $AnimeService;
  22. protected $AIImageGenerationService;
  23. protected $AIVideoGenerationService;
  24. public function __construct(
  25. AnimeService $AnimeService,
  26. AIImageGenerationService $AIImageGenerationService,
  27. AIVideoGenerationService $AIVideoGenerationService
  28. ) {
  29. $this->AnimeService = $AnimeService;
  30. $this->AIImageGenerationService = $AIImageGenerationService;
  31. $this->AIVideoGenerationService = $AIVideoGenerationService;
  32. }
  33. // 文字模型
  34. public function textModel() {
  35. $query = DB::table('mp_text_models')->where('is_enabled', 1);
  36. // 支持 model 搜索
  37. if ($model = request('model')) {
  38. $query->where('model', 'like', "%{$model}%");
  39. }
  40. // 支持 name 搜索
  41. if ($name = request('name')) {
  42. $query->where('name', 'like', "%{$name}%");
  43. }
  44. $models = $query->select('model', 'name')->get()->map(function ($value) {
  45. return (array)$value;
  46. })->toArray();
  47. return $this->success($models);
  48. }
  49. // 图片模型
  50. public function imageModel() {
  51. $query = DB::table('mp_image_models')->where('is_enabled', 1);
  52. // 支持 model 搜索
  53. if ($model = request('model')) {
  54. $query->where('model', 'like', "%{$model}%");
  55. }
  56. // 支持 name 搜索
  57. if ($name = request('name')) {
  58. $query->where('name', 'like', "%{$name}%");
  59. }
  60. $models = $query->select('model', 'name')->get()->map(function ($value) {
  61. return (array)$value;
  62. })->toArray();
  63. return $this->success($models);
  64. }
  65. // 视频模型
  66. public function videoModel() {
  67. $query = DB::table('mp_video_models')->where('is_enabled', 1);
  68. // 支持 model 搜索
  69. if ($model = request('model')) {
  70. $query->where('model', 'like', "%{$model}%");
  71. }
  72. // 支持 name 搜索
  73. if ($name = request('name')) {
  74. $query->where('name', 'like', "%{$name}%");
  75. }
  76. $models = $query->select('model', 'name')->get()->map(function ($value) {
  77. return (array)$value;
  78. })->toArray();
  79. return $this->success($models);
  80. }
  81. public function artStyleList()
  82. {
  83. $result = [
  84. [
  85. 'art_style' => '唯美真人风格',
  86. 'pic_url' => "http://zw-ai.oss-cn-hangzhou.aliyuncs.com/mp_audio/art_styles/%E5%94%AF%E7%BE%8E%E7%9C%9F%E4%BA%BA.jpg"
  87. ],
  88. [
  89. 'art_style' => '真人古风风格',
  90. 'pic_url' => "http://zw-ai.oss-cn-hangzhou.aliyuncs.com/mp_audio/art_styles/%E7%9C%9F%E4%BA%BA%E5%8F%A4%E9%A3%8E.jpg"
  91. ],
  92. [
  93. 'art_style' => '日系动漫风格',
  94. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/日系动漫风格.jpg"
  95. ],
  96. [
  97. 'art_style' => '国漫风格',
  98. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/国漫风格.jpg"
  99. ],
  100. [
  101. 'art_style' => 'Q版卡通风格',
  102. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/Q版卡通风格.jpg"
  103. ],
  104. [
  105. 'art_style' => '简约扁平风格',
  106. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/简约扁平风格.jpg"
  107. ],
  108. [
  109. 'art_style' => '古风仙侠风格',
  110. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/古风仙侠风格.jpg"
  111. ],
  112. [
  113. 'art_style' => '武侠风格',
  114. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/武侠风格.jpg"
  115. ],
  116. [
  117. 'art_style' => '新中式水墨风格',
  118. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/新中式水墨风格.jpg"
  119. ],
  120. [
  121. 'art_style' => '写实插画风格',
  122. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/写实插画风格.jpg"
  123. ],
  124. [
  125. 'art_style' => '3D卡通风格',
  126. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/3D卡通风格.jpg"
  127. ],
  128. [
  129. 'art_style' => '条漫风格',
  130. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/条漫风格.jpg"
  131. ],
  132. [
  133. 'art_style' => '赛博朋克风格',
  134. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/赛博朋克风格.jpg"
  135. ],
  136. [
  137. 'art_style' => '暗黑悬疑风格',
  138. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/暗黑悬疑风格.jpg"
  139. ],
  140. [
  141. 'art_style' => '治愈清新风格',
  142. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/治愈清新风格.jpg"
  143. ],
  144. ];
  145. return $this->success($result);
  146. }
  147. // 新建动漫
  148. public function createAnime(Request $request) {
  149. $data = $request->all();
  150. $result = $this->AnimeService->createAnime($data);
  151. return $this->success(['anime_id' => $result]);
  152. }
  153. // 编辑动漫
  154. public function editAnime(Request $request) {
  155. $data = $request->all();
  156. $result = $this->AnimeService->editAnime($data);
  157. return $this->success(['success'=>$result ? 1 : 0]);
  158. }
  159. // 删除动漫
  160. public function delAnime(Request $request) {
  161. $data = $request->all();
  162. $result = $this->AnimeService->delAnime($data);
  163. return $this->success(['success'=>$result ? 1 : 0]);
  164. }
  165. // 批量生成主体图片
  166. public function batchSetRoleImg(Request $request) {
  167. // 忽略所有超时限制
  168. set_time_limit(0);
  169. ini_set('max_execution_time', '0');
  170. $data = $request->all();
  171. $result = $this->AnimeService->batchSetRoleImg($data);
  172. return $this->success($result);
  173. }
  174. // 批量生成场景图片
  175. public function batchSetSceneImg(Request $request) {
  176. // 忽略所有超时限制
  177. set_time_limit(0);
  178. ini_set('max_execution_time', '0');
  179. $data = $request->all();
  180. $result = $this->AnimeService->batchSetSceneImg($data);
  181. return $this->success($result);
  182. }
  183. // 修改分集主体列表
  184. public function changeEpisodeRoles(Request $request) {
  185. $data = $request->all();
  186. $result = $this->AnimeService->changeEpisodeRoles($data);
  187. return $this->success(['success'=>$result ? 1 : 0]);
  188. }
  189. // 修改分集场景列表
  190. public function changeEpisodeScenes(Request $request) {
  191. $data = $request->all();
  192. $result = $this->AnimeService->changeEpisodeScenes($data);
  193. return $this->success(['success'=>$result ? 1 : 0]);
  194. }
  195. // 编辑分镜剧本
  196. public function editSegment(Request $request) {
  197. $data = $request->all();
  198. $result = $this->AnimeService->editSegment($data);
  199. return $this->success(['success'=>$result ? 1 : 0]);
  200. }
  201. // 动漫对话列表
  202. public function chatList(Request $request) {
  203. $data = $request->all();
  204. $result = $this->AnimeService->chatList($data);
  205. return $this->success($result, [new AnimeTransformer(), 'newBuildChatList']);
  206. }
  207. // 动漫对话历史记录
  208. public function chatHistory(Request $request) {
  209. $data = $request->all();
  210. $result = $this->AnimeService->chatHistory($data);
  211. return $this->success($result);
  212. }
  213. // 动漫大纲
  214. public function animeDetail(Request $request) {
  215. $data = $request->all();
  216. $result = $this->AnimeService->animeDetail($data);
  217. return $this->success($result);
  218. }
  219. // 动漫剧集
  220. public function episodeInfo(Request $request) {
  221. $data = $request->all();
  222. $result = $this->AnimeService->episodeInfo($data);
  223. return $this->success($result);
  224. }
  225. // 分镜信息
  226. public function segmentInfo(Request $request) {
  227. $data = $request->all();
  228. $result = $this->AnimeService->segmentInfo($data);
  229. return $this->success($result);
  230. }
  231. // 复制剧集副本
  232. public function copyEpisodeVersion(Request $request) {
  233. $data = $request->all();
  234. $result = $this->AnimeService->copyEpisodeVersion($data);
  235. return $this->success($result);
  236. }
  237. // 剧集副本列表
  238. public function episodeVersions(Request $request) {
  239. $data = $request->all();
  240. $result = $this->AnimeService->episodeVersions($data);
  241. return $this->success($result);
  242. }
  243. // 绑定剧集副本
  244. public function bindEpisodeVersion(Request $request) {
  245. $data = $request->all();
  246. $result = $this->AnimeService->bindEpisodeVersion($data);
  247. return $this->success(['success' => $result ? 1 : 0]);
  248. }
  249. // 对话改图
  250. public function chatChangeImg(Request $request) {
  251. $data = $request->all();
  252. $result = $this->AnimeService->chatChangeImg($data);
  253. return $this->success(['img_url' => $result]);
  254. }
  255. public function segmentChatHistory(Request $request) {
  256. $data = $request->all();
  257. $result = $this->AnimeService->segmentChatHistory($data);
  258. return $this->success($result);
  259. }
  260. // 一键生成分镜
  261. public function batchSetSegmentPics(Request $request) {
  262. // 忽略所有超时限制
  263. set_time_limit(0);
  264. ini_set('max_execution_time', '0');
  265. $data = $request->all();
  266. $result = $this->AnimeService->batchSetSegmentPics($data);
  267. return $this->success($result);
  268. }
  269. // 重新生成分镜
  270. public function reGenerateSegment(Request $request) {
  271. // 忽略所有超时限制
  272. set_time_limit(0);
  273. ini_set('max_execution_time', '0');
  274. $data = $request->all();
  275. $result = $this->AnimeService->reGenerateSegment($data);
  276. return $this->success(['img_url'=>$result]);
  277. }
  278. // 添加分镜
  279. public function addSegment(Request $request) {
  280. // 忽略所有超时限制
  281. set_time_limit(0);
  282. ini_set('max_execution_time', '0');
  283. $data = $request->all();
  284. $result = $this->AnimeService->addSegment($data);
  285. return $this->success($result);
  286. }
  287. // 复制分镜
  288. public function copySegment(Request $request) {
  289. $data = $request->all();
  290. $result = $this->AnimeService->copySegment($data);
  291. return $this->success($result);
  292. }
  293. // 移动分镜
  294. public function moveSegment(Request $request) {
  295. $data = $request->all();
  296. $result = $this->AnimeService->moveSegment($data);
  297. return $this->success(['success'=>$result ? 1: 0]);
  298. }
  299. // 删除分镜
  300. public function delSegment(Request $request) {
  301. $data = $request->all();
  302. $result = $this->AnimeService->delSegment($data);
  303. return $this->success(['success'=>$result ? 1: 0]);
  304. }
  305. public function applySegment(Request $request) {
  306. $data = $request->all();
  307. $result = $this->AnimeService->applySegment($data);
  308. return $this->success(['success'=>$result ? 1: 0]);
  309. }
  310. // 分镜历史图片|视频
  311. public function segmentHistory(Request $request) {
  312. $data = $request->all();
  313. $result = $this->AnimeService->segmentHistory($data);
  314. return $this->success($result);
  315. }
  316. public function createSegmentVideoTask(Request $request) {
  317. $uid = Site::getUid();
  318. // 忽略所有超时限制
  319. set_time_limit(0);
  320. ini_set('max_execution_time', '0');
  321. $data = $request->all();
  322. // 验证参数
  323. $validator = Validator::make($data, [
  324. 'segment_id' => 'required|string',
  325. 'tail_frame' => 'nullable|string|max:500',
  326. ], [
  327. 'segment_id.required' => '分镜ID不能为空',
  328. 'tail_frame.max' => '尾帧描述不能超过500个字符',
  329. ]);
  330. if ($validator->fails()) {
  331. Utils::throwError('1002:' . $validator->errors()->first());
  332. }
  333. // 创建视频生成任务
  334. $result = $this->AnimeService->createSegmentVideoTask($data);
  335. $taskId = $result['task_id'];
  336. // 设置 SSE 响应头
  337. return response()->stream(function () use ($taskId, $result, $uid) {
  338. // 设置 SSE 响应头
  339. echo "data: " . json_encode([
  340. 'type' => 'init',
  341. 'data' => $result
  342. ]) . "\n\n";
  343. ob_flush();
  344. flush();
  345. $startTime = time();
  346. $maxDuration = 300; // 5分钟超时
  347. $checkInterval = 5; // 每5秒检查一次
  348. while (time() - $startTime < $maxDuration) {
  349. try {
  350. // 查询任务状态
  351. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  352. if (!$task) {
  353. echo "data: " . json_encode([
  354. 'type' => 'error',
  355. 'message' => '任务不存在'
  356. ]) . "\n\n";
  357. ob_flush();
  358. flush();
  359. break;
  360. }
  361. // 如果任务还在处理中,查询最新状态
  362. if ($task->status === 'processing') {
  363. // 根据任务类型查询不同的状态
  364. if ($task->task_type === 'jimeng') {
  365. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  366. } elseif ($task->task_type === 'keling') {
  367. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  368. } else {
  369. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  370. }
  371. if (isset($statusResult['status'])) {
  372. // 更新任务状态
  373. $task->update([
  374. 'status' => $statusResult['status'],
  375. 'result_url' => $statusResult['result_url'] ?? null,
  376. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  377. 'error_message' => $statusResult['error_message'] ?? null,
  378. 'completed_at' => in_array($statusResult['status'], [
  379. 'success',
  380. 'failed'
  381. ]) ? now() : null
  382. ]);
  383. // 如果任务成功,更新分镜表
  384. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  385. try {
  386. DB::beginTransaction();
  387. $now = date('Y-m-d H:i:s');
  388. // 获取分镜ID
  389. $segment = DB::table('mp_episode_segments')
  390. ->where('video_task_id', $taskId)
  391. ->first();
  392. if (!$segment) {
  393. throw new \Exception('未找到对应的分镜记录');
  394. }
  395. $segmentId = $segment->segment_id;
  396. $anime_id = $segment->anime_id;
  397. $episode_number = $segment->episode_number;
  398. $tail_frame = $segment->tail_frame;
  399. // 更新分镜表
  400. $segmentUpdateData = [
  401. 'video_url' => $statusResult['result_url'],
  402. 'video_task_status' => '已完成',
  403. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  404. 'current_type' => 2,
  405. 'updated_at' => $now
  406. ];
  407. // 只有当video_duration存在且大于0时才更新
  408. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  409. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  410. $segmentUpdateData['video_time_point_start'] = 0;
  411. $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  412. }
  413. $updateResult = DB::table('mp_episode_segments')
  414. ->where('segment_id', $segmentId)
  415. ->update($segmentUpdateData);
  416. if (!$updateResult) {
  417. Utils::throwError('20003:更新分镜表失败');
  418. }
  419. // 更新分镜视频成功后新增对话记录
  420. // 保存对话记录
  421. $records = [
  422. [
  423. 'uid' => $uid,
  424. 'anime_id' => $anime_id,
  425. 'sequence' => $episode_number,
  426. 'role' => 'user',
  427. 'content' => '图片转视频',
  428. 'segment_id' => $segmentId,
  429. 'video_url' => '',
  430. 'created_at' => $now,
  431. 'updated_at' => $now
  432. ],
  433. [
  434. 'uid' => $uid,
  435. 'anime_id' => $anime_id,
  436. 'sequence' => $episode_number,
  437. 'role' => 'assistant',
  438. 'content' => $tail_frame,
  439. 'segment_id' => $segmentId,
  440. 'video_url' => $statusResult['result_url'],
  441. 'created_at' => $now,
  442. 'updated_at' => $now
  443. ]
  444. ];
  445. DB::table('mp_anime_records')->insert($records);
  446. DB::commit();
  447. } catch (\Exception $e) {
  448. DB::rollBack();
  449. $logData = [
  450. 'task_id' => $taskId,
  451. 'error' => $e->getMessage()
  452. ];
  453. dLog('anime')->error('视频任务处理失败', $logData);
  454. logDB('anime', 'error', '视频任务处理失败', $logData);
  455. }
  456. } elseif ($statusResult['status'] === 'failed') {
  457. DB::table('mp_episode_segments')
  458. ->where('video_task_id', $taskId)
  459. ->update([
  460. 'video_task_status' => '失败',
  461. 'updated_at' => date('Y-m-d H:i:s')
  462. ]);
  463. }
  464. }
  465. }
  466. // 发送当前状态
  467. echo "data: " . json_encode([
  468. 'type' => 'update',
  469. 'data' => [
  470. 'task_id' => $task->id,
  471. 'status' => $task->status,
  472. 'result_url' => $task->result_url,
  473. 'error_message' => $task->error_message,
  474. 'elapsed_time' => time() - $startTime
  475. ]
  476. ]) . "\n\n";
  477. ob_flush();
  478. flush();
  479. // 如果任务完成(成功或失败),结束连接
  480. if (in_array($task->status, [
  481. 'success',
  482. 'failed'
  483. ])) {
  484. echo "data: " . json_encode([
  485. 'type' => 'completed',
  486. 'data' => [
  487. 'task_id' => $task->id,
  488. 'status' => $task->status,
  489. 'video_url' => $task->result_url,
  490. 'last_frame_url' => $task->last_frame_url,
  491. 'error_message' => $task->error_message
  492. ]
  493. ]) . "\n\n";
  494. ob_flush();
  495. flush();
  496. break;
  497. }
  498. sleep($checkInterval);
  499. } catch (\Exception $e) {
  500. echo "data: " . json_encode([
  501. 'type' => 'error',
  502. 'message' => '查询任务状态失败: ' . $e->getMessage()
  503. ]) . "\n\n";
  504. ob_flush();
  505. flush();
  506. sleep($checkInterval);
  507. }
  508. }
  509. // 超时处理
  510. if (time() - $startTime >= $maxDuration) {
  511. echo "data: " . json_encode([
  512. 'type' => 'time_out',
  513. 'message' => '任务执行超时,请稍后查询任务状态',
  514. 'data' => [
  515. 'task_id' => $taskId
  516. ]
  517. ]) . "\n\n";
  518. ob_flush();
  519. flush();
  520. }
  521. }, 200, [
  522. 'Content-Type' => 'text/event-stream',
  523. 'Cache-Control' => 'no-cache',
  524. 'Connection' => 'keep-alive',
  525. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  526. ]);
  527. }
  528. /**
  529. * 批量生成分镜视频
  530. */
  531. public function batchSetSegmentVideos(Request $request) {
  532. // 忽略所有超时限制
  533. set_time_limit(0);
  534. ini_set('max_execution_time', '0');
  535. $data = $request->all();
  536. // 验证参数
  537. $validator = Validator::make($data, [
  538. 'anime_id' => 'required|string',
  539. 'episode_id' => 'required|integer',
  540. ], [
  541. 'anime_id.required' => '动漫对话ID不能为空',
  542. 'episode_id.required' => '剧集ID不能为空',
  543. 'episode_id.integer' => '剧集ID必须是整数',
  544. ]);
  545. if ($validator->fails()) {
  546. Utils::throwError('1002:' . $validator->errors()->first());
  547. }
  548. $animeId = $data['anime_id'];
  549. $episodeId = $data['episode_id'];
  550. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  551. if (!$episode) Utils::throwError('20003:分集不存在');
  552. $episodeNumber = $episode->episode_number;
  553. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  554. // 获取所有分镜信息
  555. $segments = DB::table('mp_episode_segments')
  556. ->where('anime_id', $animeId)
  557. ->where('episode_id', $episodeId)
  558. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  559. ->orderBy('segment_number')
  560. ->get();
  561. if ($segments->isEmpty()) {
  562. Utils::throwError('20003:未找到分镜数据');
  563. }
  564. // 批量创建视频任务
  565. $taskIds = [];
  566. $segmentTasks = [];
  567. foreach ($segments as $segment) {
  568. try {
  569. // 检查视频任务正在生成中或当前状态为视频
  570. if ($segment->video_task_status === '生成中' || (int)$segment->current_type === 2) {
  571. continue;
  572. }
  573. // 获取分镜内容
  574. $segmentContent = $segment->segment_content ?: '';
  575. $tailFrame = $segment->tail_frame ?: '';
  576. // 构建完整的提示词
  577. $fullPrompt = $segmentContent;
  578. if ($tailFrame) {
  579. $fullPrompt .= "\n尾帧描述:$tailFrame";
  580. }
  581. // 智能选择视频时长
  582. // $videoDuration = $this->AnimeService->calculateOptimalVideoDuration($segmentContent, $tailFrame);
  583. $videoDuration = -1;
  584. // 处理视频模型(在循环外统一处理,避免重复)
  585. if (!isset($model)) {
  586. $model = getProp($data, 'model');
  587. if (!$model) {
  588. // 用户没有输入,从episode表获取
  589. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->first();
  590. $model = getProp($episode, 'video_model');
  591. if (!$model) {
  592. // episode表也没有,使用默认值
  593. $model = 'doubao-seedance-1-5-pro-251215';
  594. }
  595. }
  596. // 验证模型是否在可用模型表中
  597. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  598. $model = 'doubao-seedance-1-5-pro-251215';
  599. }
  600. }
  601. // 构建视频生成参数
  602. $videoParams = [
  603. 'model' => $model,
  604. 'alias_segment_id' => $segment->segment_id,
  605. 'prompt' => $fullPrompt,
  606. 'video_duration' => $videoDuration,
  607. 'video_resolution' => '720P',
  608. 'seed' => -1,
  609. 'ratio' => $ratio,
  610. 'generate_audio' => false,
  611. 'draft' => false,
  612. 'watermark' => false,
  613. 'camera_fixed' => false,
  614. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  615. ];
  616. // 如果分镜有图片,作为首帧
  617. $hasImage = !empty($segment->img_url);
  618. $hasVideo = !empty($segment->video_url);
  619. if ($hasImage) {
  620. $videoParams['first_frame_url'] = $segment->img_url;
  621. }
  622. // 构建content数组
  623. $videoParams['content'] = [
  624. [
  625. 'type' => 'text',
  626. 'text' => $videoParams['prompt'],
  627. ]
  628. ];
  629. // 如果有首帧图片,添加到content中
  630. if ($hasImage) {
  631. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  632. $videoParams['content'][] = [
  633. 'type' => 'image_url',
  634. 'image_url' => [
  635. 'url' => $videoParams['first_frame_url'],
  636. ],
  637. 'role' => 'reference_image',
  638. ];
  639. }else {
  640. $videoParams['content'][] = [
  641. 'type' => 'image_url',
  642. 'image_url' => [
  643. 'url' => $videoParams['first_frame_url'],
  644. ],
  645. 'role' => 'first_frame',
  646. ];
  647. }
  648. }
  649. // 获取配音音频URL和时长
  650. $audioUrl = $segment->audio_url ?? '';
  651. $audioDuration = $segment->audio_duration ?? 0;
  652. // 音频传入的前提:必须有至少一张图片或一个视频
  653. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  654. // 根据模型选择不同的视频生成方法
  655. if (strpos($model, 'jimeng') !== false) {
  656. // 即梦模型参数调整
  657. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  658. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  659. unset($videoParams['ratio']);
  660. unset($videoParams['content']); // 即梦不使用content格式
  661. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  662. } elseif (strpos($model, 'kling') !== false) {
  663. // Keling模型参数调整
  664. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  665. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  666. unset($videoParams['ratio']);
  667. unset($videoParams['content']); // Keling不使用content格式
  668. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  669. } else {
  670. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  671. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  672. // 添加配音音频到content中
  673. $videoParams['content'][] = [
  674. 'type' => 'audio_url',
  675. 'audio_url' => [
  676. 'url' => $audioUrl,
  677. ],
  678. 'role' => 'reference_audio',
  679. ];
  680. // 优化提示词,增加音频相关描述
  681. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  682. $videoParams['prompt'] = $audioPrompt;
  683. $videoParams['content'][0]['text'] = $audioPrompt;
  684. } else if ($audioDuration) {
  685. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  686. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  687. }
  688. // Seedance模型(默认)
  689. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  690. }
  691. $taskIds[] = $task->id;
  692. // 更新分镜表的视频任务信息
  693. DB::table('mp_episode_segments')
  694. ->where('segment_id', $segment->segment_id)
  695. ->update([
  696. 'video_task_id' => $task->id,
  697. 'video_task_status' => '生成中',
  698. 'updated_at' => date('Y-m-d H:i:s')
  699. ]);
  700. $segmentTasks[] = [
  701. 'segment_id' => $segment->segment_id,
  702. 'task_id' => $task->id,
  703. 'segment_number' => $segment->segment_number,
  704. 'tail_frame' => $segment->tail_frame,
  705. ];
  706. } catch (\Exception $e) {
  707. $logData = [
  708. 'segment_id' => $segment->segment_id,
  709. 'anime_id' => $animeId,
  710. 'error' => $e->getMessage(),
  711. ];
  712. dLog('anime')->error('创建分镜视频任务失败', $logData);
  713. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  714. continue;
  715. }
  716. }
  717. if (empty($taskIds)) {
  718. Utils::throwError('20003:没有需要生成视频的分镜');
  719. }
  720. // 保存模型到episode表
  721. if (isset($model)) {
  722. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  723. 'video_model' => $model,
  724. 'updated_at' => date('Y-m-d H:i:s')
  725. ]);
  726. }
  727. // 记录开始时间(包含创建任务的时间)
  728. $startTime = time();
  729. $maxDuration = 1800; // 30分钟超时
  730. $uid = Site::getUid();
  731. // 设置 SSE 响应头并开始长连接
  732. return response()->stream(function () use ($taskIds, $segmentTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  733. $checkInterval = 10; // 每10秒检查一次
  734. // 初始化任务数组
  735. $totalTasks = $taskIds; // 所有任务ID
  736. $completeTasks = []; // 已完成的任务ID(包含失败)
  737. $successTasks = []; // 成功的任务ID
  738. // 发送初始任务创建信息
  739. echo "data: " . json_encode([
  740. 'type' => 'init',
  741. 'total_tasks_count' => count($totalTasks),
  742. 'completed_tasks_count' => count($completeTasks),
  743. 'success_tasks_count' => count($successTasks)
  744. ]) . "\n\n";
  745. ob_flush();
  746. flush();
  747. while (time() - $startTime < $maxDuration) {
  748. try {
  749. $hasUpdate = false; // 标记是否有更新
  750. // 获取所有任务的最新状态
  751. foreach ($totalTasks as $taskId) {
  752. // 如果任务已经在完成列表中,跳过
  753. if (in_array($taskId, $completeTasks)) {
  754. continue;
  755. }
  756. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  757. if (!$task) {
  758. continue;
  759. }
  760. // 如果任务还在处理中,查询最新状态
  761. if ($task->status === 'processing') {
  762. // 根据任务类型查询不同的状态
  763. if ($task->task_type === 'jimeng') {
  764. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  765. } elseif ($task->task_type === 'keling') {
  766. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  767. } else {
  768. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  769. }
  770. if (isset($statusResult['status'])) {
  771. // 更新任务状态
  772. $task->update([
  773. 'status' => $statusResult['status'],
  774. 'result_json' => $statusResult['result_json'] ?? [],
  775. 'result_url' => $statusResult['result_url'] ?? null,
  776. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  777. 'error_message' => $statusResult['error_message'] ?? null,
  778. 'completed_at' => in_array($statusResult['status'], [
  779. 'success',
  780. 'failed'
  781. ]) ? now() : null
  782. ]);
  783. // 如果任务成功,更新分镜表
  784. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  785. try {
  786. DB::beginTransaction();
  787. $now = date('Y-m-d H:i:s');
  788. // 获取分镜ID
  789. $segmentId = null;
  790. foreach ($segmentTasks as $segmentTask) {
  791. if ($segmentTask['task_id'] == $taskId) {
  792. $segmentId = $segmentTask['segment_id'];
  793. $tail_frame = $segmentTask['tail_frame'];
  794. break;
  795. }
  796. }
  797. if ($segmentId) {
  798. // 更新分镜表
  799. $segmentUpdateData = [
  800. 'video_url' => $statusResult['result_url'],
  801. 'video_task_status' => '已完成',
  802. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  803. 'current_type' => 2,
  804. 'updated_at' => $now
  805. ];
  806. // 只有当video_duration存在且大于0时才更新
  807. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  808. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  809. $segmentUpdateData['video_time_point_start'] = 0;
  810. $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  811. }
  812. $updateResult = DB::table('mp_episode_segments')
  813. ->where('segment_id', $segmentId)
  814. ->update($segmentUpdateData);
  815. if ($updateResult) {
  816. // 更新分镜视频成功后新增对话记录
  817. $records = [
  818. [
  819. 'uid' => $uid,
  820. 'anime_id' => $animeId,
  821. 'sequence' => $episodeNumber,
  822. 'role' => 'user',
  823. 'content' => '图片转视频',
  824. 'segment_id' => $segmentId,
  825. 'video_url' => '',
  826. 'created_at' => $now,
  827. 'updated_at' => $now
  828. ],
  829. [
  830. 'uid' => $uid,
  831. 'anime_id' => $animeId,
  832. 'sequence' => $episodeNumber,
  833. 'role' => 'assistant',
  834. 'content' => $tail_frame ?? '',
  835. 'segment_id' => $segmentId,
  836. 'video_url' => $statusResult['result_url'],
  837. 'created_at' => $now,
  838. 'updated_at' => $now
  839. ]
  840. ];
  841. DB::table('mp_anime_records')->insert($records);
  842. }
  843. }
  844. DB::commit();
  845. } catch (\Exception $e) {
  846. DB::rollBack();
  847. $logData = [
  848. 'task_id' => $taskId,
  849. 'error' => $e->getMessage()
  850. ];
  851. dLog('anime')->error('视频任务处理失败', $logData);
  852. logDB('anime', 'error', '视频任务处理失败', $logData);
  853. }
  854. } elseif ($statusResult['status'] === 'failed') {
  855. // 获取分镜ID并更新失败状态
  856. foreach ($segmentTasks as $segmentTask) {
  857. if ($segmentTask['task_id'] == $taskId) {
  858. DB::table('mp_episode_segments')
  859. ->where('segment_id', $segmentTask['segment_id'])
  860. ->update([
  861. 'video_task_status' => '失败',
  862. 'updated_at' => date('Y-m-d H:i:s')
  863. ]);
  864. break;
  865. }
  866. }
  867. }
  868. }
  869. }
  870. // 检查任务是否完成(成功或失败)
  871. if (in_array($task->status, ['success', 'failed'])) {
  872. $completeTasks[] = $taskId;
  873. $hasUpdate = true;
  874. if ($task->status === 'success') {
  875. $successTasks[] = $taskId;
  876. }
  877. }
  878. }
  879. // 如果有更新,发送update通知
  880. if ($hasUpdate) {
  881. echo "data: " . json_encode([
  882. 'type' => 'update',
  883. 'total_tasks_count' => count($totalTasks),
  884. 'completed_tasks_count' => count($completeTasks),
  885. 'success_tasks_count' => count($successTasks)
  886. ]) . "\n\n";
  887. ob_flush();
  888. flush();
  889. }
  890. // 如果所有任务都完成了,结束连接
  891. if (count($completeTasks) >= count($totalTasks)) {
  892. // 获取所有成功任务的分镜信息
  893. $successSegments = [];
  894. foreach ($successTasks as $taskId) {
  895. // 通过taskId找到对应的segmentTask
  896. foreach ($segmentTasks as $segmentTask) {
  897. if ($segmentTask['task_id'] == $taskId) {
  898. $segment = DB::table('mp_episode_segments')
  899. ->where('segment_id', $segmentTask['segment_id'])
  900. ->select('segment_id', 'video_url')
  901. ->first();
  902. if ($segment && !empty($segment->video_url)) {
  903. $successSegments[] = [
  904. 'segment_id' => $segment->segment_id,
  905. 'video_url' => $segment->video_url
  906. ];
  907. }
  908. break;
  909. }
  910. }
  911. }
  912. echo "data: " . json_encode([
  913. 'type' => 'completed',
  914. 'total_tasks_count' => count($totalTasks),
  915. 'completed_tasks_count' => count($completeTasks),
  916. 'success_tasks_count' => count($successTasks),
  917. 'success_segments' => $successSegments
  918. ]) . "\n\n";
  919. ob_flush();
  920. flush();
  921. break;
  922. }
  923. // 检查是否超时
  924. if (time() - $startTime >= $maxDuration) {
  925. break;
  926. }
  927. sleep($checkInterval);
  928. } catch (\Exception $e) {
  929. echo "data: " . json_encode([
  930. 'type' => 'error',
  931. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  932. 'total_tasks_count' => count($totalTasks),
  933. 'completed_tasks_count' => count($completeTasks),
  934. 'success_tasks_count' => count($successTasks)
  935. ]) . "\n\n";
  936. ob_flush();
  937. flush();
  938. // 检查是否超时,如果超时则停止循环
  939. if (time() - $startTime >= $maxDuration) {
  940. break;
  941. }
  942. sleep($checkInterval);
  943. }
  944. }
  945. // 超时处理
  946. if (time() - $startTime >= $maxDuration) {
  947. echo "data: " . json_encode([
  948. 'type' => 'time_out',
  949. 'message' => '批量视频生成已超时30分钟,停止状态查询',
  950. 'total_tasks_count' => count($totalTasks),
  951. 'completed_tasks_count' => count($completeTasks),
  952. 'success_tasks_count' => count($successTasks)
  953. ]) . "\n\n";
  954. ob_flush();
  955. flush();
  956. }
  957. }, 200, [
  958. 'Content-Type' => 'text/event-stream',
  959. 'Cache-Control' => 'no-cache',
  960. 'Connection' => 'keep-alive',
  961. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  962. ]);
  963. }
  964. // 应用有声制作参数
  965. public function applyAudioData(Request $request) {
  966. $data = $request->all();
  967. $result = $this->AnimeService->applyAudioData($data);
  968. return $this->success($result);
  969. }
  970. // 获取分集生成图片信息
  971. public function episodePicsInfo(Request $request) {
  972. // 忽略所有超时限制
  973. set_time_limit(0);
  974. ini_set('max_execution_time', '0');
  975. $data = $request->all();
  976. // 获取生成器函数
  977. $streamGenerator = $this->AnimeService->episodePicsInfo($data);
  978. // 返回 SSE 响应
  979. return response()->stream($streamGenerator, 200, [
  980. 'Content-Type' => 'text/event-stream',
  981. 'Cache-Control' => 'no-cache',
  982. 'Connection' => 'keep-alive',
  983. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  984. ]);
  985. }
  986. public function clipSegmentVideo(Request $request) {
  987. $data = $request->all();
  988. $result = $this->AnimeService->clipSegmentVideo($data);
  989. return $this->success(['success'=>$result ? 1: 0]);
  990. }
  991. /**
  992. * 创建完整视频合成任务
  993. *
  994. * @param Request $request
  995. * @return \Illuminate\Http\JsonResponse
  996. */
  997. public function createCompleteVideoTask(Request $request)
  998. {
  999. // 忽略所有超时限制
  1000. set_time_limit(0);
  1001. ini_set('max_execution_time', '0');
  1002. $data = $request->all();
  1003. // 验证参数
  1004. $validator = Validator::make($data, [
  1005. 'anime_id' => 'required|string',
  1006. 'episode_id' => 'required|string',
  1007. ], [
  1008. 'anime_id.required' => '请选择动漫',
  1009. 'episode_id.required' => '请选择分集',
  1010. ]);
  1011. if ($validator->fails()) {
  1012. Utils::throwError('1002:' . $validator->errors()->first());
  1013. }
  1014. try {
  1015. $result = $this->AnimeService->createCompleteVideoTask($data);
  1016. return $this->success($result);
  1017. } catch (\Exception $e) {
  1018. $logData = [
  1019. 'anime_id' => $data['anime_id'] ?? '',
  1020. 'episode_id' => $data['episode_id'] ?? '',
  1021. 'error' => $e->getMessage()
  1022. ];
  1023. dLog('anime')->error('创建完整视频合成任务失败', $logData);
  1024. logDB('anime', 'error', '创建完整视频合成任务失败', $logData);
  1025. return $this->error('20003:'.$e->getMessage());
  1026. }
  1027. }
  1028. // 文生图(通用)
  1029. public function generateImg(Request $request) {
  1030. $data = $request->all();
  1031. $result = $this->AnimeService->generateImg($data);
  1032. return $this->success($result);
  1033. }
  1034. /**
  1035. * 导出分集的全部图片(下载并打包)
  1036. */
  1037. public function exportEpisodeImages(Request $request) {
  1038. // 忽略所有超时限制
  1039. set_time_limit(0);
  1040. ini_set('max_execution_time', '0');
  1041. ini_set('memory_limit', '512M');
  1042. $data = $request->all();
  1043. // 验证参数
  1044. $validator = Validator::make($data, [
  1045. 'anime_id' => 'required|string',
  1046. 'episode_id' => 'required|string',
  1047. ], [
  1048. 'anime_id.required' => '动漫ID不能为空',
  1049. 'episode_id.required' => '剧集ID不能为空',
  1050. ]);
  1051. if ($validator->fails()) {
  1052. Utils::throwError('1002:' . $validator->errors()->first());
  1053. }
  1054. $animeId = $data['anime_id'];
  1055. $episodeId = $data['episode_id'];
  1056. try {
  1057. // 获取剧集信息
  1058. $episode = DB::table('mp_anime_episodes')
  1059. ->where('anime_id', $animeId)
  1060. ->where('id', $episodeId)
  1061. ->select('episode_number', 'title')
  1062. ->first();
  1063. if (!$episode) {
  1064. Utils::throwError('20003:未找到剧集信息');
  1065. }
  1066. // 获取所有分镜图片和音频
  1067. $segments = DB::table('mp_episode_segments')
  1068. ->where('anime_id', $animeId)
  1069. ->where('episode_id', $episodeId)
  1070. ->whereNotNull('img_url')
  1071. ->where('img_url', '!=', '')
  1072. ->orderBy('segment_number')
  1073. ->select('segment_id', 'segment_number', 'img_url', 'audio_url', 'act_number', 'act_title')
  1074. ->get();
  1075. if ($segments->isEmpty()) {
  1076. Utils::throwError('20003:该剧集暂无图片可导出');
  1077. }
  1078. // 创建临时目录
  1079. $tempDir = storage_path('app/temp/episode_images_' . time() . '_' . mt_rand(1000, 9999));
  1080. if (!file_exists($tempDir)) {
  1081. mkdir($tempDir, 0755, true);
  1082. }
  1083. // 下载图片或视频
  1084. $downloadedFiles = [];
  1085. foreach ($segments as $segment) {
  1086. try {
  1087. // 优先使用video_url,如果没有则使用img_url
  1088. $mediaUrl = !empty($segment->video_url) ? $segment->video_url : $segment->img_url;
  1089. if (empty($mediaUrl)) {
  1090. continue;
  1091. }
  1092. // 获取文件扩展名
  1093. $extension = pathinfo(parse_url($mediaUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
  1094. if (empty($extension)) {
  1095. // 根据URL类型设置默认扩展名
  1096. $extension = !empty($segment->video_url) ? 'mp4' : 'jpg';
  1097. }
  1098. // 构建文件名:分镜序号.扩展名
  1099. $fileName = sprintf(
  1100. '%03d.%s',
  1101. $segment->segment_number,
  1102. $extension
  1103. );
  1104. $filePath = $tempDir . '/' . $fileName;
  1105. // 下载文件(使用file_get_contents,兼容性更好)
  1106. $context = stream_context_create([
  1107. 'http' => [
  1108. 'timeout' => 30,
  1109. 'follow_location' => 1,
  1110. 'ignore_errors' => true
  1111. ],
  1112. 'ssl' => [
  1113. 'verify_peer' => false,
  1114. 'verify_peer_name' => false
  1115. ]
  1116. ]);
  1117. $fileData = @file_get_contents($mediaUrl, false, $context);
  1118. if ($fileData !== false && !empty($fileData)) {
  1119. file_put_contents($filePath, $fileData);
  1120. $downloadedFiles[] = $filePath;
  1121. } else {
  1122. $logData = [
  1123. 'segment_id' => $segment->segment_id,
  1124. 'media_url' => $mediaUrl,
  1125. 'type' => !empty($segment->video_url) ? 'video' : 'image'
  1126. ];
  1127. dLog('anime')->warning('文件下载失败', $logData);
  1128. logDB('anime', 'warning', '文件下载失败', $logData);
  1129. }
  1130. } catch (\Exception $e) {
  1131. $logData = [
  1132. 'segment_id' => $segment->segment_id,
  1133. 'video_url' => $segment->video_url,
  1134. 'img_url' => $segment->img_url,
  1135. 'error' => $e->getMessage()
  1136. ];
  1137. dLog('anime')->error('下载文件异常', $logData);
  1138. logDB('anime', 'error', '下载文件异常', $logData);
  1139. continue;
  1140. }
  1141. }
  1142. if (empty($downloadedFiles)) {
  1143. // 清理临时目录
  1144. if (file_exists($tempDir)) {
  1145. array_map('unlink', glob("$tempDir/*"));
  1146. rmdir($tempDir);
  1147. }
  1148. Utils::throwError('20003:没有成功下载任何图片');
  1149. }
  1150. // 处理音频合成
  1151. $mergedAudioPath = null;
  1152. try {
  1153. // 检查 FFmpeg 是否可用
  1154. exec('which ffmpeg 2>&1', $ffmpegCheck, $ffmpegReturnCode);
  1155. $hasFfmpeg = ($ffmpegReturnCode === 0);
  1156. if ($hasFfmpeg) {
  1157. // 下载所有分镜的音频文件
  1158. $audioFiles = [];
  1159. foreach ($segments as $segment) {
  1160. if (!empty($segment->audio_url)) {
  1161. try {
  1162. $context = stream_context_create([
  1163. 'http' => [
  1164. 'timeout' => 30,
  1165. 'follow_location' => 1,
  1166. 'ignore_errors' => true
  1167. ],
  1168. 'ssl' => [
  1169. 'verify_peer' => false,
  1170. 'verify_peer_name' => false
  1171. ]
  1172. ]);
  1173. $audioData = @file_get_contents($segment->audio_url, false, $context);
  1174. if ($audioData !== false && !empty($audioData)) {
  1175. // 获取音频文件扩展名
  1176. $audioExtension = pathinfo(parse_url($segment->audio_url, PHP_URL_PATH), PATHINFO_EXTENSION);
  1177. if (empty($audioExtension)) {
  1178. $audioExtension = 'wav';
  1179. }
  1180. $audioFileName = sprintf('audio_%03d.%s', $segment->segment_number, $audioExtension);
  1181. $audioFilePath = $tempDir . '/' . $audioFileName;
  1182. file_put_contents($audioFilePath, $audioData);
  1183. $audioFiles[] = $audioFilePath;
  1184. } else {
  1185. $logData = [
  1186. 'segment_id' => $segment->segment_id,
  1187. 'audio_url' => $segment->audio_url
  1188. ];
  1189. dLog('anime')->warning('音频下载失败', $logData);
  1190. logDB('anime', 'warning', '音频下载失败', $logData);
  1191. }
  1192. } catch (\Exception $e) {
  1193. $logData = [
  1194. 'segment_id' => $segment->segment_id,
  1195. 'audio_url' => $segment->audio_url,
  1196. 'error' => $e->getMessage()
  1197. ];
  1198. dLog('anime')->error('下载音频异常', $logData);
  1199. logDB('anime', 'error', '下载音频异常', $logData);
  1200. }
  1201. }
  1202. }
  1203. // 如果有音频文件,则进行合成
  1204. if (!empty($audioFiles)) {
  1205. // 创建 FFmpeg concat 文件列表
  1206. $concatFile = $tempDir . '/concat.txt';
  1207. $concatContent = '';
  1208. foreach ($audioFiles as $audioFile) {
  1209. // 使用相对路径,避免路径中的特殊字符问题
  1210. $concatContent .= "file '" . basename($audioFile) . "'\n";
  1211. }
  1212. file_put_contents($concatFile, $concatContent);
  1213. // 合成音频文件
  1214. $mergedAudioPath = $tempDir . '/tts.wav';
  1215. // 使用 FFmpeg 合并音频,转换为统一的 WAV 格式
  1216. $ffmpegCommand = sprintf(
  1217. 'cd %s && ffmpeg -f concat -safe 0 -i %s -ar 44100 -ac 2 -y %s 2>&1',
  1218. escapeshellarg($tempDir),
  1219. escapeshellarg(basename($concatFile)),
  1220. escapeshellarg(basename($mergedAudioPath))
  1221. );
  1222. exec($ffmpegCommand, $ffmpegOutput, $ffmpegReturnCode);
  1223. if ($ffmpegReturnCode !== 0 || !file_exists($mergedAudioPath)) {
  1224. $logData = [
  1225. 'command' => $ffmpegCommand,
  1226. 'output' => implode("\n", $ffmpegOutput),
  1227. 'return_code' => $ffmpegReturnCode
  1228. ];
  1229. dLog('anime')->error('FFmpeg 合成音频失败', $logData);
  1230. logDB('anime', 'error', 'FFmpeg 合成音频失败', $logData);
  1231. $mergedAudioPath = null;
  1232. } else {
  1233. $logData = [
  1234. 'audio_count' => count($audioFiles),
  1235. 'output_file' => $mergedAudioPath,
  1236. 'file_size' => filesize($mergedAudioPath)
  1237. ];
  1238. dLog('anime')->info('音频合成成功', $logData);
  1239. logDB('anime', 'info', '音频合成成功', $logData);
  1240. }
  1241. // 清理临时音频文件和 concat 文件
  1242. foreach ($audioFiles as $audioFile) {
  1243. if (file_exists($audioFile)) {
  1244. @unlink($audioFile);
  1245. }
  1246. }
  1247. if (file_exists($concatFile)) {
  1248. @unlink($concatFile);
  1249. }
  1250. }
  1251. } else {
  1252. dLog('anime')->warning('FFmpeg 未安装,跳过音频合成');
  1253. logDB('anime', 'warning', 'FFmpeg 未安装,跳过音频合成', []);
  1254. }
  1255. } catch (\Exception $e) {
  1256. $logData = [
  1257. 'error' => $e->getMessage(),
  1258. 'trace' => $e->getTraceAsString()
  1259. ];
  1260. dLog('anime')->error('音频合成过程异常', $logData);
  1261. logDB('anime', 'error', '音频合成过程异常', $logData);
  1262. // 音频合成失败不影响图片导出
  1263. $mergedAudioPath = null;
  1264. }
  1265. // 创建zip文件
  1266. $zipFileName = sprintf(
  1267. '%s.zip',
  1268. $episode->title ?: '未命名'
  1269. );
  1270. $zipFilePath = storage_path('app/temp/' . $zipFileName);
  1271. $zip = new \ZipArchive();
  1272. if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
  1273. // 清理临时文件
  1274. array_map('unlink', $downloadedFiles);
  1275. rmdir($tempDir);
  1276. Utils::throwError('20003:创建ZIP文件失败');
  1277. }
  1278. // 添加图片文件到zip
  1279. foreach ($downloadedFiles as $file) {
  1280. $zip->addFile($file, basename($file));
  1281. }
  1282. // 添加合成的音频文件到zip
  1283. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1284. $zip->addFile($mergedAudioPath, 'tts.wav');
  1285. }
  1286. $zip->close();
  1287. // 清理临时图片文件
  1288. array_map('unlink', $downloadedFiles);
  1289. // 清理合成的音频文件
  1290. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1291. @unlink($mergedAudioPath);
  1292. }
  1293. rmdir($tempDir);
  1294. // 返回文件下载响应
  1295. return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
  1296. } catch (\Exception $e) {
  1297. $logData = [
  1298. 'anime_id' => $animeId,
  1299. 'episode_id' => $episodeId,
  1300. 'error' => $e->getMessage()
  1301. ];
  1302. dLog('anime')->error('导出分集图片失败', $logData);
  1303. logDB('anime', 'error', '导出分集图片失败', $logData);
  1304. // 清理可能存在的临时文件
  1305. if (isset($tempDir) && file_exists($tempDir)) {
  1306. array_map('unlink', glob("$tempDir/*"));
  1307. rmdir($tempDir);
  1308. }
  1309. if (isset($zipFilePath) && file_exists($zipFilePath)) {
  1310. unlink($zipFilePath);
  1311. }
  1312. throw $e;
  1313. }
  1314. }
  1315. /**
  1316. * 监控分镜图片和音频生成任务进度(SSE)
  1317. */
  1318. public function monitorSegmentTasks(Request $request) {
  1319. // 忽略所有超时限制
  1320. set_time_limit(0);
  1321. ini_set('max_execution_time', '0');
  1322. $data = $request->all();
  1323. // 验证参数
  1324. $validator = Validator::make($data, [
  1325. 'anime_id' => 'required|string',
  1326. 'episode_id' => 'required|string',
  1327. ], [
  1328. 'anime_id.required' => '动漫ID不能为空',
  1329. 'episode_id.required' => '剧集ID不能为空',
  1330. ]);
  1331. if ($validator->fails()) {
  1332. Utils::throwError('1002:' . $validator->errors()->first());
  1333. }
  1334. $animeId = $data['anime_id'];
  1335. $episodeId = $data['episode_id'];
  1336. // 查询没有pic_task_id的分镜个数
  1337. $noPicTaskCount = DB::table('mp_episode_segments')
  1338. ->where('anime_id', $animeId)
  1339. ->where('episode_id', $episodeId)
  1340. ->where(function($query) {
  1341. $query->whereNull('pic_task_id')
  1342. ->orWhere('pic_task_id', '');
  1343. })
  1344. ->count('id');
  1345. // 获取所有分镜信息
  1346. $segments = DB::table('mp_episode_segments')
  1347. ->where('anime_id', $animeId)
  1348. ->where('episode_id', $episodeId)
  1349. ->where('pic_task_id', '!=', '')
  1350. ->orderBy('segment_number')
  1351. ->select('segment_id', 'segment_number', 'pic_task_id', 'pic_task_status', 'img_url', 'audio_url', 'dialogue', 'voice_type')
  1352. ->get();
  1353. // 判断是否有未完成的任务
  1354. $uncompleted_pic_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)
  1355. ->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->whereNotIn('pic_task_status', ['已完成', '失败'])->count('id');
  1356. // 获取dialogue和voice_type存在但audio_url不存在的分镜个数
  1357. $uncompleted_audio_count = DB::table('mp_episode_segments')
  1358. ->where('anime_id', $animeId)
  1359. ->where('episode_id', $episodeId)
  1360. ->where('dialogue', '<>', '')
  1361. ->whereNotNull('dialogue')
  1362. ->where('voice_type', '<>', '')
  1363. ->whereNotNull('voice_type')
  1364. ->where(function($query) {
  1365. $query->whereNull('audio_url')
  1366. ->orWhere('audio_url', '');
  1367. })
  1368. ->count('id');
  1369. if ($segments->isEmpty()) {
  1370. Utils::throwError('20003:未找到分镜任务数据');
  1371. }
  1372. $startTime = time();
  1373. $maxDuration = 900; // 15分钟超时
  1374. $checkInterval = 5; // 每5秒检查一次
  1375. // 设置 SSE 响应头并开始长连接
  1376. return response()->stream(function () use ($segments, $animeId, $episodeId, $startTime, $maxDuration, $checkInterval, $uncompleted_pic_count, $uncompleted_audio_count, $noPicTaskCount) {
  1377. if ($uncompleted_pic_count == 0 && $uncompleted_audio_count == 0) {
  1378. $completedCount = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->where('pic_task_status', '已完成')->count('id');
  1379. // 获取剧集信息
  1380. $episode = DB::table('mp_anime_episodes')
  1381. ->where('anime_id', $animeId)
  1382. ->where('id', $episodeId)
  1383. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1384. ->first();
  1385. if ($episode) {
  1386. $episode = (array)$episode;
  1387. $episode['roles'] = json_decode($episode['roles'], true);
  1388. $episode['scenes'] = json_decode($episode['scenes'], true);
  1389. // 获取所有分镜信息
  1390. $allSegments = DB::table('mp_episode_segments')
  1391. ->where('anime_id', $animeId)
  1392. ->where('episode_id', $episodeId)
  1393. ->orderBy('segment_number')
  1394. ->select('*')
  1395. ->get()
  1396. ->map(function ($value) {
  1397. return (array)$value;
  1398. })->toArray();
  1399. // 按照episodeInfo的格式组织数据
  1400. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1401. $episode['acts'] = $segmentsStructure['acts'];
  1402. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1403. }
  1404. echo "data: " . json_encode([
  1405. 'type' => 'completed',
  1406. 'data' => [
  1407. 'anime_id' => $animeId,
  1408. 'episode_id' => $episodeId,
  1409. 'completed_count' => $completedCount, // 成功完成的数量
  1410. 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1411. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1412. 'total_elapsed_time' => time() - $startTime,
  1413. 'episode_info' => $episode ?? null
  1414. ]
  1415. ]) . "\n\n";
  1416. ob_flush();
  1417. flush();
  1418. return;
  1419. }
  1420. // 发送初始任务信息
  1421. echo "data: " . json_encode([
  1422. 'type' => 'init',
  1423. 'data' => [
  1424. 'anime_id' => $animeId,
  1425. 'episode_id' => $episodeId,
  1426. 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1427. 'start_time' => $startTime,
  1428. 'max_duration' => $maxDuration
  1429. ]
  1430. ]) . "\n\n";
  1431. ob_flush();
  1432. flush();
  1433. $completedSegments = [];
  1434. $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
  1435. $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
  1436. while (time() - $startTime < $maxDuration) {
  1437. try {
  1438. $updatedImages = []; // 记录本次循环中更新的图片信息
  1439. foreach ($segments as $segment) {
  1440. $segmentId = $segment->segment_id;
  1441. $picTaskId = $segment->pic_task_id;
  1442. $audioUrl = $segment->audio_url;
  1443. // 跳过已处理完成的分镜
  1444. if (in_array($segmentId, $processedSegments)) {
  1445. continue;
  1446. }
  1447. $picCompleted = false;
  1448. $audioCompleted = false;
  1449. $picProcessed = false;
  1450. $audioProcessed = false;
  1451. // 检查图片任务状态
  1452. if ($picTaskId) {
  1453. $picTask = DB::table('mp_generate_pic_tasks')
  1454. ->where('id', $picTaskId)
  1455. ->select('status', 'result_url', 'error_message')
  1456. ->first();
  1457. if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
  1458. $updateData = [
  1459. 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
  1460. 'updated_at' => date('Y-m-d H:i:s')
  1461. ];
  1462. $imgUrl = '';
  1463. if ($picTask->status === 'success' && !empty($picTask->result_url)) {
  1464. // 更新分镜表的图片URL
  1465. $resultUrls = json_decode($picTask->result_url, true);
  1466. $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
  1467. $updateData['img_url'] = $imgUrl;
  1468. $picCompleted = true;
  1469. } else if ($picTask->status === 'failed') {
  1470. // 失败时清空图片URL
  1471. $updateData['img_url'] = '';
  1472. }
  1473. DB::table('mp_episode_segments')
  1474. ->where('segment_id', $segmentId)
  1475. ->update($updateData);
  1476. // 记录更新的图片信息(只有未通知过的才记录)
  1477. if (!in_array($segmentId, $notifiedSegments)) {
  1478. $updatedImages[] = [
  1479. 'segment_id' => $segmentId,
  1480. 'segment_number' => $segment->segment_number,
  1481. 'img_url' => $imgUrl,
  1482. 'status' => $picTask->status === 'success' ? 'success' : 'failed'
  1483. ];
  1484. // 标记为已通知
  1485. $notifiedSegments[] = $segmentId;
  1486. }
  1487. $picProcessed = true;
  1488. }
  1489. }
  1490. // 检查音频状态
  1491. // 获取分镜的dialogue、voice_type和audio_url信息
  1492. $segmentInfo = DB::table('mp_episode_segments')
  1493. ->where('segment_id', $segmentId)
  1494. ->select('dialogue', 'voice_type', 'audio_url')
  1495. ->first();
  1496. $needAudio = false;
  1497. $currentAudioUrl = '';
  1498. if ($segmentInfo) {
  1499. $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
  1500. $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
  1501. $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
  1502. // 如果有对话和音色类型,则需要音频
  1503. if (!empty($dialogue) && !empty($voiceType)) {
  1504. $needAudio = true;
  1505. }
  1506. }
  1507. // 判断音频状态
  1508. if ($needAudio) {
  1509. // 需要音频的情况下,检查audio_url是否有值
  1510. if (!empty($currentAudioUrl)) {
  1511. $audioCompleted = true;
  1512. $audioProcessed = true;
  1513. } else {
  1514. // 需要音频但还没有,继续等待
  1515. $audioCompleted = false;
  1516. $audioProcessed = false;
  1517. }
  1518. } else {
  1519. // 不需要音频,直接标记为已处理
  1520. $audioCompleted = false;
  1521. $audioProcessed = true;
  1522. }
  1523. // 如果图片和音频都成功完成,标记为已完成
  1524. if ($picCompleted && ($audioCompleted || !$needAudio)) {
  1525. $completedSegments[] = $segmentId;
  1526. }
  1527. // 如果图片和音频都已处理完成(成功或失败),标记为已处理
  1528. if ($picProcessed && $audioProcessed) {
  1529. $processedSegments[] = $segmentId;
  1530. }
  1531. }
  1532. // 如果有图片更新,发送具体的图片更新信息
  1533. if (!empty($updatedImages)) {
  1534. echo "data: " . json_encode([
  1535. 'type' => 'update',
  1536. 'data' => [
  1537. 'anime_id' => $animeId,
  1538. 'episode_id' => $episodeId,
  1539. 'updated_images' => $updatedImages,
  1540. 'completed_count' => count($completedSegments), // 成功完成的数量
  1541. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1542. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1543. 'elapsed_time' => time() - $startTime,
  1544. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1545. ]
  1546. ]) . "\n\n";
  1547. ob_flush();
  1548. flush();
  1549. }
  1550. // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
  1551. if (count($processedSegments) === count($segments)) {
  1552. // 获取剧集信息
  1553. $episode = DB::table('mp_anime_episodes')
  1554. ->where('anime_id', $animeId)
  1555. ->where('id', $episodeId)
  1556. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1557. ->first();
  1558. if ($episode) {
  1559. $episode = (array)$episode;
  1560. $episode['roles'] = json_decode($episode['roles'], true);
  1561. $episode['scenes'] = json_decode($episode['scenes'], true);
  1562. // 获取所有分镜信息
  1563. $allSegments = DB::table('mp_episode_segments')
  1564. ->where('anime_id', $animeId)
  1565. ->where('episode_id', $episodeId)
  1566. ->orderBy('segment_number')
  1567. ->select('*')
  1568. ->get()
  1569. ->map(function ($value) {
  1570. return (array)$value;
  1571. })->toArray();
  1572. // 按照episodeInfo的格式组织数据
  1573. $acts = [];
  1574. foreach($allSegments as $segment) {
  1575. $segmentData = [
  1576. 'segment_id' => getProp($segment, 'segment_id'),
  1577. 'segment_number' => getProp($segment, 'segment_number'),
  1578. 'segment_content' => getProp($segment, 'segment_content'),
  1579. 'description' => getProp($segment, 'description'),
  1580. 'composition' => getProp($segment, 'composition'),
  1581. 'camera_movement' => getProp($segment, 'camera_movement'),
  1582. 'voice_actor' => getProp($segment, 'voice_actor'),
  1583. 'dialogue' => getProp($segment, 'dialogue'),
  1584. 'frame_type' => getProp($segment, 'frame_type'),
  1585. 'scene' => getProp($segment, 'scene'),
  1586. 'characters' => getProp($segment, 'characters'),
  1587. 'tail_frame' => getProp($segment, 'tail_frame'),
  1588. 'emotion' => getProp($segment, 'emotion'),
  1589. 'emotion_type' => getProp($segment, 'emotion_type'),
  1590. 'gender' => getProp($segment, 'gender'),
  1591. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  1592. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  1593. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  1594. 'pitch' => getProp($segment, 'pitch'),
  1595. 'voice_name' => getProp($segment, 'voice_name'),
  1596. 'voice_type' => getProp($segment, 'voice_type'),
  1597. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  1598. 'img_url' => getProp($segment, 'img_url'),
  1599. 'audio_url' => getProp($segment, 'audio_url'),
  1600. 'video_url' => getProp($segment, 'video_url'),
  1601. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  1602. ];
  1603. $actNumber = getProp($segment, 'act_number');
  1604. if (isset($acts[$actNumber])) {
  1605. $acts[$actNumber]['segments'][] = $segmentData;
  1606. } else {
  1607. $acts[$actNumber] = [
  1608. 'act_number' => $actNumber,
  1609. 'act_title' => getProp($segment, 'act_title'),
  1610. 'segments' => [$segmentData]
  1611. ];
  1612. }
  1613. }
  1614. $episode['acts'] = array_values($acts);
  1615. }
  1616. echo "data: " . json_encode([
  1617. 'type' => 'completed',
  1618. 'data' => [
  1619. 'anime_id' => $animeId,
  1620. 'episode_id' => $episodeId,
  1621. 'completed_count' => count($completedSegments), // 成功完成的数量
  1622. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1623. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1624. 'total_elapsed_time' => time() - $startTime,
  1625. 'episode_info' => $episode ?? null
  1626. ]
  1627. ]) . "\n\n";
  1628. ob_flush();
  1629. flush();
  1630. break;
  1631. }
  1632. // 检查是否超时
  1633. if (time() - $startTime >= $maxDuration) {
  1634. break;
  1635. }
  1636. sleep($checkInterval);
  1637. } catch (\Exception $e) {
  1638. echo "data: " . json_encode([
  1639. 'type' => 'error',
  1640. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1641. 'elapsed_time' => time() - $startTime,
  1642. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1643. ]) . "\n\n";
  1644. ob_flush();
  1645. flush();
  1646. if (time() - $startTime >= $maxDuration) {
  1647. break;
  1648. }
  1649. sleep($checkInterval);
  1650. }
  1651. }
  1652. // 超时处理
  1653. if (time() - $startTime >= $maxDuration) {
  1654. echo "data: " . json_encode([
  1655. 'type' => 'time_out',
  1656. 'message' => '分镜任务监控已超时15分钟,停止状态查询',
  1657. 'data' => [
  1658. 'anime_id' => $animeId,
  1659. 'episode_id' => $episodeId,
  1660. 'completed_count' => count($completedSegments), // 成功完成的数量
  1661. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1662. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1663. 'total_elapsed_time' => time() - $startTime,
  1664. 'timeout_duration' => $maxDuration
  1665. ]
  1666. ]) . "\n\n";
  1667. ob_flush();
  1668. flush();
  1669. }
  1670. }, 200, [
  1671. 'Content-Type' => 'text/event-stream',
  1672. 'Cache-Control' => 'no-cache',
  1673. 'Connection' => 'keep-alive',
  1674. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1675. ]);
  1676. }
  1677. /**
  1678. * 音频试听接口
  1679. * 创建音频任务并返回结果
  1680. */
  1681. public function previewAudio(Request $request) {
  1682. $data = $request->all();
  1683. $result = $this->AnimeService->previewAudio($data);
  1684. return $this->success($result);
  1685. }
  1686. }