AnimeService.php 401 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $cpid = Site::getCpid();
  181. $input_art_style = getProp($data, 'art_style');
  182. $file = getProp($data, 'file');
  183. $content = getProp($data, 'content', '');
  184. $bid = getProp($data, 'bid', 0);
  185. $script_id = getProp($data, 'script_id', 0);
  186. $ace_mode = getProp($data, 'ace_mode', 0);
  187. $extra_products = getProp($data, 'products', []);
  188. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  189. if (!is_array($extra_products)) {
  190. Utils::throwError('20003:传入的资产格式不正确');
  191. }
  192. // 替换美术风格
  193. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  194. // 提取文件内容
  195. if ($file) {
  196. $content = $this->DeepSeekService->extractFileContent($file);
  197. if (!$content) {
  198. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  199. }
  200. } elseif ($script_id) {
  201. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  202. if (!$content) {
  203. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  204. }
  205. } elseif ($bid) {
  206. $content = $this->DeepSeekService->getContentByBid($bid);
  207. if (!$content) {
  208. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  209. }
  210. } elseif ($content) {
  211. $content = filterContent($content);
  212. }else {
  213. $content = '';
  214. }
  215. $anime_data = [
  216. 'user_id' => $uid,
  217. 'cpid' => $cpid,
  218. 'anime_name' => '新剧本策划',
  219. 'is_multi' => getProp($data, 'is_multi', 1),
  220. 'content' => $content,
  221. 'art_style_type' => $input_art_style,
  222. 'ace_mode' => $ace_mode,
  223. 'script_id' => $script_id,
  224. 'extra_products' => json_encode($extra_products, 256),
  225. 'created_at' => date('Y-m-d H:i:s'),
  226. 'updated_at' => date('Y-m-d H:i:s'),
  227. ];
  228. // 处理文本模型
  229. $model = getProp($data, 'model');
  230. if (!$model) {
  231. // 用户没有输入,使用默认值
  232. $model = 'deepseek-v4-pro';
  233. }
  234. // 验证模型是否在可用模型表中
  235. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  236. $model = 'deepseek-v4-pro';
  237. }
  238. $anime_data['model'] = $model;
  239. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  240. return DB::table('mp_animes')->insertGetId($anime_data);
  241. }
  242. public function chatList($data) {
  243. $uid = Site::getUid();
  244. $anime_name = getProp($data, 'anime_name');
  245. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  246. if ($anime_name) {
  247. $query->where('anime_name', 'like', "%$anime_name%");
  248. }
  249. return $query->orderBy('id', 'desc')->paginate();
  250. }
  251. public function chatHistory($data) {
  252. $anime_id = getProp($data, 'anime_id');
  253. $sequence = getProp($data, 'sequence', 0);
  254. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  255. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  256. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  257. return $query->orderBy('ar.id')->get()->map(function ($value) {
  258. $value = (array)$value;
  259. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  260. $value['created_at'] = transDate($value['created_at']);
  261. $value['episode_created_at'] = transDate($value['episode_created_at']);
  262. return $value;
  263. })->toArray();
  264. }
  265. public function batchSetRoleImg($data) {
  266. $episode_id = getProp($data, 'episode_id');
  267. if (!$episode_id) Utils::throwError('1002:请选择分集');
  268. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  269. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  270. $art_style = getProp($episode, 'art_style');
  271. $anime_id = getProp($episode, 'anime_id');
  272. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  273. $art_style_type = getProp($anime, 'art_style_type');
  274. $character_prefix = '';
  275. $scene_prefix = '';
  276. if ($art_style_type) {
  277. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  278. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  279. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  280. }
  281. foreach ($roles as &$role) {
  282. $role_name = getProp($role, 'role');
  283. if ($role_name == '旁白') continue;
  284. // 优先使用 pic_prompt,如果没有则使用 description
  285. $pic_prompt = getProp($role, 'pic_prompt');
  286. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  287. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  288. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  289. // 参考图地址
  290. $ref_img_url = getProp($role, 'url');
  291. if ($ref_img_url) continue; // 已有图片则跳过
  292. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  293. try {
  294. $params = [
  295. 'prompt' => $description,
  296. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  297. ];
  298. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  299. $task_id = $task->id;
  300. if (!$task_id) {
  301. Utils::throwError("20003:角色({$role_name})生成图片失败");
  302. }
  303. $role['task_id'] = $task_id;
  304. $role['task_status'] = 'processing';
  305. } catch (\Exception $e) {
  306. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  307. Utils::throwError("20003:" . $e->getMessage());
  308. }
  309. }
  310. // 保存角色信息
  311. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  312. 'roles' => json_encode($roles, 256),
  313. 'generate_status' => '执行中',
  314. 'generate_at' => date('Y-m-d H:i:s'),
  315. 'updated_at' => date('Y-m-d H:i:s')
  316. ]);
  317. if (!$boolen) {
  318. Utils::throwError('20003:保存角色信息失败');
  319. }
  320. return $boolen;
  321. }
  322. public function batchSetSceneImg($data) {
  323. $episode_id = getProp($data, 'episode_id');
  324. if (!$episode_id) Utils::throwError('1002:请选择分集');
  325. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  326. $scenes = json_decode(getProp($episode, 'scenes'), true);
  327. $art_style = getProp($episode, 'art_style');
  328. $target_scene = getProp($data, 'target_scene');
  329. $anime_id = getProp($episode, 'anime_id');
  330. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  331. $art_style_type = getProp($anime, 'art_style_type');
  332. $character_prefix = '';
  333. $scene_prefix = '';
  334. if ($art_style_type) {
  335. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  336. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  337. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  338. }
  339. foreach ($scenes as &$scene) {
  340. $scene_name = getProp($scene, 'scene');
  341. if ($scene_name != $target_scene) continue;
  342. // 优先使用 pic_prompt,如果没有则使用 description
  343. $pic_prompt = getProp($scene, 'pic_prompt');
  344. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  345. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  346. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  347. // 参考图地址
  348. $ref_img_url = getProp($scene, 'url');
  349. if ($ref_img_url) continue; // 已有图片则跳过
  350. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  351. try {
  352. $params = [
  353. 'prompt' => $description,
  354. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  355. ];
  356. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  357. $task_id = $task->id;
  358. if (!$task_id) {
  359. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  360. }
  361. $scene['task_id'] = $task_id;
  362. $scene['task_status'] = 'processing';
  363. } catch (\Exception $e) {
  364. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  365. Utils::throwError("20003:" . $e->getMessage());
  366. }
  367. }
  368. // 保存场景信息
  369. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  370. 'scenes' => json_encode($scenes, 256),
  371. 'generate_status' => '执行中',
  372. 'generate_at' => date('Y-m-d H:i:s'),
  373. 'updated_at' => date('Y-m-d H:i:s')
  374. ]);
  375. if (!$boolen) {
  376. Utils::throwError('20003:保存角色信息失败');
  377. }
  378. return $boolen;
  379. }
  380. public function editAnime($data) {
  381. $anime_id = getProp($data, 'anime_id');
  382. $anime_name = trim(getProp($data, 'anime_name'));
  383. // 确认对话名称唯一性
  384. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  385. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  386. }
  387. if (!$anime_id || !$anime_name) {
  388. Utils::throwError('20003:参数异常');
  389. }
  390. return DB::table('mp_animes')->where('id', $anime_id)->update([
  391. 'anime_name' => $anime_name,
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. // $script_arr =getProp($data, 'script', []);
  395. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  396. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  397. // $anime_id = getProp($data, 'anime_id');
  398. // try {
  399. // DB::beginTransaction();
  400. // $table_data = [
  401. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  402. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  403. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  404. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  405. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  406. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  407. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  408. // 'status' => 3,
  409. // 'start_episode_sequence' => $start_episode_sequence,
  410. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  411. // 'episode_num' => count($script_arr['episodes']),
  412. // 'updated_at' => date('Y-m-d H:i:s')
  413. // ];
  414. // // 保存剧本内容
  415. // if (!empty($anime_id)) {
  416. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  417. // if (!$boolen) {
  418. // dLog('anime')->info('对话保存失败', $table_data);
  419. // Utils::throwError('20003:对话保存失败');
  420. // }
  421. // }else {
  422. // $table['created_at'] = $table_data['updated_at'];
  423. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  424. // if (!$anime_id) {
  425. // dLog('anime')->info('对话保存失败', $table_data);
  426. // Utils::throwError('20003:对话保存失败');
  427. // }
  428. // }
  429. // // 保存分集内容
  430. // // 删除历史分集内容
  431. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  432. // $episodes = [];
  433. // $sequence = 1;
  434. // foreach ($script_arr['episodes'] as $episode) {
  435. // $segment_number = 1;
  436. // foreach($episode['segments'] as $segment) {
  437. // $episodes[] = [
  438. // 'anime_id' => $anime_id,
  439. // 'episode_number' => $episode['episode_number'],
  440. // 'title' => $episode['title'],
  441. // // 'content' => $episode['content'],
  442. // 'content' => '',
  443. // 'segment_number' => $segment_number,
  444. // 'segment_content' => $segment['segment_content'],
  445. // 'sequence' => $sequence,
  446. // 'created_at' => date('Y-m-d H:i:s'),
  447. // 'updated_at' => date('Y-m-d H:i:s')
  448. // ];
  449. // $sequence++;
  450. // $segment_number++;
  451. // }
  452. // }
  453. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  454. // if (!$boolen2) {
  455. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  456. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  457. // Utils::throwError('20003:分集内容保存失败');
  458. // }
  459. // } catch (\Exception $e) {
  460. // DB::rollBack();
  461. // Utils::throwError('20003:'.$e->getMessage());
  462. // }
  463. // DB::commit();
  464. // return true;
  465. }
  466. public function delAnime($data) {
  467. $anime_id = getProp($data, 'anime_id');
  468. if (!$anime_id) {
  469. Utils::throwError('20003:请选择剧本');
  470. }
  471. return DB::table('mp_animes')->where('id', $anime_id)->update([
  472. 'is_deleted' => 1,
  473. 'updated_at' => date('Y-m-d H:i:s')
  474. ]);
  475. }
  476. public function animeDetail($data) {
  477. $uid = Site::getUid();
  478. $anime_id = getProp($data, 'anime_id');
  479. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  480. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  481. if (!$anime) Utils::throwError('20003:权限不足');
  482. $anime = (array)$anime;
  483. $anime['roles'] = json_decode($anime['roles']);
  484. $anime['scenes'] = json_decode($anime['scenes']);
  485. // 获取分集信息
  486. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  487. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  488. ->orderBy('episode_number')->get()->map(function ($value) {
  489. return (array)$value;
  490. })->toArray();
  491. $anime['episodes'] = $episodes;
  492. return $anime;
  493. }
  494. public function episodeInfo($data) {
  495. $uid = Site::getUid();
  496. $anime_id = getProp($data, 'anime_id');
  497. $episode_id = getProp($data, 'episode_id');
  498. if (!$anime_id || !$episode_id) {
  499. Utils::throwError('1002:请选择剧集');
  500. }
  501. // 验证用户权限
  502. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  503. if (!$anime) Utils::throwError('20003:权限不足');
  504. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  505. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  506. $episode = (array)$episode;
  507. $episode['roles'] = json_decode($episode['roles'], true);
  508. // foreach($episode['roles'] as &$item) {
  509. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  510. // }
  511. $episode['scenes'] = json_decode($episode['scenes'], true);
  512. // foreach($episode['scenes'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  514. // }
  515. // 获取分镜信息
  516. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  517. ->select('*')->get()->map(function ($value) {
  518. return (array)$value;
  519. })->toArray();
  520. // 使用公共方法构建分镜结构
  521. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  522. $episode['acts'] = $segmentsStructure['acts'];
  523. $episode['total_duration'] = $segmentsStructure['total_duration'];
  524. return $episode;
  525. }
  526. public function episodeInfoForAce($data) {
  527. $anime_id = getProp($data, 'anime_id');
  528. $episode_id = getProp($data, 'episode_id');
  529. if (!$anime_id || !$episode_id) {
  530. Utils::throwError('1002:请选择剧集');
  531. }
  532. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  533. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  534. $episode = (array)$episode;
  535. $episode['roles'] = json_decode($episode['roles'], true);
  536. // foreach($episode['roles'] as &$item) {
  537. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  538. // }
  539. $episode['scenes'] = json_decode($episode['scenes'], true);
  540. // foreach($episode['scenes'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  542. // }
  543. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  544. // 获取分镜信息
  545. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  546. ->select('*')->get()->map(function ($value) {
  547. return (array)$value;
  548. })->toArray();
  549. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  550. $episode['acts'] = $segmentsStructure['acts'];
  551. $episode['total_duration'] = $segmentsStructure['total_duration'];
  552. // 获取mp_animes表中的视频参数
  553. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  554. $episode['video_params'] = [
  555. 'video_model' => getProp($anime, 'video_model'),
  556. 'video_resolution' => getProp($anime, 'video_resolution'),
  557. 'ratio' => getProp($anime, 'video_ratio'),
  558. ];
  559. return $episode;
  560. }
  561. public function segmentInfo($data) {
  562. $uid = Site::getUid();
  563. $segment_id = getProp($data, 'segment_id');
  564. if (!$segment_id) {
  565. Utils::throwError('1002:请选择分镜');
  566. }
  567. // 获取分镜信息
  568. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  569. // 验证用户权限
  570. if ($segment) {
  571. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  572. if (!$anime) Utils::throwError('20003:权限不足');
  573. }
  574. $result = [
  575. 'segment_id' => getProp($segment, 'segment_id'),
  576. 'segment_number' => getProp($segment, 'segment_number'),
  577. 'segment_content' => getProp($segment, 'segment_content'),
  578. 'description' => getProp($segment, 'description'),
  579. 'composition' => getProp($segment, 'composition'),
  580. 'camera_movement' => getProp($segment, 'camera_movement'),
  581. 'voice_actor' => getProp($segment, 'voice_actor'),
  582. 'dialogue' => getProp($segment, 'dialogue'),
  583. 'frame_type' => getProp($segment, 'frame_type'),
  584. 'scene' => getProp($segment, 'scene'),
  585. 'characters' => getProp($segment, 'characters'),
  586. 'tail_frame' => getProp($segment, 'tail_frame'),
  587. 'emotion' => getProp($segment, 'emotion'),
  588. 'emotion_type' => getProp($segment, 'emotion_type'),
  589. 'gender' => getProp($segment, 'gender'),
  590. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  591. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  592. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  593. 'pitch' => getProp($segment, 'pitch'),
  594. 'voice_name' => getProp($segment, 'voice_name'),
  595. 'voice_type' => getProp($segment, 'voice_type'),
  596. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  597. 'img_url' => getProp($segment, 'img_url'),
  598. 'video_url' => getProp($segment, 'video_url'),
  599. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  600. ];
  601. return $result;
  602. }
  603. public function copyEpisodeVersion($data) {
  604. $episode_id = getProp($data, 'episode_id');
  605. $uid = Site::getUid();
  606. $cpid = Site::getCpid();
  607. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  608. if (!$episode) Utils::throwError('20003:该剧集不存在');
  609. $episode = (array)$episode;
  610. $anime_id = $episode['anime_id'];
  611. $episode_number = $episode['episode_number'];
  612. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  613. $sequence = $count + 1;
  614. unset($episode['id']);
  615. $now = date('Y-m-d H:i:s');
  616. $episode['created_at'] = $now;
  617. $episode['updated_at'] = $now;
  618. $episode['is_default'] = 1;
  619. // 获取版本中含有"(副本"字样的个数
  620. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  621. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  622. $episode['sequence'] = $sequence;
  623. $episode['is_generated'] = 0;
  624. $episode['cpid'] = $cpid;
  625. // 获取ace_mode
  626. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  627. try {
  628. DB::beginTransaction();
  629. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  630. // 新增副本
  631. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  632. if (!$new_episode_id) {
  633. Utils::throwError('20003:创建副本失败!');
  634. }
  635. // 获取分镜数据并准备插入
  636. $segments_for_insert = DB::table('mp_episode_segments')
  637. ->select('anime_id', 'episode_number', 'act_number', 'act_title', 'act_duration', 'act_content', 'segment_number', 'segment_content', 'description', 'composition', 'camera_movement', 'voice_actor', 'dialogue', 'frame_type', 'scene', 'characters', 'tail_frame', 'voice_name', 'voice_type', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  638. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  639. $item = (array)$item;
  640. $item['episode_id'] = $new_episode_id;
  641. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  642. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  643. return $item;
  644. })->toArray();
  645. // 写入分镜数据
  646. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  647. if (!$boolen2) {
  648. Utils::throwError('20003:写入分镜数据失败!');
  649. }
  650. // 写入对话历史
  651. $records = [
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'user',
  656. 'content' => '创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ],
  662. [
  663. 'uid' => $uid,
  664. 'anime_id' => $anime_id,
  665. 'role' => 'assistant',
  666. 'content' => '好的,已为您创建副本',
  667. 'sequence' => $episode_number,
  668. 'episode_id' => $new_episode_id,
  669. 'created_at' => $now,
  670. 'updated_at' => $now
  671. ]
  672. ];
  673. $boolen3 = DB::table('mp_anime_records')->insert($records);
  674. if (!$boolen3) {
  675. Utils::throwError('20003:对话记录保存失败');
  676. }
  677. }catch (\Exception $e) {
  678. DB::rollBack();
  679. Utils::throwError('20003:'.$e->getMessage());
  680. }
  681. DB::commit();
  682. // 构建与 episodeInfo 方法一致的返回数据结构
  683. $result = [
  684. 'episode_id' => $new_episode_id,
  685. 'anime_id' => $anime_id,
  686. 'episode_number' => $episode_number,
  687. 'title' => $episode['title'],
  688. 'intro' => $episode['intro'],
  689. 'art_style' => $episode['art_style'],
  690. 'roles' => json_decode($episode['roles'], true),
  691. 'scenes' => json_decode($episode['scenes'], true),
  692. 'is_generated' => (int)$episode['is_generated']
  693. ];
  694. if ((int)$ace_mode === 1) {
  695. // 获取分镜信息
  696. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  697. ->select('*')->get()->map(function ($value) {
  698. return (array)$value;
  699. })->toArray();
  700. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  701. }else {
  702. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  703. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  704. }
  705. $result['acts'] = $segmentsStructure['acts'];
  706. $result['total_duration'] = $segmentsStructure['total_duration'];
  707. return $result;
  708. }
  709. public function episodeVersions($data) {
  710. $anime_id = getProp($data, 'anime_id');
  711. $episode_id = getProp($data, 'episode_id');
  712. if (!$anime_id || !$episode_id) {
  713. Utils::throwError('1002:请选择剧集');
  714. }
  715. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  716. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->select('id as episode_id', 'anime_id', 'episode_number', 'sequence', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->orderBy('sequence', 'desc')->get()->map(function($value) {
  717. return (array)$value;
  718. })->toArray();
  719. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  720. foreach($episodes as &$episode) {
  721. $episode['version'] = 'V'.$episode['sequence'];
  722. $episode['roles'] = json_decode($episode['roles'], true);
  723. $episode['scenes'] = json_decode($episode['scenes'], true);
  724. // 获取分镜信息
  725. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  726. ->select('*')->get()->map(function ($value) {
  727. return (array)$value;
  728. })->toArray();
  729. // 使用公共方法构建分镜结构
  730. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  731. $episode['acts'] = $segmentsStructure['acts'];
  732. $episode['total_duration'] = $segmentsStructure['total_duration'];
  733. }
  734. return $episodes;
  735. }
  736. public function bindEpisodeVersion($data) {
  737. $episode_id = getProp($data, 'episode_id');
  738. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  739. if (!$episode) Utils::throwError('20003:该剧集不存在');
  740. $episode = (array)$episode;
  741. if ((int)$episode['is_default'] === 1) return true;
  742. try {
  743. DB::beginTransaction();
  744. // 移除is_default标志
  745. $boolen = DB::table('mp_anime_episodes')->where('anime_id', $episode['anime_id'])->where('episode_number', $episode['episode_number'])->update(['is_default' => 0, 'updated_at'=>date('Y-m-d H:i:s')]);
  746. if (!$boolen) {
  747. Utils::throwError('20003:更新失败!');
  748. }
  749. // 绑定副本
  750. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  751. if (!$boolen2) {
  752. Utils::throwError('20003:绑定失败!');
  753. }
  754. }catch (\Exception $e) {
  755. DB::rollBack();
  756. Utils::throwError('20003:'.$e->getMessage());
  757. }
  758. DB::commit();
  759. return true;
  760. }
  761. public function chatChangeImg($data) {
  762. $segment_id = getProp($data, 'segment_id');
  763. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  764. $prompt = getProp($data, 'prompt');
  765. if (!$prompt || !$segment_id) {
  766. Utils::throwError('1002:请输入提示词,并且选择分镜');
  767. }
  768. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  769. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  770. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  771. else $ref_img_url = '';
  772. // $ref_img_url = '';
  773. if (empty($prompt)) {
  774. if (empty($ref_img_url)) {
  775. $prompt = getProp($segment, 'segment_content');
  776. }else {
  777. $prompt = '请根据图片生成';
  778. }
  779. }
  780. $anime_id = getProp($segment, 'anime_id');
  781. $episode_id = getProp($segment, 'episode_id');
  782. $episode_number = getProp($segment, 'episode_number');
  783. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  784. $ratio = getProp($data, 'ratio');
  785. if (!$ratio) {
  786. $ratio = getProp($episode, 'ratio');
  787. if (!$ratio) $ratio = '9:16';
  788. }
  789. $art_style = getProp($episode, 'art_style');
  790. if ($art_style) {
  791. $prompt = "美术风格:{$art_style}\n{$prompt}";
  792. }
  793. $dimensions = $this->getRatioDimensions($ratio);
  794. $width = $dimensions['width'];
  795. $height = $dimensions['height'];
  796. try {
  797. $params = [
  798. 'alias_segment_id' => $segment_id,
  799. 'prompt' => $prompt,
  800. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  801. 'width' => $width,
  802. 'height' => $height
  803. ];
  804. // 优化提示词(不要生成字幕)
  805. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  806. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  807. $task_id = $task->id;
  808. if (!$task_id) {
  809. Utils::throwError("20003:生成图片失败");
  810. }
  811. // 更新任务ID
  812. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update(['pic_task_id' => $task_id, 'pic_task_status' => '生成中', 'updated_at' => date('Y-m-d H:i:s')]);
  813. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  814. } catch (\Exception $e) {
  815. Utils::throwError("20003:" . $e->getMessage());
  816. }
  817. // 创建任务之后先暂停10s等待异步任务完成
  818. sleep(10);
  819. $img_url = $this->loopGetPicTaskResult($task_id);
  820. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  821. // 图片生成后新增对话记录
  822. try {
  823. $uid = Site::getUid();
  824. $now = date('Y-m-d H:i:s');
  825. // 使用AI反推图片提示词
  826. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  827. // 保存对话记录
  828. $records = [
  829. [
  830. 'uid' => $uid,
  831. 'anime_id' => $anime_id,
  832. 'sequence' => $episode_number,
  833. 'role' => 'user',
  834. 'content' => $prompt,
  835. 'segment_id' => $segment_id,
  836. 'pic_task_id' => $task_id,
  837. 'image_url' => '',
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ],
  841. [
  842. 'uid' => $uid,
  843. 'anime_id' => $anime_id,
  844. 'sequence' => $episode_number,
  845. 'role' => 'assistant',
  846. 'content' => $pic_prompt,
  847. 'segment_id' => $segment_id,
  848. 'pic_task_id' => $task_id,
  849. 'image_url' => $img_url,
  850. 'created_at' => $now,
  851. 'updated_at' => $now
  852. ]
  853. ];
  854. DB::table('mp_anime_records')->insert($records);
  855. } catch (\Exception $e) {
  856. // 记录日志但不影响主流程
  857. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  858. 'segment_id' => $segment_id,
  859. 'img_url' => $img_url
  860. ]);
  861. logDB('anime', 'error', '保存对话记录失败', [
  862. 'segment_id' => $segment_id,
  863. 'img_url' => $img_url,
  864. 'error' => $e->getMessage()
  865. ]);
  866. }
  867. return $img_url;
  868. }
  869. public function segmentChatHistory($data) {
  870. $segment_id = getProp($data, 'segment_id');
  871. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  872. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'created_at');
  873. $chat = $query->orderBy('id')->get()->map(function ($value) {
  874. $value = (array)$value;
  875. $value['created_at'] = transDate($value['created_at']);
  876. return $value;
  877. })->toArray();
  878. // 获取历史图片
  879. $url = [];
  880. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  881. foreach($pic_history as $task) {
  882. $result_url = getProp($task, 'result_url');
  883. if (is_json($result_url)) {
  884. $url = array_merge($url, json_decode($result_url, true));
  885. }else {
  886. $url[] = $result_url;
  887. }
  888. }
  889. // 获取历史视频
  890. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  891. foreach($video_history as $task) {
  892. $result_url = getProp($task, 'compressed_url');
  893. if (is_json($result_url)) {
  894. $url = array_merge($url, json_decode($result_url, true));
  895. }else {
  896. $url[] = $result_url;
  897. }
  898. }
  899. return compact('chat', 'url');
  900. }
  901. public function changeEpisodeRoles($data) {
  902. $anime_id = getProp($data, 'anime_id');
  903. $episode_id = getProp($data, 'episode_id');
  904. $target_roles = getProp($data, 'roles');
  905. $is_deleted = getProp($data, 'is_deleted', 0);
  906. // 参数验证
  907. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  908. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  909. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  910. // 验证剧集是否存在
  911. $episode = DB::table('mp_anime_episodes')
  912. ->where('anime_id', $anime_id)
  913. ->where('id', $episode_id)
  914. ->first();
  915. if (!$episode) Utils::throwError('20003:该剧集不存在');
  916. $roles = json_decode(getProp($episode, 'roles'), true);
  917. // 获取anime信息,检查是否有关联的script_id
  918. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  919. if (!$anime) Utils::throwError('20003:动漫不存在');
  920. $script_id = getProp($anime, 'script_id');
  921. $episode_number = getProp($episode, 'episode_number', 1);
  922. $uid = Site::getUid();
  923. $cpid = Site::getCpid();
  924. try {
  925. $target_role_name = getProp($target_roles, 'role');
  926. if (empty($target_role_name)) {
  927. Utils::throwError('20003:角色名称不能为空');
  928. }
  929. // 如果是删除操作
  930. if ($is_deleted == 1) {
  931. // 从角色列表中移除该角色
  932. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  933. return getProp($role, 'role') !== $target_role_name;
  934. }));
  935. // 更新角色列表
  936. $result = DB::table('mp_anime_episodes')
  937. ->where('anime_id', $anime_id)
  938. ->where('id', $episode_id)
  939. ->update([
  940. 'roles' => json_encode($roles, 256),
  941. 'updated_at' => date('Y-m-d H:i:s')
  942. ]);
  943. if ($result === false) {
  944. Utils::throwError('20003:删除角色失败');
  945. }
  946. } else {
  947. // 新增或更新操作
  948. $role_found = false;
  949. $is_new_role = false;
  950. // 查找并更新已存在的角色
  951. foreach($roles as &$role) {
  952. if (getProp($role, 'role') === $target_role_name) {
  953. $role = $target_roles;
  954. $role_found = true;
  955. break;
  956. }
  957. }
  958. // 如果角色不存在,则新增
  959. if (!$role_found) {
  960. $roles[] = $target_roles;
  961. $is_new_role = true;
  962. }
  963. // 更新角色列表
  964. $result = DB::table('mp_anime_episodes')
  965. ->where('anime_id', $anime_id)
  966. ->where('id', $episode_id)
  967. ->update([
  968. 'roles' => json_encode($roles, 256),
  969. 'updated_at' => date('Y-m-d H:i:s')
  970. ]);
  971. if ($result === false) {
  972. Utils::throwError('20003:更新角色列表失败');
  973. }
  974. // 同步更新分镜表中对应主体的音色信息
  975. $voice_name = getProp($target_roles, 'voice_name');
  976. $voice_type = getProp($target_roles, 'voice_type');
  977. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  978. DB::table('mp_episode_segments')
  979. ->where('anime_id', $anime_id)
  980. ->where('episode_id', $episode_id)
  981. ->where('voice_actor', $target_role_name)
  982. ->update([
  983. 'voice_name' => $voice_name,
  984. 'voice_type' => $voice_type,
  985. 'voice_audio_url' => $voice_audio_url,
  986. 'updated_at' => date('Y-m-d H:i:s')
  987. ]);
  988. // 如果有关联的script_id,则同步到mp_products表
  989. if ($script_id) {
  990. // 查询剧本信息
  991. $script = DB::table('mp_scripts')
  992. ->where('id', $script_id)
  993. ->where('is_deleted', 0)
  994. ->first();
  995. if ($script) {
  996. $script_name = $script->script_name ?? 'script_' . $script_id;
  997. $product_name = getProp($target_roles, 'role');
  998. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  999. $url = getProp($target_roles, 'url', '');
  1000. $product_type = 1; // 1=角色
  1001. // 查找或创建以script_name命名的文件夹
  1002. $folder = DB::table('mp_products')
  1003. ->where('cpid', $cpid)
  1004. ->where('type', 2) // 文件夹类型
  1005. ->where('product', $product_type) // 角色类型
  1006. ->where('product_name', $script_name)
  1007. ->where('parent_id', 0)
  1008. ->where('is_deleted', 0)
  1009. ->first();
  1010. if (!$folder) {
  1011. // 创建文件夹
  1012. $folder_id = DB::table('mp_products')->insertGetId([
  1013. 'user_id' => $uid,
  1014. 'cpid' => $cpid,
  1015. 'type' => 2, // 文件夹
  1016. 'product' => $product_type, // 角色类型
  1017. 'parent_id' => 0,
  1018. 'level' => 1,
  1019. 'product_name' => $script_name,
  1020. 'sort_order' => time(),
  1021. 'is_deleted' => 0,
  1022. 'created_at' => date('Y-m-d H:i:s'),
  1023. 'updated_at' => date('Y-m-d H:i:s')
  1024. ]);
  1025. } else {
  1026. $folder_id = $folder->id;
  1027. }
  1028. // 查找该文件夹下是否已存在同名资产
  1029. $existing_product = DB::table('mp_products')
  1030. ->where('cpid', $cpid)
  1031. ->where('type', 1) // 资产类型
  1032. ->where('product', $product_type)
  1033. ->where('parent_id', $folder_id)
  1034. ->where('product_name', $product_name)
  1035. ->where('is_deleted', 0)
  1036. ->first();
  1037. if ($existing_product) {
  1038. // 更新已存在的资产
  1039. $updateData = [
  1040. 'pic_task_status' => '生成成功',
  1041. ];
  1042. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1043. if ($url) $updateData['url'] = $url;
  1044. // 处理versions字段
  1045. $versions = getProp($target_roles, 'versions', []);
  1046. if ($versions && is_array($versions)) {
  1047. $updateData['versions'] = json_encode($versions, 256);
  1048. }
  1049. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1050. DB::table('mp_products')
  1051. ->where('id', $existing_product->id)
  1052. ->update($updateData);
  1053. $product_id = $existing_product->id;
  1054. } else {
  1055. // 创建新资产
  1056. $versions = getProp($target_roles, 'versions', []);
  1057. $product_id = DB::table('mp_products')->insertGetId([
  1058. 'user_id' => $uid,
  1059. 'cpid' => $cpid,
  1060. 'type' => 1, // 资产
  1061. 'product' => $product_type, // 角色
  1062. 'parent_id' => $folder_id,
  1063. 'level' => 2,
  1064. 'product_name' => $product_name,
  1065. 'url' => $url,
  1066. 'pic_prompt' => $pic_prompt,
  1067. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1068. 'sort_order' => time(),
  1069. 'is_deleted' => 0,
  1070. 'pic_task_status' => '生成成功',
  1071. 'created_at' => date('Y-m-d H:i:s'),
  1072. 'updated_at' => date('Y-m-d H:i:s')
  1073. ]);
  1074. }
  1075. // 建立或更新绑定关系
  1076. $existing_mapping = DB::table('mp_script_product_mappings')
  1077. ->where('script_id', $script_id)
  1078. ->where('product_id', $product_id)
  1079. ->where('episode_number', $episode_number)
  1080. ->first();
  1081. if (!$existing_mapping) {
  1082. // 创建绑定关系
  1083. DB::table('mp_script_product_mappings')->insert([
  1084. 'script_id' => $script_id,
  1085. 'product_id' => $product_id,
  1086. 'episode_number' => $episode_number,
  1087. 'created_at' => date('Y-m-d H:i:s'),
  1088. 'updated_at' => date('Y-m-d H:i:s')
  1089. ]);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. } catch (\Exception $e) {
  1095. dLog('anime')->error('更新剧集角色失败', [
  1096. 'anime_id' => $anime_id,
  1097. 'episode_id' => $episode_id,
  1098. 'error' => $e->getMessage()
  1099. ]);
  1100. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1101. }
  1102. return true;
  1103. }
  1104. public function changeEpisodeScenes($data) {
  1105. $anime_id = getProp($data, 'anime_id');
  1106. $episode_id = getProp($data, 'episode_id');
  1107. $target_scenes = getProp($data, 'scenes');
  1108. $is_deleted = getProp($data, 'is_deleted', 0);
  1109. // 参数验证
  1110. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1111. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1112. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1113. // 验证剧集是否存在
  1114. $episode = DB::table('mp_anime_episodes')
  1115. ->where('anime_id', $anime_id)
  1116. ->where('id', $episode_id)
  1117. ->first();
  1118. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1119. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1120. // 获取anime信息,检查是否有关联的script_id
  1121. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1122. if (!$anime) Utils::throwError('20003:动漫不存在');
  1123. $script_id = getProp($anime, 'script_id');
  1124. $episode_number = getProp($episode, 'episode_number', 1);
  1125. $uid = Site::getUid();
  1126. $cpid = Site::getCpid();
  1127. try {
  1128. $target_scene_name = getProp($target_scenes, 'scene');
  1129. if (empty($target_scene_name)) {
  1130. Utils::throwError('20003:场景名称不能为空');
  1131. }
  1132. // 如果是删除操作
  1133. if ($is_deleted == 1) {
  1134. // 从场景列表中移除该场景
  1135. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1136. return getProp($scene, 'scene') !== $target_scene_name;
  1137. }));
  1138. // 更新场景列表
  1139. $result = DB::table('mp_anime_episodes')
  1140. ->where('anime_id', $anime_id)
  1141. ->where('id', $episode_id)
  1142. ->update([
  1143. 'scenes' => json_encode($scenes, 256),
  1144. 'updated_at' => date('Y-m-d H:i:s')
  1145. ]);
  1146. if ($result === false) {
  1147. Utils::throwError('20003:删除场景失败');
  1148. }
  1149. } else {
  1150. // 新增或更新操作
  1151. $scene_found = false;
  1152. $is_new_scene = false;
  1153. // 查找并更新已存在的场景
  1154. foreach($scenes as &$scene) {
  1155. if (getProp($scene, 'scene') === $target_scene_name) {
  1156. $scene = $target_scenes;
  1157. $scene_found = true;
  1158. break;
  1159. }
  1160. }
  1161. // 如果场景不存在,则新增
  1162. if (!$scene_found) {
  1163. $scenes[] = $target_scenes;
  1164. $is_new_scene = true;
  1165. }
  1166. // 更新场景列表
  1167. $result = DB::table('mp_anime_episodes')
  1168. ->where('anime_id', $anime_id)
  1169. ->where('id', $episode_id)
  1170. ->update([
  1171. 'scenes' => json_encode($scenes, 256),
  1172. 'updated_at' => date('Y-m-d H:i:s')
  1173. ]);
  1174. if ($result === false) {
  1175. Utils::throwError('20003:更新场景列表失败');
  1176. }
  1177. // 如果有关联的script_id,则同步到mp_products表
  1178. if ($script_id) {
  1179. // 查询剧本信息
  1180. $script = DB::table('mp_scripts')
  1181. ->where('id', $script_id)
  1182. ->where('is_deleted', 0)
  1183. ->first();
  1184. if ($script) {
  1185. $script_name = $script->script_name ?? 'script_' . $script_id;
  1186. $product_name = getProp($target_scenes, 'scene');
  1187. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1188. $url = getProp($target_scenes, 'url', '');
  1189. $product_type = 2; // 2=场景
  1190. // 查找或创建以script_name命名的文件夹
  1191. $folder = DB::table('mp_products')
  1192. ->where('cpid', $cpid)
  1193. ->where('type', 2) // 文件夹类型
  1194. ->where('product', $product_type) // 场景类型
  1195. ->where('product_name', $script_name)
  1196. ->where('parent_id', 0)
  1197. ->where('is_deleted', 0)
  1198. ->first();
  1199. if (!$folder) {
  1200. // 创建文件夹
  1201. $folder_id = DB::table('mp_products')->insertGetId([
  1202. 'user_id' => $uid,
  1203. 'cpid' => $cpid,
  1204. 'type' => 2, // 文件夹
  1205. 'product' => $product_type, // 场景类型
  1206. 'parent_id' => 0,
  1207. 'level' => 1,
  1208. 'product_name' => $script_name,
  1209. 'sort_order' => time(),
  1210. 'is_deleted' => 0,
  1211. 'created_at' => date('Y-m-d H:i:s'),
  1212. 'updated_at' => date('Y-m-d H:i:s')
  1213. ]);
  1214. } else {
  1215. $folder_id = $folder->id;
  1216. }
  1217. // 查找该文件夹下是否已存在同名资产
  1218. $existing_product = DB::table('mp_products')
  1219. ->where('cpid', $cpid)
  1220. ->where('type', 1) // 资产类型
  1221. ->where('product', $product_type)
  1222. ->where('parent_id', $folder_id)
  1223. ->where('product_name', $product_name)
  1224. ->where('is_deleted', 0)
  1225. ->first();
  1226. if ($existing_product) {
  1227. // 更新已存在的资产
  1228. $updateData = [
  1229. 'pic_task_status' => '生成成功'
  1230. ];
  1231. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1232. if ($url) $updateData['url'] = $url;
  1233. // 处理versions字段
  1234. $versions = getProp($target_scenes, 'versions', []);
  1235. if ($versions && is_array($versions)) {
  1236. $updateData['versions'] = json_encode($versions, 256);
  1237. }
  1238. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1239. DB::table('mp_products')
  1240. ->where('id', $existing_product->id)
  1241. ->update($updateData);
  1242. $product_id = $existing_product->id;
  1243. } else {
  1244. // 创建新资产
  1245. $versions = getProp($target_scenes, 'versions', []);
  1246. $product_id = DB::table('mp_products')->insertGetId([
  1247. 'user_id' => $uid,
  1248. 'cpid' => $cpid,
  1249. 'type' => 1, // 资产
  1250. 'product' => $product_type, // 场景
  1251. 'parent_id' => $folder_id,
  1252. 'level' => 2,
  1253. 'product_name' => $product_name,
  1254. 'url' => $url,
  1255. 'pic_prompt' => $pic_prompt,
  1256. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1257. 'sort_order' => time(),
  1258. 'is_deleted' => 0,
  1259. 'pic_task_status' => '生成成功',
  1260. 'created_at' => date('Y-m-d H:i:s'),
  1261. 'updated_at' => date('Y-m-d H:i:s')
  1262. ]);
  1263. }
  1264. // 建立或更新绑定关系
  1265. $existing_mapping = DB::table('mp_script_product_mappings')
  1266. ->where('script_id', $script_id)
  1267. ->where('product_id', $product_id)
  1268. ->where('episode_number', $episode_number)
  1269. ->first();
  1270. if (!$existing_mapping) {
  1271. // 创建绑定关系
  1272. DB::table('mp_script_product_mappings')->insert([
  1273. 'script_id' => $script_id,
  1274. 'product_id' => $product_id,
  1275. 'episode_number' => $episode_number,
  1276. 'created_at' => date('Y-m-d H:i:s'),
  1277. 'updated_at' => date('Y-m-d H:i:s')
  1278. ]);
  1279. }
  1280. }
  1281. }
  1282. }
  1283. } catch (\Exception $e) {
  1284. dLog('anime')->error('更新剧集场景失败', [
  1285. 'anime_id' => $anime_id,
  1286. 'episode_id' => $episode_id,
  1287. 'error' => $e->getMessage()
  1288. ]);
  1289. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1290. }
  1291. return true;
  1292. }
  1293. public function changeEpisodeProps($data) {
  1294. $anime_id = getProp($data, 'anime_id');
  1295. $episode_id = getProp($data, 'episode_id');
  1296. $target_props = getProp($data, 'props');
  1297. $is_deleted = getProp($data, 'is_deleted', 0);
  1298. // 参数验证
  1299. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1300. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1301. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1302. // 验证剧集是否存在
  1303. $episode = DB::table('mp_anime_episodes')
  1304. ->where('anime_id', $anime_id)
  1305. ->where('id', $episode_id)
  1306. ->first();
  1307. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1308. $props = json_decode(getProp($episode, 'props'), true);
  1309. // 获取anime信息,检查是否有关联的script_id
  1310. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1311. if (!$anime) Utils::throwError('20003:动漫不存在');
  1312. $script_id = getProp($anime, 'script_id');
  1313. $episode_number = getProp($episode, 'episode_number', 1);
  1314. $uid = Site::getUid();
  1315. $cpid = Site::getCpid();
  1316. try {
  1317. $target_prop_name = getProp($target_props, 'prop');
  1318. if (empty($target_prop_name)) {
  1319. Utils::throwError('20003:道具名称不能为空');
  1320. }
  1321. // 如果是删除操作
  1322. if ($is_deleted == 1) {
  1323. // 从道具列表中移除该道具
  1324. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1325. return getProp($prop, 'prop') !== $target_prop_name;
  1326. }));
  1327. // 更新道具列表
  1328. $result = DB::table('mp_anime_episodes')
  1329. ->where('anime_id', $anime_id)
  1330. ->where('id', $episode_id)
  1331. ->update([
  1332. 'props' => json_encode($props, 256),
  1333. 'updated_at' => date('Y-m-d H:i:s')
  1334. ]);
  1335. if ($result === false) {
  1336. Utils::throwError('20003:删除道具失败');
  1337. }
  1338. } else {
  1339. // 新增或更新操作
  1340. $prop_found = false;
  1341. $is_new_prop = false;
  1342. // 查找并更新已存在的道具
  1343. foreach($props as &$prop) {
  1344. if (getProp($prop, 'prop') === $target_prop_name) {
  1345. $prop = $target_props;
  1346. $prop_found = true;
  1347. break;
  1348. }
  1349. }
  1350. // 如果道具不存在,则新增
  1351. if (!$prop_found) {
  1352. $props[] = $target_props;
  1353. $is_new_prop = true;
  1354. }
  1355. // 更新道具列表
  1356. $result = DB::table('mp_anime_episodes')
  1357. ->where('anime_id', $anime_id)
  1358. ->where('id', $episode_id)
  1359. ->update([
  1360. 'props' => json_encode($props, 256),
  1361. 'updated_at' => date('Y-m-d H:i:s')
  1362. ]);
  1363. if ($result === false) {
  1364. Utils::throwError('20003:更新道具列表失败');
  1365. }
  1366. // 如果有关联的script_id,则同步到mp_products表
  1367. if ($script_id) {
  1368. // 查询剧本信息
  1369. $script = DB::table('mp_scripts')
  1370. ->where('id', $script_id)
  1371. ->where('is_deleted', 0)
  1372. ->first();
  1373. if ($script) {
  1374. $script_name = $script->script_name ?? 'script_' . $script_id;
  1375. $product_name = getProp($target_props, 'prop');
  1376. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1377. $url = getProp($target_props, 'url', '');
  1378. $product_type = 3; // 3=道具
  1379. // 查找或创建以script_name命名的文件夹
  1380. $folder = DB::table('mp_products')
  1381. ->where('cpid', $cpid)
  1382. ->where('type', 2) // 文件夹类型
  1383. ->where('product', $product_type) // 道具类型
  1384. ->where('product_name', $script_name)
  1385. ->where('parent_id', 0)
  1386. ->where('is_deleted', 0)
  1387. ->first();
  1388. if (!$folder) {
  1389. // 创建文件夹
  1390. $folder_id = DB::table('mp_products')->insertGetId([
  1391. 'user_id' => $uid,
  1392. 'cpid' => $cpid,
  1393. 'type' => 2, // 文件夹
  1394. 'product' => $product_type, // 道具类型
  1395. 'parent_id' => 0,
  1396. 'level' => 1,
  1397. 'product_name' => $script_name,
  1398. 'sort_order' => time(),
  1399. 'is_deleted' => 0,
  1400. 'created_at' => date('Y-m-d H:i:s'),
  1401. 'updated_at' => date('Y-m-d H:i:s')
  1402. ]);
  1403. } else {
  1404. $folder_id = $folder->id;
  1405. }
  1406. // 查找该文件夹下是否已存在同名资产
  1407. $existing_product = DB::table('mp_products')
  1408. ->where('cpid', $cpid)
  1409. ->where('type', 1) // 资产类型
  1410. ->where('product', $product_type)
  1411. ->where('parent_id', $folder_id)
  1412. ->where('product_name', $product_name)
  1413. ->where('is_deleted', 0)
  1414. ->first();
  1415. if ($existing_product) {
  1416. // 更新已存在的资产
  1417. $updateData = [
  1418. 'pic_task_status' => '生成成功'
  1419. ];
  1420. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1421. if ($url) $updateData['url'] = $url;
  1422. // 处理versions字段
  1423. $versions = getProp($target_props, 'versions', []);
  1424. if ($versions && is_array($versions)) {
  1425. $updateData['versions'] = json_encode($versions, 256);
  1426. }
  1427. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1428. DB::table('mp_products')
  1429. ->where('id', $existing_product->id)
  1430. ->update($updateData);
  1431. $product_id = $existing_product->id;
  1432. } else {
  1433. // 创建新资产
  1434. $versions = getProp($target_props, 'versions', []);
  1435. $product_id = DB::table('mp_products')->insertGetId([
  1436. 'user_id' => $uid,
  1437. 'cpid' => $cpid,
  1438. 'type' => 1, // 资产
  1439. 'product' => $product_type, // 道具
  1440. 'parent_id' => $folder_id,
  1441. 'level' => 2,
  1442. 'product_name' => $product_name,
  1443. 'url' => $url,
  1444. 'pic_prompt' => $pic_prompt,
  1445. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1446. 'sort_order' => time(),
  1447. 'is_deleted' => 0,
  1448. 'pic_task_status' => '生成成功',
  1449. 'created_at' => date('Y-m-d H:i:s'),
  1450. 'updated_at' => date('Y-m-d H:i:s')
  1451. ]);
  1452. }
  1453. // 建立或更新绑定关系
  1454. $existing_mapping = DB::table('mp_script_product_mappings')
  1455. ->where('script_id', $script_id)
  1456. ->where('product_id', $product_id)
  1457. ->where('episode_number', $episode_number)
  1458. ->first();
  1459. if (!$existing_mapping) {
  1460. // 创建绑定关系
  1461. DB::table('mp_script_product_mappings')->insert([
  1462. 'script_id' => $script_id,
  1463. 'product_id' => $product_id,
  1464. 'episode_number' => $episode_number,
  1465. 'created_at' => date('Y-m-d H:i:s'),
  1466. 'updated_at' => date('Y-m-d H:i:s')
  1467. ]);
  1468. }
  1469. }
  1470. }
  1471. }
  1472. } catch (\Exception $e) {
  1473. dLog('anime')->error('更新剧集道具失败', [
  1474. 'anime_id' => $anime_id,
  1475. 'episode_id' => $episode_id,
  1476. 'error' => $e->getMessage()
  1477. ]);
  1478. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1479. }
  1480. return true;
  1481. }
  1482. public function editSegment($data) {
  1483. $segment_id = getProp($data, 'segment_id');
  1484. $segment_content = getProp($data, 'segment_content');
  1485. $image_url = getProp($data, 'image_url');
  1486. $video_url = getProp($data, 'video_url');
  1487. // 参数验证
  1488. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1489. // 验证分镜是否存在
  1490. $segment = DB::table('mp_episode_segments')
  1491. ->where('segment_id', $segment_id)
  1492. ->first();
  1493. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1494. $dubTaskId = 0;
  1495. try {
  1496. DB::beginTransaction();
  1497. // 准备更新数据
  1498. $update_data = [
  1499. 'updated_at' => date('Y-m-d H:i:s')
  1500. ];
  1501. if ($segment_content) {
  1502. // 先将segment_content赋值到update_data
  1503. $update_data['segment_content'] = $segment_content;
  1504. // 使用现有方法分析segment_content,提取各个字段
  1505. $this->handleSegmentContent($update_data);
  1506. // 如果有对话内容,创建视频配音合成任务
  1507. $dialogue = getProp($update_data, 'dialogue');
  1508. if (!empty($dialogue)) {
  1509. $now = date('Y-m-d H:i:s');
  1510. $generate_json = [
  1511. 'text' => $dialogue,
  1512. 'role' => getProp($update_data, 'voice_actor'),
  1513. 'voice_type' => getProp($update_data, 'voice_type'),
  1514. 'voice_name' => getProp($update_data, 'voice_name'),
  1515. 'emotion' => getProp($update_data, 'emotion'),
  1516. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1517. 'gender' => getProp($update_data, 'gender'),
  1518. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1519. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1520. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1521. 'pitch' => getProp($update_data, 'pitch', 0),
  1522. ];
  1523. // 插入视频配音合成任务
  1524. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1525. 'alias_segment_id' => $segment_id,
  1526. 'generate_status' => '执行中',
  1527. 'audio_url' => '',
  1528. 'generate_json' => json_encode($generate_json, 256),
  1529. 'created_at' => $now,
  1530. 'updated_at' => $now,
  1531. ]);
  1532. if (!$dubTaskId) {
  1533. Utils::throwError('20003:创建配音任务失败!');
  1534. }
  1535. $update_data['audio_url'] = '';
  1536. } else {
  1537. // dialogue为空时,直接写入默认音频信息
  1538. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1539. $update_data['audio_duration'] = 2.0;
  1540. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1541. }
  1542. }
  1543. if ($image_url) {
  1544. $update_data['img_url'] = $image_url;
  1545. // 同时写入一个简单的图片生成任务
  1546. $pic_task = [
  1547. 'alias_segment_id' => $segment_id,
  1548. 'ref_img_url' => json_encode([]),
  1549. 'status' => 'success',
  1550. 'result_url' => json_encode([$image_url], 256),
  1551. 'model' => '',
  1552. 'created_at' => date('Y-m-d H:i:s'),
  1553. 'updated_at' => date('Y-m-d H:i:s'),
  1554. ];
  1555. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1556. }
  1557. if ($video_url) {
  1558. $update_data['origin_video_url'] = $video_url;
  1559. $compressed_video_url = compressVideo($video_url);
  1560. $update_data['current_type'] = 2;
  1561. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1562. // 同时写入一个简单的视频生成任务
  1563. $video_task = [
  1564. 'alias_segment_id' => $segment_id,
  1565. 'status' => 'success',
  1566. 'result_url' => $update_data['origin_video_url'],
  1567. 'compressed_url' => $update_data['video_url'],
  1568. 'created_at' => date('Y-m-d H:i:s'),
  1569. 'updated_at' => date('Y-m-d H:i:s'),
  1570. ];
  1571. DB::table('mp_generate_video_tasks')->insert($video_task);
  1572. }
  1573. // 更新分镜信息
  1574. $result = DB::table('mp_episode_segments')
  1575. ->where('segment_id', $segment_id)
  1576. ->update($update_data);
  1577. if ($result === false) {
  1578. Utils::throwError('20003:更新分镜剧本失败');
  1579. }
  1580. DB::commit();
  1581. // 如果有创建音频生成任务则调用API
  1582. if ($dubTaskId) {
  1583. // 请求远程服务器执行生成
  1584. $client = new Client(['timeout' => 300, 'verify' => false]);
  1585. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1586. $response = $result->getBody()->getContents();
  1587. $response_arr = json_decode($response, true);
  1588. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1589. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1590. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1591. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1592. Utils::throwError('20003:火山生成音频失败');
  1593. }
  1594. }
  1595. return true;
  1596. } catch (\Exception $e) {
  1597. DB::rollBack();
  1598. dLog('anime')->error('更新分镜剧本失败', [
  1599. 'segment_id' => $segment_id,
  1600. 'error' => $e->getMessage()
  1601. ]);
  1602. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1603. }
  1604. }
  1605. public function batchSetSegmentPics($data) {
  1606. $anime_id = getProp($data, 'anime_id');
  1607. $episode_id = getProp($data, 'episode_id');
  1608. $ratio = getProp($data, 'ratio');
  1609. $dimensions = $this->getRatioDimensions($ratio);
  1610. $width = $dimensions['width'];
  1611. $height = $dimensions['height'];
  1612. if (!$anime_id || !$episode_id) {
  1613. Utils::throwError('1002:请选择剧集');
  1614. }
  1615. // 获取剧集信息
  1616. $episode = DB::table('mp_anime_episodes')
  1617. ->where('anime_id', $anime_id)
  1618. ->where('id', $episode_id)
  1619. ->where('is_default', 1)
  1620. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1621. ->first();
  1622. if (!$episode) {
  1623. Utils::throwError('20003:该剧集不存在');
  1624. }
  1625. $model = getProp($data, 'model');
  1626. if (!$model) {
  1627. $model = getProp($episode, 'image_model');
  1628. if (!$model) {
  1629. // episode表也没有,使用默认值
  1630. $model = 'doubao-seedream-5-0-lite-260128';
  1631. }
  1632. }
  1633. // 验证模型是否在可用模型表中
  1634. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1635. $model = 'doubao-seedream-5-0-lite-260128';
  1636. }
  1637. $roles = json_decode(getProp($episode, 'roles'), true);
  1638. if (!$roles) {
  1639. Utils::throwError('20003:角色信息格式错误');
  1640. }
  1641. // 构建角色名称到参考图的映射
  1642. $role_map = [];
  1643. foreach ($roles as $role) {
  1644. $role_name = getProp($role, 'role');
  1645. $role_url = getProp($role, 'url');
  1646. if (!empty($role_name) && !empty($role_url)) {
  1647. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1648. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1649. // $role_map[$base_name] = $role_url;
  1650. // 同时保存完整名称的映射
  1651. $role_map[$role_name] = $role_url;
  1652. }
  1653. }
  1654. $scenes = json_decode(getProp($episode, 'roles'), true);
  1655. if (!$scenes) {
  1656. Utils::throwError('20003:场景信息格式错误');
  1657. }
  1658. // 构建角色名称到参考图的映射
  1659. $scene_map = [];
  1660. foreach ($scenes as $scene) {
  1661. $scene_name = getProp($scene, 'scene');
  1662. $scene_url = getProp($scene, 'url');
  1663. if (!empty($scene_name) && !empty($scene_url)) {
  1664. $scene_map[$scene_name] = $scene_url;
  1665. }
  1666. }
  1667. // 获取所有分镜信息
  1668. $segments = DB::table('mp_episode_segments')
  1669. ->where('anime_id', $anime_id)
  1670. ->where('episode_id', $episode_id)
  1671. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1672. ->orderBy('segment_number')
  1673. ->get()
  1674. ->toArray();
  1675. if (empty($segments)) {
  1676. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1677. }
  1678. // 保存图片比例
  1679. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1680. $updated_segments = [];
  1681. $failed_segments = [];
  1682. // 批量为每个分镜生成图片任务
  1683. foreach ($segments as $segment) {
  1684. $segment_id = $segment->segment_id;
  1685. $segment_content = $segment->segment_content;
  1686. if (empty($segment_content)) {
  1687. $failed_segments[] = [
  1688. 'segment_id' => $segment_id,
  1689. 'error' => '分镜内容为空'
  1690. ];
  1691. continue;
  1692. }
  1693. try {
  1694. $dubTaskId = 0;
  1695. // 解析分镜内容,提取画面描述作为主要提示词
  1696. $prompt = $segment_content;
  1697. $ref_img_urls = [];
  1698. // 分镜场景
  1699. $scene = getProp($segment, 'scene');
  1700. $matched_scene = '';
  1701. if (isset($scene_map[$scene])) {
  1702. $img_index = count($ref_img_urls) + 1;
  1703. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1704. $ref_img_urls[] = $scene_map[$scene];
  1705. $matched_scene = $scene;
  1706. }
  1707. // 分镜角色
  1708. $characters = getProp($segment, 'characters');
  1709. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1710. $roles = explode(',', $characters);
  1711. // 从分镜内容中提取涉及的角色
  1712. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1713. // 获取匹配角色的参考图
  1714. foreach ($segment_characters as $character) {
  1715. if (isset($role_map[$character])) {
  1716. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1717. $img_index = count($ref_img_urls) + 1;
  1718. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1719. $ref_img_urls[] = $role_map[$character];
  1720. }
  1721. }
  1722. // 如果没有找到匹配的角色参考图,不使用参考图
  1723. if (empty($ref_img_urls)) {
  1724. $ref_img_urls = [];
  1725. }
  1726. // 准备生成任务参数
  1727. $params = [
  1728. 'model' => $model,
  1729. 'alias_segment_id' => $segment_id,
  1730. 'prompt' => $prompt,
  1731. 'ref_img_urls' => $ref_img_urls,
  1732. 'width' => $width,
  1733. 'height' => $height,
  1734. ];
  1735. // 优化提示词(不要生成字幕)
  1736. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1737. // $task_id = mt_rand(100000, 999999);
  1738. // 调用AI图片生成服务
  1739. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1740. $task_id = $task->id;
  1741. if (!$task_id) {
  1742. $failed_segments[] = [
  1743. 'segment_id' => $segment_id,
  1744. 'error' => '创建生成任务失败'
  1745. ];
  1746. continue;
  1747. }
  1748. $update_data = [
  1749. 'pic_task_id' => $task_id,
  1750. 'pic_task_status' => '生成中',
  1751. 'audio_url' => '',
  1752. 'updated_at' => date('Y-m-d H:i:s')
  1753. ];
  1754. // 如果有对话内容,创建视频配音合成任务
  1755. $dialogue = getProp($segment, 'dialogue');
  1756. if (!empty($dialogue)) {
  1757. $now = date('Y-m-d H:i:s');
  1758. $generate_json = [
  1759. 'text' => $dialogue,
  1760. 'role' => getProp($segment, 'voice_actor'),
  1761. 'voice_type' => getProp($segment, 'voice_type'),
  1762. 'voice_name' => getProp($segment, 'voice_name'),
  1763. 'emotion' => getProp($segment, 'emotion'),
  1764. 'emotion_type' => getProp($segment, 'emotion_type'),
  1765. 'gender' => getProp($segment, 'gender'),
  1766. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1767. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1768. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1769. 'pitch' => getProp($segment, 'pitch', 0),
  1770. ];
  1771. // 插入视频配音合成任务
  1772. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1773. 'alias_segment_id' => $segment_id,
  1774. 'generate_status' => '执行中',
  1775. 'audio_url' => '',
  1776. 'generate_json' => json_encode($generate_json, 256),
  1777. 'created_at' => $now,
  1778. 'updated_at' => $now,
  1779. ]);
  1780. if (!$dubTaskId) {
  1781. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1782. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1783. // Utils::throwError('20003:创建配音任务失败!');
  1784. }
  1785. } else {
  1786. // dialogue为空时,直接写入默认音频信息到分镜表
  1787. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1788. $update_data['audio_duration'] = 2.0;
  1789. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1790. }
  1791. // 更新分镜的任务信息
  1792. $update_result = DB::table('mp_episode_segments')
  1793. ->where('segment_id', $segment_id)
  1794. ->update($update_data);
  1795. // 如果是第一集的首帧图片,则存入待更新数组
  1796. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1797. Redis::sadd('anime_first_frame_urls', $segment_id);
  1798. }
  1799. if ($update_result) {
  1800. $updated_segments[] = [
  1801. 'segment_id' => $segment_id,
  1802. 'task_id' => $task_id,
  1803. 'status' => '生成中',
  1804. 'matched_scenes' => $matched_scene,
  1805. 'matched_roles' => $segment_characters,
  1806. 'ref_urls_count' => count($ref_img_urls)
  1807. ];
  1808. } else {
  1809. $failed_segments[] = [
  1810. 'segment_id' => $segment_id,
  1811. 'error' => '更新分镜任务状态失败'
  1812. ];
  1813. }
  1814. if ($dubTaskId) {
  1815. sleep(1);
  1816. // 请求远程服务器执行生成
  1817. $client = new Client(['timeout' => 300, 'verify' => false]);
  1818. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1819. $response = $result->getBody()->getContents();
  1820. $response_arr = json_decode($response, true);
  1821. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1822. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1823. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1824. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1825. }
  1826. }
  1827. } catch (\Exception $e) {
  1828. $failed_segments[] = [
  1829. 'segment_id' => $segment_id,
  1830. 'error' => $e->getMessage()
  1831. ];
  1832. }
  1833. }
  1834. // 更新剧集生成状态
  1835. if (!empty($updated_segments)) {
  1836. DB::table('mp_anime_episodes')
  1837. ->where('id', $episode_id)
  1838. ->update([
  1839. 'is_generated' => 1,
  1840. 'updated_at' => date('Y-m-d H:i:s')
  1841. ]);
  1842. }
  1843. return [
  1844. 'success_count' => count($updated_segments),
  1845. 'failed_count' => count($failed_segments),
  1846. 'success_segments' => $updated_segments,
  1847. 'failed_segments' => $failed_segments,
  1848. 'total_segments' => count($segments)
  1849. ];
  1850. }
  1851. public function reGenerateSegment($data) {
  1852. $segment_id = getProp($data, 'segment_id');
  1853. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1854. $anime_id = getProp($segment, 'anime_id');
  1855. $episode_id = getProp($segment, 'episode_id');
  1856. $episode_number = getProp($segment, 'episode_number');
  1857. $segment_content = getProp($data, 'segment_content');
  1858. $ratio = getProp($data, 'ratio');
  1859. if (!$ratio) {
  1860. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1861. if (!$ratio) $ratio = '9:16';
  1862. }
  1863. $dimensions = $this->getRatioDimensions($ratio);
  1864. $width = $dimensions['width'];
  1865. $height = $dimensions['height'];
  1866. if (!$anime_id || !$episode_id) {
  1867. Utils::throwError('1002:请选择分镜');
  1868. }
  1869. // 使用文生文模型重新解析segment_content
  1870. if (!empty($segment_content)) {
  1871. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1872. }
  1873. // 获取动漫的角色信息(包含参考图)
  1874. $anime = DB::table('mp_animes')
  1875. ->where('id', $anime_id)
  1876. ->select('roles', 'scenes')
  1877. ->first();
  1878. if (!$anime || !$anime->roles) {
  1879. Utils::throwError('20003:未找到角色信息');
  1880. }
  1881. $roles = json_decode($anime->roles, true);
  1882. if (!$roles) {
  1883. Utils::throwError('20003:角色信息格式错误');
  1884. }
  1885. // 构建角色名称到参考图的映射
  1886. $role_map = [];
  1887. foreach ($roles as $role) {
  1888. $role_name = getProp($role, 'role');
  1889. $role_url = getProp($role, 'url');
  1890. if (!empty($role_name) && !empty($role_url)) {
  1891. $role_map[$role_name] = $role_url;
  1892. }
  1893. }
  1894. $scenes = json_decode($anime->scenes, true);
  1895. if (!$scenes) {
  1896. Utils::throwError('20003:角色信息格式错误');
  1897. }
  1898. // 构建角色名称到参考图的映射
  1899. $scene_map = [];
  1900. foreach ($scenes as $scene) {
  1901. $scene_name = getProp($scene, 'scene');
  1902. $scene_url = getProp($scene, 'url');
  1903. if (!empty($scene_name) && !empty($scene_url)) {
  1904. $scene_map[$scene_name] = $scene_url;
  1905. }
  1906. }
  1907. $segment_id = $segment->segment_id;
  1908. $original_segment_content = $segment->segment_content;
  1909. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1910. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1911. if (empty($final_segment_content)) {
  1912. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1913. }
  1914. try {
  1915. $dubTaskId = 0;
  1916. // 分镜剧本数组
  1917. $update_data = [
  1918. 'segment_content' => $final_segment_content,
  1919. 'pic_task_status' => '生成中',
  1920. 'updated_at' => date('Y-m-d H:i:s')
  1921. ];
  1922. // 解析分镜内容,提取画面描述作为主要提示词
  1923. $prompt = $final_segment_content;
  1924. $ref_img_urls = [];
  1925. // 分镜场景
  1926. $scene = getProp($data, 'scene');
  1927. if ($scene) {
  1928. $matched_scene = '';
  1929. if (isset($scene_map[$scene])) {
  1930. $img_index = count($ref_img_urls) + 1;
  1931. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1932. $ref_img_urls[] = $scene_map[$scene];
  1933. $matched_scene = $scene;
  1934. }
  1935. $update_data['scene'] = $scene;
  1936. }
  1937. // 分镜角色
  1938. $characters = getProp($data, 'characters');
  1939. if ($characters) {
  1940. $update_data['characters'] = $characters;
  1941. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1942. $characters = explode(',', $characters);
  1943. // 从分镜内容中提取涉及的角色
  1944. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1945. // 获取匹配角色的参考图
  1946. foreach ($segment_characters as $character) {
  1947. if (isset($role_map[$character])) {
  1948. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1949. $img_index = count($ref_img_urls) + 1;
  1950. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1951. $ref_img_urls[] = $role_map[$character];
  1952. }
  1953. }
  1954. }
  1955. // 如果没有找到匹配的角色参考图,不使用参考图
  1956. if (empty($ref_img_urls)) {
  1957. $ref_img_urls = [];
  1958. }
  1959. // 准备生成任务参数
  1960. $params = [
  1961. 'alias_segment_id' => $segment_id,
  1962. 'prompt' => $prompt,
  1963. 'ref_img_urls' => $ref_img_urls,
  1964. 'width' => $width,
  1965. 'height' => $height,
  1966. ];
  1967. // 优化提示词(不要生成字幕)
  1968. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1969. // 调用AI图片生成服务
  1970. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1971. $task_id = $task->id;
  1972. if (!$task_id) {
  1973. Utils::throwError('20003:创建生成任务失败!');
  1974. }
  1975. $update_data['pic_task_id'] = $task_id;
  1976. // 更新分镜剧本信息
  1977. $this->handleSegmentContent($update_data);
  1978. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1979. if ($segment_content) {
  1980. $dialogue = getProp($update_data, 'dialogue');
  1981. if (!empty($dialogue)) {
  1982. $now = date('Y-m-d H:i:s');
  1983. $generate_json = [
  1984. 'text' => $dialogue,
  1985. 'role' => getProp($update_data, 'voice_actor'),
  1986. 'voice_type' => getProp($update_data, 'voice_type'),
  1987. 'voice_name' => getProp($update_data, 'voice_name'),
  1988. 'emotion' => getProp($update_data, 'emotion'),
  1989. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1990. 'gender' => getProp($update_data, 'gender'),
  1991. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1992. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1993. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1994. 'pitch' => getProp($update_data, 'pitch', 0),
  1995. ];
  1996. // 插入视频配音合成任务
  1997. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1998. 'alias_segment_id' => $segment_id,
  1999. 'generate_status' => '执行中',
  2000. 'audio_url' => '',
  2001. 'generate_json' => json_encode($generate_json, 256),
  2002. 'created_at' => date('Y-m-d H:i:s'),
  2003. 'updated_at' => date('Y-m-d H:i:s'),
  2004. ]);
  2005. if (!$dubTaskId) {
  2006. Utils::throwError('20003:创建配音任务失败!');
  2007. }
  2008. $update_data['audio_url'] = '';
  2009. } else {
  2010. // dialogue为空时,直接写入默认音频信息
  2011. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2012. $update_data['audio_duration'] = 2.0;
  2013. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2014. }
  2015. }
  2016. $boolen = DB::table('mp_episode_segments')
  2017. ->where('segment_id', $segment_id)
  2018. ->update($update_data);
  2019. // 如果是第一集的首帧图片,则存入待更新数组
  2020. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2021. Redis::sadd('anime_first_frame_urls', $segment_id);
  2022. }
  2023. if ($dubTaskId) {
  2024. // 请求远程服务器执行生成
  2025. $client = new Client(['timeout' => 300, 'verify' => false]);
  2026. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2027. $response = $result->getBody()->getContents();
  2028. $response_arr = json_decode($response, true);
  2029. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2030. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2031. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2032. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2033. Utils::throwError('20003:火山生成音频失败');
  2034. }
  2035. }
  2036. } catch (\Exception $e) {
  2037. $failed_segments[] = [
  2038. 'segment_id' => $segment_id,
  2039. 'error' => $e->getMessage()
  2040. ];
  2041. }
  2042. // 创建任务之后先暂停10s等待异步任务完成
  2043. sleep(10);
  2044. $img_url = $this->loopGetPicTaskResult($task_id);
  2045. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2046. // 图片生成后新增对话记录
  2047. try {
  2048. $uid = Site::getUid();
  2049. $now = date('Y-m-d H:i:s');
  2050. // 使用AI反推图片提示词
  2051. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2052. // 保存对话记录
  2053. $records = [
  2054. [
  2055. 'uid' => $uid,
  2056. 'anime_id' => $anime_id,
  2057. 'sequence' => $episode_number,
  2058. 'role' => 'user',
  2059. 'content' => '重新生成',
  2060. 'segment_id' => $segment_id,
  2061. 'pic_task_id' => $task_id,
  2062. 'image_url' => '',
  2063. 'created_at' => $now,
  2064. 'updated_at' => $now
  2065. ],
  2066. [
  2067. 'uid' => $uid,
  2068. 'anime_id' => $anime_id,
  2069. 'sequence' => $episode_number,
  2070. 'role' => 'assistant',
  2071. 'content' => $pic_prompt,
  2072. 'segment_id' => $segment_id,
  2073. 'pic_task_id' => $task_id,
  2074. 'image_url' => $img_url,
  2075. 'created_at' => $now,
  2076. 'updated_at' => $now
  2077. ]
  2078. ];
  2079. DB::table('mp_anime_records')->insert($records);
  2080. } catch (\Exception $e) {
  2081. // 记录日志但不影响主流程
  2082. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2083. 'segment_id' => $segment_id,
  2084. 'img_url' => $img_url
  2085. ]);
  2086. }
  2087. return $img_url;
  2088. }
  2089. public function addSegment($data) {
  2090. $prev_segment_id = getProp($data, 'prev_segment_id');
  2091. $img_url = getProp($data, 'img_url');
  2092. $video_url = getProp($data, 'video_url');
  2093. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2094. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2095. $anime_id = getProp($segment, 'anime_id');
  2096. $episode_id = getProp($segment, 'episode_id');
  2097. $episode_number = getProp($segment, 'episode_number');
  2098. $segment_number = getProp($segment, 'segment_number');
  2099. $new_segment_number = $segment_number + 1;
  2100. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2101. // 分镜剧本数组
  2102. $insert_data = [
  2103. 'anime_id' => $anime_id,
  2104. 'episode_id' => $episode_id,
  2105. 'episode_number' => $episode_number,
  2106. 'act_number' => getProp($segment, 'act_number'),
  2107. 'act_title' => getProp($segment, 'act_title'),
  2108. 'segment_id' => $segment_id,
  2109. 'segment_number' => $new_segment_number,
  2110. 'segment_content' => '',
  2111. 'img_url' => '',
  2112. 'video_url' => '',
  2113. 'created_at' => date('Y-m-d H:i:s'),
  2114. 'updated_at' => date('Y-m-d H:i:s')
  2115. ];
  2116. if ($img_url) $insert_data['img_url'] = $img_url;
  2117. if ($video_url) {
  2118. $insert_data['origin_video_url'] = $video_url;
  2119. $insert_data['current_type'] = 2;
  2120. $compressed_video_url = compressVideo($video_url);
  2121. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2122. }
  2123. try {
  2124. DB::beginTransaction();
  2125. // 先更新序号
  2126. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2127. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2128. if (!$id) {
  2129. Utils::throwError('20003:新增分镜失败!');
  2130. }
  2131. }catch (\Exception $e) {
  2132. DB::rollBack();
  2133. Utils::throwError('20003:'.$e->getMessage());
  2134. }
  2135. DB::commit();
  2136. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2137. $segment = $segment ? (array)$segment : [];
  2138. return $segment;
  2139. // 以下代码暂弃用
  2140. $anime_id = getProp($segment, 'anime_id');
  2141. $episode_id = getProp($segment, 'episode_id');
  2142. $episode_number = getProp($segment, 'episode_number');
  2143. $segment_number = getProp($segment, 'segment_number');
  2144. $segment_content = getProp($data, 'segment_content');
  2145. $img_url = getProp($data, 'img_url');
  2146. $video_url = getProp($data, 'video_url');
  2147. $ratio = getProp($data, 'ratio');
  2148. $dimensions = $this->getRatioDimensions($ratio);
  2149. $width = $dimensions['width'];
  2150. $height = $dimensions['height'];
  2151. if (!$anime_id || !$episode_id) {
  2152. Utils::throwError('1002:请选择分镜');
  2153. }
  2154. // 使用文生文模型重新解析segment_content
  2155. if (!empty($segment_content)) {
  2156. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2157. }
  2158. // 获取动漫的角色信息(包含参考图)
  2159. $anime = DB::table('mp_animes')
  2160. ->where('id', $anime_id)
  2161. ->select('roles', 'scenes')
  2162. ->first();
  2163. if (!$anime || !$anime->roles) {
  2164. Utils::throwError('20003:未找到角色信息');
  2165. }
  2166. $roles = json_decode($anime->roles, true);
  2167. if (!$roles) {
  2168. Utils::throwError('20003:角色信息格式错误');
  2169. }
  2170. // 构建角色名称到参考图的映射
  2171. $role_map = [];
  2172. foreach ($roles as $role) {
  2173. $role_name = getProp($role, 'role');
  2174. $role_url = getProp($role, 'url');
  2175. if (!empty($role_name) && !empty($role_url)) {
  2176. $role_map[$role_name] = $role_url;
  2177. }
  2178. }
  2179. $scenes = json_decode($anime->scenes, true);
  2180. if (!$scenes) {
  2181. Utils::throwError('20003:角色信息格式错误');
  2182. }
  2183. // 构建角色名称到参考图的映射
  2184. $scene_map = [];
  2185. foreach ($scenes as $scene) {
  2186. $scene_name = getProp($scene, 'scene');
  2187. $scene_url = getProp($scene, 'url');
  2188. if (!empty($scene_name) && !empty($scene_url)) {
  2189. $scene_map[$scene_name] = $scene_url;
  2190. }
  2191. }
  2192. $segment_id = $segment->segment_id;
  2193. $original_segment_content = $segment->segment_content;
  2194. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2195. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2196. if (empty($final_segment_content)) {
  2197. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2198. }
  2199. try {
  2200. $dubTaskId = 0;
  2201. DB::beginTransaction();
  2202. $new_segment_number = $segment_number + 1;
  2203. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2204. // 分镜剧本数组
  2205. $insert_data = [
  2206. 'anime_id' => $anime_id,
  2207. 'episode_id' => $episode_id,
  2208. 'episode_number' => $episode_number,
  2209. 'act_number' => getProp($segment, 'act_number'),
  2210. 'act_title' => getProp($segment, 'act_title'),
  2211. 'segment_id' => $segment_id,
  2212. 'segment_number' => $new_segment_number,
  2213. 'segment_content' => $final_segment_content,
  2214. 'img_url' => $img_url,
  2215. 'video_url' => $video_url,
  2216. 'created_at' => date('Y-m-d H:i:s'),
  2217. 'updated_at' => date('Y-m-d H:i:s')
  2218. ];
  2219. // 更新分镜剧本信息
  2220. $this->handleSegmentContent($insert_data);
  2221. // 如果有对话内容,创建视频配音合成任务
  2222. $dialogue = getProp($insert_data, 'dialogue');
  2223. if (!empty($dialogue)) {
  2224. $now = date('Y-m-d H:i:s');
  2225. $generate_json = [
  2226. 'text' => $dialogue,
  2227. 'role' => getProp($insert_data, 'voice_actor'),
  2228. 'voice_type' => getProp($insert_data, 'voice_type'),
  2229. 'voice_name' => getProp($insert_data, 'voice_name'),
  2230. 'emotion' => getProp($insert_data, 'emotion'),
  2231. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2232. 'gender' => getProp($insert_data, 'gender'),
  2233. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2234. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2235. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2236. 'pitch' => getProp($insert_data, 'pitch', 0),
  2237. ];
  2238. // 插入视频配音合成任务
  2239. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2240. 'alias_segment_id' => $segment_id,
  2241. 'generate_status' => '执行中',
  2242. 'audio_url' => '',
  2243. 'generate_json' => json_encode($generate_json, 256),
  2244. 'created_at' => $now,
  2245. 'updated_at' => $now,
  2246. ]);
  2247. if (!$dubTaskId) {
  2248. Utils::throwError('20003:创建配音任务失败!');
  2249. }
  2250. $insert_data['audio_url'] = '';
  2251. } else {
  2252. // dialogue为空时,直接写入默认音频信息
  2253. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2254. $insert_data['audio_duration'] = 2.0;
  2255. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2256. }
  2257. // 如果没有上传图片则使用当前描述进行生成
  2258. if (!$img_url) {
  2259. // 解析分镜内容,提取画面描述作为主要提示词
  2260. $prompt = $final_segment_content;
  2261. $ref_img_urls = [];
  2262. // 分镜场景
  2263. $scene = getProp($insert_data, 'scene');
  2264. if ($scene) {
  2265. $matched_scene = '';
  2266. if (isset($scene_map[$scene])) {
  2267. $img_index = count($ref_img_urls) + 1;
  2268. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2269. $ref_img_urls[] = $scene_map[$scene];
  2270. $matched_scene = $scene;
  2271. }
  2272. $update_data['scene'] = $scene;
  2273. }
  2274. // 分镜角色
  2275. $characters = getProp($insert_data, 'characters');
  2276. if ($characters) {
  2277. $update_data['characters'] = $characters;
  2278. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2279. $characters = explode(',', $characters);
  2280. // 从分镜内容中提取涉及的角色
  2281. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2282. // 获取匹配角色的参考图
  2283. foreach ($segment_characters as $character) {
  2284. if (isset($role_map[$character])) {
  2285. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2286. $img_index = count($ref_img_urls) + 1;
  2287. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2288. $ref_img_urls[] = $role_map[$character];
  2289. }
  2290. }
  2291. }
  2292. // 如果没有找到匹配的角色参考图,不使用参考图
  2293. if (empty($ref_img_urls)) {
  2294. $ref_img_urls = [];
  2295. }
  2296. // 准备生成任务参数
  2297. $params = [
  2298. 'alias_segment_id' => $segment_id,
  2299. 'prompt' => $prompt,
  2300. 'ref_img_urls' => $ref_img_urls,
  2301. 'width' => $width,
  2302. 'height' => $height,
  2303. ];
  2304. // 调用AI图片生成服务
  2305. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2306. $task_id = $task->id;
  2307. // $task_id = 'whatever';
  2308. if (!$task_id) {
  2309. Utils::throwError('20003:创建生成任务失败!');
  2310. }
  2311. $insert_data['pic_task_status'] = '生成中';
  2312. $insert_data['pic_task_id'] = $task_id;
  2313. }
  2314. // 先更新序号
  2315. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2316. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2317. if (!$boolen) {
  2318. Utils::throwError('20003:新增分镜失败!');
  2319. }
  2320. // 如果是第一集的首帧图片,则存入待更新数组
  2321. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2322. Redis::sadd('anime_first_frame_urls', $segment_id);
  2323. }
  2324. if ($dubTaskId) {
  2325. // 请求远程服务器执行生成
  2326. $client = new Client(['timeout' => 300, 'verify' => false]);
  2327. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2328. $response = $result->getBody()->getContents();
  2329. $response_arr = json_decode($response, true);
  2330. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2331. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2332. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2333. Utils::throwError('20003:火山生成音频失败');
  2334. }
  2335. }
  2336. } catch (\Exception $e) {
  2337. DB::rollBack();
  2338. Utils::throwError('20003:'.$e->getMessage());
  2339. }
  2340. DB::commit();
  2341. // 创建任务之后先暂停10s等待异步任务完成
  2342. sleep(10);
  2343. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2344. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2345. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2346. $segment = $segment ? (array)$segment : [];
  2347. return $segment;
  2348. }
  2349. public function copySegment($data) {
  2350. $segment_id = getProp($data, 'segment_id');
  2351. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2352. if (!$segment) Utils::throwError('20003:请选择分镜');
  2353. $anime_id = getProp($segment, 'anime_id');
  2354. $episode_id = getProp($segment, 'episode_id');
  2355. $episode_number = getProp($segment, 'episode_number');
  2356. $segment_number = getProp($segment, 'segment_number');
  2357. $new_segment_id = 0;
  2358. try {
  2359. DB::beginTransaction();
  2360. $segment = (array)$segment;
  2361. unset($segment['id']);
  2362. $segment['segment_number'] += 1;
  2363. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2364. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2365. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2366. // 更新其他分镜序号
  2367. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2368. // 复制分镜
  2369. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2370. if (!$id) {
  2371. Utils::throwError('20003:复制分镜失败');
  2372. }
  2373. }catch (\Exception $e) {
  2374. DB::rollBack();
  2375. Utils::throwError('20003:'.$e->getMessage());
  2376. }
  2377. DB::commit();
  2378. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2379. $segment = $segment ? (array)$segment : [];
  2380. return $segment;
  2381. }
  2382. public function moveSegment($data) {
  2383. $segment_id = getProp($data, 'segment_id');
  2384. $target_segment_id = getProp($data, 'target_segment_id');
  2385. // 获取源分镜信息
  2386. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2387. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2388. // 获取目标分镜信息
  2389. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2390. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2391. $anime_id = getProp($source_segment, 'anime_id');
  2392. $episode_id = getProp($source_segment, 'episode_id');
  2393. $episode_number = getProp($source_segment, 'episode_number');
  2394. $source_segment_number = getProp($source_segment, 'segment_number');
  2395. $target_segment_number = getProp($target_segment, 'segment_number');
  2396. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2397. $target_anime_id = getProp($target_segment, 'anime_id');
  2398. $target_episode_number = getProp($target_segment, 'episode_number');
  2399. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2400. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2401. }
  2402. // 如果源分镜和目标分镜相同,无需移动
  2403. if ($source_segment_number == $target_segment_number) {
  2404. return true;
  2405. }
  2406. try {
  2407. DB::beginTransaction();
  2408. if ($source_segment_number < $target_segment_number) {
  2409. // 向后移动:源分镜移动到目标分镜之后
  2410. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2411. DB::table('mp_episode_segments')
  2412. ->where('anime_id', $anime_id)
  2413. ->where('episode_id', $episode_id)
  2414. ->where('segment_number', '>', $source_segment_number)
  2415. ->where('segment_number', '<=', $target_segment_number)
  2416. ->decrement('segment_number');
  2417. // 2. 将源分镜移动到目标分镜之后
  2418. $new_segment_number = $target_segment_number;
  2419. } else {
  2420. // 向前移动:源分镜移动到目标分镜之后
  2421. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2422. DB::table('mp_episode_segments')
  2423. ->where('anime_id', $anime_id)
  2424. ->where('episode_id', $episode_id)
  2425. ->where('segment_number', '>', $target_segment_number)
  2426. ->where('segment_number', '<', $source_segment_number)
  2427. ->increment('segment_number');
  2428. // 2. 将源分镜移动到目标分镜之后
  2429. $new_segment_number = $target_segment_number + 1;
  2430. }
  2431. // 3. 更新源分镜的序号
  2432. $update_result = DB::table('mp_episode_segments')
  2433. ->where('segment_id', $segment_id)
  2434. ->update([
  2435. 'segment_number' => $new_segment_number,
  2436. 'updated_at' => date('Y-m-d H:i:s')
  2437. ]);
  2438. if (!$update_result) {
  2439. Utils::throwError('20003:更新分镜序号失败');
  2440. }
  2441. DB::commit();
  2442. return true;
  2443. } catch (\Exception $e) {
  2444. DB::rollBack();
  2445. Utils::throwError('20003:' . $e->getMessage());
  2446. }
  2447. }
  2448. public function delSegment($data) {
  2449. $segment_id = getProp($data, 'segment_id');
  2450. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2451. if (!$segment) Utils::throwError('20003:请选择分镜');
  2452. $anime_id = getProp($segment, 'anime_id');
  2453. $episode_id = getProp($segment, 'episode_id');
  2454. $episode_number = getProp($segment, 'episode_number');
  2455. $segment_number = getProp($segment, 'segment_number');
  2456. try {
  2457. DB::beginTransaction();
  2458. // 删除分镜
  2459. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2460. if (!$boolen) {
  2461. Utils::throwError('20003:删除分镜失败');
  2462. }
  2463. // 更新其他分镜序号
  2464. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2465. }catch (\Exception $e) {
  2466. DB::rollBack();
  2467. Utils::throwError('20003:'.$e->getMessage());
  2468. }
  2469. DB::commit();
  2470. return true;
  2471. }
  2472. public function applySegment($data) {
  2473. $segment_id = getProp($data, 'segment_id');
  2474. $url = getProp($data, 'url');
  2475. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2476. if (!$url) Utils::throwError('20003:URL不能为空');
  2477. // 获取URL的文件扩展名
  2478. $urlPath = parse_url($url, PHP_URL_PATH);
  2479. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2480. // 定义图片和视频的扩展名
  2481. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2482. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2483. // 判断是图片还是视频
  2484. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2485. if (in_array($extension, $imageExtensions)) {
  2486. // 图片类型
  2487. $updateData['img_url'] = $url;
  2488. $updateData['current_type'] = 1;
  2489. } elseif (in_array($extension, $videoExtensions)) {
  2490. // 视频类型
  2491. $updateData['video_url'] = $url;
  2492. $updateData['current_type'] = 2;
  2493. } else {
  2494. Utils::throwError('20003:不支持的文件类型');
  2495. }
  2496. // 更新分镜表
  2497. $result = DB::table('mp_episode_segments')
  2498. ->where('segment_id', $segment_id)
  2499. ->update($updateData);
  2500. if (!$result) {
  2501. Utils::throwError('20003:更新分镜失败');
  2502. }
  2503. return true;
  2504. }
  2505. public function segmentHistory($data) {
  2506. $segment_id = getProp($data, 'segment_id');
  2507. // 获取历史图片
  2508. $pics = [];
  2509. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2510. foreach($pic_history as $task) {
  2511. $result_url = getProp($task, 'result_url');
  2512. if (is_json($result_url)) {
  2513. $pics = array_merge($pics, json_decode($result_url, true));
  2514. }else {
  2515. $pics[] = $result_url;
  2516. }
  2517. }
  2518. // 获取历史视频
  2519. $videos = [];
  2520. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2521. foreach($video_history as $task) {
  2522. $result_url = getProp($task, 'result_url');
  2523. if (is_json($result_url)) {
  2524. $videos = array_merge($videos, json_decode($result_url, true));
  2525. }else {
  2526. $videos[] = $result_url;
  2527. }
  2528. }
  2529. return compact('pics', 'videos');
  2530. }
  2531. public function addAct($data) {
  2532. $prev_act_id = getProp($data, 'prev_act_id');
  2533. $act_title = getProp($data, 'act_title', '');
  2534. $act_content = getProp($data, 'act_content', '');
  2535. $act_duration = getProp($data, 'act_duration', 5);
  2536. $video_url = getProp($data, 'video_url');
  2537. // 根据prev_act_id获取记录
  2538. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2539. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2540. $anime_id = getProp($prev_segment, 'anime_id');
  2541. $episode_id = getProp($prev_segment, 'episode_id');
  2542. $episode_number = getProp($prev_segment, 'episode_number');
  2543. $prev_act_number = getProp($prev_segment, 'act_number');
  2544. // 获取新的act_number
  2545. $new_act_number = $prev_act_number + 1;
  2546. try {
  2547. DB::beginTransaction();
  2548. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2549. DB::table('mp_episode_segments')
  2550. ->where('anime_id', $anime_id)
  2551. ->where('episode_id', $episode_id)
  2552. ->where('act_number', '>', $prev_act_number)
  2553. ->increment('act_number');
  2554. // 插入新片段记录
  2555. $insert_data = [
  2556. 'anime_id' => $anime_id,
  2557. 'episode_id' => $episode_id,
  2558. 'episode_number' => $episode_number,
  2559. 'act_number' => $new_act_number,
  2560. 'created_at' => date('Y-m-d H:i:s'),
  2561. 'updated_at' => date('Y-m-d H:i:s')
  2562. ];
  2563. if ($act_title) {
  2564. $insert_data['act_title'] = $act_title;
  2565. }
  2566. if ($act_content) {
  2567. $insert_data['act_content'] = $act_content;
  2568. }
  2569. if ($act_duration) {
  2570. $insert_data['act_duration'] = $act_duration;
  2571. }
  2572. if ($video_url) {
  2573. $insert_data['origin_video_url'] = $video_url;
  2574. $insert_data['current_type'] = 2;
  2575. $compressed_video_url = compressVideo($video_url);
  2576. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2577. }
  2578. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2579. if (!$id) {
  2580. Utils::throwError('20003:新增片段失败!');
  2581. }
  2582. DB::commit();
  2583. }catch (\Exception $e) {
  2584. DB::rollBack();
  2585. Utils::throwError('20003:'.$e->getMessage());
  2586. }
  2587. $segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2588. $segment = $segment ? (array)$segment : [];
  2589. return $segment;
  2590. }
  2591. public function editAct($data) {
  2592. $act_id = getProp($data, 'act_id');
  2593. $act_content = getProp($data, 'act_content');
  2594. $act_duration = getProp($data, 'act_duration');
  2595. $act_title = getProp($data, 'act_title');
  2596. $image_url = getProp($data, 'image_url');
  2597. $video_url = getProp($data, 'video_url');
  2598. // 参数验证
  2599. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2600. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2601. $segment = DB::table('mp_episode_segments')
  2602. ->where('id', $act_id)
  2603. ->first();
  2604. if (!$segment) Utils::throwError('20003:该片段不存在');
  2605. try {
  2606. DB::beginTransaction();
  2607. // 准备更新数据
  2608. $update_data = [
  2609. 'updated_at' => date('Y-m-d H:i:s')
  2610. ];
  2611. // 更新act相关字段
  2612. if (!empty($act_content)) {
  2613. $update_data['act_show_content'] = $act_content;
  2614. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2615. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2616. $shot_counter = 0;
  2617. $update_data['act_show_content'] = preg_replace_callback(
  2618. '/【(?:镜头|分镜)(\d+)】/u',
  2619. function($matches) use (&$shot_counter) {
  2620. $shot_counter++;
  2621. return '【镜头' . $shot_counter . '】';
  2622. },
  2623. $update_data['act_show_content']
  2624. );
  2625. }
  2626. if (!empty($act_duration)) {
  2627. $update_data['act_duration'] = $act_duration;
  2628. }
  2629. if (!empty($act_title)) {
  2630. $update_data['act_title'] = $act_title;
  2631. }
  2632. // 处理图片上传
  2633. if ($image_url) {
  2634. $update_data['img_url'] = $image_url;
  2635. $update_data['current_type'] = 1;
  2636. // 同时写入一个图片生成任务记录
  2637. if ($act_id) {
  2638. $pic_task = [
  2639. 'alias_act_id' => $act_id,
  2640. 'ref_img_url' => json_encode([]),
  2641. 'status' => 'success',
  2642. 'result_url' => json_encode([$image_url], 256),
  2643. 'model' => '',
  2644. 'created_at' => date('Y-m-d H:i:s'),
  2645. 'updated_at' => date('Y-m-d H:i:s'),
  2646. ];
  2647. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2648. }
  2649. }
  2650. // 处理视频上传
  2651. if ($video_url) {
  2652. $update_data['origin_video_url'] = $video_url;
  2653. $compressed_video_url = compressVideo($video_url);
  2654. $update_data['current_type'] = 2;
  2655. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2656. // 同时写入一个视频生成任务记录
  2657. if ($act_id) {
  2658. $video_task = [
  2659. 'alias_act_id' => $act_id,
  2660. 'status' => 'success',
  2661. 'result_url' => $update_data['origin_video_url'],
  2662. 'compressed_url' => $update_data['video_url'],
  2663. 'created_at' => date('Y-m-d H:i:s'),
  2664. 'updated_at' => date('Y-m-d H:i:s'),
  2665. ];
  2666. DB::table('mp_generate_video_tasks')->insert($video_task);
  2667. }
  2668. }
  2669. // 更新片段信息
  2670. $result = DB::table('mp_episode_segments')
  2671. ->where('id', $act_id)
  2672. ->update($update_data);
  2673. if ($result === false) {
  2674. Utils::throwError('20003:更新片段失败');
  2675. }
  2676. DB::commit();
  2677. // 返回新复制的记录
  2678. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
  2679. $new_segment = (array)$new_segment;
  2680. return $new_segment;
  2681. } catch (\Exception $e) {
  2682. DB::rollBack();
  2683. dLog('anime')->error('更新片段失败', [
  2684. 'act_id' => $act_id,
  2685. 'error' => $e->getMessage()
  2686. ]);
  2687. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2688. }
  2689. }
  2690. public function copyAct($data) {
  2691. $act_id = getProp($data, 'act_id');
  2692. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2693. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2694. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2695. $anime_id = getProp($source_segment, 'anime_id');
  2696. $episode_id = getProp($source_segment, 'episode_id');
  2697. $episode_number = getProp($source_segment, 'episode_number');
  2698. $act_number = getProp($source_segment, 'act_number');
  2699. try {
  2700. DB::beginTransaction();
  2701. // 新act的编号
  2702. $new_act_number = $act_number + 1;
  2703. // 更新后续所有act的act_number
  2704. DB::table('mp_episode_segments')
  2705. ->where('anime_id', $anime_id)
  2706. ->where('episode_id', $episode_id)
  2707. ->where('act_number', '>', $act_number)
  2708. ->increment('act_number');
  2709. // 复制该片段记录
  2710. $segment_data = (array)$source_segment;
  2711. unset($segment_data['id']);
  2712. $segment_data['video_url'] = '';
  2713. $segment_data['video_task_id'] = '';
  2714. $segment_data['video_task_status'] = '';
  2715. $segment_data['act_number'] = $new_act_number;
  2716. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2717. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2718. if (!$id) {
  2719. Utils::throwError('20003:复制片段失败');
  2720. }
  2721. DB::commit();
  2722. }catch (\Exception $e) {
  2723. DB::rollBack();
  2724. Utils::throwError('20003:'.$e->getMessage());
  2725. }
  2726. // 返回新复制的记录
  2727. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2728. $new_segment = $new_segment ? (array)$new_segment : [];
  2729. $new_segment['act_id'] = $id;
  2730. return $new_segment;
  2731. }
  2732. public function moveAct($data) {
  2733. $act_id = getProp($data, 'act_id');
  2734. $target_act_id = getProp($data, 'target_act_id');
  2735. // 获取源片段信息
  2736. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2737. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2738. // 获取目标片段信息
  2739. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2740. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2741. $anime_id = getProp($source_segment, 'anime_id');
  2742. $episode_id = getProp($source_segment, 'episode_id');
  2743. $source_act_number = getProp($source_segment, 'act_number');
  2744. $target_act_number = getProp($target_segment, 'act_number');
  2745. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2746. $target_anime_id = getProp($target_segment, 'anime_id');
  2747. $target_episode_id = getProp($target_segment, 'episode_id');
  2748. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2749. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2750. }
  2751. // 如果源片段和目标片段相同,无需移动
  2752. if ($source_act_number == $target_act_number) {
  2753. return true;
  2754. }
  2755. try {
  2756. DB::beginTransaction();
  2757. if ($source_act_number < $target_act_number) {
  2758. // 向后移动:源片段移动到目标片段之后
  2759. // 1. 将源片段和目标片段之间的所有片段编号减1
  2760. DB::table('mp_episode_segments')
  2761. ->where('anime_id', $anime_id)
  2762. ->where('episode_id', $episode_id)
  2763. ->where('act_number', '>', $source_act_number)
  2764. ->where('act_number', '<=', $target_act_number)
  2765. ->decrement('act_number');
  2766. // 2. 将源片段移动到目标片段之后
  2767. $new_act_number = $target_act_number;
  2768. } else {
  2769. // 向前移动:源片段移动到目标片段之后
  2770. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2771. DB::table('mp_episode_segments')
  2772. ->where('anime_id', $anime_id)
  2773. ->where('episode_id', $episode_id)
  2774. ->where('act_number', '>', $target_act_number)
  2775. ->where('act_number', '<', $source_act_number)
  2776. ->increment('act_number');
  2777. // 2. 将源片段移动到目标片段之后
  2778. $new_act_number = $target_act_number + 1;
  2779. }
  2780. // 3. 更新源片段的编号
  2781. $update_result = DB::table('mp_episode_segments')
  2782. ->where('id', $act_id)
  2783. ->update([
  2784. 'act_number' => $new_act_number,
  2785. 'updated_at' => date('Y-m-d H:i:s')
  2786. ]);
  2787. if (!$update_result) {
  2788. Utils::throwError('20003:更新片段编号失败');
  2789. }
  2790. DB::commit();
  2791. return true;
  2792. } catch (\Exception $e) {
  2793. DB::rollBack();
  2794. Utils::throwError('20003:' . $e->getMessage());
  2795. }
  2796. }
  2797. public function delAct($data) {
  2798. $act_id = getProp($data, 'act_id');
  2799. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2800. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2801. if (!$segment) Utils::throwError('20003:请选择片段');
  2802. $anime_id = getProp($segment, 'anime_id');
  2803. $episode_id = getProp($segment, 'episode_id');
  2804. $act_number = getProp($segment, 'act_number');
  2805. try {
  2806. DB::beginTransaction();
  2807. // 删除该片段记录
  2808. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2809. if (!$deleted) {
  2810. Utils::throwError('20003:删除片段失败');
  2811. }
  2812. // 更新后续act的编号
  2813. DB::table('mp_episode_segments')
  2814. ->where('anime_id', $anime_id)
  2815. ->where('episode_id', $episode_id)
  2816. ->where('act_number', '>', $act_number)
  2817. ->decrement('act_number');
  2818. DB::commit();
  2819. }catch (\Exception $e) {
  2820. DB::rollBack();
  2821. Utils::throwError('20003:'.$e->getMessage());
  2822. }
  2823. return true;
  2824. }
  2825. public function applyAct($data) {
  2826. $act_id = getProp($data, 'act_id');
  2827. $url = getProp($data, 'url');
  2828. if (!$act_id) Utils::throwError('20003:请选择片段');
  2829. if (!$url) Utils::throwError('20003:URL不能为空');
  2830. // 获取URL的文件扩展名
  2831. $urlPath = parse_url($url, PHP_URL_PATH);
  2832. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2833. // 定义图片和视频的扩展名
  2834. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2835. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2836. // 判断是图片还是视频
  2837. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2838. if (in_array($extension, $imageExtensions)) {
  2839. // 图片类型
  2840. $updateData['img_url'] = $url;
  2841. $updateData['current_type'] = 1;
  2842. } elseif (in_array($extension, $videoExtensions)) {
  2843. // 视频类型
  2844. $updateData['video_url'] = $url;
  2845. $updateData['current_type'] = 2;
  2846. } else {
  2847. Utils::throwError('20003:不支持的文件类型');
  2848. }
  2849. // 更新片段记录(全能模式下每个act只有一条记录)
  2850. $result = DB::table('mp_episode_segments')
  2851. ->where('id', $act_id)
  2852. ->update($updateData);
  2853. if (!$result) {
  2854. Utils::throwError('20003:更新片段失败');
  2855. }
  2856. return true;
  2857. }
  2858. public function actChatHistory($data) {
  2859. $act_id = getProp($data, 'act_id');
  2860. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2861. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'reference_images', 'created_at');
  2862. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2863. $value = (array)$value;
  2864. $value['created_at'] = transDate($value['created_at']);
  2865. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2866. else $value['reference_images'] = [];
  2867. return $value;
  2868. })->toArray();
  2869. // 获取历史图片
  2870. $url = [];
  2871. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2872. foreach($pic_history as $task) {
  2873. $result_url = getProp($task, 'result_url');
  2874. if (is_json($result_url)) {
  2875. $url = array_merge($url, json_decode($result_url, true));
  2876. }else {
  2877. $url[] = $result_url;
  2878. }
  2879. }
  2880. // 获取历史视频
  2881. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2882. foreach($video_history as $task) {
  2883. $result_url = getProp($task, 'result_url');
  2884. if (is_json($result_url)) {
  2885. $url = array_merge($url, json_decode($result_url, true));
  2886. }else {
  2887. $url[] = $result_url;
  2888. }
  2889. }
  2890. // 获取资产库
  2891. $products = [];
  2892. // 通过act_id查询片段信息获取episode_id
  2893. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2894. if ($segment) {
  2895. $episode_id = getProp($segment, 'episode_id');
  2896. // 查询剧集信息获取roles、scenes和extra_products
  2897. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2898. if ($episode) {
  2899. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2900. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2901. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2902. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2903. // 先合并roles、scenes和props
  2904. // 处理角色数组
  2905. foreach ($roles as $role) {
  2906. $product = $role;
  2907. // 将role字段重命名为product_name
  2908. if (is_array($product) && !empty($product['role'] ?? null)) {
  2909. $product['product_name'] = $product['role'];
  2910. unset($product['role']);
  2911. $product['product'] = 1; // 标记类型为角色
  2912. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2913. }
  2914. }
  2915. // 处理场景数组
  2916. foreach ($scenes as $scene) {
  2917. $product = $scene;
  2918. // 将scene字段重命名为product_name
  2919. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2920. $product['product_name'] = $product['scene'];
  2921. unset($product['scene']);
  2922. $product['product'] = 2; // 标记类型为场景
  2923. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2924. }
  2925. }
  2926. // 处理道具数组
  2927. foreach ($props as $prop) {
  2928. $product = $prop;
  2929. // 将prop字段重命名为product_name
  2930. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2931. $product['product_name'] = $product['prop'];
  2932. unset($product['prop']);
  2933. $product['product'] = 3; // 标记类型为道具
  2934. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2935. }
  2936. }
  2937. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2938. foreach ($extra_products as $extra_product) {
  2939. $product_name = getProp($extra_product, 'product_name');
  2940. if ($product_name) {
  2941. $products[$product_name] = $extra_product; // 覆盖同名数据
  2942. }
  2943. }
  2944. // 重新索引数组(去除key)
  2945. $products = array_values($products);
  2946. }
  2947. }
  2948. // 获取执行中的任务
  2949. $tasks = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->whereNotIn('status', ['success', 'failed'])->select('id as task_id', 'alias_act_id', 'prompt', 'ref_image_url', 'status')->orderBy('id')->get()->map(function($value) {
  2950. $value = (array)$value;
  2951. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2952. else $value['ref_image_url'] = [];
  2953. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2954. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2955. if (!empty($value['prompt'])) {
  2956. $prompt = $value['prompt'];
  2957. // 查找第一个【镜头】的位置
  2958. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2959. // 从【镜头】开始截取
  2960. $prompt = substr($prompt, $matches[0][1]);
  2961. }
  2962. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2963. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2964. $value['prompt'] = $prompt;
  2965. }
  2966. return $value;
  2967. })->toArray();
  2968. return compact('chat', 'url', 'products', 'tasks');
  2969. }
  2970. public function applyAudioData($data) {
  2971. $segment_id = getProp($data, 'segment_id');
  2972. $global_data = getProp($data, 'global_data');
  2973. $segment_data = getProp($data, 'segment_data');
  2974. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2975. $global_data = is_array($global_data) ? $global_data : [];
  2976. $segment_data = is_array($segment_data) ? $segment_data : [];
  2977. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2978. $dialogue_item = null;
  2979. foreach ($global_data as $key => $item) {
  2980. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2981. $dialogue_item = $item;
  2982. unset($global_data[$key]);
  2983. break;
  2984. }
  2985. }
  2986. if ($dialogue_item) {
  2987. $segment_data[] = $dialogue_item;
  2988. }
  2989. // 特殊参数: audio_url,audio_duration,subtitle_info
  2990. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2991. // 如果不是全部存在,则仍需创建音频任务
  2992. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2993. $special_update_data = [];
  2994. $has_all_special_params = false;
  2995. // 从segment_data中提取特殊参数
  2996. $filtered_segment_data = [];
  2997. foreach ($segment_data as $item) {
  2998. $field_name = trim((string)getProp($item, 'name'));
  2999. if (in_array($field_name, $special_fields)) {
  3000. $special_update_data[$field_name] = getProp($item, 'value');
  3001. } else {
  3002. // 非特殊参数保留,继续后续处理
  3003. $filtered_segment_data[] = $item;
  3004. }
  3005. }
  3006. // 检查是否三个特殊参数都存在
  3007. if (count($special_update_data) === 3 &&
  3008. isset($special_update_data['audio_url']) &&
  3009. isset($special_update_data['audio_duration']) &&
  3010. isset($special_update_data['subtitle_info'])) {
  3011. $has_all_special_params = true;
  3012. // 立即更新到当前分镜
  3013. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3014. DB::table('mp_episode_segments')
  3015. ->where('segment_id', $segment_id)
  3016. ->update($special_update_data);
  3017. }
  3018. // 使用过滤后的segment_data继续处理其他参数
  3019. $segment_data = $filtered_segment_data;
  3020. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3021. $global_update_data = [];
  3022. $segment_update_data = [];
  3023. $global_voice_type = '';
  3024. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3025. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3026. $episode_id = getProp($target_segment, 'episode_id');
  3027. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3028. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3029. if (!$episode) Utils::throwError('20003:分集不存在');
  3030. foreach ($global_data as $item) {
  3031. $field_name = trim((string)getProp($item, 'name'));
  3032. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3033. continue;
  3034. }
  3035. $global_update_data[$field_name] = getProp($item, 'value');
  3036. if ($field_name === 'voice_type') {
  3037. $global_voice_type = trim((string)getProp($item, 'value'));
  3038. }
  3039. }
  3040. foreach ($segment_data as $item) {
  3041. $field_name = trim((string)getProp($item, 'name'));
  3042. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3043. continue;
  3044. }
  3045. $segment_update_data[$field_name] = getProp($item, 'value');
  3046. }
  3047. if ($global_voice_type) {
  3048. $timbre_info = DB::table('mp_timbres')
  3049. ->where('timbre_type', $global_voice_type)
  3050. ->select('audio_url', 'timbre_name')
  3051. ->first();
  3052. if ($timbre_info) {
  3053. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3054. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3055. }
  3056. }
  3057. try {
  3058. DB::beginTransaction();
  3059. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3060. $segment_ids_to_create_task = [];
  3061. $segments_data = [];
  3062. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3063. if (!empty($global_update_data)) {
  3064. // 如果角色不存在,则只更新当前分镜
  3065. if (!$target_voice_actor) {
  3066. // 只处理当前分镜
  3067. $affected_segments = DB::table('mp_episode_segments')
  3068. ->where('segment_id', $segment_id)
  3069. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3070. ->get();
  3071. } else {
  3072. // 获取该角色的所有分镜
  3073. $affected_segments = DB::table('mp_episode_segments')
  3074. ->where('episode_id', $episode_id)
  3075. ->where('voice_actor', $target_voice_actor)
  3076. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3077. ->get();
  3078. }
  3079. foreach ($affected_segments as $seg) {
  3080. $seg = (array)$seg;
  3081. $sid = getProp($seg, 'segment_id');
  3082. // 检查参数是否发生变化
  3083. $has_changed = false;
  3084. foreach ($global_update_data as $field => $new_value) {
  3085. $old_value = getProp($seg, $field);
  3086. if ($old_value != $new_value) {
  3087. $has_changed = true;
  3088. break;
  3089. }
  3090. }
  3091. if ($has_changed) {
  3092. $segment_ids_to_create_task[] = $sid;
  3093. $segments_data[$sid] = $seg;
  3094. }
  3095. }
  3096. // 只有在有变化的分镜时才更新
  3097. if (!empty($segment_ids_to_create_task)) {
  3098. $global_segment_update_data = $global_update_data;
  3099. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3100. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3101. DB::table('mp_episode_segments')
  3102. ->where('episode_id', $episode_id)
  3103. ->where('voice_actor', $target_voice_actor)
  3104. ->whereIn('segment_id', $segment_ids_to_create_task)
  3105. ->update($global_segment_update_data);
  3106. }
  3107. if ($global_voice_type) {
  3108. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3109. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3110. $roles_updated = false;
  3111. foreach ($episode_roles as &$role) {
  3112. // 通过 role 字段匹配角色名,而不是 voice_name
  3113. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3114. continue;
  3115. }
  3116. $role['voice_type'] = $global_voice_type;
  3117. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3118. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3119. $roles_updated = true;
  3120. }
  3121. unset($role);
  3122. if ($roles_updated) {
  3123. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3124. 'roles' => json_encode($episode_roles, 256),
  3125. 'updated_at' => date('Y-m-d H:i:s'),
  3126. ]);
  3127. }
  3128. }
  3129. }
  3130. // 如果有单个分镜更新,检查是否有变化
  3131. if (!empty($segment_update_data)) {
  3132. // 获取当前分镜数据
  3133. $current_segment = DB::table('mp_episode_segments')
  3134. ->where('segment_id', $segment_id)
  3135. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3136. ->first();
  3137. if ($current_segment) {
  3138. $current_segment = (array)$current_segment;
  3139. // 检查参数是否发生变化
  3140. $has_changed = false;
  3141. foreach ($segment_update_data as $field => $new_value) {
  3142. $old_value = getProp($current_segment, $field);
  3143. if ($old_value != $new_value) {
  3144. $has_changed = true;
  3145. break;
  3146. }
  3147. }
  3148. if ($has_changed) {
  3149. // 如果该分镜还未在列表中,添加进去
  3150. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3151. $segment_ids_to_create_task[] = $segment_id;
  3152. $segments_data[$segment_id] = $current_segment;
  3153. }
  3154. // 更新分镜数据并清空音频URL
  3155. $segment_update_data['audio_url'] = '';
  3156. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3157. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3158. }
  3159. }
  3160. }
  3161. // 为所有有变化的分镜创建音频合成任务
  3162. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3163. if (!empty($segment_ids_to_create_task)) {
  3164. foreach ($segment_ids_to_create_task as $sid) {
  3165. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3166. if ($sid === $segment_id && $has_all_special_params) {
  3167. continue;
  3168. }
  3169. // 重新获取更新后的分镜数据
  3170. $updated_segment = DB::table('mp_episode_segments')
  3171. ->where('segment_id', $sid)
  3172. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3173. ->first();
  3174. if (!$updated_segment) continue;
  3175. $updated_segment = (array)$updated_segment;
  3176. // 检查dialogue是否为空
  3177. $dialogue = getProp($updated_segment, 'dialogue');
  3178. if (empty($dialogue)) {
  3179. // dialogue为空时,直接写入默认音频信息
  3180. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3181. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3182. 'audio_duration' => 2.0,
  3183. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3184. 'updated_at' => date('Y-m-d H:i:s')
  3185. ]);
  3186. continue;
  3187. }
  3188. $generate_json = [
  3189. 'text' => $dialogue,
  3190. 'role' => getProp($updated_segment, 'voice_actor'),
  3191. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3192. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3193. 'emotion' => getProp($updated_segment, 'emotion'),
  3194. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3195. 'gender' => getProp($updated_segment, 'gender'),
  3196. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3197. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3198. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3199. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3200. ];
  3201. // 插入视频配音合成任务
  3202. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3203. 'alias_segment_id' => $sid,
  3204. 'generate_status' => '执行中',
  3205. 'audio_url' => '',
  3206. 'generate_json' => json_encode($generate_json, 256),
  3207. 'created_at' => date('Y-m-d H:i:s'),
  3208. 'updated_at' => date('Y-m-d H:i:s'),
  3209. ]);
  3210. if (!$dubTaskId) {
  3211. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3212. continue;
  3213. }
  3214. // 将任务ID添加到Redis列表中
  3215. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3216. // 请求远程服务器执行生成
  3217. try {
  3218. sleep(1);
  3219. $client = new Client(['timeout' => 300, 'verify' => false]);
  3220. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3221. $response = $result->getBody()->getContents();
  3222. $response_arr = json_decode($response, true);
  3223. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3224. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3225. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3226. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3227. }
  3228. } catch (\Exception $e) {
  3229. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3230. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3231. }
  3232. }
  3233. }
  3234. DB::commit();
  3235. } catch (\Exception $e) {
  3236. DB::rollBack();
  3237. Utils::throwError('20003:'.$e->getMessage());
  3238. }
  3239. return true;
  3240. }
  3241. public function episodePicsInfo($data) {
  3242. $anime_id = getProp($data, 'anime_id');
  3243. $episode_id = getProp($data, 'episode_id');
  3244. // 参数验证
  3245. if (!$anime_id && !$episode_id) {
  3246. Utils::throwError('20003:请提供动漫ID或分集ID');
  3247. }
  3248. // 根据参数获取数据源
  3249. if ($episode_id) {
  3250. // 从剧集表获取
  3251. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3252. if (!$source) Utils::throwError('20003:该剧集不存在');
  3253. $table_name = 'mp_anime_episodes';
  3254. $id_field = 'id';
  3255. $id_value = $episode_id;
  3256. // 获取剧集的anime_id用于继承全局数据
  3257. $anime_id = getProp($source, 'anime_id');
  3258. } else {
  3259. // 从动漫表获取
  3260. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3261. if (!$source) Utils::throwError('20003:该动漫不存在');
  3262. $table_name = 'mp_animes';
  3263. $id_field = 'id';
  3264. $id_value = $anime_id;
  3265. }
  3266. $source = (array)$source;
  3267. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3268. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3269. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3270. // 如果是分集数据,需要处理继承和任务创建逻辑
  3271. if ($episode_id) {
  3272. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3273. }
  3274. // 返回生成器函数,用于 SSE 流式输出
  3275. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3276. $startTime = time();
  3277. $maxDuration = 600; // 10分钟超时
  3278. $checkInterval = 3; // 每3秒检查一次
  3279. // Redis 缓存键
  3280. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3281. // 生成当前数据的哈希值用于比较
  3282. $generateHash = function($roles, $scenes, $props) {
  3283. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3284. };
  3285. // 发送初始数据
  3286. $currentHash = $generateHash($roles, $scenes, $props);
  3287. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3288. echo "data: " . json_encode([
  3289. 'type' => 'init',
  3290. 'data' => [
  3291. 'roles' => $roles,
  3292. 'scenes' => $scenes,
  3293. 'props' => $props,
  3294. 'start_time' => $startTime
  3295. ]
  3296. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3297. if (ob_get_level() > 0) {
  3298. ob_flush();
  3299. }
  3300. flush();
  3301. // 持续轮询任务状态
  3302. while (time() - $startTime < $maxDuration) {
  3303. $hasProcessing = false;
  3304. $updated = false;
  3305. // 检查角色任务状态
  3306. foreach ($roles as $index => &$role) {
  3307. $task_id = getProp($role, 'task_id');
  3308. $task_status = getProp($role, 'task_status');
  3309. $existing_url = getProp($role, 'url');
  3310. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3311. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3312. $hasProcessing = ($task_status === 'processing');
  3313. // 查询任务状态
  3314. $task = DB::table('mp_generate_pic_tasks')
  3315. ->where('id', $task_id)
  3316. ->select('id', 'status', 'result_url', 'error_message')
  3317. ->first();
  3318. if ($task) {
  3319. $task = (array)$task;
  3320. $status = getProp($task, 'status');
  3321. // 如果任务完成或失败
  3322. if (in_array($status, ['success', 'failed'])) {
  3323. $role['task_status'] = $status;
  3324. if ($status === 'success') {
  3325. $result_url = getProp($task, 'result_url');
  3326. if ($result_url) {
  3327. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3328. if (is_array($result_urls) && !empty($result_urls[0])) {
  3329. $role['url'] = $result_urls[0];
  3330. }
  3331. }
  3332. }
  3333. $updated = true;
  3334. } else if ($status === 'processing') {
  3335. $hasProcessing = true;
  3336. }
  3337. }
  3338. }
  3339. }
  3340. // 检查场景任务状态
  3341. foreach ($scenes as $index => &$scene) {
  3342. $task_id = getProp($scene, 'task_id');
  3343. $task_status = getProp($scene, 'task_status');
  3344. $existing_url = getProp($scene, 'url');
  3345. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3346. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3347. $hasProcessing = ($task_status === 'processing');
  3348. // 查询任务状态
  3349. $task = DB::table('mp_generate_pic_tasks')
  3350. ->where('id', $task_id)
  3351. ->select('id', 'status', 'result_url', 'error_message')
  3352. ->first();
  3353. if ($task) {
  3354. $task = (array)$task;
  3355. $status = getProp($task, 'status');
  3356. // 如果任务完成或失败
  3357. if (in_array($status, ['success', 'failed'])) {
  3358. $scene['task_status'] = $status;
  3359. if ($status === 'success') {
  3360. $result_url = getProp($task, 'result_url');
  3361. if ($result_url) {
  3362. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3363. if (is_array($result_urls) && !empty($result_urls[0])) {
  3364. $scene['url'] = $result_urls[0];
  3365. }
  3366. }
  3367. }
  3368. $updated = true;
  3369. } else if ($status === 'processing') {
  3370. $hasProcessing = true;
  3371. }
  3372. }
  3373. }
  3374. }
  3375. // 检查道具任务状态
  3376. foreach ($props as $index => &$prop) {
  3377. $task_id = getProp($prop, 'task_id');
  3378. $task_status = getProp($prop, 'task_status');
  3379. $existing_url = getProp($prop, 'url');
  3380. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3381. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3382. $hasProcessing = ($task_status === 'processing');
  3383. // 查询任务状态
  3384. $task = DB::table('mp_generate_pic_tasks')
  3385. ->where('id', $task_id)
  3386. ->select('id', 'status', 'result_url', 'error_message')
  3387. ->first();
  3388. if ($task) {
  3389. $task = (array)$task;
  3390. $status = getProp($task, 'status');
  3391. // 如果任务完成或失败
  3392. if (in_array($status, ['success', 'failed'])) {
  3393. $prop['task_status'] = $status;
  3394. if ($status === 'success') {
  3395. $result_url = getProp($task, 'result_url');
  3396. if ($result_url) {
  3397. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3398. if (is_array($result_urls) && !empty($result_urls[0])) {
  3399. $prop['url'] = $result_urls[0];
  3400. }
  3401. }
  3402. }
  3403. $updated = true;
  3404. } else if ($status === 'processing') {
  3405. $hasProcessing = true;
  3406. }
  3407. }
  3408. }
  3409. }
  3410. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3411. if ($updated) {
  3412. $newHash = $generateHash($roles, $scenes, $props);
  3413. $cachedHash = Redis::get($cacheKey);
  3414. // 只有当数据真正变化时才更新数据库和发送事件
  3415. if ($newHash !== $cachedHash) {
  3416. try {
  3417. // 更新数据库
  3418. DB::table($table_name)->where($id_field, $id_value)->update([
  3419. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3420. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3421. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3422. 'updated_at' => date('Y-m-d H:i:s')
  3423. ]);
  3424. // 更新缓存
  3425. Redis::setex($cacheKey, 600, $newHash);
  3426. // 发送更新事件
  3427. echo "data: " . json_encode([
  3428. 'type' => 'update',
  3429. 'data' => [
  3430. 'roles' => $roles,
  3431. 'scenes' => $scenes,
  3432. 'props' => $props,
  3433. 'elapsed_time' => time() - $startTime
  3434. ]
  3435. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3436. if (ob_get_level() > 0) {
  3437. ob_flush();
  3438. }
  3439. flush();
  3440. } catch (\Exception $e) {
  3441. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3442. }
  3443. } else {
  3444. // 即使哈希相同,如果有URL更新也要发送事件
  3445. $hasUrlUpdate = false;
  3446. foreach ($roles as $role) {
  3447. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3448. $hasUrlUpdate = true;
  3449. break;
  3450. }
  3451. }
  3452. if (!$hasUrlUpdate) {
  3453. foreach ($scenes as $scene) {
  3454. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3455. $hasUrlUpdate = true;
  3456. break;
  3457. }
  3458. }
  3459. }
  3460. if (!$hasUrlUpdate) {
  3461. foreach ($props as $prop) {
  3462. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3463. $hasUrlUpdate = true;
  3464. break;
  3465. }
  3466. }
  3467. }
  3468. if ($hasUrlUpdate) {
  3469. // 强制更新数据库和发送事件
  3470. try {
  3471. DB::table($table_name)->where($id_field, $id_value)->update([
  3472. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3473. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3474. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3475. 'updated_at' => date('Y-m-d H:i:s')
  3476. ]);
  3477. // 更新缓存
  3478. Redis::setex($cacheKey, 600, $newHash);
  3479. // 发送更新事件
  3480. echo "data: " . json_encode([
  3481. 'type' => 'update',
  3482. 'data' => [
  3483. 'roles' => $roles,
  3484. 'scenes' => $scenes,
  3485. 'props' => $props,
  3486. 'elapsed_time' => time() - $startTime
  3487. ]
  3488. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3489. if (ob_get_level() > 0) {
  3490. ob_flush();
  3491. }
  3492. flush();
  3493. } catch (\Exception $e) {
  3494. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3495. }
  3496. }
  3497. }
  3498. }
  3499. // 如果所有任务都已完成,发送完成事件并退出
  3500. if (!$hasProcessing) {
  3501. // 查询数据库中的最终数据,确保返回最新的完整数据
  3502. try {
  3503. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3504. if ($finalSource) {
  3505. $finalSource = (array)$finalSource;
  3506. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3507. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3508. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3509. // 使用数据库中的最终数据
  3510. $roles = $finalRoles;
  3511. $scenes = $finalScenes;
  3512. $props = $finalProps;
  3513. }
  3514. } catch (\Exception $e) {
  3515. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3516. // 如果查询失败,继续使用内存中的数据
  3517. }
  3518. // 清理缓存
  3519. Redis::del($cacheKey);
  3520. echo "data: " . json_encode([
  3521. 'type' => 'completed',
  3522. 'data' => [
  3523. 'roles' => $roles,
  3524. 'scenes' => $scenes,
  3525. 'props' => $props,
  3526. 'total_time' => time() - $startTime
  3527. ]
  3528. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3529. if (ob_get_level() > 0) {
  3530. ob_flush();
  3531. }
  3532. flush();
  3533. break;
  3534. }
  3535. // 等待下次检查
  3536. sleep($checkInterval);
  3537. }
  3538. // 超时处理
  3539. if (time() - $startTime >= $maxDuration) {
  3540. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3541. try {
  3542. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3543. if ($finalSource) {
  3544. $finalSource = (array)$finalSource;
  3545. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3546. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3547. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3548. // 使用数据库中的最终数据
  3549. $roles = $finalRoles;
  3550. $scenes = $finalScenes;
  3551. $props = $finalProps;
  3552. }
  3553. } catch (\Exception $e) {
  3554. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3555. // 如果查询失败,继续使用内存中的数据
  3556. }
  3557. // 清理缓存
  3558. Redis::del($cacheKey);
  3559. echo "data: " . json_encode([
  3560. 'type' => 'timeout',
  3561. 'message' => '轮询超时,请刷新页面查看最新状态',
  3562. 'data' => [
  3563. 'roles' => $roles,
  3564. 'scenes' => $scenes,
  3565. 'props' => $props
  3566. ]
  3567. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3568. if (ob_get_level() > 0) {
  3569. ob_flush();
  3570. }
  3571. flush();
  3572. }
  3573. };
  3574. }
  3575. public function clipSegmentVideo($data) {
  3576. $segment_id = getProp($data, 'segment_id');
  3577. $video_time_point_start = getProp($data, 'video_time_point_start');
  3578. $video_time_point_end = getProp($data, 'video_time_point_end');
  3579. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3580. Utils::throwError('20003:参数异常');
  3581. }
  3582. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3583. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3584. }
  3585. $video_duration = $video_time_point_end - $video_time_point_start;
  3586. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3587. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3588. 'video_duration' => $video_duration,
  3589. 'video_time_point_start' => $video_time_point_start,
  3590. 'video_time_point_end' => $video_time_point_end,
  3591. 'updated_at' => date('Y-m-d H:i:s')
  3592. ]);
  3593. }
  3594. // 轮训获取图片任务结果
  3595. private function loopGetPicTaskResult($task_id) {
  3596. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3597. if (!$task) {
  3598. return '';
  3599. }
  3600. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3601. $model = getProp($task, 'model');
  3602. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3603. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3604. $isSyncModel = $isVolcModel || $isGptModel;
  3605. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3606. $start_count = 0;
  3607. $img_url = '';
  3608. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3609. sleep(3);
  3610. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3611. // 如果任务已经完成,直接返回结果
  3612. if ($task->status === 'success' && $task->result_url) {
  3613. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3614. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3615. }
  3616. // 如果任务已失败,返回空
  3617. if ($task->status === 'failed') {
  3618. return '';
  3619. }
  3620. if ($isSyncModel) continue;
  3621. // 查询任务状态
  3622. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3623. if ($statusInfo['status'] === 'success') {
  3624. $task->updateStatus('success', [
  3625. 'result_url' => $statusInfo['result_url'],
  3626. 'result_json' => $statusInfo['result_json'] ?? []
  3627. ]);
  3628. // 同步调整分镜图片状态和结果
  3629. if (getProp($task, 'alias_segment_id')) {
  3630. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3631. 'img_url' => $statusInfo['result_url'][0],
  3632. 'pic_task_status' => '已完成',
  3633. ]);
  3634. }
  3635. $img_url = $statusInfo['result_url'][0];
  3636. break;
  3637. } elseif ($statusInfo['status'] === 'failed') {
  3638. $task->updateStatus('failed', [
  3639. 'error_message' => $statusInfo['error_message'],
  3640. 'result_json' => $statusInfo['result_json'] ?? []
  3641. ]);
  3642. if (getProp($task, 'alias_segment_id')) {
  3643. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3644. 'pic_task_status' => '失败',
  3645. ]);
  3646. }
  3647. break;
  3648. }
  3649. $start_count++;
  3650. }
  3651. return $img_url;
  3652. }
  3653. /**
  3654. * 从分镜内容中提取涉及的角色
  3655. */
  3656. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3657. $found_characters = [];
  3658. foreach ($available_characters as $character) {
  3659. // 检查角色名称是否在分镜内容中出现
  3660. if (strpos($segment_content, $character) !== false) {
  3661. $found_characters[] = $character;
  3662. }
  3663. }
  3664. if (!$found_characters) {
  3665. foreach ($roles as $character) {
  3666. // 检查角色名称是否在分镜内容中出现
  3667. if (strpos($segment_content, $character) !== false) {
  3668. $found_characters[] = $character;
  3669. }
  3670. }
  3671. }
  3672. return array_unique($found_characters);
  3673. }
  3674. // 从分镜剧本中提取关键字段
  3675. private function handleSegmentContent(&$data) {
  3676. $segmentContent = getProp($data, 'segment_content');
  3677. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3678. $segmentData = [
  3679. 'description' => '',
  3680. 'composition' => '',
  3681. 'camera_movement' => '',
  3682. 'voice_actor' => '',
  3683. 'dialogue' => '',
  3684. 'frame_type' => '',
  3685. 'scene' => '', // 场景
  3686. 'characters' => '', // 出镜角色
  3687. 'tail_frame' => '', // 尾帧描述
  3688. 'emotion' => '中性', // 情感
  3689. 'gender' => '0', // 性别(0未知,1男,2女)
  3690. 'speed_ratio' => 0, // 语速
  3691. 'loudness_ratio' => 0, // 音量
  3692. 'emotion_scale' => 4, // 情感强度
  3693. 'pitch' => 0, // 音调
  3694. ];
  3695. // 用于存储需要从 segment_content 中移除的匹配项
  3696. $replaceEmptyArr = [];
  3697. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3698. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3699. $segmentData['description'] = trim($descMatch[1]);
  3700. $data['description'] = trim($descMatch[1]);
  3701. }
  3702. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3703. $segmentData['composition'] = trim($compMatch[1]);
  3704. $data['composition'] = trim($compMatch[1]);
  3705. }
  3706. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3707. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3708. $data['camera_movement'] = trim($cameraMatch[1]);
  3709. }
  3710. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3711. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3712. $data['voice_actor'] = trim($voiceMatch[1]);
  3713. }
  3714. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3715. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3716. $data['dialogue'] = trim($dialogueMatch[1]);
  3717. }
  3718. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3719. $segmentData['frame_type'] = trim($frameMatch[1]);
  3720. $data['frame_type'] = trim($frameMatch[1]);
  3721. }
  3722. // 场景字段
  3723. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3724. $segmentData['scene'] = trim($sceneMatch[1]);
  3725. $data['scene'] = trim($sceneMatch[1]);
  3726. }
  3727. // 出镜角色字段
  3728. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3729. $segmentData['characters'] = trim($charactersMatch[1]);
  3730. $data['characters'] = trim($charactersMatch[1]);
  3731. }
  3732. // 尾帧描述字段
  3733. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3734. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3735. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3736. }
  3737. // 情感字段
  3738. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3739. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3740. $segmentData['emotion'] = trim($emotionMatch[1]);
  3741. $data['emotion'] = trim($emotionMatch[1]);
  3742. }
  3743. // 性别字段
  3744. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3745. $replaceEmptyArr[] = trim($genderMatch[0]);
  3746. $genderStr = trim($genderMatch[1]);
  3747. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3748. $segmentData['gender'] = '1';
  3749. $data['gender'] = '1';
  3750. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3751. $segmentData['gender'] = '2';
  3752. $data['gender'] = '2';
  3753. } else {
  3754. $segmentData['gender'] = '0';
  3755. $data['gender'] = '0';
  3756. }
  3757. }
  3758. // 语速字段
  3759. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3760. $replaceEmptyArr[] = trim($speedMatch[0]);
  3761. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3762. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3763. }
  3764. // 音量字段
  3765. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3766. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3767. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3768. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3769. }
  3770. // 情感强度字段
  3771. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3772. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3773. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3774. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3775. }
  3776. // 音调字段
  3777. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3778. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3779. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3780. $data['pitch'] = (int)trim($pitchMatch[1]);
  3781. }
  3782. // 从 segment_content 中移除已提取的配音参数字段
  3783. if (!empty($replaceEmptyArr)) {
  3784. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3785. }
  3786. // 如果有配音角色,查询音色信息并验证情感
  3787. $voice_actor = $segmentData['voice_actor'];
  3788. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3789. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3790. $anime_id = getProp($data, 'anime_id');
  3791. $episode_id = getProp($data, 'episode_id');
  3792. // 优先从剧集的角色列表中查找
  3793. $roles = [];
  3794. if ($episode_id) {
  3795. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3796. if ($episode && getProp($episode, 'roles')) {
  3797. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3798. }
  3799. }
  3800. // 如果剧集中没有,从动漫的角色列表中查找
  3801. if (empty($roles) && $anime_id) {
  3802. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3803. if ($anime && getProp($anime, 'roles')) {
  3804. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3805. }
  3806. }
  3807. // 查找匹配的角色音色信息
  3808. $timbre_info = null;
  3809. foreach ($roles as $role) {
  3810. if (getProp($role, 'role') === $voice_actor) {
  3811. $timbre_info = $role;
  3812. break;
  3813. }
  3814. }
  3815. // 如果找到音色信息,添加到数据中
  3816. if ($timbre_info) {
  3817. $voice_type = getProp($timbre_info, 'voice_type');
  3818. $voice_name = getProp($timbre_info, 'voice_name');
  3819. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3820. if ($voice_type) {
  3821. $data['voice_type'] = $voice_type;
  3822. $segmentData['voice_type'] = $voice_type;
  3823. }
  3824. if ($voice_name) {
  3825. $data['voice_name'] = $voice_name;
  3826. $segmentData['voice_name'] = $voice_name;
  3827. }
  3828. if ($voice_audio_url) {
  3829. $data['voice_audio_url'] = $voice_audio_url;
  3830. $segmentData['voice_audio_url'] = $voice_audio_url;
  3831. }
  3832. // 验证情感是否在音色支持的情感列表中
  3833. if ($voice_type) {
  3834. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3835. if ($timbre_emotion) {
  3836. $timbre_emotion = explode(',', $timbre_emotion);
  3837. } else {
  3838. $timbre_emotion = [];
  3839. }
  3840. $emotion = getProp($segmentData, 'emotion', '中性');
  3841. if (!in_array($emotion, $timbre_emotion)) {
  3842. $emotion = '中性';
  3843. }
  3844. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3845. $emotion_list = array_flip($emotion_list);
  3846. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3847. $data['emotion_type'] = $emotion_type;
  3848. $segmentData['emotion_type'] = $emotion_type;
  3849. }
  3850. }
  3851. }
  3852. return $segmentData;
  3853. }
  3854. public function createSegmentVideoTask($data) {
  3855. $segment_id = getProp($data, 'segment_id');
  3856. $tail_frame = getProp($data, 'tail_frame');
  3857. $first_frame_url = getProp($data, 'first_frame_url');
  3858. $tail_frame_url = getProp($data, 'tail_frame_url');
  3859. $generate_audio = getProp($data, 'generate_audio', 0);
  3860. if (!$segment_id) {
  3861. Utils::throwError('1002:分镜ID不能为空');
  3862. }
  3863. // 获取分镜信息
  3864. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3865. if (!$segment) {
  3866. Utils::throwError('20003:分镜不存在');
  3867. }
  3868. $segment = (array)$segment;
  3869. $episode_id = getProp($segment, 'episode_id');
  3870. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3871. if (!$ratio) $ratio = '9:16';
  3872. // 获取分镜内容
  3873. $segmentContent = getProp($segment, 'segment_content', '');
  3874. // 检查 $segmentContent 中是否已有尾帧描述
  3875. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3876. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3877. $finalTailFrame = '';
  3878. if ($tail_frame) {
  3879. // 用户输入了尾帧描述,优先使用
  3880. $finalTailFrame = $tail_frame;
  3881. // 如果 segmentContent 中已有尾帧描述,需要替换
  3882. if ($contentHasTailFrame) {
  3883. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3884. }
  3885. } elseif ($contentHasTailFrame) {
  3886. // segmentContent 中有尾帧描述,使用它
  3887. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3888. } else {
  3889. // 两者都没有,使用分镜表中的尾帧描述
  3890. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3891. }
  3892. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3893. $hasDialogue = false;
  3894. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3895. $dialogue = trim($dialogueMatch[1]);
  3896. // 如果台词不为空且不是"无"
  3897. if (!empty($dialogue) && $dialogue !== '无') {
  3898. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3899. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3900. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3901. $hasDialogue = true;
  3902. }
  3903. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3904. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3905. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3906. if (!preg_match('/^[“]/', $dialogue)) {
  3907. $dialogue = '“' . $dialogue;
  3908. }
  3909. if (!preg_match('/[”]$/', $dialogue)) {
  3910. $dialogue .= '”';
  3911. }
  3912. // 将修改后的台词替换回 $segmentContent
  3913. $originalDialogue = $dialogueMatch[1];
  3914. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3915. }
  3916. }
  3917. // 构建完整的提示词
  3918. $fullPrompt = $segmentContent;
  3919. if ($finalTailFrame && !$contentHasTailFrame) {
  3920. // 只有当 segmentContent 中没有尾帧描述时才追加
  3921. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3922. }
  3923. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3924. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3925. $fullPrompt = trim($fullPrompt);
  3926. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3927. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3928. // 智能选择视频时长
  3929. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3930. $videoDuration = -1;
  3931. // 处理视频模型
  3932. $model = getProp($data, 'model');
  3933. if (!$model) {
  3934. // 用户没有输入,从episode表获取
  3935. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3936. $model = getProp($episode, 'video_model');
  3937. if (!$model) {
  3938. // episode表也没有,使用默认值
  3939. $model = 'doubao-seedance-1-5-pro-251215';
  3940. }
  3941. }
  3942. // 验证模型是否在可用模型表中
  3943. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3944. $model = 'doubao-seedance-1-5-pro-251215';
  3945. }
  3946. // 保存到episode表
  3947. $episode_id = getProp($segment, 'episode_id');
  3948. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3949. 'video_model' => $model,
  3950. 'updated_at' => date('Y-m-d H:i:s')
  3951. ]);
  3952. // 构建视频生成参数
  3953. $videoParams = [
  3954. 'model' => $model,
  3955. 'alias_segment_id' => $segment_id,
  3956. 'prompt' => trim($fullPrompt),
  3957. 'video_duration' => $videoDuration,
  3958. 'video_resolution' => '720P',
  3959. 'seed' => -1,
  3960. 'ratio' => $ratio,
  3961. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3962. 'draft' => false,
  3963. 'watermark' => false,
  3964. 'camera_fixed' => false,
  3965. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3966. ];
  3967. // 如果分镜有图片,作为首帧
  3968. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3969. $hasVideo = !empty(getProp($segment, 'video_url'));
  3970. if ($hasImage) {
  3971. if ($first_frame_url) {
  3972. $videoParams['first_frame_url'] = $first_frame_url;
  3973. }else {
  3974. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3975. }
  3976. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3977. }
  3978. // 构建content数组
  3979. $videoParams['content'] = [
  3980. [
  3981. 'type' => 'text',
  3982. 'text' => $videoParams['prompt'],
  3983. ]
  3984. ];
  3985. // 如果有首帧图片,添加到content中
  3986. if ($hasImage) {
  3987. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3988. $videoParams['content'][] = [
  3989. 'type' => 'image_url',
  3990. 'image_url' => [
  3991. 'url' => $videoParams['first_frame_url'],
  3992. ],
  3993. 'role' => 'reference_image',
  3994. ];
  3995. if (isset($videoParams['tail_frame_url'])) {
  3996. $videoParams['content'][] = [
  3997. 'type' => 'image_url',
  3998. 'image_url' => [
  3999. 'url' => $videoParams['tail_frame_url'],
  4000. ],
  4001. 'role' => 'reference_image',
  4002. ];
  4003. }
  4004. }else {
  4005. $videoParams['content'][] = [
  4006. 'type' => 'image_url',
  4007. 'image_url' => [
  4008. 'url' => $videoParams['first_frame_url'],
  4009. ],
  4010. 'role' => 'first_frame',
  4011. ];
  4012. if (isset($videoParams['tail_frame_url'])) {
  4013. $videoParams['content'][] = [
  4014. 'type' => 'image_url',
  4015. 'image_url' => [
  4016. 'url' => $videoParams['tail_frame_url'],
  4017. ],
  4018. 'role' => 'last_frame',
  4019. ];
  4020. }
  4021. }
  4022. }
  4023. // 获取配音音频URL
  4024. $audioUrl = getProp($segment, 'audio_url');
  4025. $audioDuration = getProp($segment, 'audio_duration');
  4026. // 音频传入的前提:必须有至少一张图片或一个视频
  4027. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4028. // dd($videoParams);
  4029. // 根据模型选择不同的视频生成方法
  4030. if (strpos($model, 'jimeng') !== false) {
  4031. // 即梦模型参数调整
  4032. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4033. unset($videoParams['content']); // 即梦不使用content格式
  4034. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4035. } elseif (strpos($model, 'kling') !== false) {
  4036. // Keling模型参数调整
  4037. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4038. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4039. unset($videoParams['ratio']);
  4040. unset($videoParams['content']); // Keling不使用content格式
  4041. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4042. } elseif (strpos($model, 'zhizhen') !== false) {
  4043. // 智帧20等新模型使用统一API
  4044. // 构建统一API参数
  4045. $unifiedParams = [
  4046. 'model_code' => $model,
  4047. 'alias_segment_id' => $segment_id,
  4048. 'prompt' => trim($fullPrompt),
  4049. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4050. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4051. 'video_ratio' => $ratio,
  4052. 'seed' => -1,
  4053. ];
  4054. // 构建parameters参数
  4055. $parameters = [
  4056. 'seconds' => $unifiedParams['video_duration'],
  4057. 'resolution' => $unifiedParams['video_resolution'],
  4058. 'ratio' => $ratio,
  4059. // 'video_mode' => 'multi_image',
  4060. // 'mode' => 'multi_image',
  4061. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4062. ];
  4063. $hasImage = false;
  4064. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4065. if ($hasImage) {
  4066. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4067. if (isset($videoParams['tail_frame_url'])) {
  4068. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4069. }
  4070. // 只有在有图片的情况下才能添加参考音频
  4071. if ($audioUrl) {
  4072. // $parameters['reference_audios'] = [$audioUrl];
  4073. }
  4074. } else {
  4075. // 没有图片时,记录错误日志
  4076. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4077. 'segment_id' => $segment_id,
  4078. 'model' => $model
  4079. ]);
  4080. }
  4081. $unifiedParams['parameters'] = $parameters;
  4082. // 调用统一API创建任务
  4083. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4084. } else {
  4085. // Seedance模型(默认)
  4086. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4087. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4088. // 添加配音音频到content中
  4089. $videoParams['content'][] = [
  4090. 'type' => 'audio_url',
  4091. 'audio_url' => [
  4092. 'url' => $audioUrl,
  4093. ],
  4094. 'role' => 'reference_audio',
  4095. ];
  4096. // 优化提示词,增加音频相关描述
  4097. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4098. $videoParams['prompt'] = $audioPrompt;
  4099. $videoParams['content'][0]['text'] = $audioPrompt;
  4100. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4101. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4102. }
  4103. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4104. }
  4105. // 更新分镜表的视频任务信息
  4106. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4107. 'video_task_id' => $task->id,
  4108. 'video_task_status' => '生成中',
  4109. 'generate_audio' => $generate_audio,
  4110. 'updated_at' => date('Y-m-d H:i:s')
  4111. ]);
  4112. return [
  4113. 'task_id' => $task->id,
  4114. 'status' => $task->status,
  4115. 'segment_id' => $segment_id,
  4116. 'video_duration' => $videoDuration
  4117. ];
  4118. }
  4119. public function createActVideoTask($data) {
  4120. $act_id = getProp($data, 'act_id');
  4121. $first_frame_url = getProp($data, 'first_frame_url');
  4122. $tail_frame_url = getProp($data, 'tail_frame_url');
  4123. $generate_audio = getProp($data, 'generate_audio', 1);
  4124. $video_duration = getProp($data, 'video_duration');
  4125. $video_resolution = getProp($data, 'video_resolution');
  4126. $ratio = getProp($data, 'ratio');
  4127. $products = getProp($data, 'products', []);
  4128. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4129. if (!is_array($reference_images) || !is_array($products)) {
  4130. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4131. }
  4132. if (!$act_id) {
  4133. Utils::throwError('1002:片段ID不能为空');
  4134. }
  4135. // 获取片段信息
  4136. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4137. if (!$act) {
  4138. Utils::throwError('20003:片段不存在');
  4139. }
  4140. $act = (array)$act;
  4141. $anime_id = getProp($act, 'anime_id');
  4142. $episode_id = getProp($act, 'episode_id');
  4143. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4144. $ace_mode = getProp($anime, 'ace_mode');
  4145. $art_style_type = getProp($anime, 'art_style_type');
  4146. $art_style = getProp($anime, 'art_style');
  4147. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4148. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4149. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4150. // 将资产中新出现的资产放到extra_products中
  4151. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4152. if (!empty($products) && $episode) {
  4153. // 获取剧集中的角色、场景和道具列表
  4154. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4155. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4156. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4157. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4158. // 构建角色名称列表
  4159. $role_names = array_column($roles, 'role');
  4160. // 构建场景名称列表
  4161. $scene_names = array_column($scenes, 'scene');
  4162. // 构建道具名称列表
  4163. $prop_names = array_column($props, 'prop');
  4164. // 遍历传入的products
  4165. foreach ($products as $product) {
  4166. $product_name = getProp($product, 'product_name');
  4167. // 如果product_name不在roles、scenes和props中
  4168. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4169. // 查找是否在extra_products中存在同名的
  4170. $found = false;
  4171. foreach ($extra_products as $key => $extra_product) {
  4172. if (getProp($extra_product, 'product_name') === $product_name) {
  4173. // 有同名的则覆盖
  4174. $extra_products[$key] = $product;
  4175. $found = true;
  4176. break;
  4177. }
  4178. }
  4179. // 没有则新增
  4180. if (!$found) {
  4181. $extra_products[] = $product;
  4182. }
  4183. }
  4184. }
  4185. if ($extra_products) {
  4186. // 保存到数据库
  4187. DB::table('mp_anime_episodes')
  4188. ->where('id', $episode_id)
  4189. ->update([
  4190. 'extra_products' => json_encode($extra_products, 256),
  4191. 'updated_at' => date('Y-m-d H:i:s')
  4192. ]);
  4193. }
  4194. }
  4195. // 获取分镜内容
  4196. $actContent = getProp($act, 'act_show_content', '');
  4197. // 音效同出(默认使用)
  4198. $current_generate_audio = $generate_audio ? 1 : 0;
  4199. // 构建完整的提示词
  4200. $processResult = $this->processActContentWithProducts($actContent, $products);
  4201. $fullPrompt = $processResult['content'];
  4202. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4203. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4204. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4205. // 处理视频模型
  4206. $model = getProp($data, 'model');
  4207. if (!$model) {
  4208. $model = getProp($episode, 'video_model');
  4209. if (!$model) {
  4210. // episode表也没有,使用默认值
  4211. $model = 'zhizhen-20';
  4212. }
  4213. }
  4214. // 验证模型是否在可用模型表中
  4215. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4216. $model = 'zhizhen-20';
  4217. }
  4218. // 保存到episode表
  4219. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4220. 'video_model' => $model,
  4221. 'updated_at' => date('Y-m-d H:i:s')
  4222. ]);
  4223. // 构建视频生成参数
  4224. $videoParams = [
  4225. 'model' => $model,
  4226. 'alias_act_id' => $act_id,
  4227. 'prompt' => trim($fullPrompt),
  4228. 'video_duration' => $videoDuration,
  4229. 'video_resolution' => $video_resolution,
  4230. 'seed' => -1,
  4231. 'ratio' => $ratio,
  4232. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4233. 'draft' => false,
  4234. 'watermark' => false,
  4235. 'camera_fixed' => false,
  4236. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4237. ];
  4238. // 如果分镜有图片,作为首帧
  4239. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4240. $hasVideo = !empty(getProp($act, 'video_url'));
  4241. if ($hasImage) {
  4242. if ($first_frame_url) {
  4243. $videoParams['first_frame_url'] = $first_frame_url;
  4244. }else {
  4245. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4246. }
  4247. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4248. }
  4249. // 构建content数组
  4250. $videoParams['content'] = [
  4251. [
  4252. 'type' => 'text',
  4253. 'text' => $videoParams['prompt'],
  4254. ]
  4255. ];
  4256. // 如果有首帧图片,添加到content中
  4257. if ($hasImage) {
  4258. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4259. $videoParams['content'][] = [
  4260. 'type' => 'image_url',
  4261. 'image_url' => [
  4262. 'url' => $videoParams['first_frame_url'],
  4263. ],
  4264. 'role' => 'reference_image',
  4265. ];
  4266. if (isset($videoParams['tail_frame_url'])) {
  4267. $videoParams['content'][] = [
  4268. 'type' => 'image_url',
  4269. 'image_url' => [
  4270. 'url' => $videoParams['tail_frame_url'],
  4271. ],
  4272. 'role' => 'reference_image',
  4273. ];
  4274. }
  4275. }else {
  4276. $videoParams['content'][] = [
  4277. 'type' => 'image_url',
  4278. 'image_url' => [
  4279. 'url' => $videoParams['first_frame_url'],
  4280. ],
  4281. 'role' => 'first_frame',
  4282. ];
  4283. if (isset($videoParams['tail_frame_url'])) {
  4284. $videoParams['content'][] = [
  4285. 'type' => 'image_url',
  4286. 'image_url' => [
  4287. 'url' => $videoParams['tail_frame_url'],
  4288. ],
  4289. 'role' => 'last_frame',
  4290. ];
  4291. }
  4292. }
  4293. }
  4294. // dd($videoParams);
  4295. // 根据模型选择不同的视频生成方法
  4296. if (strpos($model, 'jimeng') !== false) {
  4297. // 即梦模型参数调整
  4298. unset($videoParams['content']); // 即梦不使用content格式
  4299. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4300. } elseif (strpos($model, 'kling') !== false) {
  4301. // Keling模型参数调整
  4302. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4303. unset($videoParams['ratio']);
  4304. unset($videoParams['content']); // Keling不使用content格式
  4305. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4306. } elseif (strpos($model, 'zhizhen') !== false) {
  4307. // 智帧20等新模型使用统一API
  4308. // 构建统一API参数
  4309. $unifiedParams = [
  4310. 'model_code' => $model,
  4311. 'alias_act_id' => $act_id,
  4312. 'prompt' => trim($fullPrompt),
  4313. 'video_duration' => $videoDuration,
  4314. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4315. 'video_ratio' => $ratio,
  4316. 'seed' => -1,
  4317. ];
  4318. // 构建parameters参数
  4319. $parameters = [
  4320. 'seconds' => $unifiedParams['video_duration'],
  4321. 'resolution' => $unifiedParams['video_resolution'],
  4322. 'ratio' => $ratio,
  4323. // 'video_mode' => 'multi_image',
  4324. // 'mode' => 'multi_image',
  4325. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4326. ];
  4327. $hasImage = false;
  4328. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4329. if ($hasImage) {
  4330. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4331. if (isset($videoParams['tail_frame_url'])) {
  4332. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4333. }
  4334. } else {
  4335. // 没有图片时,记录错误日志
  4336. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4337. 'act_id' => $act_id,
  4338. 'model' => $model
  4339. ]);
  4340. }
  4341. if ($reference_images) {
  4342. // 限制只传入9张参考图
  4343. $reference_images = array_slice($reference_images, 0, 9);
  4344. // 在处理之前先保存原始reference_images到任务参数中
  4345. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4346. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4347. $parameters['reference_images'] = $reference_images;
  4348. $parameters['video_mode'] = 'multi_image';
  4349. $parameters['mode'] = 'multi_image';
  4350. }
  4351. $unifiedParams['parameters'] = $parameters;
  4352. // 调用统一API创建任务
  4353. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4354. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4355. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4356. // 保存原始参考图用于任务记录
  4357. $videoParams['reference_images'] = $reference_images;
  4358. if ($reference_images) {
  4359. // 限制只传入9张参考图
  4360. $reference_images = array_slice($reference_images, 0, 9);
  4361. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4362. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4363. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4364. $videoParams['prompt'] = trim($fullPrompt);
  4365. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4366. $videoParams['reference_image_assets'] = $reference_image_assets;
  4367. }
  4368. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4369. } else {
  4370. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4371. }
  4372. // 更新分镜表的视频任务信息
  4373. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4374. 'video_task_id' => $task->id,
  4375. 'video_task_status' => '生成中',
  4376. 'generate_audio' => $generate_audio,
  4377. 'updated_at' => date('Y-m-d H:i:s')
  4378. ]);
  4379. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4380. $episode_number = getProp($act, 'episode_number');
  4381. $act_number = getProp($act, 'act_number');
  4382. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4383. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4384. }
  4385. return [
  4386. 'task_id' => $task->id,
  4387. 'status' => $task->status,
  4388. 'act_id' => $act_id,
  4389. 'video_duration' => $videoDuration
  4390. ];
  4391. }
  4392. /**
  4393. * 文生视频通用方法
  4394. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4395. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4396. *
  4397. * @param array $data 请求参数
  4398. * @return array
  4399. */
  4400. public function generateVideo($data) {
  4401. $prompt = getProp($data, 'prompt');
  4402. if (empty($prompt)) {
  4403. Utils::throwError('20003:提示词不能为空');
  4404. }
  4405. $model = getProp($data, 'model');
  4406. if (!$model) {
  4407. $model = 'zhizhen-20';
  4408. }
  4409. // 验证模型是否在可用模型表中
  4410. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4411. Utils::throwError('20003:该模型已不可用,请更换!');
  4412. }
  4413. $video_duration = getProp($data, 'video_duration', 5);
  4414. $video_resolution = getProp($data, 'video_resolution', '480p');
  4415. $ratio = getProp($data, 'ratio', '9:16');
  4416. $generate_audio = getProp($data, 'generate_audio', 1);
  4417. $seed = getProp($data, 'seed', -1);
  4418. $first_frame_url = getProp($data, 'first_frame_url');
  4419. $tail_frame_url = getProp($data, 'tail_frame_url');
  4420. // 参考图(支持数组或JSON字符串,最多9张)
  4421. $reference_images = getProp($data, 'reference_images', []);
  4422. if (is_string($reference_images)) {
  4423. $reference_images = json_decode($reference_images, true) ?: [];
  4424. }
  4425. if (!is_array($reference_images)) {
  4426. Utils::throwError('20003:参考图格式不正确');
  4427. }
  4428. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4429. $reference_images = array_slice($reference_images, 0, 9);
  4430. // 参考视频(支持数组或JSON字符串,最多3个)
  4431. $reference_videos = getProp($data, 'reference_videos', []);
  4432. if (is_string($reference_videos)) {
  4433. $reference_videos = json_decode($reference_videos, true) ?: [];
  4434. }
  4435. if (!is_array($reference_videos)) {
  4436. Utils::throwError('20003:参考视频格式不正确');
  4437. }
  4438. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4439. if (count($reference_videos) > 3) {
  4440. Utils::throwError('20003:参考视频最多选择3个');
  4441. }
  4442. $reference_videos = array_slice($reference_videos, 0, 3);
  4443. // 参考音频(支持数组或JSON字符串,最多3个)
  4444. $reference_audios = getProp($data, 'reference_audios', []);
  4445. if (is_string($reference_audios)) {
  4446. $reference_audios = json_decode($reference_audios, true) ?: [];
  4447. }
  4448. if (!is_array($reference_audios)) {
  4449. Utils::throwError('20003:参考音频格式不正确');
  4450. }
  4451. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4452. if (count($reference_audios) > 3) {
  4453. Utils::throwError('20003:参考音频最多选择3个');
  4454. }
  4455. $reference_audios = array_slice($reference_audios, 0, 3);
  4456. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4457. $videoParams = [
  4458. 'model' => $model,
  4459. 'prompt' => $prompt,
  4460. 'video_duration' => $video_duration,
  4461. 'video_resolution' => $video_resolution,
  4462. 'seed' => $seed,
  4463. 'ratio' => $ratio,
  4464. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4465. 'draft' => getProp($data, 'draft', false),
  4466. 'watermark' => getProp($data, 'watermark', false),
  4467. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4468. ];
  4469. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4470. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4471. // 构建content数组
  4472. $videoParams['content'] = [
  4473. [
  4474. 'type' => 'text',
  4475. 'text' => $prompt,
  4476. ]
  4477. ];
  4478. // 根据模型选择不同的视频生成方法
  4479. if (strpos($model, 'jimeng') !== false) {
  4480. // 即梦模型参数调整
  4481. unset($videoParams['content']); // 即梦不使用content格式
  4482. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4483. } elseif (strpos($model, 'kling') !== false) {
  4484. // 可灵模型参数调整
  4485. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4486. unset($videoParams['ratio']);
  4487. unset($videoParams['content']); // 可灵不使用content格式
  4488. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4489. } elseif (strpos($model, 'zhizhen') !== false) {
  4490. // 智帧等新模型使用统一API
  4491. $unifiedParams = [
  4492. 'model_code' => $model,
  4493. 'prompt' => $prompt,
  4494. 'video_duration' => $video_duration,
  4495. 'video_resolution' => strtolower($video_resolution),
  4496. 'video_ratio' => $ratio,
  4497. 'seed' => $seed,
  4498. ];
  4499. // 构建parameters参数
  4500. $parameters = [
  4501. 'seconds' => $unifiedParams['video_duration'],
  4502. 'resolution' => $unifiedParams['video_resolution'],
  4503. 'ratio' => $ratio,
  4504. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4505. ];
  4506. // 首帧和尾帧
  4507. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4508. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4509. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4510. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4511. if ($refImageUrls) {
  4512. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4513. }
  4514. // 参考图处理
  4515. if ($reference_images) {
  4516. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4517. $parameters['reference_images'] = $reference_images;
  4518. $parameters['video_mode'] = 'multi_image';
  4519. $parameters['mode'] = 'multi_image';
  4520. }
  4521. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4522. if ($reference_videos) {
  4523. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4524. $parameters['reference_videos'] = $reference_videos;
  4525. }
  4526. if ($reference_audios) {
  4527. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4528. $parameters['reference_audios'] = $reference_audios;
  4529. }
  4530. $unifiedParams['parameters'] = $parameters;
  4531. // 调用统一API创建任务
  4532. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4533. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4534. // 豆包Seedance 2.0(百度AI网关):图片/视频/音频需要先上传为素材
  4535. $videoParams['reference_images'] = $reference_images;
  4536. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4537. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4538. if ($refImageUrls) {
  4539. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4540. }
  4541. if ($reference_images) {
  4542. // 参考图上传为百度网关素材
  4543. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4544. $videoParams['reference_image_assets'] = $reference_image_assets;
  4545. }
  4546. // 参考视频上传为百度网关素材
  4547. if ($reference_videos) {
  4548. $reference_video_assets = $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4549. $videoParams['reference_video_assets'] = $reference_video_assets;
  4550. }
  4551. // 参考音频上传为百度网关素材
  4552. if ($reference_audios) {
  4553. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4554. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4555. }
  4556. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4557. if ($reference_images || $reference_videos || $reference_audios) {
  4558. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4559. }
  4560. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4561. } else {
  4562. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4563. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4564. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4565. if ($refImageUrls) {
  4566. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4567. }
  4568. if ($reference_videos) {
  4569. foreach ($reference_videos as $videoUrl) {
  4570. $videoParams['content'][] = [
  4571. 'type' => 'video_url',
  4572. 'video_url' => [
  4573. 'url' => $videoUrl,
  4574. ],
  4575. 'role' => 'reference_video',
  4576. ];
  4577. }
  4578. }
  4579. if ($reference_audios) {
  4580. foreach ($reference_audios as $audioUrl) {
  4581. $videoParams['content'][] = [
  4582. 'type' => 'audio_url',
  4583. 'audio_url' => [
  4584. 'url' => $audioUrl,
  4585. ],
  4586. 'role' => 'reference_audio',
  4587. ];
  4588. }
  4589. }
  4590. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4591. }
  4592. return [
  4593. 'task_id' => $task->id,
  4594. 'status' => $task->status,
  4595. 'model' => $model,
  4596. 'video_duration' => $video_duration,
  4597. 'video_resolution' => $video_resolution,
  4598. 'ratio' => $ratio
  4599. ];
  4600. }
  4601. /**
  4602. * 根据提示词内容智能计算最优视频时长
  4603. *
  4604. * @param string $segmentContent 分镜内容
  4605. * @param string $tailFrame 尾帧描述
  4606. * @return int 视频时长(2-12秒)
  4607. */
  4608. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4609. // 合并所有文本内容
  4610. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4611. // 如果没有内容,返回默认时长
  4612. if (empty($fullText)) {
  4613. return 5;
  4614. }
  4615. // 计算文本长度(中文字符按2个字符计算)
  4616. $textLength = mb_strlen($fullText, 'UTF-8');
  4617. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4618. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4619. // 分析内容复杂度
  4620. $complexityScore = $this->analyzeContentComplexity($fullText);
  4621. // 基础时长计算(根据文本长度)
  4622. $baseDuration = 3; // 默认2秒
  4623. // if ($adjustedLength <= 20) {
  4624. // $baseDuration = 3;
  4625. // } elseif ($adjustedLength <= 40) {
  4626. // $baseDuration = 4;
  4627. // } elseif ($adjustedLength <= 60) {
  4628. // $baseDuration = 5;
  4629. // } elseif ($adjustedLength <= 80) {
  4630. // $baseDuration = 6;
  4631. // } elseif ($adjustedLength <= 100) {
  4632. // $baseDuration = 7;
  4633. // } elseif ($adjustedLength <= 120) {
  4634. // $baseDuration = 8;
  4635. // } else {
  4636. // $baseDuration = 9;
  4637. // }
  4638. // 根据内容复杂度调整时长
  4639. $finalDuration = $baseDuration + $complexityScore;
  4640. // 确保时长在2-12秒范围内
  4641. return max(4, min(12, $finalDuration));
  4642. }
  4643. /**
  4644. * 分析内容复杂度,返回时长调整值
  4645. *
  4646. * @param string $text 文本内容
  4647. * @return int 调整值(-2到+3)
  4648. */
  4649. private function analyzeContentComplexity($text) {
  4650. $score = 0;
  4651. // 动作关键词(需要更长时间展现)
  4652. $actionKeywords = [
  4653. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4654. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4655. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4656. ];
  4657. // 静态关键词(可以用较短时间)
  4658. $staticKeywords = [
  4659. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4660. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4661. ];
  4662. // 复杂场景关键词(需要更长时间)
  4663. $complexSceneKeywords = [
  4664. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4665. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4666. ];
  4667. // 情感关键词(需要适中时间表现)
  4668. $emotionKeywords = [
  4669. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4670. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4671. ];
  4672. // 检查动作关键词
  4673. foreach ($actionKeywords as $keyword) {
  4674. if (strpos($text, $keyword) !== false) {
  4675. $score += 1;
  4676. break; // 避免重复加分
  4677. }
  4678. }
  4679. // 检查静态关键词
  4680. foreach ($staticKeywords as $keyword) {
  4681. if (strpos($text, $keyword) !== false) {
  4682. $score -= 1;
  4683. break;
  4684. }
  4685. }
  4686. // 检查复杂场景关键词
  4687. foreach ($complexSceneKeywords as $keyword) {
  4688. if (strpos($text, $keyword) !== false) {
  4689. $score += 1;
  4690. break;
  4691. }
  4692. }
  4693. // 检查情感关键词
  4694. foreach ($emotionKeywords as $keyword) {
  4695. if (strpos($text, $keyword) !== false) {
  4696. $score += 1;
  4697. break;
  4698. }
  4699. }
  4700. // 检查时间相关词汇
  4701. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4702. $score += 1;
  4703. }
  4704. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4705. $score -= 1;
  4706. }
  4707. // 检查转场词汇
  4708. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4709. $score += 1;
  4710. }
  4711. // 检查环境描述(复杂环境需要更多时间)
  4712. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4713. $score += 1;
  4714. }
  4715. // 检查对话内容(对话需要更多时间)
  4716. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4717. $score += 1;
  4718. }
  4719. // 限制调整范围
  4720. return max(-1, min(4, $score));
  4721. }
  4722. /**
  4723. * 创建完整视频合成任务
  4724. *
  4725. * @param array $data
  4726. * @return array
  4727. */
  4728. public function createCompleteVideoTask($data)
  4729. {
  4730. $animeId = getProp($data, 'anime_id');
  4731. $episodeId = getProp($data, 'episode_id');
  4732. // 验证参数
  4733. if (!$animeId || !$episodeId) {
  4734. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4735. }
  4736. // 检查是否已存在处理中的任务
  4737. $existingTask = DB::table('mp_complete_video_tasks')
  4738. ->where('anime_id', $animeId)
  4739. ->where('episode_id', $episodeId)
  4740. ->whereIn('generate_status', ['执行中'])
  4741. ->first();
  4742. if ($existingTask) {
  4743. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4744. }
  4745. // 获取全能模式状态
  4746. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4747. if ((int)$ace_mode === 1) {
  4748. // 获取所有片段的配音视频,按 act_number 排序
  4749. $segments = DB::table('mp_episode_segments')
  4750. ->where('anime_id', $animeId)
  4751. ->where('episode_id', $episodeId)
  4752. ->orderBy('segment_number')
  4753. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4754. ->get();
  4755. // 检查是否所有片段都有视频
  4756. $missingVideos = $segments->filter(function($segment) {
  4757. return empty($segment->video_url);
  4758. });
  4759. if ($missingVideos->isNotEmpty()) {
  4760. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4761. }
  4762. }else {
  4763. // 获取所有分镜的配音视频,按 segment_number 排序
  4764. $segments = DB::table('mp_episode_segments')
  4765. ->where('anime_id', $animeId)
  4766. ->where('episode_id', $episodeId)
  4767. ->orderBy('segment_number')
  4768. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4769. ->get();
  4770. // 检查是否所有分镜都有配音和视频
  4771. $missingVideos = $segments->filter(function($segment) {
  4772. return empty($segment->audio_url) || empty($segment->video_url);
  4773. });
  4774. if ($missingVideos->isNotEmpty()) {
  4775. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4776. }
  4777. }
  4778. if ($segments->isEmpty()) {
  4779. Utils::throwError('20003:未找到该剧集的分镜数据');
  4780. }
  4781. // 获取当前完整视频url
  4782. $completeVideoUrl = DB::table('mp_anime_episodes')
  4783. ->where('anime_id', $animeId)
  4784. ->where('id', $episodeId)
  4785. ->value('complete_video_url');
  4786. // 构建 generate_json
  4787. $generateJson = [];
  4788. $sequence = 1;
  4789. foreach ($segments as $segment) {
  4790. if ((int)$ace_mode === 1) {
  4791. $generateJson[] = [
  4792. 'sequence' => $sequence++,
  4793. 'video_url' => $segment->video_url,
  4794. 'video_time_point_start' => $segment->video_time_point_start,
  4795. 'video_time_point_end' => $segment->video_time_point_end
  4796. ];
  4797. }else {
  4798. $generateJson[] = [
  4799. 'sequence' => $sequence++,
  4800. 'video_url' => $segment->video_url,
  4801. 'audio_url' => $segment->audio_url,
  4802. 'video_time_point_start' => $segment->video_time_point_start,
  4803. 'video_time_point_end' => $segment->video_time_point_end
  4804. ];
  4805. }
  4806. }
  4807. // 创建任务
  4808. $now = date('Y-m-d H:i:s');
  4809. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4810. 'anime_id' => $animeId,
  4811. 'episode_id' => $episodeId,
  4812. 'generate_json' => json_encode($generateJson, 256),
  4813. 'generate_status' => '执行中',
  4814. 'complete_video_url' => '',
  4815. 'created_at' => $now,
  4816. 'updated_at' => $now
  4817. ]);
  4818. if (!$taskId) {
  4819. Utils::throwError('20003:创建任务失败');
  4820. }
  4821. // 更新剧集表的任务ID和状态
  4822. $boolen = DB::table('mp_anime_episodes')
  4823. ->where('anime_id', $animeId)
  4824. ->where('id', $episodeId)
  4825. ->update([
  4826. 'complete_video_task_id' => $taskId,
  4827. 'complete_video_task_status' => '执行中',
  4828. 'updated_at' => $now
  4829. ]);
  4830. if (!$boolen) {
  4831. Utils::throwError('20003:更新剧集表失败');
  4832. }
  4833. dLog('anime')->info('创建完整视频合成任务', [
  4834. 'task_id' => $taskId,
  4835. 'anime_id' => $animeId,
  4836. 'episode_id' => $episodeId,
  4837. 'segment_count' => count($generateJson)
  4838. ]);
  4839. // 请求远程服务器执行生成
  4840. $client = new Client(['timeout' => 600, 'verify' => false]);
  4841. try {
  4842. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4843. $response = $result->getBody()->getContents();
  4844. $response_arr = json_decode($response, true);
  4845. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4846. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4847. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4848. // // 更新任务状态为失败
  4849. // DB::table('mp_complete_video_tasks')
  4850. // ->where('id', $taskId)
  4851. // ->update([
  4852. // 'generate_status' => '执行失败',
  4853. // 'error_message' => $error_msg,
  4854. // 'updated_at' => date('Y-m-d H:i:s')
  4855. // ]);
  4856. // // 同步更新剧集表状态
  4857. // DB::table('mp_anime_episodes')
  4858. // ->where('complete_video_task_id', $taskId)
  4859. // ->update([
  4860. // 'complete_video_task_status' => '执行失败',
  4861. // 'updated_at' => date('Y-m-d H:i:s')
  4862. // ]);
  4863. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4864. }
  4865. } catch (\Exception $e) {
  4866. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4867. // 更新任务状态为失败
  4868. DB::table('mp_complete_video_tasks')
  4869. ->where('id', $taskId)
  4870. ->update([
  4871. 'generate_status' => '执行失败',
  4872. 'error_message' => $e->getMessage(),
  4873. 'updated_at' => date('Y-m-d H:i:s')
  4874. ]);
  4875. // 同步更新剧集表状态
  4876. DB::table('mp_anime_episodes')
  4877. ->where('complete_video_task_id', $taskId)
  4878. ->update([
  4879. 'complete_video_task_status' => '执行失败',
  4880. 'updated_at' => date('Y-m-d H:i:s')
  4881. ]);
  4882. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4883. }
  4884. // 开始轮询任务状态
  4885. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4886. $pollInterval = 5; // 每5秒轮询一次
  4887. $attempt = 0;
  4888. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4889. while ($attempt < $maxAttempts) {
  4890. sleep($pollInterval);
  4891. $attempt++;
  4892. // 查询任务状态
  4893. $task = DB::table('mp_complete_video_tasks')
  4894. ->where('id', $taskId)
  4895. ->first();
  4896. if (!$task) {
  4897. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4898. Utils::throwError('20003:任务不存在');
  4899. }
  4900. dLog('anime')->info('轮询任务状态', [
  4901. 'task_id' => $taskId,
  4902. 'attempt' => $attempt,
  4903. 'status' => $task->generate_status
  4904. ]);
  4905. // 检查任务是否完成
  4906. if ($task->generate_status === '执行成功') {
  4907. // 同步更新剧集表状态
  4908. $boolen3 = DB::table('mp_anime_episodes')
  4909. ->where('anime_id', $animeId)
  4910. ->where('id', $episodeId)
  4911. ->update([
  4912. 'complete_video_url' => $task->complete_video_url,
  4913. 'complete_video_task_status' => '执行成功',
  4914. 'updated_at' => date('Y-m-d H:i:s')
  4915. ]);
  4916. dLog('anime')->info('视频合成任务完成', [
  4917. 'task_id' => $taskId,
  4918. 'video_url' => $task->complete_video_url,
  4919. 'attempts' => $attempt
  4920. ]);
  4921. // 如果更新成功则远程删除之前的文件
  4922. if ($boolen3 && $completeVideoUrl) {
  4923. $encode_url = urlencode($completeVideoUrl);
  4924. $client = new Client(['timeout' => 300, 'verify' => false]);
  4925. // 根据ID通过API通知合成音频
  4926. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4927. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4928. $response = $result->getBody()->getContents();
  4929. $response_arr = json_decode($response, true);
  4930. Log::info('火山删除音频返回: '.$response);
  4931. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4932. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4933. Log::info('火山删除音频失败: '.$error_msg);
  4934. // Utils::throwError('20003:火山删除音频失败');
  4935. }
  4936. }
  4937. return [
  4938. 'task_id' => $taskId,
  4939. 'anime_id' => $animeId,
  4940. 'episode_id' => $episodeId,
  4941. 'segment_count' => count($generateJson),
  4942. 'generate_status' => '执行成功',
  4943. 'complete_video_url' => $task->complete_video_url,
  4944. ];
  4945. }
  4946. // 检查任务是否失败
  4947. if ($task->generate_status === '执行失败') {
  4948. // 同步更新剧集表状态
  4949. DB::table('mp_anime_episodes')
  4950. ->where('anime_id', $animeId)
  4951. ->where('id', $episodeId)
  4952. ->update([
  4953. 'complete_video_task_status' => '执行失败',
  4954. 'updated_at' => date('Y-m-d H:i:s')
  4955. ]);
  4956. $errorMessage = $task->error_message ?? '未知错误';
  4957. dLog('anime')->error('视频合成任务失败', [
  4958. 'task_id' => $taskId,
  4959. 'error' => $errorMessage,
  4960. 'attempts' => $attempt
  4961. ]);
  4962. return [
  4963. 'task_id' => $taskId,
  4964. 'anime_id' => $animeId,
  4965. 'episode_id' => $episodeId,
  4966. 'segment_count' => count($generateJson),
  4967. 'generate_status' => '执行失败',
  4968. 'error_message' => $errorMessage
  4969. ];
  4970. }
  4971. }
  4972. // 超时处理
  4973. dLog('anime')->warning('视频合成任务超时', [
  4974. 'task_id' => $taskId,
  4975. 'max_attempts' => $maxAttempts,
  4976. 'timeout_seconds' => $maxAttempts * $pollInterval
  4977. ]);
  4978. // 更新任务状态为超时
  4979. DB::table('mp_complete_video_tasks')
  4980. ->where('id', $taskId)
  4981. ->update([
  4982. 'generate_status' => '超时',
  4983. 'error_message' => '任务执行超时(5分钟)',
  4984. 'updated_at' => date('Y-m-d H:i:s')
  4985. ]);
  4986. return [
  4987. 'task_id' => $taskId,
  4988. 'anime_id' => $animeId,
  4989. 'episode_id' => $episodeId,
  4990. 'segment_count' => count($generateJson),
  4991. 'generate_status' => '超时',
  4992. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4993. ];
  4994. }
  4995. /**
  4996. * 根据 inner_prompt_type 附加内置提示词
  4997. *
  4998. * @param string $prompt 用户提示词
  4999. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5000. * @return string 合并后的提示词
  5001. */
  5002. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5003. {
  5004. $innerPromptMap = [
  5005. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5006. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5007. ];
  5008. if (!isset($innerPromptMap[$innerPromptType])) {
  5009. return $prompt;
  5010. }
  5011. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5012. }
  5013. /**
  5014. * 根据 inner_prompt_type 获取生成图片数量
  5015. *
  5016. * @param int $innerPromptType 内置提示词类型
  5017. * @param int $imageNum 传入的图片张数
  5018. * @return int 图片数量
  5019. */
  5020. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5021. {
  5022. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5023. }
  5024. /**
  5025. * 提取图片生成结果URL
  5026. *
  5027. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5028. * @param int $innerPromptType 内置提示词类型
  5029. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5030. */
  5031. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5032. {
  5033. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5034. if (is_array($resultUrls) && !empty($resultUrls)) {
  5035. $resultUrls = array_values($resultUrls);
  5036. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5037. }
  5038. if (!empty($resultUrl)) {
  5039. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5040. }
  5041. return (int)$innerPromptType === 2 ? [] : '';
  5042. }
  5043. public function generateImg($data) {
  5044. $prompt = getProp($data, 'prompt');
  5045. $episode_id = getProp($data, 'episode_id');
  5046. $ref_img_urls = getProp($data, 'ref_img_urls');
  5047. $ratio = getProp($data, 'ratio', '9:16');
  5048. $resolution = getProp($data, 'resolution', '2k');
  5049. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5050. $imageNum = (int)getProp($data, 'image_num', 1);
  5051. // 定义分辨率和宽高比对应的尺寸映射表
  5052. $sizeMap = [
  5053. '2k' => [
  5054. '1:1' => ['width' => 2048, 'height' => 2048],
  5055. '4:3' => ['width' => 2304, 'height' => 1728],
  5056. '3:4' => ['width' => 1728, 'height' => 2304],
  5057. '16:9' => ['width' => 2848, 'height' => 1600],
  5058. '9:16' => ['width' => 1600, 'height' => 2848],
  5059. '3:2' => ['width' => 2496, 'height' => 1664],
  5060. '2:3' => ['width' => 1664, 'height' => 2496],
  5061. '21:9' => ['width' => 3136, 'height' => 1344],
  5062. ],
  5063. '3k' => [
  5064. '1:1' => ['width' => 3072, 'height' => 3072],
  5065. '4:3' => ['width' => 3456, 'height' => 2592],
  5066. '3:4' => ['width' => 2592, 'height' => 3456],
  5067. '16:9' => ['width' => 4096, 'height' => 2304],
  5068. '9:16' => ['width' => 2304, 'height' => 4096],
  5069. '2:3' => ['width' => 2496, 'height' => 3744],
  5070. '3:2' => ['width' => 3744, 'height' => 2496],
  5071. '21:9' => ['width' => 4704, 'height' => 2016],
  5072. ],
  5073. '4k' => [
  5074. '1:1' => ['width' => 4096, 'height' => 4096],
  5075. '3:4' => ['width' => 3520, 'height' => 4704],
  5076. '4:3' => ['width' => 4704, 'height' => 3520],
  5077. '16:9' => ['width' => 5504, 'height' => 3040],
  5078. '9:16' => ['width' => 3040, 'height' => 5504],
  5079. '2:3' => ['width' => 3328, 'height' => 4992],
  5080. '3:2' => ['width' => 4992, 'height' => 3328],
  5081. '21:9' => ['width' => 6240, 'height' => 2656],
  5082. ],
  5083. ];
  5084. // 参数验证
  5085. $resolution = strtolower($resolution);
  5086. if (!isset($sizeMap[$resolution])) {
  5087. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5088. }
  5089. if (!isset($sizeMap[$resolution][$ratio])) {
  5090. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5091. }
  5092. // 根据 ratio 和 resolution 确定宽高
  5093. $width = $sizeMap[$resolution][$ratio]['width'];
  5094. $height = $sizeMap[$resolution][$ratio]['height'];
  5095. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5096. if (is_json($ref_img_urls)) {
  5097. $ref_img_urls = json_decode($ref_img_urls, true);
  5098. }else {
  5099. $ref_img_urls = explode(',', $ref_img_urls);
  5100. }
  5101. }
  5102. // 处理图片模型
  5103. $model = getProp($data, 'model');
  5104. if (!$model) {
  5105. // 用户没有输入,从episode表获取
  5106. if ($episode_id) {
  5107. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5108. $model = getProp($episode, 'image_model');
  5109. }
  5110. if (!$model) {
  5111. // episode表也没有,使用默认值
  5112. $model = 'doubao-seedream-5-0-lite-260128';
  5113. }
  5114. }
  5115. // 验证模型是否在可用模型表中
  5116. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5117. // $model = 'doubao-seedream-5-0-lite-260128';
  5118. Utils::throwError('20003:该模型已不可用,请更换!');
  5119. }
  5120. // 保存到episode表
  5121. if ($episode_id) {
  5122. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5123. 'image_model' => $model,
  5124. 'updated_at' => date('Y-m-d H:i:s')
  5125. ]);
  5126. }
  5127. // 参数验证
  5128. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5129. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5130. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5131. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5132. try {
  5133. // 创建图片生成任务
  5134. $params = [
  5135. 'prompt' => $prompt,
  5136. 'model' => $model,
  5137. 'ref_img_urls' => '',
  5138. 'width' => $width,
  5139. 'height' => $height,
  5140. 'image_num' => $imageNum
  5141. ];
  5142. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5143. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5144. $task_id = $task->id;
  5145. if (!$task_id) {
  5146. Utils::throwError('20003:创建图片生成任务失败');
  5147. }
  5148. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5149. $model = getProp($task, 'model');
  5150. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5151. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5152. $isSyncModel = $isVolcModel || $isGptModel;
  5153. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5154. $start_time = time();
  5155. $timeout = 300; // 5分钟
  5156. $img_url = '';
  5157. $img_urls = [];
  5158. while (time() - $start_time < $timeout) {
  5159. sleep(3);
  5160. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5161. if ($isSyncModel) {
  5162. // 刷新任务状态
  5163. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5164. if ($task->status === 'success' && $task->result_url) {
  5165. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5166. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5167. if (!empty($resultUrls)) {
  5168. $img_urls = $resultUrls;
  5169. $img_url = $resultUrls[0];
  5170. } else {
  5171. $img_url = (string)$task->result_url;
  5172. }
  5173. break;
  5174. } elseif ($task->status === 'failed') {
  5175. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5176. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5177. }
  5178. // // 如果还在处理中,提示用户稍后查看
  5179. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5180. }else {
  5181. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5182. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5183. if ($statusInfo['status'] === 'success') {
  5184. $task->updateStatus('success', [
  5185. 'result_url' => $statusInfo['result_url'],
  5186. 'result_json' => $statusInfo['result_json'] ?? []
  5187. ]);
  5188. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5189. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5190. if (!empty($resultUrls)) {
  5191. $img_urls = $resultUrls;
  5192. $img_url = $resultUrls[0];
  5193. } else {
  5194. $img_url = (string)$statusInfo['result_url'];
  5195. }
  5196. break;
  5197. } elseif ($statusInfo['status'] === 'failed') {
  5198. $task->updateStatus('failed', [
  5199. 'error_message' => $statusInfo['error_message'],
  5200. 'result_json' => $statusInfo['result_json'] ?? []
  5201. ]);
  5202. dLog('anime')->error('图片生成失败,', [
  5203. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5204. ]);
  5205. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5206. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5207. }
  5208. }
  5209. }
  5210. if (empty($img_url)) {
  5211. Utils::throwError('20003:图片生成超时,请稍后重试');
  5212. }
  5213. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5214. if (count($img_urls) > 1) {
  5215. return [
  5216. 'img_url' => $img_url,
  5217. 'image_urls' => $img_urls
  5218. ];
  5219. }
  5220. return $img_url;
  5221. } catch (\Exception $e) {
  5222. dLog('anime')->error('更新角色或场景失败', [
  5223. 'error' => $e->getMessage()
  5224. ]);
  5225. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5226. Utils::throwError('20003:' . $e->getMessage());
  5227. }
  5228. }
  5229. /**
  5230. * 使用文生文模型解析分镜内容
  5231. */
  5232. private function parseSegmentContentWithAI($segment_content) {
  5233. try {
  5234. // 使用DeepSeek服务的公开方法解析分镜内容
  5235. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5236. } catch (\Exception $e) {
  5237. // 如果AI解析失败,记录日志并返回原内容
  5238. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5239. return $segment_content;
  5240. }
  5241. }
  5242. /**
  5243. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5244. *
  5245. * @param int $episode_id 分集ID
  5246. * @param int $anime_id 动漫ID
  5247. * @param array $roles 分集角色数组(引用传递)
  5248. * @param array $scenes 分集场景数组(引用传递)
  5249. * @param array $episode 分集数据
  5250. */
  5251. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5252. // 获取全局动漫的角色和场景数据
  5253. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5254. if (!$anime) return;
  5255. $art_style_type = getProp($anime, 'art_style_type');
  5256. $character_prefix = '';
  5257. $scene_prefix = '';
  5258. if ($art_style_type) {
  5259. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5260. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5261. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5262. }
  5263. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5264. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5265. $roles_updated = false;
  5266. $scenes_updated = false;
  5267. // 处理角色
  5268. foreach ($roles as &$role) {
  5269. $role_name = getProp($role, 'role');
  5270. $role_description = getProp($role, 'description');
  5271. $role_pic_prompt = getProp($role, 'pic_prompt');
  5272. $role_url = getProp($role, 'url');
  5273. $role_task_id = getProp($role, 'task_id');
  5274. // 如果已有URL或已有任务ID,跳过
  5275. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5276. continue;
  5277. }
  5278. $url_inherited = false;
  5279. // 尝试从全局数据中继承
  5280. foreach ($global_roles as $global_role) {
  5281. $global_role_name = getProp($global_role, 'role');
  5282. $global_role_description = getProp($global_role, 'description');
  5283. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5284. $global_role_url = getProp($global_role, 'url');
  5285. $global_role_task_id = getProp($global_role, 'task_id');
  5286. $global_role_task_status = getProp($global_role, 'task_status');
  5287. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5288. if ($role_name === $global_role_name
  5289. && $role_description === $global_role_description
  5290. && $role_pic_prompt === $global_role_pic_prompt
  5291. && !empty($global_role_url)) {
  5292. // 继承 task_id、task_status 和 url
  5293. $role['task_id'] = $global_role_task_id;
  5294. $role['task_status'] = $global_role_task_status;
  5295. $role['url'] = $global_role_url;
  5296. $roles_updated = true;
  5297. $url_inherited = true;
  5298. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5299. break;
  5300. }
  5301. }
  5302. // 如果无法继承且没有任务ID,创建新任务
  5303. if (!$url_inherited && empty($role_task_id)) {
  5304. try {
  5305. $art_style = getProp($episode, 'art_style');
  5306. // 优先使用 pic_prompt,如果没有则使用 description
  5307. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5308. // if ($art_style) {
  5309. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5310. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5311. // }
  5312. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5313. $params = [
  5314. 'prompt' => $description,
  5315. 'ref_img_urls' => []
  5316. ];
  5317. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5318. $task_id = $task->id;
  5319. if ($task_id) {
  5320. $role['task_id'] = $task_id;
  5321. $role['task_status'] = 'processing';
  5322. $roles_updated = true;
  5323. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5324. }
  5325. } catch (\Exception $e) {
  5326. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5327. }
  5328. }
  5329. }
  5330. // 处理场景
  5331. foreach ($scenes as &$scene) {
  5332. $scene_name = getProp($scene, 'scene');
  5333. $scene_description = getProp($scene, 'description');
  5334. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5335. $scene_url = getProp($scene, 'url');
  5336. $scene_task_id = getProp($scene, 'task_id');
  5337. // 如果已有URL或已有任务ID,跳过
  5338. if (!empty($scene_url) || !empty($scene_task_id)) {
  5339. continue;
  5340. }
  5341. $url_inherited = false;
  5342. // 尝试从全局数据中继承
  5343. foreach ($global_scenes as $global_scene) {
  5344. $global_scene_name = getProp($global_scene, 'scene');
  5345. $global_scene_description = getProp($global_scene, 'description');
  5346. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5347. $global_scene_url = getProp($global_scene, 'url');
  5348. $global_scene_task_id = getProp($global_scene, 'task_id');
  5349. $global_scene_task_status = getProp($global_scene, 'task_status');
  5350. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5351. if ($scene_name === $global_scene_name
  5352. && $scene_description === $global_scene_description
  5353. && $scene_pic_prompt === $global_scene_pic_prompt
  5354. && !empty($global_scene_url)) {
  5355. // 继承 task_id、task_status 和 url
  5356. $scene['task_id'] = $global_scene_task_id;
  5357. $scene['task_status'] = $global_scene_task_status;
  5358. $scene['url'] = $global_scene_url;
  5359. $scenes_updated = true;
  5360. $url_inherited = true;
  5361. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5362. break;
  5363. }
  5364. }
  5365. // 如果无法继承且没有任务ID,创建新任务
  5366. if (!$url_inherited && empty($scene_task_id)) {
  5367. try {
  5368. $art_style = getProp($episode, 'art_style');
  5369. // 优先使用 pic_prompt,如果没有则使用 description
  5370. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5371. // if ($art_style) {
  5372. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5373. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5374. // }
  5375. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5376. $params = [
  5377. 'prompt' => $description,
  5378. 'ref_img_urls' => []
  5379. ];
  5380. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5381. $task_id = $task->id;
  5382. if ($task_id) {
  5383. $scene['task_id'] = $task_id;
  5384. $scene['task_status'] = 'processing';
  5385. $scenes_updated = true;
  5386. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5387. }
  5388. } catch (\Exception $e) {
  5389. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5390. }
  5391. }
  5392. }
  5393. // 如果有更新,保存到数据库
  5394. if ($roles_updated || $scenes_updated) {
  5395. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5396. if ($roles_updated) {
  5397. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5398. }
  5399. if ($scenes_updated) {
  5400. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5401. }
  5402. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5403. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5404. }
  5405. }
  5406. /**
  5407. * 根据图片URL使用AI反推图片提示词
  5408. *
  5409. * @param string $img_url 图片URL
  5410. * @return string 反推的提示词
  5411. */
  5412. private function generateImagePromptFromUrl($img_url) {
  5413. try {
  5414. // 获取默认模型
  5415. $model = 'doubao-seed-2-0-mini-260215';
  5416. // 构建messages参数
  5417. $messages = [
  5418. [
  5419. 'role' => 'user',
  5420. 'content' => [
  5421. [
  5422. 'type' => 'text',
  5423. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5424. ],
  5425. [
  5426. 'type' => 'image_url',
  5427. 'image_url' => [
  5428. 'url' => $img_url
  5429. ]
  5430. ]
  5431. ]
  5432. ]
  5433. ];
  5434. // 构建请求参数
  5435. $params = [
  5436. 'model' => $model,
  5437. 'messages' => $messages,
  5438. 'stream' => false,
  5439. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5440. ];
  5441. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5442. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5443. // 返回生成的内容
  5444. return getProp($result, 'fullContent', '图片描述生成失败');
  5445. } catch (\Exception $e) {
  5446. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5447. 'img_url' => $img_url
  5448. ]);
  5449. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5450. 'error' => $e->getMessage(),
  5451. 'img_url' => $img_url
  5452. ]);
  5453. return '图片描述生成失败: ' . $e->getMessage();
  5454. }
  5455. }
  5456. /**
  5457. * 音频试听接口
  5458. * 创建音频任务并轮询获取结果
  5459. *
  5460. * @param array $data 参数数组
  5461. * @return array 返回音频URL或错误信息
  5462. */
  5463. public function previewAudio($data) {
  5464. $dialogue = getProp($data, 'dialogue');
  5465. // 必填参数验证
  5466. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5467. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5468. $voice_type = getProp($data, 'voice_type');
  5469. $voice_name = getProp($data, 'voice_name');
  5470. $voice_actor = getProp($data, 'voice_actor');
  5471. $emotion_type = getProp($data, 'emotion_type');
  5472. $gender = getProp($data, 'gender', 0);
  5473. $emotion = getProp($data, 'emotion');
  5474. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5475. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5476. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5477. $pitch = getProp($data, 'pitch', 0);
  5478. try {
  5479. $now = date('Y-m-d H:i:s');
  5480. // 构建生成参数
  5481. $generate_json = json_encode([
  5482. 'text' => $dialogue,
  5483. 'role' => $voice_actor,
  5484. 'voice_type' => $voice_type,
  5485. 'voice_name' => $voice_name,
  5486. 'emotion' => $emotion,
  5487. 'emotion_type' => $emotion_type,
  5488. 'gender' => $gender,
  5489. 'speed_ratio' => $speed_ratio,
  5490. 'loudness_ratio' => $loudness_ratio,
  5491. 'emotion_scale' => $emotion_scale,
  5492. 'pitch' => $pitch,
  5493. ], 256);
  5494. // 请求远程服务器执行生成
  5495. $client = new Client(['timeout' => 600, 'verify' => false]);
  5496. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5497. $response = $result->getBody()->getContents();
  5498. $response_arr = json_decode($response, true);
  5499. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5500. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5501. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5502. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5503. }
  5504. $arr = $response_arr['data'];
  5505. $subtitle_info = $arr['subtitle_info'];
  5506. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5507. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5508. return [
  5509. 'audio_url' => $arr['url'],
  5510. 'subtitle_info' => $subtitle_info,
  5511. 'audio_duration' => round($audio_duration, 2)
  5512. ];
  5513. } catch (\Exception $e) {
  5514. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5515. Utils::throwError('20003:' . $e->getMessage());
  5516. }
  5517. }
  5518. /**
  5519. * 获取角色库列表(支持文件夹递归查询)
  5520. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5521. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5522. */
  5523. public function globalProducts($data) {
  5524. $uid = Site::getUid();
  5525. $cpid = Site::getCpid();
  5526. $role = Site::getRole();
  5527. $id = getProp($data, 'id', 0);
  5528. $parent_id = getProp($data, 'parent_id', 0);
  5529. $product_name = getProp($data, 'product_name');
  5530. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5531. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5532. if (!$product) {
  5533. Utils::throwError('20003:请选择产品类型');
  5534. }
  5535. // 根据角色和is_public参数确定查询范围
  5536. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5537. // user角色:根据is_public参数筛选
  5538. $query_user_ids = [];
  5539. if ($role === 'admin') {
  5540. // admin获取所有个人库和公共库
  5541. $query_user_ids = [$uid, 0];
  5542. } else {
  5543. // user角色根据is_public参数筛选
  5544. if ($is_public == 2) {
  5545. // 个人库+公共库
  5546. $query_user_ids = [$uid, 0];
  5547. } elseif ($is_public == 0) {
  5548. // 仅个人库
  5549. $query_user_ids = [$uid];
  5550. } elseif ($is_public == 1) {
  5551. // 仅公共库
  5552. $query_user_ids = [0];
  5553. }
  5554. }
  5555. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5556. if ($id || $product_name) {
  5557. $query = DB::table('mp_products')
  5558. ->where('cpid', $cpid)
  5559. ->whereIn('user_id', $query_user_ids)
  5560. ->where('is_deleted', 0);
  5561. // 如果指定了 id,按 id 精确查询
  5562. if ($id) {
  5563. $query->where('id', $id);
  5564. }
  5565. // 如果指定了 product_name,按名称模糊查询
  5566. if ($product_name) {
  5567. $query->where('product_name', 'like', "%{$product_name}%");
  5568. }
  5569. // 如果指定了 product,添加筛选条件
  5570. if ($product) {
  5571. $query->where('product', $product);
  5572. }
  5573. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5574. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5575. ->get()
  5576. ->map(function($value) {
  5577. $value = (array)$value;
  5578. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5579. $value['type'] = (int)$value['type'];
  5580. $value['parent_id'] = (int)$value['parent_id'];
  5581. $value['level'] = (int)$value['level'];
  5582. $value['product'] = (int)($value['product'] ?? 1);
  5583. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5584. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5585. unset($value['user_id']);
  5586. return $value;
  5587. })
  5588. ->toArray();
  5589. return $result;
  5590. }
  5591. // 递归获取所有子目录和角色
  5592. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5593. }
  5594. /**
  5595. * 递归获取指定目录下的所有子目录和角色
  5596. * @param int $cpid 公司ID
  5597. * @param int $parent_id 父目录ID
  5598. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5599. * @param array $query_user_ids 用户ID数组(支持多个)
  5600. * @param int $current_uid 当前用户ID(用于排序)
  5601. * @return array
  5602. */
  5603. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5604. // 查询当前层级的所有项(文件夹和角色)
  5605. $query = DB::table('mp_products')
  5606. ->where('cpid', $cpid)
  5607. ->where('is_deleted', 0)
  5608. ->where('parent_id', $parent_id);
  5609. // 添加用户ID验证(支持多个user_id)
  5610. if (!empty($query_user_ids)) {
  5611. $query->whereIn('user_id', $query_user_ids);
  5612. }
  5613. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5614. if ($product) {
  5615. $query->where('product', $product);
  5616. }
  5617. // 排序规则:
  5618. // 1. 文件夹在前(type DESC)
  5619. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5620. // 3. 其他排序规则
  5621. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5622. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5623. ->get();
  5624. $result = [];
  5625. foreach ($items as $item) {
  5626. $itemArray = [
  5627. 'id' => $item->id,
  5628. 'type' => (int)$item->type,
  5629. 'parent_id' => (int)$item->parent_id,
  5630. 'level' => (int)$item->level,
  5631. 'product_name' => $item->product_name,
  5632. 'url' => $item->url,
  5633. 'pic_prompt' => $item->pic_prompt ?? '',
  5634. 'three_view_image_url' => $item->three_view_image_url,
  5635. 'product' => (int)($item->product ?? 1),
  5636. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5637. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5638. ];
  5639. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5640. // 如果是文件夹,递归获取其子项
  5641. if ($item->type == 2) {
  5642. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5643. if (!empty($children)) {
  5644. $itemArray['children'] = $children;
  5645. }
  5646. }
  5647. $result[] = $itemArray;
  5648. }
  5649. return $result;
  5650. }
  5651. /**
  5652. * 创建文件夹
  5653. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5654. * @return int 返回新建文件夹ID
  5655. */
  5656. public function createFolder($data) {
  5657. $uid = Site::getUid();
  5658. $cpid = Site::getCpid();
  5659. $role = Site::getRole();
  5660. $parent_id = getProp($data, 'parent_id', 0);
  5661. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5662. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5663. // 如果是公共库操作,需要admin权限
  5664. if ($is_public && $role !== 'admin') {
  5665. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5666. }
  5667. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5668. $store_uid = $is_public ? 0 : $uid;
  5669. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5670. $product = getProp($data, 'product');
  5671. if (!in_array($product, [1, 2, 3])) {
  5672. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5673. }
  5674. // 验证父文件夹
  5675. $parent_level = 0;
  5676. if ($parent_id > 0) {
  5677. $parent = DB::table('mp_products')
  5678. ->where('id', $parent_id)
  5679. ->where('cpid', $cpid)
  5680. ->where('user_id', $store_uid)
  5681. ->where('type', 2)
  5682. ->where('is_deleted', 0)
  5683. ->first();
  5684. if (!$parent) {
  5685. Utils::throwError('20003:父文件夹不存在');
  5686. }
  5687. // 检查父文件夹的 product 类型是否一致
  5688. if ($parent->product != $product) {
  5689. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5690. }
  5691. $parent_level = $parent->level;
  5692. // 检查层级限制(最多3层)
  5693. if ($parent_level >= 3) {
  5694. Utils::throwError('20003:文件夹层级不能超过3层');
  5695. }
  5696. }
  5697. // 检查当前目录下是否已存在空白文件夹
  5698. $empty_folder_exists = DB::table('mp_products')
  5699. ->where('parent_id', $parent_id)
  5700. ->where('cpid', $cpid)
  5701. ->where('user_id', $store_uid)
  5702. ->where('type', 2)
  5703. ->where('product', $product)
  5704. ->where('product_name', '新建文件夹')
  5705. ->where('is_deleted', 0)
  5706. ->exists();
  5707. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5708. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5709. }
  5710. // 创建文件夹
  5711. $folder_id = DB::table('mp_products')->insertGetId([
  5712. 'user_id' => $store_uid,
  5713. 'cpid' => $cpid,
  5714. 'type' => 2,
  5715. 'parent_id' => $parent_id,
  5716. 'level' => $parent_level + 1,
  5717. 'product_name' => $folder_name,
  5718. 'product' => $product,
  5719. 'sort_order' => time(), // 使用时间戳作为排序权重
  5720. 'is_deleted' => 0,
  5721. 'created_at' => date('Y-m-d H:i:s'),
  5722. 'updated_at' => date('Y-m-d H:i:s')
  5723. ]);
  5724. return [
  5725. 'id' => $folder_id,
  5726. 'type' => 2,
  5727. 'parent_id' => $parent_id,
  5728. 'level' => $parent_level + 1,
  5729. 'product_name' => $folder_name,
  5730. 'product' => $product,
  5731. ];
  5732. }
  5733. /**
  5734. * 重命名文件夹或角色
  5735. * @param array $data 包含 id、product_name(新名称)
  5736. * @return bool
  5737. */
  5738. public function renameFolder($data) {
  5739. $uid = Site::getUid();
  5740. $cpid = Site::getCpid();
  5741. $role = Site::getRole();
  5742. $id = getProp($data, 'id');
  5743. $new_name = getProp($data, 'product_name');
  5744. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5745. if (!$id || !$new_name) {
  5746. Utils::throwError('20003:参数不完整');
  5747. }
  5748. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5749. $query_uid = $is_public ? 0 : $uid;
  5750. // 如果是公共库操作,需要admin权限
  5751. if ($is_public && $role !== 'admin') {
  5752. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5753. }
  5754. // 检查是否存在
  5755. $item = DB::table('mp_products')
  5756. ->where('id', $id)
  5757. ->where('cpid', $cpid)
  5758. ->where('user_id', $query_uid)
  5759. ->where('is_deleted', 0)
  5760. ->first();
  5761. if (!$item) {
  5762. Utils::throwError('20003:项目不存在');
  5763. }
  5764. return DB::table('mp_products')
  5765. ->where('id', $id)
  5766. ->where('cpid', $cpid)
  5767. ->where('user_id', $query_uid)
  5768. ->update([
  5769. 'product_name' => $new_name,
  5770. 'updated_at' => date('Y-m-d H:i:s')
  5771. ]);
  5772. }
  5773. /**
  5774. * 移动角色或文件夹到指定文件夹
  5775. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5776. * @return bool
  5777. */
  5778. public function moveProductOrFolder($data) {
  5779. $uid = Site::getUid();
  5780. $cpid = Site::getCpid();
  5781. $role = Site::getRole();
  5782. $id = getProp($data, 'id');
  5783. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5784. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5785. if (!$id) {
  5786. Utils::throwError('20003:请选择要移动的项目');
  5787. }
  5788. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5789. $query_uid = $is_public ? 0 : $uid;
  5790. // 如果是公共库操作,需要admin权限
  5791. if ($is_public && $role !== 'admin') {
  5792. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5793. }
  5794. // 检查要移动的项目
  5795. $item = DB::table('mp_products')
  5796. ->where('id', $id)
  5797. ->where('cpid', $cpid)
  5798. ->where('user_id', $query_uid)
  5799. ->where('is_deleted', 0)
  5800. ->first();
  5801. if (!$item) {
  5802. Utils::throwError('20003:项目不存在');
  5803. }
  5804. // 验证目标文件夹
  5805. $target_level = 0;
  5806. $target_product = $item->product; // 默认使用当前项目的 product
  5807. if ($target_parent_id > 0) {
  5808. $target_parent = DB::table('mp_products')
  5809. ->where('id', $target_parent_id)
  5810. ->where('cpid', $cpid)
  5811. ->where('user_id', $query_uid)
  5812. ->where('type', 2)
  5813. ->where('is_deleted', 0)
  5814. ->first();
  5815. if (!$target_parent) {
  5816. Utils::throwError('20003:目标文件夹不存在');
  5817. }
  5818. // 检查 product 类型是否一致
  5819. if ($target_parent->product != $item->product) {
  5820. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5821. }
  5822. $target_level = $target_parent->level;
  5823. $target_product = $target_parent->product;
  5824. // 如果移动的是文件夹,需要检查层级
  5825. if ($item->type == 2) {
  5826. // 计算移动后的最大层级
  5827. $max_child_level = $this->getMaxChildLevel($id);
  5828. $depth = $max_child_level - $item->level;
  5829. if ($target_level + 1 + $depth > 3) {
  5830. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5831. }
  5832. // 不能移动到自己或自己的子文件夹下
  5833. if ($this->isDescendant($target_parent_id, $id)) {
  5834. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5835. }
  5836. }
  5837. }
  5838. // 更新父文件夹和层级
  5839. $new_level = $target_level + 1;
  5840. DB::table('mp_products')
  5841. ->where('id', $id)
  5842. ->update([
  5843. 'parent_id' => $target_parent_id,
  5844. 'level' => $new_level,
  5845. 'updated_at' => date('Y-m-d H:i:s')
  5846. ]);
  5847. // 如果是文件夹,需要递归更新所有子项的层级
  5848. if ($item->type == 2) {
  5849. $this->updateChildrenLevel($id, $new_level);
  5850. }
  5851. return true;
  5852. }
  5853. /**
  5854. * 获取文件夹下最大子层级
  5855. * @param int $folder_id
  5856. * @return int
  5857. */
  5858. private function getMaxChildLevel($folder_id) {
  5859. $max_level = DB::table('mp_products')
  5860. ->where('parent_id', $folder_id)
  5861. ->where('is_deleted', 0)
  5862. ->max('level');
  5863. if (!$max_level) {
  5864. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5865. }
  5866. // 递归查找子文件夹
  5867. $children = DB::table('mp_products')
  5868. ->where('parent_id', $folder_id)
  5869. ->where('type', 2)
  5870. ->where('is_deleted', 0)
  5871. ->pluck('id');
  5872. foreach ($children as $child_id) {
  5873. $child_max = $this->getMaxChildLevel($child_id);
  5874. if ($child_max > $max_level) {
  5875. $max_level = $child_max;
  5876. }
  5877. }
  5878. return $max_level;
  5879. }
  5880. /**
  5881. * 检查 target_id 是否是 folder_id 的后代
  5882. * @param int $target_id
  5883. * @param int $folder_id
  5884. * @return bool
  5885. */
  5886. private function isDescendant($target_id, $folder_id) {
  5887. if ($target_id == $folder_id) {
  5888. return true;
  5889. }
  5890. $parent = DB::table('mp_products')
  5891. ->where('id', $target_id)
  5892. ->where('is_deleted', 0)
  5893. ->first();
  5894. if (!$parent || $parent->parent_id == 0) {
  5895. return false;
  5896. }
  5897. return $this->isDescendant($parent->parent_id, $folder_id);
  5898. }
  5899. /**
  5900. * 递归更新子项层级
  5901. * @param int $parent_id
  5902. * @param int $parent_level
  5903. */
  5904. private function updateChildrenLevel($parent_id, $parent_level) {
  5905. $children = DB::table('mp_products')
  5906. ->where('parent_id', $parent_id)
  5907. ->where('is_deleted', 0)
  5908. ->get();
  5909. foreach ($children as $child) {
  5910. $new_level = $parent_level + 1;
  5911. DB::table('mp_products')
  5912. ->where('id', $child->id)
  5913. ->update([
  5914. 'level' => $new_level,
  5915. 'updated_at' => date('Y-m-d H:i:s')
  5916. ]);
  5917. // 如果是文件夹,继续递归
  5918. if ($child->type == 2) {
  5919. $this->updateChildrenLevel($child->id, $new_level);
  5920. }
  5921. }
  5922. }
  5923. /**
  5924. * 获取文件夹路径(面包屑导航)
  5925. * @param array $data 包含 folder_id
  5926. * @return array 返回路径数组
  5927. */
  5928. public function getFolderPath($data) {
  5929. $uid = Site::getUid();
  5930. $cpid = Site::getCpid();
  5931. $folder_id = getProp($data, 'id', 0);
  5932. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5933. if ($folder_id == 0) {
  5934. return [
  5935. ['id' => 0, 'name' => '根目录']
  5936. ];
  5937. }
  5938. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5939. $query_uid = $is_public ? 0 : $uid;
  5940. $path = [];
  5941. $current_id = $folder_id;
  5942. while ($current_id > 0) {
  5943. $folder = DB::table('mp_products')
  5944. ->where('id', $current_id)
  5945. ->where('cpid', $cpid)
  5946. ->where('user_id', $query_uid)
  5947. ->where('type', 2)
  5948. ->where('is_deleted', 0)
  5949. ->first();
  5950. if (!$folder) {
  5951. break;
  5952. }
  5953. array_unshift($path, [
  5954. 'id' => $folder->id,
  5955. 'name' => $folder->product_name
  5956. ]);
  5957. $current_id = $folder->parent_id;
  5958. }
  5959. // 添加根目录
  5960. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5961. return $path;
  5962. }
  5963. public function createProduct($data) {
  5964. $uid = Site::getUid();
  5965. $cpid = Site::getCpid();
  5966. $role = Site::getRole();
  5967. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5968. // 如果是公共库操作,需要admin权限
  5969. if ($is_public && $role !== 'admin') {
  5970. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5971. }
  5972. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5973. $store_uid = $is_public ? 0 : $uid;
  5974. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  5975. $script_id = (int)getProp($data, 'script_id', 0);
  5976. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  5977. if ($script_id && empty($episode_numbers)) {
  5978. Utils::throwError('20003:剧集序号不能为空');
  5979. }
  5980. if (!$script_id && !empty($episode_numbers)) {
  5981. Utils::throwError('20003:请提供剧本ID');
  5982. }
  5983. $product_name = trim(getProp($data, 'product_name'));
  5984. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5985. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5986. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5987. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5988. $url = trim(getProp($data, 'url'));
  5989. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5990. $versions = getProp($data, 'versions');
  5991. // 检查是否是正确的图片格式
  5992. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5993. $urlPath = parse_url($url, PHP_URL_PATH);
  5994. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5995. if (!in_array($extension, $allowedExtensions)) {
  5996. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5997. }
  5998. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5999. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6000. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6001. $product = getProp($data, 'product');
  6002. if (!in_array($product, [1, 2, 3])) {
  6003. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6004. }
  6005. // 获取父文件夹ID和层级
  6006. $parent_id = getProp($data, 'parent_id', 0);
  6007. $parent_level = 0;
  6008. if ($parent_id > 0) {
  6009. $parent = DB::table('mp_products')
  6010. ->where('id', $parent_id)
  6011. ->where('cpid', $cpid)
  6012. ->where('user_id', $store_uid)
  6013. ->where('type', 2)
  6014. ->where('is_deleted', 0)
  6015. ->first();
  6016. if (!$parent) {
  6017. Utils::throwError('20003:父文件夹不存在');
  6018. }
  6019. $parent_level = $parent->level;
  6020. }
  6021. // 创建资产并保存剧本资产关联关系(同一事务)
  6022. DB::beginTransaction();
  6023. try {
  6024. $id = DB::table('mp_products')->insertGetId([
  6025. 'user_id' => $store_uid,
  6026. 'cpid' => $cpid,
  6027. 'type' => 1, // 1=角色图片
  6028. 'parent_id' => $parent_id,
  6029. 'level' => $parent_level + 1,
  6030. 'product_name' => $product_name,
  6031. 'url' => $url,
  6032. 'pic_prompt' => $pic_prompt,
  6033. 'product' => $product,
  6034. 'versions' => json_encode($versions, 256),
  6035. 'sort_order' => time(), // 使用时间戳作为排序权重
  6036. 'created_at' => date('Y-m-d H:i:s'),
  6037. 'updated_at' => date('Y-m-d H:i:s')
  6038. ]);
  6039. if (!$id) Utils::throwError('20003:创建失败');
  6040. // 保存剧本资产关联关系
  6041. if ($script_id) {
  6042. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6043. }
  6044. DB::commit();
  6045. } catch (\Exception $e) {
  6046. DB::rollback();
  6047. throw $e;
  6048. }
  6049. return [
  6050. 'id' => $id,
  6051. 'type' => 1,
  6052. 'parent_id' => $parent_id,
  6053. 'level' => $parent_level + 1,
  6054. 'product_name' => $product_name,
  6055. 'url' => $url,
  6056. 'pic_prompt' => $pic_prompt,
  6057. 'product' => $product,
  6058. 'versions' => $versions
  6059. ];
  6060. }
  6061. public function editProduct($data) {
  6062. $uid = Site::getUid();
  6063. $cpid = Site::getCpid();
  6064. $role = Site::getRole();
  6065. $id = getProp($data, 'id');
  6066. if (!$id) Utils::throwError('20003:ID不能为空');
  6067. $versions = getProp($data, 'versions');
  6068. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6069. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6070. $script_id = (int)getProp($data, 'script_id', 0);
  6071. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6072. if ($script_id && empty($episode_numbers)) {
  6073. Utils::throwError('20003:剧集序号不能为空');
  6074. }
  6075. if (!$script_id && !empty($episode_numbers)) {
  6076. Utils::throwError('20003:请提供剧本ID');
  6077. }
  6078. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6079. $query_uid = $is_public ? 0 : $uid;
  6080. // 如果是公共库操作,需要admin权限
  6081. if ($is_public && $role !== 'admin') {
  6082. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6083. }
  6084. // 检查是否存在且属于当前用户或公共库
  6085. $role = DB::table('mp_products')
  6086. ->where('id', $id)
  6087. ->where('cpid', $cpid)
  6088. ->where('user_id', $query_uid)
  6089. ->where('type', 1)->first();
  6090. if (!$role) Utils::throwError('20003:记录不存在');
  6091. $updateData = [];
  6092. // $needVersionRecord = false; // 是否需要记录版本
  6093. // 名称
  6094. $product_name = trim(getProp($data, 'product_name'));
  6095. if ($product_name) {
  6096. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6097. $updateData['product_name'] = $product_name;
  6098. }
  6099. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6100. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6101. // 图片地址
  6102. $url = trim(getProp($data, 'url'));
  6103. if ($url) {
  6104. // 检查是否是正确的图片格式
  6105. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6106. $urlPath = parse_url($url, PHP_URL_PATH);
  6107. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6108. if (!in_array($extension, $allowedExtensions)) {
  6109. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6110. }
  6111. // // 如果 url 有变更,记录版本
  6112. // if ($url !== $role->url) {
  6113. // $needVersionRecord = true;
  6114. // }
  6115. $updateData['url'] = $url;
  6116. }
  6117. // 提示词
  6118. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6119. if ($pic_prompt) {
  6120. // // 如果 pic_prompt 有变更,记录版本
  6121. // if ($pic_prompt !== $role->pic_prompt) {
  6122. // $needVersionRecord = true;
  6123. // }
  6124. $updateData['pic_prompt'] = $pic_prompt;
  6125. }
  6126. if (empty($updateData) && !$script_id) {
  6127. Utils::throwError('20003:没有需要更新的数据');
  6128. }
  6129. // // 如果需要记录版本,将数据添加到 versions 数组
  6130. // if ($needVersionRecord) {
  6131. // // 获取现有的 versions 数据
  6132. // $versions = json_decode($role->versions, true) ?: [];
  6133. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6134. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6135. // if ($isFirstVersion) {
  6136. // $oldVersion = [
  6137. // 'url' => $role->url,
  6138. // 'description' => $role->pic_prompt,
  6139. // ];
  6140. // // 旧版本添加到数组末尾
  6141. // $versions[] = $oldVersion;
  6142. // }
  6143. // // 构建新版本(变更后)
  6144. // $newVersion = [
  6145. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6146. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6147. // ];
  6148. // // 检查新版本是否已存在于历史版本中
  6149. // $existingIndex = -1;
  6150. // foreach ($versions as $index => $version) {
  6151. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6152. // $existingIndex = $index;
  6153. // break;
  6154. // }
  6155. // }
  6156. // if ($existingIndex !== -1) {
  6157. // // 如果已存在,移除旧的位置
  6158. // array_splice($versions, $existingIndex, 1);
  6159. // }
  6160. // // 新版本添加到数组开头(最新的在前)
  6161. // array_unshift($versions, $newVersion);
  6162. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6163. // // if (count($versions) > 10) {
  6164. // // $versions = array_slice($versions, 0, 10);
  6165. // // }
  6166. // $updateData['versions'] = json_encode($versions, 256);
  6167. // }
  6168. if ($versions) {
  6169. $updateData['versions'] = json_encode($versions, 256);
  6170. }
  6171. if (!empty($updateData)) {
  6172. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6173. }
  6174. // 更新资产并保存剧本资产关联关系(同一事务)
  6175. DB::beginTransaction();
  6176. try {
  6177. $updated = true;
  6178. if (!empty($updateData)) {
  6179. $updated = DB::table('mp_products')
  6180. ->where('cpid', $cpid)
  6181. ->where('id', $id)
  6182. ->update($updateData);
  6183. }
  6184. // 保存剧本资产关联关系
  6185. if ($script_id) {
  6186. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6187. }
  6188. DB::commit();
  6189. } catch (\Exception $e) {
  6190. DB::rollback();
  6191. throw $e;
  6192. }
  6193. return $updated;
  6194. }
  6195. /**
  6196. * 保存单一资产与剧本剧集的关联关系
  6197. *
  6198. * @param int $product_id 资产ID
  6199. * @param int $script_id 剧本ID
  6200. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6201. * @return int 新增关联数量
  6202. */
  6203. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6204. $uid = Site::getUid();
  6205. // 验证剧本是否存在
  6206. $script = DB::table('mp_scripts')
  6207. ->where('id', $script_id)
  6208. ->where('is_deleted', 0)
  6209. ->first();
  6210. if (!$script) {
  6211. Utils::throwError('20003:剧本不存在');
  6212. }
  6213. // 验证剧本归属:只能关联自己的剧本
  6214. if ((int)$script->user_id !== (int)$uid) {
  6215. Utils::throwError('20003:只能添加到自己的剧本');
  6216. }
  6217. // 使用 splitContent 拆分剧本内容获取总集数
  6218. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6219. // 解析剧集序号(数组)
  6220. $episodes = [];
  6221. foreach ($episode_numbers as $item) {
  6222. if (is_array($item)) {
  6223. continue;
  6224. }
  6225. $item = trim((string)$item);
  6226. if ($item === '' || !is_numeric($item)) {
  6227. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6228. }
  6229. $episodes[] = (int)$item;
  6230. }
  6231. // 去重并校验序号范围(序号从1开始)
  6232. $episodes = array_values(array_unique($episodes));
  6233. if (empty($episodes)) {
  6234. Utils::throwError('20003:剧集序号不能为空');
  6235. }
  6236. foreach ($episodes as $episode) {
  6237. if ($episode < 1 || $episode > $totalEpisodes) {
  6238. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6239. }
  6240. }
  6241. $now = now();
  6242. // 过滤已存在的关联,避免重复
  6243. $existingEpisodes = DB::table('mp_script_product_mappings')
  6244. ->where('script_id', $script_id)
  6245. ->where('product_id', $product_id)
  6246. ->whereIn('episode_number', $episodes)
  6247. ->pluck('episode_number')
  6248. ->all();
  6249. $mappingRecords = [];
  6250. foreach ($episodes as $episode) {
  6251. if (in_array($episode, $existingEpisodes)) {
  6252. continue;
  6253. }
  6254. $mappingRecords[] = [
  6255. 'script_id' => $script_id,
  6256. 'product_id' => $product_id,
  6257. 'episode_number' => $episode,
  6258. 'created_at' => $now,
  6259. 'updated_at' => $now,
  6260. ];
  6261. }
  6262. $insertedCount = 0;
  6263. if (!empty($mappingRecords)) {
  6264. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6265. }
  6266. return $insertedCount;
  6267. }
  6268. /**
  6269. * 规范化剧集序号参数,统一为数组
  6270. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6271. *
  6272. * @param mixed $episode_number 剧集序号参数
  6273. * @return array
  6274. */
  6275. private function normalizeEpisodeNumbers($episode_number) {
  6276. if (!is_array($episode_number)) {
  6277. $episode_number = explode(',', (string)$episode_number);
  6278. }
  6279. $items = [];
  6280. foreach ($episode_number as $item) {
  6281. if (is_array($item)) {
  6282. continue;
  6283. }
  6284. foreach (explode(',', (string)$item) as $part) {
  6285. $part = trim($part);
  6286. if ($part !== '') {
  6287. $items[] = $part;
  6288. }
  6289. }
  6290. }
  6291. return $items;
  6292. }
  6293. /**
  6294. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6295. *
  6296. * @param object $script 剧本记录
  6297. * @return int 总集数
  6298. */
  6299. private function getScriptTotalEpisodeCount($script) {
  6300. if (empty($script->content)) {
  6301. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6302. }
  6303. $totalEpisodes = count(splitContent($script->content));
  6304. if ($totalEpisodes < 1) {
  6305. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6306. }
  6307. return $totalEpisodes;
  6308. }
  6309. /**
  6310. * 获取剧本总集数
  6311. *
  6312. * @param array $data 包含 script_id(剧本ID)
  6313. * @return array
  6314. */
  6315. public function getScriptTotalEpisodes($data) {
  6316. $script_id = (int)getProp($data, 'script_id', 0);
  6317. if (!$script_id) {
  6318. Utils::throwError('20003:请提供剧本ID');
  6319. }
  6320. // 验证剧本是否存在
  6321. $script = DB::table('mp_scripts')
  6322. ->where('id', $script_id)
  6323. ->where('is_deleted', 0)
  6324. ->first();
  6325. if (!$script) {
  6326. Utils::throwError('20003:剧本不存在');
  6327. }
  6328. return [
  6329. 'script_id' => $script_id,
  6330. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6331. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6332. ];
  6333. }
  6334. /**
  6335. * 获取角色版本历史
  6336. * @param array $data 包含 id(角色ID)
  6337. * @return array 返回版本历史列表
  6338. */
  6339. public function getProductVersions($data) {
  6340. $cpid = Site::getCpid();
  6341. $id = getProp($data, 'id');
  6342. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6343. $role = DB::table('mp_products')
  6344. ->where('id', $id)
  6345. ->where('cpid', $cpid)
  6346. ->where('type', 1)
  6347. ->first();
  6348. if (!$role) Utils::throwError('20003:角色不存在');
  6349. // 获取版本历史
  6350. $versions = json_decode($role->versions, true) ?: [];
  6351. // 添加当前版本作为最新版本
  6352. $currentVersion = [
  6353. 'version' => 0, // 0 表示当前版本
  6354. 'url' => $role->url,
  6355. 'pic_prompt' => $role->pic_prompt,
  6356. 'updated_at' => $role->updated_at,
  6357. 'is_current' => true
  6358. ];
  6359. array_unshift($versions, $currentVersion);
  6360. return $versions;
  6361. }
  6362. /**
  6363. * 恢复到指定版本
  6364. * @param array $data 包含 id(角色ID)、version(版本号)
  6365. * @return bool
  6366. */
  6367. public function restoreProductVersion($data) {
  6368. $uid = Site::getUid();
  6369. $cpid = Site::getCpid();
  6370. $id = getProp($data, 'id');
  6371. $version = getProp($data, 'version');
  6372. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6373. if (!$version) Utils::throwError('20003:版本号不能为空');
  6374. $role = DB::table('mp_products')
  6375. ->where('id', $id)
  6376. ->where('cpid', $cpid)
  6377. ->where('type', 1)
  6378. ->first();
  6379. if (!$role) Utils::throwError('20003:角色不存在');
  6380. // 获取版本历史
  6381. $versions = json_decode($role->versions, true) ?: [];
  6382. // 查找指定版本
  6383. $targetVersion = null;
  6384. foreach ($versions as $v) {
  6385. if ($v['version'] == $version) {
  6386. $targetVersion = $v;
  6387. break;
  6388. }
  6389. }
  6390. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6391. // 先将当前版本保存到历史
  6392. $newVersion = [
  6393. 'version' => count($versions) + 1,
  6394. 'url' => $role->url,
  6395. 'pic_prompt' => $role->pic_prompt,
  6396. 'updated_at' => date('Y-m-d H:i:s'),
  6397. 'updated_by' => $uid
  6398. ];
  6399. array_unshift($versions, $newVersion);
  6400. // 限制版本数量
  6401. if (count($versions) > 10) {
  6402. $versions = array_slice($versions, 0, 10);
  6403. }
  6404. // 恢复到指定版本
  6405. return DB::table('mp_products')
  6406. ->where('id', $id)
  6407. ->where('cpid', $cpid)
  6408. ->update([
  6409. 'url' => $targetVersion['url'],
  6410. 'pic_prompt' => $targetVersion['pic_prompt'],
  6411. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6412. 'updated_at' => date('Y-m-d H:i:s')
  6413. ]);
  6414. }
  6415. public function deleteProduct($data) {
  6416. $uid = Site::getUid();
  6417. $cpid = Site::getCpid();
  6418. $role = Site::getRole();
  6419. $id = getProp($data, 'id');
  6420. if (!$id) Utils::throwError('20003:ID不能为空');
  6421. $ids = explode(',', $id);
  6422. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6423. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6424. $query_uid = $is_public ? 0 : $uid;
  6425. // 如果是公共库操作,需要admin权限
  6426. if ($is_public && $role !== 'admin') {
  6427. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6428. }
  6429. // 检查是否存在且属于当前用户或公共库
  6430. $role = DB::table('mp_products')
  6431. ->whereIn('id', $ids)
  6432. ->where('cpid', $cpid)
  6433. ->where('user_id', $query_uid)
  6434. ->get();
  6435. if (!$role) Utils::throwError('20003:记录不存在');
  6436. return DB::table('mp_products')
  6437. ->where('cpid', $cpid)
  6438. ->where('user_id', $query_uid)
  6439. ->whereIn('id', $ids)
  6440. ->update([
  6441. 'is_deleted' => 1,
  6442. 'updated_at' => date('Y-m-d H:i:s')
  6443. ]);
  6444. }
  6445. public function generateThreeView($data) {
  6446. $uid = Site::getUid();
  6447. $cpid = Site::getCpid();
  6448. $role = Site::getRole();
  6449. $id = getProp($data, 'id');
  6450. if (!$id) Utils::throwError('20003:ID不能为空');
  6451. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6452. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6453. $query_uid = $is_public ? 0 : $uid;
  6454. // 如果是公共库操作,需要admin权限
  6455. if ($is_public && $role !== 'admin') {
  6456. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6457. }
  6458. // 检查是否存在且属于当前用户或公共库
  6459. $product = DB::table('mp_products')
  6460. ->where('id', $id)
  6461. ->where('cpid', $cpid)
  6462. ->where('user_id', $query_uid)
  6463. ->where('type', 1)->first();
  6464. if (!$product) Utils::throwError('20003:资产不存在');
  6465. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6466. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6467. if (!$ref_img_url) {
  6468. // 如果没有传入参考图,使用角色表中的图片
  6469. $ref_img_url = $product->url ?? '';
  6470. if (!$ref_img_url) {
  6471. Utils::throwError('20003:参考图不能为空');
  6472. }
  6473. }
  6474. $pic_prompt = getProp($product, 'pic_prompt');
  6475. if ($pic_prompt) {
  6476. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6477. }
  6478. // 检查参考图是否是正确的图片格式
  6479. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6480. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6481. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6482. if (!in_array($extension, $allowedExtensions)) {
  6483. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6484. }
  6485. // 处理图片模型
  6486. $model = getProp($data, 'model');
  6487. if (!$model) {
  6488. // 使用默认模型
  6489. $model = 'doubao-seedream-5-0-lite-260128';
  6490. }
  6491. // 验证模型是否在可用模型表中
  6492. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6493. Utils::throwError('20003:该模型已不可用,请更换!');
  6494. }
  6495. $ratio = getProp($data, 'ratio', '16:9');
  6496. $resolution = getProp($data, 'resolution', '2k');
  6497. // 定义分辨率和宽高比对应的尺寸映射表
  6498. $sizeMap = [
  6499. '2k' => [
  6500. '1:1' => ['width' => 2048, 'height' => 2048],
  6501. '4:3' => ['width' => 2304, 'height' => 1728],
  6502. '3:4' => ['width' => 1728, 'height' => 2304],
  6503. '16:9' => ['width' => 2848, 'height' => 1600],
  6504. '9:16' => ['width' => 1600, 'height' => 2848],
  6505. '3:2' => ['width' => 2496, 'height' => 1664],
  6506. '2:3' => ['width' => 1664, 'height' => 2496],
  6507. '21:9' => ['width' => 3136, 'height' => 1344],
  6508. ],
  6509. '3k' => [
  6510. '1:1' => ['width' => 3072, 'height' => 3072],
  6511. '4:3' => ['width' => 3456, 'height' => 2592],
  6512. '3:4' => ['width' => 2592, 'height' => 3456],
  6513. '16:9' => ['width' => 4096, 'height' => 2304],
  6514. '9:16' => ['width' => 2304, 'height' => 4096],
  6515. '2:3' => ['width' => 2496, 'height' => 3744],
  6516. '3:2' => ['width' => 3744, 'height' => 2496],
  6517. '21:9' => ['width' => 4704, 'height' => 2016],
  6518. ],
  6519. '4k' => [
  6520. '1:1' => ['width' => 4096, 'height' => 4096],
  6521. '3:4' => ['width' => 3520, 'height' => 4704],
  6522. '4:3' => ['width' => 4704, 'height' => 3520],
  6523. '16:9' => ['width' => 5504, 'height' => 3040],
  6524. '9:16' => ['width' => 3040, 'height' => 5504],
  6525. '2:3' => ['width' => 3328, 'height' => 4992],
  6526. '3:2' => ['width' => 4992, 'height' => 3328],
  6527. '21:9' => ['width' => 6240, 'height' => 2656],
  6528. ],
  6529. ];
  6530. // 参数验证
  6531. $resolution = strtolower($resolution);
  6532. if (!isset($sizeMap[$resolution])) {
  6533. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6534. }
  6535. if (!isset($sizeMap[$resolution][$ratio])) {
  6536. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6537. }
  6538. // 根据 ratio 和 resolution 确定宽高
  6539. $width = $sizeMap[$resolution][$ratio]['width'];
  6540. $height = $sizeMap[$resolution][$ratio]['height'];
  6541. try {
  6542. // 创建图片生成任务
  6543. $params = [
  6544. 'prompt' => $prompt,
  6545. 'model' => $model,
  6546. 'ref_img_urls' => [$ref_img_url],
  6547. 'width' => $width,
  6548. 'height' => $height
  6549. ];
  6550. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6551. $task_id = $task->id;
  6552. if (!$task_id) {
  6553. Utils::throwError('20003:创建图片生成任务失败');
  6554. }
  6555. // 轮询获取结果
  6556. // 只查询数据库,不调用API,不更新任务表
  6557. $start_time = time();
  6558. $timeout = 1800;
  6559. $img_url = '';
  6560. while (time() - $start_time < $timeout) {
  6561. sleep(5);
  6562. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6563. $task = DB::table('mp_generate_pic_tasks')
  6564. ->where('id', $task_id)
  6565. ->first();
  6566. if (!$task) {
  6567. Utils::throwError('20003:任务不存在');
  6568. }
  6569. if ($task->status === 'success' && $task->result_url) {
  6570. $result_urls = is_string($task->result_url)
  6571. ? json_decode($task->result_url, true)
  6572. : $task->result_url;
  6573. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6574. break;
  6575. } elseif ($task->status === 'failed') {
  6576. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6577. }
  6578. // 其他状态继续轮询
  6579. }
  6580. if (empty($img_url)) {
  6581. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6582. }
  6583. // 更新 mp_products 表(不是任务表)
  6584. DB::table('mp_products')
  6585. ->where('id', $id)
  6586. ->where('cpid', $cpid)
  6587. ->update([
  6588. 'three_view_image_url' => $img_url,
  6589. 'updated_at' => date('Y-m-d H:i:s')
  6590. ]);
  6591. return ['three_view_image_url' => $img_url];
  6592. } catch (\Exception $e) {
  6593. dLog('anime')->error('生成三视图失败', [
  6594. 'error' => $e->getMessage()
  6595. ]);
  6596. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6597. Utils::throwError('20003:' . $e->getMessage());
  6598. }
  6599. }
  6600. /**
  6601. * 推送(复制)资产或文件夹到目标位置
  6602. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6603. * @return array 返回推送结果
  6604. */
  6605. public function pushProductOrFolder($data) {
  6606. $uid = Site::getUid();
  6607. $cpid = Site::getCpid();
  6608. $role = Site::getRole();
  6609. $product_id = getProp($data, 'product_id');
  6610. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6611. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6612. if (!$product_id) {
  6613. Utils::throwError('20003:请选择要推送的项目');
  6614. }
  6615. // 查询源项目(只通过cpid查询,不限制user_id)
  6616. $sourceItem = DB::table('mp_products')
  6617. ->where('id', $product_id)
  6618. ->where('cpid', $cpid)
  6619. ->where('is_deleted', 0)
  6620. ->first();
  6621. if (!$sourceItem) {
  6622. Utils::throwError('20003:要推送的项目不存在');
  6623. }
  6624. // 通过user_id判断源是公共库还是个人库
  6625. $source_uid = $sourceItem->user_id;
  6626. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6627. // 验证目标文件夹并确定目标是公共库还是个人库
  6628. $target_level = 0;
  6629. $target_uid = $uid; // 默认推送到个人库
  6630. $target_is_public = 0;
  6631. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6632. if ($target_parent_id > 0) {
  6633. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6634. $targetParent = DB::table('mp_products')
  6635. ->where('id', $target_parent_id)
  6636. ->where('cpid', $cpid)
  6637. ->where('type', 2)
  6638. ->where('is_deleted', 0)
  6639. ->first();
  6640. if (!$targetParent) {
  6641. Utils::throwError('20003:目标文件夹不存在');
  6642. }
  6643. // 通过user_id判断目标是公共库还是个人库
  6644. $target_level = $targetParent->level;
  6645. $target_uid = $targetParent->user_id;
  6646. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6647. // 使用目标文件夹的 product 类型
  6648. $final_product_type = $targetParent->product;
  6649. }
  6650. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6651. else {
  6652. $push_to_public = getProp($data, 'push_to_public');
  6653. if ($push_to_public === '') {
  6654. Utils::throwError('20003:请选择是否推送到公共库');
  6655. }
  6656. if ($push_to_public) {
  6657. $target_uid = 0;
  6658. $target_is_public = 1;
  6659. }
  6660. // 推送到根目录时,必须指定 product 类型
  6661. if ($target_product === null || $target_product === '') {
  6662. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6663. }
  6664. $final_product_type = $target_product;
  6665. }
  6666. // 如果目标是公共库,需要admin权限
  6667. if ($target_is_public && $role !== 'admin') {
  6668. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6669. }
  6670. // 权限验证:验证是否符合允许的推送规则
  6671. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6672. try {
  6673. DB::beginTransaction();
  6674. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6675. if ($sourceItem->type == 1) {
  6676. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6677. DB::commit();
  6678. return [
  6679. 'product_id' => $newId,
  6680. ];
  6681. }
  6682. // 如果是文件夹,递归复制(支持跨类型推送)
  6683. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6684. DB::commit();
  6685. return [
  6686. 'product_id' => $newFolderId,
  6687. ];
  6688. } catch (\Exception $e) {
  6689. DB::rollBack();
  6690. dLog('anime')->error('推送失败', [
  6691. 'error' => $e->getMessage(),
  6692. 'product_id' => $product_id
  6693. ]);
  6694. Utils::throwError('20003:' . $e->getMessage());
  6695. }
  6696. }
  6697. /**
  6698. * 验证推送权限
  6699. * 允许的推送规则:
  6700. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6701. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6702. * 3. 公共库推送给公共库(公共库 → 公共库)
  6703. *
  6704. * @param int $source_uid 源的user_id
  6705. * @param int $target_uid 目标的user_id
  6706. * @param int $current_uid 当前用户ID
  6707. * @throws \Exception
  6708. */
  6709. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6710. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6711. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6712. return; // 允许
  6713. }
  6714. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6715. if ($source_uid == 0 && $target_uid == $current_uid) {
  6716. return; // 允许
  6717. }
  6718. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6719. if ($source_uid == 0 && $target_uid == 0) {
  6720. return; // 允许
  6721. }
  6722. // 其他情况都不允许
  6723. if ($source_uid != 0 && $source_uid != $current_uid) {
  6724. // 源是别人的个人库
  6725. Utils::throwError('20003:无权限访问该资产');
  6726. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6727. // 个人库推送给公共库(不允许)
  6728. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6729. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6730. // 不同用户的个人库之间推送(不允许)
  6731. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6732. } else {
  6733. // 其他未知情况
  6734. Utils::throwError('20003:不允许的推送操作');
  6735. }
  6736. }
  6737. /**
  6738. * 复制单个资产
  6739. * @param object $sourceProduct 源资产对象
  6740. * @param int $targetParentId 目标父文件夹ID
  6741. * @param int $targetLevel 目标层级
  6742. * @param int $cpid 公司ID
  6743. * @param int $targetUid 目标用户ID
  6744. * @return int 返回新资产ID
  6745. */
  6746. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6747. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6748. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6749. $newProductData = [
  6750. 'user_id' => $targetUid,
  6751. 'cpid' => $cpid,
  6752. 'type' => 1,
  6753. 'parent_id' => $targetParentId,
  6754. 'level' => $targetLevel,
  6755. 'product_name' => $sourceProduct->product_name,
  6756. 'url' => $sourceProduct->url,
  6757. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6758. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6759. 'product' => $finalProductType,
  6760. 'versions' => $sourceProduct->versions ?? '',
  6761. 'sort_order' => time(),
  6762. 'is_deleted' => 0,
  6763. 'created_at' => date('Y-m-d H:i:s'),
  6764. 'updated_at' => date('Y-m-d H:i:s')
  6765. ];
  6766. return DB::table('mp_products')->insertGetId($newProductData);
  6767. }
  6768. /**
  6769. * 递归复制文件夹及其子项
  6770. * @param object $sourceFolder 源文件夹对象
  6771. * @param int $targetParentId 目标父文件夹ID
  6772. * @param int $targetLevel 目标层级
  6773. * @param int $cpid 公司ID
  6774. * @param int $targetUid 目标用户ID
  6775. * @param int $sourceUid 源用户ID
  6776. * @return int 返回新文件夹ID
  6777. */
  6778. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6779. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6780. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6781. // 创建新文件夹
  6782. $newFolderData = [
  6783. 'user_id' => $targetUid,
  6784. 'cpid' => $cpid,
  6785. 'type' => 2,
  6786. 'parent_id' => $targetParentId,
  6787. 'level' => $targetLevel,
  6788. 'product_name' => $sourceFolder->product_name,
  6789. 'product' => $finalProductType,
  6790. 'sort_order' => time(),
  6791. 'is_deleted' => 0,
  6792. 'created_at' => date('Y-m-d H:i:s'),
  6793. 'updated_at' => date('Y-m-d H:i:s')
  6794. ];
  6795. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6796. // 获取源文件夹下的所有子项
  6797. $children = DB::table('mp_products')
  6798. ->where('parent_id', $sourceFolder->id)
  6799. ->where('cpid', $cpid)
  6800. ->where('user_id', $sourceUid)
  6801. ->where('is_deleted', 0)
  6802. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6803. ->get();
  6804. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6805. foreach ($children as $child) {
  6806. if ($child->type == 1) {
  6807. // 资产
  6808. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6809. } else {
  6810. // 文件夹
  6811. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6812. }
  6813. }
  6814. return $newFolderId;
  6815. }
  6816. /**
  6817. * 保存剧本资产关联关系
  6818. * @param array $data 请求参数
  6819. * @return bool
  6820. */
  6821. public function saveScriptProducts($data) {
  6822. $uid = Site::getUid();
  6823. $cpid = Site::getCpid();
  6824. $script_id = getProp($data, 'script_id');
  6825. $products = getProp($data, 'products', []);
  6826. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6827. if (!$script_id) {
  6828. Utils::throwError('20003:请提供剧本ID');
  6829. }
  6830. // 验证剧本是否存在
  6831. $script = DB::table('mp_scripts')
  6832. ->where('id', $script_id)
  6833. ->where('is_deleted', 0)
  6834. ->first();
  6835. if (!$script) {
  6836. Utils::throwError('20003:剧本不存在');
  6837. }
  6838. // 处理图片模型
  6839. $model = getProp($data, 'model');
  6840. if (!$model) {
  6841. // 使用默认模型
  6842. $model = 'doubao-seedream-5-0-lite-260128';
  6843. }
  6844. // 验证模型是否在可用模型表中
  6845. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6846. Utils::throwError('20003:该模型已不可用,请更换!');
  6847. }
  6848. $ratio = getProp($data, 'ratio', '9:16');
  6849. $resolution = getProp($data, 'resolution', '2k');
  6850. // 定义分辨率和宽高比对应的尺寸映射表
  6851. $sizeMap = [
  6852. '2k' => [
  6853. '1:1' => ['width' => 2048, 'height' => 2048],
  6854. '4:3' => ['width' => 2304, 'height' => 1728],
  6855. '3:4' => ['width' => 1728, 'height' => 2304],
  6856. '16:9' => ['width' => 2848, 'height' => 1600],
  6857. '9:16' => ['width' => 1600, 'height' => 2848],
  6858. '3:2' => ['width' => 2496, 'height' => 1664],
  6859. '2:3' => ['width' => 1664, 'height' => 2496],
  6860. '21:9' => ['width' => 3136, 'height' => 1344],
  6861. ],
  6862. '3k' => [
  6863. '1:1' => ['width' => 3072, 'height' => 3072],
  6864. '4:3' => ['width' => 3456, 'height' => 2592],
  6865. '3:4' => ['width' => 2592, 'height' => 3456],
  6866. '16:9' => ['width' => 4096, 'height' => 2304],
  6867. '9:16' => ['width' => 2304, 'height' => 4096],
  6868. '2:3' => ['width' => 2496, 'height' => 3744],
  6869. '3:2' => ['width' => 3744, 'height' => 2496],
  6870. '21:9' => ['width' => 4704, 'height' => 2016],
  6871. ],
  6872. '4k' => [
  6873. '1:1' => ['width' => 4096, 'height' => 4096],
  6874. '3:4' => ['width' => 3520, 'height' => 4704],
  6875. '4:3' => ['width' => 4704, 'height' => 3520],
  6876. '16:9' => ['width' => 5504, 'height' => 3040],
  6877. '9:16' => ['width' => 3040, 'height' => 5504],
  6878. '2:3' => ['width' => 3328, 'height' => 4992],
  6879. '3:2' => ['width' => 4992, 'height' => 3328],
  6880. '21:9' => ['width' => 6240, 'height' => 2656],
  6881. ],
  6882. ];
  6883. // 参数验证
  6884. $resolution = strtolower($resolution);
  6885. if (!isset($sizeMap[$resolution])) {
  6886. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6887. }
  6888. if (!isset($sizeMap[$resolution][$ratio])) {
  6889. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6890. }
  6891. // 根据 ratio 和 resolution 确定宽高
  6892. $width = $sizeMap[$resolution][$ratio]['width'];
  6893. $height = $sizeMap[$resolution][$ratio]['height'];
  6894. $script_name = $script->script_name ?? 'script_' . $script_id;
  6895. // 检查是否已经有该剧本的资产数据
  6896. $existingMappings = DB::table('mp_script_product_mappings')
  6897. ->where('script_id', $script_id)
  6898. ->get();
  6899. if ($existingMappings->isNotEmpty()) {
  6900. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6901. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6902. // 查询这些资产的图片生成任务状态
  6903. $productsWithTasks = DB::table('mp_products')
  6904. ->whereIn('id', $productIds)
  6905. ->where('is_deleted', 0)
  6906. ->get();
  6907. $productTaskMap = [];
  6908. $typeFolderIds = [];
  6909. $hasAllTasks = true;
  6910. foreach ($productsWithTasks as $product) {
  6911. // 收集类型文件夹ID
  6912. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6913. $parentFolder = DB::table('mp_products')
  6914. ->where('id', $product->parent_id)
  6915. ->where('type', 2)
  6916. ->first();
  6917. if ($parentFolder) {
  6918. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6919. }
  6920. }
  6921. // 检查是否有图片生成任务
  6922. if (!empty($product->pic_task_id)) {
  6923. $productTaskMap[$product->id] = $product->pic_task_id;
  6924. } else if($product->url && $product->pic_task_status == '生成成功') {
  6925. continue;
  6926. } else {
  6927. // 有资产没有图片任务
  6928. $hasAllTasks = false;
  6929. }
  6930. }
  6931. // 如果所有资产都有任务ID,直接轮询返回结果
  6932. if ($hasAllTasks && !empty($productTaskMap)) {
  6933. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6934. 'script_id' => $script_id,
  6935. 'script_name' => $script_name,
  6936. 'product_count' => count($productTaskMap)
  6937. ]);
  6938. // 直接返回 SSE 流轮询结果
  6939. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6940. }
  6941. // 如果部分资产没有任务ID,只为这些资产创建任务
  6942. if (!$hasAllTasks && $auto_generate_images) {
  6943. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6944. 'script_id' => $script_id,
  6945. 'script_name' => $script_name
  6946. ]);
  6947. // 开启事务
  6948. DB::beginTransaction();
  6949. try {
  6950. foreach ($productsWithTasks as $product) {
  6951. // 跳过已有任务的资产
  6952. if (!empty($product->pic_task_id)) {
  6953. continue;
  6954. }
  6955. // 跳过没有提示词的资产
  6956. if (empty($product->pic_prompt)) {
  6957. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6958. 'product_id' => $product->id,
  6959. 'product_name' => $product->product_name
  6960. ]);
  6961. continue;
  6962. }
  6963. try {
  6964. // 创建图片生成任务
  6965. $params = [
  6966. 'prompt' => $product->pic_prompt,
  6967. 'model' => $model,
  6968. 'ref_img_urls' => [],
  6969. 'width' => $width,
  6970. 'height' => $height
  6971. ];
  6972. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6973. $task_id = $task->id;
  6974. if ($task_id) {
  6975. $productTaskMap[$product->id] = $task_id;
  6976. // 在事务中更新资产表的任务ID和状态
  6977. DB::table('mp_products')
  6978. ->where('id', $product->id)
  6979. ->update([
  6980. 'pic_task_id' => $task_id,
  6981. 'pic_task_status' => '生成中',
  6982. 'updated_at' => now()
  6983. ]);
  6984. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6985. 'product_id' => $product->id,
  6986. 'task_id' => $task_id
  6987. ]);
  6988. }
  6989. } catch (\Exception $e) {
  6990. dLog('anime')->error('创建资产图片生成任务失败', [
  6991. 'product_id' => $product->id,
  6992. 'error' => $e->getMessage()
  6993. ]);
  6994. // 标记为失败(仍在事务中)
  6995. DB::table('mp_products')
  6996. ->where('id', $product->id)
  6997. ->update([
  6998. 'pic_task_status' => '生成失败',
  6999. 'updated_at' => now()
  7000. ]);
  7001. }
  7002. }
  7003. // 提交事务
  7004. DB::commit();
  7005. // 如果有新创建的任务,返回 SSE 流
  7006. if (!empty($productTaskMap)) {
  7007. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7008. }
  7009. } catch (\Exception $e) {
  7010. // 回滚事务
  7011. DB::rollback();
  7012. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7013. 'script_id' => $script_id,
  7014. 'error' => $e->getMessage()
  7015. ]);
  7016. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7017. }
  7018. }
  7019. // 如果不需要生成图片,返回已存在的信息
  7020. return [
  7021. 'success' => true,
  7022. 'message' => '剧本资产已存在',
  7023. 'script_id' => $script_id,
  7024. 'script_name' => $script_name,
  7025. 'type_folder_ids' => $typeFolderIds,
  7026. 'existing_products' => count($productIds),
  7027. 'tasks_count' => count($productTaskMap)
  7028. ];
  7029. }
  7030. // 解析 products(可能是 JSON 字符串或数组)
  7031. if (is_string($products)) {
  7032. $products = json_decode($products, true);
  7033. if (json_last_error() !== JSON_ERROR_NONE) {
  7034. Utils::throwError('20003:产品数据格式错误');
  7035. }
  7036. }
  7037. if (!is_array($products) || empty($products)) {
  7038. Utils::throwError('20003:产品数据不能为空');
  7039. }
  7040. // 以下是原有的创建逻辑...
  7041. // 开启事务
  7042. DB::beginTransaction();
  7043. try {
  7044. $now = now();
  7045. $mappingRecords = [];
  7046. $createdProductIds = []; // 记录所有创建的资产ID
  7047. // 获取剧本名称
  7048. $script_name = $script->script_name ?? 'script_' . $script_id;
  7049. // 存储每个类型的根文件夹ID
  7050. $typeFolderIds = [];
  7051. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7052. foreach ($products as $productGroup) {
  7053. $type = getProp($productGroup, 'type');
  7054. $title = getProp($productGroup, 'title', '');
  7055. $content = getProp($productGroup, 'content', []);
  7056. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7057. continue;
  7058. }
  7059. // 为当前类型创建根文件夹(如果还未创建)
  7060. if (!isset($typeFolderIds[$type])) {
  7061. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7062. 'user_id' => $uid,
  7063. 'cpid' => $cpid,
  7064. 'type' => 2, // 1.资产 2文件夹
  7065. 'product' => $type, // 1.主体 2.场景 3.道具
  7066. 'parent_id' => 0, // 根文件夹,parent_id=0
  7067. 'level' => 1, // 第一层级
  7068. 'product_name' => $script_name,
  7069. 'sort_order' => time() + $type,
  7070. 'is_deleted' => 0,
  7071. 'created_at' => $now,
  7072. 'updated_at' => $now
  7073. ]);
  7074. }
  7075. $folder_id = $typeFolderIds[$type];
  7076. // 获取表头(第一行)并查找关键列的位置
  7077. $headers = $content[0];
  7078. $nameColumnIndex = -1; // 资产名称列索引
  7079. $sequenceColumnIndex = -1; // 使用范围列索引
  7080. $promptColumnIndex = -1; // 参考提示词列索引
  7081. foreach ($headers as $index => $header) {
  7082. // 查找"资产名称"列
  7083. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7084. $nameColumnIndex = $index;
  7085. }
  7086. // 查找"使用范围"列
  7087. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7088. $sequenceColumnIndex = $index;
  7089. }
  7090. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7091. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7092. $promptColumnIndex = $index;
  7093. }
  7094. }
  7095. // 验证必要的列是否都找到了
  7096. if ($nameColumnIndex === -1) {
  7097. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7098. continue;
  7099. }
  7100. if ($sequenceColumnIndex === -1) {
  7101. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7102. continue;
  7103. }
  7104. // 跳过表头,解析每一行数据
  7105. for ($i = 1; $i < count($content); $i++) {
  7106. $row = $content[$i];
  7107. // 确保行数据有效
  7108. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7109. continue;
  7110. }
  7111. // 根据动态查找的列索引提取数据
  7112. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7113. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7114. $pic_prompt = '';
  7115. // 提取参考提示词(如果找到了该列)
  7116. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7117. $pic_prompt = trim($row[$promptColumnIndex]);
  7118. }
  7119. // 解析使用范围(逗号分隔的序号)
  7120. $sequences = [];
  7121. if (!empty($sequence_str)) {
  7122. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7123. foreach ($sequenceParts as $part) {
  7124. if (is_numeric($part)) {
  7125. $sequences[] = (int)$part;
  7126. }
  7127. }
  7128. }
  7129. if (empty($product_name)) {
  7130. continue;
  7131. }
  7132. // 处理product_name两边的符号
  7133. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7134. // 如果名称不存在或仅剩占位符号,则跳过
  7135. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7136. dLog('anime')->warning('资产名称无效,跳过保存', [
  7137. 'script_id' => $script_id,
  7138. 'type' => $type,
  7139. 'product_name' => $product_name
  7140. ]);
  7141. continue;
  7142. }
  7143. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7144. $product_id = DB::table('mp_products')->insertGetId([
  7145. 'product_name' => $product_name,
  7146. 'type' => 1, // 1=资产 2.文件夹
  7147. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7148. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7149. 'level' => 2, // 第二层级
  7150. 'pic_prompt' => $pic_prompt,
  7151. 'user_id' => $uid,
  7152. 'cpid' => $cpid,
  7153. 'sort_order' => time(),
  7154. 'is_deleted' => 0,
  7155. 'created_at' => $now,
  7156. 'updated_at' => $now,
  7157. ]);
  7158. // 记录创建的资产ID
  7159. $createdProductIds[] = $product_id;
  7160. // 为每个序号创建映射记录
  7161. if (!empty($sequences)) {
  7162. foreach ($sequences as $sequence) {
  7163. $mappingRecords[] = [
  7164. 'script_id' => $script_id,
  7165. 'product_id' => $product_id,
  7166. 'episode_number' => $sequence,
  7167. 'created_at' => $now,
  7168. 'updated_at' => $now,
  7169. ];
  7170. }
  7171. } else {
  7172. // 如果没有指定序号,创建一个默认映射(序号为0)
  7173. $mappingRecords[] = [
  7174. 'script_id' => $script_id,
  7175. 'product_id' => $product_id,
  7176. 'episode_number' => 0,
  7177. 'created_at' => $now,
  7178. 'updated_at' => $now,
  7179. ];
  7180. }
  7181. }
  7182. }
  7183. if (empty($mappingRecords)) {
  7184. Utils::throwError('20003:没有有效的产品数据');
  7185. }
  7186. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7187. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7188. // 剧本已有资产,同步更新is_products标记
  7189. DB::table('mp_scripts')->where('id', $script_id)->update([
  7190. 'is_products' => 1,
  7191. 'updated_at' => $now
  7192. ]);
  7193. // 如果需要自动生成图片,在事务中创建图片生成任务
  7194. $productTaskMap = [];
  7195. if ($auto_generate_images && !empty($createdProductIds)) {
  7196. // 查询所有创建的资产
  7197. $productsToGenerate = DB::table('mp_products')
  7198. ->whereIn('id', $createdProductIds)
  7199. ->where('is_deleted', 0)
  7200. ->get();
  7201. foreach ($productsToGenerate as $product) {
  7202. if (empty($product->pic_prompt)) {
  7203. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7204. 'product_id' => $product->id,
  7205. 'product_name' => $product->product_name
  7206. ]);
  7207. continue;
  7208. }
  7209. try {
  7210. // 创建图片生成任务
  7211. $params = [
  7212. 'prompt' => $product->pic_prompt,
  7213. 'model' => $model,
  7214. 'ref_img_urls' => [],
  7215. 'width' => $width,
  7216. 'height' => $height
  7217. ];
  7218. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7219. $task_id = $task->id;
  7220. if ($task_id) {
  7221. $productTaskMap[$product->id] = $task_id;
  7222. // 在事务中更新资产表的任务ID和状态
  7223. DB::table('mp_products')
  7224. ->where('id', $product->id)
  7225. ->update([
  7226. 'pic_task_id' => $task_id,
  7227. 'pic_task_status' => '生成中',
  7228. 'updated_at' => now()
  7229. ]);
  7230. dLog('anime')->info('创建资产图片生成任务', [
  7231. 'product_id' => $product->id,
  7232. 'task_id' => $task_id
  7233. ]);
  7234. }
  7235. } catch (\Exception $e) {
  7236. dLog('anime')->error('创建资产图片生成任务失败', [
  7237. 'product_id' => $product->id,
  7238. 'error' => $e->getMessage()
  7239. ]);
  7240. // 标记为失败(仍在事务中)
  7241. DB::table('mp_products')
  7242. ->where('id', $product->id)
  7243. ->update([
  7244. 'pic_task_status' => '生成失败',
  7245. 'updated_at' => now()
  7246. ]);
  7247. }
  7248. }
  7249. }
  7250. // 提交事务
  7251. DB::commit();
  7252. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7253. if ($auto_generate_images && !empty($productTaskMap)) {
  7254. // 返回 SSE 流(事务外轮询)
  7255. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7256. }
  7257. // 如果不需要生成图片,返回普通结果
  7258. return [
  7259. 'success' => true,
  7260. 'type_folder_ids' => $typeFolderIds,
  7261. 'inserted_count' => $insertedCount,
  7262. 'total_records' => count($mappingRecords),
  7263. 'created_products' => count($createdProductIds),
  7264. 'image_tasks_created' => count($productTaskMap)
  7265. ];
  7266. } catch (\Exception $e) {
  7267. // 回滚事务
  7268. DB::rollback();
  7269. // 记录错误日志
  7270. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7271. 'script_id' => $script_id,
  7272. 'error' => $e->getMessage(),
  7273. 'trace' => $e->getTraceAsString()
  7274. ]);
  7275. // 统一使用 Utils::throwError 抛出错误
  7276. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7277. }
  7278. }
  7279. /**
  7280. * 批量为剧本资产生成图片
  7281. *
  7282. * @param array $data 请求参数
  7283. * @return \Generator 返回 SSE 流
  7284. */
  7285. public function batchGenerateProductImages($data) {
  7286. $script_id = getProp($data, 'script_id');
  7287. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7288. if (!$script_id) {
  7289. Utils::throwError('20003:请提供剧本ID');
  7290. }
  7291. // 验证剧本是否存在
  7292. $script = DB::table('mp_scripts')
  7293. ->where('id', $script_id)
  7294. ->where('is_deleted', 0)
  7295. ->first();
  7296. if (!$script) {
  7297. Utils::throwError('20003:剧本不存在');
  7298. }
  7299. $script_name = $script->script_name ?? 'script_' . $script_id;
  7300. // 获取需要生成图片的所有资产
  7301. $products = DB::table('mp_products')
  7302. ->whereIn('parent_id', array_values($type_folder_ids))
  7303. ->where('is_deleted', 0)
  7304. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7305. ->get();
  7306. if ($products->isEmpty()) {
  7307. Utils::throwError('20003:没有找到需要生成图片的资产');
  7308. }
  7309. // 默认参数
  7310. $model = 'doubao-seedream-5-0-lite-260128';
  7311. $width = 1600;
  7312. $height = 2848;
  7313. // 开始为每个资产创建图片生成任务
  7314. $taskIds = [];
  7315. $productTaskMap = []; // 资产ID到任务ID的映射
  7316. foreach ($products as $product) {
  7317. if (empty($product->pic_prompt)) {
  7318. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7319. continue;
  7320. }
  7321. try {
  7322. // 创建图片生成任务
  7323. $params = [
  7324. 'prompt' => $product->pic_prompt,
  7325. 'model' => $model,
  7326. 'ref_img_urls' => [],
  7327. 'width' => $width,
  7328. 'height' => $height
  7329. ];
  7330. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7331. $task_id = $task->id;
  7332. if ($task_id) {
  7333. $taskIds[] = $task_id;
  7334. $productTaskMap[$product->id] = $task_id;
  7335. // 更新资产表的任务ID和状态
  7336. DB::table('mp_products')
  7337. ->where('id', $product->id)
  7338. ->update([
  7339. 'pic_task_id' => $task_id,
  7340. 'pic_task_status' => '生成中',
  7341. 'updated_at' => now()
  7342. ]);
  7343. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7344. }
  7345. } catch (\Exception $e) {
  7346. dLog('anime')->error('创建资产图片生成任务失败', [
  7347. 'product_id' => $product->id,
  7348. 'error' => $e->getMessage()
  7349. ]);
  7350. // 标记为失败
  7351. DB::table('mp_products')
  7352. ->where('id', $product->id)
  7353. ->update([
  7354. 'pic_task_status' => '生成失败',
  7355. 'updated_at' => now()
  7356. ]);
  7357. }
  7358. }
  7359. if (empty($taskIds)) {
  7360. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7361. }
  7362. // 返回 SSE 流
  7363. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7364. }
  7365. /**
  7366. * 轮询资产图片生成任务状态(SSE流式返回)
  7367. * 只通过查询数据库获取任务状态,不主动调用API
  7368. *
  7369. * @param int $script_id 剧本ID
  7370. * @param string $script_name 剧本名称
  7371. * @param array $productTaskMap 资产ID到任务ID的映射
  7372. * @param array $type_folder_ids 类型文件夹ID映射
  7373. * @return \Generator
  7374. */
  7375. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7376. $startTime = time();
  7377. $timeout = 1800; // 30分钟超时
  7378. $pollInterval = 10; // 10秒轮询一次
  7379. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7380. // 定义类型名称映射
  7381. $typeNames = [
  7382. 1 => 'roles', // 角色
  7383. 2 => 'scenes', // 场景
  7384. 3 => 'props' // 道具
  7385. ];
  7386. while (time() - $startTime < $timeout) {
  7387. sleep($pollInterval);
  7388. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7389. $mappings = DB::table('mp_script_product_mappings')
  7390. ->where('script_id', $script_id)
  7391. ->pluck('product_id')
  7392. ->unique()
  7393. ->toArray();
  7394. if (empty($mappings)) {
  7395. dLog('anime')->warning('该剧本没有关联的资产', [
  7396. 'script_id' => $script_id,
  7397. 'script_name' => $script_name
  7398. ]);
  7399. break;
  7400. }
  7401. // 查询所有资产的当前状态
  7402. $products = DB::table('mp_products')
  7403. ->whereIn('id', $mappings)
  7404. ->where('is_deleted', 0)
  7405. ->get();
  7406. // 统计各类型的状态(使用类型名称作为键名)
  7407. $stats = [
  7408. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7409. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7410. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7411. ];
  7412. $allCompleted = true;
  7413. $hasStatusChange = false;
  7414. foreach ($products as $product) {
  7415. $type = $product->product;
  7416. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7417. // 如果类型名称不在 stats 中,初始化
  7418. if (!isset($stats[$typeName])) {
  7419. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7420. }
  7421. $stats[$typeName]['total']++;
  7422. $task_id = $product->pic_task_id;
  7423. $currentStatus = $product->pic_task_status;
  7424. // 检查状态是否有变化
  7425. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7426. $hasStatusChange = true;
  7427. $lastStatus[$product->id] = $currentStatus;
  7428. }
  7429. // 如果是生成中,查询任务表状态
  7430. if ($currentStatus === '生成中' && $task_id) {
  7431. // 只查询数据库,不调用API
  7432. $task = DB::table('mp_generate_pic_tasks')
  7433. ->where('id', $task_id)
  7434. ->first();
  7435. if ($task) {
  7436. // 检查任务状态
  7437. if ($task->status === 'success' && $task->result_url) {
  7438. // 解析图片URL
  7439. $result_urls = $task->result_url;
  7440. if (is_string($result_urls)) {
  7441. $result_urls = json_decode($result_urls, true);
  7442. }
  7443. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7444. // 更新资产表状态
  7445. DB::table('mp_products')
  7446. ->where('id', $product->id)
  7447. ->update([
  7448. 'pic_task_status' => '生成成功',
  7449. 'url' => $img_url,
  7450. 'updated_at' => now()
  7451. ]);
  7452. $stats[$typeName]['success']++;
  7453. $stats[$typeName]['completed']++;
  7454. $hasStatusChange = true;
  7455. dLog('anime')->info('资产图片生成成功', [
  7456. 'product_id' => $product->id,
  7457. 'task_id' => $task_id,
  7458. 'img_url' => $img_url
  7459. ]);
  7460. } elseif ($task->status === 'failed') {
  7461. // 更新资产表状态
  7462. DB::table('mp_products')
  7463. ->where('id', $product->id)
  7464. ->update([
  7465. 'pic_task_status' => '生成失败',
  7466. 'updated_at' => now()
  7467. ]);
  7468. $stats[$typeName]['completed']++;
  7469. $hasStatusChange = true;
  7470. dLog('anime')->warning('资产图片生成失败', [
  7471. 'product_id' => $product->id,
  7472. 'task_id' => $task_id,
  7473. 'error' => $task->error_message ?? '未知错误'
  7474. ]);
  7475. } else {
  7476. // 任务还在处理中
  7477. $allCompleted = false;
  7478. }
  7479. } else {
  7480. // 任务不存在,标记为失败
  7481. DB::table('mp_products')
  7482. ->where('id', $product->id)
  7483. ->update([
  7484. 'pic_task_status' => '生成失败',
  7485. 'updated_at' => now()
  7486. ]);
  7487. $stats[$type]['completed']++;
  7488. $hasStatusChange = true;
  7489. dLog('anime')->error('图片生成任务不存在', [
  7490. 'product_id' => $product->id,
  7491. 'task_id' => $task_id
  7492. ]);
  7493. }
  7494. } elseif ($currentStatus === '生成成功') {
  7495. $stats[$typeName]['success']++;
  7496. $stats[$typeName]['completed']++;
  7497. } elseif ($currentStatus === '生成失败') {
  7498. $stats[$typeName]['completed']++;
  7499. } else {
  7500. // 其他状态也认为未完成
  7501. $allCompleted = false;
  7502. }
  7503. }
  7504. // 移除没有数据的类型(total=0)
  7505. foreach ($stats as $typeName => $stat) {
  7506. if ($stat['total'] === 0) {
  7507. unset($stats[$typeName]);
  7508. }
  7509. }
  7510. // 如果有状态变化,发送 SSE 更新
  7511. if ($hasStatusChange) {
  7512. $eventType = $allCompleted ? 'complete' : 'update';
  7513. $response = [
  7514. 'type' => $eventType,
  7515. 'script_id' => $script_id,
  7516. 'script_name' => $script_name,
  7517. 'stats' => $stats,
  7518. 'timestamp' => date('Y-m-d H:i:s')
  7519. ];
  7520. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7521. dLog('anime')->info('SSE更新', [
  7522. 'event_type' => $eventType,
  7523. 'script_id' => $script_id,
  7524. 'script_name' => $script_name,
  7525. 'stats' => $stats
  7526. ]);
  7527. if ($allCompleted) {
  7528. dLog('anime')->info('所有资产图片生成任务已完成', [
  7529. 'script_id' => $script_id,
  7530. 'script_name' => $script_name,
  7531. 'stats' => $stats
  7532. ]);
  7533. break;
  7534. }
  7535. }
  7536. }
  7537. // 超时处理
  7538. if (time() - $startTime >= $timeout && !$allCompleted) {
  7539. $response = [
  7540. 'type' => 'timeout',
  7541. 'message' => '部分任务超时,请稍后查看结果',
  7542. 'script_id' => $script_id,
  7543. 'script_name' => $script_name,
  7544. 'timestamp' => date('Y-m-d H:i:s')
  7545. ];
  7546. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7547. dLog('anime')->warning('资产图片生成任务超时', [
  7548. 'script_id' => $script_id,
  7549. 'script_name' => $script_name,
  7550. 'timeout' => $timeout
  7551. ]);
  7552. }
  7553. }
  7554. /**
  7555. * 获取剧本关联的资产列表
  7556. * @param array $data 请求参数
  7557. * @return array
  7558. */
  7559. public function getScriptProducts($data) {
  7560. $uid = Site::getUid();
  7561. $cpid = Site::getCpid();
  7562. $script_id = getProp($data, 'script_id');
  7563. $episode_number = getProp($data, 'episode_number');
  7564. if (!$script_id) {
  7565. Utils::throwError('20003:请提供剧本ID');
  7566. }
  7567. // 验证剧本是否存在
  7568. $script = DB::table('mp_scripts')
  7569. ->where('id', $script_id)
  7570. ->where('is_deleted', 0)
  7571. ->first();
  7572. if (!$script) {
  7573. Utils::throwError('20003:剧本不存在');
  7574. }
  7575. // 联表查询资产信息
  7576. $query = DB::table('mp_script_product_mappings as mapping')
  7577. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7578. ->where('mapping.script_id', $script_id)
  7579. ->where('product.cpid', $cpid)
  7580. ->where('product.is_deleted', 0);
  7581. // 如果提供了 episode_number,则过滤指定集数
  7582. if ($episode_number !== null && $episode_number !== '') {
  7583. $query->where('mapping.episode_number', $episode_number);
  7584. }
  7585. $mappings = $query->select(
  7586. 'mapping.script_id',
  7587. 'mapping.product_id',
  7588. 'mapping.episode_number',
  7589. 'product.product_name',
  7590. 'product.type',
  7591. 'product.product',
  7592. 'product.pic_prompt',
  7593. 'product.url',
  7594. 'product.pic_task_id',
  7595. 'product.pic_task_status',
  7596. 'product.three_view_image_url',
  7597. 'mapping.created_at'
  7598. )
  7599. ->orderBy('mapping.product_id', 'asc')
  7600. ->orderBy('mapping.episode_number', 'asc')
  7601. ->get();
  7602. // 按 product_id 分组,合并 episode_number
  7603. $productMap = [];
  7604. foreach ($mappings as $item) {
  7605. $product_id = $item->product_id;
  7606. if (!isset($productMap[$product_id])) {
  7607. $productMap[$product_id] = [
  7608. 'product_id' => $product_id,
  7609. 'product_name' => $item->product_name,
  7610. 'type' => (int)$item->type,
  7611. 'product' => (int)$item->product,
  7612. 'pic_prompt' => $item->pic_prompt,
  7613. 'url' => $item->url,
  7614. 'pic_task_id' => $item->pic_task_id,
  7615. 'pic_task_status' => $item->pic_task_status,
  7616. 'episode_numbers' => [],
  7617. 'created_at' => $item->created_at,
  7618. ];
  7619. }
  7620. // 添加 episode_number(去重)
  7621. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7622. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7623. }
  7624. }
  7625. // 按类型分组
  7626. $roles = []; // type=1 角色/主体
  7627. $scenes = []; // type=2 场景
  7628. $props = []; // type=3 道具
  7629. foreach ($productMap as $product) {
  7630. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7631. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7632. // 构造返回数据
  7633. $productData = [
  7634. 'product_id' => $product['product_id'],
  7635. 'product_name' => $product['product_name'],
  7636. 'product' => $product['product'],
  7637. 'pic_prompt' => $product['pic_prompt'],
  7638. 'url' => $product['url'],
  7639. 'pic_task_id' => $product['pic_task_id'],
  7640. 'pic_task_status' => $product['pic_task_status'],
  7641. 'episode_numbers' => $episodeNumbersStr,
  7642. 'created_at' => $product['created_at'],
  7643. ];
  7644. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7645. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7646. switch ($product['product']) {
  7647. case 1:
  7648. $roles[] = $productData;
  7649. break;
  7650. case 2:
  7651. $scenes[] = $productData;
  7652. break;
  7653. case 3:
  7654. $props[] = $productData;
  7655. break;
  7656. }
  7657. }
  7658. return [
  7659. 'script_id' => $script_id,
  7660. 'script_name' => $script->script_name ?? '',
  7661. 'roles' => $roles, // 主体
  7662. 'scenes' => $scenes, // 场景
  7663. 'props' => $props, // 道具
  7664. ];
  7665. }
  7666. /**
  7667. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7668. * @param string $actContent 原始内容
  7669. * @param array $products 产品数组(包含product_name和url)
  7670. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7671. */
  7672. public function processActContentWithProducts($actContent, $products) {
  7673. if (empty($actContent) || empty($products)) {
  7674. return [
  7675. 'content' => $actContent,
  7676. 'reference_images' => []
  7677. ];
  7678. }
  7679. // 构建产品名称到产品信息的映射
  7680. $product_dict = [];
  7681. foreach ($products as $product) {
  7682. $product_name = getProp($product, 'product_name');
  7683. if ($product_name) {
  7684. $product_dict[$product_name] = [
  7685. 'url' => getProp($product, 'url'),
  7686. 'voice_prompt' => getProp($product, 'voice_prompt')
  7687. ];
  7688. }
  7689. }
  7690. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7691. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7692. $reference_images = [];
  7693. $product_index_map = []; // 产品名称 => 图片序号的映射
  7694. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7695. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7696. $current_index = 1;
  7697. if (!empty($matches[1])) {
  7698. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7699. $seen_products = []; // 用于去重
  7700. foreach ($matches[1] as $product_name) {
  7701. // 跳过已处理的产品
  7702. if (isset($seen_products[$product_name])) {
  7703. continue;
  7704. }
  7705. $seen_products[$product_name] = true;
  7706. // 检查产品是否在字典中
  7707. if (isset($product_dict[$product_name])) {
  7708. $url = $product_dict[$product_name]['url'];
  7709. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7710. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7711. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7712. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7713. }
  7714. // 只有URL非空才分配序号和添加到参考图片
  7715. if (!empty($url)) {
  7716. // 检查URL是否已经在reference_images中(去重)
  7717. if (!in_array($url, $reference_images)) {
  7718. $reference_images[] = $url;
  7719. $product_index_map[$product_name] = $current_index;
  7720. $current_index++;
  7721. } else {
  7722. // URL重复,找到已有的序号
  7723. $existing_index = array_search($url, $reference_images) + 1;
  7724. $product_index_map[$product_name] = $existing_index;
  7725. }
  7726. } else {
  7727. // URL为空,不分配序号(后续直接去掉{})
  7728. $product_index_map[$product_name] = 0;
  7729. }
  7730. } else {
  7731. // 产品不在字典中,不分配序号
  7732. $product_index_map[$product_name] = 0;
  7733. }
  7734. }
  7735. }
  7736. // 第二步:替换内容中的 {产品名称}
  7737. $processedContent = $actContent;
  7738. foreach ($product_index_map as $product_name => $index) {
  7739. $escaped_name = preg_quote($product_name, '/');
  7740. if ($index > 0) {
  7741. // 有图片,替换为:产品名称(图X)
  7742. $replacement = $product_name . '<图片' . $index . '>';
  7743. } else {
  7744. // 无图片,只保留产品名称
  7745. $replacement = $product_name;
  7746. }
  7747. // 替换所有 {产品名称} 为处理后的格式
  7748. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7749. }
  7750. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7751. foreach ($products as $product) {
  7752. $product_name = getProp($product, 'product_name');
  7753. $voice_prompt = getProp($product, 'voice_prompt');
  7754. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7755. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7756. break; // 找到旁白后退出循环
  7757. }
  7758. }
  7759. // 第四步:将voice_prompt信息添加到内容最前面
  7760. $voice_prompt_prefix = '';
  7761. if (!empty($voice_prompts)) {
  7762. $voice_prompt_prefix .= implode('', $voice_prompts);
  7763. }
  7764. // 旁白的voice_prompt放在最后
  7765. if (!empty($narrator_voice_prompt)) {
  7766. $voice_prompt_prefix .= $narrator_voice_prompt;
  7767. }
  7768. // 如果有voice_prompt信息,添加到内容开头
  7769. if (!empty($voice_prompt_prefix)) {
  7770. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7771. }
  7772. return [
  7773. 'content' => $processedContent,
  7774. 'reference_images' => $reference_images
  7775. ];
  7776. }
  7777. public function saveActVideoGenerateParams($data) {
  7778. $episode_id = getProp($data, 'episode_id');
  7779. $model = getProp($data, 'video_model');
  7780. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7781. Utils::throwError('20003:该模型不可用');
  7782. }
  7783. if (!$model) {
  7784. // 使用默认模型
  7785. $model = 'zhizhen-20';
  7786. }
  7787. // 验证模型是否在可用模型表中
  7788. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7789. Utils::throwError('20003:该模型已不可用,请更换!');
  7790. }
  7791. $video_resolution = getProp($data, 'video_resolution', '720p');
  7792. $ratio = getProp($data, 'ratio');
  7793. if (!$ratio) $ratio = '9:16';
  7794. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  7795. if (!$episode) {
  7796. Utils::throwError('20003:分集不存在');
  7797. }
  7798. try {
  7799. DB::beginTransaction();
  7800. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7801. 'video_model' => $model,
  7802. 'video_resolution' => $video_resolution,
  7803. 'ratio' => $ratio,
  7804. 'updated_at' => date('Y-m-d H:i:s')
  7805. ]);
  7806. if ($result === false) {
  7807. Utils::throwError('20003:分集视频参数保存失败');
  7808. }
  7809. // 同步更新mp_animes表
  7810. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  7811. 'video_model' => $model,
  7812. 'video_resolution' => $video_resolution,
  7813. 'video_ratio' => $ratio,
  7814. 'updated_at' => date('Y-m-d H:i:s')
  7815. ]);
  7816. if ($anime_result === false) {
  7817. Utils::throwError('20003:动漫视频参数保存失败');
  7818. }
  7819. } catch (\Exception $e) {
  7820. DB::rollBack();
  7821. Utils::throwError('20003:'.$e->getMessage());
  7822. }
  7823. DB::commit();
  7824. return $result;
  7825. }
  7826. public function confirmActs($data) {
  7827. $episode_id = getProp($data, 'episode_id');
  7828. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7829. if (!$episode) {
  7830. Utils::throwError('20003:分集不存在');
  7831. }
  7832. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7833. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7834. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7835. // 获取所有片段数据
  7836. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7837. // 收集所有资产名称(角色、场景、道具)
  7838. $product_names = [];
  7839. // 收集角色名称
  7840. foreach ($roles as $role) {
  7841. $role_name = getProp($role, 'role');
  7842. if ($role_name && $role_name != '旁白') {
  7843. $product_names[] = $role_name;
  7844. }
  7845. }
  7846. // 收集场景名称
  7847. foreach ($scenes as $scene) {
  7848. $scene_name = getProp($scene, 'scene');
  7849. if ($scene_name) {
  7850. $product_names[] = $scene_name;
  7851. }
  7852. }
  7853. // 收集道具名称
  7854. foreach ($props as $prop) {
  7855. $prop_name = getProp($prop, 'prop');
  7856. if ($prop_name) {
  7857. $product_names[] = $prop_name;
  7858. }
  7859. }
  7860. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7861. $product_names = array_unique($product_names);
  7862. usort($product_names, function($a, $b) {
  7863. return mb_strlen($b) - mb_strlen($a);
  7864. });
  7865. try {
  7866. DB::beginTransaction();
  7867. // 处理每个片段
  7868. foreach ($acts as $act) {
  7869. $act_content = getProp($act, 'act_content');
  7870. if (!$act_content) continue;
  7871. $processed_content = $act_content;
  7872. // 统一替换所有资产名称为 {资产名} 格式
  7873. // 使用占位符避免嵌套替换问题
  7874. $placeholder_map = [];
  7875. $placeholder_index = 0;
  7876. foreach ($product_names as $product_name) {
  7877. // 转义特殊字符
  7878. $escaped_product = preg_quote($product_name, '/');
  7879. // 检查是否匹配且未被 {} 包裹
  7880. $processed_content = preg_replace_callback(
  7881. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7882. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7883. // 使用唯一占位符
  7884. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7885. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7886. $placeholder_index++;
  7887. return $placeholder;
  7888. },
  7889. $processed_content
  7890. );
  7891. }
  7892. // 将所有占位符替换回实际内容
  7893. foreach ($placeholder_map as $placeholder => $replacement) {
  7894. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7895. }
  7896. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7897. $shot_counter = 0;
  7898. $processed_content = preg_replace_callback(
  7899. '/【(?:镜头|分镜)(\d+)】/u',
  7900. function($matches) use (&$shot_counter) {
  7901. $shot_counter++;
  7902. return '【镜头' . $shot_counter . '】';
  7903. },
  7904. $processed_content
  7905. );
  7906. // 更新数据库
  7907. $boolen = DB::table('mp_episode_segments')
  7908. ->where('id', $act->id)
  7909. ->update([
  7910. 'act_show_content' => $processed_content,
  7911. 'updated_at' => date('Y-m-d H:i:s')
  7912. ]);
  7913. if (!$boolen) {
  7914. Utils::throwError('20003:片段处理失败');
  7915. }
  7916. }
  7917. }catch (\Exception $e) {
  7918. DB::rollBack();
  7919. Utils::throwError('20003:'.$e->getMessage());
  7920. }
  7921. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7922. 'is_generated' => 1,
  7923. 'updated_at' => date('Y-m-d H:i:s')
  7924. ]);
  7925. if (!$boolen1) {
  7926. DB::rollBack();
  7927. Utils::throwError('20003:分集处理失败!');
  7928. }
  7929. DB::commit();
  7930. // 重新查询更新后的片段数据
  7931. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7932. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7933. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7934. $products = [];
  7935. // 先处理角色数组
  7936. foreach ($roles as $role) {
  7937. $product = $role;
  7938. // 将role字段重命名为product_name
  7939. if (isset($product['role'])) {
  7940. $product['product_name'] = $product['role'];
  7941. unset($product['role']);
  7942. $product['product'] = 1; // 标记类型为角色
  7943. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7944. }
  7945. }
  7946. // 处理场景数组
  7947. foreach ($scenes as $scene) {
  7948. $product = $scene;
  7949. // 将scene字段重命名为product_name
  7950. if (isset($product['scene'])) {
  7951. $product['product_name'] = $product['scene'];
  7952. unset($product['scene']);
  7953. $product['product'] = 2; // 标记类型为场景
  7954. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7955. }
  7956. }
  7957. // 处理道具数组(逻辑与场景一致)
  7958. foreach ($props as $prop) {
  7959. $product = $prop;
  7960. // 将prop字段重命名为product_name
  7961. if (isset($product['prop'])) {
  7962. $product['product_name'] = $product['prop'];
  7963. unset($product['prop']);
  7964. $product['product'] = 3; // 标记类型为道具
  7965. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7966. }
  7967. }
  7968. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7969. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7970. foreach ($extra_products as $extra_product) {
  7971. $product_name = getProp($extra_product, 'product_name');
  7972. if ($product_name) {
  7973. $products[$product_name] = $extra_product; // 覆盖同名数据
  7974. }
  7975. }
  7976. // 重新索引数组(去除key)
  7977. $products = array_values($products);
  7978. // 构建返回的acts数组
  7979. $return_acts = [];
  7980. foreach ($acts as $act) {
  7981. $return_acts[] = [
  7982. 'act_id' => getProp($act, 'id'),
  7983. 'act_number' => getProp($act, 'act_number'),
  7984. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7985. 'act_show_content' => getProp($act, 'act_show_content'),
  7986. 'video_url' => getProp($act, 'video_url'),
  7987. 'video_duration' => getProp($act, 'video_duration'),
  7988. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7989. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7990. ];
  7991. }
  7992. return [
  7993. 'anime_id' => getProp($episode, 'anime_id'),
  7994. 'episode_id' => $episode_id,
  7995. 'title' => getProp($episode, 'title'),
  7996. 'episode_number' => getProp($episode, 'episode_number'),
  7997. 'is_generated' => getProp($episode, 'is_generated'),
  7998. 'video_params' => [
  7999. 'video_model' => getProp($episode, 'video_model'),
  8000. 'video_resolution' => getProp($episode, 'video_resolution'),
  8001. 'ratio' => getProp($episode, 'ratio'),
  8002. ],
  8003. 'products' => $products,
  8004. 'acts' => $return_acts
  8005. ];
  8006. }
  8007. }