AnimeController.php 143 KB

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