AnimeController.php 135 KB

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