AnimeController.php 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  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. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1372. $episode['acts'] = $segmentsStructure['acts'];
  1373. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1374. }
  1375. echo "data: " . json_encode([
  1376. 'type' => 'completed',
  1377. 'data' => [
  1378. 'anime_id' => $animeId,
  1379. 'episode_id' => $episodeId,
  1380. 'completed_count' => $completedCount, // 成功完成的数量
  1381. 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1382. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1383. 'total_elapsed_time' => time() - $startTime,
  1384. 'episode_info' => $episode ?? null
  1385. ]
  1386. ]) . "\n\n";
  1387. ob_flush();
  1388. flush();
  1389. return;
  1390. }
  1391. // 发送初始任务信息
  1392. echo "data: " . json_encode([
  1393. 'type' => 'init',
  1394. 'data' => [
  1395. 'anime_id' => $animeId,
  1396. 'episode_id' => $episodeId,
  1397. 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1398. 'start_time' => $startTime,
  1399. 'max_duration' => $maxDuration
  1400. ]
  1401. ]) . "\n\n";
  1402. ob_flush();
  1403. flush();
  1404. $completedSegments = [];
  1405. $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
  1406. $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
  1407. while (time() - $startTime < $maxDuration) {
  1408. try {
  1409. $updatedImages = []; // 记录本次循环中更新的图片信息
  1410. foreach ($segments as $segment) {
  1411. $segmentId = $segment->segment_id;
  1412. $picTaskId = $segment->pic_task_id;
  1413. $audioUrl = $segment->audio_url;
  1414. // 跳过已处理完成的分镜
  1415. if (in_array($segmentId, $processedSegments)) {
  1416. continue;
  1417. }
  1418. $picCompleted = false;
  1419. $audioCompleted = false;
  1420. $picProcessed = false;
  1421. $audioProcessed = false;
  1422. // 检查图片任务状态
  1423. if ($picTaskId) {
  1424. $picTask = DB::table('mp_generate_pic_tasks')
  1425. ->where('id', $picTaskId)
  1426. ->select('status', 'result_url', 'error_message')
  1427. ->first();
  1428. if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
  1429. $updateData = [
  1430. 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
  1431. 'updated_at' => date('Y-m-d H:i:s')
  1432. ];
  1433. $imgUrl = '';
  1434. if ($picTask->status === 'success' && !empty($picTask->result_url)) {
  1435. // 更新分镜表的图片URL
  1436. $resultUrls = json_decode($picTask->result_url, true);
  1437. $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
  1438. $updateData['img_url'] = $imgUrl;
  1439. $picCompleted = true;
  1440. } else if ($picTask->status === 'failed') {
  1441. // 失败时清空图片URL
  1442. $updateData['img_url'] = '';
  1443. }
  1444. DB::table('mp_episode_segments')
  1445. ->where('segment_id', $segmentId)
  1446. ->update($updateData);
  1447. // 记录更新的图片信息(只有未通知过的才记录)
  1448. if (!in_array($segmentId, $notifiedSegments)) {
  1449. $updatedImages[] = [
  1450. 'segment_id' => $segmentId,
  1451. 'segment_number' => $segment->segment_number,
  1452. 'img_url' => $imgUrl,
  1453. 'status' => $picTask->status === 'success' ? 'success' : 'failed'
  1454. ];
  1455. // 标记为已通知
  1456. $notifiedSegments[] = $segmentId;
  1457. }
  1458. $picProcessed = true;
  1459. }
  1460. }
  1461. // 检查音频状态
  1462. // 获取分镜的dialogue、voice_type和audio_url信息
  1463. $segmentInfo = DB::table('mp_episode_segments')
  1464. ->where('segment_id', $segmentId)
  1465. ->select('dialogue', 'voice_type', 'audio_url')
  1466. ->first();
  1467. $needAudio = false;
  1468. $currentAudioUrl = '';
  1469. if ($segmentInfo) {
  1470. $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
  1471. $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
  1472. $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
  1473. // 如果有对话和音色类型,则需要音频
  1474. if (!empty($dialogue) && !empty($voiceType)) {
  1475. $needAudio = true;
  1476. }
  1477. }
  1478. // 判断音频状态
  1479. if ($needAudio) {
  1480. // 需要音频的情况下,检查audio_url是否有值
  1481. if (!empty($currentAudioUrl)) {
  1482. $audioCompleted = true;
  1483. $audioProcessed = true;
  1484. } else {
  1485. // 需要音频但还没有,继续等待
  1486. $audioCompleted = false;
  1487. $audioProcessed = false;
  1488. }
  1489. } else {
  1490. // 不需要音频,直接标记为已处理
  1491. $audioCompleted = false;
  1492. $audioProcessed = true;
  1493. }
  1494. // 如果图片和音频都成功完成,标记为已完成
  1495. if ($picCompleted && ($audioCompleted || !$needAudio)) {
  1496. $completedSegments[] = $segmentId;
  1497. }
  1498. // 如果图片和音频都已处理完成(成功或失败),标记为已处理
  1499. if ($picProcessed && $audioProcessed) {
  1500. $processedSegments[] = $segmentId;
  1501. }
  1502. }
  1503. // 如果有图片更新,发送具体的图片更新信息
  1504. if (!empty($updatedImages)) {
  1505. echo "data: " . json_encode([
  1506. 'type' => 'update',
  1507. 'data' => [
  1508. 'anime_id' => $animeId,
  1509. 'episode_id' => $episodeId,
  1510. 'updated_images' => $updatedImages,
  1511. 'completed_count' => count($completedSegments), // 成功完成的数量
  1512. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1513. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1514. 'elapsed_time' => time() - $startTime,
  1515. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1516. ]
  1517. ]) . "\n\n";
  1518. ob_flush();
  1519. flush();
  1520. }
  1521. // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
  1522. if (count($processedSegments) === count($segments)) {
  1523. // 获取剧集信息
  1524. $episode = DB::table('mp_anime_episodes')
  1525. ->where('anime_id', $animeId)
  1526. ->where('id', $episodeId)
  1527. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1528. ->first();
  1529. if ($episode) {
  1530. $episode = (array)$episode;
  1531. $episode['roles'] = json_decode($episode['roles'], true);
  1532. $episode['scenes'] = json_decode($episode['scenes'], true);
  1533. // 获取所有分镜信息
  1534. $allSegments = DB::table('mp_episode_segments')
  1535. ->where('anime_id', $animeId)
  1536. ->where('episode_id', $episodeId)
  1537. ->orderBy('segment_number')
  1538. ->select('*')
  1539. ->get()
  1540. ->map(function ($value) {
  1541. return (array)$value;
  1542. })->toArray();
  1543. // 按照episodeInfo的格式组织数据
  1544. $acts = [];
  1545. foreach($allSegments as $segment) {
  1546. $segmentData = [
  1547. 'segment_id' => getProp($segment, 'segment_id'),
  1548. 'segment_number' => getProp($segment, 'segment_number'),
  1549. 'segment_content' => getProp($segment, 'segment_content'),
  1550. 'description' => getProp($segment, 'description'),
  1551. 'composition' => getProp($segment, 'composition'),
  1552. 'camera_movement' => getProp($segment, 'camera_movement'),
  1553. 'voice_actor' => getProp($segment, 'voice_actor'),
  1554. 'dialogue' => getProp($segment, 'dialogue'),
  1555. 'frame_type' => getProp($segment, 'frame_type'),
  1556. 'scene' => getProp($segment, 'scene'),
  1557. 'characters' => getProp($segment, 'characters'),
  1558. 'tail_frame' => getProp($segment, 'tail_frame'),
  1559. 'emotion' => getProp($segment, 'emotion'),
  1560. 'emotion_type' => getProp($segment, 'emotion_type'),
  1561. 'gender' => getProp($segment, 'gender'),
  1562. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  1563. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  1564. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  1565. 'pitch' => getProp($segment, 'pitch'),
  1566. 'voice_name' => getProp($segment, 'voice_name'),
  1567. 'voice_type' => getProp($segment, 'voice_type'),
  1568. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  1569. 'img_url' => getProp($segment, 'img_url'),
  1570. 'audio_url' => getProp($segment, 'audio_url'),
  1571. 'video_url' => getProp($segment, 'video_url'),
  1572. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  1573. ];
  1574. $actNumber = getProp($segment, 'act_number');
  1575. if (isset($acts[$actNumber])) {
  1576. $acts[$actNumber]['segments'][] = $segmentData;
  1577. } else {
  1578. $acts[$actNumber] = [
  1579. 'act_number' => $actNumber,
  1580. 'act_title' => getProp($segment, 'act_title'),
  1581. 'segments' => [$segmentData]
  1582. ];
  1583. }
  1584. }
  1585. $episode['acts'] = array_values($acts);
  1586. }
  1587. echo "data: " . json_encode([
  1588. 'type' => 'completed',
  1589. 'data' => [
  1590. 'anime_id' => $animeId,
  1591. 'episode_id' => $episodeId,
  1592. 'completed_count' => count($completedSegments), // 成功完成的数量
  1593. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1594. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1595. 'total_elapsed_time' => time() - $startTime,
  1596. 'episode_info' => $episode ?? null
  1597. ]
  1598. ]) . "\n\n";
  1599. ob_flush();
  1600. flush();
  1601. break;
  1602. }
  1603. // 检查是否超时
  1604. if (time() - $startTime >= $maxDuration) {
  1605. break;
  1606. }
  1607. sleep($checkInterval);
  1608. } catch (\Exception $e) {
  1609. echo "data: " . json_encode([
  1610. 'type' => 'error',
  1611. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1612. 'elapsed_time' => time() - $startTime,
  1613. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1614. ]) . "\n\n";
  1615. ob_flush();
  1616. flush();
  1617. if (time() - $startTime >= $maxDuration) {
  1618. break;
  1619. }
  1620. sleep($checkInterval);
  1621. }
  1622. }
  1623. // 超时处理
  1624. if (time() - $startTime >= $maxDuration) {
  1625. echo "data: " . json_encode([
  1626. 'type' => 'time_out',
  1627. 'message' => '分镜任务监控已超时15分钟,停止状态查询',
  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. 'timeout_duration' => $maxDuration
  1636. ]
  1637. ]) . "\n\n";
  1638. ob_flush();
  1639. flush();
  1640. }
  1641. }, 200, [
  1642. 'Content-Type' => 'text/event-stream',
  1643. 'Cache-Control' => 'no-cache',
  1644. 'Connection' => 'keep-alive',
  1645. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1646. ]);
  1647. }
  1648. /**
  1649. * 音频试听接口
  1650. * 创建音频任务并返回结果
  1651. */
  1652. public function previewAudio(Request $request) {
  1653. $data = $request->all();
  1654. $result = $this->AnimeService->previewAudio($data);
  1655. return $this->success($result);
  1656. }
  1657. }