AnimeController.php 139 KB

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