| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295 |
- <?php
- namespace App\Http\Controllers\Anime;
- use App\Transformer\Anime\AnimeTransformer;
- use App\Facade\Site;
- use App\Consts\ErrorConst;
- use App\Exceptions\ApiException;
- use App\Libs\ApiResponse;
- use App\Libs\Utils;
- use App\Models\MpGenerateVideoTask;
- use App\Services\AIGeneration\AIImageGenerationService;
- use App\Services\AIGeneration\AIVideoGenerationService;
- use App\Services\Anime\AnimeService;
- use Illuminate\Http\Request;
- use Illuminate\Routing\Controller as BaseController;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Redis;
- use Illuminate\Support\Facades\Validator;
- class AnimeController extends BaseController
- {
- use ApiResponse;
- protected $AnimeService;
- protected $AIImageGenerationService;
- protected $AIVideoGenerationService;
- public function __construct(
- AnimeService $AnimeService,
- AIImageGenerationService $AIImageGenerationService,
- AIVideoGenerationService $AIVideoGenerationService
- ) {
- $this->AnimeService = $AnimeService;
- $this->AIImageGenerationService = $AIImageGenerationService;
- $this->AIVideoGenerationService = $AIVideoGenerationService;
- }
- // 文字模型
- public function textModel() {
- $query = DB::table('mp_text_models')->where('is_enabled', 1);
-
- // 支持 model 搜索
- if ($model = request('model')) {
- $query->where('model', 'like', "%{$model}%");
- }
-
- // 支持 name 搜索
- if ($name = request('name')) {
- $query->where('name', 'like', "%{$name}%");
- }
-
- $models = $query->select('model', 'name')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- return $this->success($models);
- }
- // 图片模型
- public function imageModel() {
- $query = DB::table('mp_image_models')->where('is_enabled', 1);
-
- // 支持 model 搜索
- if ($model = request('model')) {
- $query->where('model', 'like', "%{$model}%");
- }
-
- // 支持 name 搜索
- if ($name = request('name')) {
- $query->where('name', 'like', "%{$name}%");
- }
-
- $models = $query->select('model', 'name')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- return $this->success($models);
- }
- // 视频模型
- public function videoModel() {
- $query = DB::table('mp_video_models')->where('is_enabled', 1);
-
- // 支持 model 搜索
- if ($model = request('model')) {
- $query->where('model', 'like', "%{$model}%");
- }
-
- // 支持 name 搜索
- if ($name = request('name')) {
- $query->where('name', 'like', "%{$name}%");
- }
-
- $models = $query->select('model', 'name')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- return $this->success($models);
- }
- public function artStyleList()
- {
- $result = [
- [
- 'art_style' => '唯美真人风格',
- '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"
- ],
- [
- 'art_style' => '真人古风风格',
- '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"
- ],
- [
- 'art_style' => '日系动漫风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/日系动漫风格.jpg"
- ],
- [
- 'art_style' => '国漫风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/国漫风格.jpg"
- ],
- [
- 'art_style' => 'Q版卡通风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/Q版卡通风格.jpg"
- ],
- [
- 'art_style' => '简约扁平风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/简约扁平风格.jpg"
- ],
- [
- 'art_style' => '古风仙侠风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/古风仙侠风格.jpg"
- ],
- [
- 'art_style' => '武侠风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/武侠风格.jpg"
- ],
- [
- 'art_style' => '新中式水墨风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/新中式水墨风格.jpg"
- ],
- [
- 'art_style' => '写实插画风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/写实插画风格.jpg"
- ],
- [
- 'art_style' => '3D卡通风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/3D卡通风格.jpg"
- ],
- [
- 'art_style' => '条漫风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/条漫风格.jpg"
- ],
- [
- 'art_style' => '赛博朋克风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/赛博朋克风格.jpg"
- ],
- [
- 'art_style' => '暗黑悬疑风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/暗黑悬疑风格.jpg"
- ],
- [
- 'art_style' => '治愈清新风格',
- 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/治愈清新风格.jpg"
- ],
- ];
- return $this->success($result);
- }
- // 新建动漫
- public function createAnime(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->createAnime($data);
- return $this->success(['anime_id' => $result]);
- }
- // 编辑动漫
- public function editAnime(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->editAnime($data);
- return $this->success(['success'=>$result ? 1 : 0]);
- }
- // 删除动漫
- public function delAnime(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->delAnime($data);
- return $this->success(['success'=>$result ? 1 : 0]);
- }
- // 批量生成主体图片
- public function batchSetRoleImg(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- $result = $this->AnimeService->batchSetRoleImg($data);
- return $this->success($result);
- }
- // 批量生成场景图片
- public function batchSetSceneImg(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- $result = $this->AnimeService->batchSetSceneImg($data);
- return $this->success($result);
- }
- // 修改分集主体列表
- public function changeEpisodeRoles(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->changeEpisodeRoles($data);
- return $this->success(['success'=>$result ? 1 : 0]);
- }
- // 修改分集场景列表
- public function changeEpisodeScenes(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->changeEpisodeScenes($data);
- return $this->success(['success'=>$result ? 1 : 0]);
- }
- // 编辑分镜剧本
- public function editSegment(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->editSegment($data);
- return $this->success(['success'=>$result ? 1 : 0]);
- }
- // 动漫对话列表
- public function chatList(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->chatList($data);
- return $this->success($result, [new AnimeTransformer(), 'newBuildChatList']);
- }
- // 动漫对话历史记录
- public function chatHistory(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->chatHistory($data);
- return $this->success($result);
- }
- // 动漫大纲
- public function animeDetail(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->animeDetail($data);
- return $this->success($result);
- }
- // 动漫剧集
- public function episodeInfo(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->episodeInfo($data);
- return $this->success($result);
- }
- // 动漫剧集(全能模式)
- public function episodeInfoForAce(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->episodeInfoForAce($data);
- return $this->success($result);
- }
- // 分镜信息
- public function segmentInfo(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->segmentInfo($data);
- return $this->success($result);
- }
- // 复制剧集副本
- public function copyEpisodeVersion(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->copyEpisodeVersion($data);
- return $this->success($result);
- }
- // 剧集副本列表
- public function episodeVersions(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->episodeVersions($data);
- return $this->success($result);
- }
- // 绑定剧集副本
- public function bindEpisodeVersion(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->bindEpisodeVersion($data);
- return $this->success(['success' => $result ? 1 : 0]);
- }
- // 对话改图
- public function chatChangeImg(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->chatChangeImg($data);
- return $this->success(['img_url' => $result]);
- }
- public function segmentChatHistory(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->segmentChatHistory($data);
- return $this->success($result);
- }
- // 一键生成分镜
- public function batchSetSegmentPics(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- $result = $this->AnimeService->batchSetSegmentPics($data);
- return $this->success($result);
- }
- // 重新生成分镜
- public function reGenerateSegment(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- $result = $this->AnimeService->reGenerateSegment($data);
- return $this->success(['img_url'=>$result]);
- }
- // 添加分镜
- public function addSegment(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- $result = $this->AnimeService->addSegment($data);
- return $this->success($result);
- }
- // 复制分镜
- public function copySegment(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->copySegment($data);
- return $this->success($result);
- }
- // 移动分镜
- public function moveSegment(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->moveSegment($data);
- return $this->success(['success'=>$result ? 1: 0]);
- }
- // 删除分镜
- public function delSegment(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->delSegment($data);
- return $this->success(['success'=>$result ? 1: 0]);
- }
- public function applySegment(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->applySegment($data);
- return $this->success(['success'=>$result ? 1: 0]);
- }
- // 添加片段
- public function addAct(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- $result = $this->AnimeService->addAct($data);
- return $this->success($result);
- }
- // 编辑片段
- public function editAct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->editAct($data);
- return $this->success(['success'=>$result ? 1 : 0]);
- }
- // 复制片段
- public function copyAct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->copyAct($data);
- return $this->success($result);
- }
- // 移动片段
- public function moveAct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->moveAct($data);
- return $this->success(['success'=>$result ? 1: 0]);
- }
- // 删除片段
- public function delAct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->delAct($data);
- return $this->success(['success'=>$result ? 1: 0]);
- }
- // 应用片段
- public function applyAct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->applyAct($data);
- return $this->success(['success'=>$result ? 1: 0]);
- }
- // 片段对话历史记录
- public function actChatHistory(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->actChatHistory($data);
- return $this->success($result);
- }
- // 分镜历史图片|视频
- public function segmentHistory(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->segmentHistory($data);
- return $this->success($result);
- }
- public function createSegmentVideoTask(Request $request) {
- $uid = Site::getUid();
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
-
- // 验证参数
- $validator = Validator::make($data, [
- 'segment_id' => 'required|string',
- 'tail_frame' => 'nullable|string|max:500',
- ], [
- 'segment_id.required' => '分镜ID不能为空',
- 'tail_frame.max' => '尾帧描述不能超过500个字符',
- ]);
-
- if ($validator->fails()) {
- Utils::throwError('1002:' . $validator->errors()->first());
- }
-
- // 创建视频生成任务
- $result = $this->AnimeService->createSegmentVideoTask($data);
- $taskId = $result['task_id'];
-
- // 设置 SSE 响应头
- return response()->stream(function () use ($taskId, $result, $uid) {
- // 设置 SSE 响应头
- echo "data: " . json_encode([
- 'type' => 'init',
- 'data' => $result
- ]) . "\n\n";
- ob_flush();
- flush();
-
- $startTime = time();
- $maxDuration = 300; // 5分钟超时
- $checkInterval = 5; // 每5秒检查一次
-
- while (time() - $startTime < $maxDuration) {
- try {
- // 查询任务状态
- $task = \App\Models\MpGenerateVideoTask::find($taskId);
- if (!$task) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '任务不存在'
- ]) . "\n\n";
- ob_flush();
- flush();
- break;
- }
-
- // 如果任务还在处理中,查询最新状态
- if ($task->status === 'processing') {
- // 根据任务类型查询不同的状态
- if ($task->api_type === 'jimeng') {
- $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
- } elseif ($task->api_type === 'keling') {
- $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
- } elseif ($task->api_type === 'zzengine') {
- $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
- } else {
- $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
- }
- if (isset($statusResult['status'])) {
- // 更新任务状态
- $task->update([
- 'status' => $statusResult['status'],
- 'result_url' => $statusResult['result_url'] ?? null,
- 'compressed_url' => $statusResult['compressed_url'] ?? null,
- 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- 'error_message' => $statusResult['error_message'] ?? null,
- 'completed_at' => in_array($statusResult['status'], [
- 'success',
- 'failed'
- ]) ? now() : null
- ]);
-
- // 如果任务成功,更新分镜表
- if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
- try {
- DB::beginTransaction();
-
- $now = date('Y-m-d H:i:s');
-
- // 获取分镜ID
- $segment = DB::table('mp_episode_segments')
- ->where('video_task_id', $taskId)
- ->first();
-
- if (!$segment) {
- throw new \Exception('未找到对应的分镜记录');
- }
-
- $segmentId = $segment->segment_id;
- $anime_id = $segment->anime_id;
- $episode_number = $segment->episode_number;
- $tail_frame = $segment->tail_frame;
-
- // 更新分镜表
- $segmentUpdateData = [
- 'origin_video_url' => $statusResult['result_url'],
- 'video_task_status' => '已完成',
- 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- 'current_type' => 2,
- 'updated_at' => $now
- ];
- $compressed_video_url = compressVideo($statusResult['result_url']);
- $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
-
- // 只有当video_duration存在且大于0时才更新
- if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
- $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
- $segmentUpdateData['video_time_point_start'] = 0;
- // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
- $segmentUpdateData['video_time_point_end'] = $segment->audio_duration ?? 0;
- }
-
- $updateResult = DB::table('mp_episode_segments')
- ->where('segment_id', $segmentId)
- ->update($segmentUpdateData);
-
- if (!$updateResult) {
- Utils::throwError('20003:更新分镜表失败');
- }
- // 更新分镜视频成功后新增对话记录
- // 保存对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'user',
- 'content' => '图片转视频',
- 'segment_id' => $segmentId,
- 'video_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'assistant',
- 'content' => $tail_frame,
- 'segment_id' => $segmentId,
- 'video_url' => $statusResult['result_url'],
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
- DB::table('mp_anime_records')->insert($records);
-
- DB::commit();
-
- } catch (\Exception $e) {
- DB::rollBack();
-
- $logData = [
- 'task_id' => $taskId,
- 'error' => $e->getMessage()
- ];
- dLog('anime')->error('视频任务处理失败', $logData);
- logDB('anime', 'error', '视频任务处理失败', $logData);
- }
- } elseif ($statusResult['status'] === 'failed') {
- DB::table('mp_episode_segments')
- ->where('video_task_id', $taskId)
- ->update([
- 'video_task_status' => '失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- }
- }
-
- // 发送当前状态
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'result_url' => $task->result_url,
- 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : '',
- 'elapsed_time' => time() - $startTime
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
-
- // 如果任务完成(成功或失败),结束连接
- if (in_array($task->status, [
- 'success',
- 'failed'
- ])) {
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'video_url' => $task->compressed_url ?: $task->result_url,
- 'origin_video_url' => $task->result_url,
- 'last_frame_url' => $task->last_frame_url,
- 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : ''
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- break;
- }
-
- sleep($checkInterval);
-
- } catch (\Exception $e) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '查询任务状态失败: ' . $e->getMessage()
- ]) . "\n\n";
- ob_flush();
- flush();
- sleep($checkInterval);
- }
- }
-
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- echo "data: " . json_encode([
- 'type' => 'time_out',
- 'message' => '任务执行超时,请稍后查询任务状态',
- 'data' => [
- 'task_id' => $taskId
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
- ]);
- }
-
- /**
- * 批量生成分镜视频
- */
- public function batchSetSegmentVideos(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
-
- // 验证参数
- $validator = Validator::make($data, [
- 'anime_id' => 'required|string',
- 'episode_id' => 'required|integer',
- ], [
- 'anime_id.required' => '动漫对话ID不能为空',
- 'episode_id.required' => '剧集ID不能为空',
- 'episode_id.integer' => '剧集ID必须是整数',
- ]);
-
- if ($validator->fails()) {
- Utils::throwError('1002:' . $validator->errors()->first());
- }
-
- $animeId = $data['anime_id'];
- $episodeId = $data['episode_id'];
- $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
- if (!$episode) Utils::throwError('20003:分集不存在');
- $episodeNumber = $episode->episode_number;
- $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
- $generate_audio = getProp($data, 'generate_audio', 0);
-
- // 处理视频模型(在循环外统一处理)
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,从episode表获取
- $model = getProp($episode, 'video_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedance-1-5-pro-251215';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seedance-1-5-pro-251215';
- }
-
- // 获取所有分镜信息
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->whereNotIn('video_task_status', ['已完成', '生成中'])
- ->orderBy('segment_number')
- ->get();
-
- if ($segments->isEmpty()) {
- Utils::throwError('20003:未找到分镜数据');
- }
-
- // 批量创建视频任务
- $taskIds = [];
- $segmentTasks = [];
-
- foreach ($segments as $segment) {
- try {
- // 检查视频任务正在生成中或当前状态为视频
- if ($segment->video_task_status === '生成中' || (int)$segment->current_type === 2) {
- continue;
- }
-
- // 获取分镜内容
- $segmentContent = $segment->segment_content ?: '';
- $tailFrame = $segment->tail_frame ?: '';
-
- // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
- $hasDialogue = false;
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $dialogue = trim($dialogueMatch[1]);
-
- // 如果台词不为空且不是"无"
- if (!empty($dialogue) && $dialogue !== '无') {
- // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
- $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
- if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
- $hasDialogue = true;
- }
-
- $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
- $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
- // 句首或句尾没有中文双引号,则分别添加中文左右双引号
- if (!preg_match('/^[“]/', $dialogue)) {
- $dialogue = '“' . $dialogue;
- }
- if (!preg_match('/[”]$/', $dialogue)) {
- $dialogue .= '”';
- }
-
- // 将修改后的台词替换回 $segmentContent
- $originalDialogue = $dialogueMatch[1];
- $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
- }
- }
-
- // 检查 $segmentContent 中是否已有尾帧描述
- $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
-
- // 确定最终使用的尾帧描述(优先级:segmentContent自带 > 分镜表字段)
- $finalTailFrame = '';
- if ($contentHasTailFrame) {
- // segmentContent 中有尾帧描述,使用它
- $finalTailFrame = trim($contentTailFrameMatch[1]);
- } else {
- // segmentContent 中没有,使用分镜表中的尾帧描述
- $finalTailFrame = $tailFrame;
- }
-
- // 构建完整的提示词
- $fullPrompt = $segmentContent;
- if ($finalTailFrame && !$contentHasTailFrame) {
- // 只有当 segmentContent 中没有尾帧描述时才追加
- $fullPrompt .= "\n尾帧描述:$finalTailFrame";
- }
-
- // 去除多余的换行符(将连续多个换行符替换为单个换行符)
- $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
- $fullPrompt = trim($fullPrompt);
- // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
- $current_generate_audio = $hasDialogue ? $generate_audio : 0;
-
- // 智能选择视频时长
- // $videoDuration = $this->AnimeService->calculateOptimalVideoDuration($segmentContent, $tailFrame);
- $videoDuration = -1;
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_segment_id' => $segment->segment_id,
- 'prompt' => $fullPrompt,
- 'video_duration' => $videoDuration,
- 'video_resolution' => '720P',
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
-
- // 如果分镜有图片,作为首帧
- $hasImage = !empty($segment->img_url);
- $hasVideo = !empty($segment->video_url);
-
- if ($hasImage) {
- $videoParams['first_frame_url'] = $segment->img_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- }
- }
-
- // 获取配音音频URL和时长
- $audioUrl = $segment->audio_url ?? '';
- $audioDuration = $segment->audio_duration ?? 0;
-
- // 音频传入的前提:必须有至少一张图片或一个视频
- $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
-
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧20等新模型使用统一API
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_segment_id' => $segment->segment_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- 'video_mode' => 'multi_image',
- 'mode' => 'multi_image',
- 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
- ];
-
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
-
- // 只有在有图片的情况下才能添加参考音频
- if ($audioUrl) {
- $parameters['reference_audios'] = [$audioUrl];
- }
- } else {
- // 没有图片时,记录错误并跳过
- $logData = [
- 'segment_id' => $segment->segment_id,
- 'model' => $model,
- 'error' => '智帧20模型需要提供首帧图片'
- ];
- dLog('anime')->error('智帧20模型缺少首帧图片', $logData);
- logDB('anime', 'error', '智帧20模型缺少首帧图片', $logData);
- continue;
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->AIVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } else {
- // Seedance模型(默认)
- // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
- if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- // 添加配音音频到content中
- $videoParams['content'][] = [
- 'type' => 'audio_url',
- 'audio_url' => [
- 'url' => $audioUrl,
- ],
- 'role' => 'reference_audio',
- ];
-
- // 优化提示词,增加音频相关描述
- $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
- $videoParams['prompt'] = $audioPrompt;
- $videoParams['content'][0]['text'] = $audioPrompt;
- } else if ($audioDuration) {
- // 有音频时长则需将视频时长设置为比音频时长更长的整数
- $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
- }
- $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
- }
- $taskIds[] = $task->id;
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')
- ->where('segment_id', $segment->segment_id)
- ->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- $segmentTasks[] = [
- 'segment_id' => $segment->segment_id,
- 'task_id' => $task->id,
- 'segment_number' => $segment->segment_number,
- 'tail_frame' => $segment->tail_frame,
- 'audio_duration' => $segment->audio_duration,
- ];
-
- } catch (\Exception $e) {
- $logData = [
- 'segment_id' => $segment->segment_id,
- 'anime_id' => $animeId,
- 'error' => $e->getMessage(),
- ];
- dLog('anime')->error('创建分镜视频任务失败', $logData);
- logDB('anime', 'error', '创建分镜视频任务失败', $logData);
- continue;
- }
- }
-
- if (empty($taskIds)) {
- Utils::throwError('20003:没有需要生成视频的分镜');
- }
-
- // 保存模型到episode表
- DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
- 'video_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 记录开始时间(包含创建任务的时间)
- $startTime = time();
- $maxDuration = 1800; // 30分钟超时
-
- $uid = Site::getUid();
- // 设置 SSE 响应头并开始长连接
- return response()->stream(function () use ($taskIds, $segmentTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
- $checkInterval = 10; // 每10秒检查一次
-
- // 初始化任务数组
- $totalTasks = $taskIds; // 所有任务ID
- $completeTasks = []; // 已完成的任务ID(包含失败)
- $successTasks = []; // 成功的任务ID
-
- // 发送初始任务创建信息
- echo "data: " . json_encode([
- 'type' => 'init',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
-
- while (time() - $startTime < $maxDuration) {
- try {
- $hasUpdate = false; // 标记是否有更新
-
- // 获取所有任务的最新状态
- foreach ($totalTasks as $taskId) {
- // 如果任务已经在完成列表中,跳过
- if (in_array($taskId, $completeTasks)) {
- continue;
- }
-
- $task = \App\Models\MpGenerateVideoTask::find($taskId);
- if (!$task) {
- continue;
- }
-
- // 如果任务还在处理中,查询最新状态
- if ($task->status === 'processing') {
- // 根据任务类型查询不同的状态
- if ($task->api_type === 'jimeng') {
- $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
- } elseif ($task->api_type === 'keling') {
- $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
- } elseif ($task->api_type === 'zzengine') {
- $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
- } else {
- $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
- }
-
- if (isset($statusResult['status'])) {
- // 更新任务状态
- $task->update([
- 'status' => $statusResult['status'],
- 'result_json' => $statusResult['result_json'] ?? [],
- 'result_url' => $statusResult['result_url'] ?? null,
- 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- 'error_message' => $statusResult['error_message'] ?? null,
- 'completed_at' => in_array($statusResult['status'], [
- 'success',
- 'failed'
- ]) ? now() : null
- ]);
-
- // 如果任务成功,更新分镜表
- if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
- try {
- DB::beginTransaction();
-
- $now = date('Y-m-d H:i:s');
-
- // 获取分镜ID
- $segmentId = null;
- foreach ($segmentTasks as $segmentTask) {
- if ($segmentTask['task_id'] == $taskId) {
- $segmentId = $segmentTask['segment_id'];
- $tail_frame = $segmentTask['tail_frame'];
- $audio_duration = $segmentTask['audio_duration'];
- break;
- }
- }
-
- if ($segmentId) {
- // 更新分镜表
- $segmentUpdateData = [
- 'origin_video_url' => $statusResult['result_url'],
- 'video_task_status' => '已完成',
- 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- 'current_type' => 2,
- 'updated_at' => $now
- ];
- $compressed_video_url = compressVideo($statusResult['result_url']);
- $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
-
- // 只有当video_duration存在且大于0时才更新
- if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
- $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
- $segmentUpdateData['video_time_point_start'] = 0;
- // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
- $segmentUpdateData['video_time_point_end'] = $audio_duration ?? 0;
- }
-
- $updateResult = DB::table('mp_episode_segments')
- ->where('segment_id', $segmentId)
- ->update($segmentUpdateData);
-
- if ($updateResult) {
- // 更新分镜视频成功后新增对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $animeId,
- 'sequence' => $episodeNumber,
- 'role' => 'user',
- 'content' => '图片转视频',
- 'segment_id' => $segmentId,
- 'video_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $animeId,
- 'sequence' => $episodeNumber,
- 'role' => 'assistant',
- 'content' => $tail_frame ?? '',
- 'segment_id' => $segmentId,
- 'video_url' => $statusResult['result_url'],
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
-
- DB::table('mp_anime_records')->insert($records);
- }
- }
-
- DB::commit();
-
- } catch (\Exception $e) {
- DB::rollBack();
-
- $logData = [
- 'task_id' => $taskId,
- 'error' => $e->getMessage()
- ];
- dLog('anime')->error('视频任务处理失败', $logData);
- logDB('anime', 'error', '视频任务处理失败', $logData);
- }
-
- } elseif ($statusResult['status'] === 'failed') {
- // 获取分镜ID并更新失败状态
- foreach ($segmentTasks as $segmentTask) {
- if ($segmentTask['task_id'] == $taskId) {
- DB::table('mp_episode_segments')
- ->where('segment_id', $segmentTask['segment_id'])
- ->update([
- 'video_task_status' => '失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- break;
- }
- }
- }
- }
- }
-
- // 检查任务是否完成(成功或失败)
- if (in_array($task->status, ['success', 'failed'])) {
- $completeTasks[] = $taskId;
- $hasUpdate = true;
-
- if ($task->status === 'success') {
- $successTasks[] = $taskId;
- }
- }
- }
-
- // 如果有更新,发送update通知
- if ($hasUpdate) {
- echo "data: " . json_encode([
- 'type' => 'update',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- // 如果所有任务都完成了,结束连接
- if (count($completeTasks) >= count($totalTasks)) {
- // 获取所有成功任务的分镜信息
- $successSegments = [];
- foreach ($successTasks as $taskId) {
- // 通过taskId找到对应的segmentTask
- foreach ($segmentTasks as $segmentTask) {
- if ($segmentTask['task_id'] == $taskId) {
- $segment = DB::table('mp_episode_segments')
- ->where('segment_id', $segmentTask['segment_id'])
- ->select('segment_id', 'video_url')
- ->first();
-
- if ($segment && !empty($segment->video_url)) {
- $successSegments[] = [
- 'segment_id' => $segment->segment_id,
- 'video_url' => $segment->video_url
- ];
- }
- break;
- }
- }
- }
-
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks),
- 'success_segments' => $successSegments
- ]) . "\n\n";
- ob_flush();
- flush();
- break;
- }
-
- // 检查是否超时
- if (time() - $startTime >= $maxDuration) {
- break;
- }
-
- sleep($checkInterval);
-
- } catch (\Exception $e) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '查询任务状态失败: ' . $e->getMessage(),
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
-
- // 检查是否超时,如果超时则停止循环
- if (time() - $startTime >= $maxDuration) {
- break;
- }
-
- sleep($checkInterval);
- }
- }
-
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- echo "data: " . json_encode([
- 'type' => 'time_out',
- 'message' => '批量视频生成已超时30分钟,停止状态查询',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
- ]);
- }
- // 应用有声制作参数
- public function applyAudioData(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->applyAudioData($data);
- return $this->success($result);
- }
- // 获取分集生成图片信息
- public function episodePicsInfo(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- // 获取生成器函数
- $streamGenerator = $this->AnimeService->episodePicsInfo($data);
- // 返回 SSE 响应
- return response()->stream($streamGenerator, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
- ]);
- }
- public function clipSegmentVideo(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->clipSegmentVideo($data);
- return $this->success(['success'=>$result ? 1: 0]);
- }
- /**
- * 创建完整视频合成任务
- *
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse
- */
- public function createCompleteVideoTask(Request $request)
- {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
-
- // 验证参数
- $validator = Validator::make($data, [
- 'anime_id' => 'required|string',
- 'episode_id' => 'required|string',
- ], [
- 'anime_id.required' => '请选择动漫',
- 'episode_id.required' => '请选择分集',
- ]);
-
- if ($validator->fails()) {
- Utils::throwError('1002:' . $validator->errors()->first());
- }
-
- try {
- $result = $this->AnimeService->createCompleteVideoTask($data);
- return $this->success($result);
- } catch (\Exception $e) {
- $logData = [
- 'anime_id' => $data['anime_id'] ?? '',
- 'episode_id' => $data['episode_id'] ?? '',
- 'error' => $e->getMessage()
- ];
- dLog('anime')->error('创建完整视频合成任务失败', $logData);
- logDB('anime', 'error', '创建完整视频合成任务失败', $logData);
- return $this->error('20003:'.$e->getMessage());
- }
- }
- // 文生图(通用)
- public function generateImg(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
- $result = $this->AnimeService->generateImg($data);
- return $this->success($result);
- }
- /**
- * 导出分集的全部图片(下载并打包)
- */
- public function exportEpisodeImages(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- ini_set('memory_limit', '512M');
- $data = $request->all();
-
- // 验证参数
- $validator = Validator::make($data, [
- 'anime_id' => 'required|string',
- 'episode_id' => 'required|string',
- ], [
- 'anime_id.required' => '动漫ID不能为空',
- 'episode_id.required' => '剧集ID不能为空',
- ]);
-
- if ($validator->fails()) {
- Utils::throwError('1002:' . $validator->errors()->first());
- }
-
- $animeId = $data['anime_id'];
- $episodeId = $data['episode_id'];
-
- try {
- // 获取动漫信息,判断是否为全能模式
- $anime = DB::table('mp_animes')
- ->where('id', $animeId)
- ->select('ace_mode')
- ->first();
-
- if (!$anime) {
- Utils::throwError('20003:未找到动漫信息');
- }
-
- $isAceMode = ($anime->ace_mode == 1);
-
- // 获取剧集信息
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->select('episode_number', 'title')
- ->first();
-
- if (!$episode) {
- Utils::throwError('20003:未找到剧集信息');
- }
-
- // 根据模式查询和排序分镜数据
- if ($isAceMode) {
- // 全能模式:只查询有视频的分镜,按act_number排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->whereNotNull('video_url')
- ->where('video_url', '!=', '')
- ->orderBy('act_number')
- ->select('id as act_id', 'act_number', 'video_url', 'act_title')
- ->get();
-
- if ($segments->isEmpty()) {
- Utils::throwError('20003:该剧集暂无视频可导出');
- }
- } else {
- // 普通模式:查询所有分镜,按segment_number排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('segment_id', 'segment_number', 'img_url', 'video_url', 'audio_url')
- ->get();
-
- if ($segments->isEmpty()) {
- Utils::throwError('20003:该剧集暂无分镜数据');
- }
-
- // 过滤出有图片或视频的分镜
- $validSegments = $segments->filter(function($segment) {
- return (!empty($segment->img_url) || !empty($segment->video_url));
- });
-
- if ($validSegments->isEmpty()) {
- Utils::throwError('20003:该剧集暂无图片或视频可导出');
- }
-
- $segments = $validSegments->values();
- }
-
- // 创建临时目录
- $tempDir = storage_path('app/temp/episode_images_' . time() . '_' . mt_rand(1000, 9999));
- if (!file_exists($tempDir)) {
- mkdir($tempDir, 0755, true);
- }
-
- // 并行下载文件(使用 cURL multi)
- $downloadedFiles = [];
- $multiHandle = curl_multi_init();
- $curlHandles = [];
- $fileInfos = [];
-
- // 准备所有下载任务
- foreach ($segments as $index => $segment) {
- try {
- if ($isAceMode) {
- // 全能模式:只下载视频
- $mediaUrl = $segment->video_url;
- } else {
- // 普通模式:优先使用video_url,如果没有则使用img_url
- $mediaUrl = !empty($segment->video_url) ? $segment->video_url : $segment->img_url;
- }
-
- if (empty($mediaUrl)) {
- continue;
- }
-
- // 获取文件扩展名
- $extension = pathinfo(parse_url($mediaUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
- if (empty($extension)) {
- // 根据URL类型设置默认扩展名
- $extension = !empty($segment->video_url) ? 'mp4' : 'jpg';
- }
-
- // 构建文件名
- if ($isAceMode) {
- // 全能模式:使用act_number
- $fileName = sprintf('%03d.%s', $segment->act_number, $extension);
- } else {
- // 普通模式:使用segment_number
- $fileName = sprintf('%03d.%s', $segment->segment_number, $extension);
- }
- $filePath = $tempDir . '/' . $fileName;
-
- // 创建 cURL 句柄
- $ch = curl_init($mediaUrl);
- $fp = fopen($filePath, 'wb');
-
- curl_setopt($ch, CURLOPT_FILE, $fp);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_TIMEOUT, 60);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
-
- curl_multi_add_handle($multiHandle, $ch);
-
- $curlHandles[(int)$ch] = [
- 'handle' => $ch,
- 'file' => $fp,
- 'path' => $filePath,
- 'url' => $mediaUrl,
- 'segment' => $segment
- ];
-
- } catch (\Exception $e) {
- $logData = ['error' => $e->getMessage()];
- if ($isAceMode) {
- $logData['act_id'] = $segment->act_id;
- } else {
- $logData['segment_id'] = $segment->segment_id;
- }
- logDB('anime', 'error', '准备下载任务异常', $logData);
- continue;
- }
- }
-
- // 执行并行下载
- $running = null;
- do {
- curl_multi_exec($multiHandle, $running);
- curl_multi_select($multiHandle, 0.1);
- } while ($running > 0);
-
- // 处理下载结果
- foreach ($curlHandles as $info) {
- $ch = $info['handle'];
- $fp = $info['file'];
- $filePath = $info['path'];
- $segment = $info['segment'];
-
- fclose($fp);
-
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-
- if ($httpCode == 200 && file_exists($filePath) && filesize($filePath) > 0) {
- $downloadedFiles[] = $filePath;
- } else {
- // 删除失败的文件
- if (file_exists($filePath)) {
- @unlink($filePath);
- }
-
- $logData = [
- 'media_url' => $info['url'],
- 'http_code' => $httpCode,
- 'type' => $isAceMode ? 'video' : 'image'
- ];
-
- if ($isAceMode) {
- $logData['act_id'] = $segment->act_id;
- } else {
- $logData['segment_id'] = $segment->segment_id;
- }
-
- logDB('anime', 'warning', '文件下载失败', $logData);
- }
-
- curl_multi_remove_handle($multiHandle, $ch);
- curl_close($ch);
- }
-
- curl_multi_close($multiHandle);
-
- if (empty($downloadedFiles)) {
- // 清理临时目录
- if (file_exists($tempDir)) {
- array_map('unlink', glob("$tempDir/*"));
- rmdir($tempDir);
- }
- Utils::throwError('20003:没有成功下载任何文件');
- }
-
- // 处理音频合成(仅普通模式)
- $mergedAudioPath = null;
- if (!$isAceMode) {
- try {
- // 检查 FFmpeg 是否可用
- exec('which ffmpeg 2>&1', $ffmpegCheck, $ffmpegReturnCode);
- $hasFfmpeg = ($ffmpegReturnCode === 0);
-
- if ($hasFfmpeg) {
- // 下载所有分镜的音频文件
- $audioFiles = [];
- foreach ($segments as $segment) {
- if (!empty($segment->audio_url)) {
- try {
- $context = stream_context_create([
- 'http' => [
- 'timeout' => 30,
- 'follow_location' => 1,
- 'ignore_errors' => true
- ],
- 'ssl' => [
- 'verify_peer' => false,
- 'verify_peer_name' => false
- ]
- ]);
-
- $audioData = @file_get_contents($segment->audio_url, false, $context);
-
- if ($audioData !== false && !empty($audioData)) {
- // 获取音频文件扩展名
- $audioExtension = pathinfo(parse_url($segment->audio_url, PHP_URL_PATH), PATHINFO_EXTENSION);
- if (empty($audioExtension)) {
- $audioExtension = 'wav';
- }
-
- $audioFileName = sprintf('audio_%03d.%s', $segment->segment_number, $audioExtension);
- $audioFilePath = $tempDir . '/' . $audioFileName;
- file_put_contents($audioFilePath, $audioData);
- $audioFiles[] = $audioFilePath;
- } else {
- logDB('anime', 'warning', '音频下载失败', [
- 'segment_id' => $segment->segment_id,
- 'audio_url' => $segment->audio_url
- ]);
- }
- } catch (\Exception $e) {
- logDB('anime', 'error', '下载音频异常', [
- 'segment_id' => $segment->segment_id,
- 'audio_url' => $segment->audio_url,
- 'error' => $e->getMessage()
- ]);
- }
- }
- }
-
- // 如果有音频文件,则进行合成
- if (!empty($audioFiles)) {
- // 创建 FFmpeg concat 文件列表
- $concatFile = $tempDir . '/concat.txt';
- $concatContent = '';
- foreach ($audioFiles as $audioFile) {
- // 使用相对路径,避免路径中的特殊字符问题
- $concatContent .= "file '" . basename($audioFile) . "'\n";
- }
- file_put_contents($concatFile, $concatContent);
-
- // 合成音频文件
- $mergedAudioPath = $tempDir . '/tts.wav';
-
- // 使用 FFmpeg 合并音频,转换为统一的 WAV 格式
- $ffmpegCommand = sprintf(
- 'cd %s && ffmpeg -f concat -safe 0 -i %s -ar 44100 -ac 2 -y %s 2>&1',
- escapeshellarg($tempDir),
- escapeshellarg(basename($concatFile)),
- escapeshellarg(basename($mergedAudioPath))
- );
-
- exec($ffmpegCommand, $ffmpegOutput, $ffmpegReturnCode);
-
- if ($ffmpegReturnCode !== 0 || !file_exists($mergedAudioPath)) {
- logDB('anime', 'error', 'FFmpeg 合成音频失败', [
- 'command' => $ffmpegCommand,
- 'output' => implode("\n", $ffmpegOutput),
- 'return_code' => $ffmpegReturnCode
- ]);
- $mergedAudioPath = null;
- } else {
- logDB('anime', 'info', '音频合成成功', [
- 'audio_count' => count($audioFiles),
- 'output_file' => $mergedAudioPath,
- 'file_size' => filesize($mergedAudioPath)
- ]);
- }
-
- // 清理临时音频文件和 concat 文件
- foreach ($audioFiles as $audioFile) {
- if (file_exists($audioFile)) {
- @unlink($audioFile);
- }
- }
- if (file_exists($concatFile)) {
- @unlink($concatFile);
- }
- }
- } else {
- logDB('anime', 'warning', 'FFmpeg 未安装,跳过音频合成', []);
- }
- } catch (\Exception $e) {
- logDB('anime', 'error', '音频合成过程异常', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- // 音频合成失败不影响图片导出
- $mergedAudioPath = null;
- }
- }
-
- // 创建zip文件(使用安全的文件名)
- $safeTitle = preg_replace('/[^\p{L}\p{N}\s\-_]/u', '', $episode->title ?: '未命名');
- $safeTitle = trim($safeTitle) ?: '未命名';
- $zipFileName = sprintf('%s_%s.zip', $safeTitle, time());
- $zipFilePath = storage_path('app/temp/' . $zipFileName);
-
- // 确保 temp 目录存在
- $tempZipDir = storage_path('app/temp');
- if (!file_exists($tempZipDir)) {
- mkdir($tempZipDir, 0755, true);
- }
-
- $zip = new \ZipArchive();
- $openResult = $zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
-
- if ($openResult !== true) {
- // 清理临时文件
- array_map('unlink', $downloadedFiles);
- if ($mergedAudioPath && file_exists($mergedAudioPath)) {
- @unlink($mergedAudioPath);
- }
- rmdir($tempDir);
-
- logDB('anime', 'error', '创建ZIP文件失败', [
- 'zip_path' => $zipFilePath,
- 'open_result' => $openResult
- ]);
-
- Utils::throwError('20003:创建ZIP文件失败');
- }
-
- // 设置压缩级别为最快(0=不压缩,1=最快,9=最好压缩)
- // 对于视频和图片,压缩效果不明显,使用最快速度
- $zip->setCompressionIndex(0, \ZipArchive::CM_STORE); // 不压缩,直接存储
-
- // 添加文件到zip
- foreach ($downloadedFiles as $file) {
- if (file_exists($file)) {
- $zip->addFile($file, basename($file));
- }
- }
-
- // 添加合成的音频文件到zip(仅普通模式)
- if (!$isAceMode && $mergedAudioPath && file_exists($mergedAudioPath)) {
- $zip->addFile($mergedAudioPath, 'tts.wav');
- }
-
- // 关闭 ZIP 文件
- $zip->close();
-
- // 验证 ZIP 文件是否创建成功
- if (!file_exists($zipFilePath) || filesize($zipFilePath) == 0) {
- // 清理临时文件
- array_map('unlink', $downloadedFiles);
- if ($mergedAudioPath && file_exists($mergedAudioPath)) {
- @unlink($mergedAudioPath);
- }
- rmdir($tempDir);
-
- logDB('anime', 'error', 'ZIP文件创建后无效', ['zip_path' => $zipFilePath]);
-
- Utils::throwError('20003:ZIP文件创建失败或文件为空');
- }
-
- // 清理临时文件
- array_map('unlink', $downloadedFiles);
-
- // 清理合成的音频文件
- if ($mergedAudioPath && file_exists($mergedAudioPath)) {
- @unlink($mergedAudioPath);
- }
-
- rmdir($tempDir);
-
- // 清空所有输出缓冲区,避免污染ZIP文件
- while (ob_get_level() > 0) {
- ob_end_clean();
- }
-
- // 返回文件下载响应
- return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
-
- } catch (\Exception $e) {
- logDB('anime', 'error', '导出分集图片失败', [
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'error' => $e->getMessage()
- ]);
-
- // 清理可能存在的临时文件
- if (isset($tempDir) && file_exists($tempDir)) {
- array_map('unlink', glob("$tempDir/*"));
- rmdir($tempDir);
- }
- if (isset($zipFilePath) && file_exists($zipFilePath)) {
- unlink($zipFilePath);
- }
-
- throw $e;
- }
- }
- /**
- * 监控分镜图片和音频生成任务进度(SSE)
- */
- public function monitorSegmentTasks(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
-
- // 验证参数
- $validator = Validator::make($data, [
- 'anime_id' => 'required|string',
- 'episode_id' => 'required|string',
- ], [
- 'anime_id.required' => '动漫ID不能为空',
- 'episode_id.required' => '剧集ID不能为空',
- ]);
-
- if ($validator->fails()) {
- Utils::throwError('1002:' . $validator->errors()->first());
- }
-
- $animeId = $data['anime_id'];
- $episodeId = $data['episode_id'];
-
- // 查询没有pic_task_id的分镜个数
- $noPicTaskCount = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->where(function($query) {
- $query->whereNull('pic_task_id')
- ->orWhere('pic_task_id', '');
- })
- ->count('id');
-
- // 获取所有分镜信息
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->where('pic_task_id', '!=', '')
- ->orderBy('segment_number')
- ->get();
- // 判断是否有未完成的任务
- $uncompleted_pic_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->whereNotIn('pic_task_status', ['已完成', '失败'])->count('id');
-
- // 获取dialogue和voice_type存在但audio_url不存在的分镜个数
- $uncompleted_audio_count = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->where('dialogue', '<>', '')
- ->whereNotNull('dialogue')
- ->where('voice_type', '<>', '')
- ->whereNotNull('voice_type')
- ->where(function($query) {
- $query->whereNull('audio_url')
- ->orWhere('audio_url', '');
- })
- ->count('id');
-
- if ($segments->isEmpty()) {
- Utils::throwError('20003:未找到分镜任务数据');
- }
-
- $startTime = time();
- $maxDuration = 900; // 15分钟超时
- $checkInterval = 5; // 每5秒检查一次
-
- // 设置 SSE 响应头并开始长连接
- return response()->stream(function () use ($segments, $animeId, $episodeId, $startTime, $maxDuration, $checkInterval, $uncompleted_pic_count, $uncompleted_audio_count, $noPicTaskCount) {
- if ($uncompleted_pic_count == 0 && $uncompleted_audio_count == 0) {
- $completedCount = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->where('pic_task_status', '已完成')->count('id');
- // 获取剧集信息之前先处理视频截止时间点
- $this->handleVideoTimePointEnd();
- // 获取剧集信息
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
- ->first();
-
- if ($episode) {
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- $episode['scenes'] = json_decode($episode['scenes'], true);
-
- // 获取所有分镜信息
- $allSegments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('*')
- ->get()
- ->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 按照episodeInfo的格式组织数据
- $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- }
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'completed_count' => $completedCount, // 成功完成的数量
- 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
- 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
- 'total_elapsed_time' => time() - $startTime,
- 'episode_info' => $episode ?? null
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- return;
- }
- // 发送初始任务信息
- echo "data: " . json_encode([
- 'type' => 'init',
- 'data' => [
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
- 'start_time' => $startTime,
- 'max_duration' => $maxDuration
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
-
- $completedSegments = [];
- $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
- $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
-
- while (time() - $startTime < $maxDuration) {
- try {
- $updatedImages = []; // 记录本次循环中更新的图片信息
-
- foreach ($segments as $segment) {
- $segmentId = $segment->segment_id;
- $picTaskId = $segment->pic_task_id;
- $audioUrl = $segment->audio_url;
-
- // 跳过已处理完成的分镜
- if (in_array($segmentId, $processedSegments)) {
- continue;
- }
-
- $picCompleted = false;
- $audioCompleted = false;
- $picProcessed = false;
- $audioProcessed = false;
-
- // 检查图片任务状态
- if ($picTaskId) {
- $picTask = DB::table('mp_generate_pic_tasks')
- ->where('id', $picTaskId)
- ->select('status', 'result_url', 'error_message')
- ->first();
-
- if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
- $updateData = [
- 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
-
- $imgUrl = '';
- if ($picTask->status === 'success' && !empty($picTask->result_url)) {
- // 更新分镜表的图片URL
- $resultUrls = json_decode($picTask->result_url, true);
- $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
- $updateData['img_url'] = $imgUrl;
- $picCompleted = true;
- } else if ($picTask->status === 'failed') {
- // 失败时清空图片URL
- $updateData['img_url'] = '';
- }
-
- DB::table('mp_episode_segments')
- ->where('segment_id', $segmentId)
- ->update($updateData);
-
- // 记录更新的图片信息(只有未通知过的才记录)
- if (!in_array($segmentId, $notifiedSegments)) {
- $updatedImages[] = [
- 'segment_id' => $segmentId,
- 'segment_number' => $segment->segment_number,
- 'img_url' => $imgUrl,
- 'status' => $picTask->status === 'success' ? 'success' : 'failed'
- ];
-
- // 标记为已通知
- $notifiedSegments[] = $segmentId;
- }
-
- $picProcessed = true;
- }
- }
-
- // 检查音频状态
- // 获取分镜的dialogue、voice_type和audio_url信息
- $segmentInfo = DB::table('mp_episode_segments')
- ->where('segment_id', $segmentId)
- ->select('dialogue', 'voice_type', 'audio_url')
- ->first();
-
- $needAudio = false;
- $currentAudioUrl = '';
-
- if ($segmentInfo) {
- $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
- $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
- $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
-
- // 如果有对话和音色类型,则需要音频
- if (!empty($dialogue) && !empty($voiceType)) {
- $needAudio = true;
- }
- }
-
- // 判断音频状态
- if ($needAudio) {
- // 需要音频的情况下,检查audio_url是否有值
- if (!empty($currentAudioUrl)) {
- $audioCompleted = true;
- $audioProcessed = true;
- } else {
- // 需要音频但还没有,继续等待
- $audioCompleted = false;
- $audioProcessed = false;
- }
- } else {
- // 不需要音频,直接标记为已处理
- $audioCompleted = false;
- $audioProcessed = true;
- }
-
- // 如果图片和音频都成功完成,标记为已完成
- if ($picCompleted && ($audioCompleted || !$needAudio)) {
- $completedSegments[] = $segmentId;
- }
-
- // 如果图片和音频都已处理完成(成功或失败),标记为已处理
- if ($picProcessed && $audioProcessed) {
- $processedSegments[] = $segmentId;
- }
-
- }
-
- // 如果有图片更新,发送具体的图片更新信息
- if (!empty($updatedImages)) {
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'updated_images' => $updatedImages,
- 'completed_count' => count($completedSegments), // 成功完成的数量
- 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
- 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
- 'elapsed_time' => time() - $startTime,
- 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
- if (count($processedSegments) === count($segments)) {
- // 获取剧集信息之前先处理视频截止时间点
- $this->handleVideoTimePointEnd();
- // 获取剧集信息
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
- ->first();
-
- if ($episode) {
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- $episode['scenes'] = json_decode($episode['scenes'], true);
-
- // 获取所有分镜信息
- $allSegments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('*')
- ->get()
- ->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 按照episodeInfo的格式组织数据
- $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- }
-
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'completed_count' => count($completedSegments), // 成功完成的数量
- 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
- 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
- 'total_elapsed_time' => time() - $startTime,
- 'episode_info' => $episode ?? null
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- break;
- }
-
- // 检查是否超时
- if (time() - $startTime >= $maxDuration) {
- break;
- }
-
- sleep($checkInterval);
-
- } catch (\Exception $e) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '查询任务状态失败: ' . $e->getMessage(),
- 'elapsed_time' => time() - $startTime,
- 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
- ]) . "\n\n";
- ob_flush();
- flush();
-
- if (time() - $startTime >= $maxDuration) {
- break;
- }
-
- sleep($checkInterval);
- }
- }
-
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- echo "data: " . json_encode([
- 'type' => 'time_out',
- 'message' => '分镜任务监控已超时15分钟,停止状态查询',
- 'data' => [
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'completed_count' => count($completedSegments), // 成功完成的数量
- 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
- 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
- 'total_elapsed_time' => time() - $startTime,
- 'timeout_duration' => $maxDuration
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
- ]);
- }
- /**
- * 音频试听接口
- * 创建音频任务并返回结果
- */
- public function previewAudio(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->previewAudio($data);
- return $this->success($result);
- }
- // 角色库
- public function globalProducts(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->globalProducts($data);
- return $this->success($result);
- }
- // 新建角色
- public function createProduct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->createProduct($data);
- return $this->success($result);
- }
- // 编辑角色
- public function editProduct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->editProduct($data);
- return $this->success(['success' => $result ? 1 : 0]);
- }
-
- // 获取角色版本历史
- public function getProductVersions(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->getProductVersions($data);
- return $this->success($result);
- }
-
- // 恢复到指定版本
- public function restoreProductVersion(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->restoreProductVersion($data);
- return $this->success(['success' => $result ? 1 : 0]);
- }
- // 删除角色
- public function deleteProduct(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->deleteProduct($data);
- return $this->success(['success' => $result ? 1 : 0]);
- }
-
- // 新建文件夹
- public function createFolder(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->createFolder($data);
- return $this->success(['id' => $result]);
- }
-
- // 重命名文件夹或角色
- public function renameFolder(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->renameFolder($data);
- return $this->success(['success' => $result ? 1 : 0]);
- }
-
- // 移动角色或文件夹
- public function moveProductOrFolder(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->moveProductOrFolder($data);
- return $this->success(['success' => $result ? 1 : 0]);
- }
-
- // 获取文件夹路径(面包屑导航)
- public function getFolderPath(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->getFolderPath($data);
- return $this->success($result);
- }
- // 生成三视图
- public function generateThreeView(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->generateThreeView($data);
- return $this->success($result);
- }
- private function handleVideoTimePointEnd() {
- // 处理音频时长,循环查询dub_video_task_queue列表中的任务
- $queueLength = Redis::llen('dub_video_task_queue');
- if ($queueLength > 0) {
- $processedTaskIds = []; // 记录已处理的任务ID
-
- // 遍历队列中的所有任务
- for ($i = 0; $i < $queueLength; $i++) {
- $dubTaskId = Redis::lindex('dub_video_task_queue', $i);
- if (!$dubTaskId) continue;
-
- // 查询任务状态
- $dubTask = DB::table('mp_dub_video_tasks')
- ->where('id', $dubTaskId)
- ->first();
-
- if (!$dubTask) {
- // 任务不存在,标记为需要删除
- $processedTaskIds[] = $dubTaskId;
- continue;
- }
-
- // 如果任务状态是已完成
- if ($dubTask->generate_status === '执行成功') {
- // 获取对应的分镜信息
- $segment = DB::table('mp_episode_segments')
- ->where('segment_id', $dubTask->alias_segment_id)
- ->first();
-
- // 如果分镜存在且audio_duration大于0
- if ($segment && isset($segment->audio_duration) && $segment->audio_duration > 0) {
- // 更新video_time_point_end字段
- DB::table('mp_episode_segments')
- ->where('segment_id', $dubTask->alias_segment_id)
- ->update([
- 'video_time_point_end' => $segment->audio_duration,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- dLog('anime')->info('更新分镜视频截止时间点', [
- 'task_id' => $dubTaskId,
- 'segment_id' => $dubTask->alias_segment_id,
- 'audio_duration' => $segment->audio_duration
- ]);
- }
-
- // 标记为需要从队列中删除
- $processedTaskIds[] = $dubTaskId;
- }
- }
-
- // 从Redis列表中删除已处理的任务ID
- foreach ($processedTaskIds as $taskId) {
- Redis::lrem('dub_video_task_queue', 0, $taskId);
- }
- }
- }
- // 确认片段
- public function confirmActs(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->confirmActs($data);
- return $this->success($result);
- }
- public function saveActVideoGenerateParams(Request $request) {
- $data = $request->all();
- $result = $this->AnimeService->saveActVideoGenerateParams($data);
- return $this->success(['success' => $result ? 1 : 0]);
- }
- public function createActVideoTask(Request $request) {
- $uid = Site::getUid();
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
-
- // 创建视频生成任务
- $result = $this->AnimeService->createActVideoTask($data);
- $taskId = $result['task_id'];
-
- // 设置 SSE 响应头
- return response()->stream(function () use ($taskId, $result, $uid) {
- // 设置 SSE 响应头
- echo "data: " . json_encode([
- 'type' => 'init',
- 'data' => $result
- ]) . "\n\n";
- ob_flush();
- flush();
-
- $startTime = time();
- $maxDuration = 900; // 15分钟超时
- $checkInterval = 5; // 每5秒检查一次
-
- while (time() - $startTime < $maxDuration) {
- try {
- // 查询任务状态
- $task = \App\Models\MpGenerateVideoTask::find($taskId);
- if (!$task) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '任务不存在'
- ]) . "\n\n";
- ob_flush();
- flush();
- break;
- }
-
- // // 如果任务还在处理中,查询最新状态
- // if ($task->status === 'processing') {
- // // 根据任务类型查询不同的状态
- // if ($task->api_type === 'jimeng') {
- // $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
- // } elseif ($task->api_type === 'keling') {
- // $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
- // } elseif ($task->api_type === 'zzengine') {
- // $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
- // } else {
- // $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
- // }
- // if (isset($statusResult['status'])) {
- // // 更新任务状态
- // $task->update([
- // 'status' => $statusResult['status'],
- // 'result_url' => $statusResult['result_url'] ?? null,
- // 'compressed_url' => $statusResult['compressed_url'] ?? null,
- // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- // 'error_message' => $statusResult['error_message'] ?? null,
- // 'completed_at' => in_array($statusResult['status'], [
- // 'success',
- // 'failed'
- // ]) ? now() : null
- // ]);
-
- // // 如果任务成功,更新分镜表
- // if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
- // try {
- // DB::beginTransaction();
-
- // $now = date('Y-m-d H:i:s');
-
- // // 获取分镜ID
- // $act = DB::table('mp_episode_segments')
- // ->where('video_task_id', $taskId)
- // ->first();
-
- // if (!$act) {
- // throw new \Exception('未找到对应的片段记录');
- // }
-
- // $act_id = $act->id;
- // $anime_id = $act->anime_id;
- // $episode_number = $act->episode_number;
- // $act_content = $act->act_content;
-
- // // 更新分镜表
- // $segmentUpdateData = [
- // 'origin_video_url' => $statusResult['result_url'],
- // 'video_task_status' => '已完成',
- // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- // 'current_type' => 2,
- // 'updated_at' => $now
- // ];
- // $compressed_video_url = compressVideo($statusResult['result_url']);
- // $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
-
- // // 只有当video_duration存在且大于0时才更新
- // if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
- // $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
- // $segmentUpdateData['video_time_point_start'] = 0;
- // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
- // }
-
- // $updateResult = DB::table('mp_episode_segments')
- // ->where('id', $act_id)
- // ->update($segmentUpdateData);
-
- // if (!$updateResult) {
- // Utils::throwError('20003:更新分镜表失败');
- // }
- // // 更新分镜视频成功后新增对话记录
- // // 获取参考图记录
- // $reference_images = getProp($task, 'ref_image_url');
- // if (!$reference_images) $reference_images = json_encode([], 256);
- // // 保存对话记录
- // $records = [
- // [
- // 'uid' => $uid,
- // 'anime_id' => $anime_id,
- // 'sequence' => $episode_number,
- // 'role' => 'user',
- // 'content' => '片段转视频',
- // 'act_id' => $act_id,
- // 'video_url' => '',
- // 'created_at' => $now,
- // 'updated_at' => $now
- // ],
- // [
- // 'uid' => $uid,
- // 'anime_id' => $anime_id,
- // 'sequence' => $episode_number,
- // 'role' => 'assistant',
- // 'content' => $act_content,
- // 'act_id' => $act_id,
- // 'video_url' => $statusResult['result_url'],
- // 'reference_images' => $reference_images,
- // 'created_at' => $now,
- // 'updated_at' => $now
- // ]
- // ];
- // DB::table('mp_anime_records')->insert($records);
-
- // DB::commit();
-
- // } catch (\Exception $e) {
- // DB::rollBack();
-
- // $logData = [
- // 'task_id' => $taskId,
- // 'error' => $e->getMessage()
- // ];
- // dLog('anime')->error('视频任务处理失败', $logData);
- // logDB('anime', 'error', '视频任务处理失败', $logData);
- // }
- // } elseif ($statusResult['status'] === 'failed') {
- // DB::table('mp_episode_segments')
- // ->where('video_task_id', $taskId)
- // ->update([
- // 'video_task_status' => '失败',
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
- // }
- // }
- // }
- //
- // // 发送当前状态
- // echo "data: " . json_encode([
- // 'type' => 'update',
- // 'data' => [
- // 'task_id' => $task->id,
- // 'status' => $task->status,
- // 'result_url' => $task->result_url,
- // 'error_message' => $task->error_message,
- // 'elapsed_time' => time() - $startTime
- // ]
- // ]) . "\n\n";
- // ob_flush();
- // flush();
-
- // 如果任务完成(成功或失败),结束连接
- if (in_array($task->status, [
- 'success',
- 'failed'
- ])) {
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'video_url' => $task->compressed_url ?: $task->result_url,
- 'origin_video_url' => $task->result_url,
- 'last_frame_url' => $task->last_frame_url,
- 'error_message' => $task->error_message ? mapErrorMessage($task->error_message) : ''
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- break;
- }
-
- sleep($checkInterval);
-
- } catch (\Exception $e) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '查询任务状态失败: ' . $e->getMessage()
- ]) . "\n\n";
- ob_flush();
- flush();
- sleep($checkInterval);
- }
- }
-
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- echo "data: " . json_encode([
- 'type' => 'time_out',
- 'message' => '任务执行超时,请稍后查询任务状态',
- 'data' => [
- 'task_id' => $taskId
- ]
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
- ]);
- }
- /**
- * 批量生成片段视频
- */
- public function batchSetActVideos(Request $request) {
- // 忽略所有超时限制
- set_time_limit(0);
- ini_set('max_execution_time', '0');
- $data = $request->all();
-
- // 验证参数
- $validator = Validator::make($data, [
- 'anime_id' => 'required|string',
- 'episode_id' => 'required|integer',
- ], [
- 'anime_id.required' => '动漫对话ID不能为空',
- 'episode_id.required' => '剧集ID不能为空',
- 'episode_id.integer' => '剧集ID必须是整数',
- ]);
-
- if ($validator->fails()) {
- return response()->stream(function () use ($validator) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => $validator->errors()->first()
- ]) . "\n\n";
- ob_flush();
- flush();
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no',
- ]);
- }
-
- $animeId = $data['anime_id'];
- $episodeId = $data['episode_id'];
- $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
- if (!$episode) {
- return response()->stream(function () {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '分集不存在'
- ]) . "\n\n";
- ob_flush();
- flush();
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no',
- ]);
- }
- $episodeNumber = $episode->episode_number;
- $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
- $generate_audio = getProp($data, 'generate_audio', 1);
- // 合并角色和场景作为products,统一字段名为product_name
- $products = [];
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
-
- // 处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (isset($product['role'])) {
- $product['product_name'] = $product['role'];
- unset($product['role']);
- }
- $product['product'] = 1; // 标记类型为角色
- $products[] = $product;
- }
-
- // 处理场景数组
- foreach ($scenes as $scene) {
- $product = $scene;
- // 将scene字段重命名为product_name
- if (isset($product['scene'])) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- }
- $product['product'] = 2; // 标记类型为场景
- $products[] = $product;
- }
-
- // 处理视频模型(在循环外统一处理)
- // $model = getProp($data, 'model');
- // if (!$model) {
- // // 用户没有输入,从episode表获取
- // $model = getProp($episode, 'video_model');
- // if (!$model) {
- // // episode表也没有,使用默认值
- // $model = 'zhizhen-20-mini';
- // }
- // }
- $model = 'zhizhen-20-mini'; // 使用默认值
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'zhizhen-20-mini';
- }
-
- // 获取所有分镜信息
- $acts = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('act_number')
- ->get();
-
- if ($acts->isEmpty()) {
- return response()->stream(function () {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '未找到分镜数据'
- ]) . "\n\n";
- ob_flush();
- flush();
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no',
- ]);
- }
- foreach($acts as $act) {
- $videoDuration = $act->act_duration;
- if (!$videoDuration || $videoDuration <= 0) {
- return response()->stream(function () {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '请检查是否有时长为空的片段'
- ]) . "\n\n";
- ob_flush();
- flush();
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no',
- ]);
- }
- }
-
- // 批量创建视频任务
- $taskIds = [];
- $actTasks = [];
-
- foreach ($acts as $act) {
- try {
- // 检查视频任务正在生成中或当前状态为视频
- if ($act->video_task_status === '生成中') {
- $actTasks[] = [
- 'act_id' => $act->id,
- 'task_id' => $act->video_task_id,
- 'act_number' => $act->act_number,
- 'act_content' => $act->act_content,
- 'audio_duration' => $act->audio_duration,
- ];
- continue;
- }
- if ((int)$act->current_type === 2) {
- continue;
- }
-
- // 获取分镜内容
- $actContent = $act->act_show_content ?: '';
- // 构建完整的提示词
- $processResult = $this->AnimeService->processActContentWithProducts($actContent, $products);
- $fullPrompt = $processResult['content'];
- $reference_images = $processResult['reference_images'];
- $videoDuration = $act->act_duration;
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_act_id' => $act->id,
- 'prompt' => $fullPrompt,
- 'video_duration' => $videoDuration,
- 'video_resolution' => '720P',
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
-
- // 如果分镜有图片,作为首帧
- $hasImage = !empty($act->img_url);
- $hasVideo = !empty($act->video_url);
-
- if ($hasImage) {
- $videoParams['first_frame_url'] = $act->img_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- }
- }
-
- // 获取配音音频URL和时长
- $audioUrl = $act->audio_url ?? '';
- $audioDuration = $act->audio_duration ?? 0;
-
- // 音频传入的前提:必须有至少一张图片或一个视频
- $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
-
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- $videoParams['video_duration'] = $videoDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['video_duration'] = max(3, min(15, ceil($videoDuration))); // Keling支持3-15秒
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_act_id' => $act->id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- // 'video_mode' => 'multi_image',
- // 'mode' => 'multi_image',
- 'generate_audio' => (int)$generate_audio === 1 ? true : false,
- ];
-
- $hasImage = false;
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
- if (isset($videoParams['tail_frame_url'])) {
- $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
- }
- }
- if ($reference_images) {
- $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
- $reference_images = $this->AIImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
- $parameters['reference_images'] = $reference_images;
- $parameters['video_mode'] = 'multi_image';
- $parameters['mode'] = 'multi_image';
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->AIVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } else {
- // Seedance模型(默认)
- // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
- if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- // 添加配音音频到content中
- $videoParams['content'][] = [
- 'type' => 'audio_url',
- 'audio_url' => [
- 'url' => $audioUrl,
- ],
- 'role' => 'reference_audio',
- ];
-
- // 优化提示词,增加音频相关描述
- $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
- $videoParams['prompt'] = $audioPrompt;
- $videoParams['content'][0]['text'] = $audioPrompt;
- } else if ($videoDuration) {
- // 有音频时长则需将视频时长设置为比音频时长更长的整数
- $videoParams['video_duration'] = max(4, min(12, ceil($videoDuration))); // seedance支持2-12s
- }
- $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
- }
- $taskIds[] = $task->id;
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')
- ->where('id', $act->id)
- ->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
- if ((int)$episodeNumber === 1 && (int)$act->act_number === 1) {
- Redis::sadd('anime_act_first_frame_urls', $act->id);
- }
-
- $actTasks[] = [
- 'act_id' => $act->id,
- 'task_id' => $task->id,
- 'act_number' => $act->act_number,
- 'content' => $fullPrompt,
- 'audio_duration' => $act->audio_duration,
- ];
-
- } catch (\Exception $e) {
- $logData = [
- 'act_id' => $act->id,
- 'anime_id' => $animeId,
- 'error' => $e->getMessage(),
- ];
- dLog('anime')->error('创建分镜视频任务失败', $logData);
- logDB('anime', 'error', '创建分镜视频任务失败', $logData);
- continue;
- }
- }
-
- if (empty($taskIds)) {
- // 没有任务时,获取完整剧集信息进行验证
- $episode = $this->AnimeService->episodeInfoForAce([
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId
- ]);
-
- // 检查所有片段是否都已生成视频且current_type=2
- $allActsValid = true;
- $invalidActs = [];
-
- $total_tasks_count = count($episode['acts']);
- foreach ($episode['acts'] as $act) {
- $videoUrl = getProp($act, 'video_url');
- $currentType = getProp($act, 'current_type');
- // 检查视频是否已生成
- if (!$videoUrl) {
- $allActsValid = false;
- $invalidActs[] = [
- 'act_number' => getProp($act, 'act_number'),
- 'reason' => '视频未生成'
- ];
- continue;
- }
-
- // 检查current_type是否为2
- if ($currentType != 2) {
- $allActsValid = false;
- $invalidActs[] = [
- 'act_number' => getProp($act, 'act_number'),
- 'reason' => '当前不是视频模式'
- ];
- }
- }
-
- // 如果所有分镜都满足条件,使用SSE格式返回完成状态
- if ($allActsValid) {
- return response()->stream(function () use ($episode, $total_tasks_count) {
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'total_tasks_count' => $total_tasks_count,
- 'completed_tasks_count' => $total_tasks_count,
- 'success_tasks_count' => $total_tasks_count,
- 'episode' => $episode
- ]) . "\n\n";
- ob_flush();
- flush();
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no',
- ]);
- } else {
- // 有未完成或不满足条件的分镜,使用SSE格式报错
- $errorMsg = '存在未完成的片段:' . "\n";
- foreach ($invalidActs as $invalid) {
- $errorMsg .= "分镜{$invalid['act_number']}:{$invalid['reason']}\n";
- }
- return response()->stream(function () use ($errorMsg) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => trim($errorMsg)
- ]) . "\n\n";
- ob_flush();
- flush();
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no',
- ]);
- }
- }
-
- // 保存模型到episode表
- DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
- 'video_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 记录开始时间(包含创建任务的时间)
- $startTime = time();
- $maxDuration = 3600;
-
- $uid = Site::getUid();
- // 设置 SSE 响应头并开始长连接
- return response()->stream(function () use ($taskIds, $actTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
- $checkInterval = 10; // 每10秒检查一次
-
- // 初始化任务数组
- $totalTasks = $taskIds; // 所有任务ID
- $completeTasks = []; // 已完成的任务ID(包含失败)
- $successTasks = []; // 成功的任务ID
-
- // 发送初始任务创建信息
- echo "data: " . json_encode([
- 'type' => 'init',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
-
- while (time() - $startTime < $maxDuration) {
- try {
- $hasUpdate = false; // 标记是否有更新
-
- // 获取所有任务的最新状态
- foreach ($totalTasks as $taskId) {
- // 如果任务已经在完成列表中,跳过
- if (in_array($taskId, $completeTasks)) {
- continue;
- }
-
- $task = \App\Models\MpGenerateVideoTask::find($taskId);
- if (!$task) {
- continue;
- }
-
- // // 如果任务还在处理中,查询最新状态
- // if ($task->status === 'processing') {
- // // 根据任务类型查询不同的状态
- // if ($task->api_type === 'jimeng') {
- // $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
- // } elseif ($task->api_type === 'keling') {
- // $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
- // } elseif ($task->api_type === 'zzengine') {
- // $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
- // } else {
- // $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
- // }
-
- // if (isset($statusResult['status'])) {
- // // 更新任务状态
- // $task->update([
- // 'status' => $statusResult['status'],
- // 'result_json' => $statusResult['result_json'] ?? [],
- // 'result_url' => $statusResult['result_url'] ?? null,
- // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- // 'error_message' => $statusResult['error_message'] ?? null,
- // 'completed_at' => in_array($statusResult['status'], [
- // 'success',
- // 'failed'
- // ]) ? now() : null
- // ]);
-
- // // 如果任务成功,更新分镜表
- // if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
- // try {
- // DB::beginTransaction();
-
- // $now = date('Y-m-d H:i:s');
-
- // // 获取分镜ID
- // $actId = null;
- // foreach ($actTasks as $actTask) {
- // if ($actTask['task_id'] == $taskId) {
- // $actId = $actTask['act_id'];
- // $content = $actTask['content'];
- // $audio_duration = $actTask['audio_duration'];
- // break;
- // }
- // }
-
- // if ($actId) {
- // // 更新分镜表
- // $actUpdateData = [
- // 'origin_video_url' => $statusResult['result_url'],
- // 'video_task_status' => '已完成',
- // 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
- // 'current_type' => 2,
- // 'updated_at' => $now
- // ];
- // $compressed_video_url = compressVideo($statusResult['result_url']);
- // $actUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
-
- // // 只有当video_duration存在且大于0时才更新
- // if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
- // $actUpdateData['video_duration'] = $statusResult['video_duration'];
- // $actUpdateData['video_time_point_start'] = 0;
- // $actUpdateData['video_time_point_end'] = $statusResult['video_duration'];
- // }
-
- // $updateResult = DB::table('mp_episode_segments')
- // ->where('id', $actId)
- // ->update($actUpdateData);
-
- // if ($updateResult) {
- // // 更新分镜视频成功后新增对话记录
- // // 获取参考图记录
- // $reference_images = getProp($task, 'ref_image_url');
- // if (!$reference_images) $reference_images = json_encode([], 256);
- // $records = [
- // [
- // 'uid' => $uid,
- // 'anime_id' => $animeId,
- // 'sequence' => $episodeNumber,
- // 'role' => 'user',
- // 'content' => '片段转视频',
- // 'act_id' => $actId,
- // 'video_url' => '',
- // 'created_at' => $now,
- // 'updated_at' => $now
- // ],
- // [
- // 'uid' => $uid,
- // 'anime_id' => $animeId,
- // 'sequence' => $episodeNumber,
- // 'role' => 'assistant',
- // 'content' => $content ?? '',
- // 'act_id' => $actId,
- // 'video_url' => $statusResult['result_url'],
- // 'reference_images' => $reference_images,
- // 'created_at' => $now,
- // 'updated_at' => $now
- // ]
- // ];
-
- // DB::table('mp_anime_records')->insert($records);
- // }
- // }
-
- // DB::commit();
-
- // } catch (\Exception $e) {
- // DB::rollBack();
-
- // $logData = [
- // 'task_id' => $taskId,
- // 'error' => $e->getMessage()
- // ];
- // dLog('anime')->error('视频任务处理失败', $logData);
- // logDB('anime', 'error', '视频任务处理失败', $logData);
- // }
-
- // } elseif ($statusResult['status'] === 'failed') {
- // // 获取分镜ID并更新失败状态
- // foreach ($actTasks as $actTask) {
- // if ($actTask['task_id'] == $taskId) {
- // DB::table('mp_episode_segments')
- // ->where('id', $actTask['act_id'])
- // ->update([
- // 'video_task_status' => '失败',
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
- // break;
- // }
- // }
- // }
- // }
- // }
-
- // 检查任务是否完成(成功或失败)
- if (in_array($task->status, ['success', 'failed'])) {
- $completeTasks[] = $taskId;
- $hasUpdate = true;
-
- if ($task->status === 'success') {
- $successTasks[] = $taskId;
- }
- }
- }
-
- // 如果有更新,发送update通知
- if ($hasUpdate) {
- echo "data: " . json_encode([
- 'type' => 'update',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- // 如果所有任务都完成了,结束连接
- if (count($completeTasks) >= count($totalTasks)) {
-
- // 重新获取完整的剧集信息
- $updatedEpisode = $this->AnimeService->episodeInfoForAce([
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId
- ]);
-
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks),
- 'episode' => $updatedEpisode
- ]) . "\n\n";
- ob_flush();
- flush();
- break;
- }
-
- // 检查是否超时
- if (time() - $startTime >= $maxDuration) {
- break;
- }
-
- sleep($checkInterval);
-
- } catch (\Exception $e) {
- echo "data: " . json_encode([
- 'type' => 'error',
- 'message' => '查询任务状态失败: ' . $e->getMessage(),
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
-
- // 检查是否超时,如果超时则停止循环
- if (time() - $startTime >= $maxDuration) {
- break;
- }
-
- sleep($checkInterval);
- }
- }
-
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- echo "data: " . json_encode([
- 'type' => 'time_out',
- 'message' => '批量视频生成已超时,停止状态查询',
- 'total_tasks_count' => count($totalTasks),
- 'completed_tasks_count' => count($completeTasks),
- 'success_tasks_count' => count($successTasks)
- ]) . "\n\n";
- ob_flush();
- flush();
- }
-
- }, 200, [
- 'Content-Type' => 'text/event-stream',
- 'Cache-Control' => 'no-cache',
- 'Connection' => 'keep-alive',
- 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
- ]);
- }
- }
|