AnimeController.php 136 KB

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