AnimeController.php 139 KB

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