AnimeController.php 147 KB

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