AnimeController.php 87 KB

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