AnimeController.php 142 KB

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