AnimeController.php 153 KB

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