AnimeController.php 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  1. <?php
  2. namespace App\Http\Controllers\Anime;
  3. use App\Transformer\Anime\AnimeTransformer;
  4. use App\Facade\Site;
  5. use App\Consts\ErrorConst;
  6. use App\Exceptions\ApiException;
  7. use App\Libs\ApiResponse;
  8. use App\Libs\Utils;
  9. use App\Models\MpGenerateVideoTask;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\Anime\AnimeService;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Routing\Controller as BaseController;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Redis;
  17. use Illuminate\Support\Facades\Validator;
  18. class AnimeController extends BaseController
  19. {
  20. use ApiResponse;
  21. protected $AnimeService;
  22. protected $AIImageGenerationService;
  23. protected $AIVideoGenerationService;
  24. public function __construct(
  25. AnimeService $AnimeService,
  26. AIImageGenerationService $AIImageGenerationService,
  27. AIVideoGenerationService $AIVideoGenerationService
  28. ) {
  29. $this->AnimeService = $AnimeService;
  30. $this->AIImageGenerationService = $AIImageGenerationService;
  31. $this->AIVideoGenerationService = $AIVideoGenerationService;
  32. }
  33. // 文字模型
  34. public function textModel() {
  35. $query = DB::table('mp_text_models')->where('is_enabled', 1);
  36. // 支持 model 搜索
  37. if ($model = request('model')) {
  38. $query->where('model', 'like', "%{$model}%");
  39. }
  40. // 支持 name 搜索
  41. if ($name = request('name')) {
  42. $query->where('name', 'like', "%{$name}%");
  43. }
  44. $models = $query->select('model', 'name')->get()->map(function ($value) {
  45. return (array)$value;
  46. })->toArray();
  47. return $this->success($models);
  48. }
  49. // 图片模型
  50. public function imageModel() {
  51. $query = DB::table('mp_image_models')->where('is_enabled', 1);
  52. // 支持 model 搜索
  53. if ($model = request('model')) {
  54. $query->where('model', 'like', "%{$model}%");
  55. }
  56. // 支持 name 搜索
  57. if ($name = request('name')) {
  58. $query->where('name', 'like', "%{$name}%");
  59. }
  60. $models = $query->select('model', 'name')->get()->map(function ($value) {
  61. return (array)$value;
  62. })->toArray();
  63. return $this->success($models);
  64. }
  65. // 视频模型
  66. public function videoModel() {
  67. $query = DB::table('mp_video_models')->where('is_enabled', 1);
  68. // 支持 model 搜索
  69. if ($model = request('model')) {
  70. $query->where('model', 'like', "%{$model}%");
  71. }
  72. // 支持 name 搜索
  73. if ($name = request('name')) {
  74. $query->where('name', 'like', "%{$name}%");
  75. }
  76. $models = $query->select('model', 'name')->get()->map(function ($value) {
  77. return (array)$value;
  78. })->toArray();
  79. return $this->success($models);
  80. }
  81. public function artStyleList()
  82. {
  83. $result = [
  84. [
  85. 'art_style' => '日系动漫风格',
  86. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/日系动漫风格.jpg"
  87. ],
  88. [
  89. 'art_style' => '国漫风格',
  90. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/国漫风格.jpg"
  91. ],
  92. [
  93. 'art_style' => 'Q版卡通风格',
  94. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/Q版卡通风格.jpg"
  95. ],
  96. [
  97. 'art_style' => '简约扁平风格',
  98. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/简约扁平风格.jpg"
  99. ],
  100. [
  101. 'art_style' => '古风仙侠风格',
  102. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/古风仙侠风格.jpg"
  103. ],
  104. [
  105. 'art_style' => '武侠风格',
  106. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/武侠风格.jpg"
  107. ],
  108. [
  109. 'art_style' => '新中式水墨风格',
  110. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/新中式水墨风格.jpg"
  111. ],
  112. [
  113. 'art_style' => '写实插画风格',
  114. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/写实插画风格.jpg"
  115. ],
  116. [
  117. 'art_style' => '3D卡通风格',
  118. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/3D卡通风格.jpg"
  119. ],
  120. [
  121. 'art_style' => '条漫风格',
  122. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/条漫风格.jpg"
  123. ],
  124. [
  125. 'art_style' => '赛博朋克风格',
  126. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/赛博朋克风格.jpg"
  127. ],
  128. [
  129. 'art_style' => '暗黑悬疑风格',
  130. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/暗黑悬疑风格.jpg"
  131. ],
  132. [
  133. 'art_style' => '治愈清新风格',
  134. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/治愈清新风格.jpg"
  135. ],
  136. ];
  137. return $this->success($result);
  138. }
  139. // 新建动漫
  140. public function createAnime(Request $request) {
  141. $data = $request->all();
  142. $result = $this->AnimeService->createAnime($data);
  143. return $this->success(['anime_id' => $result]);
  144. }
  145. // 编辑动漫
  146. public function editAnime(Request $request) {
  147. $data = $request->all();
  148. $result = $this->AnimeService->editAnime($data);
  149. return $this->success(['success'=>$result ? 1 : 0]);
  150. }
  151. // 删除动漫
  152. public function delAnime(Request $request) {
  153. $data = $request->all();
  154. $result = $this->AnimeService->delAnime($data);
  155. return $this->success(['success'=>$result ? 1 : 0]);
  156. }
  157. // 批量生成主体图片
  158. public function batchSetRoleImg(Request $request) {
  159. // 忽略所有超时限制
  160. set_time_limit(0);
  161. ini_set('max_execution_time', '0');
  162. $data = $request->all();
  163. $result = $this->AnimeService->batchSetRoleImg($data);
  164. return $this->success($result);
  165. }
  166. // 批量生成场景图片
  167. public function batchSetSceneImg(Request $request) {
  168. // 忽略所有超时限制
  169. set_time_limit(0);
  170. ini_set('max_execution_time', '0');
  171. $data = $request->all();
  172. $result = $this->AnimeService->batchSetSceneImg($data);
  173. return $this->success($result);
  174. }
  175. // 修改分集主体列表
  176. public function changeEpisodeRoles(Request $request) {
  177. $data = $request->all();
  178. $result = $this->AnimeService->changeEpisodeRoles($data);
  179. return $this->success(['success'=>$result ? 1 : 0]);
  180. }
  181. // 修改分集场景列表
  182. public function changeEpisodeScenes(Request $request) {
  183. $data = $request->all();
  184. $result = $this->AnimeService->changeEpisodeScenes($data);
  185. return $this->success(['success'=>$result ? 1 : 0]);
  186. }
  187. // 编辑分镜剧本
  188. public function editSegment(Request $request) {
  189. $data = $request->all();
  190. $result = $this->AnimeService->editSegment($data);
  191. return $this->success(['success'=>$result ? 1 : 0]);
  192. }
  193. // 动漫对话列表
  194. public function chatList(Request $request) {
  195. $data = $request->all();
  196. $result = $this->AnimeService->chatList($data);
  197. return $this->success($result, [new AnimeTransformer(), 'newBuildChatList']);
  198. }
  199. // 动漫对话历史记录
  200. public function chatHistory(Request $request) {
  201. $data = $request->all();
  202. $result = $this->AnimeService->chatHistory($data);
  203. return $this->success($result);
  204. }
  205. // 动漫大纲
  206. public function animeDetail(Request $request) {
  207. $data = $request->all();
  208. $result = $this->AnimeService->animeDetail($data);
  209. return $this->success($result);
  210. }
  211. // 动漫剧集
  212. public function episodeInfo(Request $request) {
  213. $data = $request->all();
  214. $result = $this->AnimeService->episodeInfo($data);
  215. return $this->success($result);
  216. }
  217. // 分镜信息
  218. public function segmentInfo(Request $request) {
  219. $data = $request->all();
  220. $result = $this->AnimeService->segmentInfo($data);
  221. return $this->success($result);
  222. }
  223. // 复制剧集副本
  224. public function copyEpisodeVersion(Request $request) {
  225. $data = $request->all();
  226. $result = $this->AnimeService->copyEpisodeVersion($data);
  227. return $this->success($result);
  228. }
  229. // 剧集副本列表
  230. public function episodeVersions(Request $request) {
  231. $data = $request->all();
  232. $result = $this->AnimeService->episodeVersions($data);
  233. return $this->success($result);
  234. }
  235. // 绑定剧集副本
  236. public function bindEpisodeVersion(Request $request) {
  237. $data = $request->all();
  238. $result = $this->AnimeService->bindEpisodeVersion($data);
  239. return $this->success(['success' => $result ? 1 : 0]);
  240. }
  241. // 对话改图
  242. public function chatChangeImg(Request $request) {
  243. $data = $request->all();
  244. $result = $this->AnimeService->chatChangeImg($data);
  245. return $this->success(['img_url' => $result]);
  246. }
  247. public function segmentChatHistory(Request $request) {
  248. $data = $request->all();
  249. $result = $this->AnimeService->segmentChatHistory($data);
  250. return $this->success($result);
  251. }
  252. // 一键生成分镜
  253. public function batchSetSegmentPics(Request $request) {
  254. // 忽略所有超时限制
  255. set_time_limit(0);
  256. ini_set('max_execution_time', '0');
  257. $data = $request->all();
  258. $result = $this->AnimeService->batchSetSegmentPics($data);
  259. return $this->success($result);
  260. }
  261. // 重新生成分镜
  262. public function reGenerateSegment(Request $request) {
  263. // 忽略所有超时限制
  264. set_time_limit(0);
  265. ini_set('max_execution_time', '0');
  266. $data = $request->all();
  267. $result = $this->AnimeService->reGenerateSegment($data);
  268. return $this->success(['img_url'=>$result]);
  269. }
  270. // 添加分镜
  271. public function addSegment(Request $request) {
  272. // 忽略所有超时限制
  273. set_time_limit(0);
  274. ini_set('max_execution_time', '0');
  275. $data = $request->all();
  276. $result = $this->AnimeService->addSegment($data);
  277. return $this->success($result);
  278. }
  279. // 复制分镜
  280. public function copySegment(Request $request) {
  281. $data = $request->all();
  282. $result = $this->AnimeService->copySegment($data);
  283. return $this->success($result);
  284. }
  285. // 移动分镜
  286. public function moveSegment(Request $request) {
  287. $data = $request->all();
  288. $result = $this->AnimeService->moveSegment($data);
  289. return $this->success(['success'=>$result ? 1: 0]);
  290. }
  291. // 删除分镜
  292. public function delSegment(Request $request) {
  293. $data = $request->all();
  294. $result = $this->AnimeService->delSegment($data);
  295. return $this->success(['success'=>$result ? 1: 0]);
  296. }
  297. public function applySegment(Request $request) {
  298. $data = $request->all();
  299. $result = $this->AnimeService->applySegment($data);
  300. return $this->success(['success'=>$result ? 1: 0]);
  301. }
  302. // 分镜历史图片|视频
  303. public function segmentHistory(Request $request) {
  304. $data = $request->all();
  305. $result = $this->AnimeService->segmentHistory($data);
  306. return $this->success($result);
  307. }
  308. public function createSegmentVideoTask(Request $request) {
  309. $uid = Site::getUid();
  310. // 忽略所有超时限制
  311. set_time_limit(0);
  312. ini_set('max_execution_time', '0');
  313. $data = $request->all();
  314. // 验证参数
  315. $validator = Validator::make($data, [
  316. 'segment_id' => 'required|string',
  317. 'tail_frame' => 'nullable|string|max:500',
  318. ], [
  319. 'segment_id.required' => '分镜ID不能为空',
  320. 'tail_frame.max' => '尾帧描述不能超过500个字符',
  321. ]);
  322. if ($validator->fails()) {
  323. Utils::throwError('1002:' . $validator->errors()->first());
  324. }
  325. // 创建视频生成任务
  326. $result = $this->AnimeService->createSegmentVideoTask($data);
  327. $taskId = $result['task_id'];
  328. // 设置 SSE 响应头
  329. return response()->stream(function () use ($taskId, $result, $uid) {
  330. // 设置 SSE 响应头
  331. echo "data: " . json_encode([
  332. 'type' => 'init',
  333. 'data' => $result
  334. ]) . "\n\n";
  335. ob_flush();
  336. flush();
  337. $startTime = time();
  338. $maxDuration = 300; // 5分钟超时
  339. $checkInterval = 5; // 每5秒检查一次
  340. while (time() - $startTime < $maxDuration) {
  341. try {
  342. // 查询任务状态
  343. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  344. if (!$task) {
  345. echo "data: " . json_encode([
  346. 'type' => 'error',
  347. 'message' => '任务不存在'
  348. ]) . "\n\n";
  349. ob_flush();
  350. flush();
  351. break;
  352. }
  353. // 如果任务还在处理中,查询最新状态
  354. if ($task->status === 'processing') {
  355. // 根据任务类型查询不同的状态
  356. if ($task->task_type === 'jimeng') {
  357. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  358. } elseif ($task->task_type === 'keling') {
  359. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  360. } else {
  361. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  362. }
  363. if (isset($statusResult['status'])) {
  364. // 更新任务状态
  365. $task->update([
  366. 'status' => $statusResult['status'],
  367. 'result_url' => $statusResult['result_url'] ?? null,
  368. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  369. 'error_message' => $statusResult['error_message'] ?? null,
  370. 'completed_at' => in_array($statusResult['status'], [
  371. 'success',
  372. 'failed'
  373. ]) ? now() : null
  374. ]);
  375. // 如果任务成功,更新分镜表
  376. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  377. try {
  378. DB::beginTransaction();
  379. $now = date('Y-m-d H:i:s');
  380. // 获取分镜ID
  381. $segment = DB::table('mp_episode_segments')
  382. ->where('video_task_id', $taskId)
  383. ->first();
  384. if (!$segment) {
  385. throw new \Exception('未找到对应的分镜记录');
  386. }
  387. $segmentId = $segment->segment_id;
  388. $anime_id = $segment->anime_id;
  389. $episode_number = $segment->episode_number;
  390. $tail_frame = $segment->tail_frame;
  391. // 更新分镜表
  392. $segmentUpdateData = [
  393. 'video_url' => $statusResult['result_url'],
  394. 'video_task_status' => '已完成',
  395. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  396. 'current_type' => 2,
  397. 'updated_at' => $now
  398. ];
  399. // 只有当video_duration存在且大于0时才更新
  400. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  401. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  402. $segmentUpdateData['video_time_point_start'] = 0;
  403. $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  404. }
  405. $updateResult = DB::table('mp_episode_segments')
  406. ->where('segment_id', $segmentId)
  407. ->update($segmentUpdateData);
  408. if (!$updateResult) {
  409. Utils::throwError('20003:更新分镜表失败');
  410. }
  411. // 更新分镜视频成功后新增对话记录
  412. // 保存对话记录
  413. $records = [
  414. [
  415. 'uid' => $uid,
  416. 'anime_id' => $anime_id,
  417. 'sequence' => $episode_number,
  418. 'role' => 'user',
  419. 'content' => '图片转视频',
  420. 'segment_id' => $segmentId,
  421. 'video_url' => '',
  422. 'created_at' => $now,
  423. 'updated_at' => $now
  424. ],
  425. [
  426. 'uid' => $uid,
  427. 'anime_id' => $anime_id,
  428. 'sequence' => $episode_number,
  429. 'role' => 'assistant',
  430. 'content' => $tail_frame,
  431. 'segment_id' => $segmentId,
  432. 'video_url' => $statusResult['result_url'],
  433. 'created_at' => $now,
  434. 'updated_at' => $now
  435. ]
  436. ];
  437. DB::table('mp_anime_records')->insert($records);
  438. DB::commit();
  439. } catch (\Exception $e) {
  440. DB::rollBack();
  441. $logData = [
  442. 'task_id' => $taskId,
  443. 'error' => $e->getMessage()
  444. ];
  445. dLog('anime')->error('视频任务处理失败', $logData);
  446. logDB('anime', 'error', '视频任务处理失败', $logData);
  447. }
  448. } elseif ($statusResult['status'] === 'failed') {
  449. DB::table('mp_episode_segments')
  450. ->where('video_task_id', $taskId)
  451. ->update([
  452. 'video_task_status' => '失败',
  453. 'updated_at' => date('Y-m-d H:i:s')
  454. ]);
  455. }
  456. }
  457. }
  458. // 发送当前状态
  459. echo "data: " . json_encode([
  460. 'type' => 'update',
  461. 'data' => [
  462. 'task_id' => $task->id,
  463. 'status' => $task->status,
  464. 'result_url' => $task->result_url,
  465. 'error_message' => $task->error_message,
  466. 'elapsed_time' => time() - $startTime
  467. ]
  468. ]) . "\n\n";
  469. ob_flush();
  470. flush();
  471. // 如果任务完成(成功或失败),结束连接
  472. if (in_array($task->status, [
  473. 'success',
  474. 'failed'
  475. ])) {
  476. echo "data: " . json_encode([
  477. 'type' => 'completed',
  478. 'data' => [
  479. 'task_id' => $task->id,
  480. 'status' => $task->status,
  481. 'video_url' => $task->result_url,
  482. 'last_frame_url' => $task->last_frame_url,
  483. 'error_message' => $task->error_message
  484. ]
  485. ]) . "\n\n";
  486. ob_flush();
  487. flush();
  488. break;
  489. }
  490. sleep($checkInterval);
  491. } catch (\Exception $e) {
  492. echo "data: " . json_encode([
  493. 'type' => 'error',
  494. 'message' => '查询任务状态失败: ' . $e->getMessage()
  495. ]) . "\n\n";
  496. ob_flush();
  497. flush();
  498. sleep($checkInterval);
  499. }
  500. }
  501. // 超时处理
  502. if (time() - $startTime >= $maxDuration) {
  503. echo "data: " . json_encode([
  504. 'type' => 'time_out',
  505. 'message' => '任务执行超时,请稍后查询任务状态',
  506. 'data' => [
  507. 'task_id' => $taskId
  508. ]
  509. ]) . "\n\n";
  510. ob_flush();
  511. flush();
  512. }
  513. }, 200, [
  514. 'Content-Type' => 'text/event-stream',
  515. 'Cache-Control' => 'no-cache',
  516. 'Connection' => 'keep-alive',
  517. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  518. ]);
  519. }
  520. /**
  521. * 批量生成分镜视频
  522. */
  523. public function batchSetSegmentVideos(Request $request) {
  524. // 忽略所有超时限制
  525. set_time_limit(0);
  526. ini_set('max_execution_time', '0');
  527. $data = $request->all();
  528. // 验证参数
  529. $validator = Validator::make($data, [
  530. 'anime_id' => 'required|string',
  531. 'episode_id' => 'required|integer',
  532. ], [
  533. 'anime_id.required' => '动漫对话ID不能为空',
  534. 'episode_id.required' => '剧集ID不能为空',
  535. 'episode_id.integer' => '剧集ID必须是整数',
  536. ]);
  537. if ($validator->fails()) {
  538. Utils::throwError('1002:' . $validator->errors()->first());
  539. }
  540. $animeId = $data['anime_id'];
  541. $episodeId = $data['episode_id'];
  542. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  543. if (!$episode) Utils::throwError('20003:分集不存在');
  544. $episodeNumber = $episode->episode_number;
  545. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  546. // 获取所有分镜信息
  547. $segments = DB::table('mp_episode_segments')
  548. ->where('anime_id', $animeId)
  549. ->where('episode_id', $episodeId)
  550. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  551. ->orderBy('segment_number')
  552. ->get();
  553. if ($segments->isEmpty()) {
  554. Utils::throwError('20003:未找到分镜数据');
  555. }
  556. // 批量创建视频任务
  557. $taskIds = [];
  558. $segmentTasks = [];
  559. foreach ($segments as $segment) {
  560. try {
  561. // 检查视频任务正在生成中或当前状态为视频
  562. if ($segment->video_task_status === '生成中' || (int)$segment->current_type === 2) {
  563. continue;
  564. }
  565. // 获取分镜内容
  566. $segmentContent = $segment->segment_content ?: '';
  567. $tailFrame = $segment->tail_frame ?: '';
  568. // 构建完整的提示词
  569. $fullPrompt = $segmentContent;
  570. if ($tailFrame) {
  571. $fullPrompt .= "\n尾帧描述:$tailFrame";
  572. }
  573. // 智能选择视频时长
  574. // $videoDuration = $this->AnimeService->calculateOptimalVideoDuration($segmentContent, $tailFrame);
  575. $videoDuration = -1;
  576. // 处理视频模型(在循环外统一处理,避免重复)
  577. if (!isset($model)) {
  578. $model = getProp($data, 'model');
  579. if (!$model) {
  580. // 用户没有输入,从episode表获取
  581. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->first();
  582. $model = getProp($episode, 'video_model');
  583. if (!$model) {
  584. // episode表也没有,使用默认值
  585. $model = 'doubao-seedance-1-5-pro-251215';
  586. }
  587. }
  588. // 验证模型是否在可用模型表中
  589. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  590. $model = 'doubao-seedance-1-5-pro-251215';
  591. }
  592. }
  593. // 构建视频生成参数
  594. $videoParams = [
  595. 'model' => $model,
  596. 'alias_segment_id' => $segment->segment_id,
  597. 'prompt' => $fullPrompt,
  598. 'video_duration' => $videoDuration,
  599. 'video_resolution' => '720P',
  600. 'seed' => -1,
  601. 'ratio' => $ratio,
  602. 'generate_audio' => false,
  603. 'draft' => false,
  604. 'watermark' => false,
  605. 'camera_fixed' => false,
  606. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  607. ];
  608. // 如果分镜有图片,作为首帧
  609. $hasImage = !empty($segment->img_url);
  610. $hasVideo = !empty($segment->video_url);
  611. if ($hasImage) {
  612. $videoParams['first_frame_url'] = $segment->img_url;
  613. }
  614. // 构建content数组
  615. $videoParams['content'] = [
  616. [
  617. 'type' => 'text',
  618. 'text' => $videoParams['prompt'],
  619. ]
  620. ];
  621. // 如果有首帧图片,添加到content中
  622. if ($hasImage) {
  623. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  624. $videoParams['content'][] = [
  625. 'type' => 'image_url',
  626. 'image_url' => [
  627. 'url' => $videoParams['first_frame_url'],
  628. ],
  629. 'role' => 'reference_image',
  630. ];
  631. }else {
  632. $videoParams['content'][] = [
  633. 'type' => 'image_url',
  634. 'image_url' => [
  635. 'url' => $videoParams['first_frame_url'],
  636. ],
  637. 'role' => 'first_frame',
  638. ];
  639. }
  640. }
  641. // 获取配音音频URL和时长
  642. $audioUrl = $segment->audio_url ?? '';
  643. $audioDuration = $segment->audio_duration ?? 0;
  644. // 音频传入的前提:必须有至少一张图片或一个视频
  645. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  646. // 根据模型选择不同的视频生成方法
  647. if (strpos($model, 'jimeng') !== false) {
  648. // 即梦模型参数调整
  649. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  650. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  651. unset($videoParams['ratio']);
  652. unset($videoParams['content']); // 即梦不使用content格式
  653. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  654. } elseif (strpos($model, 'kling') !== false) {
  655. // Keling模型参数调整
  656. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  657. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  658. unset($videoParams['ratio']);
  659. unset($videoParams['content']); // Keling不使用content格式
  660. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  661. } else {
  662. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  663. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  664. // 添加配音音频到content中
  665. $videoParams['content'][] = [
  666. 'type' => 'audio_url',
  667. 'audio_url' => [
  668. 'url' => $audioUrl,
  669. ],
  670. 'role' => 'reference_audio',
  671. ];
  672. // 优化提示词,增加音频相关描述
  673. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  674. $videoParams['prompt'] = $audioPrompt;
  675. $videoParams['content'][0]['text'] = $audioPrompt;
  676. } else if ($audioDuration) {
  677. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  678. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  679. }
  680. // Seedance模型(默认)
  681. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  682. }
  683. $taskIds[] = $task->id;
  684. // 更新分镜表的视频任务信息
  685. DB::table('mp_episode_segments')
  686. ->where('segment_id', $segment->segment_id)
  687. ->update([
  688. 'video_task_id' => $task->id,
  689. 'video_task_status' => '生成中',
  690. 'updated_at' => date('Y-m-d H:i:s')
  691. ]);
  692. $segmentTasks[] = [
  693. 'segment_id' => $segment->segment_id,
  694. 'task_id' => $task->id,
  695. 'segment_number' => $segment->segment_number,
  696. 'tail_frame' => $segment->tail_frame,
  697. ];
  698. } catch (\Exception $e) {
  699. $logData = [
  700. 'segment_id' => $segment->segment_id,
  701. 'anime_id' => $animeId,
  702. 'error' => $e->getMessage(),
  703. ];
  704. dLog('anime')->error('创建分镜视频任务失败', $logData);
  705. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  706. continue;
  707. }
  708. }
  709. if (empty($taskIds)) {
  710. Utils::throwError('20003:没有需要生成视频的分镜');
  711. }
  712. // 保存模型到episode表
  713. if (isset($model)) {
  714. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  715. 'video_model' => $model,
  716. 'updated_at' => date('Y-m-d H:i:s')
  717. ]);
  718. }
  719. // 记录开始时间(包含创建任务的时间)
  720. $startTime = time();
  721. $maxDuration = 1800; // 30分钟超时
  722. $uid = Site::getUid();
  723. // 设置 SSE 响应头并开始长连接
  724. return response()->stream(function () use ($taskIds, $segmentTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  725. $checkInterval = 10; // 每10秒检查一次
  726. // 初始化任务数组
  727. $totalTasks = $taskIds; // 所有任务ID
  728. $completeTasks = []; // 已完成的任务ID(包含失败)
  729. $successTasks = []; // 成功的任务ID
  730. // 发送初始任务创建信息
  731. echo "data: " . json_encode([
  732. 'type' => 'init',
  733. 'total_tasks_count' => count($totalTasks),
  734. 'completed_tasks_count' => count($completeTasks),
  735. 'success_tasks_count' => count($successTasks)
  736. ]) . "\n\n";
  737. ob_flush();
  738. flush();
  739. while (time() - $startTime < $maxDuration) {
  740. try {
  741. $hasUpdate = false; // 标记是否有更新
  742. // 获取所有任务的最新状态
  743. foreach ($totalTasks as $taskId) {
  744. // 如果任务已经在完成列表中,跳过
  745. if (in_array($taskId, $completeTasks)) {
  746. continue;
  747. }
  748. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  749. if (!$task) {
  750. continue;
  751. }
  752. // 如果任务还在处理中,查询最新状态
  753. if ($task->status === 'processing') {
  754. // 根据任务类型查询不同的状态
  755. if ($task->task_type === 'jimeng') {
  756. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  757. } elseif ($task->task_type === 'keling') {
  758. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  759. } else {
  760. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  761. }
  762. if (isset($statusResult['status'])) {
  763. // 更新任务状态
  764. $task->update([
  765. 'status' => $statusResult['status'],
  766. 'result_json' => $statusResult['result_json'] ?? [],
  767. 'result_url' => $statusResult['result_url'] ?? null,
  768. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  769. 'error_message' => $statusResult['error_message'] ?? null,
  770. 'completed_at' => in_array($statusResult['status'], [
  771. 'success',
  772. 'failed'
  773. ]) ? now() : null
  774. ]);
  775. // 如果任务成功,更新分镜表
  776. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  777. try {
  778. DB::beginTransaction();
  779. $now = date('Y-m-d H:i:s');
  780. // 获取分镜ID
  781. $segmentId = null;
  782. foreach ($segmentTasks as $segmentTask) {
  783. if ($segmentTask['task_id'] == $taskId) {
  784. $segmentId = $segmentTask['segment_id'];
  785. $tail_frame = $segmentTask['tail_frame'];
  786. break;
  787. }
  788. }
  789. if ($segmentId) {
  790. // 更新分镜表
  791. $segmentUpdateData = [
  792. 'video_url' => $statusResult['result_url'],
  793. 'video_task_status' => '已完成',
  794. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  795. 'current_type' => 2,
  796. 'updated_at' => $now
  797. ];
  798. // 只有当video_duration存在且大于0时才更新
  799. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  800. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  801. $segmentUpdateData['video_time_point_start'] = 0;
  802. $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  803. }
  804. $updateResult = DB::table('mp_episode_segments')
  805. ->where('segment_id', $segmentId)
  806. ->update($segmentUpdateData);
  807. if ($updateResult) {
  808. // 更新分镜视频成功后新增对话记录
  809. $records = [
  810. [
  811. 'uid' => $uid,
  812. 'anime_id' => $animeId,
  813. 'sequence' => $episodeNumber,
  814. 'role' => 'user',
  815. 'content' => '图片转视频',
  816. 'segment_id' => $segmentId,
  817. 'video_url' => '',
  818. 'created_at' => $now,
  819. 'updated_at' => $now
  820. ],
  821. [
  822. 'uid' => $uid,
  823. 'anime_id' => $animeId,
  824. 'sequence' => $episodeNumber,
  825. 'role' => 'assistant',
  826. 'content' => $tail_frame ?? '',
  827. 'segment_id' => $segmentId,
  828. 'video_url' => $statusResult['result_url'],
  829. 'created_at' => $now,
  830. 'updated_at' => $now
  831. ]
  832. ];
  833. DB::table('mp_anime_records')->insert($records);
  834. }
  835. }
  836. DB::commit();
  837. } catch (\Exception $e) {
  838. DB::rollBack();
  839. $logData = [
  840. 'task_id' => $taskId,
  841. 'error' => $e->getMessage()
  842. ];
  843. dLog('anime')->error('视频任务处理失败', $logData);
  844. logDB('anime', 'error', '视频任务处理失败', $logData);
  845. }
  846. } elseif ($statusResult['status'] === 'failed') {
  847. // 获取分镜ID并更新失败状态
  848. foreach ($segmentTasks as $segmentTask) {
  849. if ($segmentTask['task_id'] == $taskId) {
  850. DB::table('mp_episode_segments')
  851. ->where('segment_id', $segmentTask['segment_id'])
  852. ->update([
  853. 'video_task_status' => '失败',
  854. 'updated_at' => date('Y-m-d H:i:s')
  855. ]);
  856. break;
  857. }
  858. }
  859. }
  860. }
  861. }
  862. // 检查任务是否完成(成功或失败)
  863. if (in_array($task->status, ['success', 'failed'])) {
  864. $completeTasks[] = $taskId;
  865. $hasUpdate = true;
  866. if ($task->status === 'success') {
  867. $successTasks[] = $taskId;
  868. }
  869. }
  870. }
  871. // 如果有更新,发送update通知
  872. if ($hasUpdate) {
  873. echo "data: " . json_encode([
  874. 'type' => 'update',
  875. 'total_tasks_count' => count($totalTasks),
  876. 'completed_tasks_count' => count($completeTasks),
  877. 'success_tasks_count' => count($successTasks)
  878. ]) . "\n\n";
  879. ob_flush();
  880. flush();
  881. }
  882. // 如果所有任务都完成了,结束连接
  883. if (count($completeTasks) >= count($totalTasks)) {
  884. // 获取所有成功任务的分镜信息
  885. $successSegments = [];
  886. foreach ($successTasks as $taskId) {
  887. // 通过taskId找到对应的segmentTask
  888. foreach ($segmentTasks as $segmentTask) {
  889. if ($segmentTask['task_id'] == $taskId) {
  890. $segment = DB::table('mp_episode_segments')
  891. ->where('segment_id', $segmentTask['segment_id'])
  892. ->select('segment_id', 'video_url')
  893. ->first();
  894. if ($segment && !empty($segment->video_url)) {
  895. $successSegments[] = [
  896. 'segment_id' => $segment->segment_id,
  897. 'video_url' => $segment->video_url
  898. ];
  899. }
  900. break;
  901. }
  902. }
  903. }
  904. echo "data: " . json_encode([
  905. 'type' => 'completed',
  906. 'total_tasks_count' => count($totalTasks),
  907. 'completed_tasks_count' => count($completeTasks),
  908. 'success_tasks_count' => count($successTasks),
  909. 'success_segments' => $successSegments
  910. ]) . "\n\n";
  911. ob_flush();
  912. flush();
  913. break;
  914. }
  915. // 检查是否超时
  916. if (time() - $startTime >= $maxDuration) {
  917. break;
  918. }
  919. sleep($checkInterval);
  920. } catch (\Exception $e) {
  921. echo "data: " . json_encode([
  922. 'type' => 'error',
  923. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  924. 'total_tasks_count' => count($totalTasks),
  925. 'completed_tasks_count' => count($completeTasks),
  926. 'success_tasks_count' => count($successTasks)
  927. ]) . "\n\n";
  928. ob_flush();
  929. flush();
  930. // 检查是否超时,如果超时则停止循环
  931. if (time() - $startTime >= $maxDuration) {
  932. break;
  933. }
  934. sleep($checkInterval);
  935. }
  936. }
  937. // 超时处理
  938. if (time() - $startTime >= $maxDuration) {
  939. echo "data: " . json_encode([
  940. 'type' => 'time_out',
  941. 'message' => '批量视频生成已超时30分钟,停止状态查询',
  942. 'total_tasks_count' => count($totalTasks),
  943. 'completed_tasks_count' => count($completeTasks),
  944. 'success_tasks_count' => count($successTasks)
  945. ]) . "\n\n";
  946. ob_flush();
  947. flush();
  948. }
  949. }, 200, [
  950. 'Content-Type' => 'text/event-stream',
  951. 'Cache-Control' => 'no-cache',
  952. 'Connection' => 'keep-alive',
  953. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  954. ]);
  955. }
  956. // 应用有声制作参数
  957. public function applyAudioData(Request $request) {
  958. $data = $request->all();
  959. $result = $this->AnimeService->applyAudioData($data);
  960. return $this->success($result);
  961. }
  962. // 获取分集生成图片信息
  963. public function episodePicsInfo(Request $request) {
  964. // 忽略所有超时限制
  965. set_time_limit(0);
  966. ini_set('max_execution_time', '0');
  967. $data = $request->all();
  968. // 获取生成器函数
  969. $streamGenerator = $this->AnimeService->episodePicsInfo($data);
  970. // 返回 SSE 响应
  971. return response()->stream($streamGenerator, 200, [
  972. 'Content-Type' => 'text/event-stream',
  973. 'Cache-Control' => 'no-cache',
  974. 'Connection' => 'keep-alive',
  975. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  976. ]);
  977. }
  978. public function clipSegmentVideo(Request $request) {
  979. $data = $request->all();
  980. $result = $this->AnimeService->clipSegmentVideo($data);
  981. return $this->success(['success'=>$result ? 1: 0]);
  982. }
  983. /**
  984. * 创建完整视频合成任务
  985. *
  986. * @param Request $request
  987. * @return \Illuminate\Http\JsonResponse
  988. */
  989. public function createCompleteVideoTask(Request $request)
  990. {
  991. $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. }