AnimeController.php 155 KB

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