AnimeController.php 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  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. $is_multimodal = request('is_multimodal');
  45. if ($is_multimodal !== null) {
  46. $query->where('is_multimodal', $is_multimodal);
  47. }
  48. $models = $query->select('model', 'name', 'is_multimodal')->orderBy('order', 'desc')->orderBy('id', 'desc')->get()->map(function ($value) {
  49. return (array)$value;
  50. })->toArray();
  51. return $this->success($models);
  52. }
  53. // 图片模型
  54. public function imageModel() {
  55. $query = DB::table('mp_image_models')->where('is_enabled', 1);
  56. // 支持 model 搜索
  57. if ($model = request('model')) {
  58. $query->where('model', 'like', "%{$model}%");
  59. }
  60. // 支持 name 搜索
  61. if ($name = request('name')) {
  62. $query->where('name', 'like', "%{$name}%");
  63. }
  64. $is_multimodal = request('is_multimodal');
  65. if ($is_multimodal !== null) {
  66. $query->where('is_multimodal', $is_multimodal);
  67. }
  68. $models = $query->select('model', 'name')->orderBy('order', 'desc')->orderBy('id', 'desc')->get()->map(function ($value) {
  69. return (array)$value;
  70. })->toArray();
  71. return $this->success($models);
  72. }
  73. // 视频模型
  74. public function videoModel() {
  75. $query = DB::table('mp_video_models')->where('is_enabled', 1);
  76. // 支持 model 搜索
  77. if ($model = request('model')) {
  78. $query->where('model', 'like', "%{$model}%");
  79. }
  80. // 支持 name 搜索
  81. if ($name = request('name')) {
  82. $query->where('name', 'like', "%{$name}%");
  83. }
  84. $is_multimodal = request('is_multimodal');
  85. if ($is_multimodal !== null) {
  86. $query->where('is_multimodal', $is_multimodal);
  87. }
  88. $models = $query->select('model', 'name')->orderBy('order', 'desc')->orderBy('id', 'desc')->get()->map(function ($value) {
  89. return (array)$value;
  90. })->toArray();
  91. return $this->success($models);
  92. }
  93. public function artStyleList()
  94. {
  95. $result = [
  96. [
  97. 'art_style' => '唯美真人风格',
  98. '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"
  99. ],
  100. [
  101. 'art_style' => '真人古风风格',
  102. '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"
  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' => 'Q版卡通风格',
  114. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/Q版卡通风格.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' => '武侠风格',
  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. 'art_style' => '3D卡通风格',
  138. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/3D卡通风格.jpg"
  139. ],
  140. [
  141. 'art_style' => '条漫风格',
  142. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/条漫风格.jpg"
  143. ],
  144. [
  145. 'art_style' => '赛博朋克风格',
  146. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/赛博朋克风格.jpg"
  147. ],
  148. [
  149. 'art_style' => '暗黑悬疑风格',
  150. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/暗黑悬疑风格.jpg"
  151. ],
  152. [
  153. 'art_style' => '治愈清新风格',
  154. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/治愈清新风格.jpg"
  155. ],
  156. ];
  157. return $this->success($result);
  158. }
  159. // 新建动漫
  160. public function createAnime(Request $request) {
  161. $data = $request->all();
  162. $result = $this->AnimeService->createAnime($data);
  163. return $this->success(['anime_id' => $result]);
  164. }
  165. // 编辑动漫
  166. public function editAnime(Request $request) {
  167. $data = $request->all();
  168. $result = $this->AnimeService->editAnime($data);
  169. return $this->success(['success'=>$result ? 1 : 0]);
  170. }
  171. // 删除动漫
  172. public function delAnime(Request $request) {
  173. $data = $request->all();
  174. $result = $this->AnimeService->delAnime($data);
  175. return $this->success(['success'=>$result ? 1 : 0]);
  176. }
  177. // 批量生成主体图片
  178. public function batchSetRoleImg(Request $request) {
  179. // 忽略所有超时限制
  180. set_time_limit(0);
  181. ini_set('max_execution_time', '0');
  182. $data = $request->all();
  183. $result = $this->AnimeService->batchSetRoleImg($data);
  184. return $this->success($result);
  185. }
  186. // 批量生成场景图片
  187. public function batchSetSceneImg(Request $request) {
  188. // 忽略所有超时限制
  189. set_time_limit(0);
  190. ini_set('max_execution_time', '0');
  191. $data = $request->all();
  192. $result = $this->AnimeService->batchSetSceneImg($data);
  193. return $this->success($result);
  194. }
  195. // 修改分集主体列表
  196. public function changeEpisodeRoles(Request $request) {
  197. $data = $request->all();
  198. $result = $this->AnimeService->changeEpisodeRoles($data);
  199. return $this->success(['success'=>$result ? 1 : 0]);
  200. }
  201. // 修改分集场景列表
  202. public function changeEpisodeScenes(Request $request) {
  203. $data = $request->all();
  204. $result = $this->AnimeService->changeEpisodeScenes($data);
  205. return $this->success(['success'=>$result ? 1 : 0]);
  206. }
  207. // 修改分集道具列表
  208. public function changeEpisodeProps(Request $request) {
  209. $data = $request->all();
  210. $result = $this->AnimeService->changeEpisodeProps($data);
  211. return $this->success(['success'=>$result ? 1 : 0]);
  212. }
  213. // 编辑分镜剧本
  214. public function editSegment(Request $request) {
  215. $data = $request->all();
  216. $result = $this->AnimeService->editSegment($data);
  217. return $this->success(['success'=>$result ? 1 : 0]);
  218. }
  219. // 动漫对话列表
  220. public function chatList(Request $request) {
  221. $data = $request->all();
  222. $result = $this->AnimeService->chatList($data);
  223. return $this->success($result, [new AnimeTransformer(), 'newBuildChatList']);
  224. }
  225. // 动漫对话历史记录
  226. public function chatHistory(Request $request) {
  227. $data = $request->all();
  228. $result = $this->AnimeService->chatHistory($data);
  229. return $this->success($result);
  230. }
  231. // 动漫大纲
  232. public function animeDetail(Request $request) {
  233. $data = $request->all();
  234. $result = $this->AnimeService->animeDetail($data);
  235. return $this->success($result);
  236. }
  237. // 动漫剧集
  238. public function episodeInfo(Request $request) {
  239. $data = $request->all();
  240. $result = $this->AnimeService->episodeInfo($data);
  241. return $this->success($result);
  242. }
  243. // 动漫剧集(全能模式)
  244. public function episodeInfoForAce(Request $request) {
  245. $data = $request->all();
  246. $result = $this->AnimeService->episodeInfoForAce($data);
  247. return $this->success($result);
  248. }
  249. // 分镜信息
  250. public function segmentInfo(Request $request) {
  251. $data = $request->all();
  252. $result = $this->AnimeService->segmentInfo($data);
  253. return $this->success($result);
  254. }
  255. // 复制剧集副本
  256. public function copyEpisodeVersion(Request $request) {
  257. $data = $request->all();
  258. $result = $this->AnimeService->copyEpisodeVersion($data);
  259. return $this->success($result);
  260. }
  261. // 剧集副本列表
  262. public function episodeVersions(Request $request) {
  263. $data = $request->all();
  264. $result = $this->AnimeService->episodeVersions($data);
  265. return $this->success($result);
  266. }
  267. // 绑定剧集副本
  268. public function bindEpisodeVersion(Request $request) {
  269. $data = $request->all();
  270. $result = $this->AnimeService->bindEpisodeVersion($data);
  271. return $this->success(['success' => $result ? 1 : 0]);
  272. }
  273. // 对话改图
  274. public function chatChangeImg(Request $request) {
  275. $data = $request->all();
  276. $result = $this->AnimeService->chatChangeImg($data);
  277. return $this->success(['img_url' => $result]);
  278. }
  279. public function segmentChatHistory(Request $request) {
  280. $data = $request->all();
  281. $result = $this->AnimeService->segmentChatHistory($data);
  282. return $this->success($result);
  283. }
  284. // 一键生成分镜
  285. public function batchSetSegmentPics(Request $request) {
  286. // 忽略所有超时限制
  287. set_time_limit(0);
  288. ini_set('max_execution_time', '0');
  289. $data = $request->all();
  290. $result = $this->AnimeService->batchSetSegmentPics($data);
  291. return $this->success($result);
  292. }
  293. // 重新生成分镜
  294. public function reGenerateSegment(Request $request) {
  295. // 忽略所有超时限制
  296. set_time_limit(0);
  297. ini_set('max_execution_time', '0');
  298. $data = $request->all();
  299. $result = $this->AnimeService->reGenerateSegment($data);
  300. return $this->success(['img_url'=>$result]);
  301. }
  302. // 添加分镜
  303. public function addSegment(Request $request) {
  304. // 忽略所有超时限制
  305. set_time_limit(0);
  306. ini_set('max_execution_time', '0');
  307. $data = $request->all();
  308. $result = $this->AnimeService->addSegment($data);
  309. return $this->success($result);
  310. }
  311. // 复制分镜
  312. public function copySegment(Request $request) {
  313. $data = $request->all();
  314. $result = $this->AnimeService->copySegment($data);
  315. return $this->success($result);
  316. }
  317. // 移动分镜
  318. public function moveSegment(Request $request) {
  319. $data = $request->all();
  320. $result = $this->AnimeService->moveSegment($data);
  321. return $this->success(['success'=>$result ? 1: 0]);
  322. }
  323. // 删除分镜
  324. public function delSegment(Request $request) {
  325. $data = $request->all();
  326. $result = $this->AnimeService->delSegment($data);
  327. return $this->success(['success'=>$result ? 1: 0]);
  328. }
  329. public function applySegment(Request $request) {
  330. $data = $request->all();
  331. $result = $this->AnimeService->applySegment($data);
  332. return $this->success(['success'=>$result ? 1: 0]);
  333. }
  334. // 添加片段
  335. public function addAct(Request $request) {
  336. // 忽略所有超时限制
  337. set_time_limit(0);
  338. ini_set('max_execution_time', '0');
  339. $data = $request->all();
  340. $result = $this->AnimeService->addAct($data);
  341. return $this->success($result);
  342. }
  343. // 编辑片段
  344. public function editAct(Request $request) {
  345. $data = $request->all();
  346. $result = $this->AnimeService->editAct($data);
  347. return $this->success($result);
  348. }
  349. // 复制片段
  350. public function copyAct(Request $request) {
  351. $data = $request->all();
  352. $result = $this->AnimeService->copyAct($data);
  353. return $this->success($result);
  354. }
  355. // 移动片段
  356. public function moveAct(Request $request) {
  357. $data = $request->all();
  358. $result = $this->AnimeService->moveAct($data);
  359. return $this->success(['success'=>$result ? 1: 0]);
  360. }
  361. // 删除片段
  362. public function delAct(Request $request) {
  363. $data = $request->all();
  364. $result = $this->AnimeService->delAct($data);
  365. return $this->success(['success'=>$result ? 1: 0]);
  366. }
  367. // 应用片段
  368. public function applyAct(Request $request) {
  369. $data = $request->all();
  370. $result = $this->AnimeService->applyAct($data);
  371. return $this->success(['success'=>$result ? 1: 0]);
  372. }
  373. // 片段对话历史记录
  374. public function actChatHistory(Request $request) {
  375. $data = $request->all();
  376. $result = $this->AnimeService->actChatHistory($data);
  377. return $this->success($result);
  378. }
  379. // 分镜历史图片|视频
  380. public function segmentHistory(Request $request) {
  381. $data = $request->all();
  382. $result = $this->AnimeService->segmentHistory($data);
  383. return $this->success($result);
  384. }
  385. public function createSegmentVideoTask(Request $request) {
  386. // 忽略所有超时限制
  387. set_time_limit(0);
  388. ini_set('max_execution_time', '0');
  389. $data = $request->all();
  390. // 验证参数
  391. $validator = Validator::make($data, [
  392. 'segment_id' => 'required|string',
  393. 'tail_frame' => 'nullable|string|max:500',
  394. ], [
  395. 'segment_id.required' => '分镜ID不能为空',
  396. 'tail_frame.max' => '尾帧描述不能超过500个字符',
  397. ]);
  398. if ($validator->fails()) {
  399. Utils::throwError('1002:' . $validator->errors()->first());
  400. }
  401. // 创建视频生成任务
  402. $result = $this->AnimeService->createSegmentVideoTask($data);
  403. $taskId = $result['task_id'];
  404. // 设置 SSE 响应头
  405. return response()->stream(function () use ($taskId, $result) {
  406. // 设置 SSE 响应头
  407. echo "data: " . json_encode([
  408. 'type' => 'init',
  409. 'data' => $result
  410. ]) . "\n\n";
  411. if (ob_get_level() > 0) {
  412. ob_flush();
  413. }
  414. flush();
  415. $startTime = time();
  416. $maxDuration = 1800; // 5分钟超时
  417. $checkInterval = 5; // 每5秒检查一次
  418. $lastTaskData = null; // 记录上一次推送的任务数据,仅在有变化时发送update
  419. $lastQueueMessageTime = time(); // 记录上次发送队列消息的时间
  420. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  421. while (time() - $startTime < $maxDuration) {
  422. try {
  423. // 查询任务状态
  424. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  425. if (!$task) {
  426. echo "data: " . json_encode([
  427. 'type' => 'error',
  428. 'message' => '任务不存在'
  429. ]) . "\n\n";
  430. if (ob_get_level() > 0) {
  431. ob_flush();
  432. }
  433. flush();
  434. break;
  435. }
  436. // 视频任务结果由定时任务实时更新,此处直接读取任务表状态
  437. // 构建当前任务数据
  438. $taskData = [
  439. 'status' => $task->status,
  440. 'result_url' => $task->result_url,
  441. 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : ''
  442. ];
  443. // 首次查询只记录状态,不发送update(init已推送任务创建信息)
  444. if ($lastTaskData === null) {
  445. $lastTaskData = $taskData;
  446. } elseif ($taskData != $lastTaskData) {
  447. $lastTaskData = $taskData;
  448. // 有数据更新才发送update
  449. echo "data: " . json_encode([
  450. 'type' => 'update',
  451. 'data' => [
  452. 'task_id' => $task->id,
  453. 'status' => $task->status,
  454. 'result_url' => $task->result_url,
  455. 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : '',
  456. 'elapsed_time' => time() - $startTime
  457. ]
  458. ]) . "\n\n";
  459. if (ob_get_level() > 0) {
  460. ob_flush();
  461. }
  462. flush();
  463. }
  464. // 如果任务完成(成功或失败),结束连接
  465. if (in_array($task->status, [
  466. 'success',
  467. 'failed'
  468. ])) {
  469. echo "data: " . json_encode([
  470. 'type' => 'completed',
  471. 'data' => [
  472. 'task_id' => $task->id,
  473. 'status' => $task->status,
  474. 'video_url' => $task->compressed_url ?: $task->result_url,
  475. 'origin_video_url' => $task->result_url,
  476. 'last_frame_url' => $task->last_frame_url,
  477. 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : ''
  478. ]
  479. ]) . "\n\n";
  480. if (ob_get_level() > 0) {
  481. ob_flush();
  482. }
  483. flush();
  484. break;
  485. }
  486. // 每分钟发送一次队列状态消息
  487. $currentTime = time();
  488. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  489. echo "data: " . json_encode([
  490. 'type' => 'queue',
  491. 'data' => [
  492. 'task_id' => $task->id,
  493. 'status' => $task->status,
  494. 'elapsed_time' => $currentTime - $startTime,
  495. 'message' => '任务正在队列中执行...'
  496. ]
  497. ]) . "\n\n";
  498. if (ob_get_level() > 0) {
  499. ob_flush();
  500. }
  501. flush();
  502. $lastQueueMessageTime = $currentTime;
  503. }
  504. sleep($checkInterval);
  505. } catch (\Exception $e) {
  506. echo "data: " . json_encode([
  507. 'type' => 'error',
  508. 'message' => '查询任务状态失败: ' . $e->getMessage()
  509. ]) . "\n\n";
  510. if (ob_get_level() > 0) {
  511. ob_flush();
  512. }
  513. flush();
  514. sleep($checkInterval);
  515. }
  516. }
  517. // 超时处理
  518. if (time() - $startTime >= $maxDuration) {
  519. echo "data: " . json_encode([
  520. 'type' => 'time_out',
  521. 'message' => '任务执行超时,请稍后查询任务状态',
  522. 'data' => [
  523. 'task_id' => $taskId
  524. ]
  525. ]) . "\n\n";
  526. if (ob_get_level() > 0) {
  527. ob_flush();
  528. }
  529. flush();
  530. }
  531. }, 200, [
  532. 'Content-Type' => 'text/event-stream',
  533. 'Cache-Control' => 'no-cache',
  534. 'Connection' => 'keep-alive',
  535. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  536. ]);
  537. }
  538. /**
  539. * 批量生成分镜视频
  540. */
  541. public function batchSetSegmentVideos(Request $request) {
  542. // 忽略所有超时限制
  543. set_time_limit(0);
  544. ini_set('max_execution_time', '0');
  545. $data = $request->all();
  546. // 验证参数
  547. $validator = Validator::make($data, [
  548. 'anime_id' => 'required|string',
  549. 'episode_id' => 'required|integer',
  550. ], [
  551. 'anime_id.required' => '动漫对话ID不能为空',
  552. 'episode_id.required' => '剧集ID不能为空',
  553. 'episode_id.integer' => '剧集ID必须是整数',
  554. ]);
  555. if ($validator->fails()) {
  556. Utils::throwError('1002:' . $validator->errors()->first());
  557. }
  558. $animeId = $data['anime_id'];
  559. $episodeId = $data['episode_id'];
  560. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  561. if (!$episode) Utils::throwError('20003:分集不存在');
  562. $episodeNumber = $episode->episode_number;
  563. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  564. $generate_audio = getProp($data, 'generate_audio', 0);
  565. // 处理视频模型(在循环外统一处理)
  566. $model = getProp($data, 'model');
  567. if (!$model) {
  568. // 用户没有输入,从episode表获取
  569. $model = getProp($episode, 'video_model');
  570. if (!$model) {
  571. // episode表也没有,使用默认值
  572. $model = 'doubao-seedance-1-5-pro-251215';
  573. }
  574. }
  575. // 验证模型是否在可用模型表中
  576. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  577. $model = 'doubao-seedance-1-5-pro-251215';
  578. }
  579. // 获取所有分镜信息
  580. $segments = DB::table('mp_episode_segments')
  581. ->where('anime_id', $animeId)
  582. ->where('episode_id', $episodeId)
  583. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  584. ->orderBy('segment_number')
  585. ->get();
  586. if ($segments->isEmpty()) {
  587. Utils::throwError('20003:未找到分镜数据');
  588. }
  589. // 批量创建视频任务
  590. $taskIds = [];
  591. $segmentTasks = [];
  592. foreach ($segments as $segment) {
  593. try {
  594. // 检查视频任务正在生成中或当前状态为视频
  595. if ($segment->video_task_status === '生成中' || (int)$segment->current_type === 2) {
  596. continue;
  597. }
  598. // 获取分镜内容
  599. $segmentContent = $segment->segment_content ?: '';
  600. $tailFrame = $segment->tail_frame ?: '';
  601. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  602. $hasDialogue = false;
  603. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  604. $dialogue = trim($dialogueMatch[1]);
  605. // 如果台词不为空且不是"无"
  606. if (!empty($dialogue) && $dialogue !== '无') {
  607. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  608. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  609. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  610. $hasDialogue = true;
  611. }
  612. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  613. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  614. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  615. if (!preg_match('/^[“]/', $dialogue)) {
  616. $dialogue = '“' . $dialogue;
  617. }
  618. if (!preg_match('/[”]$/', $dialogue)) {
  619. $dialogue .= '”';
  620. }
  621. // 将修改后的台词替换回 $segmentContent
  622. $originalDialogue = $dialogueMatch[1];
  623. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  624. }
  625. }
  626. // 检查 $segmentContent 中是否已有尾帧描述
  627. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  628. // 确定最终使用的尾帧描述(优先级:segmentContent自带 > 分镜表字段)
  629. $finalTailFrame = '';
  630. if ($contentHasTailFrame) {
  631. // segmentContent 中有尾帧描述,使用它
  632. $finalTailFrame = trim($contentTailFrameMatch[1]);
  633. } else {
  634. // segmentContent 中没有,使用分镜表中的尾帧描述
  635. $finalTailFrame = $tailFrame;
  636. }
  637. // 构建完整的提示词
  638. $fullPrompt = $segmentContent;
  639. if ($finalTailFrame && !$contentHasTailFrame) {
  640. // 只有当 segmentContent 中没有尾帧描述时才追加
  641. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  642. }
  643. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  644. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  645. $fullPrompt = trim($fullPrompt);
  646. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  647. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  648. // 智能选择视频时长
  649. // $videoDuration = $this->AnimeService->calculateOptimalVideoDuration($segmentContent, $tailFrame);
  650. $videoDuration = -1;
  651. // 构建视频生成参数
  652. $videoParams = [
  653. 'model' => $model,
  654. 'alias_segment_id' => $segment->segment_id,
  655. 'prompt' => $fullPrompt,
  656. 'video_duration' => $videoDuration,
  657. 'video_resolution' => '720P',
  658. 'seed' => -1,
  659. 'ratio' => $ratio,
  660. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  661. 'draft' => false,
  662. 'watermark' => false,
  663. 'camera_fixed' => false,
  664. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  665. ];
  666. // 如果分镜有图片,作为首帧
  667. $hasImage = !empty($segment->img_url);
  668. $hasVideo = !empty($segment->video_url);
  669. if ($hasImage) {
  670. $videoParams['first_frame_url'] = $segment->img_url;
  671. }
  672. // 构建content数组
  673. $videoParams['content'] = [
  674. [
  675. 'type' => 'text',
  676. 'text' => $videoParams['prompt'],
  677. ]
  678. ];
  679. // 如果有首帧图片,添加到content中
  680. if ($hasImage) {
  681. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  682. $videoParams['content'][] = [
  683. 'type' => 'image_url',
  684. 'image_url' => [
  685. 'url' => $videoParams['first_frame_url'],
  686. ],
  687. 'role' => 'reference_image',
  688. ];
  689. }else {
  690. $videoParams['content'][] = [
  691. 'type' => 'image_url',
  692. 'image_url' => [
  693. 'url' => $videoParams['first_frame_url'],
  694. ],
  695. 'role' => 'first_frame',
  696. ];
  697. }
  698. }
  699. // 获取配音音频URL和时长
  700. $audioUrl = $segment->audio_url ?? '';
  701. $audioDuration = $segment->audio_duration ?? 0;
  702. // 音频传入的前提:必须有至少一张图片或一个视频
  703. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  704. // 根据模型选择不同的视频生成方法
  705. if (strpos($model, 'jimeng') !== false) {
  706. // 即梦模型参数调整
  707. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  708. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  709. unset($videoParams['ratio']);
  710. unset($videoParams['content']); // 即梦不使用content格式
  711. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  712. } elseif (strpos($model, 'kling') !== false) {
  713. // Keling模型参数调整
  714. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  715. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  716. unset($videoParams['ratio']);
  717. unset($videoParams['content']); // Keling不使用content格式
  718. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  719. } elseif (strpos($model, 'zhizhen') !== false) {
  720. // 智帧20等新模型使用统一API
  721. // 构建统一API参数
  722. $unifiedParams = [
  723. 'model_code' => $model,
  724. 'alias_segment_id' => $segment->segment_id,
  725. 'prompt' => trim($fullPrompt),
  726. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  727. 'video_resolution' => strtolower($videoParams['video_resolution']),
  728. 'video_ratio' => $ratio,
  729. 'seed' => -1,
  730. ];
  731. // 构建parameters参数
  732. $parameters = [
  733. 'seconds' => $unifiedParams['video_duration'],
  734. 'resolution' => $unifiedParams['video_resolution'],
  735. 'ratio' => $ratio,
  736. 'video_mode' => 'multi_image',
  737. 'mode' => 'multi_image',
  738. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  739. ];
  740. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  741. if ($hasImage) {
  742. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  743. // 只有在有图片的情况下才能添加参考音频
  744. if ($audioUrl) {
  745. $parameters['reference_audios'] = [$audioUrl];
  746. }
  747. } else {
  748. // 没有图片时,记录错误并跳过
  749. $logData = [
  750. 'segment_id' => $segment->segment_id,
  751. 'model' => $model,
  752. 'error' => '智帧20模型需要提供首帧图片'
  753. ];
  754. dLog('anime')->error('智帧20模型缺少首帧图片', $logData);
  755. logDB('anime', 'error', '智帧20模型缺少首帧图片', $logData);
  756. continue;
  757. }
  758. $unifiedParams['parameters'] = $parameters;
  759. // 调用统一API创建任务
  760. $task = $this->AIVideoGenerationService->createUnifiedApiTask($unifiedParams);
  761. } else {
  762. // Seedance模型(默认)
  763. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  764. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  765. // 添加配音音频到content中
  766. $videoParams['content'][] = [
  767. 'type' => 'audio_url',
  768. 'audio_url' => [
  769. 'url' => $audioUrl,
  770. ],
  771. 'role' => 'reference_audio',
  772. ];
  773. // 优化提示词,增加音频相关描述
  774. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  775. $videoParams['prompt'] = $audioPrompt;
  776. $videoParams['content'][0]['text'] = $audioPrompt;
  777. } else if ($audioDuration) {
  778. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  779. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  780. }
  781. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  782. }
  783. $taskIds[] = $task->id;
  784. // 更新分镜表的视频任务信息
  785. DB::table('mp_episode_segments')
  786. ->where('segment_id', $segment->segment_id)
  787. ->update([
  788. 'video_task_id' => $task->id,
  789. 'video_task_status' => '生成中',
  790. 'updated_at' => date('Y-m-d H:i:s')
  791. ]);
  792. $segmentTasks[] = [
  793. 'segment_id' => $segment->segment_id,
  794. 'task_id' => $task->id,
  795. 'segment_number' => $segment->segment_number,
  796. 'tail_frame' => $segment->tail_frame,
  797. 'audio_duration' => $segment->audio_duration,
  798. ];
  799. } catch (\Exception $e) {
  800. $logData = [
  801. 'segment_id' => $segment->segment_id,
  802. 'anime_id' => $animeId,
  803. 'error' => $e->getMessage(),
  804. ];
  805. dLog('anime')->error('创建分镜视频任务失败', $logData);
  806. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  807. continue;
  808. }
  809. }
  810. if (empty($taskIds)) {
  811. Utils::throwError('20003:没有需要生成视频的分镜');
  812. }
  813. // 保存模型到episode表
  814. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  815. 'video_model' => $model,
  816. 'updated_at' => date('Y-m-d H:i:s')
  817. ]);
  818. // 记录开始时间(包含创建任务的时间)
  819. $startTime = time();
  820. $maxDuration = 1800; // 30分钟超时
  821. // 设置 SSE 响应头并开始长连接
  822. return response()->stream(function () use ($taskIds, $segmentTasks, $episodeId, $startTime, $maxDuration) {
  823. $checkInterval = 10; // 每10秒检查一次
  824. $lastQueueMessageTime = time(); // 记录上次发送队列消息的时间
  825. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  826. // 初始化任务数组
  827. $totalTasks = $taskIds; // 所有任务ID
  828. $completeTasks = []; // 已完成的任务ID(包含失败)
  829. $successTasks = []; // 成功的任务ID
  830. // 发送初始任务创建信息
  831. echo "data: " . json_encode([
  832. 'type' => 'init',
  833. 'total_tasks_count' => count($totalTasks),
  834. 'completed_tasks_count' => count($completeTasks),
  835. 'success_tasks_count' => count($successTasks)
  836. ]) . "\n\n";
  837. if (ob_get_level() > 0) {
  838. ob_flush();
  839. }
  840. flush();
  841. while (time() - $startTime < $maxDuration) {
  842. try {
  843. $hasUpdate = false; // 标记是否有更新
  844. // 获取所有任务的最新状态
  845. foreach ($totalTasks as $taskId) {
  846. // 如果任务已经在完成列表中,跳过
  847. if (in_array($taskId, $completeTasks)) {
  848. continue;
  849. }
  850. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  851. if (!$task) {
  852. continue;
  853. }
  854. // 视频任务结果由定时任务实时更新,此处直接读取任务表状态
  855. // 检查任务是否完成(成功或失败)
  856. if (in_array($task->status, ['success', 'failed'])) {
  857. $completeTasks[] = $taskId;
  858. $hasUpdate = true;
  859. if ($task->status === 'success') {
  860. $successTasks[] = $taskId;
  861. }
  862. }
  863. }
  864. // 如果有更新,发送update通知
  865. if ($hasUpdate) {
  866. echo "data: " . json_encode([
  867. 'type' => 'update',
  868. 'total_tasks_count' => count($totalTasks),
  869. 'completed_tasks_count' => count($completeTasks),
  870. 'success_tasks_count' => count($successTasks)
  871. ]) . "\n\n";
  872. if (ob_get_level() > 0) {
  873. ob_flush();
  874. }
  875. flush();
  876. }
  877. // 如果所有任务都完成了,结束连接
  878. if (count($completeTasks) >= count($totalTasks)) {
  879. // 获取所有成功任务的分镜信息
  880. $successSegments = [];
  881. foreach ($successTasks as $taskId) {
  882. // 通过taskId找到对应的segmentTask
  883. foreach ($segmentTasks as $segmentTask) {
  884. if ($segmentTask['task_id'] == $taskId) {
  885. $segment = DB::table('mp_episode_segments')
  886. ->where('segment_id', $segmentTask['segment_id'])
  887. ->select('segment_id', 'video_url')
  888. ->first();
  889. if ($segment && !empty($segment->video_url)) {
  890. $successSegments[] = [
  891. 'segment_id' => $segment->segment_id,
  892. 'video_url' => $segment->video_url
  893. ];
  894. }
  895. break;
  896. }
  897. }
  898. }
  899. echo "data: " . json_encode([
  900. 'type' => 'completed',
  901. 'total_tasks_count' => count($totalTasks),
  902. 'completed_tasks_count' => count($completeTasks),
  903. 'success_tasks_count' => count($successTasks),
  904. 'success_segments' => $successSegments
  905. ]) . "\n\n";
  906. if (ob_get_level() > 0) {
  907. ob_flush();
  908. }
  909. flush();
  910. break;
  911. }
  912. // 每分钟发送一次队列状态消息
  913. $currentTime = time();
  914. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  915. echo "data: " . json_encode([
  916. 'type' => 'queue',
  917. 'data' => [
  918. 'total_tasks_count' => count($totalTasks),
  919. 'completed_tasks_count' => count($completeTasks),
  920. 'success_tasks_count' => count($successTasks),
  921. 'elapsed_time' => $currentTime - $startTime,
  922. 'message' => '任务正在队列中执行...'
  923. ]
  924. ]) . "\n\n";
  925. if (ob_get_level() > 0) {
  926. ob_flush();
  927. }
  928. flush();
  929. $lastQueueMessageTime = $currentTime;
  930. }
  931. // 检查是否超时
  932. if (time() - $startTime >= $maxDuration) {
  933. break;
  934. }
  935. sleep($checkInterval);
  936. } catch (\Exception $e) {
  937. echo "data: " . json_encode([
  938. 'type' => 'error',
  939. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  940. 'total_tasks_count' => count($totalTasks),
  941. 'completed_tasks_count' => count($completeTasks),
  942. 'success_tasks_count' => count($successTasks)
  943. ]) . "\n\n";
  944. if (ob_get_level() > 0) {
  945. ob_flush();
  946. }
  947. flush();
  948. // 检查是否超时,如果超时则停止循环
  949. if (time() - $startTime >= $maxDuration) {
  950. break;
  951. }
  952. sleep($checkInterval);
  953. }
  954. }
  955. // 超时处理
  956. if (time() - $startTime >= $maxDuration) {
  957. echo "data: " . json_encode([
  958. 'type' => 'time_out',
  959. 'message' => '批量视频生成已超时30分钟,停止状态查询',
  960. 'total_tasks_count' => count($totalTasks),
  961. 'completed_tasks_count' => count($completeTasks),
  962. 'success_tasks_count' => count($successTasks)
  963. ]) . "\n\n";
  964. if (ob_get_level() > 0) {
  965. ob_flush();
  966. }
  967. flush();
  968. }
  969. }, 200, [
  970. 'Content-Type' => 'text/event-stream',
  971. 'Cache-Control' => 'no-cache',
  972. 'Connection' => 'keep-alive',
  973. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  974. ]);
  975. }
  976. // 应用有声制作参数
  977. public function applyAudioData(Request $request) {
  978. $data = $request->all();
  979. $result = $this->AnimeService->applyAudioData($data);
  980. return $this->success($result);
  981. }
  982. // 获取分集生成图片信息
  983. public function episodePicsInfo(Request $request) {
  984. // 忽略所有超时限制
  985. set_time_limit(0);
  986. ini_set('max_execution_time', '0');
  987. $data = $request->all();
  988. // 获取生成器函数
  989. $streamGenerator = $this->AnimeService->episodePicsInfo($data);
  990. // 返回 SSE 响应
  991. return response()->stream($streamGenerator, 200, [
  992. 'Content-Type' => 'text/event-stream',
  993. 'Cache-Control' => 'no-cache',
  994. 'Connection' => 'keep-alive',
  995. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  996. ]);
  997. }
  998. public function clipSegmentVideo(Request $request) {
  999. $data = $request->all();
  1000. $result = $this->AnimeService->clipSegmentVideo($data);
  1001. return $this->success(['success'=>$result ? 1: 0]);
  1002. }
  1003. /**
  1004. * 创建完整视频合成任务
  1005. *
  1006. * @param Request $request
  1007. * @return \Illuminate\Http\JsonResponse
  1008. */
  1009. public function createCompleteVideoTask(Request $request)
  1010. {
  1011. // 忽略所有超时限制
  1012. set_time_limit(0);
  1013. ini_set('max_execution_time', '0');
  1014. $data = $request->all();
  1015. // 验证参数
  1016. $validator = Validator::make($data, [
  1017. 'anime_id' => 'required|string',
  1018. 'episode_id' => 'required|string',
  1019. ], [
  1020. 'anime_id.required' => '请选择动漫',
  1021. 'episode_id.required' => '请选择分集',
  1022. ]);
  1023. if ($validator->fails()) {
  1024. Utils::throwError('1002:' . $validator->errors()->first());
  1025. }
  1026. try {
  1027. $result = $this->AnimeService->createCompleteVideoTask($data);
  1028. return $this->success($result);
  1029. } catch (\Exception $e) {
  1030. $logData = [
  1031. 'anime_id' => $data['anime_id'] ?? '',
  1032. 'episode_id' => $data['episode_id'] ?? '',
  1033. 'error' => $e->getMessage()
  1034. ];
  1035. dLog('anime')->error('创建完整视频合成任务失败', $logData);
  1036. logDB('anime', 'error', '创建完整视频合成任务失败', $logData);
  1037. return $this->error('20003:'.$e->getMessage());
  1038. }
  1039. }
  1040. // 文生图(通用)
  1041. public function generateImg(Request $request) {
  1042. // 忽略所有超时限制
  1043. set_time_limit(0);
  1044. ini_set('max_execution_time', '0');
  1045. $data = $request->all();
  1046. $result = $this->AnimeService->generateImg($data);
  1047. return $this->success($result);
  1048. }
  1049. /**
  1050. * 导出分集的全部图片(下载并打包)
  1051. */
  1052. public function exportEpisodeImages(Request $request) {
  1053. // 忽略所有超时限制
  1054. set_time_limit(0);
  1055. ini_set('max_execution_time', '0');
  1056. ini_set('memory_limit', '512M');
  1057. $data = $request->all();
  1058. // 验证参数
  1059. $validator = Validator::make($data, [
  1060. 'anime_id' => 'required|string',
  1061. 'episode_id' => 'required|string',
  1062. ], [
  1063. 'anime_id.required' => '动漫ID不能为空',
  1064. 'episode_id.required' => '剧集ID不能为空',
  1065. ]);
  1066. if ($validator->fails()) {
  1067. Utils::throwError('1002:' . $validator->errors()->first());
  1068. }
  1069. $animeId = $data['anime_id'];
  1070. $episodeId = $data['episode_id'];
  1071. try {
  1072. // 获取动漫信息,判断是否为全能模式
  1073. $anime = DB::table('mp_animes')
  1074. ->where('id', $animeId)
  1075. ->select('ace_mode')
  1076. ->first();
  1077. if (!$anime) {
  1078. Utils::throwError('20003:未找到动漫信息');
  1079. }
  1080. $isAceMode = ($anime->ace_mode == 1);
  1081. // 获取剧集信息
  1082. $episode = DB::table('mp_anime_episodes')
  1083. ->where('anime_id', $animeId)
  1084. ->where('id', $episodeId)
  1085. ->select('episode_number', 'title')
  1086. ->first();
  1087. if (!$episode) {
  1088. Utils::throwError('20003:未找到剧集信息');
  1089. }
  1090. // 根据模式查询和排序分镜数据
  1091. if ($isAceMode) {
  1092. // 全能模式:只查询有视频的分镜,按act_number排序
  1093. $segments = DB::table('mp_episode_segments')
  1094. ->where('anime_id', $animeId)
  1095. ->where('episode_id', $episodeId)
  1096. ->whereNotNull('video_url')
  1097. ->where('video_url', '!=', '')
  1098. ->orderBy('act_number')
  1099. ->select('id as act_id', 'act_number', 'video_url', 'act_title')
  1100. ->get();
  1101. if ($segments->isEmpty()) {
  1102. Utils::throwError('20003:该剧集暂无视频可导出');
  1103. }
  1104. } else {
  1105. // 普通模式:查询所有分镜,按segment_number排序
  1106. $segments = DB::table('mp_episode_segments')
  1107. ->where('anime_id', $animeId)
  1108. ->where('episode_id', $episodeId)
  1109. ->orderBy('segment_number')
  1110. ->select('segment_id', 'segment_number', 'img_url', 'video_url', 'audio_url')
  1111. ->get();
  1112. if ($segments->isEmpty()) {
  1113. Utils::throwError('20003:该剧集暂无分镜数据');
  1114. }
  1115. // 过滤出有图片或视频的分镜
  1116. $validSegments = $segments->filter(function($segment) {
  1117. return (!empty($segment->img_url) || !empty($segment->video_url));
  1118. });
  1119. if ($validSegments->isEmpty()) {
  1120. Utils::throwError('20003:该剧集暂无图片或视频可导出');
  1121. }
  1122. $segments = $validSegments->values();
  1123. }
  1124. // 创建临时目录
  1125. $tempDir = storage_path('app/temp/episode_images_' . time() . '_' . mt_rand(1000, 9999));
  1126. if (!file_exists($tempDir)) {
  1127. mkdir($tempDir, 0755, true);
  1128. }
  1129. // 并行下载文件(使用 cURL multi)
  1130. $downloadedFiles = [];
  1131. $multiHandle = curl_multi_init();
  1132. $curlHandles = [];
  1133. $fileInfos = [];
  1134. // 准备所有下载任务
  1135. foreach ($segments as $index => $segment) {
  1136. try {
  1137. if ($isAceMode) {
  1138. // 全能模式:只下载视频
  1139. $mediaUrl = $segment->video_url;
  1140. } else {
  1141. // 普通模式:优先使用video_url,如果没有则使用img_url
  1142. $mediaUrl = !empty($segment->video_url) ? $segment->video_url : $segment->img_url;
  1143. }
  1144. if (empty($mediaUrl)) {
  1145. continue;
  1146. }
  1147. // 获取文件扩展名
  1148. $extension = pathinfo(parse_url($mediaUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
  1149. if (empty($extension)) {
  1150. // 根据URL类型设置默认扩展名
  1151. $extension = !empty($segment->video_url) ? 'mp4' : 'jpg';
  1152. }
  1153. // 构建文件名
  1154. if ($isAceMode) {
  1155. // 全能模式:使用act_number
  1156. $fileName = sprintf('%03d.%s', $segment->act_number, $extension);
  1157. } else {
  1158. // 普通模式:使用segment_number
  1159. $fileName = sprintf('%03d.%s', $segment->segment_number, $extension);
  1160. }
  1161. $filePath = $tempDir . '/' . $fileName;
  1162. // 创建 cURL 句柄
  1163. $ch = curl_init($mediaUrl);
  1164. $fp = fopen($filePath, 'wb');
  1165. curl_setopt($ch, CURLOPT_FILE, $fp);
  1166. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  1167. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1168. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  1169. curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  1170. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  1171. curl_multi_add_handle($multiHandle, $ch);
  1172. $curlHandles[(int)$ch] = [
  1173. 'handle' => $ch,
  1174. 'file' => $fp,
  1175. 'path' => $filePath,
  1176. 'url' => $mediaUrl,
  1177. 'segment' => $segment
  1178. ];
  1179. } catch (\Exception $e) {
  1180. $logData = ['error' => $e->getMessage()];
  1181. if ($isAceMode) {
  1182. $logData['act_id'] = $segment->act_id;
  1183. } else {
  1184. $logData['segment_id'] = $segment->segment_id;
  1185. }
  1186. logDB('anime', 'error', '准备下载任务异常', $logData);
  1187. continue;
  1188. }
  1189. }
  1190. // 执行并行下载
  1191. $running = null;
  1192. do {
  1193. curl_multi_exec($multiHandle, $running);
  1194. curl_multi_select($multiHandle, 0.1);
  1195. } while ($running > 0);
  1196. // 处理下载结果
  1197. foreach ($curlHandles as $info) {
  1198. $ch = $info['handle'];
  1199. $fp = $info['file'];
  1200. $filePath = $info['path'];
  1201. $segment = $info['segment'];
  1202. fclose($fp);
  1203. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  1204. if ($httpCode == 200 && file_exists($filePath) && filesize($filePath) > 0) {
  1205. $downloadedFiles[] = $filePath;
  1206. } else {
  1207. // 删除失败的文件
  1208. if (file_exists($filePath)) {
  1209. @unlink($filePath);
  1210. }
  1211. $logData = [
  1212. 'media_url' => $info['url'],
  1213. 'http_code' => $httpCode,
  1214. 'type' => $isAceMode ? 'video' : 'image'
  1215. ];
  1216. if ($isAceMode) {
  1217. $logData['act_id'] = $segment->act_id;
  1218. } else {
  1219. $logData['segment_id'] = $segment->segment_id;
  1220. }
  1221. logDB('anime', 'warning', '文件下载失败', $logData);
  1222. }
  1223. curl_multi_remove_handle($multiHandle, $ch);
  1224. curl_close($ch);
  1225. }
  1226. curl_multi_close($multiHandle);
  1227. if (empty($downloadedFiles)) {
  1228. // 清理临时目录
  1229. if (file_exists($tempDir)) {
  1230. array_map('unlink', glob("$tempDir/*"));
  1231. rmdir($tempDir);
  1232. }
  1233. Utils::throwError('20003:没有成功下载任何文件');
  1234. }
  1235. // 处理音频合成(仅普通模式)
  1236. $mergedAudioPath = null;
  1237. if (!$isAceMode) {
  1238. try {
  1239. // 检查 FFmpeg 是否可用
  1240. exec('which ffmpeg 2>&1', $ffmpegCheck, $ffmpegReturnCode);
  1241. $hasFfmpeg = ($ffmpegReturnCode === 0);
  1242. if ($hasFfmpeg) {
  1243. // 下载所有分镜的音频文件
  1244. $audioFiles = [];
  1245. foreach ($segments as $segment) {
  1246. if (!empty($segment->audio_url)) {
  1247. try {
  1248. $context = stream_context_create([
  1249. 'http' => [
  1250. 'timeout' => 30,
  1251. 'follow_location' => 1,
  1252. 'ignore_errors' => true
  1253. ],
  1254. 'ssl' => [
  1255. 'verify_peer' => false,
  1256. 'verify_peer_name' => false
  1257. ]
  1258. ]);
  1259. $audioData = @file_get_contents($segment->audio_url, false, $context);
  1260. if ($audioData !== false && !empty($audioData)) {
  1261. // 获取音频文件扩展名
  1262. $audioExtension = pathinfo(parse_url($segment->audio_url, PHP_URL_PATH), PATHINFO_EXTENSION);
  1263. if (empty($audioExtension)) {
  1264. $audioExtension = 'wav';
  1265. }
  1266. $audioFileName = sprintf('audio_%03d.%s', $segment->segment_number, $audioExtension);
  1267. $audioFilePath = $tempDir . '/' . $audioFileName;
  1268. file_put_contents($audioFilePath, $audioData);
  1269. $audioFiles[] = $audioFilePath;
  1270. } else {
  1271. logDB('anime', 'warning', '音频下载失败', [
  1272. 'segment_id' => $segment->segment_id,
  1273. 'audio_url' => $segment->audio_url
  1274. ]);
  1275. }
  1276. } catch (\Exception $e) {
  1277. logDB('anime', 'error', '下载音频异常', [
  1278. 'segment_id' => $segment->segment_id,
  1279. 'audio_url' => $segment->audio_url,
  1280. 'error' => $e->getMessage()
  1281. ]);
  1282. }
  1283. }
  1284. }
  1285. // 如果有音频文件,则进行合成
  1286. if (!empty($audioFiles)) {
  1287. // 创建 FFmpeg concat 文件列表
  1288. $concatFile = $tempDir . '/concat.txt';
  1289. $concatContent = '';
  1290. foreach ($audioFiles as $audioFile) {
  1291. // 使用相对路径,避免路径中的特殊字符问题
  1292. $concatContent .= "file '" . basename($audioFile) . "'\n";
  1293. }
  1294. file_put_contents($concatFile, $concatContent);
  1295. // 合成音频文件
  1296. $mergedAudioPath = $tempDir . '/tts.wav';
  1297. // 使用 FFmpeg 合并音频,转换为统一的 WAV 格式
  1298. $ffmpegCommand = sprintf(
  1299. 'cd %s && ffmpeg -f concat -safe 0 -i %s -ar 44100 -ac 2 -y %s 2>&1',
  1300. escapeshellarg($tempDir),
  1301. escapeshellarg(basename($concatFile)),
  1302. escapeshellarg(basename($mergedAudioPath))
  1303. );
  1304. exec($ffmpegCommand, $ffmpegOutput, $ffmpegReturnCode);
  1305. if ($ffmpegReturnCode !== 0 || !file_exists($mergedAudioPath)) {
  1306. logDB('anime', 'error', 'FFmpeg 合成音频失败', [
  1307. 'command' => $ffmpegCommand,
  1308. 'output' => implode("\n", $ffmpegOutput),
  1309. 'return_code' => $ffmpegReturnCode
  1310. ]);
  1311. $mergedAudioPath = null;
  1312. } else {
  1313. logDB('anime', 'info', '音频合成成功', [
  1314. 'audio_count' => count($audioFiles),
  1315. 'output_file' => $mergedAudioPath,
  1316. 'file_size' => filesize($mergedAudioPath)
  1317. ]);
  1318. }
  1319. // 清理临时音频文件和 concat 文件
  1320. foreach ($audioFiles as $audioFile) {
  1321. if (file_exists($audioFile)) {
  1322. @unlink($audioFile);
  1323. }
  1324. }
  1325. if (file_exists($concatFile)) {
  1326. @unlink($concatFile);
  1327. }
  1328. }
  1329. } else {
  1330. logDB('anime', 'warning', 'FFmpeg 未安装,跳过音频合成', []);
  1331. }
  1332. } catch (\Exception $e) {
  1333. logDB('anime', 'error', '音频合成过程异常', [
  1334. 'error' => $e->getMessage(),
  1335. 'trace' => $e->getTraceAsString()
  1336. ]);
  1337. // 音频合成失败不影响图片导出
  1338. $mergedAudioPath = null;
  1339. }
  1340. }
  1341. // 创建zip文件(使用安全的文件名)
  1342. $safeTitle = preg_replace('/[^\p{L}\p{N}\s\-_]/u', '', $episode->title ?: '未命名');
  1343. $safeTitle = trim($safeTitle) ?: '未命名';
  1344. $zipFileName = sprintf('%s_%s.zip', $safeTitle, time());
  1345. $zipFilePath = storage_path('app/temp/' . $zipFileName);
  1346. // 确保 temp 目录存在
  1347. $tempZipDir = storage_path('app/temp');
  1348. if (!file_exists($tempZipDir)) {
  1349. mkdir($tempZipDir, 0755, true);
  1350. }
  1351. $zip = new \ZipArchive();
  1352. $openResult = $zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
  1353. if ($openResult !== true) {
  1354. // 清理临时文件
  1355. array_map('unlink', $downloadedFiles);
  1356. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1357. @unlink($mergedAudioPath);
  1358. }
  1359. rmdir($tempDir);
  1360. logDB('anime', 'error', '创建ZIP文件失败', [
  1361. 'zip_path' => $zipFilePath,
  1362. 'open_result' => $openResult
  1363. ]);
  1364. Utils::throwError('20003:创建ZIP文件失败');
  1365. }
  1366. // 设置压缩级别为最快(0=不压缩,1=最快,9=最好压缩)
  1367. // 对于视频和图片,压缩效果不明显,使用最快速度
  1368. $zip->setCompressionIndex(0, \ZipArchive::CM_STORE); // 不压缩,直接存储
  1369. // 添加文件到zip
  1370. foreach ($downloadedFiles as $file) {
  1371. if (file_exists($file)) {
  1372. $zip->addFile($file, basename($file));
  1373. }
  1374. }
  1375. // 添加合成的音频文件到zip(仅普通模式)
  1376. if (!$isAceMode && $mergedAudioPath && file_exists($mergedAudioPath)) {
  1377. $zip->addFile($mergedAudioPath, 'tts.wav');
  1378. }
  1379. // 关闭 ZIP 文件
  1380. $zip->close();
  1381. // 验证 ZIP 文件是否创建成功
  1382. if (!file_exists($zipFilePath) || filesize($zipFilePath) == 0) {
  1383. // 清理临时文件
  1384. array_map('unlink', $downloadedFiles);
  1385. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1386. @unlink($mergedAudioPath);
  1387. }
  1388. rmdir($tempDir);
  1389. logDB('anime', 'error', 'ZIP文件创建后无效', ['zip_path' => $zipFilePath]);
  1390. Utils::throwError('20003:ZIP文件创建失败或文件为空');
  1391. }
  1392. // 清理临时文件
  1393. array_map('unlink', $downloadedFiles);
  1394. // 清理合成的音频文件
  1395. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1396. @unlink($mergedAudioPath);
  1397. }
  1398. rmdir($tempDir);
  1399. // 清空所有输出缓冲区,避免污染ZIP文件
  1400. while (ob_get_level() > 0) {
  1401. ob_end_clean();
  1402. }
  1403. // 返回文件下载响应
  1404. return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
  1405. } catch (\Exception $e) {
  1406. logDB('anime', 'error', '导出分集图片失败', [
  1407. 'anime_id' => $animeId,
  1408. 'episode_id' => $episodeId,
  1409. 'error' => $e->getMessage()
  1410. ]);
  1411. // 清理可能存在的临时文件
  1412. if (isset($tempDir) && file_exists($tempDir)) {
  1413. array_map('unlink', glob("$tempDir/*"));
  1414. rmdir($tempDir);
  1415. }
  1416. if (isset($zipFilePath) && file_exists($zipFilePath)) {
  1417. unlink($zipFilePath);
  1418. }
  1419. throw $e;
  1420. }
  1421. }
  1422. /**
  1423. * 监控分镜图片和音频生成任务进度(SSE)
  1424. */
  1425. public function monitorSegmentTasks(Request $request) {
  1426. // 忽略所有超时限制
  1427. set_time_limit(0);
  1428. ini_set('max_execution_time', '0');
  1429. $data = $request->all();
  1430. // 验证参数
  1431. $validator = Validator::make($data, [
  1432. 'anime_id' => 'required|string',
  1433. 'episode_id' => 'required|string',
  1434. ], [
  1435. 'anime_id.required' => '动漫ID不能为空',
  1436. 'episode_id.required' => '剧集ID不能为空',
  1437. ]);
  1438. if ($validator->fails()) {
  1439. Utils::throwError('1002:' . $validator->errors()->first());
  1440. }
  1441. $animeId = $data['anime_id'];
  1442. $episodeId = $data['episode_id'];
  1443. // 查询没有pic_task_id的分镜个数
  1444. $noPicTaskCount = DB::table('mp_episode_segments')
  1445. ->where('anime_id', $animeId)
  1446. ->where('episode_id', $episodeId)
  1447. ->where(function($query) {
  1448. $query->whereNull('pic_task_id')
  1449. ->orWhere('pic_task_id', '');
  1450. })
  1451. ->count('id');
  1452. // 获取所有分镜信息
  1453. $segments = DB::table('mp_episode_segments')
  1454. ->where('anime_id', $animeId)
  1455. ->where('episode_id', $episodeId)
  1456. ->where('pic_task_id', '!=', '')
  1457. ->orderBy('segment_number')
  1458. ->get();
  1459. // 判断是否有未完成的任务
  1460. $uncompleted_pic_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)
  1461. ->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->whereNotIn('pic_task_status', ['已完成', '失败'])->count('id');
  1462. // 获取dialogue和voice_type存在但audio_url不存在的分镜个数
  1463. $uncompleted_audio_count = DB::table('mp_episode_segments')
  1464. ->where('anime_id', $animeId)
  1465. ->where('episode_id', $episodeId)
  1466. ->where('dialogue', '<>', '')
  1467. ->whereNotNull('dialogue')
  1468. ->where('voice_type', '<>', '')
  1469. ->whereNotNull('voice_type')
  1470. ->where(function($query) {
  1471. $query->whereNull('audio_url')
  1472. ->orWhere('audio_url', '');
  1473. })
  1474. ->count('id');
  1475. if ($segments->isEmpty()) {
  1476. Utils::throwError('20003:未找到分镜任务数据');
  1477. }
  1478. $startTime = time();
  1479. $maxDuration = 900; // 15分钟超时
  1480. $checkInterval = 5; // 每5秒检查一次
  1481. // 设置 SSE 响应头并开始长连接
  1482. return response()->stream(function () use ($segments, $animeId, $episodeId, $startTime, $maxDuration, $checkInterval, $uncompleted_pic_count, $uncompleted_audio_count, $noPicTaskCount) {
  1483. if ($uncompleted_pic_count == 0 && $uncompleted_audio_count == 0) {
  1484. $completedCount = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->where('pic_task_status', '已完成')->count('id');
  1485. // 获取剧集信息之前先处理视频截止时间点
  1486. $this->handleVideoTimePointEnd();
  1487. // 获取剧集信息
  1488. $episode = DB::table('mp_anime_episodes')
  1489. ->where('anime_id', $animeId)
  1490. ->where('id', $episodeId)
  1491. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1492. ->first();
  1493. if ($episode) {
  1494. $episode = (array)$episode;
  1495. $episode['roles'] = json_decode($episode['roles'], true);
  1496. $episode['scenes'] = json_decode($episode['scenes'], true);
  1497. // 获取所有分镜信息
  1498. $allSegments = DB::table('mp_episode_segments')
  1499. ->where('anime_id', $animeId)
  1500. ->where('episode_id', $episodeId)
  1501. ->orderBy('segment_number')
  1502. ->select('*')
  1503. ->get()
  1504. ->map(function ($value) {
  1505. return (array)$value;
  1506. })->toArray();
  1507. // 按照episodeInfo的格式组织数据
  1508. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1509. $episode['acts'] = $segmentsStructure['acts'];
  1510. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1511. }
  1512. echo "data: " . json_encode([
  1513. 'type' => 'completed',
  1514. 'data' => [
  1515. 'anime_id' => $animeId,
  1516. 'episode_id' => $episodeId,
  1517. 'completed_count' => $completedCount, // 成功完成的数量
  1518. 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1519. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1520. 'total_elapsed_time' => time() - $startTime,
  1521. 'episode_info' => $episode ?? null
  1522. ]
  1523. ]) . "\n\n";
  1524. if (ob_get_level() > 0) {
  1525. ob_flush();
  1526. }
  1527. flush();
  1528. return;
  1529. }
  1530. // 发送初始任务信息
  1531. echo "data: " . json_encode([
  1532. 'type' => 'init',
  1533. 'data' => [
  1534. 'anime_id' => $animeId,
  1535. 'episode_id' => $episodeId,
  1536. 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1537. 'start_time' => $startTime,
  1538. 'max_duration' => $maxDuration
  1539. ]
  1540. ]) . "\n\n";
  1541. if (ob_get_level() > 0) {
  1542. ob_flush();
  1543. }
  1544. flush();
  1545. $completedSegments = [];
  1546. $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
  1547. $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
  1548. while (time() - $startTime < $maxDuration) {
  1549. try {
  1550. $updatedImages = []; // 记录本次循环中更新的图片信息
  1551. foreach ($segments as $segment) {
  1552. $segmentId = $segment->segment_id;
  1553. $picTaskId = $segment->pic_task_id;
  1554. $audioUrl = $segment->audio_url;
  1555. // 跳过已处理完成的分镜
  1556. if (in_array($segmentId, $processedSegments)) {
  1557. continue;
  1558. }
  1559. $picCompleted = false;
  1560. $audioCompleted = false;
  1561. $picProcessed = false;
  1562. $audioProcessed = false;
  1563. // 检查图片任务状态
  1564. if ($picTaskId) {
  1565. $picTask = DB::table('mp_generate_pic_tasks')
  1566. ->where('id', $picTaskId)
  1567. ->select('status', 'result_url', 'error_message')
  1568. ->first();
  1569. if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
  1570. $updateData = [
  1571. 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
  1572. 'updated_at' => date('Y-m-d H:i:s')
  1573. ];
  1574. $imgUrl = '';
  1575. if ($picTask->status === 'success' && !empty($picTask->result_url)) {
  1576. // 更新分镜表的图片URL
  1577. $resultUrls = json_decode($picTask->result_url, true);
  1578. $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
  1579. $updateData['img_url'] = $imgUrl;
  1580. $picCompleted = true;
  1581. } else if ($picTask->status === 'failed') {
  1582. // 失败时清空图片URL
  1583. $updateData['img_url'] = '';
  1584. }
  1585. DB::table('mp_episode_segments')
  1586. ->where('segment_id', $segmentId)
  1587. ->update($updateData);
  1588. // 记录更新的图片信息(只有未通知过的才记录)
  1589. if (!in_array($segmentId, $notifiedSegments)) {
  1590. $updatedImages[] = [
  1591. 'segment_id' => $segmentId,
  1592. 'segment_number' => $segment->segment_number,
  1593. 'img_url' => $imgUrl,
  1594. 'status' => $picTask->status === 'success' ? 'success' : 'failed'
  1595. ];
  1596. // 标记为已通知
  1597. $notifiedSegments[] = $segmentId;
  1598. }
  1599. $picProcessed = true;
  1600. }
  1601. }
  1602. // 检查音频状态
  1603. // 获取分镜的dialogue、voice_type和audio_url信息
  1604. $segmentInfo = DB::table('mp_episode_segments')
  1605. ->where('segment_id', $segmentId)
  1606. ->select('dialogue', 'voice_type', 'audio_url')
  1607. ->first();
  1608. $needAudio = false;
  1609. $currentAudioUrl = '';
  1610. if ($segmentInfo) {
  1611. $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
  1612. $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
  1613. $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
  1614. // 如果有对话和音色类型,则需要音频
  1615. if (!empty($dialogue) && !empty($voiceType)) {
  1616. $needAudio = true;
  1617. }
  1618. }
  1619. // 判断音频状态
  1620. if ($needAudio) {
  1621. // 需要音频的情况下,检查audio_url是否有值
  1622. if (!empty($currentAudioUrl)) {
  1623. $audioCompleted = true;
  1624. $audioProcessed = true;
  1625. } else {
  1626. // 需要音频但还没有,继续等待
  1627. $audioCompleted = false;
  1628. $audioProcessed = false;
  1629. }
  1630. } else {
  1631. // 不需要音频,直接标记为已处理
  1632. $audioCompleted = false;
  1633. $audioProcessed = true;
  1634. }
  1635. // 如果图片和音频都成功完成,标记为已完成
  1636. if ($picCompleted && ($audioCompleted || !$needAudio)) {
  1637. $completedSegments[] = $segmentId;
  1638. }
  1639. // 如果图片和音频都已处理完成(成功或失败),标记为已处理
  1640. if ($picProcessed && $audioProcessed) {
  1641. $processedSegments[] = $segmentId;
  1642. }
  1643. }
  1644. // 如果有图片更新,发送具体的图片更新信息
  1645. if (!empty($updatedImages)) {
  1646. echo "data: " . json_encode([
  1647. 'type' => 'update',
  1648. 'data' => [
  1649. 'anime_id' => $animeId,
  1650. 'episode_id' => $episodeId,
  1651. 'updated_images' => $updatedImages,
  1652. 'completed_count' => count($completedSegments), // 成功完成的数量
  1653. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1654. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1655. 'elapsed_time' => time() - $startTime,
  1656. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1657. ]
  1658. ]) . "\n\n";
  1659. if (ob_get_level() > 0) {
  1660. ob_flush();
  1661. }
  1662. flush();
  1663. }
  1664. // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
  1665. if (count($processedSegments) === count($segments)) {
  1666. // 获取剧集信息之前先处理视频截止时间点
  1667. $this->handleVideoTimePointEnd();
  1668. // 获取剧集信息
  1669. $episode = DB::table('mp_anime_episodes')
  1670. ->where('anime_id', $animeId)
  1671. ->where('id', $episodeId)
  1672. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1673. ->first();
  1674. if ($episode) {
  1675. $episode = (array)$episode;
  1676. $episode['roles'] = json_decode($episode['roles'], true);
  1677. $episode['scenes'] = json_decode($episode['scenes'], true);
  1678. // 获取所有分镜信息
  1679. $allSegments = DB::table('mp_episode_segments')
  1680. ->where('anime_id', $animeId)
  1681. ->where('episode_id', $episodeId)
  1682. ->orderBy('segment_number')
  1683. ->select('*')
  1684. ->get()
  1685. ->map(function ($value) {
  1686. return (array)$value;
  1687. })->toArray();
  1688. // 按照episodeInfo的格式组织数据
  1689. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1690. $episode['acts'] = $segmentsStructure['acts'];
  1691. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1692. }
  1693. echo "data: " . json_encode([
  1694. 'type' => 'completed',
  1695. 'data' => [
  1696. 'anime_id' => $animeId,
  1697. 'episode_id' => $episodeId,
  1698. 'completed_count' => count($completedSegments), // 成功完成的数量
  1699. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1700. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1701. 'total_elapsed_time' => time() - $startTime,
  1702. 'episode_info' => $episode ?? null
  1703. ]
  1704. ]) . "\n\n";
  1705. if (ob_get_level() > 0) ob_flush();
  1706. flush();
  1707. break;
  1708. }
  1709. // 检查是否超时
  1710. if (time() - $startTime >= $maxDuration) {
  1711. break;
  1712. }
  1713. sleep($checkInterval);
  1714. } catch (\Exception $e) {
  1715. echo "data: " . json_encode([
  1716. 'type' => 'error',
  1717. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1718. 'elapsed_time' => time() - $startTime,
  1719. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1720. ]) . "\n\n";
  1721. if (ob_get_level() > 0) ob_flush();
  1722. flush();
  1723. if (time() - $startTime >= $maxDuration) {
  1724. break;
  1725. }
  1726. sleep($checkInterval);
  1727. }
  1728. }
  1729. // 超时处理
  1730. if (time() - $startTime >= $maxDuration) {
  1731. echo "data: " . json_encode([
  1732. 'type' => 'time_out',
  1733. 'message' => '分镜任务监控已超时15分钟,停止状态查询',
  1734. 'data' => [
  1735. 'anime_id' => $animeId,
  1736. 'episode_id' => $episodeId,
  1737. 'completed_count' => count($completedSegments), // 成功完成的数量
  1738. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1739. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1740. 'total_elapsed_time' => time() - $startTime,
  1741. 'timeout_duration' => $maxDuration
  1742. ]
  1743. ]) . "\n\n";
  1744. if (ob_get_level() > 0) ob_flush();
  1745. flush();
  1746. }
  1747. }, 200, [
  1748. 'Content-Type' => 'text/event-stream',
  1749. 'Cache-Control' => 'no-cache',
  1750. 'Connection' => 'keep-alive',
  1751. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1752. ]);
  1753. }
  1754. /**
  1755. * 音频试听接口
  1756. * 创建音频任务并返回结果
  1757. */
  1758. public function previewAudio(Request $request) {
  1759. $data = $request->all();
  1760. $result = $this->AnimeService->previewAudio($data);
  1761. return $this->success($result);
  1762. }
  1763. // 角色库
  1764. public function globalProducts(Request $request) {
  1765. $data = $request->all();
  1766. $result = $this->AnimeService->globalProducts($data);
  1767. return $this->success($result);
  1768. }
  1769. // 新建角色
  1770. public function createProduct(Request $request) {
  1771. $data = $request->all();
  1772. $result = $this->AnimeService->createProduct($data);
  1773. return $this->success($result);
  1774. }
  1775. // 编辑角色
  1776. public function editProduct(Request $request) {
  1777. $data = $request->all();
  1778. $result = $this->AnimeService->editProduct($data);
  1779. return $this->success(['success' => $result ? 1 : 0]);
  1780. }
  1781. // 获取角色版本历史
  1782. public function getProductVersions(Request $request) {
  1783. $data = $request->all();
  1784. $result = $this->AnimeService->getProductVersions($data);
  1785. return $this->success($result);
  1786. }
  1787. // 恢复到指定版本
  1788. public function restoreProductVersion(Request $request) {
  1789. $data = $request->all();
  1790. $result = $this->AnimeService->restoreProductVersion($data);
  1791. return $this->success(['success' => $result ? 1 : 0]);
  1792. }
  1793. // 删除角色
  1794. public function deleteProduct(Request $request) {
  1795. $data = $request->all();
  1796. $result = $this->AnimeService->deleteProduct($data);
  1797. return $this->success(['success' => $result ? 1 : 0]);
  1798. }
  1799. // 新建文件夹
  1800. public function createFolder(Request $request) {
  1801. $data = $request->all();
  1802. $result = $this->AnimeService->createFolder($data);
  1803. return $this->success(['id' => $result]);
  1804. }
  1805. // 重命名文件夹或角色
  1806. public function renameFolder(Request $request) {
  1807. $data = $request->all();
  1808. $result = $this->AnimeService->renameFolder($data);
  1809. return $this->success(['success' => $result ? 1 : 0]);
  1810. }
  1811. // 移动角色或文件夹
  1812. public function moveProductOrFolder(Request $request) {
  1813. $data = $request->all();
  1814. $result = $this->AnimeService->moveProductOrFolder($data);
  1815. return $this->success(['success' => $result ? 1 : 0]);
  1816. }
  1817. // 获取文件夹路径(面包屑导航)
  1818. public function getFolderPath(Request $request) {
  1819. $data = $request->all();
  1820. $result = $this->AnimeService->getFolderPath($data);
  1821. return $this->success($result);
  1822. }
  1823. // 生成三视图
  1824. public function generateThreeView(Request $request) {
  1825. // 忽略所有超时限制
  1826. set_time_limit(0);
  1827. ini_set('max_execution_time', '0');
  1828. $data = $request->all();
  1829. $result = $this->AnimeService->generateThreeView($data);
  1830. return $this->success($result);
  1831. }
  1832. // 推送资产或文件夹到目标位置
  1833. public function pushProductOrFolder(Request $request) {
  1834. $data = $request->all();
  1835. $result = $this->AnimeService->pushProductOrFolder($data);
  1836. return $this->success($result);
  1837. }
  1838. /**
  1839. * 保存剧本资产关联关系
  1840. * @param Request $request
  1841. * @return mixed
  1842. */
  1843. public function saveScriptProducts(Request $request) {
  1844. // 忽略所有超时限制
  1845. set_time_limit(0);
  1846. ini_set('max_execution_time', '0');
  1847. $data = $request->all();
  1848. $result = $this->AnimeService->saveScriptProducts($data);
  1849. // 判断是否是 SSE 流(Generator)
  1850. if ($result instanceof \Generator) {
  1851. // 返回 SSE 响应
  1852. return response()->stream(function () use ($result) {
  1853. // 设置不缓冲输出
  1854. if (ob_get_level()) {
  1855. ob_end_flush();
  1856. }
  1857. foreach ($result as $event) {
  1858. echo $event;
  1859. if (ob_get_level()) {
  1860. ob_flush();
  1861. }
  1862. flush();
  1863. }
  1864. }, 200, [
  1865. 'Content-Type' => 'text/event-stream',
  1866. 'Cache-Control' => 'no-cache',
  1867. 'Connection' => 'keep-alive',
  1868. 'X-Accel-Buffering' => 'no'
  1869. ]);
  1870. }
  1871. // 普通JSON响应
  1872. return $this->success($result);
  1873. }
  1874. /**
  1875. * 获取剧本关联的资产列表
  1876. * @param Request $request
  1877. * @return mixed
  1878. */
  1879. public function getScriptProducts(Request $request) {
  1880. $data = $request->all();
  1881. $result = $this->AnimeService->getScriptProducts($data);
  1882. return $this->success($result);
  1883. }
  1884. private function handleVideoTimePointEnd() {
  1885. // 处理音频时长,循环查询dub_video_task_queue列表中的任务
  1886. $queueLength = Redis::llen('dub_video_task_queue');
  1887. if ($queueLength > 0) {
  1888. $processedTaskIds = []; // 记录已处理的任务ID
  1889. // 遍历队列中的所有任务
  1890. for ($i = 0; $i < $queueLength; $i++) {
  1891. $dubTaskId = Redis::lindex('dub_video_task_queue', $i);
  1892. if (!$dubTaskId) continue;
  1893. // 查询任务状态
  1894. $dubTask = DB::table('mp_dub_video_tasks')
  1895. ->where('id', $dubTaskId)
  1896. ->first();
  1897. if (!$dubTask) {
  1898. // 任务不存在,标记为需要删除
  1899. $processedTaskIds[] = $dubTaskId;
  1900. continue;
  1901. }
  1902. // 如果任务状态是已完成
  1903. if ($dubTask->generate_status === '执行成功') {
  1904. // 获取对应的分镜信息
  1905. $segment = DB::table('mp_episode_segments')
  1906. ->where('segment_id', $dubTask->alias_segment_id)
  1907. ->first();
  1908. // 如果分镜存在且audio_duration大于0
  1909. if ($segment && isset($segment->audio_duration) && $segment->audio_duration > 0) {
  1910. // 更新video_time_point_end字段
  1911. DB::table('mp_episode_segments')
  1912. ->where('segment_id', $dubTask->alias_segment_id)
  1913. ->update([
  1914. 'video_time_point_end' => $segment->audio_duration,
  1915. 'updated_at' => date('Y-m-d H:i:s')
  1916. ]);
  1917. dLog('anime')->info('更新分镜视频截止时间点', [
  1918. 'task_id' => $dubTaskId,
  1919. 'segment_id' => $dubTask->alias_segment_id,
  1920. 'audio_duration' => $segment->audio_duration
  1921. ]);
  1922. }
  1923. // 标记为需要从队列中删除
  1924. $processedTaskIds[] = $dubTaskId;
  1925. }
  1926. }
  1927. // 从Redis列表中删除已处理的任务ID
  1928. foreach ($processedTaskIds as $taskId) {
  1929. Redis::lrem('dub_video_task_queue', 0, $taskId);
  1930. }
  1931. }
  1932. }
  1933. // 确认片段
  1934. public function confirmActs(Request $request) {
  1935. $data = $request->all();
  1936. $result = $this->AnimeService->confirmActs($data);
  1937. return $this->success($result);
  1938. }
  1939. public function saveActVideoGenerateParams(Request $request) {
  1940. $data = $request->all();
  1941. $result = $this->AnimeService->saveActVideoGenerateParams($data);
  1942. return $this->success(['success' => $result ? 1 : 0]);
  1943. }
  1944. public function createActVideoTask(Request $request) {
  1945. $uid = Site::getUid();
  1946. // 忽略所有超时限制
  1947. set_time_limit(0);
  1948. ini_set('max_execution_time', '0');
  1949. $data = $request->all();
  1950. // 创建视频生成任务
  1951. $result = $this->AnimeService->createActVideoTask($data);
  1952. $taskId = $result['task_id'];
  1953. // 设置 SSE 响应头
  1954. return response()->stream(function () use ($taskId, $result, $uid) {
  1955. // 立即发送 init 消息
  1956. echo "data: " . json_encode([
  1957. 'type' => 'init',
  1958. 'data' => $result
  1959. ]) . "\n\n";
  1960. if (ob_get_level() > 0) ob_flush();
  1961. flush();
  1962. $startTime = time();
  1963. $maxDuration = 3600; // 超时设置
  1964. $checkInterval = 5; // 检查间隔
  1965. $lastQueueMessageTime = time(); // 记录上次发送队列消息的时间
  1966. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  1967. while (time() - $startTime < $maxDuration) {
  1968. try {
  1969. // 查询任务状态
  1970. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  1971. if (!$task) {
  1972. echo "data: " . json_encode([
  1973. 'type' => 'error',
  1974. 'message' => '任务不存在'
  1975. ]) . "\n\n";
  1976. if (ob_get_level() > 0) ob_flush();
  1977. flush();
  1978. break;
  1979. }
  1980. // 如果任务完成(成功或失败),结束连接
  1981. if (in_array($task->status, [
  1982. 'success',
  1983. 'failed'
  1984. ])) {
  1985. echo "data: " . json_encode([
  1986. 'type' => 'completed',
  1987. 'data' => [
  1988. 'task_id' => $task->id,
  1989. 'status' => $task->status,
  1990. 'video_url' => $task->compressed_url ?: $task->result_url,
  1991. 'origin_video_url' => $task->result_url,
  1992. 'last_frame_url' => $task->last_frame_url,
  1993. 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : ''
  1994. ]
  1995. ]) . "\n\n";
  1996. if (ob_get_level() > 0) ob_flush();
  1997. flush();
  1998. break;
  1999. }
  2000. // 每分钟发送一次队列状态消息
  2001. $currentTime = time();
  2002. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  2003. echo "data: " . json_encode([
  2004. 'type' => 'queue',
  2005. 'data' => [
  2006. 'task_id' => $task->id,
  2007. 'status' => $task->status,
  2008. 'elapsed_time' => $currentTime - $startTime,
  2009. 'message' => '任务正在队列中执行...'
  2010. ]
  2011. ]) . "\n\n";
  2012. if (ob_get_level() > 0) ob_flush();
  2013. flush();
  2014. $lastQueueMessageTime = $currentTime;
  2015. }
  2016. sleep($checkInterval);
  2017. } catch (\Exception $e) {
  2018. echo "data: " . json_encode([
  2019. 'type' => 'error',
  2020. 'message' => '查询任务状态失败: ' . $e->getMessage()
  2021. ]) . "\n\n";
  2022. if (ob_get_level() > 0) ob_flush();
  2023. flush();
  2024. sleep($checkInterval);
  2025. }
  2026. }
  2027. // 超时处理
  2028. if (time() - $startTime >= $maxDuration) {
  2029. echo "data: " . json_encode([
  2030. 'type' => 'time_out',
  2031. 'message' => '任务执行超时,请稍后查询任务状态',
  2032. 'data' => [
  2033. 'task_id' => $taskId
  2034. ]
  2035. ]) . "\n\n";
  2036. if (ob_get_level() > 0) ob_flush();
  2037. flush();
  2038. }
  2039. }, 200, [
  2040. 'Content-Type' => 'text/event-stream',
  2041. 'Cache-Control' => 'no-cache',
  2042. 'Connection' => 'keep-alive',
  2043. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  2044. ]);
  2045. }
  2046. /**
  2047. * 批量生成片段视频
  2048. */
  2049. public function batchSetActVideos(Request $request) {
  2050. // 忽略所有超时限制
  2051. set_time_limit(0);
  2052. ini_set('max_execution_time', '0');
  2053. $data = $request->all();
  2054. // 验证参数
  2055. $validator = Validator::make($data, [
  2056. 'anime_id' => 'required|string',
  2057. 'episode_id' => 'required|integer',
  2058. ], [
  2059. 'anime_id.required' => '动漫对话ID不能为空',
  2060. 'episode_id.required' => '剧集ID不能为空',
  2061. 'episode_id.integer' => '剧集ID必须是整数',
  2062. ]);
  2063. if ($validator->fails()) {
  2064. return response()->stream(function () use ($validator) {
  2065. echo "data: " . json_encode([
  2066. 'type' => 'error',
  2067. 'message' => $validator->errors()->first()
  2068. ]) . "\n\n";
  2069. if (ob_get_level() > 0) {
  2070. ob_flush();
  2071. }
  2072. flush();
  2073. }, 200, [
  2074. 'Content-Type' => 'text/event-stream',
  2075. 'Cache-Control' => 'no-cache',
  2076. 'Connection' => 'keep-alive',
  2077. 'X-Accel-Buffering' => 'no',
  2078. ]);
  2079. }
  2080. $animeId = $data['anime_id'];
  2081. $episodeId = $data['episode_id'];
  2082. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  2083. if (!$episode) {
  2084. return response()->stream(function () {
  2085. echo "data: " . json_encode([
  2086. 'type' => 'error',
  2087. 'message' => '分集不存在'
  2088. ]) . "\n\n";
  2089. if (ob_get_level() > 0) {
  2090. ob_flush();
  2091. }
  2092. flush();
  2093. }, 200, [
  2094. 'Content-Type' => 'text/event-stream',
  2095. 'Cache-Control' => 'no-cache',
  2096. 'Connection' => 'keep-alive',
  2097. 'X-Accel-Buffering' => 'no',
  2098. ]);
  2099. }
  2100. $episodeNumber = $episode->episode_number;
  2101. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  2102. $generate_audio = getProp($data, 'generate_audio', 1);
  2103. // 合并角色、场景和道具作为products,统一字段名为product_name
  2104. $products = [];
  2105. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  2106. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  2107. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  2108. // 处理角色数组
  2109. foreach ($roles as $role) {
  2110. $product = $role;
  2111. // 将role字段重命名为product_name
  2112. if (isset($product['role'])) {
  2113. $product['product_name'] = $product['role'];
  2114. unset($product['role']);
  2115. }
  2116. $product['product'] = 1; // 标记类型为角色
  2117. $products[] = $product;
  2118. }
  2119. // 处理场景数组
  2120. foreach ($scenes as $scene) {
  2121. $product = $scene;
  2122. // 将scene字段重命名为product_name
  2123. if (isset($product['scene'])) {
  2124. $product['product_name'] = $product['scene'];
  2125. unset($product['scene']);
  2126. }
  2127. $product['product'] = 2; // 标记类型为场景
  2128. $products[] = $product;
  2129. }
  2130. // 处理道具数组
  2131. foreach ($props as $prop) {
  2132. $product = $prop;
  2133. // 将prop字段重命名为product_name
  2134. if (isset($product['prop'])) {
  2135. $product['product_name'] = $product['prop'];
  2136. unset($product['prop']);
  2137. }
  2138. $product['product'] = 3; // 标记类型为道具
  2139. $products[] = $product;
  2140. }
  2141. // 处理视频模型(在循环外统一处理)
  2142. // $model = getProp($data, 'model');
  2143. // if (!$model) {
  2144. // // 用户没有输入,从episode表获取
  2145. // $model = getProp($episode, 'video_model');
  2146. // if (!$model) {
  2147. // // episode表也没有,使用默认值
  2148. // $model = 'zhizhen-20';
  2149. // }
  2150. // }
  2151. $model = 'zhizhen-20'; // 使用默认值
  2152. // 验证模型是否在可用模型表中
  2153. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2154. $model = 'zhizhen-20';
  2155. }
  2156. // 获取所有分镜信息
  2157. $acts = DB::table('mp_episode_segments')
  2158. ->where('anime_id', $animeId)
  2159. ->where('episode_id', $episodeId)
  2160. ->orderBy('act_number')
  2161. ->get();
  2162. if ($acts->isEmpty()) {
  2163. return response()->stream(function () {
  2164. echo "data: " . json_encode([
  2165. 'type' => 'error',
  2166. 'message' => '未找到分镜数据'
  2167. ]) . "\n\n";
  2168. if (ob_get_level() > 0) ob_flush();
  2169. flush();
  2170. }, 200, [
  2171. 'Content-Type' => 'text/event-stream',
  2172. 'Cache-Control' => 'no-cache',
  2173. 'Connection' => 'keep-alive',
  2174. 'X-Accel-Buffering' => 'no',
  2175. ]);
  2176. }
  2177. foreach($acts as $act) {
  2178. $videoDuration = $act->act_duration;
  2179. if (!$videoDuration || $videoDuration <= 0) {
  2180. return response()->stream(function () {
  2181. echo "data: " . json_encode([
  2182. 'type' => 'error',
  2183. 'message' => '请检查是否有时长为空的片段'
  2184. ]) . "\n\n";
  2185. if (ob_get_level() > 0) ob_flush();
  2186. flush();
  2187. }, 200, [
  2188. 'Content-Type' => 'text/event-stream',
  2189. 'Cache-Control' => 'no-cache',
  2190. 'Connection' => 'keep-alive',
  2191. 'X-Accel-Buffering' => 'no',
  2192. ]);
  2193. }
  2194. }
  2195. // 批量创建视频任务
  2196. $taskIds = [];
  2197. $actTasks = [];
  2198. foreach ($acts as $act) {
  2199. try {
  2200. // 检查视频任务正在生成中或当前状态为视频
  2201. if ($act->video_task_status === '生成中') {
  2202. $actTasks[] = [
  2203. 'act_id' => $act->id,
  2204. 'task_id' => $act->video_task_id,
  2205. 'act_number' => $act->act_number,
  2206. 'act_content' => $act->act_content,
  2207. 'audio_duration' => $act->audio_duration,
  2208. ];
  2209. continue;
  2210. }
  2211. if ((int)$act->current_type === 2) {
  2212. continue;
  2213. }
  2214. // 获取分镜内容
  2215. $actContent = $act->act_show_content ?: '';
  2216. // 构建完整的提示词
  2217. $processResult = $this->AnimeService->processActContentWithProducts($actContent, $products);
  2218. $fullPrompt = $processResult['content'];
  2219. $reference_images = $processResult['reference_images'];
  2220. $videoDuration = $act->act_duration;
  2221. // 构建视频生成参数
  2222. $videoParams = [
  2223. 'model' => $model,
  2224. 'alias_act_id' => $act->id,
  2225. 'prompt' => $fullPrompt,
  2226. 'video_duration' => $videoDuration,
  2227. 'video_resolution' => '720P',
  2228. 'seed' => -1,
  2229. 'ratio' => $ratio,
  2230. 'generate_audio' => (int)$generate_audio === 0 ? false : true,
  2231. 'draft' => false,
  2232. 'watermark' => false,
  2233. 'camera_fixed' => false,
  2234. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  2235. ];
  2236. // 如果分镜有图片,作为首帧
  2237. $hasImage = !empty($act->img_url);
  2238. $hasVideo = !empty($act->video_url);
  2239. if ($hasImage) {
  2240. $videoParams['first_frame_url'] = $act->img_url;
  2241. }
  2242. // 构建content数组
  2243. $videoParams['content'] = [
  2244. [
  2245. 'type' => 'text',
  2246. 'text' => $videoParams['prompt'],
  2247. ]
  2248. ];
  2249. // 如果有首帧图片,添加到content中
  2250. if ($hasImage) {
  2251. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  2252. $videoParams['content'][] = [
  2253. 'type' => 'image_url',
  2254. 'image_url' => [
  2255. 'url' => $videoParams['first_frame_url'],
  2256. ],
  2257. 'role' => 'reference_image',
  2258. ];
  2259. }else {
  2260. $videoParams['content'][] = [
  2261. 'type' => 'image_url',
  2262. 'image_url' => [
  2263. 'url' => $videoParams['first_frame_url'],
  2264. ],
  2265. 'role' => 'first_frame',
  2266. ];
  2267. }
  2268. }
  2269. // 获取配音音频URL和时长
  2270. $audioUrl = $act->audio_url ?? '';
  2271. $audioDuration = $act->audio_duration ?? 0;
  2272. // 音频传入的前提:必须有至少一张图片或一个视频
  2273. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  2274. // 根据模型选择不同的视频生成方法
  2275. if (strpos($model, 'jimeng') !== false) {
  2276. // 即梦模型参数调整
  2277. $videoParams['video_duration'] = $videoDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  2278. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  2279. unset($videoParams['ratio']);
  2280. unset($videoParams['content']); // 即梦不使用content格式
  2281. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  2282. } elseif (strpos($model, 'kling') !== false) {
  2283. // Keling模型参数调整
  2284. $videoParams['video_duration'] = max(3, min(15, ceil($videoDuration))); // Keling支持3-15秒
  2285. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  2286. unset($videoParams['ratio']);
  2287. unset($videoParams['content']); // Keling不使用content格式
  2288. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  2289. } elseif (strpos($model, 'zhizhen') !== false) {
  2290. // 构建统一API参数
  2291. $unifiedParams = [
  2292. 'model_code' => $model,
  2293. 'alias_act_id' => $act->id,
  2294. 'prompt' => trim($fullPrompt),
  2295. 'video_duration' => $videoDuration,
  2296. 'video_resolution' => strtolower($videoParams['video_resolution']),
  2297. 'video_ratio' => $ratio,
  2298. 'seed' => -1,
  2299. ];
  2300. // 构建parameters参数
  2301. $parameters = [
  2302. 'seconds' => $unifiedParams['video_duration'],
  2303. 'resolution' => $unifiedParams['video_resolution'],
  2304. 'ratio' => $ratio,
  2305. // 'video_mode' => 'multi_image',
  2306. // 'mode' => 'multi_image',
  2307. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  2308. ];
  2309. $hasImage = false;
  2310. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  2311. if ($hasImage) {
  2312. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  2313. if (isset($videoParams['tail_frame_url'])) {
  2314. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  2315. }
  2316. }
  2317. if ($reference_images) {
  2318. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  2319. $reference_images = $this->AIImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  2320. $parameters['reference_images'] = $reference_images;
  2321. $parameters['video_mode'] = 'multi_image';
  2322. $parameters['mode'] = 'multi_image';
  2323. }
  2324. $unifiedParams['parameters'] = $parameters;
  2325. // 调用统一API创建任务
  2326. $task = $this->AIVideoGenerationService->createUnifiedApiTask($unifiedParams);
  2327. } else {
  2328. // Seedance模型(默认)
  2329. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  2330. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  2331. // 添加配音音频到content中
  2332. $videoParams['content'][] = [
  2333. 'type' => 'audio_url',
  2334. 'audio_url' => [
  2335. 'url' => $audioUrl,
  2336. ],
  2337. 'role' => 'reference_audio',
  2338. ];
  2339. // 优化提示词,增加音频相关描述
  2340. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  2341. $videoParams['prompt'] = $audioPrompt;
  2342. $videoParams['content'][0]['text'] = $audioPrompt;
  2343. } else if ($videoDuration) {
  2344. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  2345. $videoParams['video_duration'] = max(4, min(12, ceil($videoDuration))); // seedance支持2-12s
  2346. }
  2347. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  2348. }
  2349. $taskIds[] = $task->id;
  2350. // 更新分镜表的视频任务信息
  2351. DB::table('mp_episode_segments')
  2352. ->where('id', $act->id)
  2353. ->update([
  2354. 'video_task_id' => $task->id,
  2355. 'video_task_status' => '生成中',
  2356. 'updated_at' => date('Y-m-d H:i:s')
  2357. ]);
  2358. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  2359. if ((int)$episodeNumber === 1 && (int)$act->act_number === 1) {
  2360. Redis::sadd('anime_act_first_frame_urls', $act->id);
  2361. }
  2362. $actTasks[] = [
  2363. 'act_id' => $act->id,
  2364. 'task_id' => $task->id,
  2365. 'act_number' => $act->act_number,
  2366. 'content' => $fullPrompt,
  2367. 'audio_duration' => $act->audio_duration,
  2368. ];
  2369. } catch (\Exception $e) {
  2370. $logData = [
  2371. 'act_id' => $act->id,
  2372. 'anime_id' => $animeId,
  2373. 'error' => $e->getMessage(),
  2374. ];
  2375. dLog('anime')->error('创建分镜视频任务失败', $logData);
  2376. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  2377. continue;
  2378. }
  2379. }
  2380. if (empty($taskIds)) {
  2381. // 没有任务时,获取完整剧集信息进行验证
  2382. $episode = $this->AnimeService->episodeInfoForAce([
  2383. 'anime_id' => $animeId,
  2384. 'episode_id' => $episodeId
  2385. ]);
  2386. // 检查所有片段是否都已生成视频且current_type=2
  2387. $allActsValid = true;
  2388. $invalidActs = [];
  2389. $total_tasks_count = count($episode['acts']);
  2390. foreach ($episode['acts'] as $act) {
  2391. $videoUrl = getProp($act, 'video_url');
  2392. $currentType = getProp($act, 'current_type');
  2393. // 检查视频是否已生成
  2394. if (!$videoUrl) {
  2395. $allActsValid = false;
  2396. $invalidActs[] = [
  2397. 'act_number' => getProp($act, 'act_number'),
  2398. 'reason' => '视频未生成'
  2399. ];
  2400. continue;
  2401. }
  2402. // 检查current_type是否为2
  2403. if ($currentType != 2) {
  2404. $allActsValid = false;
  2405. $invalidActs[] = [
  2406. 'act_number' => getProp($act, 'act_number'),
  2407. 'reason' => '当前不是视频模式'
  2408. ];
  2409. }
  2410. }
  2411. // 如果所有分镜都满足条件,使用SSE格式返回完成状态
  2412. if ($allActsValid) {
  2413. return response()->stream(function () use ($episode, $total_tasks_count) {
  2414. echo "data: " . json_encode([
  2415. 'type' => 'completed',
  2416. 'total_tasks_count' => $total_tasks_count,
  2417. 'completed_tasks_count' => $total_tasks_count,
  2418. 'success_tasks_count' => $total_tasks_count,
  2419. 'episode' => $episode
  2420. ]) . "\n\n";
  2421. if (ob_get_level() > 0) ob_flush();
  2422. flush();
  2423. }, 200, [
  2424. 'Content-Type' => 'text/event-stream',
  2425. 'Cache-Control' => 'no-cache',
  2426. 'Connection' => 'keep-alive',
  2427. 'X-Accel-Buffering' => 'no',
  2428. ]);
  2429. } else {
  2430. // 有未完成或不满足条件的分镜,使用SSE格式报错
  2431. $errorMsg = '存在未完成的片段:' . "\n";
  2432. foreach ($invalidActs as $invalid) {
  2433. $errorMsg .= "分镜{$invalid['act_number']}:{$invalid['reason']}\n";
  2434. }
  2435. return response()->stream(function () use ($errorMsg) {
  2436. echo "data: " . json_encode([
  2437. 'type' => 'error',
  2438. 'message' => trim($errorMsg)
  2439. ]) . "\n\n";
  2440. if (ob_get_level() > 0) ob_flush();
  2441. flush();
  2442. }, 200, [
  2443. 'Content-Type' => 'text/event-stream',
  2444. 'Cache-Control' => 'no-cache',
  2445. 'Connection' => 'keep-alive',
  2446. 'X-Accel-Buffering' => 'no',
  2447. ]);
  2448. }
  2449. }
  2450. // 保存模型到episode表
  2451. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  2452. 'video_model' => $model,
  2453. 'updated_at' => date('Y-m-d H:i:s')
  2454. ]);
  2455. // 记录开始时间(包含创建任务的时间)
  2456. $startTime = time();
  2457. $maxDuration = 7200;
  2458. $uid = Site::getUid();
  2459. // 设置 SSE 响应头并开始长连接
  2460. return response()->stream(function () use ($taskIds, $actTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  2461. $checkInterval = 10; // 每10秒检查一次
  2462. // 初始化任务数组
  2463. $totalTasks = $taskIds; // 所有任务ID
  2464. $completeTasks = []; // 已完成的任务ID(包含失败)
  2465. $successTasks = []; // 成功的任务ID
  2466. // 发送初始任务创建信息
  2467. echo "data: " . json_encode([
  2468. 'type' => 'init',
  2469. 'total_tasks_count' => count($totalTasks),
  2470. 'completed_tasks_count' => count($completeTasks),
  2471. 'success_tasks_count' => count($successTasks)
  2472. ]) . "\n\n";
  2473. if (ob_get_level() > 0) ob_flush();
  2474. flush();
  2475. while (time() - $startTime < $maxDuration) {
  2476. try {
  2477. $hasUpdate = false; // 标记是否有更新
  2478. // 获取所有任务的最新状态
  2479. foreach ($totalTasks as $taskId) {
  2480. // 如果任务已经在完成列表中,跳过
  2481. if (in_array($taskId, $completeTasks)) {
  2482. continue;
  2483. }
  2484. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  2485. if (!$task) {
  2486. continue;
  2487. }
  2488. // // 如果任务还在处理中,查询最新状态
  2489. // if ($task->status === 'processing') {
  2490. // // 根据任务类型查询不同的状态
  2491. // if ($task->api_type === 'jimeng') {
  2492. // $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  2493. // } elseif ($task->api_type === 'keling') {
  2494. // $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  2495. // } elseif ($task->api_type === 'zzengine') {
  2496. // $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
  2497. // } else {
  2498. // $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  2499. // }
  2500. // if (isset($statusResult['status'])) {
  2501. // // 更新任务状态
  2502. // $task->update([
  2503. // 'status' => $statusResult['status'],
  2504. // 'result_json' => $statusResult['result_json'] ?? [],
  2505. // 'result_url' => $statusResult['result_url'] ?? null,
  2506. // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  2507. // 'error_message' => $statusResult['error_message'] ?? null,
  2508. // 'completed_at' => in_array($statusResult['status'], [
  2509. // 'success',
  2510. // 'failed'
  2511. // ]) ? now() : null
  2512. // ]);
  2513. // // 如果任务成功,更新分镜表
  2514. // if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  2515. // try {
  2516. // DB::beginTransaction();
  2517. // $now = date('Y-m-d H:i:s');
  2518. // // 获取分镜ID
  2519. // $actId = null;
  2520. // foreach ($actTasks as $actTask) {
  2521. // if ($actTask['task_id'] == $taskId) {
  2522. // $actId = $actTask['act_id'];
  2523. // $content = $actTask['content'];
  2524. // $audio_duration = $actTask['audio_duration'];
  2525. // break;
  2526. // }
  2527. // }
  2528. // if ($actId) {
  2529. // // 更新分镜表
  2530. // $actUpdateData = [
  2531. // 'origin_video_url' => $statusResult['result_url'],
  2532. // 'video_task_status' => '已完成',
  2533. // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  2534. // 'current_type' => 2,
  2535. // 'updated_at' => $now
  2536. // ];
  2537. // $compressed_video_url = compressVideo($statusResult['result_url']);
  2538. // $actUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  2539. // // 只有当video_duration存在且大于0时才更新
  2540. // if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  2541. // $actUpdateData['video_duration'] = $statusResult['video_duration'];
  2542. // $actUpdateData['video_time_point_start'] = 0;
  2543. // $actUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  2544. // }
  2545. // $updateResult = DB::table('mp_episode_segments')
  2546. // ->where('id', $actId)
  2547. // ->update($actUpdateData);
  2548. // if ($updateResult) {
  2549. // // 更新分镜视频成功后新增对话记录
  2550. // // 获取参考图记录
  2551. // $reference_images = getProp($task, 'ref_image_url');
  2552. // if (!$reference_images) $reference_images = json_encode([], 256);
  2553. // $records = [
  2554. // [
  2555. // 'uid' => $uid,
  2556. // 'anime_id' => $animeId,
  2557. // 'sequence' => $episodeNumber,
  2558. // 'role' => 'user',
  2559. // 'content' => '片段转视频',
  2560. // 'act_id' => $actId,
  2561. // 'video_url' => '',
  2562. // 'created_at' => $now,
  2563. // 'updated_at' => $now
  2564. // ],
  2565. // [
  2566. // 'uid' => $uid,
  2567. // 'anime_id' => $animeId,
  2568. // 'sequence' => $episodeNumber,
  2569. // 'role' => 'assistant',
  2570. // 'content' => $content ?? '',
  2571. // 'act_id' => $actId,
  2572. // 'video_url' => $statusResult['result_url'],
  2573. // 'reference_images' => $reference_images,
  2574. // 'created_at' => $now,
  2575. // 'updated_at' => $now
  2576. // ]
  2577. // ];
  2578. // DB::table('mp_anime_records')->insert($records);
  2579. // }
  2580. // }
  2581. // DB::commit();
  2582. // } catch (\Exception $e) {
  2583. // DB::rollBack();
  2584. // $logData = [
  2585. // 'task_id' => $taskId,
  2586. // 'error' => $e->getMessage()
  2587. // ];
  2588. // dLog('anime')->error('视频任务处理失败', $logData);
  2589. // logDB('anime', 'error', '视频任务处理失败', $logData);
  2590. // }
  2591. // } elseif ($statusResult['status'] === 'failed') {
  2592. // // 获取分镜ID并更新失败状态
  2593. // foreach ($actTasks as $actTask) {
  2594. // if ($actTask['task_id'] == $taskId) {
  2595. // DB::table('mp_episode_segments')
  2596. // ->where('id', $actTask['act_id'])
  2597. // ->update([
  2598. // 'video_task_status' => '失败',
  2599. // 'updated_at' => date('Y-m-d H:i:s')
  2600. // ]);
  2601. // break;
  2602. // }
  2603. // }
  2604. // }
  2605. // }
  2606. // }
  2607. // 检查任务是否完成(成功或失败)
  2608. if (in_array($task->status, ['success', 'failed'])) {
  2609. $completeTasks[] = $taskId;
  2610. $hasUpdate = true;
  2611. if ($task->status === 'success') {
  2612. $successTasks[] = $taskId;
  2613. }
  2614. }
  2615. }
  2616. // 如果有更新,发送update通知
  2617. if ($hasUpdate) {
  2618. echo "data: " . json_encode([
  2619. 'type' => 'update',
  2620. 'total_tasks_count' => count($totalTasks),
  2621. 'completed_tasks_count' => count($completeTasks),
  2622. 'success_tasks_count' => count($successTasks)
  2623. ]) . "\n\n";
  2624. if (ob_get_level() > 0) ob_flush();
  2625. flush();
  2626. }
  2627. // 如果所有任务都完成了,结束连接
  2628. if (count($completeTasks) >= count($totalTasks)) {
  2629. // 重新获取完整的剧集信息
  2630. $updatedEpisode = $this->AnimeService->episodeInfoForAce([
  2631. 'anime_id' => $animeId,
  2632. 'episode_id' => $episodeId
  2633. ]);
  2634. echo "data: " . json_encode([
  2635. 'type' => 'completed',
  2636. 'total_tasks_count' => count($totalTasks),
  2637. 'completed_tasks_count' => count($completeTasks),
  2638. 'success_tasks_count' => count($successTasks),
  2639. 'episode' => $updatedEpisode
  2640. ]) . "\n\n";
  2641. if (ob_get_level() > 0) ob_flush();
  2642. flush();
  2643. break;
  2644. }
  2645. // 检查是否超时
  2646. if (time() - $startTime >= $maxDuration) {
  2647. break;
  2648. }
  2649. sleep($checkInterval);
  2650. } catch (\Exception $e) {
  2651. echo "data: " . json_encode([
  2652. 'type' => 'error',
  2653. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  2654. 'total_tasks_count' => count($totalTasks),
  2655. 'completed_tasks_count' => count($completeTasks),
  2656. 'success_tasks_count' => count($successTasks)
  2657. ]) . "\n\n";
  2658. if (ob_get_level() > 0) ob_flush();
  2659. flush();
  2660. // 检查是否超时,如果超时则停止循环
  2661. if (time() - $startTime >= $maxDuration) {
  2662. break;
  2663. }
  2664. sleep($checkInterval);
  2665. }
  2666. }
  2667. // 超时处理
  2668. if (time() - $startTime >= $maxDuration) {
  2669. echo "data: " . json_encode([
  2670. 'type' => 'time_out',
  2671. 'message' => '批量视频生成已超时,停止状态查询',
  2672. 'total_tasks_count' => count($totalTasks),
  2673. 'completed_tasks_count' => count($completeTasks),
  2674. 'success_tasks_count' => count($successTasks)
  2675. ]) . "\n\n";
  2676. if (ob_get_level() > 0) ob_flush();
  2677. flush();
  2678. }
  2679. }, 200, [
  2680. 'Content-Type' => 'text/event-stream',
  2681. 'Cache-Control' => 'no-cache',
  2682. 'Connection' => 'keep-alive',
  2683. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  2684. ]);
  2685. }
  2686. }