AnimeController.php 87 KB

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