AnimeController.php 150 KB

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