AnimeController.php 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559
  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', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  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. } elseif ($this->AnimeService->isSeedance20SeriesModel($model)) {
  863. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  864. $isKuaikuai = $this->AnimeService->isKuaikuaiSeedanceModel($model);
  865. // 保存原始参考图用于任务记录
  866. $videoParams['reference_images'] = $reference_images;
  867. if ($reference_images) {
  868. // 限制只传入9张参考图
  869. $reference_images = array_slice($reference_images, 0, 9);
  870. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  871. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  872. // 参考图上传为素材(百度网关/快快AI),上传失败时同步清理提示词中的<图片N>标记
  873. $reference_image_assets = $isKuaikuai
  874. ? $this->AIVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  875. : $this->AIVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  876. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  877. $videoParams['prompt'] = trim($videoParams['prompt']);
  878. $videoParams['content'][0]['text'] = trim($videoParams['prompt']);
  879. $videoParams['reference_image_assets'] = $reference_image_assets;
  880. }
  881. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  882. if ($isKuaikuai) {
  883. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  884. $task = $this->AIVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  885. } else {
  886. $task = $this->AIVideoGenerationService->createSeedance20Task($videoParams);
  887. }
  888. } else {
  889. // Seedance模型(默认)
  890. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  891. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  892. // 添加配音音频到content中
  893. $videoParams['content'][] = [
  894. 'type' => 'audio_url',
  895. 'audio_url' => [
  896. 'url' => $audioUrl,
  897. ],
  898. 'role' => 'reference_audio',
  899. ];
  900. // 优化提示词,增加音频相关描述
  901. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  902. $videoParams['prompt'] = $audioPrompt;
  903. $videoParams['content'][0]['text'] = $audioPrompt;
  904. } else if ($audioDuration) {
  905. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  906. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  907. }
  908. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  909. }
  910. $taskIds[] = $task->id;
  911. // 更新分镜表的视频任务信息
  912. DB::table('mp_episode_segments')
  913. ->where('segment_id', $segment->segment_id)
  914. ->update([
  915. 'video_task_id' => $task->id,
  916. 'video_task_status' => '生成中',
  917. 'updated_at' => date('Y-m-d H:i:s')
  918. ]);
  919. $segmentTasks[] = [
  920. 'segment_id' => $segment->segment_id,
  921. 'task_id' => $task->id,
  922. 'segment_number' => $segment->segment_number,
  923. 'tail_frame' => $segment->tail_frame,
  924. 'audio_duration' => $segment->audio_duration,
  925. ];
  926. } catch (\Exception $e) {
  927. $logData = [
  928. 'segment_id' => $segment->segment_id,
  929. 'anime_id' => $animeId,
  930. 'error' => $e->getMessage(),
  931. ];
  932. dLog('anime')->error('创建分镜视频任务失败', $logData);
  933. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  934. continue;
  935. }
  936. }
  937. if (empty($taskIds)) {
  938. Utils::throwError('20003:没有需要生成视频的分镜');
  939. }
  940. // 保存模型到episode表
  941. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  942. 'video_model' => $model,
  943. 'updated_at' => date('Y-m-d H:i:s')
  944. ]);
  945. // 记录开始时间(包含创建任务的时间)
  946. $startTime = time();
  947. $maxDuration = 1800; // 30分钟超时
  948. // 设置 SSE 响应头并开始长连接
  949. return response()->stream(function () use ($taskIds, $segmentTasks, $episodeId, $startTime, $maxDuration) {
  950. $checkInterval = 10; // 每10秒检查一次
  951. $lastQueueMessageTime = time(); // 记录上次发送队列消息的时间
  952. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  953. // 初始化任务数组
  954. $totalTasks = $taskIds; // 所有任务ID
  955. $completeTasks = []; // 已完成的任务ID(包含失败)
  956. $successTasks = []; // 成功的任务ID
  957. // 发送初始任务创建信息
  958. echo "data: " . json_encode([
  959. 'type' => 'init',
  960. 'total_tasks_count' => count($totalTasks),
  961. 'completed_tasks_count' => count($completeTasks),
  962. 'success_tasks_count' => count($successTasks)
  963. ]) . "\n\n";
  964. if (ob_get_level() > 0) {
  965. ob_flush();
  966. }
  967. flush();
  968. while (time() - $startTime < $maxDuration) {
  969. try {
  970. $hasUpdate = false; // 标记是否有更新
  971. // 获取所有任务的最新状态
  972. foreach ($totalTasks as $taskId) {
  973. // 如果任务已经在完成列表中,跳过
  974. if (in_array($taskId, $completeTasks)) {
  975. continue;
  976. }
  977. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  978. if (!$task) {
  979. continue;
  980. }
  981. // 视频任务结果由定时任务实时更新,此处直接读取任务表状态
  982. // 检查任务是否完成(成功或失败)
  983. if (in_array($task->status, ['success', 'failed'])) {
  984. $completeTasks[] = $taskId;
  985. $hasUpdate = true;
  986. if ($task->status === 'success') {
  987. $successTasks[] = $taskId;
  988. }
  989. }
  990. }
  991. // 如果有更新,发送update通知
  992. if ($hasUpdate) {
  993. echo "data: " . json_encode([
  994. 'type' => 'update',
  995. 'total_tasks_count' => count($totalTasks),
  996. 'completed_tasks_count' => count($completeTasks),
  997. 'success_tasks_count' => count($successTasks)
  998. ]) . "\n\n";
  999. if (ob_get_level() > 0) {
  1000. ob_flush();
  1001. }
  1002. flush();
  1003. }
  1004. // 如果所有任务都完成了,结束连接
  1005. if (count($completeTasks) >= count($totalTasks)) {
  1006. // 获取所有成功任务的分镜信息
  1007. $successSegments = [];
  1008. foreach ($successTasks as $taskId) {
  1009. // 通过taskId找到对应的segmentTask
  1010. foreach ($segmentTasks as $segmentTask) {
  1011. if ($segmentTask['task_id'] == $taskId) {
  1012. $segment = DB::table('mp_episode_segments')
  1013. ->where('segment_id', $segmentTask['segment_id'])
  1014. ->select('segment_id', 'video_url')
  1015. ->first();
  1016. if ($segment && !empty($segment->video_url)) {
  1017. $successSegments[] = [
  1018. 'segment_id' => $segment->segment_id,
  1019. 'video_url' => $segment->video_url
  1020. ];
  1021. }
  1022. break;
  1023. }
  1024. }
  1025. }
  1026. echo "data: " . json_encode([
  1027. 'type' => 'completed',
  1028. 'total_tasks_count' => count($totalTasks),
  1029. 'completed_tasks_count' => count($completeTasks),
  1030. 'success_tasks_count' => count($successTasks),
  1031. 'success_segments' => $successSegments
  1032. ]) . "\n\n";
  1033. if (ob_get_level() > 0) {
  1034. ob_flush();
  1035. }
  1036. flush();
  1037. break;
  1038. }
  1039. // 每分钟发送一次队列状态消息
  1040. $currentTime = time();
  1041. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  1042. echo "data: " . json_encode([
  1043. 'type' => 'queue',
  1044. 'data' => [
  1045. 'total_tasks_count' => count($totalTasks),
  1046. 'completed_tasks_count' => count($completeTasks),
  1047. 'success_tasks_count' => count($successTasks),
  1048. 'elapsed_time' => $currentTime - $startTime,
  1049. 'message' => '任务正在队列中执行...'
  1050. ]
  1051. ]) . "\n\n";
  1052. if (ob_get_level() > 0) {
  1053. ob_flush();
  1054. }
  1055. flush();
  1056. $lastQueueMessageTime = $currentTime;
  1057. }
  1058. // 检查是否超时
  1059. if (time() - $startTime >= $maxDuration) {
  1060. break;
  1061. }
  1062. sleep($checkInterval);
  1063. } catch (\Exception $e) {
  1064. echo "data: " . json_encode([
  1065. 'type' => 'error',
  1066. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1067. 'total_tasks_count' => count($totalTasks),
  1068. 'completed_tasks_count' => count($completeTasks),
  1069. 'success_tasks_count' => count($successTasks)
  1070. ]) . "\n\n";
  1071. if (ob_get_level() > 0) {
  1072. ob_flush();
  1073. }
  1074. flush();
  1075. // 检查是否超时,如果超时则停止循环
  1076. if (time() - $startTime >= $maxDuration) {
  1077. break;
  1078. }
  1079. sleep($checkInterval);
  1080. }
  1081. }
  1082. // 超时处理
  1083. if (time() - $startTime >= $maxDuration) {
  1084. echo "data: " . json_encode([
  1085. 'type' => 'time_out',
  1086. 'message' => '批量视频生成已超时30分钟,停止状态查询',
  1087. 'total_tasks_count' => count($totalTasks),
  1088. 'completed_tasks_count' => count($completeTasks),
  1089. 'success_tasks_count' => count($successTasks)
  1090. ]) . "\n\n";
  1091. if (ob_get_level() > 0) {
  1092. ob_flush();
  1093. }
  1094. flush();
  1095. }
  1096. }, 200, [
  1097. 'Content-Type' => 'text/event-stream',
  1098. 'Cache-Control' => 'no-cache',
  1099. 'Connection' => 'keep-alive',
  1100. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1101. ]);
  1102. }
  1103. // 应用有声制作参数
  1104. public function applyAudioData(Request $request) {
  1105. $data = $request->all();
  1106. $result = $this->AnimeService->applyAudioData($data);
  1107. return $this->success($result);
  1108. }
  1109. // 获取分集生成图片信息
  1110. public function episodePicsInfo(Request $request) {
  1111. // 忽略所有超时限制
  1112. set_time_limit(0);
  1113. ini_set('max_execution_time', '0');
  1114. $data = $request->all();
  1115. // 获取生成器函数
  1116. $streamGenerator = $this->AnimeService->episodePicsInfo($data);
  1117. // 返回 SSE 响应
  1118. return response()->stream($streamGenerator, 200, [
  1119. 'Content-Type' => 'text/event-stream',
  1120. 'Cache-Control' => 'no-cache',
  1121. 'Connection' => 'keep-alive',
  1122. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1123. ]);
  1124. }
  1125. public function clipSegmentVideo(Request $request) {
  1126. $data = $request->all();
  1127. $result = $this->AnimeService->clipSegmentVideo($data);
  1128. return $this->success(['success'=>$result ? 1: 0]);
  1129. }
  1130. /**
  1131. * 创建完整视频合成任务
  1132. *
  1133. * @param Request $request
  1134. * @return \Illuminate\Http\JsonResponse
  1135. */
  1136. public function createCompleteVideoTask(Request $request)
  1137. {
  1138. // 忽略所有超时限制
  1139. set_time_limit(0);
  1140. ini_set('max_execution_time', '0');
  1141. $data = $request->all();
  1142. // 验证参数
  1143. $validator = Validator::make($data, [
  1144. 'anime_id' => 'required|string',
  1145. 'episode_id' => 'required|string',
  1146. ], [
  1147. 'anime_id.required' => '请选择动漫',
  1148. 'episode_id.required' => '请选择分集',
  1149. ]);
  1150. if ($validator->fails()) {
  1151. Utils::throwError('1002:' . $validator->errors()->first());
  1152. }
  1153. try {
  1154. $result = $this->AnimeService->createCompleteVideoTask($data);
  1155. return $this->success($result);
  1156. } catch (\Exception $e) {
  1157. $logData = [
  1158. 'anime_id' => $data['anime_id'] ?? '',
  1159. 'episode_id' => $data['episode_id'] ?? '',
  1160. 'error' => $e->getMessage()
  1161. ];
  1162. dLog('anime')->error('创建完整视频合成任务失败', $logData);
  1163. logDB('anime', 'error', '创建完整视频合成任务失败', $logData);
  1164. return $this->error('20003:'.$e->getMessage());
  1165. }
  1166. }
  1167. // 文生图(通用)
  1168. public function generateImg(Request $request) {
  1169. // 忽略所有超时限制
  1170. set_time_limit(0);
  1171. ini_set('max_execution_time', '0');
  1172. $data = $request->all();
  1173. // 兼容开关:stream=1 走 SSE 流式输出;默认不传时保持原有普通 JSON 响应
  1174. $useStream = (int)($request->input('stream', 0)) === 1;
  1175. if (!$useStream) {
  1176. // 原有逻辑:同步等待结果,普通 JSON 响应(格式保持不变)
  1177. $result = $this->AnimeService->generateImg($data);
  1178. // 多张图片:data为首图URL,image_urls为全部图片URL数组,task_center_id为任务中心ID
  1179. if (is_array($result) && isset($result['img_url']) && isset($result['image_urls'])) {
  1180. return $this->respond([
  1181. 'msg' => '',
  1182. 'code' => 0,
  1183. 'data' => $result['img_url'],
  1184. 'image_urls' => $result['image_urls'],
  1185. 'task_center_id' => $result['task_id'] ?? 0,
  1186. ]);
  1187. }
  1188. // 单张图片:data为图片URL,task_center_id为任务中心ID
  1189. if (is_array($result) && isset($result['img_url'])) {
  1190. return $this->respond([
  1191. 'msg' => '',
  1192. 'code' => 0,
  1193. 'data' => $result['img_url'],
  1194. 'task_center_id' => $result['task_id'] ?? 0,
  1195. ]);
  1196. }
  1197. return $this->success($result);
  1198. }
  1199. // 设置 SSE 响应头
  1200. return response()->stream(function () use ($data) {
  1201. // 禁用所有输出缓冲
  1202. if (ob_get_level()) {
  1203. ob_end_clean();
  1204. }
  1205. ini_set('output_buffering', 'off');
  1206. ini_set('zlib.output_compression', 'off');
  1207. if (function_exists('apache_setenv')) {
  1208. apache_setenv('no-gzip', '1');
  1209. }
  1210. try {
  1211. // 创建图片生成任务,任务创建后立即回调发送init消息(包含任务中心ID和任务信息)
  1212. $result = $this->AnimeService->generateImg($data, function ($taskCenterId, $taskInfo) {
  1213. echo "data: " . json_encode([
  1214. 'type' => 'init',
  1215. 'data' => $taskInfo,
  1216. 'task_center_id' => $taskCenterId,
  1217. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  1218. if (ob_get_level() > 0) {
  1219. ob_flush();
  1220. }
  1221. flush();
  1222. }, function ($taskCenterId, $taskId, $elapsedTime) {
  1223. // 每分钟发送一次队列状态消息
  1224. echo "data: " . json_encode([
  1225. 'type' => 'queue',
  1226. 'data' => [
  1227. 'task_id' => $taskId,
  1228. 'status' => 'processing',
  1229. 'elapsed_time' => $elapsedTime,
  1230. 'message' => '任务正在队列中执行...',
  1231. ],
  1232. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  1233. if (ob_get_level() > 0) {
  1234. ob_flush();
  1235. }
  1236. flush();
  1237. });
  1238. // 最终结果:保持原有返回格式(msg/code/data/image_urls/task_center_id)
  1239. if (is_array($result) && isset($result['img_url']) && isset($result['image_urls'])) {
  1240. $finalData = [
  1241. 'msg' => '',
  1242. 'code' => 0,
  1243. 'data' => $result['img_url'],
  1244. 'image_urls' => $result['image_urls'],
  1245. 'task_center_id' => $result['task_id'] ?? 0,
  1246. ];
  1247. } elseif (is_array($result) && isset($result['img_url'])) {
  1248. $finalData = [
  1249. 'msg' => '',
  1250. 'code' => 0,
  1251. 'data' => $result['img_url'],
  1252. 'task_center_id' => $result['task_id'] ?? 0,
  1253. ];
  1254. } else {
  1255. $finalData = [
  1256. 'msg' => '',
  1257. 'code' => 0,
  1258. 'data' => $result,
  1259. ];
  1260. }
  1261. echo "data: " . json_encode([
  1262. 'type' => 'completed',
  1263. 'data' => $finalData,
  1264. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  1265. if (ob_get_level() > 0) {
  1266. ob_flush();
  1267. }
  1268. flush();
  1269. } catch (\Exception $e) {
  1270. echo "data: " . json_encode([
  1271. 'type' => 'error',
  1272. 'message' => $e->getMessage(),
  1273. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  1274. if (ob_get_level() > 0) {
  1275. ob_flush();
  1276. }
  1277. flush();
  1278. }
  1279. }, 200, [
  1280. 'Content-Type' => 'text/event-stream',
  1281. 'Cache-Control' => 'no-cache',
  1282. 'Connection' => 'keep-alive',
  1283. 'X-Accel-Buffering' => 'no',
  1284. ]);
  1285. }
  1286. /**
  1287. * 导出动漫剧本为PDF
  1288. * @param Request $request
  1289. */
  1290. public function exportAnimeScriptPdf(Request $request) {
  1291. // 忽略超时限制(图片下载可能耗时较长)
  1292. set_time_limit(0);
  1293. ini_set('max_execution_time', '0');
  1294. ini_set('memory_limit', '512M');
  1295. $animeId = (int)$request->input('anime_id', 0);
  1296. $episodeCount = (int)$request->input('episode_count', 8);
  1297. if ($animeId <= 0) {
  1298. Utils::throwError('20003:缺少anime_id');
  1299. }
  1300. return $this->AnimeService->exportAnimeScriptAsPdf($animeId, $episodeCount);
  1301. }
  1302. /**
  1303. * 导出分集的全部图片(下载并打包)
  1304. */
  1305. public function exportEpisodeImages(Request $request) {
  1306. // 忽略所有超时限制
  1307. set_time_limit(0);
  1308. ini_set('max_execution_time', '0');
  1309. ini_set('memory_limit', '512M');
  1310. $data = $request->all();
  1311. // 验证参数
  1312. $validator = Validator::make($data, [
  1313. 'anime_id' => 'required|string',
  1314. 'episode_id' => 'required|string',
  1315. ], [
  1316. 'anime_id.required' => '动漫ID不能为空',
  1317. 'episode_id.required' => '剧集ID不能为空',
  1318. ]);
  1319. if ($validator->fails()) {
  1320. Utils::throwError('1002:' . $validator->errors()->first());
  1321. }
  1322. $animeId = $data['anime_id'];
  1323. $episodeId = $data['episode_id'];
  1324. try {
  1325. // 获取动漫信息,判断是否为全能模式
  1326. $anime = DB::table('mp_animes')
  1327. ->where('id', $animeId)
  1328. ->select('ace_mode')
  1329. ->first();
  1330. if (!$anime) {
  1331. Utils::throwError('20003:未找到动漫信息');
  1332. }
  1333. $isAceMode = ($anime->ace_mode == 1);
  1334. // 获取剧集信息
  1335. $episode = DB::table('mp_anime_episodes')
  1336. ->where('anime_id', $animeId)
  1337. ->where('id', $episodeId)
  1338. ->select('episode_number', 'title')
  1339. ->first();
  1340. if (!$episode) {
  1341. Utils::throwError('20003:未找到剧集信息');
  1342. }
  1343. // 根据模式查询和排序分镜数据
  1344. if ($isAceMode) {
  1345. // 全能模式:只查询有视频的分镜,按act_number排序
  1346. $segments = DB::table('mp_episode_segments')
  1347. ->where('anime_id', $animeId)
  1348. ->where('episode_id', $episodeId)
  1349. ->whereNotNull('video_url')
  1350. ->where('video_url', '!=', '')
  1351. ->orderBy('act_number')
  1352. ->select('id as act_id', 'act_number', 'video_url', 'act_title')
  1353. ->get();
  1354. if ($segments->isEmpty()) {
  1355. Utils::throwError('20003:该剧集暂无视频可导出');
  1356. }
  1357. } else {
  1358. // 普通模式:查询所有分镜,按segment_number排序
  1359. $segments = DB::table('mp_episode_segments')
  1360. ->where('anime_id', $animeId)
  1361. ->where('episode_id', $episodeId)
  1362. ->orderBy('segment_number')
  1363. ->select('segment_id', 'segment_number', 'img_url', 'video_url', 'audio_url')
  1364. ->get();
  1365. if ($segments->isEmpty()) {
  1366. Utils::throwError('20003:该剧集暂无分镜数据');
  1367. }
  1368. // 过滤出有图片或视频的分镜
  1369. $validSegments = $segments->filter(function($segment) {
  1370. return (!empty($segment->img_url) || !empty($segment->video_url));
  1371. });
  1372. if ($validSegments->isEmpty()) {
  1373. Utils::throwError('20003:该剧集暂无图片或视频可导出');
  1374. }
  1375. $segments = $validSegments->values();
  1376. }
  1377. // 创建临时目录
  1378. $tempDir = storage_path('app/temp/episode_images_' . time() . '_' . mt_rand(1000, 9999));
  1379. if (!file_exists($tempDir)) {
  1380. mkdir($tempDir, 0755, true);
  1381. }
  1382. // 并行下载文件(使用 cURL multi)
  1383. $downloadedFiles = [];
  1384. $multiHandle = curl_multi_init();
  1385. $curlHandles = [];
  1386. $fileInfos = [];
  1387. // 准备所有下载任务
  1388. foreach ($segments as $index => $segment) {
  1389. try {
  1390. if ($isAceMode) {
  1391. // 全能模式:只下载视频
  1392. $mediaUrl = $segment->video_url;
  1393. } else {
  1394. // 普通模式:优先使用video_url,如果没有则使用img_url
  1395. $mediaUrl = !empty($segment->video_url) ? $segment->video_url : $segment->img_url;
  1396. }
  1397. if (empty($mediaUrl)) {
  1398. continue;
  1399. }
  1400. // 获取文件扩展名
  1401. $extension = pathinfo(parse_url($mediaUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
  1402. if (empty($extension)) {
  1403. // 根据URL类型设置默认扩展名
  1404. $extension = !empty($segment->video_url) ? 'mp4' : 'jpg';
  1405. }
  1406. // 构建文件名
  1407. if ($isAceMode) {
  1408. // 全能模式:使用act_number
  1409. $fileName = sprintf('%03d.%s', $segment->act_number, $extension);
  1410. } else {
  1411. // 普通模式:使用segment_number
  1412. $fileName = sprintf('%03d.%s', $segment->segment_number, $extension);
  1413. }
  1414. $filePath = $tempDir . '/' . $fileName;
  1415. // 创建 cURL 句柄
  1416. $ch = curl_init($mediaUrl);
  1417. $fp = fopen($filePath, 'wb');
  1418. curl_setopt($ch, CURLOPT_FILE, $fp);
  1419. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  1420. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1421. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  1422. curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  1423. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  1424. curl_multi_add_handle($multiHandle, $ch);
  1425. $curlHandles[(int)$ch] = [
  1426. 'handle' => $ch,
  1427. 'file' => $fp,
  1428. 'path' => $filePath,
  1429. 'url' => $mediaUrl,
  1430. 'segment' => $segment
  1431. ];
  1432. } catch (\Exception $e) {
  1433. $logData = ['error' => $e->getMessage()];
  1434. if ($isAceMode) {
  1435. $logData['act_id'] = $segment->act_id;
  1436. } else {
  1437. $logData['segment_id'] = $segment->segment_id;
  1438. }
  1439. logDB('anime', 'error', '准备下载任务异常', $logData);
  1440. continue;
  1441. }
  1442. }
  1443. // 执行并行下载
  1444. $running = null;
  1445. do {
  1446. curl_multi_exec($multiHandle, $running);
  1447. curl_multi_select($multiHandle, 0.1);
  1448. } while ($running > 0);
  1449. // 处理下载结果
  1450. foreach ($curlHandles as $info) {
  1451. $ch = $info['handle'];
  1452. $fp = $info['file'];
  1453. $filePath = $info['path'];
  1454. $segment = $info['segment'];
  1455. fclose($fp);
  1456. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  1457. if ($httpCode == 200 && file_exists($filePath) && filesize($filePath) > 0) {
  1458. $downloadedFiles[] = $filePath;
  1459. } else {
  1460. // 删除失败的文件
  1461. if (file_exists($filePath)) {
  1462. @unlink($filePath);
  1463. }
  1464. $logData = [
  1465. 'media_url' => $info['url'],
  1466. 'http_code' => $httpCode,
  1467. 'type' => $isAceMode ? 'video' : 'image'
  1468. ];
  1469. if ($isAceMode) {
  1470. $logData['act_id'] = $segment->act_id;
  1471. } else {
  1472. $logData['segment_id'] = $segment->segment_id;
  1473. }
  1474. logDB('anime', 'warning', '文件下载失败', $logData);
  1475. }
  1476. curl_multi_remove_handle($multiHandle, $ch);
  1477. curl_close($ch);
  1478. }
  1479. curl_multi_close($multiHandle);
  1480. if (empty($downloadedFiles)) {
  1481. // 清理临时目录
  1482. if (file_exists($tempDir)) {
  1483. array_map('unlink', glob("$tempDir/*"));
  1484. rmdir($tempDir);
  1485. }
  1486. Utils::throwError('20003:没有成功下载任何文件');
  1487. }
  1488. // 处理音频合成(仅普通模式)
  1489. $mergedAudioPath = null;
  1490. if (!$isAceMode) {
  1491. try {
  1492. // 检查 FFmpeg 是否可用
  1493. exec('which ffmpeg 2>&1', $ffmpegCheck, $ffmpegReturnCode);
  1494. $hasFfmpeg = ($ffmpegReturnCode === 0);
  1495. if ($hasFfmpeg) {
  1496. // 下载所有分镜的音频文件
  1497. $audioFiles = [];
  1498. foreach ($segments as $segment) {
  1499. if (!empty($segment->audio_url)) {
  1500. try {
  1501. $context = stream_context_create([
  1502. 'http' => [
  1503. 'timeout' => 30,
  1504. 'follow_location' => 1,
  1505. 'ignore_errors' => true
  1506. ],
  1507. 'ssl' => [
  1508. 'verify_peer' => false,
  1509. 'verify_peer_name' => false
  1510. ]
  1511. ]);
  1512. $audioData = @file_get_contents($segment->audio_url, false, $context);
  1513. if ($audioData !== false && !empty($audioData)) {
  1514. // 获取音频文件扩展名
  1515. $audioExtension = pathinfo(parse_url($segment->audio_url, PHP_URL_PATH), PATHINFO_EXTENSION);
  1516. if (empty($audioExtension)) {
  1517. $audioExtension = 'wav';
  1518. }
  1519. $audioFileName = sprintf('audio_%03d.%s', $segment->segment_number, $audioExtension);
  1520. $audioFilePath = $tempDir . '/' . $audioFileName;
  1521. file_put_contents($audioFilePath, $audioData);
  1522. $audioFiles[] = $audioFilePath;
  1523. } else {
  1524. logDB('anime', 'warning', '音频下载失败', [
  1525. 'segment_id' => $segment->segment_id,
  1526. 'audio_url' => $segment->audio_url
  1527. ]);
  1528. }
  1529. } catch (\Exception $e) {
  1530. logDB('anime', 'error', '下载音频异常', [
  1531. 'segment_id' => $segment->segment_id,
  1532. 'audio_url' => $segment->audio_url,
  1533. 'error' => $e->getMessage()
  1534. ]);
  1535. }
  1536. }
  1537. }
  1538. // 如果有音频文件,则进行合成
  1539. if (!empty($audioFiles)) {
  1540. // 创建 FFmpeg concat 文件列表
  1541. $concatFile = $tempDir . '/concat.txt';
  1542. $concatContent = '';
  1543. foreach ($audioFiles as $audioFile) {
  1544. // 使用相对路径,避免路径中的特殊字符问题
  1545. $concatContent .= "file '" . basename($audioFile) . "'\n";
  1546. }
  1547. file_put_contents($concatFile, $concatContent);
  1548. // 合成音频文件
  1549. $mergedAudioPath = $tempDir . '/tts.wav';
  1550. // 使用 FFmpeg 合并音频,转换为统一的 WAV 格式
  1551. $ffmpegCommand = sprintf(
  1552. 'cd %s && ffmpeg -f concat -safe 0 -i %s -ar 44100 -ac 2 -y %s 2>&1',
  1553. escapeshellarg($tempDir),
  1554. escapeshellarg(basename($concatFile)),
  1555. escapeshellarg(basename($mergedAudioPath))
  1556. );
  1557. exec($ffmpegCommand, $ffmpegOutput, $ffmpegReturnCode);
  1558. if ($ffmpegReturnCode !== 0 || !file_exists($mergedAudioPath)) {
  1559. logDB('anime', 'error', 'FFmpeg 合成音频失败', [
  1560. 'command' => $ffmpegCommand,
  1561. 'output' => implode("\n", $ffmpegOutput),
  1562. 'return_code' => $ffmpegReturnCode
  1563. ]);
  1564. $mergedAudioPath = null;
  1565. } else {
  1566. logDB('anime', 'info', '音频合成成功', [
  1567. 'audio_count' => count($audioFiles),
  1568. 'output_file' => $mergedAudioPath,
  1569. 'file_size' => filesize($mergedAudioPath)
  1570. ]);
  1571. }
  1572. // 清理临时音频文件和 concat 文件
  1573. foreach ($audioFiles as $audioFile) {
  1574. if (file_exists($audioFile)) {
  1575. @unlink($audioFile);
  1576. }
  1577. }
  1578. if (file_exists($concatFile)) {
  1579. @unlink($concatFile);
  1580. }
  1581. }
  1582. } else {
  1583. logDB('anime', 'warning', 'FFmpeg 未安装,跳过音频合成', []);
  1584. }
  1585. } catch (\Exception $e) {
  1586. logDB('anime', 'error', '音频合成过程异常', [
  1587. 'error' => $e->getMessage(),
  1588. 'trace' => $e->getTraceAsString()
  1589. ]);
  1590. // 音频合成失败不影响图片导出
  1591. $mergedAudioPath = null;
  1592. }
  1593. }
  1594. // 创建zip文件(使用安全的文件名)
  1595. $safeTitle = preg_replace('/[^\p{L}\p{N}\s\-_]/u', '', $episode->title ?: '未命名');
  1596. $safeTitle = trim($safeTitle) ?: '未命名';
  1597. $zipFileName = sprintf('%s_%s.zip', $safeTitle, time());
  1598. $zipFilePath = storage_path('app/temp/' . $zipFileName);
  1599. // 确保 temp 目录存在
  1600. $tempZipDir = storage_path('app/temp');
  1601. if (!file_exists($tempZipDir)) {
  1602. mkdir($tempZipDir, 0755, true);
  1603. }
  1604. $zip = new \ZipArchive();
  1605. $openResult = $zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
  1606. if ($openResult !== true) {
  1607. // 清理临时文件
  1608. array_map('unlink', $downloadedFiles);
  1609. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1610. @unlink($mergedAudioPath);
  1611. }
  1612. rmdir($tempDir);
  1613. logDB('anime', 'error', '创建ZIP文件失败', [
  1614. 'zip_path' => $zipFilePath,
  1615. 'open_result' => $openResult
  1616. ]);
  1617. Utils::throwError('20003:创建ZIP文件失败');
  1618. }
  1619. // 设置压缩级别为最快(0=不压缩,1=最快,9=最好压缩)
  1620. // 对于视频和图片,压缩效果不明显,使用最快速度
  1621. $zip->setCompressionIndex(0, \ZipArchive::CM_STORE); // 不压缩,直接存储
  1622. // 添加文件到zip
  1623. foreach ($downloadedFiles as $file) {
  1624. if (file_exists($file)) {
  1625. $zip->addFile($file, basename($file));
  1626. }
  1627. }
  1628. // 添加合成的音频文件到zip(仅普通模式)
  1629. if (!$isAceMode && $mergedAudioPath && file_exists($mergedAudioPath)) {
  1630. $zip->addFile($mergedAudioPath, 'tts.wav');
  1631. }
  1632. // 关闭 ZIP 文件
  1633. $zip->close();
  1634. // 验证 ZIP 文件是否创建成功
  1635. if (!file_exists($zipFilePath) || filesize($zipFilePath) == 0) {
  1636. // 清理临时文件
  1637. array_map('unlink', $downloadedFiles);
  1638. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1639. @unlink($mergedAudioPath);
  1640. }
  1641. rmdir($tempDir);
  1642. logDB('anime', 'error', 'ZIP文件创建后无效', ['zip_path' => $zipFilePath]);
  1643. Utils::throwError('20003:ZIP文件创建失败或文件为空');
  1644. }
  1645. // 清理临时文件
  1646. array_map('unlink', $downloadedFiles);
  1647. // 清理合成的音频文件
  1648. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1649. @unlink($mergedAudioPath);
  1650. }
  1651. rmdir($tempDir);
  1652. // 清空所有输出缓冲区,避免污染ZIP文件
  1653. while (ob_get_level() > 0) {
  1654. ob_end_clean();
  1655. }
  1656. // 返回文件下载响应
  1657. return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
  1658. } catch (\Exception $e) {
  1659. logDB('anime', 'error', '导出分集图片失败', [
  1660. 'anime_id' => $animeId,
  1661. 'episode_id' => $episodeId,
  1662. 'error' => $e->getMessage()
  1663. ]);
  1664. // 清理可能存在的临时文件
  1665. if (isset($tempDir) && file_exists($tempDir)) {
  1666. array_map('unlink', glob("$tempDir/*"));
  1667. rmdir($tempDir);
  1668. }
  1669. if (isset($zipFilePath) && file_exists($zipFilePath)) {
  1670. unlink($zipFilePath);
  1671. }
  1672. throw $e;
  1673. }
  1674. }
  1675. /**
  1676. * 监控分镜图片和音频生成任务进度(SSE)
  1677. */
  1678. public function monitorSegmentTasks(Request $request) {
  1679. // 忽略所有超时限制
  1680. set_time_limit(0);
  1681. ini_set('max_execution_time', '0');
  1682. $data = $request->all();
  1683. // 验证参数
  1684. $validator = Validator::make($data, [
  1685. 'anime_id' => 'required|string',
  1686. 'episode_id' => 'required|string',
  1687. ], [
  1688. 'anime_id.required' => '动漫ID不能为空',
  1689. 'episode_id.required' => '剧集ID不能为空',
  1690. ]);
  1691. if ($validator->fails()) {
  1692. Utils::throwError('1002:' . $validator->errors()->first());
  1693. }
  1694. $animeId = $data['anime_id'];
  1695. $episodeId = $data['episode_id'];
  1696. // 查询没有pic_task_id的分镜个数
  1697. $noPicTaskCount = DB::table('mp_episode_segments')
  1698. ->where('anime_id', $animeId)
  1699. ->where('episode_id', $episodeId)
  1700. ->where(function($query) {
  1701. $query->whereNull('pic_task_id')
  1702. ->orWhere('pic_task_id', '');
  1703. })
  1704. ->count('id');
  1705. // 获取所有分镜信息
  1706. $segments = DB::table('mp_episode_segments')
  1707. ->where('anime_id', $animeId)
  1708. ->where('episode_id', $episodeId)
  1709. ->where('pic_task_id', '!=', '')
  1710. ->orderBy('segment_number')
  1711. ->get();
  1712. // 判断是否有未完成的任务
  1713. $uncompleted_pic_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)
  1714. ->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->whereNotIn('pic_task_status', ['已完成', '失败'])->count('id');
  1715. // 获取dialogue和voice_type存在但audio_url不存在的分镜个数
  1716. $uncompleted_audio_count = DB::table('mp_episode_segments')
  1717. ->where('anime_id', $animeId)
  1718. ->where('episode_id', $episodeId)
  1719. ->where('dialogue', '<>', '')
  1720. ->whereNotNull('dialogue')
  1721. ->where('voice_type', '<>', '')
  1722. ->whereNotNull('voice_type')
  1723. ->where(function($query) {
  1724. $query->whereNull('audio_url')
  1725. ->orWhere('audio_url', '');
  1726. })
  1727. ->count('id');
  1728. if ($segments->isEmpty()) {
  1729. Utils::throwError('20003:未找到分镜任务数据');
  1730. }
  1731. $startTime = time();
  1732. $maxDuration = 900; // 15分钟超时
  1733. $checkInterval = 5; // 每5秒检查一次
  1734. // 设置 SSE 响应头并开始长连接
  1735. return response()->stream(function () use ($segments, $animeId, $episodeId, $startTime, $maxDuration, $checkInterval, $uncompleted_pic_count, $uncompleted_audio_count, $noPicTaskCount) {
  1736. if ($uncompleted_pic_count == 0 && $uncompleted_audio_count == 0) {
  1737. $completedCount = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->where('pic_task_status', '已完成')->count('id');
  1738. // 获取剧集信息之前先处理视频截止时间点
  1739. $this->handleVideoTimePointEnd();
  1740. // 获取剧集信息
  1741. $episode = DB::table('mp_anime_episodes')
  1742. ->where('anime_id', $animeId)
  1743. ->where('id', $episodeId)
  1744. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1745. ->first();
  1746. if ($episode) {
  1747. $episode = (array)$episode;
  1748. $episode['roles'] = json_decode($episode['roles'], true);
  1749. $episode['scenes'] = json_decode($episode['scenes'], true);
  1750. // 获取所有分镜信息
  1751. $allSegments = DB::table('mp_episode_segments')
  1752. ->where('anime_id', $animeId)
  1753. ->where('episode_id', $episodeId)
  1754. ->orderBy('segment_number')
  1755. ->select('*')
  1756. ->get()
  1757. ->map(function ($value) {
  1758. return (array)$value;
  1759. })->toArray();
  1760. // 按照episodeInfo的格式组织数据
  1761. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1762. $episode['acts'] = $segmentsStructure['acts'];
  1763. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1764. }
  1765. echo "data: " . json_encode([
  1766. 'type' => 'completed',
  1767. 'data' => [
  1768. 'anime_id' => $animeId,
  1769. 'episode_id' => $episodeId,
  1770. 'completed_count' => $completedCount, // 成功完成的数量
  1771. 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1772. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1773. 'total_elapsed_time' => time() - $startTime,
  1774. 'episode_info' => $episode ?? null
  1775. ]
  1776. ]) . "\n\n";
  1777. if (ob_get_level() > 0) {
  1778. ob_flush();
  1779. }
  1780. flush();
  1781. return;
  1782. }
  1783. // 发送初始任务信息
  1784. echo "data: " . json_encode([
  1785. 'type' => 'init',
  1786. 'data' => [
  1787. 'anime_id' => $animeId,
  1788. 'episode_id' => $episodeId,
  1789. 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1790. 'start_time' => $startTime,
  1791. 'max_duration' => $maxDuration
  1792. ]
  1793. ]) . "\n\n";
  1794. if (ob_get_level() > 0) {
  1795. ob_flush();
  1796. }
  1797. flush();
  1798. $completedSegments = [];
  1799. $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
  1800. $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
  1801. while (time() - $startTime < $maxDuration) {
  1802. try {
  1803. $updatedImages = []; // 记录本次循环中更新的图片信息
  1804. foreach ($segments as $segment) {
  1805. $segmentId = $segment->segment_id;
  1806. $picTaskId = $segment->pic_task_id;
  1807. $audioUrl = $segment->audio_url;
  1808. // 跳过已处理完成的分镜
  1809. if (in_array($segmentId, $processedSegments)) {
  1810. continue;
  1811. }
  1812. $picCompleted = false;
  1813. $audioCompleted = false;
  1814. $picProcessed = false;
  1815. $audioProcessed = false;
  1816. // 检查图片任务状态
  1817. if ($picTaskId) {
  1818. $picTask = DB::table('mp_generate_pic_tasks')
  1819. ->where('id', $picTaskId)
  1820. ->select('status', 'result_url', 'error_message')
  1821. ->first();
  1822. if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
  1823. $updateData = [
  1824. 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
  1825. 'updated_at' => date('Y-m-d H:i:s')
  1826. ];
  1827. $imgUrl = '';
  1828. if ($picTask->status === 'success' && !empty($picTask->result_url)) {
  1829. // 更新分镜表的图片URL
  1830. $resultUrls = json_decode($picTask->result_url, true);
  1831. $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
  1832. $updateData['img_url'] = $imgUrl;
  1833. $picCompleted = true;
  1834. } else if ($picTask->status === 'failed') {
  1835. // 失败时清空图片URL
  1836. $updateData['img_url'] = '';
  1837. }
  1838. DB::table('mp_episode_segments')
  1839. ->where('segment_id', $segmentId)
  1840. ->update($updateData);
  1841. // 记录更新的图片信息(只有未通知过的才记录)
  1842. if (!in_array($segmentId, $notifiedSegments)) {
  1843. $updatedImages[] = [
  1844. 'segment_id' => $segmentId,
  1845. 'segment_number' => $segment->segment_number,
  1846. 'img_url' => $imgUrl,
  1847. 'status' => $picTask->status === 'success' ? 'success' : 'failed'
  1848. ];
  1849. // 标记为已通知
  1850. $notifiedSegments[] = $segmentId;
  1851. }
  1852. $picProcessed = true;
  1853. }
  1854. }
  1855. // 检查音频状态
  1856. // 获取分镜的dialogue、voice_type和audio_url信息
  1857. $segmentInfo = DB::table('mp_episode_segments')
  1858. ->where('segment_id', $segmentId)
  1859. ->select('dialogue', 'voice_type', 'audio_url')
  1860. ->first();
  1861. $needAudio = false;
  1862. $currentAudioUrl = '';
  1863. if ($segmentInfo) {
  1864. $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
  1865. $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
  1866. $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
  1867. // 如果有对话和音色类型,则需要音频
  1868. if (!empty($dialogue) && !empty($voiceType)) {
  1869. $needAudio = true;
  1870. }
  1871. }
  1872. // 判断音频状态
  1873. if ($needAudio) {
  1874. // 需要音频的情况下,检查audio_url是否有值
  1875. if (!empty($currentAudioUrl)) {
  1876. $audioCompleted = true;
  1877. $audioProcessed = true;
  1878. } else {
  1879. // 需要音频但还没有,继续等待
  1880. $audioCompleted = false;
  1881. $audioProcessed = false;
  1882. }
  1883. } else {
  1884. // 不需要音频,直接标记为已处理
  1885. $audioCompleted = false;
  1886. $audioProcessed = true;
  1887. }
  1888. // 如果图片和音频都成功完成,标记为已完成
  1889. if ($picCompleted && ($audioCompleted || !$needAudio)) {
  1890. $completedSegments[] = $segmentId;
  1891. }
  1892. // 如果图片和音频都已处理完成(成功或失败),标记为已处理
  1893. if ($picProcessed && $audioProcessed) {
  1894. $processedSegments[] = $segmentId;
  1895. }
  1896. }
  1897. // 如果有图片更新,发送具体的图片更新信息
  1898. if (!empty($updatedImages)) {
  1899. echo "data: " . json_encode([
  1900. 'type' => 'update',
  1901. 'data' => [
  1902. 'anime_id' => $animeId,
  1903. 'episode_id' => $episodeId,
  1904. 'updated_images' => $updatedImages,
  1905. 'completed_count' => count($completedSegments), // 成功完成的数量
  1906. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1907. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1908. 'elapsed_time' => time() - $startTime,
  1909. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1910. ]
  1911. ]) . "\n\n";
  1912. if (ob_get_level() > 0) {
  1913. ob_flush();
  1914. }
  1915. flush();
  1916. }
  1917. // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
  1918. if (count($processedSegments) === count($segments)) {
  1919. // 获取剧集信息之前先处理视频截止时间点
  1920. $this->handleVideoTimePointEnd();
  1921. // 获取剧集信息
  1922. $episode = DB::table('mp_anime_episodes')
  1923. ->where('anime_id', $animeId)
  1924. ->where('id', $episodeId)
  1925. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1926. ->first();
  1927. if ($episode) {
  1928. $episode = (array)$episode;
  1929. $episode['roles'] = json_decode($episode['roles'], true);
  1930. $episode['scenes'] = json_decode($episode['scenes'], true);
  1931. // 获取所有分镜信息
  1932. $allSegments = DB::table('mp_episode_segments')
  1933. ->where('anime_id', $animeId)
  1934. ->where('episode_id', $episodeId)
  1935. ->orderBy('segment_number')
  1936. ->select('*')
  1937. ->get()
  1938. ->map(function ($value) {
  1939. return (array)$value;
  1940. })->toArray();
  1941. // 按照episodeInfo的格式组织数据
  1942. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1943. $episode['acts'] = $segmentsStructure['acts'];
  1944. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1945. }
  1946. echo "data: " . json_encode([
  1947. 'type' => 'completed',
  1948. 'data' => [
  1949. 'anime_id' => $animeId,
  1950. 'episode_id' => $episodeId,
  1951. 'completed_count' => count($completedSegments), // 成功完成的数量
  1952. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1953. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1954. 'total_elapsed_time' => time() - $startTime,
  1955. 'episode_info' => $episode ?? null
  1956. ]
  1957. ]) . "\n\n";
  1958. if (ob_get_level() > 0) ob_flush();
  1959. flush();
  1960. break;
  1961. }
  1962. // 检查是否超时
  1963. if (time() - $startTime >= $maxDuration) {
  1964. break;
  1965. }
  1966. sleep($checkInterval);
  1967. } catch (\Exception $e) {
  1968. echo "data: " . json_encode([
  1969. 'type' => 'error',
  1970. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1971. 'elapsed_time' => time() - $startTime,
  1972. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1973. ]) . "\n\n";
  1974. if (ob_get_level() > 0) ob_flush();
  1975. flush();
  1976. if (time() - $startTime >= $maxDuration) {
  1977. break;
  1978. }
  1979. sleep($checkInterval);
  1980. }
  1981. }
  1982. // 超时处理
  1983. if (time() - $startTime >= $maxDuration) {
  1984. echo "data: " . json_encode([
  1985. 'type' => 'time_out',
  1986. 'message' => '分镜任务监控已超时15分钟,停止状态查询',
  1987. 'data' => [
  1988. 'anime_id' => $animeId,
  1989. 'episode_id' => $episodeId,
  1990. 'completed_count' => count($completedSegments), // 成功完成的数量
  1991. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1992. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1993. 'total_elapsed_time' => time() - $startTime,
  1994. 'timeout_duration' => $maxDuration
  1995. ]
  1996. ]) . "\n\n";
  1997. if (ob_get_level() > 0) ob_flush();
  1998. flush();
  1999. }
  2000. }, 200, [
  2001. 'Content-Type' => 'text/event-stream',
  2002. 'Cache-Control' => 'no-cache',
  2003. 'Connection' => 'keep-alive',
  2004. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  2005. ]);
  2006. }
  2007. /**
  2008. * 音频试听接口
  2009. * 创建音频任务并返回结果
  2010. */
  2011. public function previewAudio(Request $request) {
  2012. $data = $request->all();
  2013. $result = $this->AnimeService->previewAudio($data);
  2014. return $this->success($result);
  2015. }
  2016. // 角色库
  2017. public function globalProducts(Request $request) {
  2018. $data = $request->all();
  2019. $result = $this->AnimeService->globalProducts($data);
  2020. return $this->success($result);
  2021. }
  2022. // 新建角色
  2023. public function createProduct(Request $request) {
  2024. $data = $request->all();
  2025. $result = $this->AnimeService->createProduct($data);
  2026. return $this->success($result);
  2027. }
  2028. // 编辑角色
  2029. public function editProduct(Request $request) {
  2030. $data = $request->all();
  2031. $result = $this->AnimeService->editProduct($data);
  2032. return $this->success(['success' => $result ? 1 : 0]);
  2033. }
  2034. // 获取角色版本历史
  2035. public function getProductVersions(Request $request) {
  2036. $data = $request->all();
  2037. $result = $this->AnimeService->getProductVersions($data);
  2038. return $this->success($result);
  2039. }
  2040. // 恢复到指定版本
  2041. public function restoreProductVersion(Request $request) {
  2042. $data = $request->all();
  2043. $result = $this->AnimeService->restoreProductVersion($data);
  2044. return $this->success(['success' => $result ? 1 : 0]);
  2045. }
  2046. // 删除角色
  2047. public function deleteProduct(Request $request) {
  2048. $data = $request->all();
  2049. $result = $this->AnimeService->deleteProduct($data);
  2050. return $this->success(['success' => $result ? 1 : 0]);
  2051. }
  2052. // 新建文件夹
  2053. public function createFolder(Request $request) {
  2054. $data = $request->all();
  2055. $result = $this->AnimeService->createFolder($data);
  2056. return $this->success(['id' => $result]);
  2057. }
  2058. // 重命名文件夹或角色
  2059. public function renameFolder(Request $request) {
  2060. $data = $request->all();
  2061. $result = $this->AnimeService->renameFolder($data);
  2062. return $this->success(['success' => $result ? 1 : 0]);
  2063. }
  2064. // 移动角色或文件夹
  2065. public function moveProductOrFolder(Request $request) {
  2066. $data = $request->all();
  2067. $result = $this->AnimeService->moveProductOrFolder($data);
  2068. return $this->success(['success' => $result ? 1 : 0]);
  2069. }
  2070. // 获取文件夹路径(面包屑导航)
  2071. public function getFolderPath(Request $request) {
  2072. $data = $request->all();
  2073. $result = $this->AnimeService->getFolderPath($data);
  2074. return $this->success($result);
  2075. }
  2076. // 生成三视图
  2077. public function generateThreeView(Request $request) {
  2078. // 忽略所有超时限制
  2079. set_time_limit(0);
  2080. ini_set('max_execution_time', '0');
  2081. $data = $request->all();
  2082. $result = $this->AnimeService->generateThreeView($data);
  2083. return $this->success($result);
  2084. }
  2085. // 推送资产或文件夹到目标位置
  2086. public function pushProductOrFolder(Request $request) {
  2087. $data = $request->all();
  2088. $result = $this->AnimeService->pushProductOrFolder($data);
  2089. return $this->success($result);
  2090. }
  2091. /**
  2092. * 保存剧本资产关联关系
  2093. * @param Request $request
  2094. * @return mixed
  2095. */
  2096. public function saveScriptProducts(Request $request) {
  2097. // 忽略所有超时限制
  2098. set_time_limit(0);
  2099. ini_set('max_execution_time', '0');
  2100. $data = $request->all();
  2101. $result = $this->AnimeService->saveScriptProducts($data);
  2102. // 判断是否是 SSE 流(Generator)
  2103. if ($result instanceof \Generator) {
  2104. // 返回 SSE 响应
  2105. return response()->stream(function () use ($result) {
  2106. // 设置不缓冲输出
  2107. if (ob_get_level()) {
  2108. ob_end_flush();
  2109. }
  2110. foreach ($result as $event) {
  2111. echo $event;
  2112. if (ob_get_level()) {
  2113. ob_flush();
  2114. }
  2115. flush();
  2116. }
  2117. }, 200, [
  2118. 'Content-Type' => 'text/event-stream',
  2119. 'Cache-Control' => 'no-cache',
  2120. 'Connection' => 'keep-alive',
  2121. 'X-Accel-Buffering' => 'no'
  2122. ]);
  2123. }
  2124. // 普通JSON响应
  2125. return $this->success($result);
  2126. }
  2127. /**
  2128. * 获取剧本关联的资产列表
  2129. * @param Request $request
  2130. * @return mixed
  2131. */
  2132. public function getScriptProducts(Request $request) {
  2133. $data = $request->all();
  2134. $result = $this->AnimeService->getScriptProducts($data);
  2135. return $this->success($result);
  2136. }
  2137. /**
  2138. * 获取剧本总集数
  2139. * @param Request $request
  2140. * @return mixed
  2141. */
  2142. public function getScriptTotalEpisodes(Request $request) {
  2143. $data = $request->all();
  2144. $result = $this->AnimeService->getScriptTotalEpisodes($data);
  2145. return $this->success($result);
  2146. }
  2147. private function handleVideoTimePointEnd() {
  2148. // 处理音频时长,循环查询dub_video_task_queue列表中的任务
  2149. $queueLength = Redis::llen('dub_video_task_queue');
  2150. if ($queueLength > 0) {
  2151. $processedTaskIds = []; // 记录已处理的任务ID
  2152. // 遍历队列中的所有任务
  2153. for ($i = 0; $i < $queueLength; $i++) {
  2154. $dubTaskId = Redis::lindex('dub_video_task_queue', $i);
  2155. if (!$dubTaskId) continue;
  2156. // 查询任务状态
  2157. $dubTask = DB::table('mp_dub_video_tasks')
  2158. ->where('id', $dubTaskId)
  2159. ->first();
  2160. if (!$dubTask) {
  2161. // 任务不存在,标记为需要删除
  2162. $processedTaskIds[] = $dubTaskId;
  2163. continue;
  2164. }
  2165. // 如果任务状态是已完成
  2166. if ($dubTask->generate_status === '执行成功') {
  2167. // 获取对应的分镜信息
  2168. $segment = DB::table('mp_episode_segments')
  2169. ->where('segment_id', $dubTask->alias_segment_id)
  2170. ->first();
  2171. // 如果分镜存在且audio_duration大于0
  2172. if ($segment && isset($segment->audio_duration) && $segment->audio_duration > 0) {
  2173. // 更新video_time_point_end字段
  2174. DB::table('mp_episode_segments')
  2175. ->where('segment_id', $dubTask->alias_segment_id)
  2176. ->update([
  2177. 'video_time_point_end' => $segment->audio_duration,
  2178. 'updated_at' => date('Y-m-d H:i:s')
  2179. ]);
  2180. dLog('anime')->info('更新分镜视频截止时间点', [
  2181. 'task_id' => $dubTaskId,
  2182. 'segment_id' => $dubTask->alias_segment_id,
  2183. 'audio_duration' => $segment->audio_duration
  2184. ]);
  2185. }
  2186. // 标记为需要从队列中删除
  2187. $processedTaskIds[] = $dubTaskId;
  2188. }
  2189. }
  2190. // 从Redis列表中删除已处理的任务ID
  2191. foreach ($processedTaskIds as $taskId) {
  2192. Redis::lrem('dub_video_task_queue', 0, $taskId);
  2193. }
  2194. }
  2195. }
  2196. // 确认片段
  2197. public function confirmActs(Request $request) {
  2198. $data = $request->all();
  2199. $result = $this->AnimeService->confirmActs($data);
  2200. return $this->success($result);
  2201. }
  2202. public function saveActVideoGenerateParams(Request $request) {
  2203. $data = $request->all();
  2204. $result = $this->AnimeService->saveActVideoGenerateParams($data);
  2205. return $this->success(['success' => $result ? 1 : 0]);
  2206. }
  2207. public function createActVideoTask(Request $request) {
  2208. $uid = Site::getUid();
  2209. // 忽略所有超时限制
  2210. set_time_limit(0);
  2211. ini_set('max_execution_time', '0');
  2212. $data = $request->all();
  2213. // 创建视频生成任务
  2214. $result = $this->AnimeService->createActVideoTask($data);
  2215. $taskId = $result['task_id'];
  2216. // 设置 SSE 响应头
  2217. return response()->stream(function () use ($taskId, $result, $uid) {
  2218. // 立即发送 init 消息
  2219. echo "data: " . json_encode([
  2220. 'type' => 'init',
  2221. 'data' => $result
  2222. ]) . "\n\n";
  2223. if (ob_get_level() > 0) ob_flush();
  2224. flush();
  2225. $startTime = time();
  2226. $maxDuration = 3600; // 超时设置
  2227. $checkInterval = 5; // 检查间隔
  2228. $lastQueueMessageTime = time(); // 记录上次发送队列消息的时间
  2229. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  2230. while (time() - $startTime < $maxDuration) {
  2231. try {
  2232. // 查询任务状态
  2233. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  2234. if (!$task) {
  2235. echo "data: " . json_encode([
  2236. 'type' => 'error',
  2237. 'message' => '任务不存在'
  2238. ]) . "\n\n";
  2239. if (ob_get_level() > 0) ob_flush();
  2240. flush();
  2241. break;
  2242. }
  2243. // 如果任务完成(成功或失败),结束连接
  2244. if (in_array($task->status, [
  2245. 'success',
  2246. 'failed'
  2247. ])) {
  2248. echo "data: " . json_encode([
  2249. 'type' => 'completed',
  2250. 'data' => [
  2251. 'task_id' => $task->id,
  2252. 'status' => $task->status,
  2253. 'video_url' => $task->compressed_url ?: $task->result_url,
  2254. 'origin_video_url' => $task->result_url,
  2255. 'last_frame_url' => $task->last_frame_url,
  2256. 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : ''
  2257. ]
  2258. ]) . "\n\n";
  2259. if (ob_get_level() > 0) ob_flush();
  2260. flush();
  2261. break;
  2262. }
  2263. // 每分钟发送一次队列状态消息
  2264. $currentTime = time();
  2265. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  2266. echo "data: " . json_encode([
  2267. 'type' => 'queue',
  2268. 'data' => [
  2269. 'task_id' => $task->id,
  2270. 'status' => $task->status,
  2271. 'elapsed_time' => $currentTime - $startTime,
  2272. 'message' => '任务正在队列中执行...'
  2273. ]
  2274. ]) . "\n\n";
  2275. if (ob_get_level() > 0) ob_flush();
  2276. flush();
  2277. $lastQueueMessageTime = $currentTime;
  2278. }
  2279. sleep($checkInterval);
  2280. } catch (\Exception $e) {
  2281. echo "data: " . json_encode([
  2282. 'type' => 'error',
  2283. 'message' => '查询任务状态失败: ' . $e->getMessage()
  2284. ]) . "\n\n";
  2285. if (ob_get_level() > 0) ob_flush();
  2286. flush();
  2287. sleep($checkInterval);
  2288. }
  2289. }
  2290. // 超时处理
  2291. if (time() - $startTime >= $maxDuration) {
  2292. echo "data: " . json_encode([
  2293. 'type' => 'time_out',
  2294. 'message' => '任务执行超时,请稍后查询任务状态',
  2295. 'data' => [
  2296. 'task_id' => $taskId
  2297. ]
  2298. ]) . "\n\n";
  2299. if (ob_get_level() > 0) ob_flush();
  2300. flush();
  2301. }
  2302. }, 200, [
  2303. 'Content-Type' => 'text/event-stream',
  2304. 'Cache-Control' => 'no-cache',
  2305. 'Connection' => 'keep-alive',
  2306. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  2307. ]);
  2308. }
  2309. /**
  2310. * 文生视频(通用)
  2311. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  2312. */
  2313. public function generateVideo(Request $request) {
  2314. // 忽略所有超时限制
  2315. set_time_limit(0);
  2316. ini_set('max_execution_time', '0');
  2317. $data = $request->all();
  2318. // 创建视频生成任务
  2319. $result = $this->AnimeService->generateVideo($data);
  2320. $taskId = $result['task_id'];
  2321. // 创建任务中心记录并关联视频任务ID
  2322. $taskCenter = $this->taskCenterService->createTask('video', [
  2323. 'title' => '文生视频',
  2324. 'ref_task_id' => $taskId,
  2325. // 'prompt' => getProp($data, 'prompt', ''),
  2326. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  2327. ]);
  2328. $taskCenterId = $taskCenter->id;
  2329. // 设置 SSE 响应头
  2330. return response()->stream(function () use ($taskId, $taskCenterId, $result) {
  2331. // 立即发送 init 消息
  2332. echo "data: " . json_encode([
  2333. 'type' => 'init',
  2334. 'data' => $result,
  2335. 'task_center_id' => $taskCenterId,
  2336. ]) . "\n\n";
  2337. if (ob_get_level() > 0) ob_flush();
  2338. flush();
  2339. $startTime = time();
  2340. $maxDuration = 3600; // 超时设置
  2341. $checkInterval = 5; // 检查间隔
  2342. $lastQueueMessageTime = time(); // 记录上次发送队列消息的时间
  2343. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  2344. while (time() - $startTime < $maxDuration) {
  2345. try {
  2346. // 查询任务状态
  2347. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  2348. if (!$task) {
  2349. echo "data: " . json_encode([
  2350. 'type' => 'error',
  2351. 'message' => '任务不存在'
  2352. ]) . "\n\n";
  2353. if (ob_get_level() > 0) ob_flush();
  2354. flush();
  2355. break;
  2356. }
  2357. // 如果任务完成(成功或失败),结束连接
  2358. if (in_array($task->status, [
  2359. 'success',
  2360. 'failed'
  2361. ])) {
  2362. echo "data: " . json_encode([
  2363. 'type' => 'completed',
  2364. 'data' => [
  2365. 'task_id' => $task->id,
  2366. 'status' => $task->status,
  2367. 'video_url' => $task->compressed_url ?: $task->result_url,
  2368. 'origin_video_url' => $task->result_url,
  2369. 'last_frame_url' => $task->last_frame_url,
  2370. 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : ''
  2371. ]
  2372. ]) . "\n\n";
  2373. if (ob_get_level() > 0) ob_flush();
  2374. flush();
  2375. break;
  2376. }
  2377. // 每分钟发送一次队列状态消息
  2378. $currentTime = time();
  2379. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  2380. echo "data: " . json_encode([
  2381. 'type' => 'queue',
  2382. 'data' => [
  2383. 'task_id' => $task->id,
  2384. 'status' => $task->status,
  2385. 'elapsed_time' => $currentTime - $startTime,
  2386. 'message' => '任务正在队列中执行...'
  2387. ]
  2388. ]) . "\n\n";
  2389. if (ob_get_level() > 0) ob_flush();
  2390. flush();
  2391. $lastQueueMessageTime = $currentTime;
  2392. }
  2393. sleep($checkInterval);
  2394. } catch (\Exception $e) {
  2395. echo "data: " . json_encode([
  2396. 'type' => 'error',
  2397. 'message' => '查询任务状态失败: ' . $e->getMessage()
  2398. ]) . "\n\n";
  2399. if (ob_get_level() > 0) ob_flush();
  2400. flush();
  2401. sleep($checkInterval);
  2402. }
  2403. }
  2404. // 超时处理
  2405. if (time() - $startTime >= $maxDuration) {
  2406. echo "data: " . json_encode([
  2407. 'type' => 'time_out',
  2408. 'message' => '任务执行超时,请稍后查询任务状态',
  2409. 'data' => [
  2410. 'task_id' => $taskId
  2411. ]
  2412. ]) . "\n\n";
  2413. if (ob_get_level() > 0) ob_flush();
  2414. flush();
  2415. }
  2416. }, 200, [
  2417. 'Content-Type' => 'text/event-stream',
  2418. 'Cache-Control' => 'no-cache',
  2419. 'Connection' => 'keep-alive',
  2420. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  2421. ]);
  2422. }
  2423. /**
  2424. * 预估视频生成所需积分(单一/批量)
  2425. * 传参与创建接口一致,批量场景需额外传 type=batch_segment / batch_act
  2426. *
  2427. * @param Request $request
  2428. * @return mixed
  2429. */
  2430. public function previewCharge(Request $request) {
  2431. $data = $request->all();
  2432. $result = $this->AnimeService->previewCharge($data);
  2433. return $this->success($result);
  2434. }
  2435. /**
  2436. * 批量生成片段视频
  2437. */
  2438. public function batchSetActVideos(Request $request) {
  2439. // 忽略所有超时限制
  2440. set_time_limit(0);
  2441. ini_set('max_execution_time', '0');
  2442. $data = $request->all();
  2443. // 验证参数
  2444. $validator = Validator::make($data, [
  2445. 'anime_id' => 'required|string',
  2446. 'episode_id' => 'required|integer',
  2447. ], [
  2448. 'anime_id.required' => '动漫对话ID不能为空',
  2449. 'episode_id.required' => '剧集ID不能为空',
  2450. 'episode_id.integer' => '剧集ID必须是整数',
  2451. ]);
  2452. if ($validator->fails()) {
  2453. return response()->stream(function () use ($validator) {
  2454. echo "data: " . json_encode([
  2455. 'type' => 'error',
  2456. 'message' => $validator->errors()->first()
  2457. ]) . "\n\n";
  2458. if (ob_get_level() > 0) {
  2459. ob_flush();
  2460. }
  2461. flush();
  2462. }, 200, [
  2463. 'Content-Type' => 'text/event-stream',
  2464. 'Cache-Control' => 'no-cache',
  2465. 'Connection' => 'keep-alive',
  2466. 'X-Accel-Buffering' => 'no',
  2467. ]);
  2468. }
  2469. $animeId = $data['anime_id'];
  2470. $episodeId = $data['episode_id'];
  2471. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  2472. if (!$episode) {
  2473. return response()->stream(function () {
  2474. echo "data: " . json_encode([
  2475. 'type' => 'error',
  2476. 'message' => '分集不存在'
  2477. ]) . "\n\n";
  2478. if (ob_get_level() > 0) {
  2479. ob_flush();
  2480. }
  2481. flush();
  2482. }, 200, [
  2483. 'Content-Type' => 'text/event-stream',
  2484. 'Cache-Control' => 'no-cache',
  2485. 'Connection' => 'keep-alive',
  2486. 'X-Accel-Buffering' => 'no',
  2487. ]);
  2488. }
  2489. $episodeNumber = $episode->episode_number;
  2490. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  2491. // 使用剧集保存的视频参数(saveActVideoGenerateParams 保存的 video_resolution / video_model)
  2492. $videoResolution = !empty($episode->video_resolution) ? $episode->video_resolution : '720p';
  2493. $generate_audio = getProp($data, 'generate_audio', 1);
  2494. // 合并角色、场景和道具作为products,统一字段名为product_name
  2495. $products = [];
  2496. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  2497. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  2498. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  2499. // 处理角色数组
  2500. foreach ($roles as $role) {
  2501. $product = $role;
  2502. // 将role字段重命名为product_name
  2503. if (isset($product['role'])) {
  2504. $product['product_name'] = $product['role'];
  2505. unset($product['role']);
  2506. }
  2507. $product['product'] = 1; // 标记类型为角色
  2508. $products[] = $product;
  2509. }
  2510. // 处理场景数组
  2511. foreach ($scenes as $scene) {
  2512. $product = $scene;
  2513. // 将scene字段重命名为product_name
  2514. if (isset($product['scene'])) {
  2515. $product['product_name'] = $product['scene'];
  2516. unset($product['scene']);
  2517. }
  2518. $product['product'] = 2; // 标记类型为场景
  2519. $products[] = $product;
  2520. }
  2521. // 处理道具数组
  2522. foreach ($props as $prop) {
  2523. $product = $prop;
  2524. // 将prop字段重命名为product_name
  2525. if (isset($product['prop'])) {
  2526. $product['product_name'] = $product['prop'];
  2527. unset($product['prop']);
  2528. }
  2529. $product['product'] = 3; // 标记类型为道具
  2530. $products[] = $product;
  2531. }
  2532. // 处理视频模型(在循环外统一处理)
  2533. // $model = getProp($data, 'model');
  2534. // if (!$model) {
  2535. // // 用户没有输入,从episode表获取
  2536. // $model = getProp($episode, 'video_model');
  2537. // if (!$model) {
  2538. // // episode表也没有,使用默认值
  2539. // $model = 'zhizhen-20';
  2540. // }
  2541. // }
  2542. // 使用剧集保存的视频模型,未保存时使用默认值
  2543. $model = getProp($episode, 'video_model');
  2544. if (!$model) {
  2545. $model = 'seed-2'; // 使用默认值
  2546. }
  2547. // 验证模型是否在可用模型表中
  2548. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2549. $model = 'seed-2';
  2550. }
  2551. // 获取所有分镜信息
  2552. $acts = DB::table('mp_episode_segments')
  2553. ->where('anime_id', $animeId)
  2554. ->where('episode_id', $episodeId)
  2555. ->orderBy('act_number')
  2556. ->get();
  2557. if ($acts->isEmpty()) {
  2558. return response()->stream(function () {
  2559. echo "data: " . json_encode([
  2560. 'type' => 'error',
  2561. 'message' => '未找到分镜数据'
  2562. ]) . "\n\n";
  2563. if (ob_get_level() > 0) ob_flush();
  2564. flush();
  2565. }, 200, [
  2566. 'Content-Type' => 'text/event-stream',
  2567. 'Cache-Control' => 'no-cache',
  2568. 'Connection' => 'keep-alive',
  2569. 'X-Accel-Buffering' => 'no',
  2570. ]);
  2571. }
  2572. foreach($acts as $act) {
  2573. $videoDuration = $act->act_duration;
  2574. if (!$videoDuration || $videoDuration <= 0) {
  2575. return response()->stream(function () {
  2576. echo "data: " . json_encode([
  2577. 'type' => 'error',
  2578. 'message' => '请检查是否有时长为空的片段'
  2579. ]) . "\n\n";
  2580. if (ob_get_level() > 0) ob_flush();
  2581. flush();
  2582. }, 200, [
  2583. 'Content-Type' => 'text/event-stream',
  2584. 'Cache-Control' => 'no-cache',
  2585. 'Connection' => 'keep-alive',
  2586. 'X-Accel-Buffering' => 'no',
  2587. ]);
  2588. }
  2589. }
  2590. // 余额预检:按实际需要生成的片段逐条按时长估算积分,不足直接报错
  2591. $needPoints = 0;
  2592. foreach ($acts as $act) {
  2593. if ($act->video_task_status === '生成中' || (int)$act->current_type === 2) {
  2594. continue;
  2595. }
  2596. $duration = (int)ceil((float)$act->act_duration);
  2597. if ($duration <= 0) {
  2598. $duration = 5; // 无时长时按默认5秒预估
  2599. }
  2600. $needPoints += $this->pointsService->getVideoChargePoints([
  2601. 'model' => $model,
  2602. 'video_resolution' => $videoResolution,
  2603. 'video_duration' => $duration,
  2604. 'ratio' => $ratio,
  2605. 'generate_audio' => (int)$generate_audio,
  2606. ]);
  2607. }
  2608. if ($needPoints > 0) {
  2609. $this->pointsService->checkUserPointsEnough($needPoints);
  2610. }
  2611. // 批量创建视频任务
  2612. $taskIds = [];
  2613. $actTasks = [];
  2614. foreach ($acts as $act) {
  2615. try {
  2616. // 检查视频任务正在生成中或当前状态为视频
  2617. if ($act->video_task_status === '生成中') {
  2618. $actTasks[] = [
  2619. 'act_id' => $act->id,
  2620. 'task_id' => $act->video_task_id,
  2621. 'act_number' => $act->act_number,
  2622. 'act_content' => $act->act_content,
  2623. 'audio_duration' => $act->audio_duration,
  2624. ];
  2625. continue;
  2626. }
  2627. if ((int)$act->current_type === 2) {
  2628. continue;
  2629. }
  2630. // 获取分镜内容
  2631. $actContent = $act->act_show_content ?: '';
  2632. // 构建完整的提示词
  2633. $processResult = $this->AnimeService->processActContentWithProducts($actContent, $products);
  2634. $fullPrompt = $processResult['content'];
  2635. $reference_images = $processResult['reference_images'];
  2636. $videoDuration = $act->act_duration;
  2637. // 构建视频生成参数
  2638. $videoParams = [
  2639. 'model' => $model,
  2640. 'alias_act_id' => $act->id,
  2641. 'prompt' => $fullPrompt,
  2642. 'video_duration' => $videoDuration,
  2643. 'video_resolution' => $videoResolution,
  2644. 'seed' => -1,
  2645. 'ratio' => $ratio,
  2646. 'generate_audio' => (int)$generate_audio === 0 ? false : true,
  2647. 'draft' => false,
  2648. 'watermark' => false,
  2649. 'camera_fixed' => false,
  2650. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  2651. ];
  2652. // 如果分镜有图片,作为首帧
  2653. $hasImage = !empty($act->img_url);
  2654. $hasVideo = !empty($act->video_url);
  2655. if ($hasImage) {
  2656. $videoParams['first_frame_url'] = $act->img_url;
  2657. }
  2658. // 构建content数组
  2659. $videoParams['content'] = [
  2660. [
  2661. 'type' => 'text',
  2662. 'text' => $videoParams['prompt'],
  2663. ]
  2664. ];
  2665. // 如果有首帧图片,添加到content中
  2666. if ($hasImage) {
  2667. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  2668. $videoParams['content'][] = [
  2669. 'type' => 'image_url',
  2670. 'image_url' => [
  2671. 'url' => $videoParams['first_frame_url'],
  2672. ],
  2673. 'role' => 'reference_image',
  2674. ];
  2675. }else {
  2676. $videoParams['content'][] = [
  2677. 'type' => 'image_url',
  2678. 'image_url' => [
  2679. 'url' => $videoParams['first_frame_url'],
  2680. ],
  2681. 'role' => 'first_frame',
  2682. ];
  2683. }
  2684. }
  2685. // 获取配音音频URL和时长
  2686. $audioUrl = $act->audio_url ?? '';
  2687. $audioDuration = $act->audio_duration ?? 0;
  2688. // 音频传入的前提:必须有至少一张图片或一个视频
  2689. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  2690. // 根据模型选择不同的视频生成方法
  2691. if (strpos($model, 'jimeng') !== false) {
  2692. // 即梦模型参数调整
  2693. $videoParams['video_duration'] = $videoDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  2694. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  2695. unset($videoParams['ratio']);
  2696. unset($videoParams['content']); // 即梦不使用content格式
  2697. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  2698. } elseif (strpos($model, 'kling') !== false) {
  2699. // Keling模型参数调整
  2700. $videoParams['video_duration'] = max(3, min(15, ceil($videoDuration))); // Keling支持3-15秒
  2701. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  2702. unset($videoParams['ratio']);
  2703. unset($videoParams['content']); // Keling不使用content格式
  2704. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  2705. } elseif (strpos($model, 'zhizhen') !== false) {
  2706. // 构建统一API参数
  2707. $unifiedParams = [
  2708. 'model_code' => $model,
  2709. 'alias_act_id' => $act->id,
  2710. 'prompt' => trim($fullPrompt),
  2711. 'video_duration' => $videoDuration,
  2712. 'video_resolution' => strtolower($videoParams['video_resolution']),
  2713. 'video_ratio' => $ratio,
  2714. 'seed' => -1,
  2715. ];
  2716. // 构建parameters参数
  2717. $parameters = [
  2718. 'seconds' => $unifiedParams['video_duration'],
  2719. 'resolution' => $unifiedParams['video_resolution'],
  2720. 'ratio' => $ratio,
  2721. // 'video_mode' => 'multi_image',
  2722. // 'mode' => 'multi_image',
  2723. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  2724. ];
  2725. $hasImage = false;
  2726. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  2727. if ($hasImage) {
  2728. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  2729. if (isset($videoParams['tail_frame_url'])) {
  2730. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  2731. }
  2732. }
  2733. if ($reference_images) {
  2734. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  2735. $reference_images = $this->AIImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  2736. $parameters['reference_images'] = $reference_images;
  2737. $parameters['video_mode'] = 'multi_image';
  2738. $parameters['mode'] = 'multi_image';
  2739. }
  2740. $unifiedParams['parameters'] = $parameters;
  2741. // 调用统一API创建任务
  2742. $task = $this->AIVideoGenerationService->createUnifiedApiTask($unifiedParams);
  2743. } else {
  2744. // Seedance模型(默认)
  2745. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  2746. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  2747. // 添加配音音频到content中
  2748. $videoParams['content'][] = [
  2749. 'type' => 'audio_url',
  2750. 'audio_url' => [
  2751. 'url' => $audioUrl,
  2752. ],
  2753. 'role' => 'reference_audio',
  2754. ];
  2755. // 优化提示词,增加音频相关描述
  2756. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  2757. $videoParams['prompt'] = $audioPrompt;
  2758. $videoParams['content'][0]['text'] = $audioPrompt;
  2759. } else if ($videoDuration) {
  2760. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  2761. $videoParams['video_duration'] = max(4, min(12, ceil($videoDuration))); // seedance支持2-12s
  2762. }
  2763. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  2764. }
  2765. $taskIds[] = $task->id;
  2766. // 更新分镜表的视频任务信息
  2767. DB::table('mp_episode_segments')
  2768. ->where('id', $act->id)
  2769. ->update([
  2770. 'video_task_id' => $task->id,
  2771. 'video_task_status' => '生成中',
  2772. 'updated_at' => date('Y-m-d H:i:s')
  2773. ]);
  2774. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  2775. if ((int)$episodeNumber === 1 && (int)$act->act_number === 1) {
  2776. Redis::sadd('anime_act_first_frame_urls', $act->id);
  2777. }
  2778. $actTasks[] = [
  2779. 'act_id' => $act->id,
  2780. 'task_id' => $task->id,
  2781. 'act_number' => $act->act_number,
  2782. 'content' => $fullPrompt,
  2783. 'audio_duration' => $act->audio_duration,
  2784. ];
  2785. } catch (\Exception $e) {
  2786. $logData = [
  2787. 'act_id' => $act->id,
  2788. 'anime_id' => $animeId,
  2789. 'error' => $e->getMessage(),
  2790. ];
  2791. dLog('anime')->error('创建分镜视频任务失败', $logData);
  2792. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  2793. continue;
  2794. }
  2795. }
  2796. if (empty($taskIds)) {
  2797. // 没有任务时,获取完整剧集信息进行验证
  2798. $episode = $this->AnimeService->episodeInfoForAce([
  2799. 'anime_id' => $animeId,
  2800. 'episode_id' => $episodeId
  2801. ]);
  2802. // 检查所有片段是否都已生成视频且current_type=2
  2803. $allActsValid = true;
  2804. $invalidActs = [];
  2805. $total_tasks_count = count($episode['acts']);
  2806. foreach ($episode['acts'] as $act) {
  2807. $videoUrl = getProp($act, 'video_url');
  2808. $currentType = getProp($act, 'current_type');
  2809. // 检查视频是否已生成
  2810. if (!$videoUrl) {
  2811. $allActsValid = false;
  2812. $invalidActs[] = [
  2813. 'act_number' => getProp($act, 'act_number'),
  2814. 'reason' => '视频未生成'
  2815. ];
  2816. continue;
  2817. }
  2818. // 检查current_type是否为2
  2819. if ($currentType != 2) {
  2820. $allActsValid = false;
  2821. $invalidActs[] = [
  2822. 'act_number' => getProp($act, 'act_number'),
  2823. 'reason' => '当前不是视频模式'
  2824. ];
  2825. }
  2826. }
  2827. // 如果所有分镜都满足条件,使用SSE格式返回完成状态
  2828. if ($allActsValid) {
  2829. return response()->stream(function () use ($episode, $total_tasks_count) {
  2830. echo "data: " . json_encode([
  2831. 'type' => 'completed',
  2832. 'total_tasks_count' => $total_tasks_count,
  2833. 'completed_tasks_count' => $total_tasks_count,
  2834. 'success_tasks_count' => $total_tasks_count,
  2835. 'episode' => $episode
  2836. ]) . "\n\n";
  2837. if (ob_get_level() > 0) ob_flush();
  2838. flush();
  2839. }, 200, [
  2840. 'Content-Type' => 'text/event-stream',
  2841. 'Cache-Control' => 'no-cache',
  2842. 'Connection' => 'keep-alive',
  2843. 'X-Accel-Buffering' => 'no',
  2844. ]);
  2845. } else {
  2846. // 有未完成或不满足条件的分镜,使用SSE格式报错
  2847. $errorMsg = '存在未完成的片段:' . "\n";
  2848. foreach ($invalidActs as $invalid) {
  2849. $errorMsg .= "分镜{$invalid['act_number']}:{$invalid['reason']}\n";
  2850. }
  2851. return response()->stream(function () use ($errorMsg) {
  2852. echo "data: " . json_encode([
  2853. 'type' => 'error',
  2854. 'message' => trim($errorMsg)
  2855. ]) . "\n\n";
  2856. if (ob_get_level() > 0) ob_flush();
  2857. flush();
  2858. }, 200, [
  2859. 'Content-Type' => 'text/event-stream',
  2860. 'Cache-Control' => 'no-cache',
  2861. 'Connection' => 'keep-alive',
  2862. 'X-Accel-Buffering' => 'no',
  2863. ]);
  2864. }
  2865. }
  2866. // 保存模型到episode表
  2867. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  2868. 'video_model' => $model,
  2869. 'updated_at' => date('Y-m-d H:i:s')
  2870. ]);
  2871. // 记录开始时间(包含创建任务的时间)
  2872. $startTime = time();
  2873. $maxDuration = 7200;
  2874. $uid = Site::getUid();
  2875. // 设置 SSE 响应头并开始长连接
  2876. return response()->stream(function () use ($taskIds, $actTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  2877. $checkInterval = 10; // 每10秒检查一次
  2878. // 初始化任务数组
  2879. $totalTasks = $taskIds; // 所有任务ID
  2880. $completeTasks = []; // 已完成的任务ID(包含失败)
  2881. $successTasks = []; // 成功的任务ID
  2882. // 发送初始任务创建信息
  2883. echo "data: " . json_encode([
  2884. 'type' => 'init',
  2885. 'total_tasks_count' => count($totalTasks),
  2886. 'completed_tasks_count' => count($completeTasks),
  2887. 'success_tasks_count' => count($successTasks)
  2888. ]) . "\n\n";
  2889. if (ob_get_level() > 0) ob_flush();
  2890. flush();
  2891. while (time() - $startTime < $maxDuration) {
  2892. try {
  2893. $hasUpdate = false; // 标记是否有更新
  2894. // 获取所有任务的最新状态
  2895. foreach ($totalTasks as $taskId) {
  2896. // 如果任务已经在完成列表中,跳过
  2897. if (in_array($taskId, $completeTasks)) {
  2898. continue;
  2899. }
  2900. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  2901. if (!$task) {
  2902. continue;
  2903. }
  2904. // // 如果任务还在处理中,查询最新状态
  2905. // if ($task->status === 'processing') {
  2906. // // 根据任务类型查询不同的状态
  2907. // if ($task->api_type === 'jimeng') {
  2908. // $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  2909. // } elseif ($task->api_type === 'keling') {
  2910. // $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  2911. // } elseif ($task->api_type === 'zzengine') {
  2912. // $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
  2913. // } else {
  2914. // $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  2915. // }
  2916. // if (isset($statusResult['status'])) {
  2917. // // 更新任务状态
  2918. // $task->update([
  2919. // 'status' => $statusResult['status'],
  2920. // 'result_json' => $statusResult['result_json'] ?? [],
  2921. // 'result_url' => $statusResult['result_url'] ?? null,
  2922. // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  2923. // 'error_message' => $statusResult['error_message'] ?? null,
  2924. // 'completed_at' => in_array($statusResult['status'], [
  2925. // 'success',
  2926. // 'failed'
  2927. // ]) ? now() : null
  2928. // ]);
  2929. // // 如果任务成功,更新分镜表
  2930. // if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  2931. // try {
  2932. // DB::beginTransaction();
  2933. // $now = date('Y-m-d H:i:s');
  2934. // // 获取分镜ID
  2935. // $actId = null;
  2936. // foreach ($actTasks as $actTask) {
  2937. // if ($actTask['task_id'] == $taskId) {
  2938. // $actId = $actTask['act_id'];
  2939. // $content = $actTask['content'];
  2940. // $audio_duration = $actTask['audio_duration'];
  2941. // break;
  2942. // }
  2943. // }
  2944. // if ($actId) {
  2945. // // 更新分镜表
  2946. // $actUpdateData = [
  2947. // 'origin_video_url' => $statusResult['result_url'],
  2948. // 'video_task_status' => '已完成',
  2949. // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  2950. // 'current_type' => 2,
  2951. // 'updated_at' => $now
  2952. // ];
  2953. // $compressed_video_url = compressVideo($statusResult['result_url']);
  2954. // $actUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  2955. // // 只有当video_duration存在且大于0时才更新
  2956. // if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  2957. // $actUpdateData['video_duration'] = $statusResult['video_duration'];
  2958. // $actUpdateData['video_time_point_start'] = 0;
  2959. // $actUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  2960. // }
  2961. // $updateResult = DB::table('mp_episode_segments')
  2962. // ->where('id', $actId)
  2963. // ->update($actUpdateData);
  2964. // if ($updateResult) {
  2965. // // 更新分镜视频成功后新增对话记录
  2966. // // 获取参考图记录
  2967. // $reference_images = getProp($task, 'ref_image_url');
  2968. // if (!$reference_images) $reference_images = json_encode([], 256);
  2969. // $records = [
  2970. // [
  2971. // 'uid' => $uid,
  2972. // 'anime_id' => $animeId,
  2973. // 'sequence' => $episodeNumber,
  2974. // 'role' => 'user',
  2975. // 'content' => '片段转视频',
  2976. // 'act_id' => $actId,
  2977. // 'video_url' => '',
  2978. // 'created_at' => $now,
  2979. // 'updated_at' => $now
  2980. // ],
  2981. // [
  2982. // 'uid' => $uid,
  2983. // 'anime_id' => $animeId,
  2984. // 'sequence' => $episodeNumber,
  2985. // 'role' => 'assistant',
  2986. // 'content' => $content ?? '',
  2987. // 'act_id' => $actId,
  2988. // 'video_url' => $statusResult['result_url'],
  2989. // 'reference_images' => $reference_images,
  2990. // 'created_at' => $now,
  2991. // 'updated_at' => $now
  2992. // ]
  2993. // ];
  2994. // DB::table('mp_anime_records')->insert($records);
  2995. // }
  2996. // }
  2997. // DB::commit();
  2998. // } catch (\Exception $e) {
  2999. // DB::rollBack();
  3000. // $logData = [
  3001. // 'task_id' => $taskId,
  3002. // 'error' => $e->getMessage()
  3003. // ];
  3004. // dLog('anime')->error('视频任务处理失败', $logData);
  3005. // logDB('anime', 'error', '视频任务处理失败', $logData);
  3006. // }
  3007. // } elseif ($statusResult['status'] === 'failed') {
  3008. // // 获取分镜ID并更新失败状态
  3009. // foreach ($actTasks as $actTask) {
  3010. // if ($actTask['task_id'] == $taskId) {
  3011. // DB::table('mp_episode_segments')
  3012. // ->where('id', $actTask['act_id'])
  3013. // ->update([
  3014. // 'video_task_status' => '失败',
  3015. // 'updated_at' => date('Y-m-d H:i:s')
  3016. // ]);
  3017. // break;
  3018. // }
  3019. // }
  3020. // }
  3021. // }
  3022. // }
  3023. // 检查任务是否完成(成功或失败)
  3024. if (in_array($task->status, ['success', 'failed'])) {
  3025. $completeTasks[] = $taskId;
  3026. $hasUpdate = true;
  3027. if ($task->status === 'success') {
  3028. $successTasks[] = $taskId;
  3029. }
  3030. }
  3031. }
  3032. // 如果有更新,发送update通知
  3033. if ($hasUpdate) {
  3034. echo "data: " . json_encode([
  3035. 'type' => 'update',
  3036. 'total_tasks_count' => count($totalTasks),
  3037. 'completed_tasks_count' => count($completeTasks),
  3038. 'success_tasks_count' => count($successTasks)
  3039. ]) . "\n\n";
  3040. if (ob_get_level() > 0) ob_flush();
  3041. flush();
  3042. }
  3043. // 如果所有任务都完成了,结束连接
  3044. if (count($completeTasks) >= count($totalTasks)) {
  3045. // 重新获取完整的剧集信息
  3046. $updatedEpisode = $this->AnimeService->episodeInfoForAce([
  3047. 'anime_id' => $animeId,
  3048. 'episode_id' => $episodeId
  3049. ]);
  3050. echo "data: " . json_encode([
  3051. 'type' => 'completed',
  3052. 'total_tasks_count' => count($totalTasks),
  3053. 'completed_tasks_count' => count($completeTasks),
  3054. 'success_tasks_count' => count($successTasks),
  3055. 'episode' => $updatedEpisode
  3056. ]) . "\n\n";
  3057. if (ob_get_level() > 0) ob_flush();
  3058. flush();
  3059. break;
  3060. }
  3061. // 检查是否超时
  3062. if (time() - $startTime >= $maxDuration) {
  3063. break;
  3064. }
  3065. sleep($checkInterval);
  3066. } catch (\Exception $e) {
  3067. echo "data: " . json_encode([
  3068. 'type' => 'error',
  3069. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  3070. 'total_tasks_count' => count($totalTasks),
  3071. 'completed_tasks_count' => count($completeTasks),
  3072. 'success_tasks_count' => count($successTasks)
  3073. ]) . "\n\n";
  3074. if (ob_get_level() > 0) ob_flush();
  3075. flush();
  3076. // 检查是否超时,如果超时则停止循环
  3077. if (time() - $startTime >= $maxDuration) {
  3078. break;
  3079. }
  3080. sleep($checkInterval);
  3081. }
  3082. }
  3083. // 超时处理
  3084. if (time() - $startTime >= $maxDuration) {
  3085. echo "data: " . json_encode([
  3086. 'type' => 'time_out',
  3087. 'message' => '批量视频生成已超时,停止状态查询',
  3088. 'total_tasks_count' => count($totalTasks),
  3089. 'completed_tasks_count' => count($completeTasks),
  3090. 'success_tasks_count' => count($successTasks)
  3091. ]) . "\n\n";
  3092. if (ob_get_level() > 0) ob_flush();
  3093. flush();
  3094. }
  3095. }, 200, [
  3096. 'Content-Type' => 'text/event-stream',
  3097. 'Cache-Control' => 'no-cache',
  3098. 'Connection' => 'keep-alive',
  3099. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  3100. ]);
  3101. }
  3102. }