AnimeController.php 148 KB

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