AnimeController.php 154 KB

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