AnimeController.php 86 KB

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