AnimeController.php 142 KB

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