AnimeController.php 88 KB

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