AnimeService.php 380 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772
  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. $input_art_style = getProp($data, 'art_style');
  181. $file = getProp($data, 'file');
  182. $content = getProp($data, 'content', '');
  183. $bid = getProp($data, 'bid', 0);
  184. $script_id = getProp($data, 'script_id', 0);
  185. $ace_mode = getProp($data, 'ace_mode', 0);
  186. $extra_products = getProp($data, 'products', []);
  187. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  188. if (!is_array($extra_products)) {
  189. Utils::throwError('20003:传入的资产格式不正确');
  190. }
  191. // 替换美术风格
  192. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  193. // 提取文件内容
  194. if ($file) {
  195. $content = $this->DeepSeekService->extractFileContent($file);
  196. if (!$content) {
  197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  198. }
  199. } elseif ($script_id) {
  200. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  201. if (!$content) {
  202. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  203. }
  204. } elseif ($bid) {
  205. $content = $this->DeepSeekService->getContentByBid($bid);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  208. }
  209. } elseif ($content) {
  210. $content = filterContent($content);
  211. }else {
  212. $content = '';
  213. }
  214. $anime_data = [
  215. 'user_id' => $uid,
  216. 'anime_name' => '新剧本策划',
  217. 'is_multi' => getProp($data, 'is_multi', 1),
  218. 'content' => $content,
  219. 'art_style_type' => $input_art_style,
  220. 'ace_mode' => $ace_mode,
  221. 'script_id' => $script_id,
  222. 'extra_products' => json_encode($extra_products, 256),
  223. 'created_at' => date('Y-m-d H:i:s'),
  224. 'updated_at' => date('Y-m-d H:i:s'),
  225. ];
  226. // 处理文本模型
  227. $model = getProp($data, 'model');
  228. if (!$model) {
  229. // 用户没有输入,使用默认值
  230. $model = 'deepseek-v4-pro';
  231. }
  232. // 验证模型是否在可用模型表中
  233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  234. $model = 'deepseek-v4-pro';
  235. }
  236. $anime_data['model'] = $model;
  237. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  238. return DB::table('mp_animes')->insertGetId($anime_data);
  239. }
  240. public function chatList($data) {
  241. $uid = Site::getUid();
  242. $anime_name = getProp($data, 'anime_name');
  243. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  244. if ($anime_name) {
  245. $query->where('anime_name', 'like', "%$anime_name%");
  246. }
  247. return $query->orderBy('id', 'desc')->paginate();
  248. }
  249. public function chatHistory($data) {
  250. $anime_id = getProp($data, 'anime_id');
  251. $sequence = getProp($data, 'sequence', 0);
  252. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  253. $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)
  254. ->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');
  255. return $query->orderBy('ar.id')->get()->map(function ($value) {
  256. $value = (array)$value;
  257. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  258. $value['created_at'] = transDate($value['created_at']);
  259. $value['episode_created_at'] = transDate($value['episode_created_at']);
  260. return $value;
  261. })->toArray();
  262. }
  263. public function batchSetRoleImg($data) {
  264. $episode_id = getProp($data, 'episode_id');
  265. if (!$episode_id) Utils::throwError('1002:请选择分集');
  266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  267. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  268. $art_style = getProp($episode, 'art_style');
  269. $anime_id = getProp($episode, 'anime_id');
  270. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  271. $art_style_type = getProp($anime, 'art_style_type');
  272. $character_prefix = '';
  273. $scene_prefix = '';
  274. if ($art_style_type) {
  275. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  276. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  277. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  278. }
  279. foreach ($roles as &$role) {
  280. $role_name = getProp($role, 'role');
  281. if ($role_name == '旁白') continue;
  282. // 优先使用 pic_prompt,如果没有则使用 description
  283. $pic_prompt = getProp($role, 'pic_prompt');
  284. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  285. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  286. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  287. // 参考图地址
  288. $ref_img_url = getProp($role, 'url');
  289. if ($ref_img_url) continue; // 已有图片则跳过
  290. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  291. try {
  292. $params = [
  293. 'prompt' => $description,
  294. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  295. ];
  296. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  297. $task_id = $task->id;
  298. if (!$task_id) {
  299. Utils::throwError("20003:角色({$role_name})生成图片失败");
  300. }
  301. $role['task_id'] = $task_id;
  302. $role['task_status'] = 'processing';
  303. } catch (\Exception $e) {
  304. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  305. Utils::throwError("20003:" . $e->getMessage());
  306. }
  307. }
  308. // 保存角色信息
  309. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  310. 'roles' => json_encode($roles, 256),
  311. 'generate_status' => '执行中',
  312. 'generate_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$boolen) {
  316. Utils::throwError('20003:保存角色信息失败');
  317. }
  318. return $boolen;
  319. }
  320. public function batchSetSceneImg($data) {
  321. $episode_id = getProp($data, 'episode_id');
  322. if (!$episode_id) Utils::throwError('1002:请选择分集');
  323. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  324. $scenes = json_decode(getProp($episode, 'scenes'), true);
  325. $art_style = getProp($episode, 'art_style');
  326. $target_scene = getProp($data, 'target_scene');
  327. $anime_id = getProp($episode, 'anime_id');
  328. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  329. $art_style_type = getProp($anime, 'art_style_type');
  330. $character_prefix = '';
  331. $scene_prefix = '';
  332. if ($art_style_type) {
  333. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  334. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  335. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  336. }
  337. foreach ($scenes as &$scene) {
  338. $scene_name = getProp($scene, 'scene');
  339. if ($scene_name != $target_scene) continue;
  340. // 优先使用 pic_prompt,如果没有则使用 description
  341. $pic_prompt = getProp($scene, 'pic_prompt');
  342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  343. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  344. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  345. // 参考图地址
  346. $ref_img_url = getProp($scene, 'url');
  347. if ($ref_img_url) continue; // 已有图片则跳过
  348. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  349. try {
  350. $params = [
  351. 'prompt' => $description,
  352. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  353. ];
  354. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  355. $task_id = $task->id;
  356. if (!$task_id) {
  357. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  358. }
  359. $scene['task_id'] = $task_id;
  360. $scene['task_status'] = 'processing';
  361. } catch (\Exception $e) {
  362. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  363. Utils::throwError("20003:" . $e->getMessage());
  364. }
  365. }
  366. // 保存场景信息
  367. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  368. 'scenes' => json_encode($scenes, 256),
  369. 'generate_status' => '执行中',
  370. 'generate_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$boolen) {
  374. Utils::throwError('20003:保存角色信息失败');
  375. }
  376. return $boolen;
  377. }
  378. public function editAnime($data) {
  379. $anime_id = getProp($data, 'anime_id');
  380. $anime_name = trim(getProp($data, 'anime_name'));
  381. // 确认对话名称唯一性
  382. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  383. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  384. }
  385. if (!$anime_id || !$anime_name) {
  386. Utils::throwError('20003:参数异常');
  387. }
  388. return DB::table('mp_animes')->where('id', $anime_id)->update([
  389. 'anime_name' => $anime_name,
  390. 'updated_at' => date('Y-m-d H:i:s')
  391. ]);
  392. // $script_arr =getProp($data, 'script', []);
  393. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  394. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  395. // $anime_id = getProp($data, 'anime_id');
  396. // try {
  397. // DB::beginTransaction();
  398. // $table_data = [
  399. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  400. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  401. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  402. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  403. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  404. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  405. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  406. // 'status' => 3,
  407. // 'start_episode_sequence' => $start_episode_sequence,
  408. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  409. // 'episode_num' => count($script_arr['episodes']),
  410. // 'updated_at' => date('Y-m-d H:i:s')
  411. // ];
  412. // // 保存剧本内容
  413. // if (!empty($anime_id)) {
  414. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  415. // if (!$boolen) {
  416. // dLog('anime')->info('对话保存失败', $table_data);
  417. // Utils::throwError('20003:对话保存失败');
  418. // }
  419. // }else {
  420. // $table['created_at'] = $table_data['updated_at'];
  421. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  422. // if (!$anime_id) {
  423. // dLog('anime')->info('对话保存失败', $table_data);
  424. // Utils::throwError('20003:对话保存失败');
  425. // }
  426. // }
  427. // // 保存分集内容
  428. // // 删除历史分集内容
  429. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  430. // $episodes = [];
  431. // $sequence = 1;
  432. // foreach ($script_arr['episodes'] as $episode) {
  433. // $segment_number = 1;
  434. // foreach($episode['segments'] as $segment) {
  435. // $episodes[] = [
  436. // 'anime_id' => $anime_id,
  437. // 'episode_number' => $episode['episode_number'],
  438. // 'title' => $episode['title'],
  439. // // 'content' => $episode['content'],
  440. // 'content' => '',
  441. // 'segment_number' => $segment_number,
  442. // 'segment_content' => $segment['segment_content'],
  443. // 'sequence' => $sequence,
  444. // 'created_at' => date('Y-m-d H:i:s'),
  445. // 'updated_at' => date('Y-m-d H:i:s')
  446. // ];
  447. // $sequence++;
  448. // $segment_number++;
  449. // }
  450. // }
  451. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  452. // if (!$boolen2) {
  453. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  454. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  455. // Utils::throwError('20003:分集内容保存失败');
  456. // }
  457. // } catch (\Exception $e) {
  458. // DB::rollBack();
  459. // Utils::throwError('20003:'.$e->getMessage());
  460. // }
  461. // DB::commit();
  462. // return true;
  463. }
  464. public function delAnime($data) {
  465. $anime_id = getProp($data, 'anime_id');
  466. if (!$anime_id) {
  467. Utils::throwError('20003:请选择剧本');
  468. }
  469. return DB::table('mp_animes')->where('id', $anime_id)->update([
  470. 'is_deleted' => 1,
  471. 'updated_at' => date('Y-m-d H:i:s')
  472. ]);
  473. }
  474. public function animeDetail($data) {
  475. $uid = Site::getUid();
  476. $anime_id = getProp($data, 'anime_id');
  477. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  478. ->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')->first();
  479. if (!$anime) Utils::throwError('20003:权限不足');
  480. $anime = (array)$anime;
  481. $anime['roles'] = json_decode($anime['roles']);
  482. $anime['scenes'] = json_decode($anime['scenes']);
  483. // 获取分集信息
  484. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  485. ->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"))
  486. ->orderBy('episode_number')->get()->map(function ($value) {
  487. return (array)$value;
  488. })->toArray();
  489. $anime['episodes'] = $episodes;
  490. return $anime;
  491. }
  492. public function episodeInfo($data) {
  493. $uid = Site::getUid();
  494. $anime_id = getProp($data, 'anime_id');
  495. $episode_id = getProp($data, 'episode_id');
  496. if (!$anime_id || !$episode_id) {
  497. Utils::throwError('1002:请选择剧集');
  498. }
  499. // 验证用户权限
  500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $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();
  503. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  504. $episode = (array)$episode;
  505. $episode['roles'] = json_decode($episode['roles'], true);
  506. // foreach($episode['roles'] as &$item) {
  507. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  508. // }
  509. $episode['scenes'] = json_decode($episode['scenes'], true);
  510. // foreach($episode['scenes'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  512. // }
  513. // 获取分镜信息
  514. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  515. ->select('*')->get()->map(function ($value) {
  516. return (array)$value;
  517. })->toArray();
  518. // 使用公共方法构建分镜结构
  519. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  520. $episode['acts'] = $segmentsStructure['acts'];
  521. $episode['total_duration'] = $segmentsStructure['total_duration'];
  522. return $episode;
  523. }
  524. public function episodeInfoForAce($data) {
  525. $anime_id = getProp($data, 'anime_id');
  526. $episode_id = getProp($data, 'episode_id');
  527. if (!$anime_id || !$episode_id) {
  528. Utils::throwError('1002:请选择剧集');
  529. }
  530. $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();
  531. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  532. $episode = (array)$episode;
  533. $episode['roles'] = json_decode($episode['roles'], true);
  534. // foreach($episode['roles'] as &$item) {
  535. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  536. // }
  537. $episode['scenes'] = json_decode($episode['scenes'], true);
  538. // foreach($episode['scenes'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  540. // }
  541. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  542. // 获取分镜信息
  543. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  544. ->select('*')->get()->map(function ($value) {
  545. return (array)$value;
  546. })->toArray();
  547. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  548. $episode['acts'] = $segmentsStructure['acts'];
  549. $episode['total_duration'] = $segmentsStructure['total_duration'];
  550. return $episode;
  551. }
  552. public function segmentInfo($data) {
  553. $uid = Site::getUid();
  554. $segment_id = getProp($data, 'segment_id');
  555. if (!$segment_id) {
  556. Utils::throwError('1002:请选择分镜');
  557. }
  558. // 获取分镜信息
  559. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  560. // 验证用户权限
  561. if ($segment) {
  562. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  563. if (!$anime) Utils::throwError('20003:权限不足');
  564. }
  565. $result = [
  566. 'segment_id' => getProp($segment, 'segment_id'),
  567. 'segment_number' => getProp($segment, 'segment_number'),
  568. 'segment_content' => getProp($segment, 'segment_content'),
  569. 'description' => getProp($segment, 'description'),
  570. 'composition' => getProp($segment, 'composition'),
  571. 'camera_movement' => getProp($segment, 'camera_movement'),
  572. 'voice_actor' => getProp($segment, 'voice_actor'),
  573. 'dialogue' => getProp($segment, 'dialogue'),
  574. 'frame_type' => getProp($segment, 'frame_type'),
  575. 'scene' => getProp($segment, 'scene'),
  576. 'characters' => getProp($segment, 'characters'),
  577. 'tail_frame' => getProp($segment, 'tail_frame'),
  578. 'emotion' => getProp($segment, 'emotion'),
  579. 'emotion_type' => getProp($segment, 'emotion_type'),
  580. 'gender' => getProp($segment, 'gender'),
  581. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  582. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  583. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  584. 'pitch' => getProp($segment, 'pitch'),
  585. 'voice_name' => getProp($segment, 'voice_name'),
  586. 'voice_type' => getProp($segment, 'voice_type'),
  587. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  588. 'img_url' => getProp($segment, 'img_url'),
  589. 'video_url' => getProp($segment, 'video_url'),
  590. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  591. ];
  592. return $result;
  593. }
  594. public function copyEpisodeVersion($data) {
  595. $episode_id = getProp($data, 'episode_id');
  596. $uid = Site::getUid();
  597. $cpid = Site::getCpid();
  598. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  599. if (!$episode) Utils::throwError('20003:该剧集不存在');
  600. $episode = (array)$episode;
  601. $anime_id = $episode['anime_id'];
  602. $episode_number = $episode['episode_number'];
  603. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  604. $sequence = $count + 1;
  605. unset($episode['id']);
  606. $now = date('Y-m-d H:i:s');
  607. $episode['created_at'] = $now;
  608. $episode['updated_at'] = $now;
  609. $episode['is_default'] = 1;
  610. // 获取版本中含有"(副本"字样的个数
  611. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  612. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  613. $episode['sequence'] = $sequence;
  614. $episode['is_generated'] = 0;
  615. $episode['cpid'] = $cpid;
  616. // 获取ace_mode
  617. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  618. try {
  619. DB::beginTransaction();
  620. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  621. // 新增副本
  622. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  623. if (!$new_episode_id) {
  624. Utils::throwError('20003:创建副本失败!');
  625. }
  626. // 获取分镜数据并准备插入
  627. $segments_for_insert = DB::table('mp_episode_segments')
  628. ->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')
  629. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  630. $item = (array)$item;
  631. $item['episode_id'] = $new_episode_id;
  632. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  633. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  634. return $item;
  635. })->toArray();
  636. // 写入分镜数据
  637. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  638. if (!$boolen2) {
  639. Utils::throwError('20003:写入分镜数据失败!');
  640. }
  641. // 写入对话历史
  642. $records = [
  643. [
  644. 'uid' => $uid,
  645. 'anime_id' => $anime_id,
  646. 'role' => 'user',
  647. 'content' => '创建副本',
  648. 'sequence' => $episode_number,
  649. 'episode_id' => $new_episode_id,
  650. 'created_at' => $now,
  651. 'updated_at' => $now
  652. ],
  653. [
  654. 'uid' => $uid,
  655. 'anime_id' => $anime_id,
  656. 'role' => 'assistant',
  657. 'content' => '好的,已为您创建副本',
  658. 'sequence' => $episode_number,
  659. 'episode_id' => $new_episode_id,
  660. 'created_at' => $now,
  661. 'updated_at' => $now
  662. ]
  663. ];
  664. $boolen3 = DB::table('mp_anime_records')->insert($records);
  665. if (!$boolen3) {
  666. Utils::throwError('20003:对话记录保存失败');
  667. }
  668. }catch (\Exception $e) {
  669. DB::rollBack();
  670. Utils::throwError('20003:'.$e->getMessage());
  671. }
  672. DB::commit();
  673. // 构建与 episodeInfo 方法一致的返回数据结构
  674. $result = [
  675. 'episode_id' => $new_episode_id,
  676. 'anime_id' => $anime_id,
  677. 'episode_number' => $episode_number,
  678. 'title' => $episode['title'],
  679. 'intro' => $episode['intro'],
  680. 'art_style' => $episode['art_style'],
  681. 'roles' => json_decode($episode['roles'], true),
  682. 'scenes' => json_decode($episode['scenes'], true),
  683. 'is_generated' => (int)$episode['is_generated']
  684. ];
  685. if ((int)$ace_mode === 1) {
  686. // 获取分镜信息
  687. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  688. ->select('*')->get()->map(function ($value) {
  689. return (array)$value;
  690. })->toArray();
  691. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  692. }else {
  693. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  694. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  695. }
  696. $result['acts'] = $segmentsStructure['acts'];
  697. $result['total_duration'] = $segmentsStructure['total_duration'];
  698. return $result;
  699. }
  700. public function episodeVersions($data) {
  701. $anime_id = getProp($data, 'anime_id');
  702. $episode_id = getProp($data, 'episode_id');
  703. if (!$anime_id || !$episode_id) {
  704. Utils::throwError('1002:请选择剧集');
  705. }
  706. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  707. $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) {
  708. return (array)$value;
  709. })->toArray();
  710. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  711. foreach($episodes as &$episode) {
  712. $episode['version'] = 'V'.$episode['sequence'];
  713. $episode['roles'] = json_decode($episode['roles'], true);
  714. $episode['scenes'] = json_decode($episode['scenes'], true);
  715. // 获取分镜信息
  716. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  717. ->select('*')->get()->map(function ($value) {
  718. return (array)$value;
  719. })->toArray();
  720. // 使用公共方法构建分镜结构
  721. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  722. $episode['acts'] = $segmentsStructure['acts'];
  723. $episode['total_duration'] = $segmentsStructure['total_duration'];
  724. }
  725. return $episodes;
  726. }
  727. public function bindEpisodeVersion($data) {
  728. $episode_id = getProp($data, 'episode_id');
  729. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  730. if (!$episode) Utils::throwError('20003:该剧集不存在');
  731. $episode = (array)$episode;
  732. if ((int)$episode['is_default'] === 1) return true;
  733. try {
  734. DB::beginTransaction();
  735. // 移除is_default标志
  736. $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')]);
  737. if (!$boolen) {
  738. Utils::throwError('20003:更新失败!');
  739. }
  740. // 绑定副本
  741. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  742. if (!$boolen2) {
  743. Utils::throwError('20003:绑定失败!');
  744. }
  745. }catch (\Exception $e) {
  746. DB::rollBack();
  747. Utils::throwError('20003:'.$e->getMessage());
  748. }
  749. DB::commit();
  750. return true;
  751. }
  752. public function chatChangeImg($data) {
  753. $segment_id = getProp($data, 'segment_id');
  754. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  755. $prompt = getProp($data, 'prompt');
  756. if (!$prompt || !$segment_id) {
  757. Utils::throwError('1002:请输入提示词,并且选择分镜');
  758. }
  759. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  760. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  761. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  762. else $ref_img_url = '';
  763. // $ref_img_url = '';
  764. if (empty($prompt)) {
  765. if (empty($ref_img_url)) {
  766. $prompt = getProp($segment, 'segment_content');
  767. }else {
  768. $prompt = '请根据图片生成';
  769. }
  770. }
  771. $anime_id = getProp($segment, 'anime_id');
  772. $episode_id = getProp($segment, 'episode_id');
  773. $episode_number = getProp($segment, 'episode_number');
  774. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  775. $ratio = getProp($data, 'ratio');
  776. if (!$ratio) {
  777. $ratio = getProp($episode, 'ratio');
  778. if (!$ratio) $ratio = '9:16';
  779. }
  780. $art_style = getProp($episode, 'art_style');
  781. if ($art_style) {
  782. $prompt = "美术风格:{$art_style}\n{$prompt}";
  783. }
  784. $dimensions = $this->getRatioDimensions($ratio);
  785. $width = $dimensions['width'];
  786. $height = $dimensions['height'];
  787. try {
  788. $params = [
  789. 'alias_segment_id' => $segment_id,
  790. 'prompt' => $prompt,
  791. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  792. 'width' => $width,
  793. 'height' => $height
  794. ];
  795. // 优化提示词(不要生成字幕)
  796. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  797. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  798. $task_id = $task->id;
  799. if (!$task_id) {
  800. Utils::throwError("20003:生成图片失败");
  801. }
  802. // 更新任务ID
  803. $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')]);
  804. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  805. } catch (\Exception $e) {
  806. Utils::throwError("20003:" . $e->getMessage());
  807. }
  808. // 创建任务之后先暂停10s等待异步任务完成
  809. sleep(10);
  810. $img_url = $this->loopGetPicTaskResult($task_id);
  811. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  812. // 图片生成后新增对话记录
  813. try {
  814. $uid = Site::getUid();
  815. $now = date('Y-m-d H:i:s');
  816. // 使用AI反推图片提示词
  817. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  818. // 保存对话记录
  819. $records = [
  820. [
  821. 'uid' => $uid,
  822. 'anime_id' => $anime_id,
  823. 'sequence' => $episode_number,
  824. 'role' => 'user',
  825. 'content' => $prompt,
  826. 'segment_id' => $segment_id,
  827. 'image_url' => '',
  828. 'created_at' => $now,
  829. 'updated_at' => $now
  830. ],
  831. [
  832. 'uid' => $uid,
  833. 'anime_id' => $anime_id,
  834. 'sequence' => $episode_number,
  835. 'role' => 'assistant',
  836. 'content' => $pic_prompt,
  837. 'segment_id' => $segment_id,
  838. 'image_url' => $img_url,
  839. 'created_at' => $now,
  840. 'updated_at' => $now
  841. ]
  842. ];
  843. DB::table('mp_anime_records')->insert($records);
  844. } catch (\Exception $e) {
  845. // 记录日志但不影响主流程
  846. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  847. 'segment_id' => $segment_id,
  848. 'img_url' => $img_url
  849. ]);
  850. logDB('anime', 'error', '保存对话记录失败', [
  851. 'segment_id' => $segment_id,
  852. 'img_url' => $img_url,
  853. 'error' => $e->getMessage()
  854. ]);
  855. }
  856. return $img_url;
  857. }
  858. public function segmentChatHistory($data) {
  859. $segment_id = getProp($data, 'segment_id');
  860. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  861. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  862. $chat = $query->orderBy('id')->get()->map(function ($value) {
  863. $value = (array)$value;
  864. $value['created_at'] = transDate($value['created_at']);
  865. return $value;
  866. })->toArray();
  867. // 获取历史图片
  868. $url = [];
  869. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  870. foreach($pic_history as $task) {
  871. $result_url = getProp($task, 'result_url');
  872. if (is_json($result_url)) {
  873. $url = array_merge($url, json_decode($result_url, true));
  874. }else {
  875. $url[] = $result_url;
  876. }
  877. }
  878. // 获取历史视频
  879. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  880. foreach($video_history as $task) {
  881. $result_url = getProp($task, 'compressed_url');
  882. if (is_json($result_url)) {
  883. $url = array_merge($url, json_decode($result_url, true));
  884. }else {
  885. $url[] = $result_url;
  886. }
  887. }
  888. return compact('chat', 'url');
  889. }
  890. public function changeEpisodeRoles($data) {
  891. $anime_id = getProp($data, 'anime_id');
  892. $episode_id = getProp($data, 'episode_id');
  893. $target_roles = getProp($data, 'roles');
  894. $is_deleted = getProp($data, 'is_deleted', 0);
  895. // 参数验证
  896. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  897. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  898. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  899. // 验证剧集是否存在
  900. $episode = DB::table('mp_anime_episodes')
  901. ->where('anime_id', $anime_id)
  902. ->where('id', $episode_id)
  903. ->first();
  904. if (!$episode) Utils::throwError('20003:该剧集不存在');
  905. $roles = json_decode(getProp($episode, 'roles'), true);
  906. // 获取anime信息,检查是否有关联的script_id
  907. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  908. if (!$anime) Utils::throwError('20003:动漫不存在');
  909. $script_id = getProp($anime, 'script_id');
  910. $episode_number = getProp($episode, 'episode_number', 1);
  911. $uid = Site::getUid();
  912. $cpid = Site::getCpid();
  913. try {
  914. $target_role_name = getProp($target_roles, 'role');
  915. // 如果是删除操作
  916. if ($is_deleted == 1) {
  917. // 从角色列表中移除该角色
  918. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  919. return getProp($role, 'role') !== $target_role_name;
  920. }));
  921. // 更新角色列表
  922. $result = DB::table('mp_anime_episodes')
  923. ->where('anime_id', $anime_id)
  924. ->where('id', $episode_id)
  925. ->update([
  926. 'roles' => json_encode($roles, 256),
  927. 'updated_at' => date('Y-m-d H:i:s')
  928. ]);
  929. if ($result === false) {
  930. Utils::throwError('20003:删除角色失败');
  931. }
  932. } else {
  933. // 新增或更新操作
  934. $role_found = false;
  935. $is_new_role = false;
  936. // 查找并更新已存在的角色
  937. foreach($roles as &$role) {
  938. if (getProp($role, 'role') === $target_role_name) {
  939. $role = $target_roles;
  940. $role_found = true;
  941. break;
  942. }
  943. }
  944. // 如果角色不存在,则新增
  945. if (!$role_found) {
  946. $roles[] = $target_roles;
  947. $is_new_role = true;
  948. }
  949. // 更新角色列表
  950. $result = DB::table('mp_anime_episodes')
  951. ->where('anime_id', $anime_id)
  952. ->where('id', $episode_id)
  953. ->update([
  954. 'roles' => json_encode($roles, 256),
  955. 'updated_at' => date('Y-m-d H:i:s')
  956. ]);
  957. if ($result === false) {
  958. Utils::throwError('20003:更新角色列表失败');
  959. }
  960. // 同步更新分镜表中对应主体的音色信息
  961. $voice_name = getProp($target_roles, 'voice_name');
  962. $voice_type = getProp($target_roles, 'voice_type');
  963. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  964. DB::table('mp_episode_segments')
  965. ->where('anime_id', $anime_id)
  966. ->where('episode_id', $episode_id)
  967. ->where('voice_actor', $target_role_name)
  968. ->update([
  969. 'voice_name' => $voice_name,
  970. 'voice_type' => $voice_type,
  971. 'voice_audio_url' => $voice_audio_url,
  972. 'updated_at' => date('Y-m-d H:i:s')
  973. ]);
  974. // 如果有关联的script_id,则同步到mp_products表
  975. if ($script_id) {
  976. // 查询剧本信息
  977. $script = DB::table('mp_scripts')
  978. ->where('id', $script_id)
  979. ->where('is_deleted', 0)
  980. ->first();
  981. if ($script) {
  982. $script_name = $script->script_name ?? 'script_' . $script_id;
  983. $product_name = getProp($target_roles, 'role');
  984. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  985. $url = getProp($target_roles, 'url', '');
  986. $product_type = 1; // 1=角色
  987. // 查找或创建以script_name命名的文件夹
  988. $folder = DB::table('mp_products')
  989. ->where('cpid', $cpid)
  990. ->where('type', 2) // 文件夹类型
  991. ->where('product', $product_type) // 角色类型
  992. ->where('product_name', $script_name)
  993. ->where('parent_id', 0)
  994. ->where('is_deleted', 0)
  995. ->first();
  996. if (!$folder) {
  997. // 创建文件夹
  998. $folder_id = DB::table('mp_products')->insertGetId([
  999. 'user_id' => $uid,
  1000. 'cpid' => $cpid,
  1001. 'type' => 2, // 文件夹
  1002. 'product' => $product_type, // 角色类型
  1003. 'parent_id' => 0,
  1004. 'level' => 1,
  1005. 'product_name' => $script_name,
  1006. 'sort_order' => time(),
  1007. 'is_deleted' => 0,
  1008. 'created_at' => date('Y-m-d H:i:s'),
  1009. 'updated_at' => date('Y-m-d H:i:s')
  1010. ]);
  1011. } else {
  1012. $folder_id = $folder->id;
  1013. }
  1014. // 查找该文件夹下是否已存在同名资产
  1015. $existing_product = DB::table('mp_products')
  1016. ->where('cpid', $cpid)
  1017. ->where('type', 1) // 资产类型
  1018. ->where('product', $product_type)
  1019. ->where('parent_id', $folder_id)
  1020. ->where('product_name', $product_name)
  1021. ->where('is_deleted', 0)
  1022. ->first();
  1023. if ($existing_product) {
  1024. // 更新已存在的资产
  1025. $updateData = [
  1026. 'pic_task_status' => '生成成功',
  1027. ];
  1028. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1029. if ($url) $updateData['url'] = $url;
  1030. // 处理versions字段
  1031. $versions = getProp($target_roles, 'versions', []);
  1032. if ($versions && is_array($versions)) {
  1033. $updateData['versions'] = json_encode($versions, 256);
  1034. }
  1035. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1036. DB::table('mp_products')
  1037. ->where('id', $existing_product->id)
  1038. ->update($updateData);
  1039. $product_id = $existing_product->id;
  1040. } else {
  1041. // 创建新资产
  1042. $versions = getProp($target_roles, 'versions', []);
  1043. $product_id = DB::table('mp_products')->insertGetId([
  1044. 'user_id' => $uid,
  1045. 'cpid' => $cpid,
  1046. 'type' => 1, // 资产
  1047. 'product' => $product_type, // 角色
  1048. 'parent_id' => $folder_id,
  1049. 'level' => 2,
  1050. 'product_name' => $product_name,
  1051. 'url' => $url,
  1052. 'pic_prompt' => $pic_prompt,
  1053. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1054. 'sort_order' => time(),
  1055. 'is_deleted' => 0,
  1056. 'pic_task_status' => '生成成功',
  1057. 'created_at' => date('Y-m-d H:i:s'),
  1058. 'updated_at' => date('Y-m-d H:i:s')
  1059. ]);
  1060. }
  1061. // 建立或更新绑定关系
  1062. $existing_mapping = DB::table('mp_script_product_mappings')
  1063. ->where('script_id', $script_id)
  1064. ->where('product_id', $product_id)
  1065. ->where('episode_number', $episode_number)
  1066. ->first();
  1067. if (!$existing_mapping) {
  1068. // 创建绑定关系
  1069. DB::table('mp_script_product_mappings')->insert([
  1070. 'script_id' => $script_id,
  1071. 'product_id' => $product_id,
  1072. 'episode_number' => $episode_number,
  1073. 'created_at' => date('Y-m-d H:i:s'),
  1074. 'updated_at' => date('Y-m-d H:i:s')
  1075. ]);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. } catch (\Exception $e) {
  1081. dLog('anime')->error('更新剧集角色失败', [
  1082. 'anime_id' => $anime_id,
  1083. 'episode_id' => $episode_id,
  1084. 'error' => $e->getMessage()
  1085. ]);
  1086. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1087. }
  1088. return true;
  1089. }
  1090. public function changeEpisodeScenes($data) {
  1091. $anime_id = getProp($data, 'anime_id');
  1092. $episode_id = getProp($data, 'episode_id');
  1093. $target_scenes = getProp($data, 'scenes');
  1094. $is_deleted = getProp($data, 'is_deleted', 0);
  1095. // 参数验证
  1096. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1097. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1098. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1099. // 验证剧集是否存在
  1100. $episode = DB::table('mp_anime_episodes')
  1101. ->where('anime_id', $anime_id)
  1102. ->where('id', $episode_id)
  1103. ->first();
  1104. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1105. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1106. // 获取anime信息,检查是否有关联的script_id
  1107. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1108. if (!$anime) Utils::throwError('20003:动漫不存在');
  1109. $script_id = getProp($anime, 'script_id');
  1110. $episode_number = getProp($episode, 'episode_number', 1);
  1111. $uid = Site::getUid();
  1112. $cpid = Site::getCpid();
  1113. try {
  1114. $target_scene_name = getProp($target_scenes, 'scene');
  1115. // 如果是删除操作
  1116. if ($is_deleted == 1) {
  1117. // 从场景列表中移除该场景
  1118. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1119. return getProp($scene, 'scene') !== $target_scene_name;
  1120. }));
  1121. // 更新场景列表
  1122. $result = DB::table('mp_anime_episodes')
  1123. ->where('anime_id', $anime_id)
  1124. ->where('id', $episode_id)
  1125. ->update([
  1126. 'scenes' => json_encode($scenes, 256),
  1127. 'updated_at' => date('Y-m-d H:i:s')
  1128. ]);
  1129. if ($result === false) {
  1130. Utils::throwError('20003:删除场景失败');
  1131. }
  1132. } else {
  1133. // 新增或更新操作
  1134. $scene_found = false;
  1135. $is_new_scene = false;
  1136. // 查找并更新已存在的场景
  1137. foreach($scenes as &$scene) {
  1138. if (getProp($scene, 'scene') === $target_scene_name) {
  1139. $scene = $target_scenes;
  1140. $scene_found = true;
  1141. break;
  1142. }
  1143. }
  1144. // 如果场景不存在,则新增
  1145. if (!$scene_found) {
  1146. $scenes[] = $target_scenes;
  1147. $is_new_scene = true;
  1148. }
  1149. // 更新场景列表
  1150. $result = DB::table('mp_anime_episodes')
  1151. ->where('anime_id', $anime_id)
  1152. ->where('id', $episode_id)
  1153. ->update([
  1154. 'scenes' => json_encode($scenes, 256),
  1155. 'updated_at' => date('Y-m-d H:i:s')
  1156. ]);
  1157. if ($result === false) {
  1158. Utils::throwError('20003:更新场景列表失败');
  1159. }
  1160. // 如果有关联的script_id,则同步到mp_products表
  1161. if ($script_id) {
  1162. // 查询剧本信息
  1163. $script = DB::table('mp_scripts')
  1164. ->where('id', $script_id)
  1165. ->where('is_deleted', 0)
  1166. ->first();
  1167. if ($script) {
  1168. $script_name = $script->script_name ?? 'script_' . $script_id;
  1169. $product_name = getProp($target_scenes, 'scene');
  1170. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1171. $url = getProp($target_scenes, 'url', '');
  1172. $product_type = 2; // 2=场景
  1173. // 查找或创建以script_name命名的文件夹
  1174. $folder = DB::table('mp_products')
  1175. ->where('cpid', $cpid)
  1176. ->where('type', 2) // 文件夹类型
  1177. ->where('product', $product_type) // 场景类型
  1178. ->where('product_name', $script_name)
  1179. ->where('parent_id', 0)
  1180. ->where('is_deleted', 0)
  1181. ->first();
  1182. if (!$folder) {
  1183. // 创建文件夹
  1184. $folder_id = DB::table('mp_products')->insertGetId([
  1185. 'user_id' => $uid,
  1186. 'cpid' => $cpid,
  1187. 'type' => 2, // 文件夹
  1188. 'product' => $product_type, // 场景类型
  1189. 'parent_id' => 0,
  1190. 'level' => 1,
  1191. 'product_name' => $script_name,
  1192. 'sort_order' => time(),
  1193. 'is_deleted' => 0,
  1194. 'created_at' => date('Y-m-d H:i:s'),
  1195. 'updated_at' => date('Y-m-d H:i:s')
  1196. ]);
  1197. } else {
  1198. $folder_id = $folder->id;
  1199. }
  1200. // 查找该文件夹下是否已存在同名资产
  1201. $existing_product = DB::table('mp_products')
  1202. ->where('cpid', $cpid)
  1203. ->where('type', 1) // 资产类型
  1204. ->where('product', $product_type)
  1205. ->where('parent_id', $folder_id)
  1206. ->where('product_name', $product_name)
  1207. ->where('is_deleted', 0)
  1208. ->first();
  1209. if ($existing_product) {
  1210. // 更新已存在的资产
  1211. $updateData = [
  1212. 'pic_task_status' => '生成成功'
  1213. ];
  1214. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1215. if ($url) $updateData['url'] = $url;
  1216. // 处理versions字段
  1217. $versions = getProp($target_scenes, 'versions', []);
  1218. if ($versions && is_array($versions)) {
  1219. $updateData['versions'] = json_encode($versions, 256);
  1220. }
  1221. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1222. DB::table('mp_products')
  1223. ->where('id', $existing_product->id)
  1224. ->update($updateData);
  1225. $product_id = $existing_product->id;
  1226. } else {
  1227. // 创建新资产
  1228. $versions = getProp($target_scenes, 'versions', []);
  1229. $product_id = DB::table('mp_products')->insertGetId([
  1230. 'user_id' => $uid,
  1231. 'cpid' => $cpid,
  1232. 'type' => 1, // 资产
  1233. 'product' => $product_type, // 场景
  1234. 'parent_id' => $folder_id,
  1235. 'level' => 2,
  1236. 'product_name' => $product_name,
  1237. 'url' => $url,
  1238. 'pic_prompt' => $pic_prompt,
  1239. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1240. 'sort_order' => time(),
  1241. 'is_deleted' => 0,
  1242. 'pic_task_status' => '生成成功',
  1243. 'created_at' => date('Y-m-d H:i:s'),
  1244. 'updated_at' => date('Y-m-d H:i:s')
  1245. ]);
  1246. }
  1247. // 建立或更新绑定关系
  1248. $existing_mapping = DB::table('mp_script_product_mappings')
  1249. ->where('script_id', $script_id)
  1250. ->where('product_id', $product_id)
  1251. ->where('episode_number', $episode_number)
  1252. ->first();
  1253. if (!$existing_mapping) {
  1254. // 创建绑定关系
  1255. DB::table('mp_script_product_mappings')->insert([
  1256. 'script_id' => $script_id,
  1257. 'product_id' => $product_id,
  1258. 'episode_number' => $episode_number,
  1259. 'created_at' => date('Y-m-d H:i:s'),
  1260. 'updated_at' => date('Y-m-d H:i:s')
  1261. ]);
  1262. }
  1263. }
  1264. }
  1265. }
  1266. } catch (\Exception $e) {
  1267. dLog('anime')->error('更新剧集场景失败', [
  1268. 'anime_id' => $anime_id,
  1269. 'episode_id' => $episode_id,
  1270. 'error' => $e->getMessage()
  1271. ]);
  1272. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1273. }
  1274. return true;
  1275. }
  1276. public function changeEpisodeProps($data) {
  1277. $anime_id = getProp($data, 'anime_id');
  1278. $episode_id = getProp($data, 'episode_id');
  1279. $target_props = getProp($data, 'props');
  1280. $is_deleted = getProp($data, 'is_deleted', 0);
  1281. // 参数验证
  1282. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1283. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1284. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1285. // 验证剧集是否存在
  1286. $episode = DB::table('mp_anime_episodes')
  1287. ->where('anime_id', $anime_id)
  1288. ->where('id', $episode_id)
  1289. ->first();
  1290. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1291. $props = json_decode(getProp($episode, 'props'), true);
  1292. // 获取anime信息,检查是否有关联的script_id
  1293. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1294. if (!$anime) Utils::throwError('20003:动漫不存在');
  1295. $script_id = getProp($anime, 'script_id');
  1296. $episode_number = getProp($episode, 'episode_number', 1);
  1297. $uid = Site::getUid();
  1298. $cpid = Site::getCpid();
  1299. try {
  1300. $target_prop_name = getProp($target_props, 'prop');
  1301. // 如果是删除操作
  1302. if ($is_deleted == 1) {
  1303. // 从道具列表中移除该道具
  1304. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1305. return getProp($prop, 'prop') !== $target_prop_name;
  1306. }));
  1307. // 更新道具列表
  1308. $result = DB::table('mp_anime_episodes')
  1309. ->where('anime_id', $anime_id)
  1310. ->where('id', $episode_id)
  1311. ->update([
  1312. 'props' => json_encode($props, 256),
  1313. 'updated_at' => date('Y-m-d H:i:s')
  1314. ]);
  1315. if ($result === false) {
  1316. Utils::throwError('20003:删除道具失败');
  1317. }
  1318. } else {
  1319. // 新增或更新操作
  1320. $prop_found = false;
  1321. $is_new_prop = false;
  1322. // 查找并更新已存在的道具
  1323. foreach($props as &$prop) {
  1324. if (getProp($prop, 'prop') === $target_prop_name) {
  1325. $prop = $target_props;
  1326. $prop_found = true;
  1327. break;
  1328. }
  1329. }
  1330. // 如果道具不存在,则新增
  1331. if (!$prop_found) {
  1332. $props[] = $target_props;
  1333. $is_new_prop = true;
  1334. }
  1335. // 更新道具列表
  1336. $result = DB::table('mp_anime_episodes')
  1337. ->where('anime_id', $anime_id)
  1338. ->where('id', $episode_id)
  1339. ->update([
  1340. 'props' => json_encode($props, 256),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. if ($result === false) {
  1344. Utils::throwError('20003:更新道具列表失败');
  1345. }
  1346. // 如果有关联的script_id,则同步到mp_products表
  1347. if ($script_id) {
  1348. // 查询剧本信息
  1349. $script = DB::table('mp_scripts')
  1350. ->where('id', $script_id)
  1351. ->where('is_deleted', 0)
  1352. ->first();
  1353. if ($script) {
  1354. $script_name = $script->script_name ?? 'script_' . $script_id;
  1355. $product_name = getProp($target_props, 'prop');
  1356. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1357. $url = getProp($target_props, 'url', '');
  1358. $product_type = 3; // 3=道具
  1359. // 查找或创建以script_name命名的文件夹
  1360. $folder = DB::table('mp_products')
  1361. ->where('cpid', $cpid)
  1362. ->where('type', 2) // 文件夹类型
  1363. ->where('product', $product_type) // 道具类型
  1364. ->where('product_name', $script_name)
  1365. ->where('parent_id', 0)
  1366. ->where('is_deleted', 0)
  1367. ->first();
  1368. if (!$folder) {
  1369. // 创建文件夹
  1370. $folder_id = DB::table('mp_products')->insertGetId([
  1371. 'user_id' => $uid,
  1372. 'cpid' => $cpid,
  1373. 'type' => 2, // 文件夹
  1374. 'product' => $product_type, // 道具类型
  1375. 'parent_id' => 0,
  1376. 'level' => 1,
  1377. 'product_name' => $script_name,
  1378. 'sort_order' => time(),
  1379. 'is_deleted' => 0,
  1380. 'created_at' => date('Y-m-d H:i:s'),
  1381. 'updated_at' => date('Y-m-d H:i:s')
  1382. ]);
  1383. } else {
  1384. $folder_id = $folder->id;
  1385. }
  1386. // 查找该文件夹下是否已存在同名资产
  1387. $existing_product = DB::table('mp_products')
  1388. ->where('cpid', $cpid)
  1389. ->where('type', 1) // 资产类型
  1390. ->where('product', $product_type)
  1391. ->where('parent_id', $folder_id)
  1392. ->where('product_name', $product_name)
  1393. ->where('is_deleted', 0)
  1394. ->first();
  1395. if ($existing_product) {
  1396. // 更新已存在的资产
  1397. $updateData = [
  1398. 'pic_task_status' => '生成成功'
  1399. ];
  1400. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1401. if ($url) $updateData['url'] = $url;
  1402. // 处理versions字段
  1403. $versions = getProp($target_props, 'versions', []);
  1404. if ($versions && is_array($versions)) {
  1405. $updateData['versions'] = json_encode($versions, 256);
  1406. }
  1407. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1408. DB::table('mp_products')
  1409. ->where('id', $existing_product->id)
  1410. ->update($updateData);
  1411. $product_id = $existing_product->id;
  1412. } else {
  1413. // 创建新资产
  1414. $versions = getProp($target_props, 'versions', []);
  1415. $product_id = DB::table('mp_products')->insertGetId([
  1416. 'user_id' => $uid,
  1417. 'cpid' => $cpid,
  1418. 'type' => 1, // 资产
  1419. 'product' => $product_type, // 道具
  1420. 'parent_id' => $folder_id,
  1421. 'level' => 2,
  1422. 'product_name' => $product_name,
  1423. 'url' => $url,
  1424. 'pic_prompt' => $pic_prompt,
  1425. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1426. 'sort_order' => time(),
  1427. 'is_deleted' => 0,
  1428. 'pic_task_status' => '生成成功',
  1429. 'created_at' => date('Y-m-d H:i:s'),
  1430. 'updated_at' => date('Y-m-d H:i:s')
  1431. ]);
  1432. }
  1433. // 建立或更新绑定关系
  1434. $existing_mapping = DB::table('mp_script_product_mappings')
  1435. ->where('script_id', $script_id)
  1436. ->where('product_id', $product_id)
  1437. ->where('episode_number', $episode_number)
  1438. ->first();
  1439. if (!$existing_mapping) {
  1440. // 创建绑定关系
  1441. DB::table('mp_script_product_mappings')->insert([
  1442. 'script_id' => $script_id,
  1443. 'product_id' => $product_id,
  1444. 'episode_number' => $episode_number,
  1445. 'created_at' => date('Y-m-d H:i:s'),
  1446. 'updated_at' => date('Y-m-d H:i:s')
  1447. ]);
  1448. }
  1449. }
  1450. }
  1451. }
  1452. } catch (\Exception $e) {
  1453. dLog('anime')->error('更新剧集道具失败', [
  1454. 'anime_id' => $anime_id,
  1455. 'episode_id' => $episode_id,
  1456. 'error' => $e->getMessage()
  1457. ]);
  1458. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1459. }
  1460. return true;
  1461. }
  1462. public function editSegment($data) {
  1463. $segment_id = getProp($data, 'segment_id');
  1464. $segment_content = getProp($data, 'segment_content');
  1465. $image_url = getProp($data, 'image_url');
  1466. $video_url = getProp($data, 'video_url');
  1467. // 参数验证
  1468. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1469. // 验证分镜是否存在
  1470. $segment = DB::table('mp_episode_segments')
  1471. ->where('segment_id', $segment_id)
  1472. ->first();
  1473. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1474. $dubTaskId = 0;
  1475. try {
  1476. DB::beginTransaction();
  1477. // 准备更新数据
  1478. $update_data = [
  1479. 'updated_at' => date('Y-m-d H:i:s')
  1480. ];
  1481. if ($segment_content) {
  1482. // 先将segment_content赋值到update_data
  1483. $update_data['segment_content'] = $segment_content;
  1484. // 使用现有方法分析segment_content,提取各个字段
  1485. $this->handleSegmentContent($update_data);
  1486. // 如果有对话内容,创建视频配音合成任务
  1487. $dialogue = getProp($update_data, 'dialogue');
  1488. if (!empty($dialogue)) {
  1489. $now = date('Y-m-d H:i:s');
  1490. $generate_json = [
  1491. 'text' => $dialogue,
  1492. 'role' => getProp($update_data, 'voice_actor'),
  1493. 'voice_type' => getProp($update_data, 'voice_type'),
  1494. 'voice_name' => getProp($update_data, 'voice_name'),
  1495. 'emotion' => getProp($update_data, 'emotion'),
  1496. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1497. 'gender' => getProp($update_data, 'gender'),
  1498. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1499. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1500. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1501. 'pitch' => getProp($update_data, 'pitch', 0),
  1502. ];
  1503. // 插入视频配音合成任务
  1504. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1505. 'alias_segment_id' => $segment_id,
  1506. 'generate_status' => '执行中',
  1507. 'audio_url' => '',
  1508. 'generate_json' => json_encode($generate_json, 256),
  1509. 'created_at' => $now,
  1510. 'updated_at' => $now,
  1511. ]);
  1512. if (!$dubTaskId) {
  1513. Utils::throwError('20003:创建配音任务失败!');
  1514. }
  1515. $update_data['audio_url'] = '';
  1516. } else {
  1517. // dialogue为空时,直接写入默认音频信息
  1518. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1519. $update_data['audio_duration'] = 2.0;
  1520. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1521. }
  1522. }
  1523. if ($image_url) {
  1524. $update_data['img_url'] = $image_url;
  1525. // 同时写入一个简单的图片生成任务
  1526. $pic_task = [
  1527. 'alias_segment_id' => $segment_id,
  1528. 'ref_img_url' => json_encode([]),
  1529. 'status' => 'success',
  1530. 'result_url' => json_encode([$image_url], 256),
  1531. 'model' => '',
  1532. 'created_at' => date('Y-m-d H:i:s'),
  1533. 'updated_at' => date('Y-m-d H:i:s'),
  1534. ];
  1535. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1536. }
  1537. if ($video_url) {
  1538. $update_data['origin_video_url'] = $video_url;
  1539. $compressed_video_url = compressVideo($video_url);
  1540. $update_data['current_type'] = 2;
  1541. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1542. // 同时写入一个简单的视频生成任务
  1543. $video_task = [
  1544. 'alias_segment_id' => $segment_id,
  1545. 'status' => 'success',
  1546. 'result_url' => $update_data['origin_video_url'],
  1547. 'compressed_url' => $update_data['video_url'],
  1548. 'created_at' => date('Y-m-d H:i:s'),
  1549. 'updated_at' => date('Y-m-d H:i:s'),
  1550. ];
  1551. DB::table('mp_generate_video_tasks')->insert($video_task);
  1552. }
  1553. // 更新分镜信息
  1554. $result = DB::table('mp_episode_segments')
  1555. ->where('segment_id', $segment_id)
  1556. ->update($update_data);
  1557. if ($result === false) {
  1558. Utils::throwError('20003:更新分镜剧本失败');
  1559. }
  1560. DB::commit();
  1561. // 如果有创建音频生成任务则调用API
  1562. if ($dubTaskId) {
  1563. // 请求远程服务器执行生成
  1564. $client = new Client(['timeout' => 300, 'verify' => false]);
  1565. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1566. $response = $result->getBody()->getContents();
  1567. $response_arr = json_decode($response, true);
  1568. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1569. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1570. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1571. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1572. Utils::throwError('20003:火山生成音频失败');
  1573. }
  1574. }
  1575. return true;
  1576. } catch (\Exception $e) {
  1577. DB::rollBack();
  1578. dLog('anime')->error('更新分镜剧本失败', [
  1579. 'segment_id' => $segment_id,
  1580. 'error' => $e->getMessage()
  1581. ]);
  1582. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1583. }
  1584. }
  1585. public function batchSetSegmentPics($data) {
  1586. $anime_id = getProp($data, 'anime_id');
  1587. $episode_id = getProp($data, 'episode_id');
  1588. $ratio = getProp($data, 'ratio');
  1589. $dimensions = $this->getRatioDimensions($ratio);
  1590. $width = $dimensions['width'];
  1591. $height = $dimensions['height'];
  1592. if (!$anime_id || !$episode_id) {
  1593. Utils::throwError('1002:请选择剧集');
  1594. }
  1595. // 获取剧集信息
  1596. $episode = DB::table('mp_anime_episodes')
  1597. ->where('anime_id', $anime_id)
  1598. ->where('id', $episode_id)
  1599. ->where('is_default', 1)
  1600. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1601. ->first();
  1602. if (!$episode) {
  1603. Utils::throwError('20003:该剧集不存在');
  1604. }
  1605. $model = getProp($data, 'model');
  1606. if (!$model) {
  1607. $model = getProp($episode, 'image_model');
  1608. if (!$model) {
  1609. // episode表也没有,使用默认值
  1610. $model = 'doubao-seedream-5-0-lite-260128';
  1611. }
  1612. }
  1613. // 验证模型是否在可用模型表中
  1614. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1615. $model = 'doubao-seedream-5-0-lite-260128';
  1616. }
  1617. $roles = json_decode(getProp($episode, 'roles'), true);
  1618. if (!$roles) {
  1619. Utils::throwError('20003:角色信息格式错误');
  1620. }
  1621. // 构建角色名称到参考图的映射
  1622. $role_map = [];
  1623. foreach ($roles as $role) {
  1624. $role_name = getProp($role, 'role');
  1625. $role_url = getProp($role, 'url');
  1626. if (!empty($role_name) && !empty($role_url)) {
  1627. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1628. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1629. // $role_map[$base_name] = $role_url;
  1630. // 同时保存完整名称的映射
  1631. $role_map[$role_name] = $role_url;
  1632. }
  1633. }
  1634. $scenes = json_decode(getProp($episode, 'roles'), true);
  1635. if (!$scenes) {
  1636. Utils::throwError('20003:场景信息格式错误');
  1637. }
  1638. // 构建角色名称到参考图的映射
  1639. $scene_map = [];
  1640. foreach ($scenes as $scene) {
  1641. $scene_name = getProp($scene, 'scene');
  1642. $scene_url = getProp($scene, 'url');
  1643. if (!empty($scene_name) && !empty($scene_url)) {
  1644. $scene_map[$scene_name] = $scene_url;
  1645. }
  1646. }
  1647. // 获取所有分镜信息
  1648. $segments = DB::table('mp_episode_segments')
  1649. ->where('anime_id', $anime_id)
  1650. ->where('episode_id', $episode_id)
  1651. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1652. ->orderBy('segment_number')
  1653. ->get()
  1654. ->toArray();
  1655. if (empty($segments)) {
  1656. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1657. }
  1658. // 保存图片比例
  1659. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1660. $updated_segments = [];
  1661. $failed_segments = [];
  1662. // 批量为每个分镜生成图片任务
  1663. foreach ($segments as $segment) {
  1664. $segment_id = $segment->segment_id;
  1665. $segment_content = $segment->segment_content;
  1666. if (empty($segment_content)) {
  1667. $failed_segments[] = [
  1668. 'segment_id' => $segment_id,
  1669. 'error' => '分镜内容为空'
  1670. ];
  1671. continue;
  1672. }
  1673. try {
  1674. $dubTaskId = 0;
  1675. // 解析分镜内容,提取画面描述作为主要提示词
  1676. $prompt = $segment_content;
  1677. $ref_img_urls = [];
  1678. // 分镜场景
  1679. $scene = getProp($segment, 'scene');
  1680. $matched_scene = '';
  1681. if (isset($scene_map[$scene])) {
  1682. $img_index = count($ref_img_urls) + 1;
  1683. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1684. $ref_img_urls[] = $scene_map[$scene];
  1685. $matched_scene = $scene;
  1686. }
  1687. // 分镜角色
  1688. $characters = getProp($segment, 'characters');
  1689. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1690. $roles = explode(',', $characters);
  1691. // 从分镜内容中提取涉及的角色
  1692. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1693. // 获取匹配角色的参考图
  1694. foreach ($segment_characters as $character) {
  1695. if (isset($role_map[$character])) {
  1696. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1697. $img_index = count($ref_img_urls) + 1;
  1698. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1699. $ref_img_urls[] = $role_map[$character];
  1700. }
  1701. }
  1702. // 如果没有找到匹配的角色参考图,不使用参考图
  1703. if (empty($ref_img_urls)) {
  1704. $ref_img_urls = [];
  1705. }
  1706. // 准备生成任务参数
  1707. $params = [
  1708. 'model' => $model,
  1709. 'alias_segment_id' => $segment_id,
  1710. 'prompt' => $prompt,
  1711. 'ref_img_urls' => $ref_img_urls,
  1712. 'width' => $width,
  1713. 'height' => $height,
  1714. ];
  1715. // 优化提示词(不要生成字幕)
  1716. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1717. // $task_id = mt_rand(100000, 999999);
  1718. // 调用AI图片生成服务
  1719. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1720. $task_id = $task->id;
  1721. if (!$task_id) {
  1722. $failed_segments[] = [
  1723. 'segment_id' => $segment_id,
  1724. 'error' => '创建生成任务失败'
  1725. ];
  1726. continue;
  1727. }
  1728. $update_data = [
  1729. 'pic_task_id' => $task_id,
  1730. 'pic_task_status' => '生成中',
  1731. 'audio_url' => '',
  1732. 'updated_at' => date('Y-m-d H:i:s')
  1733. ];
  1734. // 如果有对话内容,创建视频配音合成任务
  1735. $dialogue = getProp($segment, 'dialogue');
  1736. if (!empty($dialogue)) {
  1737. $now = date('Y-m-d H:i:s');
  1738. $generate_json = [
  1739. 'text' => $dialogue,
  1740. 'role' => getProp($segment, 'voice_actor'),
  1741. 'voice_type' => getProp($segment, 'voice_type'),
  1742. 'voice_name' => getProp($segment, 'voice_name'),
  1743. 'emotion' => getProp($segment, 'emotion'),
  1744. 'emotion_type' => getProp($segment, 'emotion_type'),
  1745. 'gender' => getProp($segment, 'gender'),
  1746. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1747. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1748. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1749. 'pitch' => getProp($segment, 'pitch', 0),
  1750. ];
  1751. // 插入视频配音合成任务
  1752. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1753. 'alias_segment_id' => $segment_id,
  1754. 'generate_status' => '执行中',
  1755. 'audio_url' => '',
  1756. 'generate_json' => json_encode($generate_json, 256),
  1757. 'created_at' => $now,
  1758. 'updated_at' => $now,
  1759. ]);
  1760. if (!$dubTaskId) {
  1761. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1762. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1763. // Utils::throwError('20003:创建配音任务失败!');
  1764. }
  1765. } else {
  1766. // dialogue为空时,直接写入默认音频信息到分镜表
  1767. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1768. $update_data['audio_duration'] = 2.0;
  1769. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1770. }
  1771. // 更新分镜的任务信息
  1772. $update_result = DB::table('mp_episode_segments')
  1773. ->where('segment_id', $segment_id)
  1774. ->update($update_data);
  1775. // 如果是第一集的首帧图片,则存入待更新数组
  1776. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1777. Redis::sadd('anime_first_frame_urls', $segment_id);
  1778. }
  1779. if ($update_result) {
  1780. $updated_segments[] = [
  1781. 'segment_id' => $segment_id,
  1782. 'task_id' => $task_id,
  1783. 'status' => '生成中',
  1784. 'matched_scenes' => $matched_scene,
  1785. 'matched_roles' => $segment_characters,
  1786. 'ref_urls_count' => count($ref_img_urls)
  1787. ];
  1788. } else {
  1789. $failed_segments[] = [
  1790. 'segment_id' => $segment_id,
  1791. 'error' => '更新分镜任务状态失败'
  1792. ];
  1793. }
  1794. if ($dubTaskId) {
  1795. sleep(1);
  1796. // 请求远程服务器执行生成
  1797. $client = new Client(['timeout' => 300, 'verify' => false]);
  1798. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1799. $response = $result->getBody()->getContents();
  1800. $response_arr = json_decode($response, true);
  1801. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1802. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1803. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1804. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1805. }
  1806. }
  1807. } catch (\Exception $e) {
  1808. $failed_segments[] = [
  1809. 'segment_id' => $segment_id,
  1810. 'error' => $e->getMessage()
  1811. ];
  1812. }
  1813. }
  1814. // 更新剧集生成状态
  1815. if (!empty($updated_segments)) {
  1816. DB::table('mp_anime_episodes')
  1817. ->where('id', $episode_id)
  1818. ->update([
  1819. 'is_generated' => 1,
  1820. 'updated_at' => date('Y-m-d H:i:s')
  1821. ]);
  1822. }
  1823. return [
  1824. 'success_count' => count($updated_segments),
  1825. 'failed_count' => count($failed_segments),
  1826. 'success_segments' => $updated_segments,
  1827. 'failed_segments' => $failed_segments,
  1828. 'total_segments' => count($segments)
  1829. ];
  1830. }
  1831. public function reGenerateSegment($data) {
  1832. $segment_id = getProp($data, 'segment_id');
  1833. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1834. $anime_id = getProp($segment, 'anime_id');
  1835. $episode_id = getProp($segment, 'episode_id');
  1836. $episode_number = getProp($segment, 'episode_number');
  1837. $segment_content = getProp($data, 'segment_content');
  1838. $ratio = getProp($data, 'ratio');
  1839. if (!$ratio) {
  1840. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1841. if (!$ratio) $ratio = '9:16';
  1842. }
  1843. $dimensions = $this->getRatioDimensions($ratio);
  1844. $width = $dimensions['width'];
  1845. $height = $dimensions['height'];
  1846. if (!$anime_id || !$episode_id) {
  1847. Utils::throwError('1002:请选择分镜');
  1848. }
  1849. // 使用文生文模型重新解析segment_content
  1850. if (!empty($segment_content)) {
  1851. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1852. }
  1853. // 获取动漫的角色信息(包含参考图)
  1854. $anime = DB::table('mp_animes')
  1855. ->where('id', $anime_id)
  1856. ->select('roles', 'scenes')
  1857. ->first();
  1858. if (!$anime || !$anime->roles) {
  1859. Utils::throwError('20003:未找到角色信息');
  1860. }
  1861. $roles = json_decode($anime->roles, true);
  1862. if (!$roles) {
  1863. Utils::throwError('20003:角色信息格式错误');
  1864. }
  1865. // 构建角色名称到参考图的映射
  1866. $role_map = [];
  1867. foreach ($roles as $role) {
  1868. $role_name = getProp($role, 'role');
  1869. $role_url = getProp($role, 'url');
  1870. if (!empty($role_name) && !empty($role_url)) {
  1871. $role_map[$role_name] = $role_url;
  1872. }
  1873. }
  1874. $scenes = json_decode($anime->scenes, true);
  1875. if (!$scenes) {
  1876. Utils::throwError('20003:角色信息格式错误');
  1877. }
  1878. // 构建角色名称到参考图的映射
  1879. $scene_map = [];
  1880. foreach ($scenes as $scene) {
  1881. $scene_name = getProp($scene, 'scene');
  1882. $scene_url = getProp($scene, 'url');
  1883. if (!empty($scene_name) && !empty($scene_url)) {
  1884. $scene_map[$scene_name] = $scene_url;
  1885. }
  1886. }
  1887. $segment_id = $segment->segment_id;
  1888. $original_segment_content = $segment->segment_content;
  1889. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1890. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1891. if (empty($final_segment_content)) {
  1892. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1893. }
  1894. try {
  1895. $dubTaskId = 0;
  1896. // 分镜剧本数组
  1897. $update_data = [
  1898. 'segment_content' => $final_segment_content,
  1899. 'pic_task_status' => '生成中',
  1900. 'updated_at' => date('Y-m-d H:i:s')
  1901. ];
  1902. // 解析分镜内容,提取画面描述作为主要提示词
  1903. $prompt = $final_segment_content;
  1904. $ref_img_urls = [];
  1905. // 分镜场景
  1906. $scene = getProp($data, 'scene');
  1907. if ($scene) {
  1908. $matched_scene = '';
  1909. if (isset($scene_map[$scene])) {
  1910. $img_index = count($ref_img_urls) + 1;
  1911. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1912. $ref_img_urls[] = $scene_map[$scene];
  1913. $matched_scene = $scene;
  1914. }
  1915. $update_data['scene'] = $scene;
  1916. }
  1917. // 分镜角色
  1918. $characters = getProp($data, 'characters');
  1919. if ($characters) {
  1920. $update_data['characters'] = $characters;
  1921. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1922. $characters = explode(',', $characters);
  1923. // 从分镜内容中提取涉及的角色
  1924. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1925. // 获取匹配角色的参考图
  1926. foreach ($segment_characters as $character) {
  1927. if (isset($role_map[$character])) {
  1928. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1929. $img_index = count($ref_img_urls) + 1;
  1930. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1931. $ref_img_urls[] = $role_map[$character];
  1932. }
  1933. }
  1934. }
  1935. // 如果没有找到匹配的角色参考图,不使用参考图
  1936. if (empty($ref_img_urls)) {
  1937. $ref_img_urls = [];
  1938. }
  1939. // 准备生成任务参数
  1940. $params = [
  1941. 'alias_segment_id' => $segment_id,
  1942. 'prompt' => $prompt,
  1943. 'ref_img_urls' => $ref_img_urls,
  1944. 'width' => $width,
  1945. 'height' => $height,
  1946. ];
  1947. // 优化提示词(不要生成字幕)
  1948. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1949. // 调用AI图片生成服务
  1950. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1951. $task_id = $task->id;
  1952. if (!$task_id) {
  1953. Utils::throwError('20003:创建生成任务失败!');
  1954. }
  1955. $update_data['pic_task_id'] = $task_id;
  1956. // 更新分镜剧本信息
  1957. $this->handleSegmentContent($update_data);
  1958. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1959. if ($segment_content) {
  1960. $dialogue = getProp($update_data, 'dialogue');
  1961. if (!empty($dialogue)) {
  1962. $now = date('Y-m-d H:i:s');
  1963. $generate_json = [
  1964. 'text' => $dialogue,
  1965. 'role' => getProp($update_data, 'voice_actor'),
  1966. 'voice_type' => getProp($update_data, 'voice_type'),
  1967. 'voice_name' => getProp($update_data, 'voice_name'),
  1968. 'emotion' => getProp($update_data, 'emotion'),
  1969. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1970. 'gender' => getProp($update_data, 'gender'),
  1971. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1972. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1973. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1974. 'pitch' => getProp($update_data, 'pitch', 0),
  1975. ];
  1976. // 插入视频配音合成任务
  1977. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1978. 'alias_segment_id' => $segment_id,
  1979. 'generate_status' => '执行中',
  1980. 'audio_url' => '',
  1981. 'generate_json' => json_encode($generate_json, 256),
  1982. 'created_at' => date('Y-m-d H:i:s'),
  1983. 'updated_at' => date('Y-m-d H:i:s'),
  1984. ]);
  1985. if (!$dubTaskId) {
  1986. Utils::throwError('20003:创建配音任务失败!');
  1987. }
  1988. $update_data['audio_url'] = '';
  1989. } else {
  1990. // dialogue为空时,直接写入默认音频信息
  1991. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1992. $update_data['audio_duration'] = 2.0;
  1993. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1994. }
  1995. }
  1996. $boolen = DB::table('mp_episode_segments')
  1997. ->where('segment_id', $segment_id)
  1998. ->update($update_data);
  1999. // 如果是第一集的首帧图片,则存入待更新数组
  2000. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2001. Redis::sadd('anime_first_frame_urls', $segment_id);
  2002. }
  2003. if ($dubTaskId) {
  2004. // 请求远程服务器执行生成
  2005. $client = new Client(['timeout' => 300, 'verify' => false]);
  2006. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2007. $response = $result->getBody()->getContents();
  2008. $response_arr = json_decode($response, true);
  2009. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2010. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2011. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2012. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2013. Utils::throwError('20003:火山生成音频失败');
  2014. }
  2015. }
  2016. } catch (\Exception $e) {
  2017. $failed_segments[] = [
  2018. 'segment_id' => $segment_id,
  2019. 'error' => $e->getMessage()
  2020. ];
  2021. }
  2022. // 创建任务之后先暂停10s等待异步任务完成
  2023. sleep(10);
  2024. $img_url = $this->loopGetPicTaskResult($task_id);
  2025. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2026. // 图片生成后新增对话记录
  2027. try {
  2028. $uid = Site::getUid();
  2029. $now = date('Y-m-d H:i:s');
  2030. // 使用AI反推图片提示词
  2031. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2032. // 保存对话记录
  2033. $records = [
  2034. [
  2035. 'uid' => $uid,
  2036. 'anime_id' => $anime_id,
  2037. 'sequence' => $episode_number,
  2038. 'role' => 'user',
  2039. 'content' => '重新生成',
  2040. 'segment_id' => $segment_id,
  2041. 'image_url' => '',
  2042. 'created_at' => $now,
  2043. 'updated_at' => $now
  2044. ],
  2045. [
  2046. 'uid' => $uid,
  2047. 'anime_id' => $anime_id,
  2048. 'sequence' => $episode_number,
  2049. 'role' => 'assistant',
  2050. 'content' => $pic_prompt,
  2051. 'segment_id' => $segment_id,
  2052. 'image_url' => $img_url,
  2053. 'created_at' => $now,
  2054. 'updated_at' => $now
  2055. ]
  2056. ];
  2057. DB::table('mp_anime_records')->insert($records);
  2058. } catch (\Exception $e) {
  2059. // 记录日志但不影响主流程
  2060. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2061. 'segment_id' => $segment_id,
  2062. 'img_url' => $img_url
  2063. ]);
  2064. }
  2065. return $img_url;
  2066. }
  2067. public function addSegment($data) {
  2068. $prev_segment_id = getProp($data, 'prev_segment_id');
  2069. $img_url = getProp($data, 'img_url');
  2070. $video_url = getProp($data, 'video_url');
  2071. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2072. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2073. $anime_id = getProp($segment, 'anime_id');
  2074. $episode_id = getProp($segment, 'episode_id');
  2075. $episode_number = getProp($segment, 'episode_number');
  2076. $segment_number = getProp($segment, 'segment_number');
  2077. $new_segment_number = $segment_number + 1;
  2078. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2079. // 分镜剧本数组
  2080. $insert_data = [
  2081. 'anime_id' => $anime_id,
  2082. 'episode_id' => $episode_id,
  2083. 'episode_number' => $episode_number,
  2084. 'act_number' => getProp($segment, 'act_number'),
  2085. 'act_title' => getProp($segment, 'act_title'),
  2086. 'segment_id' => $segment_id,
  2087. 'segment_number' => $new_segment_number,
  2088. 'segment_content' => '',
  2089. 'img_url' => '',
  2090. 'video_url' => '',
  2091. 'created_at' => date('Y-m-d H:i:s'),
  2092. 'updated_at' => date('Y-m-d H:i:s')
  2093. ];
  2094. if ($img_url) $insert_data['img_url'] = $img_url;
  2095. if ($video_url) {
  2096. $insert_data['origin_video_url'] = $video_url;
  2097. $insert_data['current_type'] = 2;
  2098. $compressed_video_url = compressVideo($video_url);
  2099. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2100. }
  2101. try {
  2102. DB::beginTransaction();
  2103. // 先更新序号
  2104. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2105. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2106. if (!$id) {
  2107. Utils::throwError('20003:新增分镜失败!');
  2108. }
  2109. }catch (\Exception $e) {
  2110. DB::rollBack();
  2111. Utils::throwError('20003:'.$e->getMessage());
  2112. }
  2113. DB::commit();
  2114. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2115. $segment = $segment ? (array)$segment : [];
  2116. return $segment;
  2117. // 以下代码暂弃用
  2118. $anime_id = getProp($segment, 'anime_id');
  2119. $episode_id = getProp($segment, 'episode_id');
  2120. $episode_number = getProp($segment, 'episode_number');
  2121. $segment_number = getProp($segment, 'segment_number');
  2122. $segment_content = getProp($data, 'segment_content');
  2123. $img_url = getProp($data, 'img_url');
  2124. $video_url = getProp($data, 'video_url');
  2125. $ratio = getProp($data, 'ratio');
  2126. $dimensions = $this->getRatioDimensions($ratio);
  2127. $width = $dimensions['width'];
  2128. $height = $dimensions['height'];
  2129. if (!$anime_id || !$episode_id) {
  2130. Utils::throwError('1002:请选择分镜');
  2131. }
  2132. // 使用文生文模型重新解析segment_content
  2133. if (!empty($segment_content)) {
  2134. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2135. }
  2136. // 获取动漫的角色信息(包含参考图)
  2137. $anime = DB::table('mp_animes')
  2138. ->where('id', $anime_id)
  2139. ->select('roles', 'scenes')
  2140. ->first();
  2141. if (!$anime || !$anime->roles) {
  2142. Utils::throwError('20003:未找到角色信息');
  2143. }
  2144. $roles = json_decode($anime->roles, true);
  2145. if (!$roles) {
  2146. Utils::throwError('20003:角色信息格式错误');
  2147. }
  2148. // 构建角色名称到参考图的映射
  2149. $role_map = [];
  2150. foreach ($roles as $role) {
  2151. $role_name = getProp($role, 'role');
  2152. $role_url = getProp($role, 'url');
  2153. if (!empty($role_name) && !empty($role_url)) {
  2154. $role_map[$role_name] = $role_url;
  2155. }
  2156. }
  2157. $scenes = json_decode($anime->scenes, true);
  2158. if (!$scenes) {
  2159. Utils::throwError('20003:角色信息格式错误');
  2160. }
  2161. // 构建角色名称到参考图的映射
  2162. $scene_map = [];
  2163. foreach ($scenes as $scene) {
  2164. $scene_name = getProp($scene, 'scene');
  2165. $scene_url = getProp($scene, 'url');
  2166. if (!empty($scene_name) && !empty($scene_url)) {
  2167. $scene_map[$scene_name] = $scene_url;
  2168. }
  2169. }
  2170. $segment_id = $segment->segment_id;
  2171. $original_segment_content = $segment->segment_content;
  2172. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2173. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2174. if (empty($final_segment_content)) {
  2175. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2176. }
  2177. try {
  2178. $dubTaskId = 0;
  2179. DB::beginTransaction();
  2180. $new_segment_number = $segment_number + 1;
  2181. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2182. // 分镜剧本数组
  2183. $insert_data = [
  2184. 'anime_id' => $anime_id,
  2185. 'episode_id' => $episode_id,
  2186. 'episode_number' => $episode_number,
  2187. 'act_number' => getProp($segment, 'act_number'),
  2188. 'act_title' => getProp($segment, 'act_title'),
  2189. 'segment_id' => $segment_id,
  2190. 'segment_number' => $new_segment_number,
  2191. 'segment_content' => $final_segment_content,
  2192. 'img_url' => $img_url,
  2193. 'video_url' => $video_url,
  2194. 'created_at' => date('Y-m-d H:i:s'),
  2195. 'updated_at' => date('Y-m-d H:i:s')
  2196. ];
  2197. // 更新分镜剧本信息
  2198. $this->handleSegmentContent($insert_data);
  2199. // 如果有对话内容,创建视频配音合成任务
  2200. $dialogue = getProp($insert_data, 'dialogue');
  2201. if (!empty($dialogue)) {
  2202. $now = date('Y-m-d H:i:s');
  2203. $generate_json = [
  2204. 'text' => $dialogue,
  2205. 'role' => getProp($insert_data, 'voice_actor'),
  2206. 'voice_type' => getProp($insert_data, 'voice_type'),
  2207. 'voice_name' => getProp($insert_data, 'voice_name'),
  2208. 'emotion' => getProp($insert_data, 'emotion'),
  2209. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2210. 'gender' => getProp($insert_data, 'gender'),
  2211. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2212. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2213. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2214. 'pitch' => getProp($insert_data, 'pitch', 0),
  2215. ];
  2216. // 插入视频配音合成任务
  2217. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2218. 'alias_segment_id' => $segment_id,
  2219. 'generate_status' => '执行中',
  2220. 'audio_url' => '',
  2221. 'generate_json' => json_encode($generate_json, 256),
  2222. 'created_at' => $now,
  2223. 'updated_at' => $now,
  2224. ]);
  2225. if (!$dubTaskId) {
  2226. Utils::throwError('20003:创建配音任务失败!');
  2227. }
  2228. $insert_data['audio_url'] = '';
  2229. } else {
  2230. // dialogue为空时,直接写入默认音频信息
  2231. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2232. $insert_data['audio_duration'] = 2.0;
  2233. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2234. }
  2235. // 如果没有上传图片则使用当前描述进行生成
  2236. if (!$img_url) {
  2237. // 解析分镜内容,提取画面描述作为主要提示词
  2238. $prompt = $final_segment_content;
  2239. $ref_img_urls = [];
  2240. // 分镜场景
  2241. $scene = getProp($insert_data, 'scene');
  2242. if ($scene) {
  2243. $matched_scene = '';
  2244. if (isset($scene_map[$scene])) {
  2245. $img_index = count($ref_img_urls) + 1;
  2246. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2247. $ref_img_urls[] = $scene_map[$scene];
  2248. $matched_scene = $scene;
  2249. }
  2250. $update_data['scene'] = $scene;
  2251. }
  2252. // 分镜角色
  2253. $characters = getProp($insert_data, 'characters');
  2254. if ($characters) {
  2255. $update_data['characters'] = $characters;
  2256. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2257. $characters = explode(',', $characters);
  2258. // 从分镜内容中提取涉及的角色
  2259. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2260. // 获取匹配角色的参考图
  2261. foreach ($segment_characters as $character) {
  2262. if (isset($role_map[$character])) {
  2263. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2264. $img_index = count($ref_img_urls) + 1;
  2265. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2266. $ref_img_urls[] = $role_map[$character];
  2267. }
  2268. }
  2269. }
  2270. // 如果没有找到匹配的角色参考图,不使用参考图
  2271. if (empty($ref_img_urls)) {
  2272. $ref_img_urls = [];
  2273. }
  2274. // 准备生成任务参数
  2275. $params = [
  2276. 'alias_segment_id' => $segment_id,
  2277. 'prompt' => $prompt,
  2278. 'ref_img_urls' => $ref_img_urls,
  2279. 'width' => $width,
  2280. 'height' => $height,
  2281. ];
  2282. // 调用AI图片生成服务
  2283. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2284. $task_id = $task->id;
  2285. // $task_id = 'whatever';
  2286. if (!$task_id) {
  2287. Utils::throwError('20003:创建生成任务失败!');
  2288. }
  2289. $insert_data['pic_task_status'] = '生成中';
  2290. $insert_data['pic_task_id'] = $task_id;
  2291. }
  2292. // 先更新序号
  2293. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2294. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2295. if (!$boolen) {
  2296. Utils::throwError('20003:新增分镜失败!');
  2297. }
  2298. // 如果是第一集的首帧图片,则存入待更新数组
  2299. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2300. Redis::sadd('anime_first_frame_urls', $segment_id);
  2301. }
  2302. if ($dubTaskId) {
  2303. // 请求远程服务器执行生成
  2304. $client = new Client(['timeout' => 300, 'verify' => false]);
  2305. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2306. $response = $result->getBody()->getContents();
  2307. $response_arr = json_decode($response, true);
  2308. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2309. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2310. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2311. Utils::throwError('20003:火山生成音频失败');
  2312. }
  2313. }
  2314. } catch (\Exception $e) {
  2315. DB::rollBack();
  2316. Utils::throwError('20003:'.$e->getMessage());
  2317. }
  2318. DB::commit();
  2319. // 创建任务之后先暂停10s等待异步任务完成
  2320. sleep(10);
  2321. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2322. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2323. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2324. $segment = $segment ? (array)$segment : [];
  2325. return $segment;
  2326. }
  2327. public function copySegment($data) {
  2328. $segment_id = getProp($data, 'segment_id');
  2329. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2330. if (!$segment) Utils::throwError('20003:请选择分镜');
  2331. $anime_id = getProp($segment, 'anime_id');
  2332. $episode_id = getProp($segment, 'episode_id');
  2333. $episode_number = getProp($segment, 'episode_number');
  2334. $segment_number = getProp($segment, 'segment_number');
  2335. $new_segment_id = 0;
  2336. try {
  2337. DB::beginTransaction();
  2338. $segment = (array)$segment;
  2339. unset($segment['id']);
  2340. $segment['segment_number'] += 1;
  2341. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2342. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2343. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2344. // 更新其他分镜序号
  2345. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2346. // 复制分镜
  2347. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2348. if (!$id) {
  2349. Utils::throwError('20003:复制分镜失败');
  2350. }
  2351. }catch (\Exception $e) {
  2352. DB::rollBack();
  2353. Utils::throwError('20003:'.$e->getMessage());
  2354. }
  2355. DB::commit();
  2356. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2357. $segment = $segment ? (array)$segment : [];
  2358. return $segment;
  2359. }
  2360. public function moveSegment($data) {
  2361. $segment_id = getProp($data, 'segment_id');
  2362. $target_segment_id = getProp($data, 'target_segment_id');
  2363. // 获取源分镜信息
  2364. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2365. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2366. // 获取目标分镜信息
  2367. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2368. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2369. $anime_id = getProp($source_segment, 'anime_id');
  2370. $episode_id = getProp($source_segment, 'episode_id');
  2371. $episode_number = getProp($source_segment, 'episode_number');
  2372. $source_segment_number = getProp($source_segment, 'segment_number');
  2373. $target_segment_number = getProp($target_segment, 'segment_number');
  2374. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2375. $target_anime_id = getProp($target_segment, 'anime_id');
  2376. $target_episode_number = getProp($target_segment, 'episode_number');
  2377. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2378. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2379. }
  2380. // 如果源分镜和目标分镜相同,无需移动
  2381. if ($source_segment_number == $target_segment_number) {
  2382. return true;
  2383. }
  2384. try {
  2385. DB::beginTransaction();
  2386. if ($source_segment_number < $target_segment_number) {
  2387. // 向后移动:源分镜移动到目标分镜之后
  2388. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2389. DB::table('mp_episode_segments')
  2390. ->where('anime_id', $anime_id)
  2391. ->where('episode_id', $episode_id)
  2392. ->where('segment_number', '>', $source_segment_number)
  2393. ->where('segment_number', '<=', $target_segment_number)
  2394. ->decrement('segment_number');
  2395. // 2. 将源分镜移动到目标分镜之后
  2396. $new_segment_number = $target_segment_number;
  2397. } else {
  2398. // 向前移动:源分镜移动到目标分镜之后
  2399. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2400. DB::table('mp_episode_segments')
  2401. ->where('anime_id', $anime_id)
  2402. ->where('episode_id', $episode_id)
  2403. ->where('segment_number', '>', $target_segment_number)
  2404. ->where('segment_number', '<', $source_segment_number)
  2405. ->increment('segment_number');
  2406. // 2. 将源分镜移动到目标分镜之后
  2407. $new_segment_number = $target_segment_number + 1;
  2408. }
  2409. // 3. 更新源分镜的序号
  2410. $update_result = DB::table('mp_episode_segments')
  2411. ->where('segment_id', $segment_id)
  2412. ->update([
  2413. 'segment_number' => $new_segment_number,
  2414. 'updated_at' => date('Y-m-d H:i:s')
  2415. ]);
  2416. if (!$update_result) {
  2417. Utils::throwError('20003:更新分镜序号失败');
  2418. }
  2419. DB::commit();
  2420. return true;
  2421. } catch (\Exception $e) {
  2422. DB::rollBack();
  2423. Utils::throwError('20003:' . $e->getMessage());
  2424. }
  2425. }
  2426. public function delSegment($data) {
  2427. $segment_id = getProp($data, 'segment_id');
  2428. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2429. if (!$segment) Utils::throwError('20003:请选择分镜');
  2430. $anime_id = getProp($segment, 'anime_id');
  2431. $episode_id = getProp($segment, 'episode_id');
  2432. $episode_number = getProp($segment, 'episode_number');
  2433. $segment_number = getProp($segment, 'segment_number');
  2434. try {
  2435. DB::beginTransaction();
  2436. // 删除分镜
  2437. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2438. if (!$boolen) {
  2439. Utils::throwError('20003:删除分镜失败');
  2440. }
  2441. // 更新其他分镜序号
  2442. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2443. }catch (\Exception $e) {
  2444. DB::rollBack();
  2445. Utils::throwError('20003:'.$e->getMessage());
  2446. }
  2447. DB::commit();
  2448. return true;
  2449. }
  2450. public function applySegment($data) {
  2451. $segment_id = getProp($data, 'segment_id');
  2452. $url = getProp($data, 'url');
  2453. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2454. if (!$url) Utils::throwError('20003:URL不能为空');
  2455. // 获取URL的文件扩展名
  2456. $urlPath = parse_url($url, PHP_URL_PATH);
  2457. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2458. // 定义图片和视频的扩展名
  2459. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2460. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2461. // 判断是图片还是视频
  2462. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2463. if (in_array($extension, $imageExtensions)) {
  2464. // 图片类型
  2465. $updateData['img_url'] = $url;
  2466. $updateData['current_type'] = 1;
  2467. } elseif (in_array($extension, $videoExtensions)) {
  2468. // 视频类型
  2469. $updateData['video_url'] = $url;
  2470. $updateData['current_type'] = 2;
  2471. } else {
  2472. Utils::throwError('20003:不支持的文件类型');
  2473. }
  2474. // 更新分镜表
  2475. $result = DB::table('mp_episode_segments')
  2476. ->where('segment_id', $segment_id)
  2477. ->update($updateData);
  2478. if (!$result) {
  2479. Utils::throwError('20003:更新分镜失败');
  2480. }
  2481. return true;
  2482. }
  2483. public function segmentHistory($data) {
  2484. $segment_id = getProp($data, 'segment_id');
  2485. // 获取历史图片
  2486. $pics = [];
  2487. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2488. foreach($pic_history as $task) {
  2489. $result_url = getProp($task, 'result_url');
  2490. if (is_json($result_url)) {
  2491. $pics = array_merge($pics, json_decode($result_url, true));
  2492. }else {
  2493. $pics[] = $result_url;
  2494. }
  2495. }
  2496. // 获取历史视频
  2497. $videos = [];
  2498. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2499. foreach($video_history as $task) {
  2500. $result_url = getProp($task, 'result_url');
  2501. if (is_json($result_url)) {
  2502. $videos = array_merge($videos, json_decode($result_url, true));
  2503. }else {
  2504. $videos[] = $result_url;
  2505. }
  2506. }
  2507. return compact('pics', 'videos');
  2508. }
  2509. public function addAct($data) {
  2510. $prev_act_id = getProp($data, 'prev_act_id');
  2511. $act_title = getProp($data, 'act_title', '');
  2512. $act_content = getProp($data, 'act_content', '');
  2513. $act_duration = getProp($data, 'act_duration', 5);
  2514. $video_url = getProp($data, 'video_url');
  2515. // 根据prev_act_id获取记录
  2516. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2517. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2518. $anime_id = getProp($prev_segment, 'anime_id');
  2519. $episode_id = getProp($prev_segment, 'episode_id');
  2520. $episode_number = getProp($prev_segment, 'episode_number');
  2521. $prev_act_number = getProp($prev_segment, 'act_number');
  2522. // 获取新的act_number
  2523. $new_act_number = $prev_act_number + 1;
  2524. try {
  2525. DB::beginTransaction();
  2526. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2527. DB::table('mp_episode_segments')
  2528. ->where('anime_id', $anime_id)
  2529. ->where('episode_id', $episode_id)
  2530. ->where('act_number', '>', $prev_act_number)
  2531. ->increment('act_number');
  2532. // 插入新片段记录
  2533. $insert_data = [
  2534. 'anime_id' => $anime_id,
  2535. 'episode_id' => $episode_id,
  2536. 'episode_number' => $episode_number,
  2537. 'act_number' => $new_act_number,
  2538. 'created_at' => date('Y-m-d H:i:s'),
  2539. 'updated_at' => date('Y-m-d H:i:s')
  2540. ];
  2541. if ($act_title) {
  2542. $insert_data['act_title'] = $act_title;
  2543. }
  2544. if ($act_content) {
  2545. $insert_data['act_content'] = $act_content;
  2546. }
  2547. if ($act_duration) {
  2548. $insert_data['act_duration'] = $act_duration;
  2549. }
  2550. if ($video_url) {
  2551. $insert_data['origin_video_url'] = $video_url;
  2552. $insert_data['current_type'] = 2;
  2553. $compressed_video_url = compressVideo($video_url);
  2554. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2555. }
  2556. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2557. if (!$id) {
  2558. Utils::throwError('20003:新增片段失败!');
  2559. }
  2560. DB::commit();
  2561. }catch (\Exception $e) {
  2562. DB::rollBack();
  2563. Utils::throwError('20003:'.$e->getMessage());
  2564. }
  2565. $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();
  2566. $segment = $segment ? (array)$segment : [];
  2567. return $segment;
  2568. }
  2569. public function editAct($data) {
  2570. $act_id = getProp($data, 'act_id');
  2571. $act_content = getProp($data, 'act_content');
  2572. $act_duration = getProp($data, 'act_duration');
  2573. $act_title = getProp($data, 'act_title');
  2574. $image_url = getProp($data, 'image_url');
  2575. $video_url = getProp($data, 'video_url');
  2576. // 参数验证
  2577. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2578. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2579. $segment = DB::table('mp_episode_segments')
  2580. ->where('id', $act_id)
  2581. ->first();
  2582. if (!$segment) Utils::throwError('20003:该片段不存在');
  2583. try {
  2584. DB::beginTransaction();
  2585. // 准备更新数据
  2586. $update_data = [
  2587. 'updated_at' => date('Y-m-d H:i:s')
  2588. ];
  2589. // 更新act相关字段
  2590. if (!empty($act_content)) {
  2591. $update_data['act_show_content'] = $act_content;
  2592. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2593. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2594. $shot_counter = 0;
  2595. $update_data['act_show_content'] = preg_replace_callback(
  2596. '/【(?:镜头|分镜)(\d+)】/u',
  2597. function($matches) use (&$shot_counter) {
  2598. $shot_counter++;
  2599. return '【镜头' . $shot_counter . '】';
  2600. },
  2601. $update_data['act_show_content']
  2602. );
  2603. }
  2604. if (!empty($act_duration)) {
  2605. $update_data['act_duration'] = $act_duration;
  2606. }
  2607. if (!empty($act_title)) {
  2608. $update_data['act_title'] = $act_title;
  2609. }
  2610. // 处理图片上传
  2611. if ($image_url) {
  2612. $update_data['img_url'] = $image_url;
  2613. $update_data['current_type'] = 1;
  2614. // 同时写入一个图片生成任务记录
  2615. if ($act_id) {
  2616. $pic_task = [
  2617. 'alias_act_id' => $act_id,
  2618. 'ref_img_url' => json_encode([]),
  2619. 'status' => 'success',
  2620. 'result_url' => json_encode([$image_url], 256),
  2621. 'model' => '',
  2622. 'created_at' => date('Y-m-d H:i:s'),
  2623. 'updated_at' => date('Y-m-d H:i:s'),
  2624. ];
  2625. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2626. }
  2627. }
  2628. // 处理视频上传
  2629. if ($video_url) {
  2630. $update_data['origin_video_url'] = $video_url;
  2631. $compressed_video_url = compressVideo($video_url);
  2632. $update_data['current_type'] = 2;
  2633. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2634. // 同时写入一个视频生成任务记录
  2635. if ($act_id) {
  2636. $video_task = [
  2637. 'alias_act_id' => $act_id,
  2638. 'status' => 'success',
  2639. 'result_url' => $update_data['origin_video_url'],
  2640. 'compressed_url' => $update_data['video_url'],
  2641. 'created_at' => date('Y-m-d H:i:s'),
  2642. 'updated_at' => date('Y-m-d H:i:s'),
  2643. ];
  2644. DB::table('mp_generate_video_tasks')->insert($video_task);
  2645. }
  2646. }
  2647. // 更新片段信息
  2648. $result = DB::table('mp_episode_segments')
  2649. ->where('id', $act_id)
  2650. ->update($update_data);
  2651. if ($result === false) {
  2652. Utils::throwError('20003:更新片段失败');
  2653. }
  2654. DB::commit();
  2655. // 返回新复制的记录
  2656. $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();
  2657. $new_segment = (array)$new_segment;
  2658. return $new_segment;
  2659. } catch (\Exception $e) {
  2660. DB::rollBack();
  2661. dLog('anime')->error('更新片段失败', [
  2662. 'act_id' => $act_id,
  2663. 'error' => $e->getMessage()
  2664. ]);
  2665. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2666. }
  2667. }
  2668. public function copyAct($data) {
  2669. $act_id = getProp($data, 'act_id');
  2670. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2671. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2672. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2673. $anime_id = getProp($source_segment, 'anime_id');
  2674. $episode_id = getProp($source_segment, 'episode_id');
  2675. $episode_number = getProp($source_segment, 'episode_number');
  2676. $act_number = getProp($source_segment, 'act_number');
  2677. try {
  2678. DB::beginTransaction();
  2679. // 新act的编号
  2680. $new_act_number = $act_number + 1;
  2681. // 更新后续所有act的act_number
  2682. DB::table('mp_episode_segments')
  2683. ->where('anime_id', $anime_id)
  2684. ->where('episode_id', $episode_id)
  2685. ->where('act_number', '>', $act_number)
  2686. ->increment('act_number');
  2687. // 复制该片段记录
  2688. $segment_data = (array)$source_segment;
  2689. unset($segment_data['id']);
  2690. $segment_data['video_url'] = '';
  2691. $segment_data['video_task_id'] = '';
  2692. $segment_data['video_task_status'] = '';
  2693. $segment_data['act_number'] = $new_act_number;
  2694. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2695. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2696. if (!$id) {
  2697. Utils::throwError('20003:复制片段失败');
  2698. }
  2699. DB::commit();
  2700. }catch (\Exception $e) {
  2701. DB::rollBack();
  2702. Utils::throwError('20003:'.$e->getMessage());
  2703. }
  2704. // 返回新复制的记录
  2705. $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();
  2706. $new_segment = $new_segment ? (array)$new_segment : [];
  2707. $new_segment['act_id'] = $id;
  2708. return $new_segment;
  2709. }
  2710. public function moveAct($data) {
  2711. $act_id = getProp($data, 'act_id');
  2712. $target_act_id = getProp($data, 'target_act_id');
  2713. // 获取源片段信息
  2714. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2715. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2716. // 获取目标片段信息
  2717. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2718. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2719. $anime_id = getProp($source_segment, 'anime_id');
  2720. $episode_id = getProp($source_segment, 'episode_id');
  2721. $source_act_number = getProp($source_segment, 'act_number');
  2722. $target_act_number = getProp($target_segment, 'act_number');
  2723. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2724. $target_anime_id = getProp($target_segment, 'anime_id');
  2725. $target_episode_id = getProp($target_segment, 'episode_id');
  2726. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2727. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2728. }
  2729. // 如果源片段和目标片段相同,无需移动
  2730. if ($source_act_number == $target_act_number) {
  2731. return true;
  2732. }
  2733. try {
  2734. DB::beginTransaction();
  2735. if ($source_act_number < $target_act_number) {
  2736. // 向后移动:源片段移动到目标片段之后
  2737. // 1. 将源片段和目标片段之间的所有片段编号减1
  2738. DB::table('mp_episode_segments')
  2739. ->where('anime_id', $anime_id)
  2740. ->where('episode_id', $episode_id)
  2741. ->where('act_number', '>', $source_act_number)
  2742. ->where('act_number', '<=', $target_act_number)
  2743. ->decrement('act_number');
  2744. // 2. 将源片段移动到目标片段之后
  2745. $new_act_number = $target_act_number;
  2746. } else {
  2747. // 向前移动:源片段移动到目标片段之后
  2748. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2749. DB::table('mp_episode_segments')
  2750. ->where('anime_id', $anime_id)
  2751. ->where('episode_id', $episode_id)
  2752. ->where('act_number', '>', $target_act_number)
  2753. ->where('act_number', '<', $source_act_number)
  2754. ->increment('act_number');
  2755. // 2. 将源片段移动到目标片段之后
  2756. $new_act_number = $target_act_number + 1;
  2757. }
  2758. // 3. 更新源片段的编号
  2759. $update_result = DB::table('mp_episode_segments')
  2760. ->where('id', $act_id)
  2761. ->update([
  2762. 'act_number' => $new_act_number,
  2763. 'updated_at' => date('Y-m-d H:i:s')
  2764. ]);
  2765. if (!$update_result) {
  2766. Utils::throwError('20003:更新片段编号失败');
  2767. }
  2768. DB::commit();
  2769. return true;
  2770. } catch (\Exception $e) {
  2771. DB::rollBack();
  2772. Utils::throwError('20003:' . $e->getMessage());
  2773. }
  2774. }
  2775. public function delAct($data) {
  2776. $act_id = getProp($data, 'act_id');
  2777. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2778. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2779. if (!$segment) Utils::throwError('20003:请选择片段');
  2780. $anime_id = getProp($segment, 'anime_id');
  2781. $episode_id = getProp($segment, 'episode_id');
  2782. $act_number = getProp($segment, 'act_number');
  2783. try {
  2784. DB::beginTransaction();
  2785. // 删除该片段记录
  2786. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2787. if (!$deleted) {
  2788. Utils::throwError('20003:删除片段失败');
  2789. }
  2790. // 更新后续act的编号
  2791. DB::table('mp_episode_segments')
  2792. ->where('anime_id', $anime_id)
  2793. ->where('episode_id', $episode_id)
  2794. ->where('act_number', '>', $act_number)
  2795. ->decrement('act_number');
  2796. DB::commit();
  2797. }catch (\Exception $e) {
  2798. DB::rollBack();
  2799. Utils::throwError('20003:'.$e->getMessage());
  2800. }
  2801. return true;
  2802. }
  2803. public function applyAct($data) {
  2804. $act_id = getProp($data, 'act_id');
  2805. $url = getProp($data, 'url');
  2806. if (!$act_id) Utils::throwError('20003:请选择片段');
  2807. if (!$url) Utils::throwError('20003:URL不能为空');
  2808. // 获取URL的文件扩展名
  2809. $urlPath = parse_url($url, PHP_URL_PATH);
  2810. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2811. // 定义图片和视频的扩展名
  2812. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2813. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2814. // 判断是图片还是视频
  2815. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2816. if (in_array($extension, $imageExtensions)) {
  2817. // 图片类型
  2818. $updateData['img_url'] = $url;
  2819. $updateData['current_type'] = 1;
  2820. } elseif (in_array($extension, $videoExtensions)) {
  2821. // 视频类型
  2822. $updateData['video_url'] = $url;
  2823. $updateData['current_type'] = 2;
  2824. } else {
  2825. Utils::throwError('20003:不支持的文件类型');
  2826. }
  2827. // 更新片段记录(全能模式下每个act只有一条记录)
  2828. $result = DB::table('mp_episode_segments')
  2829. ->where('id', $act_id)
  2830. ->update($updateData);
  2831. if (!$result) {
  2832. Utils::throwError('20003:更新片段失败');
  2833. }
  2834. return true;
  2835. }
  2836. public function actChatHistory($data) {
  2837. $act_id = getProp($data, 'act_id');
  2838. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2839. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2840. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2841. $value = (array)$value;
  2842. $value['created_at'] = transDate($value['created_at']);
  2843. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2844. else $value['reference_images'] = [];
  2845. return $value;
  2846. })->toArray();
  2847. // 获取历史图片
  2848. $url = [];
  2849. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2850. foreach($pic_history as $task) {
  2851. $result_url = getProp($task, 'result_url');
  2852. if (is_json($result_url)) {
  2853. $url = array_merge($url, json_decode($result_url, true));
  2854. }else {
  2855. $url[] = $result_url;
  2856. }
  2857. }
  2858. // 获取历史视频
  2859. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2860. foreach($video_history as $task) {
  2861. $result_url = getProp($task, 'result_url');
  2862. if (is_json($result_url)) {
  2863. $url = array_merge($url, json_decode($result_url, true));
  2864. }else {
  2865. $url[] = $result_url;
  2866. }
  2867. }
  2868. // 获取资产库
  2869. $products = [];
  2870. // 通过act_id查询片段信息获取episode_id
  2871. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2872. if ($segment) {
  2873. $episode_id = getProp($segment, 'episode_id');
  2874. // 查询剧集信息获取roles、scenes和extra_products
  2875. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2876. if ($episode) {
  2877. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2878. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2879. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2880. // 先合并roles和scenes
  2881. // 处理角色数组
  2882. foreach ($roles as $role) {
  2883. $product = $role;
  2884. // 将role字段重命名为product_name
  2885. if (isset($product['role'])) {
  2886. $product['product_name'] = $product['role'];
  2887. unset($product['role']);
  2888. }
  2889. $product['product'] = 1; // 标记类型为角色
  2890. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2891. }
  2892. // 处理场景数组
  2893. foreach ($scenes as $scene) {
  2894. $product = $scene;
  2895. // 将scene字段重命名为product_name
  2896. if (isset($product['scene'])) {
  2897. $product['product_name'] = $product['scene'];
  2898. unset($product['scene']);
  2899. }
  2900. $product['product'] = 2; // 标记类型为场景
  2901. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2902. }
  2903. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2904. foreach ($extra_products as $extra_product) {
  2905. $product_name = getProp($extra_product, 'product_name');
  2906. if ($product_name) {
  2907. $products[$product_name] = $extra_product; // 覆盖同名数据
  2908. }
  2909. }
  2910. // 重新索引数组(去除key)
  2911. $products = array_values($products);
  2912. }
  2913. }
  2914. // 获取执行中的任务
  2915. $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) {
  2916. $value = (array)$value;
  2917. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2918. else $value['ref_image_url'] = [];
  2919. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2920. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2921. if (!empty($value['prompt'])) {
  2922. $prompt = $value['prompt'];
  2923. // 查找第一个【镜头】的位置
  2924. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2925. // 从【镜头】开始截取
  2926. $prompt = substr($prompt, $matches[0][1]);
  2927. }
  2928. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2929. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2930. $value['prompt'] = $prompt;
  2931. }
  2932. return $value;
  2933. })->toArray();
  2934. return compact('chat', 'url', 'products', 'tasks');
  2935. }
  2936. public function applyAudioData($data) {
  2937. $segment_id = getProp($data, 'segment_id');
  2938. $global_data = getProp($data, 'global_data');
  2939. $segment_data = getProp($data, 'segment_data');
  2940. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2941. $global_data = is_array($global_data) ? $global_data : [];
  2942. $segment_data = is_array($segment_data) ? $segment_data : [];
  2943. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2944. $dialogue_item = null;
  2945. foreach ($global_data as $key => $item) {
  2946. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2947. $dialogue_item = $item;
  2948. unset($global_data[$key]);
  2949. break;
  2950. }
  2951. }
  2952. if ($dialogue_item) {
  2953. $segment_data[] = $dialogue_item;
  2954. }
  2955. // 特殊参数: audio_url,audio_duration,subtitle_info
  2956. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2957. // 如果不是全部存在,则仍需创建音频任务
  2958. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2959. $special_update_data = [];
  2960. $has_all_special_params = false;
  2961. // 从segment_data中提取特殊参数
  2962. $filtered_segment_data = [];
  2963. foreach ($segment_data as $item) {
  2964. $field_name = trim((string)getProp($item, 'name'));
  2965. if (in_array($field_name, $special_fields)) {
  2966. $special_update_data[$field_name] = getProp($item, 'value');
  2967. } else {
  2968. // 非特殊参数保留,继续后续处理
  2969. $filtered_segment_data[] = $item;
  2970. }
  2971. }
  2972. // 检查是否三个特殊参数都存在
  2973. if (count($special_update_data) === 3 &&
  2974. isset($special_update_data['audio_url']) &&
  2975. isset($special_update_data['audio_duration']) &&
  2976. isset($special_update_data['subtitle_info'])) {
  2977. $has_all_special_params = true;
  2978. // 立即更新到当前分镜
  2979. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2980. DB::table('mp_episode_segments')
  2981. ->where('segment_id', $segment_id)
  2982. ->update($special_update_data);
  2983. }
  2984. // 使用过滤后的segment_data继续处理其他参数
  2985. $segment_data = $filtered_segment_data;
  2986. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2987. $global_update_data = [];
  2988. $segment_update_data = [];
  2989. $global_voice_type = '';
  2990. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2991. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2992. $episode_id = getProp($target_segment, 'episode_id');
  2993. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2994. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2995. if (!$episode) Utils::throwError('20003:分集不存在');
  2996. foreach ($global_data as $item) {
  2997. $field_name = trim((string)getProp($item, 'name'));
  2998. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2999. continue;
  3000. }
  3001. $global_update_data[$field_name] = getProp($item, 'value');
  3002. if ($field_name === 'voice_type') {
  3003. $global_voice_type = trim((string)getProp($item, 'value'));
  3004. }
  3005. }
  3006. foreach ($segment_data as $item) {
  3007. $field_name = trim((string)getProp($item, 'name'));
  3008. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3009. continue;
  3010. }
  3011. $segment_update_data[$field_name] = getProp($item, 'value');
  3012. }
  3013. if ($global_voice_type) {
  3014. $timbre_info = DB::table('mp_timbres')
  3015. ->where('timbre_type', $global_voice_type)
  3016. ->select('audio_url', 'timbre_name')
  3017. ->first();
  3018. if ($timbre_info) {
  3019. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3020. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3021. }
  3022. }
  3023. try {
  3024. DB::beginTransaction();
  3025. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3026. $segment_ids_to_create_task = [];
  3027. $segments_data = [];
  3028. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3029. if (!empty($global_update_data)) {
  3030. // 如果角色不存在,则只更新当前分镜
  3031. if (!$target_voice_actor) {
  3032. // 只处理当前分镜
  3033. $affected_segments = DB::table('mp_episode_segments')
  3034. ->where('segment_id', $segment_id)
  3035. ->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')
  3036. ->get();
  3037. } else {
  3038. // 获取该角色的所有分镜
  3039. $affected_segments = DB::table('mp_episode_segments')
  3040. ->where('episode_id', $episode_id)
  3041. ->where('voice_actor', $target_voice_actor)
  3042. ->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')
  3043. ->get();
  3044. }
  3045. foreach ($affected_segments as $seg) {
  3046. $seg = (array)$seg;
  3047. $sid = getProp($seg, 'segment_id');
  3048. // 检查参数是否发生变化
  3049. $has_changed = false;
  3050. foreach ($global_update_data as $field => $new_value) {
  3051. $old_value = getProp($seg, $field);
  3052. if ($old_value != $new_value) {
  3053. $has_changed = true;
  3054. break;
  3055. }
  3056. }
  3057. if ($has_changed) {
  3058. $segment_ids_to_create_task[] = $sid;
  3059. $segments_data[$sid] = $seg;
  3060. }
  3061. }
  3062. // 只有在有变化的分镜时才更新
  3063. if (!empty($segment_ids_to_create_task)) {
  3064. $global_segment_update_data = $global_update_data;
  3065. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3066. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3067. DB::table('mp_episode_segments')
  3068. ->where('episode_id', $episode_id)
  3069. ->where('voice_actor', $target_voice_actor)
  3070. ->whereIn('segment_id', $segment_ids_to_create_task)
  3071. ->update($global_segment_update_data);
  3072. }
  3073. if ($global_voice_type) {
  3074. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3075. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3076. $roles_updated = false;
  3077. foreach ($episode_roles as &$role) {
  3078. // 通过 role 字段匹配角色名,而不是 voice_name
  3079. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3080. continue;
  3081. }
  3082. $role['voice_type'] = $global_voice_type;
  3083. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3084. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3085. $roles_updated = true;
  3086. }
  3087. unset($role);
  3088. if ($roles_updated) {
  3089. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3090. 'roles' => json_encode($episode_roles, 256),
  3091. 'updated_at' => date('Y-m-d H:i:s'),
  3092. ]);
  3093. }
  3094. }
  3095. }
  3096. // 如果有单个分镜更新,检查是否有变化
  3097. if (!empty($segment_update_data)) {
  3098. // 获取当前分镜数据
  3099. $current_segment = DB::table('mp_episode_segments')
  3100. ->where('segment_id', $segment_id)
  3101. ->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')
  3102. ->first();
  3103. if ($current_segment) {
  3104. $current_segment = (array)$current_segment;
  3105. // 检查参数是否发生变化
  3106. $has_changed = false;
  3107. foreach ($segment_update_data as $field => $new_value) {
  3108. $old_value = getProp($current_segment, $field);
  3109. if ($old_value != $new_value) {
  3110. $has_changed = true;
  3111. break;
  3112. }
  3113. }
  3114. if ($has_changed) {
  3115. // 如果该分镜还未在列表中,添加进去
  3116. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3117. $segment_ids_to_create_task[] = $segment_id;
  3118. $segments_data[$segment_id] = $current_segment;
  3119. }
  3120. // 更新分镜数据并清空音频URL
  3121. $segment_update_data['audio_url'] = '';
  3122. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3123. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3124. }
  3125. }
  3126. }
  3127. // 为所有有变化的分镜创建音频合成任务
  3128. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3129. if (!empty($segment_ids_to_create_task)) {
  3130. foreach ($segment_ids_to_create_task as $sid) {
  3131. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3132. if ($sid === $segment_id && $has_all_special_params) {
  3133. continue;
  3134. }
  3135. // 重新获取更新后的分镜数据
  3136. $updated_segment = DB::table('mp_episode_segments')
  3137. ->where('segment_id', $sid)
  3138. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3139. ->first();
  3140. if (!$updated_segment) continue;
  3141. $updated_segment = (array)$updated_segment;
  3142. // 检查dialogue是否为空
  3143. $dialogue = getProp($updated_segment, 'dialogue');
  3144. if (empty($dialogue)) {
  3145. // dialogue为空时,直接写入默认音频信息
  3146. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3147. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3148. 'audio_duration' => 2.0,
  3149. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3150. 'updated_at' => date('Y-m-d H:i:s')
  3151. ]);
  3152. continue;
  3153. }
  3154. $generate_json = [
  3155. 'text' => $dialogue,
  3156. 'role' => getProp($updated_segment, 'voice_actor'),
  3157. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3158. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3159. 'emotion' => getProp($updated_segment, 'emotion'),
  3160. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3161. 'gender' => getProp($updated_segment, 'gender'),
  3162. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3163. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3164. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3165. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3166. ];
  3167. // 插入视频配音合成任务
  3168. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3169. 'alias_segment_id' => $sid,
  3170. 'generate_status' => '执行中',
  3171. 'audio_url' => '',
  3172. 'generate_json' => json_encode($generate_json, 256),
  3173. 'created_at' => date('Y-m-d H:i:s'),
  3174. 'updated_at' => date('Y-m-d H:i:s'),
  3175. ]);
  3176. if (!$dubTaskId) {
  3177. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3178. continue;
  3179. }
  3180. // 将任务ID添加到Redis列表中
  3181. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3182. // 请求远程服务器执行生成
  3183. try {
  3184. sleep(1);
  3185. $client = new Client(['timeout' => 300, 'verify' => false]);
  3186. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3187. $response = $result->getBody()->getContents();
  3188. $response_arr = json_decode($response, true);
  3189. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3190. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3191. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3192. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3193. }
  3194. } catch (\Exception $e) {
  3195. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3196. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3197. }
  3198. }
  3199. }
  3200. DB::commit();
  3201. } catch (\Exception $e) {
  3202. DB::rollBack();
  3203. Utils::throwError('20003:'.$e->getMessage());
  3204. }
  3205. return true;
  3206. }
  3207. public function episodePicsInfo($data) {
  3208. $anime_id = getProp($data, 'anime_id');
  3209. $episode_id = getProp($data, 'episode_id');
  3210. // 参数验证
  3211. if (!$anime_id && !$episode_id) {
  3212. Utils::throwError('20003:请提供动漫ID或分集ID');
  3213. }
  3214. // 根据参数获取数据源
  3215. if ($episode_id) {
  3216. // 从剧集表获取
  3217. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3218. if (!$source) Utils::throwError('20003:该剧集不存在');
  3219. $table_name = 'mp_anime_episodes';
  3220. $id_field = 'id';
  3221. $id_value = $episode_id;
  3222. // 获取剧集的anime_id用于继承全局数据
  3223. $anime_id = getProp($source, 'anime_id');
  3224. } else {
  3225. // 从动漫表获取
  3226. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3227. if (!$source) Utils::throwError('20003:该动漫不存在');
  3228. $table_name = 'mp_animes';
  3229. $id_field = 'id';
  3230. $id_value = $anime_id;
  3231. }
  3232. $source = (array)$source;
  3233. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3234. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3235. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3236. // 如果是分集数据,需要处理继承和任务创建逻辑
  3237. if ($episode_id) {
  3238. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3239. }
  3240. // 返回生成器函数,用于 SSE 流式输出
  3241. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3242. $startTime = time();
  3243. $maxDuration = 600; // 10分钟超时
  3244. $checkInterval = 3; // 每3秒检查一次
  3245. // Redis 缓存键
  3246. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3247. // 生成当前数据的哈希值用于比较
  3248. $generateHash = function($roles, $scenes, $props) {
  3249. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3250. };
  3251. // 发送初始数据
  3252. $currentHash = $generateHash($roles, $scenes, $props);
  3253. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3254. echo "data: " . json_encode([
  3255. 'type' => 'init',
  3256. 'data' => [
  3257. 'roles' => $roles,
  3258. 'scenes' => $scenes,
  3259. 'props' => $props,
  3260. 'start_time' => $startTime
  3261. ]
  3262. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3263. if (ob_get_level() > 0) {
  3264. ob_flush();
  3265. }
  3266. flush();
  3267. // 持续轮询任务状态
  3268. while (time() - $startTime < $maxDuration) {
  3269. $hasProcessing = false;
  3270. $updated = false;
  3271. // 检查角色任务状态
  3272. foreach ($roles as $index => &$role) {
  3273. $task_id = getProp($role, 'task_id');
  3274. $task_status = getProp($role, 'task_status');
  3275. $existing_url = getProp($role, 'url');
  3276. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3277. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3278. $hasProcessing = ($task_status === 'processing');
  3279. // 查询任务状态
  3280. $task = DB::table('mp_generate_pic_tasks')
  3281. ->where('id', $task_id)
  3282. ->select('id', 'status', 'result_url', 'error_message')
  3283. ->first();
  3284. if ($task) {
  3285. $task = (array)$task;
  3286. $status = getProp($task, 'status');
  3287. // 如果任务完成或失败
  3288. if (in_array($status, ['success', 'failed'])) {
  3289. $role['task_status'] = $status;
  3290. if ($status === 'success') {
  3291. $result_url = getProp($task, 'result_url');
  3292. if ($result_url) {
  3293. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3294. if (is_array($result_urls) && !empty($result_urls[0])) {
  3295. $role['url'] = $result_urls[0];
  3296. }
  3297. }
  3298. }
  3299. $updated = true;
  3300. } else if ($status === 'processing') {
  3301. $hasProcessing = true;
  3302. }
  3303. }
  3304. }
  3305. }
  3306. // 检查场景任务状态
  3307. foreach ($scenes as $index => &$scene) {
  3308. $task_id = getProp($scene, 'task_id');
  3309. $task_status = getProp($scene, 'task_status');
  3310. $existing_url = getProp($scene, 'url');
  3311. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3312. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3313. $hasProcessing = ($task_status === 'processing');
  3314. // 查询任务状态
  3315. $task = DB::table('mp_generate_pic_tasks')
  3316. ->where('id', $task_id)
  3317. ->select('id', 'status', 'result_url', 'error_message')
  3318. ->first();
  3319. if ($task) {
  3320. $task = (array)$task;
  3321. $status = getProp($task, 'status');
  3322. // 如果任务完成或失败
  3323. if (in_array($status, ['success', 'failed'])) {
  3324. $scene['task_status'] = $status;
  3325. if ($status === 'success') {
  3326. $result_url = getProp($task, 'result_url');
  3327. if ($result_url) {
  3328. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3329. if (is_array($result_urls) && !empty($result_urls[0])) {
  3330. $scene['url'] = $result_urls[0];
  3331. }
  3332. }
  3333. }
  3334. $updated = true;
  3335. } else if ($status === 'processing') {
  3336. $hasProcessing = true;
  3337. }
  3338. }
  3339. }
  3340. }
  3341. // 检查道具任务状态
  3342. foreach ($props as $index => &$prop) {
  3343. $task_id = getProp($prop, 'task_id');
  3344. $task_status = getProp($prop, 'task_status');
  3345. $existing_url = getProp($prop, 'url');
  3346. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3347. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3348. $hasProcessing = ($task_status === 'processing');
  3349. // 查询任务状态
  3350. $task = DB::table('mp_generate_pic_tasks')
  3351. ->where('id', $task_id)
  3352. ->select('id', 'status', 'result_url', 'error_message')
  3353. ->first();
  3354. if ($task) {
  3355. $task = (array)$task;
  3356. $status = getProp($task, 'status');
  3357. // 如果任务完成或失败
  3358. if (in_array($status, ['success', 'failed'])) {
  3359. $prop['task_status'] = $status;
  3360. if ($status === 'success') {
  3361. $result_url = getProp($task, 'result_url');
  3362. if ($result_url) {
  3363. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3364. if (is_array($result_urls) && !empty($result_urls[0])) {
  3365. $prop['url'] = $result_urls[0];
  3366. }
  3367. }
  3368. }
  3369. $updated = true;
  3370. } else if ($status === 'processing') {
  3371. $hasProcessing = true;
  3372. }
  3373. }
  3374. }
  3375. }
  3376. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3377. if ($updated) {
  3378. $newHash = $generateHash($roles, $scenes, $props);
  3379. $cachedHash = Redis::get($cacheKey);
  3380. // 只有当数据真正变化时才更新数据库和发送事件
  3381. if ($newHash !== $cachedHash) {
  3382. try {
  3383. // 更新数据库
  3384. DB::table($table_name)->where($id_field, $id_value)->update([
  3385. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3386. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3387. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3388. 'updated_at' => date('Y-m-d H:i:s')
  3389. ]);
  3390. // 更新缓存
  3391. Redis::setex($cacheKey, 600, $newHash);
  3392. // 发送更新事件
  3393. echo "data: " . json_encode([
  3394. 'type' => 'update',
  3395. 'data' => [
  3396. 'roles' => $roles,
  3397. 'scenes' => $scenes,
  3398. 'props' => $props,
  3399. 'elapsed_time' => time() - $startTime
  3400. ]
  3401. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3402. if (ob_get_level() > 0) {
  3403. ob_flush();
  3404. }
  3405. flush();
  3406. } catch (\Exception $e) {
  3407. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3408. }
  3409. } else {
  3410. // 即使哈希相同,如果有URL更新也要发送事件
  3411. $hasUrlUpdate = false;
  3412. foreach ($roles as $role) {
  3413. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3414. $hasUrlUpdate = true;
  3415. break;
  3416. }
  3417. }
  3418. if (!$hasUrlUpdate) {
  3419. foreach ($scenes as $scene) {
  3420. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3421. $hasUrlUpdate = true;
  3422. break;
  3423. }
  3424. }
  3425. }
  3426. if (!$hasUrlUpdate) {
  3427. foreach ($props as $prop) {
  3428. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3429. $hasUrlUpdate = true;
  3430. break;
  3431. }
  3432. }
  3433. }
  3434. if ($hasUrlUpdate) {
  3435. // 强制更新数据库和发送事件
  3436. try {
  3437. DB::table($table_name)->where($id_field, $id_value)->update([
  3438. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3439. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3440. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3441. 'updated_at' => date('Y-m-d H:i:s')
  3442. ]);
  3443. // 更新缓存
  3444. Redis::setex($cacheKey, 600, $newHash);
  3445. // 发送更新事件
  3446. echo "data: " . json_encode([
  3447. 'type' => 'update',
  3448. 'data' => [
  3449. 'roles' => $roles,
  3450. 'scenes' => $scenes,
  3451. 'props' => $props,
  3452. 'elapsed_time' => time() - $startTime
  3453. ]
  3454. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3455. if (ob_get_level() > 0) {
  3456. ob_flush();
  3457. }
  3458. flush();
  3459. } catch (\Exception $e) {
  3460. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3461. }
  3462. }
  3463. }
  3464. }
  3465. // 如果所有任务都已完成,发送完成事件并退出
  3466. if (!$hasProcessing) {
  3467. // 查询数据库中的最终数据,确保返回最新的完整数据
  3468. try {
  3469. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3470. if ($finalSource) {
  3471. $finalSource = (array)$finalSource;
  3472. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3473. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3474. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3475. // 使用数据库中的最终数据
  3476. $roles = $finalRoles;
  3477. $scenes = $finalScenes;
  3478. $props = $finalProps;
  3479. }
  3480. } catch (\Exception $e) {
  3481. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3482. // 如果查询失败,继续使用内存中的数据
  3483. }
  3484. // 清理缓存
  3485. Redis::del($cacheKey);
  3486. echo "data: " . json_encode([
  3487. 'type' => 'completed',
  3488. 'data' => [
  3489. 'roles' => $roles,
  3490. 'scenes' => $scenes,
  3491. 'props' => $props,
  3492. 'total_time' => time() - $startTime
  3493. ]
  3494. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3495. if (ob_get_level() > 0) {
  3496. ob_flush();
  3497. }
  3498. flush();
  3499. break;
  3500. }
  3501. // 等待下次检查
  3502. sleep($checkInterval);
  3503. }
  3504. // 超时处理
  3505. if (time() - $startTime >= $maxDuration) {
  3506. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3507. try {
  3508. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3509. if ($finalSource) {
  3510. $finalSource = (array)$finalSource;
  3511. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3512. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3513. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3514. // 使用数据库中的最终数据
  3515. $roles = $finalRoles;
  3516. $scenes = $finalScenes;
  3517. $props = $finalProps;
  3518. }
  3519. } catch (\Exception $e) {
  3520. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3521. // 如果查询失败,继续使用内存中的数据
  3522. }
  3523. // 清理缓存
  3524. Redis::del($cacheKey);
  3525. echo "data: " . json_encode([
  3526. 'type' => 'timeout',
  3527. 'message' => '轮询超时,请刷新页面查看最新状态',
  3528. 'data' => [
  3529. 'roles' => $roles,
  3530. 'scenes' => $scenes,
  3531. 'props' => $props
  3532. ]
  3533. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3534. if (ob_get_level() > 0) {
  3535. ob_flush();
  3536. }
  3537. flush();
  3538. }
  3539. };
  3540. }
  3541. public function clipSegmentVideo($data) {
  3542. $segment_id = getProp($data, 'segment_id');
  3543. $video_time_point_start = getProp($data, 'video_time_point_start');
  3544. $video_time_point_end = getProp($data, 'video_time_point_end');
  3545. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3546. Utils::throwError('20003:参数异常');
  3547. }
  3548. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3549. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3550. }
  3551. $video_duration = $video_time_point_end - $video_time_point_start;
  3552. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3553. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3554. 'video_duration' => $video_duration,
  3555. 'video_time_point_start' => $video_time_point_start,
  3556. 'video_time_point_end' => $video_time_point_end,
  3557. 'updated_at' => date('Y-m-d H:i:s')
  3558. ]);
  3559. }
  3560. // 轮训获取图片任务结果
  3561. private function loopGetPicTaskResult($task_id) {
  3562. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3563. if (!$task) {
  3564. return '';
  3565. }
  3566. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3567. $model = getProp($task, 'model');
  3568. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3569. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3570. $isSyncModel = $isVolcModel || $isGptModel;
  3571. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3572. $start_count = 0;
  3573. $img_url = '';
  3574. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3575. sleep(3);
  3576. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3577. // 如果任务已经完成,直接返回结果
  3578. if ($task->status === 'success' && $task->result_url) {
  3579. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3580. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3581. }
  3582. // 如果任务已失败,返回空
  3583. if ($task->status === 'failed') {
  3584. return '';
  3585. }
  3586. if ($isSyncModel) continue;
  3587. // 查询任务状态
  3588. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3589. if ($statusInfo['status'] === 'success') {
  3590. $task->updateStatus('success', [
  3591. 'result_url' => $statusInfo['result_url'],
  3592. 'result_json' => $statusInfo['result_json'] ?? []
  3593. ]);
  3594. // 同步调整分镜图片状态和结果
  3595. if (getProp($task, 'alias_segment_id')) {
  3596. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3597. 'img_url' => $statusInfo['result_url'][0],
  3598. 'pic_task_status' => '已完成',
  3599. ]);
  3600. }
  3601. $img_url = $statusInfo['result_url'][0];
  3602. break;
  3603. } elseif ($statusInfo['status'] === 'failed') {
  3604. $task->updateStatus('failed', [
  3605. 'error_message' => $statusInfo['error_message'],
  3606. 'result_json' => $statusInfo['result_json'] ?? []
  3607. ]);
  3608. if (getProp($task, 'alias_segment_id')) {
  3609. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3610. 'pic_task_status' => '失败',
  3611. ]);
  3612. }
  3613. break;
  3614. }
  3615. $start_count++;
  3616. }
  3617. return $img_url;
  3618. }
  3619. /**
  3620. * 从分镜内容中提取涉及的角色
  3621. */
  3622. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3623. $found_characters = [];
  3624. foreach ($available_characters as $character) {
  3625. // 检查角色名称是否在分镜内容中出现
  3626. if (strpos($segment_content, $character) !== false) {
  3627. $found_characters[] = $character;
  3628. }
  3629. }
  3630. if (!$found_characters) {
  3631. foreach ($roles as $character) {
  3632. // 检查角色名称是否在分镜内容中出现
  3633. if (strpos($segment_content, $character) !== false) {
  3634. $found_characters[] = $character;
  3635. }
  3636. }
  3637. }
  3638. return array_unique($found_characters);
  3639. }
  3640. // 从分镜剧本中提取关键字段
  3641. private function handleSegmentContent(&$data) {
  3642. $segmentContent = getProp($data, 'segment_content');
  3643. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3644. $segmentData = [
  3645. 'description' => '',
  3646. 'composition' => '',
  3647. 'camera_movement' => '',
  3648. 'voice_actor' => '',
  3649. 'dialogue' => '',
  3650. 'frame_type' => '',
  3651. 'scene' => '', // 场景
  3652. 'characters' => '', // 出镜角色
  3653. 'tail_frame' => '', // 尾帧描述
  3654. 'emotion' => '中性', // 情感
  3655. 'gender' => '0', // 性别(0未知,1男,2女)
  3656. 'speed_ratio' => 0, // 语速
  3657. 'loudness_ratio' => 0, // 音量
  3658. 'emotion_scale' => 4, // 情感强度
  3659. 'pitch' => 0, // 音调
  3660. ];
  3661. // 用于存储需要从 segment_content 中移除的匹配项
  3662. $replaceEmptyArr = [];
  3663. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3664. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3665. $segmentData['description'] = trim($descMatch[1]);
  3666. $data['description'] = trim($descMatch[1]);
  3667. }
  3668. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3669. $segmentData['composition'] = trim($compMatch[1]);
  3670. $data['composition'] = trim($compMatch[1]);
  3671. }
  3672. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3673. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3674. $data['camera_movement'] = trim($cameraMatch[1]);
  3675. }
  3676. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3677. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3678. $data['voice_actor'] = trim($voiceMatch[1]);
  3679. }
  3680. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3681. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3682. $data['dialogue'] = trim($dialogueMatch[1]);
  3683. }
  3684. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3685. $segmentData['frame_type'] = trim($frameMatch[1]);
  3686. $data['frame_type'] = trim($frameMatch[1]);
  3687. }
  3688. // 场景字段
  3689. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3690. $segmentData['scene'] = trim($sceneMatch[1]);
  3691. $data['scene'] = trim($sceneMatch[1]);
  3692. }
  3693. // 出镜角色字段
  3694. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3695. $segmentData['characters'] = trim($charactersMatch[1]);
  3696. $data['characters'] = trim($charactersMatch[1]);
  3697. }
  3698. // 尾帧描述字段
  3699. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3700. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3701. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3702. }
  3703. // 情感字段
  3704. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3705. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3706. $segmentData['emotion'] = trim($emotionMatch[1]);
  3707. $data['emotion'] = trim($emotionMatch[1]);
  3708. }
  3709. // 性别字段
  3710. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3711. $replaceEmptyArr[] = trim($genderMatch[0]);
  3712. $genderStr = trim($genderMatch[1]);
  3713. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3714. $segmentData['gender'] = '1';
  3715. $data['gender'] = '1';
  3716. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3717. $segmentData['gender'] = '2';
  3718. $data['gender'] = '2';
  3719. } else {
  3720. $segmentData['gender'] = '0';
  3721. $data['gender'] = '0';
  3722. }
  3723. }
  3724. // 语速字段
  3725. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3726. $replaceEmptyArr[] = trim($speedMatch[0]);
  3727. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3728. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3729. }
  3730. // 音量字段
  3731. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3732. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3733. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3734. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3735. }
  3736. // 情感强度字段
  3737. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3738. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3739. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3740. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3741. }
  3742. // 音调字段
  3743. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3744. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3745. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3746. $data['pitch'] = (int)trim($pitchMatch[1]);
  3747. }
  3748. // 从 segment_content 中移除已提取的配音参数字段
  3749. if (!empty($replaceEmptyArr)) {
  3750. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3751. }
  3752. // 如果有配音角色,查询音色信息并验证情感
  3753. $voice_actor = $segmentData['voice_actor'];
  3754. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3755. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3756. $anime_id = getProp($data, 'anime_id');
  3757. $episode_id = getProp($data, 'episode_id');
  3758. // 优先从剧集的角色列表中查找
  3759. $roles = [];
  3760. if ($episode_id) {
  3761. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3762. if ($episode && getProp($episode, 'roles')) {
  3763. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3764. }
  3765. }
  3766. // 如果剧集中没有,从动漫的角色列表中查找
  3767. if (empty($roles) && $anime_id) {
  3768. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3769. if ($anime && getProp($anime, 'roles')) {
  3770. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3771. }
  3772. }
  3773. // 查找匹配的角色音色信息
  3774. $timbre_info = null;
  3775. foreach ($roles as $role) {
  3776. if (getProp($role, 'role') === $voice_actor) {
  3777. $timbre_info = $role;
  3778. break;
  3779. }
  3780. }
  3781. // 如果找到音色信息,添加到数据中
  3782. if ($timbre_info) {
  3783. $voice_type = getProp($timbre_info, 'voice_type');
  3784. $voice_name = getProp($timbre_info, 'voice_name');
  3785. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3786. if ($voice_type) {
  3787. $data['voice_type'] = $voice_type;
  3788. $segmentData['voice_type'] = $voice_type;
  3789. }
  3790. if ($voice_name) {
  3791. $data['voice_name'] = $voice_name;
  3792. $segmentData['voice_name'] = $voice_name;
  3793. }
  3794. if ($voice_audio_url) {
  3795. $data['voice_audio_url'] = $voice_audio_url;
  3796. $segmentData['voice_audio_url'] = $voice_audio_url;
  3797. }
  3798. // 验证情感是否在音色支持的情感列表中
  3799. if ($voice_type) {
  3800. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3801. if ($timbre_emotion) {
  3802. $timbre_emotion = explode(',', $timbre_emotion);
  3803. } else {
  3804. $timbre_emotion = [];
  3805. }
  3806. $emotion = getProp($segmentData, 'emotion', '中性');
  3807. if (!in_array($emotion, $timbre_emotion)) {
  3808. $emotion = '中性';
  3809. }
  3810. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3811. $emotion_list = array_flip($emotion_list);
  3812. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3813. $data['emotion_type'] = $emotion_type;
  3814. $segmentData['emotion_type'] = $emotion_type;
  3815. }
  3816. }
  3817. }
  3818. return $segmentData;
  3819. }
  3820. public function createSegmentVideoTask($data) {
  3821. $segment_id = getProp($data, 'segment_id');
  3822. $tail_frame = getProp($data, 'tail_frame');
  3823. $first_frame_url = getProp($data, 'first_frame_url');
  3824. $tail_frame_url = getProp($data, 'tail_frame_url');
  3825. $generate_audio = getProp($data, 'generate_audio', 0);
  3826. if (!$segment_id) {
  3827. Utils::throwError('1002:分镜ID不能为空');
  3828. }
  3829. // 获取分镜信息
  3830. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3831. if (!$segment) {
  3832. Utils::throwError('20003:分镜不存在');
  3833. }
  3834. $segment = (array)$segment;
  3835. $episode_id = getProp($segment, 'episode_id');
  3836. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3837. if (!$ratio) $ratio = '9:16';
  3838. // 获取分镜内容
  3839. $segmentContent = getProp($segment, 'segment_content', '');
  3840. // 检查 $segmentContent 中是否已有尾帧描述
  3841. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3842. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3843. $finalTailFrame = '';
  3844. if ($tail_frame) {
  3845. // 用户输入了尾帧描述,优先使用
  3846. $finalTailFrame = $tail_frame;
  3847. // 如果 segmentContent 中已有尾帧描述,需要替换
  3848. if ($contentHasTailFrame) {
  3849. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3850. }
  3851. } elseif ($contentHasTailFrame) {
  3852. // segmentContent 中有尾帧描述,使用它
  3853. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3854. } else {
  3855. // 两者都没有,使用分镜表中的尾帧描述
  3856. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3857. }
  3858. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3859. $hasDialogue = false;
  3860. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3861. $dialogue = trim($dialogueMatch[1]);
  3862. // 如果台词不为空且不是"无"
  3863. if (!empty($dialogue) && $dialogue !== '无') {
  3864. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3865. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3866. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3867. $hasDialogue = true;
  3868. }
  3869. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3870. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3871. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3872. if (!preg_match('/^[“]/', $dialogue)) {
  3873. $dialogue = '“' . $dialogue;
  3874. }
  3875. if (!preg_match('/[”]$/', $dialogue)) {
  3876. $dialogue .= '”';
  3877. }
  3878. // 将修改后的台词替换回 $segmentContent
  3879. $originalDialogue = $dialogueMatch[1];
  3880. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3881. }
  3882. }
  3883. // 构建完整的提示词
  3884. $fullPrompt = $segmentContent;
  3885. if ($finalTailFrame && !$contentHasTailFrame) {
  3886. // 只有当 segmentContent 中没有尾帧描述时才追加
  3887. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3888. }
  3889. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3890. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3891. $fullPrompt = trim($fullPrompt);
  3892. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3893. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3894. // 智能选择视频时长
  3895. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3896. $videoDuration = -1;
  3897. // 处理视频模型
  3898. $model = getProp($data, 'model');
  3899. if (!$model) {
  3900. // 用户没有输入,从episode表获取
  3901. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3902. $model = getProp($episode, 'video_model');
  3903. if (!$model) {
  3904. // episode表也没有,使用默认值
  3905. $model = 'doubao-seedance-1-5-pro-251215';
  3906. }
  3907. }
  3908. // 验证模型是否在可用模型表中
  3909. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3910. $model = 'doubao-seedance-1-5-pro-251215';
  3911. }
  3912. // 保存到episode表
  3913. $episode_id = getProp($segment, 'episode_id');
  3914. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3915. 'video_model' => $model,
  3916. 'updated_at' => date('Y-m-d H:i:s')
  3917. ]);
  3918. // 构建视频生成参数
  3919. $videoParams = [
  3920. 'model' => $model,
  3921. 'alias_segment_id' => $segment_id,
  3922. 'prompt' => trim($fullPrompt),
  3923. 'video_duration' => $videoDuration,
  3924. 'video_resolution' => '720P',
  3925. 'seed' => -1,
  3926. 'ratio' => $ratio,
  3927. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3928. 'draft' => false,
  3929. 'watermark' => false,
  3930. 'camera_fixed' => false,
  3931. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3932. ];
  3933. // 如果分镜有图片,作为首帧
  3934. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3935. $hasVideo = !empty(getProp($segment, 'video_url'));
  3936. if ($hasImage) {
  3937. if ($first_frame_url) {
  3938. $videoParams['first_frame_url'] = $first_frame_url;
  3939. }else {
  3940. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3941. }
  3942. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3943. }
  3944. // 构建content数组
  3945. $videoParams['content'] = [
  3946. [
  3947. 'type' => 'text',
  3948. 'text' => $videoParams['prompt'],
  3949. ]
  3950. ];
  3951. // 如果有首帧图片,添加到content中
  3952. if ($hasImage) {
  3953. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3954. $videoParams['content'][] = [
  3955. 'type' => 'image_url',
  3956. 'image_url' => [
  3957. 'url' => $videoParams['first_frame_url'],
  3958. ],
  3959. 'role' => 'reference_image',
  3960. ];
  3961. if (isset($videoParams['tail_frame_url'])) {
  3962. $videoParams['content'][] = [
  3963. 'type' => 'image_url',
  3964. 'image_url' => [
  3965. 'url' => $videoParams['tail_frame_url'],
  3966. ],
  3967. 'role' => 'reference_image',
  3968. ];
  3969. }
  3970. }else {
  3971. $videoParams['content'][] = [
  3972. 'type' => 'image_url',
  3973. 'image_url' => [
  3974. 'url' => $videoParams['first_frame_url'],
  3975. ],
  3976. 'role' => 'first_frame',
  3977. ];
  3978. if (isset($videoParams['tail_frame_url'])) {
  3979. $videoParams['content'][] = [
  3980. 'type' => 'image_url',
  3981. 'image_url' => [
  3982. 'url' => $videoParams['tail_frame_url'],
  3983. ],
  3984. 'role' => 'last_frame',
  3985. ];
  3986. }
  3987. }
  3988. }
  3989. // 获取配音音频URL
  3990. $audioUrl = getProp($segment, 'audio_url');
  3991. $audioDuration = getProp($segment, 'audio_duration');
  3992. // 音频传入的前提:必须有至少一张图片或一个视频
  3993. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3994. // dd($videoParams);
  3995. // 根据模型选择不同的视频生成方法
  3996. if (strpos($model, 'jimeng') !== false) {
  3997. // 即梦模型参数调整
  3998. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3999. unset($videoParams['content']); // 即梦不使用content格式
  4000. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4001. } elseif (strpos($model, 'kling') !== false) {
  4002. // Keling模型参数调整
  4003. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4004. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4005. unset($videoParams['ratio']);
  4006. unset($videoParams['content']); // Keling不使用content格式
  4007. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4008. } elseif (strpos($model, 'zhizhen') !== false) {
  4009. // 智帧20等新模型使用统一API
  4010. // 构建统一API参数
  4011. $unifiedParams = [
  4012. 'model_code' => $model,
  4013. 'alias_segment_id' => $segment_id,
  4014. 'prompt' => trim($fullPrompt),
  4015. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4016. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4017. 'video_ratio' => $ratio,
  4018. 'seed' => -1,
  4019. ];
  4020. // 构建parameters参数
  4021. $parameters = [
  4022. 'seconds' => $unifiedParams['video_duration'],
  4023. 'resolution' => $unifiedParams['video_resolution'],
  4024. 'ratio' => $ratio,
  4025. // 'video_mode' => 'multi_image',
  4026. // 'mode' => 'multi_image',
  4027. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4028. ];
  4029. $hasImage = false;
  4030. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4031. if ($hasImage) {
  4032. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4033. if (isset($videoParams['tail_frame_url'])) {
  4034. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4035. }
  4036. // 只有在有图片的情况下才能添加参考音频
  4037. if ($audioUrl) {
  4038. // $parameters['reference_audios'] = [$audioUrl];
  4039. }
  4040. } else {
  4041. // 没有图片时,记录错误日志
  4042. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4043. 'segment_id' => $segment_id,
  4044. 'model' => $model
  4045. ]);
  4046. }
  4047. $unifiedParams['parameters'] = $parameters;
  4048. // 调用统一API创建任务
  4049. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4050. } else {
  4051. // Seedance模型(默认)
  4052. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4053. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4054. // 添加配音音频到content中
  4055. $videoParams['content'][] = [
  4056. 'type' => 'audio_url',
  4057. 'audio_url' => [
  4058. 'url' => $audioUrl,
  4059. ],
  4060. 'role' => 'reference_audio',
  4061. ];
  4062. // 优化提示词,增加音频相关描述
  4063. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4064. $videoParams['prompt'] = $audioPrompt;
  4065. $videoParams['content'][0]['text'] = $audioPrompt;
  4066. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4067. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4068. }
  4069. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4070. }
  4071. // 更新分镜表的视频任务信息
  4072. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4073. 'video_task_id' => $task->id,
  4074. 'video_task_status' => '生成中',
  4075. 'generate_audio' => $generate_audio,
  4076. 'updated_at' => date('Y-m-d H:i:s')
  4077. ]);
  4078. return [
  4079. 'task_id' => $task->id,
  4080. 'status' => $task->status,
  4081. 'segment_id' => $segment_id,
  4082. 'video_duration' => $videoDuration
  4083. ];
  4084. }
  4085. public function createActVideoTask($data) {
  4086. $act_id = getProp($data, 'act_id');
  4087. $first_frame_url = getProp($data, 'first_frame_url');
  4088. $tail_frame_url = getProp($data, 'tail_frame_url');
  4089. $generate_audio = getProp($data, 'generate_audio', 1);
  4090. $video_duration = getProp($data, 'video_duration');
  4091. $video_resolution = getProp($data, 'video_resolution');
  4092. $ratio = getProp($data, 'ratio');
  4093. $products = getProp($data, 'products', []);
  4094. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4095. if (!is_array($reference_images) || !is_array($products)) {
  4096. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4097. }
  4098. if (!$act_id) {
  4099. Utils::throwError('1002:片段ID不能为空');
  4100. }
  4101. // 获取片段信息
  4102. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4103. if (!$act) {
  4104. Utils::throwError('20003:片段不存在');
  4105. }
  4106. $act = (array)$act;
  4107. $anime_id = getProp($act, 'anime_id');
  4108. $episode_id = getProp($act, 'episode_id');
  4109. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4110. $ace_mode = getProp($anime, 'ace_mode');
  4111. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4112. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4113. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4114. // 将资产中新出现的资产放到extra_products中
  4115. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4116. if (!empty($products) && $episode) {
  4117. // 获取剧集中的角色、场景和道具列表
  4118. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4119. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4120. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4121. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4122. // 构建角色名称列表
  4123. $role_names = array_column($roles, 'role');
  4124. // 构建场景名称列表
  4125. $scene_names = array_column($scenes, 'scene');
  4126. // 构建道具名称列表
  4127. $prop_names = array_column($props, 'prop');
  4128. // 遍历传入的products
  4129. foreach ($products as $product) {
  4130. $product_name = getProp($product, 'product_name');
  4131. // 如果product_name不在roles、scenes和props中
  4132. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4133. // 查找是否在extra_products中存在同名的
  4134. $found = false;
  4135. foreach ($extra_products as $key => $extra_product) {
  4136. if (getProp($extra_product, 'product_name') === $product_name) {
  4137. // 有同名的则覆盖
  4138. $extra_products[$key] = $product;
  4139. $found = true;
  4140. break;
  4141. }
  4142. }
  4143. // 没有则新增
  4144. if (!$found) {
  4145. $extra_products[] = $product;
  4146. }
  4147. }
  4148. }
  4149. if ($extra_products) {
  4150. // 保存到数据库
  4151. DB::table('mp_anime_episodes')
  4152. ->where('id', $episode_id)
  4153. ->update([
  4154. 'extra_products' => json_encode($extra_products, 256),
  4155. 'updated_at' => date('Y-m-d H:i:s')
  4156. ]);
  4157. }
  4158. }
  4159. // 获取分镜内容
  4160. $actContent = getProp($act, 'act_show_content', '');
  4161. // 音效同出(默认使用)
  4162. $current_generate_audio = $generate_audio ? 1 : 0;
  4163. // 构建完整的提示词
  4164. $processResult = $this->processActContentWithProducts($actContent, $products);
  4165. $fullPrompt = $processResult['content'];
  4166. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4167. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4168. // 处理视频模型
  4169. $model = getProp($data, 'model');
  4170. if (!$model) {
  4171. $model = getProp($episode, 'video_model');
  4172. if (!$model) {
  4173. // episode表也没有,使用默认值
  4174. $model = 'zhizhen-20';
  4175. }
  4176. }
  4177. // 验证模型是否在可用模型表中
  4178. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4179. $model = 'zhizhen-20';
  4180. }
  4181. // 保存到episode表
  4182. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4183. 'video_model' => $model,
  4184. 'updated_at' => date('Y-m-d H:i:s')
  4185. ]);
  4186. // 构建视频生成参数
  4187. $videoParams = [
  4188. 'model' => $model,
  4189. 'alias_act_id' => $act_id,
  4190. 'prompt' => trim($fullPrompt),
  4191. 'video_duration' => $videoDuration,
  4192. 'video_resolution' => $video_resolution,
  4193. 'seed' => -1,
  4194. 'ratio' => $ratio,
  4195. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4196. 'draft' => false,
  4197. 'watermark' => false,
  4198. 'camera_fixed' => false,
  4199. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4200. ];
  4201. // 如果分镜有图片,作为首帧
  4202. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4203. $hasVideo = !empty(getProp($act, 'video_url'));
  4204. if ($hasImage) {
  4205. if ($first_frame_url) {
  4206. $videoParams['first_frame_url'] = $first_frame_url;
  4207. }else {
  4208. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4209. }
  4210. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4211. }
  4212. // 构建content数组
  4213. $videoParams['content'] = [
  4214. [
  4215. 'type' => 'text',
  4216. 'text' => $videoParams['prompt'],
  4217. ]
  4218. ];
  4219. // 如果有首帧图片,添加到content中
  4220. if ($hasImage) {
  4221. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4222. $videoParams['content'][] = [
  4223. 'type' => 'image_url',
  4224. 'image_url' => [
  4225. 'url' => $videoParams['first_frame_url'],
  4226. ],
  4227. 'role' => 'reference_image',
  4228. ];
  4229. if (isset($videoParams['tail_frame_url'])) {
  4230. $videoParams['content'][] = [
  4231. 'type' => 'image_url',
  4232. 'image_url' => [
  4233. 'url' => $videoParams['tail_frame_url'],
  4234. ],
  4235. 'role' => 'reference_image',
  4236. ];
  4237. }
  4238. }else {
  4239. $videoParams['content'][] = [
  4240. 'type' => 'image_url',
  4241. 'image_url' => [
  4242. 'url' => $videoParams['first_frame_url'],
  4243. ],
  4244. 'role' => 'first_frame',
  4245. ];
  4246. if (isset($videoParams['tail_frame_url'])) {
  4247. $videoParams['content'][] = [
  4248. 'type' => 'image_url',
  4249. 'image_url' => [
  4250. 'url' => $videoParams['tail_frame_url'],
  4251. ],
  4252. 'role' => 'last_frame',
  4253. ];
  4254. }
  4255. }
  4256. }
  4257. // dd($videoParams);
  4258. // 根据模型选择不同的视频生成方法
  4259. if (strpos($model, 'jimeng') !== false) {
  4260. // 即梦模型参数调整
  4261. unset($videoParams['content']); // 即梦不使用content格式
  4262. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4263. } elseif (strpos($model, 'kling') !== false) {
  4264. // Keling模型参数调整
  4265. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4266. unset($videoParams['ratio']);
  4267. unset($videoParams['content']); // Keling不使用content格式
  4268. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4269. } elseif (strpos($model, 'zhizhen') !== false) {
  4270. // 智帧20等新模型使用统一API
  4271. // 构建统一API参数
  4272. $unifiedParams = [
  4273. 'model_code' => $model,
  4274. 'alias_act_id' => $act_id,
  4275. 'prompt' => trim($fullPrompt),
  4276. 'video_duration' => $videoDuration,
  4277. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4278. 'video_ratio' => $ratio,
  4279. 'seed' => -1,
  4280. ];
  4281. // 构建parameters参数
  4282. $parameters = [
  4283. 'seconds' => $unifiedParams['video_duration'],
  4284. 'resolution' => $unifiedParams['video_resolution'],
  4285. 'ratio' => $ratio,
  4286. // 'video_mode' => 'multi_image',
  4287. // 'mode' => 'multi_image',
  4288. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4289. ];
  4290. $hasImage = false;
  4291. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4292. if ($hasImage) {
  4293. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4294. if (isset($videoParams['tail_frame_url'])) {
  4295. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4296. }
  4297. } else {
  4298. // 没有图片时,记录错误日志
  4299. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4300. 'act_id' => $act_id,
  4301. 'model' => $model
  4302. ]);
  4303. }
  4304. if ($reference_images) {
  4305. // 限制只传入9张参考图
  4306. $reference_images = array_slice($reference_images, 0, 9);
  4307. // 在处理之前先保存原始reference_images到任务参数中
  4308. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4309. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4310. $parameters['reference_images'] = $reference_images;
  4311. $parameters['video_mode'] = 'multi_image';
  4312. $parameters['mode'] = 'multi_image';
  4313. }
  4314. $unifiedParams['parameters'] = $parameters;
  4315. // 调用统一API创建任务
  4316. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4317. } else {
  4318. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4319. }
  4320. // 更新分镜表的视频任务信息
  4321. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4322. 'video_task_id' => $task->id,
  4323. 'video_task_status' => '生成中',
  4324. 'generate_audio' => $generate_audio,
  4325. 'updated_at' => date('Y-m-d H:i:s')
  4326. ]);
  4327. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4328. $episode_number = getProp($act, 'episode_number');
  4329. $act_number = getProp($act, 'act_number');
  4330. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4331. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4332. }
  4333. return [
  4334. 'task_id' => $task->id,
  4335. 'status' => $task->status,
  4336. 'act_id' => $act_id,
  4337. 'video_duration' => $videoDuration
  4338. ];
  4339. }
  4340. /**
  4341. * 根据提示词内容智能计算最优视频时长
  4342. *
  4343. * @param string $segmentContent 分镜内容
  4344. * @param string $tailFrame 尾帧描述
  4345. * @return int 视频时长(2-12秒)
  4346. */
  4347. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4348. // 合并所有文本内容
  4349. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4350. // 如果没有内容,返回默认时长
  4351. if (empty($fullText)) {
  4352. return 5;
  4353. }
  4354. // 计算文本长度(中文字符按2个字符计算)
  4355. $textLength = mb_strlen($fullText, 'UTF-8');
  4356. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4357. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4358. // 分析内容复杂度
  4359. $complexityScore = $this->analyzeContentComplexity($fullText);
  4360. // 基础时长计算(根据文本长度)
  4361. $baseDuration = 3; // 默认2秒
  4362. // if ($adjustedLength <= 20) {
  4363. // $baseDuration = 3;
  4364. // } elseif ($adjustedLength <= 40) {
  4365. // $baseDuration = 4;
  4366. // } elseif ($adjustedLength <= 60) {
  4367. // $baseDuration = 5;
  4368. // } elseif ($adjustedLength <= 80) {
  4369. // $baseDuration = 6;
  4370. // } elseif ($adjustedLength <= 100) {
  4371. // $baseDuration = 7;
  4372. // } elseif ($adjustedLength <= 120) {
  4373. // $baseDuration = 8;
  4374. // } else {
  4375. // $baseDuration = 9;
  4376. // }
  4377. // 根据内容复杂度调整时长
  4378. $finalDuration = $baseDuration + $complexityScore;
  4379. // 确保时长在2-12秒范围内
  4380. return max(4, min(12, $finalDuration));
  4381. }
  4382. /**
  4383. * 分析内容复杂度,返回时长调整值
  4384. *
  4385. * @param string $text 文本内容
  4386. * @return int 调整值(-2到+3)
  4387. */
  4388. private function analyzeContentComplexity($text) {
  4389. $score = 0;
  4390. // 动作关键词(需要更长时间展现)
  4391. $actionKeywords = [
  4392. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4393. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4394. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4395. ];
  4396. // 静态关键词(可以用较短时间)
  4397. $staticKeywords = [
  4398. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4399. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4400. ];
  4401. // 复杂场景关键词(需要更长时间)
  4402. $complexSceneKeywords = [
  4403. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4404. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4405. ];
  4406. // 情感关键词(需要适中时间表现)
  4407. $emotionKeywords = [
  4408. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4409. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4410. ];
  4411. // 检查动作关键词
  4412. foreach ($actionKeywords as $keyword) {
  4413. if (strpos($text, $keyword) !== false) {
  4414. $score += 1;
  4415. break; // 避免重复加分
  4416. }
  4417. }
  4418. // 检查静态关键词
  4419. foreach ($staticKeywords as $keyword) {
  4420. if (strpos($text, $keyword) !== false) {
  4421. $score -= 1;
  4422. break;
  4423. }
  4424. }
  4425. // 检查复杂场景关键词
  4426. foreach ($complexSceneKeywords as $keyword) {
  4427. if (strpos($text, $keyword) !== false) {
  4428. $score += 1;
  4429. break;
  4430. }
  4431. }
  4432. // 检查情感关键词
  4433. foreach ($emotionKeywords as $keyword) {
  4434. if (strpos($text, $keyword) !== false) {
  4435. $score += 1;
  4436. break;
  4437. }
  4438. }
  4439. // 检查时间相关词汇
  4440. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4441. $score += 1;
  4442. }
  4443. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4444. $score -= 1;
  4445. }
  4446. // 检查转场词汇
  4447. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4448. $score += 1;
  4449. }
  4450. // 检查环境描述(复杂环境需要更多时间)
  4451. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4452. $score += 1;
  4453. }
  4454. // 检查对话内容(对话需要更多时间)
  4455. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4456. $score += 1;
  4457. }
  4458. // 限制调整范围
  4459. return max(-1, min(4, $score));
  4460. }
  4461. /**
  4462. * 创建完整视频合成任务
  4463. *
  4464. * @param array $data
  4465. * @return array
  4466. */
  4467. public function createCompleteVideoTask($data)
  4468. {
  4469. $animeId = getProp($data, 'anime_id');
  4470. $episodeId = getProp($data, 'episode_id');
  4471. // 验证参数
  4472. if (!$animeId || !$episodeId) {
  4473. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4474. }
  4475. // 检查是否已存在处理中的任务
  4476. $existingTask = DB::table('mp_complete_video_tasks')
  4477. ->where('anime_id', $animeId)
  4478. ->where('episode_id', $episodeId)
  4479. ->whereIn('generate_status', ['执行中'])
  4480. ->first();
  4481. if ($existingTask) {
  4482. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4483. }
  4484. // 获取全能模式状态
  4485. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4486. if ((int)$ace_mode === 1) {
  4487. // 获取所有片段的配音视频,按 act_number 排序
  4488. $segments = DB::table('mp_episode_segments')
  4489. ->where('anime_id', $animeId)
  4490. ->where('episode_id', $episodeId)
  4491. ->orderBy('segment_number')
  4492. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4493. ->get();
  4494. // 检查是否所有片段都有视频
  4495. $missingVideos = $segments->filter(function($segment) {
  4496. return empty($segment->video_url);
  4497. });
  4498. if ($missingVideos->isNotEmpty()) {
  4499. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4500. }
  4501. }else {
  4502. // 获取所有分镜的配音视频,按 segment_number 排序
  4503. $segments = DB::table('mp_episode_segments')
  4504. ->where('anime_id', $animeId)
  4505. ->where('episode_id', $episodeId)
  4506. ->orderBy('segment_number')
  4507. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4508. ->get();
  4509. // 检查是否所有分镜都有配音和视频
  4510. $missingVideos = $segments->filter(function($segment) {
  4511. return empty($segment->audio_url) || empty($segment->video_url);
  4512. });
  4513. if ($missingVideos->isNotEmpty()) {
  4514. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4515. }
  4516. }
  4517. if ($segments->isEmpty()) {
  4518. Utils::throwError('20003:未找到该剧集的分镜数据');
  4519. }
  4520. // 获取当前完整视频url
  4521. $completeVideoUrl = DB::table('mp_anime_episodes')
  4522. ->where('anime_id', $animeId)
  4523. ->where('id', $episodeId)
  4524. ->value('complete_video_url');
  4525. // 构建 generate_json
  4526. $generateJson = [];
  4527. $sequence = 1;
  4528. foreach ($segments as $segment) {
  4529. if ((int)$ace_mode === 1) {
  4530. $generateJson[] = [
  4531. 'sequence' => $sequence++,
  4532. 'video_url' => $segment->video_url,
  4533. 'video_time_point_start' => $segment->video_time_point_start,
  4534. 'video_time_point_end' => $segment->video_time_point_end
  4535. ];
  4536. }else {
  4537. $generateJson[] = [
  4538. 'sequence' => $sequence++,
  4539. 'video_url' => $segment->video_url,
  4540. 'audio_url' => $segment->audio_url,
  4541. 'video_time_point_start' => $segment->video_time_point_start,
  4542. 'video_time_point_end' => $segment->video_time_point_end
  4543. ];
  4544. }
  4545. }
  4546. // 创建任务
  4547. $now = date('Y-m-d H:i:s');
  4548. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4549. 'anime_id' => $animeId,
  4550. 'episode_id' => $episodeId,
  4551. 'generate_json' => json_encode($generateJson, 256),
  4552. 'generate_status' => '执行中',
  4553. 'complete_video_url' => '',
  4554. 'created_at' => $now,
  4555. 'updated_at' => $now
  4556. ]);
  4557. if (!$taskId) {
  4558. Utils::throwError('20003:创建任务失败');
  4559. }
  4560. // 更新剧集表的任务ID和状态
  4561. $boolen = DB::table('mp_anime_episodes')
  4562. ->where('anime_id', $animeId)
  4563. ->where('id', $episodeId)
  4564. ->update([
  4565. 'complete_video_task_id' => $taskId,
  4566. 'complete_video_task_status' => '执行中',
  4567. 'updated_at' => $now
  4568. ]);
  4569. if (!$boolen) {
  4570. Utils::throwError('20003:更新剧集表失败');
  4571. }
  4572. dLog('anime')->info('创建完整视频合成任务', [
  4573. 'task_id' => $taskId,
  4574. 'anime_id' => $animeId,
  4575. 'episode_id' => $episodeId,
  4576. 'segment_count' => count($generateJson)
  4577. ]);
  4578. // 请求远程服务器执行生成
  4579. $client = new Client(['timeout' => 600, 'verify' => false]);
  4580. try {
  4581. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4582. $response = $result->getBody()->getContents();
  4583. $response_arr = json_decode($response, true);
  4584. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4585. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4586. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4587. // // 更新任务状态为失败
  4588. // DB::table('mp_complete_video_tasks')
  4589. // ->where('id', $taskId)
  4590. // ->update([
  4591. // 'generate_status' => '执行失败',
  4592. // 'error_message' => $error_msg,
  4593. // 'updated_at' => date('Y-m-d H:i:s')
  4594. // ]);
  4595. // // 同步更新剧集表状态
  4596. // DB::table('mp_anime_episodes')
  4597. // ->where('complete_video_task_id', $taskId)
  4598. // ->update([
  4599. // 'complete_video_task_status' => '执行失败',
  4600. // 'updated_at' => date('Y-m-d H:i:s')
  4601. // ]);
  4602. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4603. }
  4604. } catch (\Exception $e) {
  4605. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4606. // 更新任务状态为失败
  4607. DB::table('mp_complete_video_tasks')
  4608. ->where('id', $taskId)
  4609. ->update([
  4610. 'generate_status' => '执行失败',
  4611. 'error_message' => $e->getMessage(),
  4612. 'updated_at' => date('Y-m-d H:i:s')
  4613. ]);
  4614. // 同步更新剧集表状态
  4615. DB::table('mp_anime_episodes')
  4616. ->where('complete_video_task_id', $taskId)
  4617. ->update([
  4618. 'complete_video_task_status' => '执行失败',
  4619. 'updated_at' => date('Y-m-d H:i:s')
  4620. ]);
  4621. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4622. }
  4623. // 开始轮询任务状态
  4624. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4625. $pollInterval = 5; // 每5秒轮询一次
  4626. $attempt = 0;
  4627. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4628. while ($attempt < $maxAttempts) {
  4629. sleep($pollInterval);
  4630. $attempt++;
  4631. // 查询任务状态
  4632. $task = DB::table('mp_complete_video_tasks')
  4633. ->where('id', $taskId)
  4634. ->first();
  4635. if (!$task) {
  4636. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4637. Utils::throwError('20003:任务不存在');
  4638. }
  4639. dLog('anime')->info('轮询任务状态', [
  4640. 'task_id' => $taskId,
  4641. 'attempt' => $attempt,
  4642. 'status' => $task->generate_status
  4643. ]);
  4644. // 检查任务是否完成
  4645. if ($task->generate_status === '执行成功') {
  4646. // 同步更新剧集表状态
  4647. $boolen3 = DB::table('mp_anime_episodes')
  4648. ->where('anime_id', $animeId)
  4649. ->where('id', $episodeId)
  4650. ->update([
  4651. 'complete_video_url' => $task->complete_video_url,
  4652. 'complete_video_task_status' => '执行成功',
  4653. 'updated_at' => date('Y-m-d H:i:s')
  4654. ]);
  4655. dLog('anime')->info('视频合成任务完成', [
  4656. 'task_id' => $taskId,
  4657. 'video_url' => $task->complete_video_url,
  4658. 'attempts' => $attempt
  4659. ]);
  4660. // 如果更新成功则远程删除之前的文件
  4661. if ($boolen3 && $completeVideoUrl) {
  4662. $encode_url = urlencode($completeVideoUrl);
  4663. $client = new Client(['timeout' => 300, 'verify' => false]);
  4664. // 根据ID通过API通知合成音频
  4665. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4666. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4667. $response = $result->getBody()->getContents();
  4668. $response_arr = json_decode($response, true);
  4669. Log::info('火山删除音频返回: '.$response);
  4670. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4671. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4672. Log::info('火山删除音频失败: '.$error_msg);
  4673. // Utils::throwError('20003:火山删除音频失败');
  4674. }
  4675. }
  4676. return [
  4677. 'task_id' => $taskId,
  4678. 'anime_id' => $animeId,
  4679. 'episode_id' => $episodeId,
  4680. 'segment_count' => count($generateJson),
  4681. 'generate_status' => '执行成功',
  4682. 'complete_video_url' => $task->complete_video_url,
  4683. ];
  4684. }
  4685. // 检查任务是否失败
  4686. if ($task->generate_status === '执行失败') {
  4687. // 同步更新剧集表状态
  4688. DB::table('mp_anime_episodes')
  4689. ->where('anime_id', $animeId)
  4690. ->where('id', $episodeId)
  4691. ->update([
  4692. 'complete_video_task_status' => '执行失败',
  4693. 'updated_at' => date('Y-m-d H:i:s')
  4694. ]);
  4695. $errorMessage = $task->error_message ?? '未知错误';
  4696. dLog('anime')->error('视频合成任务失败', [
  4697. 'task_id' => $taskId,
  4698. 'error' => $errorMessage,
  4699. 'attempts' => $attempt
  4700. ]);
  4701. return [
  4702. 'task_id' => $taskId,
  4703. 'anime_id' => $animeId,
  4704. 'episode_id' => $episodeId,
  4705. 'segment_count' => count($generateJson),
  4706. 'generate_status' => '执行失败',
  4707. 'error_message' => $errorMessage
  4708. ];
  4709. }
  4710. }
  4711. // 超时处理
  4712. dLog('anime')->warning('视频合成任务超时', [
  4713. 'task_id' => $taskId,
  4714. 'max_attempts' => $maxAttempts,
  4715. 'timeout_seconds' => $maxAttempts * $pollInterval
  4716. ]);
  4717. // 更新任务状态为超时
  4718. DB::table('mp_complete_video_tasks')
  4719. ->where('id', $taskId)
  4720. ->update([
  4721. 'generate_status' => '超时',
  4722. 'error_message' => '任务执行超时(5分钟)',
  4723. 'updated_at' => date('Y-m-d H:i:s')
  4724. ]);
  4725. return [
  4726. 'task_id' => $taskId,
  4727. 'anime_id' => $animeId,
  4728. 'episode_id' => $episodeId,
  4729. 'segment_count' => count($generateJson),
  4730. 'generate_status' => '超时',
  4731. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4732. ];
  4733. }
  4734. public function generateImg($data) {
  4735. $prompt = getProp($data, 'prompt');
  4736. $episode_id = getProp($data, 'episode_id');
  4737. $ref_img_urls = getProp($data, 'ref_img_urls');
  4738. $ratio = getProp($data, 'ratio', '9:16');
  4739. $resolution = getProp($data, 'resolution', '2k');
  4740. // 定义分辨率和宽高比对应的尺寸映射表
  4741. $sizeMap = [
  4742. '2k' => [
  4743. '1:1' => ['width' => 2048, 'height' => 2048],
  4744. '4:3' => ['width' => 2304, 'height' => 1728],
  4745. '3:4' => ['width' => 1728, 'height' => 2304],
  4746. '16:9' => ['width' => 2848, 'height' => 1600],
  4747. '9:16' => ['width' => 1600, 'height' => 2848],
  4748. '3:2' => ['width' => 2496, 'height' => 1664],
  4749. '2:3' => ['width' => 1664, 'height' => 2496],
  4750. '21:9' => ['width' => 3136, 'height' => 1344],
  4751. ],
  4752. '3k' => [
  4753. '1:1' => ['width' => 3072, 'height' => 3072],
  4754. '4:3' => ['width' => 3456, 'height' => 2592],
  4755. '3:4' => ['width' => 2592, 'height' => 3456],
  4756. '16:9' => ['width' => 4096, 'height' => 2304],
  4757. '9:16' => ['width' => 2304, 'height' => 4096],
  4758. '2:3' => ['width' => 2496, 'height' => 3744],
  4759. '3:2' => ['width' => 3744, 'height' => 2496],
  4760. '21:9' => ['width' => 4704, 'height' => 2016],
  4761. ],
  4762. '4k' => [
  4763. '1:1' => ['width' => 4096, 'height' => 4096],
  4764. '3:4' => ['width' => 3520, 'height' => 4704],
  4765. '4:3' => ['width' => 4704, 'height' => 3520],
  4766. '16:9' => ['width' => 5504, 'height' => 3040],
  4767. '9:16' => ['width' => 3040, 'height' => 5504],
  4768. '2:3' => ['width' => 3328, 'height' => 4992],
  4769. '3:2' => ['width' => 4992, 'height' => 3328],
  4770. '21:9' => ['width' => 6240, 'height' => 2656],
  4771. ],
  4772. ];
  4773. // 参数验证
  4774. $resolution = strtolower($resolution);
  4775. if (!isset($sizeMap[$resolution])) {
  4776. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4777. }
  4778. if (!isset($sizeMap[$resolution][$ratio])) {
  4779. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4780. }
  4781. // 根据 ratio 和 resolution 确定宽高
  4782. $width = $sizeMap[$resolution][$ratio]['width'];
  4783. $height = $sizeMap[$resolution][$ratio]['height'];
  4784. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4785. if (is_json($ref_img_urls)) {
  4786. $ref_img_urls = json_decode($ref_img_urls, true);
  4787. }else {
  4788. $ref_img_urls = explode(',', $ref_img_urls);
  4789. }
  4790. }
  4791. // 处理图片模型
  4792. $model = getProp($data, 'model');
  4793. if (!$model) {
  4794. // 用户没有输入,从episode表获取
  4795. if ($episode_id) {
  4796. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4797. $model = getProp($episode, 'image_model');
  4798. }
  4799. if (!$model) {
  4800. // episode表也没有,使用默认值
  4801. $model = 'doubao-seedream-5-0-lite-260128';
  4802. }
  4803. }
  4804. // 验证模型是否在可用模型表中
  4805. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4806. // $model = 'doubao-seedream-5-0-lite-260128';
  4807. Utils::throwError('20003:该模型已不可用,请更换!');
  4808. }
  4809. // 保存到episode表
  4810. if ($episode_id) {
  4811. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4812. 'image_model' => $model,
  4813. 'updated_at' => date('Y-m-d H:i:s')
  4814. ]);
  4815. }
  4816. // 参数验证
  4817. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4818. try {
  4819. // 创建图片生成任务
  4820. $params = [
  4821. 'prompt' => $prompt,
  4822. 'model' => $model,
  4823. 'ref_img_urls' => '',
  4824. 'width' => $width,
  4825. 'height' => $height
  4826. ];
  4827. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4828. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4829. $task_id = $task->id;
  4830. if (!$task_id) {
  4831. Utils::throwError('20003:创建图片生成任务失败');
  4832. }
  4833. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4834. $model = getProp($task, 'model');
  4835. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4836. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4837. $isSyncModel = $isVolcModel || $isGptModel;
  4838. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4839. $start_time = time();
  4840. $timeout = 300; // 5分钟
  4841. $img_url = '';
  4842. while (time() - $start_time < $timeout) {
  4843. sleep(3);
  4844. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4845. if ($isSyncModel) {
  4846. // 刷新任务状态
  4847. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4848. if ($task->status === 'success' && $task->result_url) {
  4849. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4850. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4851. break;
  4852. } elseif ($task->status === 'failed') {
  4853. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4854. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4855. }
  4856. // // 如果还在处理中,提示用户稍后查看
  4857. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4858. }else {
  4859. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4860. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4861. if ($statusInfo['status'] === 'success') {
  4862. $task->updateStatus('success', [
  4863. 'result_url' => $statusInfo['result_url'],
  4864. 'result_json' => $statusInfo['result_json'] ?? []
  4865. ]);
  4866. $img_url = $statusInfo['result_url'][0];
  4867. break;
  4868. } elseif ($statusInfo['status'] === 'failed') {
  4869. $task->updateStatus('failed', [
  4870. 'error_message' => $statusInfo['error_message'],
  4871. 'result_json' => $statusInfo['result_json'] ?? []
  4872. ]);
  4873. dLog('anime')->error('图片生成失败,', [
  4874. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4875. ]);
  4876. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4877. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4878. }
  4879. }
  4880. }
  4881. if (empty($img_url)) {
  4882. Utils::throwError('20003:图片生成超时,请稍后重试');
  4883. }
  4884. return $img_url;
  4885. } catch (\Exception $e) {
  4886. dLog('anime')->error('更新角色或场景失败', [
  4887. 'error' => $e->getMessage()
  4888. ]);
  4889. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4890. Utils::throwError('20003:' . $e->getMessage());
  4891. }
  4892. }
  4893. /**
  4894. * 使用文生文模型解析分镜内容
  4895. */
  4896. private function parseSegmentContentWithAI($segment_content) {
  4897. try {
  4898. // 使用DeepSeek服务的公开方法解析分镜内容
  4899. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4900. } catch (\Exception $e) {
  4901. // 如果AI解析失败,记录日志并返回原内容
  4902. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4903. return $segment_content;
  4904. }
  4905. }
  4906. /**
  4907. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4908. *
  4909. * @param int $episode_id 分集ID
  4910. * @param int $anime_id 动漫ID
  4911. * @param array $roles 分集角色数组(引用传递)
  4912. * @param array $scenes 分集场景数组(引用传递)
  4913. * @param array $episode 分集数据
  4914. */
  4915. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4916. // 获取全局动漫的角色和场景数据
  4917. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4918. if (!$anime) return;
  4919. $art_style_type = getProp($anime, 'art_style_type');
  4920. $character_prefix = '';
  4921. $scene_prefix = '';
  4922. if ($art_style_type) {
  4923. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4924. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4925. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4926. }
  4927. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4928. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4929. $roles_updated = false;
  4930. $scenes_updated = false;
  4931. // 处理角色
  4932. foreach ($roles as &$role) {
  4933. $role_name = getProp($role, 'role');
  4934. $role_description = getProp($role, 'description');
  4935. $role_pic_prompt = getProp($role, 'pic_prompt');
  4936. $role_url = getProp($role, 'url');
  4937. $role_task_id = getProp($role, 'task_id');
  4938. // 如果已有URL或已有任务ID,跳过
  4939. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4940. continue;
  4941. }
  4942. $url_inherited = false;
  4943. // 尝试从全局数据中继承
  4944. foreach ($global_roles as $global_role) {
  4945. $global_role_name = getProp($global_role, 'role');
  4946. $global_role_description = getProp($global_role, 'description');
  4947. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4948. $global_role_url = getProp($global_role, 'url');
  4949. $global_role_task_id = getProp($global_role, 'task_id');
  4950. $global_role_task_status = getProp($global_role, 'task_status');
  4951. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4952. if ($role_name === $global_role_name
  4953. && $role_description === $global_role_description
  4954. && $role_pic_prompt === $global_role_pic_prompt
  4955. && !empty($global_role_url)) {
  4956. // 继承 task_id、task_status 和 url
  4957. $role['task_id'] = $global_role_task_id;
  4958. $role['task_status'] = $global_role_task_status;
  4959. $role['url'] = $global_role_url;
  4960. $roles_updated = true;
  4961. $url_inherited = true;
  4962. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4963. break;
  4964. }
  4965. }
  4966. // 如果无法继承且没有任务ID,创建新任务
  4967. if (!$url_inherited && empty($role_task_id)) {
  4968. try {
  4969. $art_style = getProp($episode, 'art_style');
  4970. // 优先使用 pic_prompt,如果没有则使用 description
  4971. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4972. // if ($art_style) {
  4973. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4974. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4975. // }
  4976. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4977. $params = [
  4978. 'prompt' => $description,
  4979. 'ref_img_urls' => []
  4980. ];
  4981. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4982. $task_id = $task->id;
  4983. if ($task_id) {
  4984. $role['task_id'] = $task_id;
  4985. $role['task_status'] = 'processing';
  4986. $roles_updated = true;
  4987. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4988. }
  4989. } catch (\Exception $e) {
  4990. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4991. }
  4992. }
  4993. }
  4994. // 处理场景
  4995. foreach ($scenes as &$scene) {
  4996. $scene_name = getProp($scene, 'scene');
  4997. $scene_description = getProp($scene, 'description');
  4998. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4999. $scene_url = getProp($scene, 'url');
  5000. $scene_task_id = getProp($scene, 'task_id');
  5001. // 如果已有URL或已有任务ID,跳过
  5002. if (!empty($scene_url) || !empty($scene_task_id)) {
  5003. continue;
  5004. }
  5005. $url_inherited = false;
  5006. // 尝试从全局数据中继承
  5007. foreach ($global_scenes as $global_scene) {
  5008. $global_scene_name = getProp($global_scene, 'scene');
  5009. $global_scene_description = getProp($global_scene, 'description');
  5010. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5011. $global_scene_url = getProp($global_scene, 'url');
  5012. $global_scene_task_id = getProp($global_scene, 'task_id');
  5013. $global_scene_task_status = getProp($global_scene, 'task_status');
  5014. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5015. if ($scene_name === $global_scene_name
  5016. && $scene_description === $global_scene_description
  5017. && $scene_pic_prompt === $global_scene_pic_prompt
  5018. && !empty($global_scene_url)) {
  5019. // 继承 task_id、task_status 和 url
  5020. $scene['task_id'] = $global_scene_task_id;
  5021. $scene['task_status'] = $global_scene_task_status;
  5022. $scene['url'] = $global_scene_url;
  5023. $scenes_updated = true;
  5024. $url_inherited = true;
  5025. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5026. break;
  5027. }
  5028. }
  5029. // 如果无法继承且没有任务ID,创建新任务
  5030. if (!$url_inherited && empty($scene_task_id)) {
  5031. try {
  5032. $art_style = getProp($episode, 'art_style');
  5033. // 优先使用 pic_prompt,如果没有则使用 description
  5034. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5035. // if ($art_style) {
  5036. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5037. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5038. // }
  5039. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5040. $params = [
  5041. 'prompt' => $description,
  5042. 'ref_img_urls' => []
  5043. ];
  5044. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5045. $task_id = $task->id;
  5046. if ($task_id) {
  5047. $scene['task_id'] = $task_id;
  5048. $scene['task_status'] = 'processing';
  5049. $scenes_updated = true;
  5050. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5051. }
  5052. } catch (\Exception $e) {
  5053. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5054. }
  5055. }
  5056. }
  5057. // 如果有更新,保存到数据库
  5058. if ($roles_updated || $scenes_updated) {
  5059. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5060. if ($roles_updated) {
  5061. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5062. }
  5063. if ($scenes_updated) {
  5064. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5065. }
  5066. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5067. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5068. }
  5069. }
  5070. /**
  5071. * 根据图片URL使用AI反推图片提示词
  5072. *
  5073. * @param string $img_url 图片URL
  5074. * @return string 反推的提示词
  5075. */
  5076. private function generateImagePromptFromUrl($img_url) {
  5077. try {
  5078. // 获取默认模型
  5079. $model = 'doubao-seed-2-0-mini-260215';
  5080. // 构建messages参数
  5081. $messages = [
  5082. [
  5083. 'role' => 'user',
  5084. 'content' => [
  5085. [
  5086. 'type' => 'text',
  5087. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5088. ],
  5089. [
  5090. 'type' => 'image_url',
  5091. 'image_url' => [
  5092. 'url' => $img_url
  5093. ]
  5094. ]
  5095. ]
  5096. ]
  5097. ];
  5098. // 构建请求参数
  5099. $params = [
  5100. 'model' => $model,
  5101. 'messages' => $messages,
  5102. 'stream' => false,
  5103. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5104. ];
  5105. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5106. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5107. // 返回生成的内容
  5108. return getProp($result, 'fullContent', '图片描述生成失败');
  5109. } catch (\Exception $e) {
  5110. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5111. 'img_url' => $img_url
  5112. ]);
  5113. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5114. 'error' => $e->getMessage(),
  5115. 'img_url' => $img_url
  5116. ]);
  5117. return '图片描述生成失败: ' . $e->getMessage();
  5118. }
  5119. }
  5120. /**
  5121. * 音频试听接口
  5122. * 创建音频任务并轮询获取结果
  5123. *
  5124. * @param array $data 参数数组
  5125. * @return array 返回音频URL或错误信息
  5126. */
  5127. public function previewAudio($data) {
  5128. $dialogue = getProp($data, 'dialogue');
  5129. // 必填参数验证
  5130. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5131. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5132. $voice_type = getProp($data, 'voice_type');
  5133. $voice_name = getProp($data, 'voice_name');
  5134. $voice_actor = getProp($data, 'voice_actor');
  5135. $emotion_type = getProp($data, 'emotion_type');
  5136. $gender = getProp($data, 'gender', 0);
  5137. $emotion = getProp($data, 'emotion');
  5138. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5139. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5140. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5141. $pitch = getProp($data, 'pitch', 0);
  5142. try {
  5143. $now = date('Y-m-d H:i:s');
  5144. // 构建生成参数
  5145. $generate_json = json_encode([
  5146. 'text' => $dialogue,
  5147. 'role' => $voice_actor,
  5148. 'voice_type' => $voice_type,
  5149. 'voice_name' => $voice_name,
  5150. 'emotion' => $emotion,
  5151. 'emotion_type' => $emotion_type,
  5152. 'gender' => $gender,
  5153. 'speed_ratio' => $speed_ratio,
  5154. 'loudness_ratio' => $loudness_ratio,
  5155. 'emotion_scale' => $emotion_scale,
  5156. 'pitch' => $pitch,
  5157. ], 256);
  5158. // 请求远程服务器执行生成
  5159. $client = new Client(['timeout' => 600, 'verify' => false]);
  5160. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5161. $response = $result->getBody()->getContents();
  5162. $response_arr = json_decode($response, true);
  5163. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5164. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5165. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5166. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5167. }
  5168. $arr = $response_arr['data'];
  5169. $subtitle_info = $arr['subtitle_info'];
  5170. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5171. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5172. return [
  5173. 'audio_url' => $arr['url'],
  5174. 'subtitle_info' => $subtitle_info,
  5175. 'audio_duration' => round($audio_duration, 2)
  5176. ];
  5177. } catch (\Exception $e) {
  5178. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5179. Utils::throwError('20003:' . $e->getMessage());
  5180. }
  5181. }
  5182. /**
  5183. * 获取角色库列表(支持文件夹递归查询)
  5184. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5185. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5186. */
  5187. public function globalProducts($data) {
  5188. $uid = Site::getUid();
  5189. $cpid = Site::getCpid();
  5190. $role = Site::getRole();
  5191. $id = getProp($data, 'id', 0);
  5192. $parent_id = getProp($data, 'parent_id', 0);
  5193. $product_name = getProp($data, 'product_name');
  5194. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5195. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5196. if (!$product) {
  5197. Utils::throwError('20003:请选择产品类型');
  5198. }
  5199. // 根据角色和is_public参数确定查询范围
  5200. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5201. // user角色:根据is_public参数筛选
  5202. $query_user_ids = [];
  5203. if ($role === 'admin') {
  5204. // admin获取所有个人库和公共库
  5205. $query_user_ids = [$uid, 0];
  5206. } else {
  5207. // user角色根据is_public参数筛选
  5208. if ($is_public == 2) {
  5209. // 个人库+公共库
  5210. $query_user_ids = [$uid, 0];
  5211. } elseif ($is_public == 0) {
  5212. // 仅个人库
  5213. $query_user_ids = [$uid];
  5214. } elseif ($is_public == 1) {
  5215. // 仅公共库
  5216. $query_user_ids = [0];
  5217. }
  5218. }
  5219. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5220. if ($id || $product_name) {
  5221. $query = DB::table('mp_products')
  5222. ->where('cpid', $cpid)
  5223. ->whereIn('user_id', $query_user_ids)
  5224. ->where('is_deleted', 0);
  5225. // 如果指定了 id,按 id 精确查询
  5226. if ($id) {
  5227. $query->where('id', $id);
  5228. }
  5229. // 如果指定了 product_name,按名称模糊查询
  5230. if ($product_name) {
  5231. $query->where('product_name', 'like', "%{$product_name}%");
  5232. }
  5233. // 如果指定了 product,添加筛选条件
  5234. if ($product) {
  5235. $query->where('product', $product);
  5236. }
  5237. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5238. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5239. ->get()
  5240. ->map(function($value) {
  5241. $value = (array)$value;
  5242. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5243. $value['type'] = (int)$value['type'];
  5244. $value['parent_id'] = (int)$value['parent_id'];
  5245. $value['level'] = (int)$value['level'];
  5246. $value['product'] = (int)($value['product'] ?? 1);
  5247. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5248. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5249. unset($value['user_id']);
  5250. return $value;
  5251. })
  5252. ->toArray();
  5253. return $result;
  5254. }
  5255. // 递归获取所有子目录和角色
  5256. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5257. }
  5258. /**
  5259. * 递归获取指定目录下的所有子目录和角色
  5260. * @param int $cpid 公司ID
  5261. * @param int $parent_id 父目录ID
  5262. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5263. * @param array $query_user_ids 用户ID数组(支持多个)
  5264. * @param int $current_uid 当前用户ID(用于排序)
  5265. * @return array
  5266. */
  5267. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5268. // 查询当前层级的所有项(文件夹和角色)
  5269. $query = DB::table('mp_products')
  5270. ->where('cpid', $cpid)
  5271. ->where('is_deleted', 0)
  5272. ->where('parent_id', $parent_id);
  5273. // 添加用户ID验证(支持多个user_id)
  5274. if (!empty($query_user_ids)) {
  5275. $query->whereIn('user_id', $query_user_ids);
  5276. }
  5277. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5278. if ($product) {
  5279. $query->where('product', $product);
  5280. }
  5281. // 排序规则:
  5282. // 1. 文件夹在前(type DESC)
  5283. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5284. // 3. 其他排序规则
  5285. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5286. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5287. ->get();
  5288. $result = [];
  5289. foreach ($items as $item) {
  5290. $itemArray = [
  5291. 'id' => $item->id,
  5292. 'type' => (int)$item->type,
  5293. 'parent_id' => (int)$item->parent_id,
  5294. 'level' => (int)$item->level,
  5295. 'product_name' => $item->product_name,
  5296. 'url' => $item->url,
  5297. 'pic_prompt' => $item->pic_prompt ?? '',
  5298. 'three_view_image_url' => $item->three_view_image_url,
  5299. 'product' => (int)($item->product ?? 1),
  5300. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5301. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5302. ];
  5303. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5304. // 如果是文件夹,递归获取其子项
  5305. if ($item->type == 2) {
  5306. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5307. if (!empty($children)) {
  5308. $itemArray['children'] = $children;
  5309. }
  5310. }
  5311. $result[] = $itemArray;
  5312. }
  5313. return $result;
  5314. }
  5315. /**
  5316. * 创建文件夹
  5317. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5318. * @return int 返回新建文件夹ID
  5319. */
  5320. public function createFolder($data) {
  5321. $uid = Site::getUid();
  5322. $cpid = Site::getCpid();
  5323. $role = Site::getRole();
  5324. $parent_id = getProp($data, 'parent_id', 0);
  5325. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5326. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5327. // 如果是公共库操作,需要admin权限
  5328. if ($is_public && $role !== 'admin') {
  5329. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5330. }
  5331. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5332. $store_uid = $is_public ? 0 : $uid;
  5333. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5334. $product = getProp($data, 'product');
  5335. if (!in_array($product, [1, 2, 3])) {
  5336. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5337. }
  5338. // 验证父文件夹
  5339. $parent_level = 0;
  5340. if ($parent_id > 0) {
  5341. $parent = DB::table('mp_products')
  5342. ->where('id', $parent_id)
  5343. ->where('cpid', $cpid)
  5344. ->where('user_id', $store_uid)
  5345. ->where('type', 2)
  5346. ->where('is_deleted', 0)
  5347. ->first();
  5348. if (!$parent) {
  5349. Utils::throwError('20003:父文件夹不存在');
  5350. }
  5351. // 检查父文件夹的 product 类型是否一致
  5352. if ($parent->product != $product) {
  5353. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5354. }
  5355. $parent_level = $parent->level;
  5356. // 检查层级限制(最多3层)
  5357. if ($parent_level >= 3) {
  5358. Utils::throwError('20003:文件夹层级不能超过3层');
  5359. }
  5360. }
  5361. // 检查当前目录下是否已存在空白文件夹
  5362. $empty_folder_exists = DB::table('mp_products')
  5363. ->where('parent_id', $parent_id)
  5364. ->where('cpid', $cpid)
  5365. ->where('user_id', $store_uid)
  5366. ->where('type', 2)
  5367. ->where('product', $product)
  5368. ->where('product_name', '新建文件夹')
  5369. ->where('is_deleted', 0)
  5370. ->exists();
  5371. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5372. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5373. }
  5374. // 创建文件夹
  5375. $folder_id = DB::table('mp_products')->insertGetId([
  5376. 'user_id' => $store_uid,
  5377. 'cpid' => $cpid,
  5378. 'type' => 2,
  5379. 'parent_id' => $parent_id,
  5380. 'level' => $parent_level + 1,
  5381. 'product_name' => $folder_name,
  5382. 'product' => $product,
  5383. 'sort_order' => time(), // 使用时间戳作为排序权重
  5384. 'is_deleted' => 0,
  5385. 'created_at' => date('Y-m-d H:i:s'),
  5386. 'updated_at' => date('Y-m-d H:i:s')
  5387. ]);
  5388. return [
  5389. 'id' => $folder_id,
  5390. 'type' => 2,
  5391. 'parent_id' => $parent_id,
  5392. 'level' => $parent_level + 1,
  5393. 'product_name' => $folder_name,
  5394. 'product' => $product,
  5395. ];
  5396. }
  5397. /**
  5398. * 重命名文件夹或角色
  5399. * @param array $data 包含 id、product_name(新名称)
  5400. * @return bool
  5401. */
  5402. public function renameFolder($data) {
  5403. $uid = Site::getUid();
  5404. $cpid = Site::getCpid();
  5405. $role = Site::getRole();
  5406. $id = getProp($data, 'id');
  5407. $new_name = getProp($data, 'product_name');
  5408. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5409. if (!$id || !$new_name) {
  5410. Utils::throwError('20003:参数不完整');
  5411. }
  5412. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5413. $query_uid = $is_public ? 0 : $uid;
  5414. // 如果是公共库操作,需要admin权限
  5415. if ($is_public && $role !== 'admin') {
  5416. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5417. }
  5418. // 检查是否存在
  5419. $item = DB::table('mp_products')
  5420. ->where('id', $id)
  5421. ->where('cpid', $cpid)
  5422. ->where('user_id', $query_uid)
  5423. ->where('is_deleted', 0)
  5424. ->first();
  5425. if (!$item) {
  5426. Utils::throwError('20003:项目不存在');
  5427. }
  5428. return DB::table('mp_products')
  5429. ->where('id', $id)
  5430. ->where('cpid', $cpid)
  5431. ->where('user_id', $query_uid)
  5432. ->update([
  5433. 'product_name' => $new_name,
  5434. 'updated_at' => date('Y-m-d H:i:s')
  5435. ]);
  5436. }
  5437. /**
  5438. * 移动角色或文件夹到指定文件夹
  5439. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5440. * @return bool
  5441. */
  5442. public function moveProductOrFolder($data) {
  5443. $uid = Site::getUid();
  5444. $cpid = Site::getCpid();
  5445. $role = Site::getRole();
  5446. $id = getProp($data, 'id');
  5447. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5448. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5449. if (!$id) {
  5450. Utils::throwError('20003:请选择要移动的项目');
  5451. }
  5452. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5453. $query_uid = $is_public ? 0 : $uid;
  5454. // 如果是公共库操作,需要admin权限
  5455. if ($is_public && $role !== 'admin') {
  5456. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5457. }
  5458. // 检查要移动的项目
  5459. $item = DB::table('mp_products')
  5460. ->where('id', $id)
  5461. ->where('cpid', $cpid)
  5462. ->where('user_id', $query_uid)
  5463. ->where('is_deleted', 0)
  5464. ->first();
  5465. if (!$item) {
  5466. Utils::throwError('20003:项目不存在');
  5467. }
  5468. // 验证目标文件夹
  5469. $target_level = 0;
  5470. $target_product = $item->product; // 默认使用当前项目的 product
  5471. if ($target_parent_id > 0) {
  5472. $target_parent = DB::table('mp_products')
  5473. ->where('id', $target_parent_id)
  5474. ->where('cpid', $cpid)
  5475. ->where('user_id', $query_uid)
  5476. ->where('type', 2)
  5477. ->where('is_deleted', 0)
  5478. ->first();
  5479. if (!$target_parent) {
  5480. Utils::throwError('20003:目标文件夹不存在');
  5481. }
  5482. // 检查 product 类型是否一致
  5483. if ($target_parent->product != $item->product) {
  5484. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5485. }
  5486. $target_level = $target_parent->level;
  5487. $target_product = $target_parent->product;
  5488. // 如果移动的是文件夹,需要检查层级
  5489. if ($item->type == 2) {
  5490. // 计算移动后的最大层级
  5491. $max_child_level = $this->getMaxChildLevel($id);
  5492. $depth = $max_child_level - $item->level;
  5493. if ($target_level + 1 + $depth > 3) {
  5494. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5495. }
  5496. // 不能移动到自己或自己的子文件夹下
  5497. if ($this->isDescendant($target_parent_id, $id)) {
  5498. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5499. }
  5500. }
  5501. }
  5502. // 更新父文件夹和层级
  5503. $new_level = $target_level + 1;
  5504. DB::table('mp_products')
  5505. ->where('id', $id)
  5506. ->update([
  5507. 'parent_id' => $target_parent_id,
  5508. 'level' => $new_level,
  5509. 'updated_at' => date('Y-m-d H:i:s')
  5510. ]);
  5511. // 如果是文件夹,需要递归更新所有子项的层级
  5512. if ($item->type == 2) {
  5513. $this->updateChildrenLevel($id, $new_level);
  5514. }
  5515. return true;
  5516. }
  5517. /**
  5518. * 获取文件夹下最大子层级
  5519. * @param int $folder_id
  5520. * @return int
  5521. */
  5522. private function getMaxChildLevel($folder_id) {
  5523. $max_level = DB::table('mp_products')
  5524. ->where('parent_id', $folder_id)
  5525. ->where('is_deleted', 0)
  5526. ->max('level');
  5527. if (!$max_level) {
  5528. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5529. }
  5530. // 递归查找子文件夹
  5531. $children = DB::table('mp_products')
  5532. ->where('parent_id', $folder_id)
  5533. ->where('type', 2)
  5534. ->where('is_deleted', 0)
  5535. ->pluck('id');
  5536. foreach ($children as $child_id) {
  5537. $child_max = $this->getMaxChildLevel($child_id);
  5538. if ($child_max > $max_level) {
  5539. $max_level = $child_max;
  5540. }
  5541. }
  5542. return $max_level;
  5543. }
  5544. /**
  5545. * 检查 target_id 是否是 folder_id 的后代
  5546. * @param int $target_id
  5547. * @param int $folder_id
  5548. * @return bool
  5549. */
  5550. private function isDescendant($target_id, $folder_id) {
  5551. if ($target_id == $folder_id) {
  5552. return true;
  5553. }
  5554. $parent = DB::table('mp_products')
  5555. ->where('id', $target_id)
  5556. ->where('is_deleted', 0)
  5557. ->first();
  5558. if (!$parent || $parent->parent_id == 0) {
  5559. return false;
  5560. }
  5561. return $this->isDescendant($parent->parent_id, $folder_id);
  5562. }
  5563. /**
  5564. * 递归更新子项层级
  5565. * @param int $parent_id
  5566. * @param int $parent_level
  5567. */
  5568. private function updateChildrenLevel($parent_id, $parent_level) {
  5569. $children = DB::table('mp_products')
  5570. ->where('parent_id', $parent_id)
  5571. ->where('is_deleted', 0)
  5572. ->get();
  5573. foreach ($children as $child) {
  5574. $new_level = $parent_level + 1;
  5575. DB::table('mp_products')
  5576. ->where('id', $child->id)
  5577. ->update([
  5578. 'level' => $new_level,
  5579. 'updated_at' => date('Y-m-d H:i:s')
  5580. ]);
  5581. // 如果是文件夹,继续递归
  5582. if ($child->type == 2) {
  5583. $this->updateChildrenLevel($child->id, $new_level);
  5584. }
  5585. }
  5586. }
  5587. /**
  5588. * 获取文件夹路径(面包屑导航)
  5589. * @param array $data 包含 folder_id
  5590. * @return array 返回路径数组
  5591. */
  5592. public function getFolderPath($data) {
  5593. $uid = Site::getUid();
  5594. $cpid = Site::getCpid();
  5595. $folder_id = getProp($data, 'id', 0);
  5596. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5597. if ($folder_id == 0) {
  5598. return [
  5599. ['id' => 0, 'name' => '根目录']
  5600. ];
  5601. }
  5602. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5603. $query_uid = $is_public ? 0 : $uid;
  5604. $path = [];
  5605. $current_id = $folder_id;
  5606. while ($current_id > 0) {
  5607. $folder = DB::table('mp_products')
  5608. ->where('id', $current_id)
  5609. ->where('cpid', $cpid)
  5610. ->where('user_id', $query_uid)
  5611. ->where('type', 2)
  5612. ->where('is_deleted', 0)
  5613. ->first();
  5614. if (!$folder) {
  5615. break;
  5616. }
  5617. array_unshift($path, [
  5618. 'id' => $folder->id,
  5619. 'name' => $folder->product_name
  5620. ]);
  5621. $current_id = $folder->parent_id;
  5622. }
  5623. // 添加根目录
  5624. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5625. return $path;
  5626. }
  5627. public function createProduct($data) {
  5628. $uid = Site::getUid();
  5629. $cpid = Site::getCpid();
  5630. $role = Site::getRole();
  5631. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5632. // 如果是公共库操作,需要admin权限
  5633. if ($is_public && $role !== 'admin') {
  5634. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5635. }
  5636. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5637. $store_uid = $is_public ? 0 : $uid;
  5638. $product_name = trim(getProp($data, 'product_name'));
  5639. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5640. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5641. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5642. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5643. $url = trim(getProp($data, 'url'));
  5644. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5645. $versions = getProp($data, 'versions');
  5646. // 检查是否是正确的图片格式
  5647. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5648. $urlPath = parse_url($url, PHP_URL_PATH);
  5649. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5650. if (!in_array($extension, $allowedExtensions)) {
  5651. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5652. }
  5653. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5654. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5655. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5656. $product = getProp($data, 'product');
  5657. if (!in_array($product, [1, 2, 3])) {
  5658. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5659. }
  5660. // 获取父文件夹ID和层级
  5661. $parent_id = getProp($data, 'parent_id', 0);
  5662. $parent_level = 0;
  5663. if ($parent_id > 0) {
  5664. $parent = DB::table('mp_products')
  5665. ->where('id', $parent_id)
  5666. ->where('cpid', $cpid)
  5667. ->where('user_id', $store_uid)
  5668. ->where('type', 2)
  5669. ->where('is_deleted', 0)
  5670. ->first();
  5671. if (!$parent) {
  5672. Utils::throwError('20003:父文件夹不存在');
  5673. }
  5674. $parent_level = $parent->level;
  5675. }
  5676. $id = DB::table('mp_products')->insertGetId([
  5677. 'user_id' => $store_uid,
  5678. 'cpid' => $cpid,
  5679. 'type' => 1, // 1=角色图片
  5680. 'parent_id' => $parent_id,
  5681. 'level' => $parent_level + 1,
  5682. 'product_name' => $product_name,
  5683. 'url' => $url,
  5684. 'pic_prompt' => $pic_prompt,
  5685. 'product' => $product,
  5686. 'versions' => json_encode($versions, 256),
  5687. 'sort_order' => time(), // 使用时间戳作为排序权重
  5688. 'created_at' => date('Y-m-d H:i:s'),
  5689. 'updated_at' => date('Y-m-d H:i:s')
  5690. ]);
  5691. if (!$id) Utils::throwError('20003:创建失败');
  5692. return [
  5693. 'id' => $id,
  5694. 'type' => 1,
  5695. 'parent_id' => $parent_id,
  5696. 'level' => $parent_level + 1,
  5697. 'product_name' => $product_name,
  5698. 'url' => $url,
  5699. 'pic_prompt' => $pic_prompt,
  5700. 'product' => $product,
  5701. 'versions' => $versions
  5702. ];
  5703. }
  5704. public function editProduct($data) {
  5705. $uid = Site::getUid();
  5706. $cpid = Site::getCpid();
  5707. $role = Site::getRole();
  5708. $id = getProp($data, 'id');
  5709. if (!$id) Utils::throwError('20003:ID不能为空');
  5710. $versions = getProp($data, 'versions');
  5711. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5712. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5713. $query_uid = $is_public ? 0 : $uid;
  5714. // 如果是公共库操作,需要admin权限
  5715. if ($is_public && $role !== 'admin') {
  5716. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5717. }
  5718. // 检查是否存在且属于当前用户或公共库
  5719. $role = DB::table('mp_products')
  5720. ->where('id', $id)
  5721. ->where('cpid', $cpid)
  5722. ->where('user_id', $query_uid)
  5723. ->where('type', 1)->first();
  5724. if (!$role) Utils::throwError('20003:记录不存在');
  5725. $updateData = [];
  5726. // $needVersionRecord = false; // 是否需要记录版本
  5727. // 名称
  5728. $product_name = trim(getProp($data, 'product_name'));
  5729. if ($product_name) {
  5730. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5731. $updateData['product_name'] = $product_name;
  5732. }
  5733. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5734. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5735. // 图片地址
  5736. $url = trim(getProp($data, 'url'));
  5737. if ($url) {
  5738. // 检查是否是正确的图片格式
  5739. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5740. $urlPath = parse_url($url, PHP_URL_PATH);
  5741. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5742. if (!in_array($extension, $allowedExtensions)) {
  5743. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5744. }
  5745. // // 如果 url 有变更,记录版本
  5746. // if ($url !== $role->url) {
  5747. // $needVersionRecord = true;
  5748. // }
  5749. $updateData['url'] = $url;
  5750. }
  5751. // 提示词
  5752. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5753. if ($pic_prompt) {
  5754. // // 如果 pic_prompt 有变更,记录版本
  5755. // if ($pic_prompt !== $role->pic_prompt) {
  5756. // $needVersionRecord = true;
  5757. // }
  5758. $updateData['pic_prompt'] = $pic_prompt;
  5759. }
  5760. if (empty($updateData)) {
  5761. Utils::throwError('20003:没有需要更新的数据');
  5762. }
  5763. // // 如果需要记录版本,将数据添加到 versions 数组
  5764. // if ($needVersionRecord) {
  5765. // // 获取现有的 versions 数据
  5766. // $versions = json_decode($role->versions, true) ?: [];
  5767. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5768. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5769. // if ($isFirstVersion) {
  5770. // $oldVersion = [
  5771. // 'url' => $role->url,
  5772. // 'description' => $role->pic_prompt,
  5773. // ];
  5774. // // 旧版本添加到数组末尾
  5775. // $versions[] = $oldVersion;
  5776. // }
  5777. // // 构建新版本(变更后)
  5778. // $newVersion = [
  5779. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5780. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5781. // ];
  5782. // // 检查新版本是否已存在于历史版本中
  5783. // $existingIndex = -1;
  5784. // foreach ($versions as $index => $version) {
  5785. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5786. // $existingIndex = $index;
  5787. // break;
  5788. // }
  5789. // }
  5790. // if ($existingIndex !== -1) {
  5791. // // 如果已存在,移除旧的位置
  5792. // array_splice($versions, $existingIndex, 1);
  5793. // }
  5794. // // 新版本添加到数组开头(最新的在前)
  5795. // array_unshift($versions, $newVersion);
  5796. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5797. // // if (count($versions) > 10) {
  5798. // // $versions = array_slice($versions, 0, 10);
  5799. // // }
  5800. // $updateData['versions'] = json_encode($versions, 256);
  5801. // }
  5802. if ($versions) {
  5803. $updateData['versions'] = json_encode($versions, 256);
  5804. }
  5805. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5806. return DB::table('mp_products')
  5807. ->where('cpid', $cpid)
  5808. ->where('id', $id)->update($updateData);
  5809. }
  5810. /**
  5811. * 获取角色版本历史
  5812. * @param array $data 包含 id(角色ID)
  5813. * @return array 返回版本历史列表
  5814. */
  5815. public function getProductVersions($data) {
  5816. $cpid = Site::getCpid();
  5817. $id = getProp($data, 'id');
  5818. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5819. $role = DB::table('mp_products')
  5820. ->where('id', $id)
  5821. ->where('cpid', $cpid)
  5822. ->where('type', 1)
  5823. ->first();
  5824. if (!$role) Utils::throwError('20003:角色不存在');
  5825. // 获取版本历史
  5826. $versions = json_decode($role->versions, true) ?: [];
  5827. // 添加当前版本作为最新版本
  5828. $currentVersion = [
  5829. 'version' => 0, // 0 表示当前版本
  5830. 'url' => $role->url,
  5831. 'pic_prompt' => $role->pic_prompt,
  5832. 'updated_at' => $role->updated_at,
  5833. 'is_current' => true
  5834. ];
  5835. array_unshift($versions, $currentVersion);
  5836. return $versions;
  5837. }
  5838. /**
  5839. * 恢复到指定版本
  5840. * @param array $data 包含 id(角色ID)、version(版本号)
  5841. * @return bool
  5842. */
  5843. public function restoreProductVersion($data) {
  5844. $uid = Site::getUid();
  5845. $cpid = Site::getCpid();
  5846. $id = getProp($data, 'id');
  5847. $version = getProp($data, 'version');
  5848. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5849. if (!$version) Utils::throwError('20003:版本号不能为空');
  5850. $role = DB::table('mp_products')
  5851. ->where('id', $id)
  5852. ->where('cpid', $cpid)
  5853. ->where('type', 1)
  5854. ->first();
  5855. if (!$role) Utils::throwError('20003:角色不存在');
  5856. // 获取版本历史
  5857. $versions = json_decode($role->versions, true) ?: [];
  5858. // 查找指定版本
  5859. $targetVersion = null;
  5860. foreach ($versions as $v) {
  5861. if ($v['version'] == $version) {
  5862. $targetVersion = $v;
  5863. break;
  5864. }
  5865. }
  5866. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5867. // 先将当前版本保存到历史
  5868. $newVersion = [
  5869. 'version' => count($versions) + 1,
  5870. 'url' => $role->url,
  5871. 'pic_prompt' => $role->pic_prompt,
  5872. 'updated_at' => date('Y-m-d H:i:s'),
  5873. 'updated_by' => $uid
  5874. ];
  5875. array_unshift($versions, $newVersion);
  5876. // 限制版本数量
  5877. if (count($versions) > 10) {
  5878. $versions = array_slice($versions, 0, 10);
  5879. }
  5880. // 恢复到指定版本
  5881. return DB::table('mp_products')
  5882. ->where('id', $id)
  5883. ->where('cpid', $cpid)
  5884. ->update([
  5885. 'url' => $targetVersion['url'],
  5886. 'pic_prompt' => $targetVersion['pic_prompt'],
  5887. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5888. 'updated_at' => date('Y-m-d H:i:s')
  5889. ]);
  5890. }
  5891. public function deleteProduct($data) {
  5892. $uid = Site::getUid();
  5893. $cpid = Site::getCpid();
  5894. $role = Site::getRole();
  5895. $id = getProp($data, 'id');
  5896. if (!$id) Utils::throwError('20003:ID不能为空');
  5897. $ids = explode(',', $id);
  5898. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5899. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5900. $query_uid = $is_public ? 0 : $uid;
  5901. // 如果是公共库操作,需要admin权限
  5902. if ($is_public && $role !== 'admin') {
  5903. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5904. }
  5905. // 检查是否存在且属于当前用户或公共库
  5906. $role = DB::table('mp_products')
  5907. ->whereIn('id', $ids)
  5908. ->where('cpid', $cpid)
  5909. ->where('user_id', $query_uid)
  5910. ->get();
  5911. if (!$role) Utils::throwError('20003:记录不存在');
  5912. return DB::table('mp_products')
  5913. ->where('cpid', $cpid)
  5914. ->where('user_id', $query_uid)
  5915. ->whereIn('id', $ids)
  5916. ->update([
  5917. 'is_deleted' => 1,
  5918. 'updated_at' => date('Y-m-d H:i:s')
  5919. ]);
  5920. }
  5921. public function generateThreeView($data) {
  5922. $uid = Site::getUid();
  5923. $cpid = Site::getCpid();
  5924. $role = Site::getRole();
  5925. $id = getProp($data, 'id');
  5926. if (!$id) Utils::throwError('20003:ID不能为空');
  5927. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5928. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5929. $query_uid = $is_public ? 0 : $uid;
  5930. // 如果是公共库操作,需要admin权限
  5931. if ($is_public && $role !== 'admin') {
  5932. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5933. }
  5934. // 检查是否存在且属于当前用户或公共库
  5935. $product = DB::table('mp_products')
  5936. ->where('id', $id)
  5937. ->where('cpid', $cpid)
  5938. ->where('user_id', $query_uid)
  5939. ->where('type', 1)->first();
  5940. if (!$product) Utils::throwError('20003:资产不存在');
  5941. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5942. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5943. if (!$ref_img_url) {
  5944. // 如果没有传入参考图,使用角色表中的图片
  5945. $ref_img_url = $product->url ?? '';
  5946. if (!$ref_img_url) {
  5947. Utils::throwError('20003:参考图不能为空');
  5948. }
  5949. }
  5950. $pic_prompt = getProp($product, 'pic_prompt');
  5951. if ($pic_prompt) {
  5952. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  5953. }
  5954. // 检查参考图是否是正确的图片格式
  5955. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5956. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5957. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5958. if (!in_array($extension, $allowedExtensions)) {
  5959. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5960. }
  5961. // 处理图片模型
  5962. $model = getProp($data, 'model');
  5963. if (!$model) {
  5964. // 使用默认模型
  5965. $model = 'doubao-seedream-5-0-lite-260128';
  5966. }
  5967. // 验证模型是否在可用模型表中
  5968. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5969. Utils::throwError('20003:该模型已不可用,请更换!');
  5970. }
  5971. $ratio = getProp($data, 'ratio', '16:9');
  5972. $resolution = getProp($data, 'resolution', '2k');
  5973. // 定义分辨率和宽高比对应的尺寸映射表
  5974. $sizeMap = [
  5975. '2k' => [
  5976. '1:1' => ['width' => 2048, 'height' => 2048],
  5977. '4:3' => ['width' => 2304, 'height' => 1728],
  5978. '3:4' => ['width' => 1728, 'height' => 2304],
  5979. '16:9' => ['width' => 2848, 'height' => 1600],
  5980. '9:16' => ['width' => 1600, 'height' => 2848],
  5981. '3:2' => ['width' => 2496, 'height' => 1664],
  5982. '2:3' => ['width' => 1664, 'height' => 2496],
  5983. '21:9' => ['width' => 3136, 'height' => 1344],
  5984. ],
  5985. '3k' => [
  5986. '1:1' => ['width' => 3072, 'height' => 3072],
  5987. '4:3' => ['width' => 3456, 'height' => 2592],
  5988. '3:4' => ['width' => 2592, 'height' => 3456],
  5989. '16:9' => ['width' => 4096, 'height' => 2304],
  5990. '9:16' => ['width' => 2304, 'height' => 4096],
  5991. '2:3' => ['width' => 2496, 'height' => 3744],
  5992. '3:2' => ['width' => 3744, 'height' => 2496],
  5993. '21:9' => ['width' => 4704, 'height' => 2016],
  5994. ],
  5995. '4k' => [
  5996. '1:1' => ['width' => 4096, 'height' => 4096],
  5997. '3:4' => ['width' => 3520, 'height' => 4704],
  5998. '4:3' => ['width' => 4704, 'height' => 3520],
  5999. '16:9' => ['width' => 5504, 'height' => 3040],
  6000. '9:16' => ['width' => 3040, 'height' => 5504],
  6001. '2:3' => ['width' => 3328, 'height' => 4992],
  6002. '3:2' => ['width' => 4992, 'height' => 3328],
  6003. '21:9' => ['width' => 6240, 'height' => 2656],
  6004. ],
  6005. ];
  6006. // 参数验证
  6007. $resolution = strtolower($resolution);
  6008. if (!isset($sizeMap[$resolution])) {
  6009. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6010. }
  6011. if (!isset($sizeMap[$resolution][$ratio])) {
  6012. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6013. }
  6014. // 根据 ratio 和 resolution 确定宽高
  6015. $width = $sizeMap[$resolution][$ratio]['width'];
  6016. $height = $sizeMap[$resolution][$ratio]['height'];
  6017. try {
  6018. // 创建图片生成任务
  6019. $params = [
  6020. 'prompt' => $prompt,
  6021. 'model' => $model,
  6022. 'ref_img_urls' => [$ref_img_url],
  6023. 'width' => $width,
  6024. 'height' => $height
  6025. ];
  6026. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6027. $task_id = $task->id;
  6028. if (!$task_id) {
  6029. Utils::throwError('20003:创建图片生成任务失败');
  6030. }
  6031. // 轮询获取结果
  6032. // 只查询数据库,不调用API,不更新任务表
  6033. $start_time = time();
  6034. $timeout = 1800;
  6035. $img_url = '';
  6036. while (time() - $start_time < $timeout) {
  6037. sleep(5);
  6038. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6039. $task = DB::table('mp_generate_pic_tasks')
  6040. ->where('id', $task_id)
  6041. ->first();
  6042. if (!$task) {
  6043. Utils::throwError('20003:任务不存在');
  6044. }
  6045. if ($task->status === 'success' && $task->result_url) {
  6046. $result_urls = is_string($task->result_url)
  6047. ? json_decode($task->result_url, true)
  6048. : $task->result_url;
  6049. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6050. break;
  6051. } elseif ($task->status === 'failed') {
  6052. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6053. }
  6054. // 其他状态继续轮询
  6055. }
  6056. if (empty($img_url)) {
  6057. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6058. }
  6059. // 更新 mp_products 表(不是任务表)
  6060. DB::table('mp_products')
  6061. ->where('id', $id)
  6062. ->where('cpid', $cpid)
  6063. ->update([
  6064. 'three_view_image_url' => $img_url,
  6065. 'updated_at' => date('Y-m-d H:i:s')
  6066. ]);
  6067. return ['three_view_image_url' => $img_url];
  6068. } catch (\Exception $e) {
  6069. dLog('anime')->error('生成三视图失败', [
  6070. 'error' => $e->getMessage()
  6071. ]);
  6072. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6073. Utils::throwError('20003:' . $e->getMessage());
  6074. }
  6075. }
  6076. /**
  6077. * 推送(复制)资产或文件夹到目标位置
  6078. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6079. * @return array 返回推送结果
  6080. */
  6081. public function pushProductOrFolder($data) {
  6082. $uid = Site::getUid();
  6083. $cpid = Site::getCpid();
  6084. $role = Site::getRole();
  6085. $product_id = getProp($data, 'product_id');
  6086. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6087. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6088. if (!$product_id) {
  6089. Utils::throwError('20003:请选择要推送的项目');
  6090. }
  6091. // 查询源项目(只通过cpid查询,不限制user_id)
  6092. $sourceItem = DB::table('mp_products')
  6093. ->where('id', $product_id)
  6094. ->where('cpid', $cpid)
  6095. ->where('is_deleted', 0)
  6096. ->first();
  6097. if (!$sourceItem) {
  6098. Utils::throwError('20003:要推送的项目不存在');
  6099. }
  6100. // 通过user_id判断源是公共库还是个人库
  6101. $source_uid = $sourceItem->user_id;
  6102. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6103. // 验证目标文件夹并确定目标是公共库还是个人库
  6104. $target_level = 0;
  6105. $target_uid = $uid; // 默认推送到个人库
  6106. $target_is_public = 0;
  6107. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6108. if ($target_parent_id > 0) {
  6109. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6110. $targetParent = DB::table('mp_products')
  6111. ->where('id', $target_parent_id)
  6112. ->where('cpid', $cpid)
  6113. ->where('type', 2)
  6114. ->where('is_deleted', 0)
  6115. ->first();
  6116. if (!$targetParent) {
  6117. Utils::throwError('20003:目标文件夹不存在');
  6118. }
  6119. // 通过user_id判断目标是公共库还是个人库
  6120. $target_level = $targetParent->level;
  6121. $target_uid = $targetParent->user_id;
  6122. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6123. // 使用目标文件夹的 product 类型
  6124. $final_product_type = $targetParent->product;
  6125. }
  6126. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6127. else {
  6128. $push_to_public = getProp($data, 'push_to_public');
  6129. if ($push_to_public === '') {
  6130. Utils::throwError('20003:请选择是否推送到公共库');
  6131. }
  6132. if ($push_to_public) {
  6133. $target_uid = 0;
  6134. $target_is_public = 1;
  6135. }
  6136. // 推送到根目录时,必须指定 product 类型
  6137. if ($target_product === null || $target_product === '') {
  6138. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6139. }
  6140. $final_product_type = $target_product;
  6141. }
  6142. // 如果目标是公共库,需要admin权限
  6143. if ($target_is_public && $role !== 'admin') {
  6144. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6145. }
  6146. // 权限验证:验证是否符合允许的推送规则
  6147. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6148. try {
  6149. DB::beginTransaction();
  6150. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6151. if ($sourceItem->type == 1) {
  6152. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6153. DB::commit();
  6154. return [
  6155. 'product_id' => $newId,
  6156. ];
  6157. }
  6158. // 如果是文件夹,递归复制(支持跨类型推送)
  6159. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6160. DB::commit();
  6161. return [
  6162. 'product_id' => $newFolderId,
  6163. ];
  6164. } catch (\Exception $e) {
  6165. DB::rollBack();
  6166. dLog('anime')->error('推送失败', [
  6167. 'error' => $e->getMessage(),
  6168. 'product_id' => $product_id
  6169. ]);
  6170. Utils::throwError('20003:' . $e->getMessage());
  6171. }
  6172. }
  6173. /**
  6174. * 验证推送权限
  6175. * 允许的推送规则:
  6176. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6177. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6178. * 3. 公共库推送给公共库(公共库 → 公共库)
  6179. *
  6180. * @param int $source_uid 源的user_id
  6181. * @param int $target_uid 目标的user_id
  6182. * @param int $current_uid 当前用户ID
  6183. * @throws \Exception
  6184. */
  6185. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6186. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6187. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6188. return; // 允许
  6189. }
  6190. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6191. if ($source_uid == 0 && $target_uid == $current_uid) {
  6192. return; // 允许
  6193. }
  6194. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6195. if ($source_uid == 0 && $target_uid == 0) {
  6196. return; // 允许
  6197. }
  6198. // 其他情况都不允许
  6199. if ($source_uid != 0 && $source_uid != $current_uid) {
  6200. // 源是别人的个人库
  6201. Utils::throwError('20003:无权限访问该资产');
  6202. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6203. // 个人库推送给公共库(不允许)
  6204. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6205. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6206. // 不同用户的个人库之间推送(不允许)
  6207. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6208. } else {
  6209. // 其他未知情况
  6210. Utils::throwError('20003:不允许的推送操作');
  6211. }
  6212. }
  6213. /**
  6214. * 复制单个资产
  6215. * @param object $sourceProduct 源资产对象
  6216. * @param int $targetParentId 目标父文件夹ID
  6217. * @param int $targetLevel 目标层级
  6218. * @param int $cpid 公司ID
  6219. * @param int $targetUid 目标用户ID
  6220. * @return int 返回新资产ID
  6221. */
  6222. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6223. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6224. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6225. $newProductData = [
  6226. 'user_id' => $targetUid,
  6227. 'cpid' => $cpid,
  6228. 'type' => 1,
  6229. 'parent_id' => $targetParentId,
  6230. 'level' => $targetLevel,
  6231. 'product_name' => $sourceProduct->product_name,
  6232. 'url' => $sourceProduct->url,
  6233. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6234. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6235. 'product' => $finalProductType,
  6236. 'versions' => $sourceProduct->versions ?? '',
  6237. 'sort_order' => time(),
  6238. 'is_deleted' => 0,
  6239. 'created_at' => date('Y-m-d H:i:s'),
  6240. 'updated_at' => date('Y-m-d H:i:s')
  6241. ];
  6242. return DB::table('mp_products')->insertGetId($newProductData);
  6243. }
  6244. /**
  6245. * 递归复制文件夹及其子项
  6246. * @param object $sourceFolder 源文件夹对象
  6247. * @param int $targetParentId 目标父文件夹ID
  6248. * @param int $targetLevel 目标层级
  6249. * @param int $cpid 公司ID
  6250. * @param int $targetUid 目标用户ID
  6251. * @param int $sourceUid 源用户ID
  6252. * @return int 返回新文件夹ID
  6253. */
  6254. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6255. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6256. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6257. // 创建新文件夹
  6258. $newFolderData = [
  6259. 'user_id' => $targetUid,
  6260. 'cpid' => $cpid,
  6261. 'type' => 2,
  6262. 'parent_id' => $targetParentId,
  6263. 'level' => $targetLevel,
  6264. 'product_name' => $sourceFolder->product_name,
  6265. 'product' => $finalProductType,
  6266. 'sort_order' => time(),
  6267. 'is_deleted' => 0,
  6268. 'created_at' => date('Y-m-d H:i:s'),
  6269. 'updated_at' => date('Y-m-d H:i:s')
  6270. ];
  6271. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6272. // 获取源文件夹下的所有子项
  6273. $children = DB::table('mp_products')
  6274. ->where('parent_id', $sourceFolder->id)
  6275. ->where('cpid', $cpid)
  6276. ->where('user_id', $sourceUid)
  6277. ->where('is_deleted', 0)
  6278. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6279. ->get();
  6280. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6281. foreach ($children as $child) {
  6282. if ($child->type == 1) {
  6283. // 资产
  6284. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6285. } else {
  6286. // 文件夹
  6287. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6288. }
  6289. }
  6290. return $newFolderId;
  6291. }
  6292. /**
  6293. * 保存剧本资产关联关系
  6294. * @param array $data 请求参数
  6295. * @return bool
  6296. */
  6297. public function saveScriptProducts($data) {
  6298. $uid = Site::getUid();
  6299. $cpid = Site::getCpid();
  6300. $script_id = getProp($data, 'script_id');
  6301. $products = getProp($data, 'products', []);
  6302. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6303. if (!$script_id) {
  6304. Utils::throwError('20003:请提供剧本ID');
  6305. }
  6306. // 验证剧本是否存在
  6307. $script = DB::table('mp_scripts')
  6308. ->where('id', $script_id)
  6309. ->where('is_deleted', 0)
  6310. ->first();
  6311. if (!$script) {
  6312. Utils::throwError('20003:剧本不存在');
  6313. }
  6314. // 处理图片模型
  6315. $model = getProp($data, 'model');
  6316. if (!$model) {
  6317. // 使用默认模型
  6318. $model = 'doubao-seedream-5-0-lite-260128';
  6319. }
  6320. // 验证模型是否在可用模型表中
  6321. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6322. Utils::throwError('20003:该模型已不可用,请更换!');
  6323. }
  6324. $ratio = getProp($data, 'ratio', '9:16');
  6325. $resolution = getProp($data, 'resolution', '2k');
  6326. // 定义分辨率和宽高比对应的尺寸映射表
  6327. $sizeMap = [
  6328. '2k' => [
  6329. '1:1' => ['width' => 2048, 'height' => 2048],
  6330. '4:3' => ['width' => 2304, 'height' => 1728],
  6331. '3:4' => ['width' => 1728, 'height' => 2304],
  6332. '16:9' => ['width' => 2848, 'height' => 1600],
  6333. '9:16' => ['width' => 1600, 'height' => 2848],
  6334. '3:2' => ['width' => 2496, 'height' => 1664],
  6335. '2:3' => ['width' => 1664, 'height' => 2496],
  6336. '21:9' => ['width' => 3136, 'height' => 1344],
  6337. ],
  6338. '3k' => [
  6339. '1:1' => ['width' => 3072, 'height' => 3072],
  6340. '4:3' => ['width' => 3456, 'height' => 2592],
  6341. '3:4' => ['width' => 2592, 'height' => 3456],
  6342. '16:9' => ['width' => 4096, 'height' => 2304],
  6343. '9:16' => ['width' => 2304, 'height' => 4096],
  6344. '2:3' => ['width' => 2496, 'height' => 3744],
  6345. '3:2' => ['width' => 3744, 'height' => 2496],
  6346. '21:9' => ['width' => 4704, 'height' => 2016],
  6347. ],
  6348. '4k' => [
  6349. '1:1' => ['width' => 4096, 'height' => 4096],
  6350. '3:4' => ['width' => 3520, 'height' => 4704],
  6351. '4:3' => ['width' => 4704, 'height' => 3520],
  6352. '16:9' => ['width' => 5504, 'height' => 3040],
  6353. '9:16' => ['width' => 3040, 'height' => 5504],
  6354. '2:3' => ['width' => 3328, 'height' => 4992],
  6355. '3:2' => ['width' => 4992, 'height' => 3328],
  6356. '21:9' => ['width' => 6240, 'height' => 2656],
  6357. ],
  6358. ];
  6359. // 参数验证
  6360. $resolution = strtolower($resolution);
  6361. if (!isset($sizeMap[$resolution])) {
  6362. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6363. }
  6364. if (!isset($sizeMap[$resolution][$ratio])) {
  6365. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6366. }
  6367. // 根据 ratio 和 resolution 确定宽高
  6368. $width = $sizeMap[$resolution][$ratio]['width'];
  6369. $height = $sizeMap[$resolution][$ratio]['height'];
  6370. $script_name = $script->script_name ?? 'script_' . $script_id;
  6371. // 检查是否已经有该剧本的资产数据
  6372. $existingMappings = DB::table('mp_script_product_mappings')
  6373. ->where('script_id', $script_id)
  6374. ->get();
  6375. if ($existingMappings->isNotEmpty()) {
  6376. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6377. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6378. // 查询这些资产的图片生成任务状态
  6379. $productsWithTasks = DB::table('mp_products')
  6380. ->whereIn('id', $productIds)
  6381. ->where('is_deleted', 0)
  6382. ->get();
  6383. $productTaskMap = [];
  6384. $typeFolderIds = [];
  6385. $hasAllTasks = true;
  6386. foreach ($productsWithTasks as $product) {
  6387. // 收集类型文件夹ID
  6388. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6389. $parentFolder = DB::table('mp_products')
  6390. ->where('id', $product->parent_id)
  6391. ->where('type', 2)
  6392. ->first();
  6393. if ($parentFolder) {
  6394. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6395. }
  6396. }
  6397. // 检查是否有图片生成任务
  6398. if (!empty($product->pic_task_id)) {
  6399. $productTaskMap[$product->id] = $product->pic_task_id;
  6400. } else if($product->url && $product->pic_task_status == '生成成功') {
  6401. continue;
  6402. } else {
  6403. // 有资产没有图片任务
  6404. $hasAllTasks = false;
  6405. }
  6406. }
  6407. // 如果所有资产都有任务ID,直接轮询返回结果
  6408. if ($hasAllTasks && !empty($productTaskMap)) {
  6409. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6410. 'script_id' => $script_id,
  6411. 'script_name' => $script_name,
  6412. 'product_count' => count($productTaskMap)
  6413. ]);
  6414. // 直接返回 SSE 流轮询结果
  6415. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6416. }
  6417. // 如果部分资产没有任务ID,只为这些资产创建任务
  6418. if (!$hasAllTasks && $auto_generate_images) {
  6419. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6420. 'script_id' => $script_id,
  6421. 'script_name' => $script_name
  6422. ]);
  6423. // 开启事务
  6424. DB::beginTransaction();
  6425. try {
  6426. foreach ($productsWithTasks as $product) {
  6427. // 跳过已有任务的资产
  6428. if (!empty($product->pic_task_id)) {
  6429. continue;
  6430. }
  6431. // 跳过没有提示词的资产
  6432. if (empty($product->pic_prompt)) {
  6433. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6434. 'product_id' => $product->id,
  6435. 'product_name' => $product->product_name
  6436. ]);
  6437. continue;
  6438. }
  6439. try {
  6440. // 创建图片生成任务
  6441. $params = [
  6442. 'prompt' => $product->pic_prompt,
  6443. 'model' => $model,
  6444. 'ref_img_urls' => [],
  6445. 'width' => $width,
  6446. 'height' => $height
  6447. ];
  6448. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6449. $task_id = $task->id;
  6450. if ($task_id) {
  6451. $productTaskMap[$product->id] = $task_id;
  6452. // 在事务中更新资产表的任务ID和状态
  6453. DB::table('mp_products')
  6454. ->where('id', $product->id)
  6455. ->update([
  6456. 'pic_task_id' => $task_id,
  6457. 'pic_task_status' => '生成中',
  6458. 'updated_at' => now()
  6459. ]);
  6460. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6461. 'product_id' => $product->id,
  6462. 'task_id' => $task_id
  6463. ]);
  6464. }
  6465. } catch (\Exception $e) {
  6466. dLog('anime')->error('创建资产图片生成任务失败', [
  6467. 'product_id' => $product->id,
  6468. 'error' => $e->getMessage()
  6469. ]);
  6470. // 标记为失败(仍在事务中)
  6471. DB::table('mp_products')
  6472. ->where('id', $product->id)
  6473. ->update([
  6474. 'pic_task_status' => '生成失败',
  6475. 'updated_at' => now()
  6476. ]);
  6477. }
  6478. }
  6479. // 提交事务
  6480. DB::commit();
  6481. // 如果有新创建的任务,返回 SSE 流
  6482. if (!empty($productTaskMap)) {
  6483. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6484. }
  6485. } catch (\Exception $e) {
  6486. // 回滚事务
  6487. DB::rollback();
  6488. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6489. 'script_id' => $script_id,
  6490. 'error' => $e->getMessage()
  6491. ]);
  6492. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6493. }
  6494. }
  6495. // 如果不需要生成图片,返回已存在的信息
  6496. return [
  6497. 'success' => true,
  6498. 'message' => '剧本资产已存在',
  6499. 'script_id' => $script_id,
  6500. 'script_name' => $script_name,
  6501. 'type_folder_ids' => $typeFolderIds,
  6502. 'existing_products' => count($productIds),
  6503. 'tasks_count' => count($productTaskMap)
  6504. ];
  6505. }
  6506. // 解析 products(可能是 JSON 字符串或数组)
  6507. if (is_string($products)) {
  6508. $products = json_decode($products, true);
  6509. if (json_last_error() !== JSON_ERROR_NONE) {
  6510. Utils::throwError('20003:产品数据格式错误');
  6511. }
  6512. }
  6513. if (!is_array($products) || empty($products)) {
  6514. Utils::throwError('20003:产品数据不能为空');
  6515. }
  6516. // 以下是原有的创建逻辑...
  6517. // 开启事务
  6518. DB::beginTransaction();
  6519. try {
  6520. $now = now();
  6521. $mappingRecords = [];
  6522. $createdProductIds = []; // 记录所有创建的资产ID
  6523. // 获取剧本名称
  6524. $script_name = $script->script_name ?? 'script_' . $script_id;
  6525. // 存储每个类型的根文件夹ID
  6526. $typeFolderIds = [];
  6527. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6528. foreach ($products as $productGroup) {
  6529. $type = getProp($productGroup, 'type');
  6530. $title = getProp($productGroup, 'title', '');
  6531. $content = getProp($productGroup, 'content', []);
  6532. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6533. continue;
  6534. }
  6535. // 为当前类型创建根文件夹(如果还未创建)
  6536. if (!isset($typeFolderIds[$type])) {
  6537. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6538. 'user_id' => $uid,
  6539. 'cpid' => $cpid,
  6540. 'type' => 2, // 1.资产 2文件夹
  6541. 'product' => $type, // 1.主体 2.场景 3.道具
  6542. 'parent_id' => 0, // 根文件夹,parent_id=0
  6543. 'level' => 1, // 第一层级
  6544. 'product_name' => $script_name,
  6545. 'sort_order' => time() + $type,
  6546. 'is_deleted' => 0,
  6547. 'created_at' => $now,
  6548. 'updated_at' => $now
  6549. ]);
  6550. }
  6551. $folder_id = $typeFolderIds[$type];
  6552. // 获取表头(第一行)并查找关键列的位置
  6553. $headers = $content[0];
  6554. $nameColumnIndex = -1; // 资产名称列索引
  6555. $sequenceColumnIndex = -1; // 使用范围列索引
  6556. $promptColumnIndex = -1; // 参考提示词列索引
  6557. foreach ($headers as $index => $header) {
  6558. // 查找"资产名称"列
  6559. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6560. $nameColumnIndex = $index;
  6561. }
  6562. // 查找"使用范围"列
  6563. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6564. $sequenceColumnIndex = $index;
  6565. }
  6566. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6567. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6568. $promptColumnIndex = $index;
  6569. }
  6570. }
  6571. // 验证必要的列是否都找到了
  6572. if ($nameColumnIndex === -1) {
  6573. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6574. continue;
  6575. }
  6576. if ($sequenceColumnIndex === -1) {
  6577. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6578. continue;
  6579. }
  6580. // 跳过表头,解析每一行数据
  6581. for ($i = 1; $i < count($content); $i++) {
  6582. $row = $content[$i];
  6583. // 确保行数据有效
  6584. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6585. continue;
  6586. }
  6587. // 根据动态查找的列索引提取数据
  6588. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6589. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6590. $pic_prompt = '';
  6591. // 提取参考提示词(如果找到了该列)
  6592. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6593. $pic_prompt = trim($row[$promptColumnIndex]);
  6594. }
  6595. // 解析使用范围(逗号分隔的序号)
  6596. $sequences = [];
  6597. if (!empty($sequence_str)) {
  6598. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6599. foreach ($sequenceParts as $part) {
  6600. if (is_numeric($part)) {
  6601. $sequences[] = (int)$part;
  6602. }
  6603. }
  6604. }
  6605. if (empty($product_name)) {
  6606. continue;
  6607. }
  6608. // 处理product_name两边的符号
  6609. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6610. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6611. $product_id = DB::table('mp_products')->insertGetId([
  6612. 'product_name' => $product_name,
  6613. 'type' => 1, // 1=资产 2.文件夹
  6614. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6615. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6616. 'level' => 2, // 第二层级
  6617. 'pic_prompt' => $pic_prompt,
  6618. 'user_id' => $uid,
  6619. 'cpid' => $cpid,
  6620. 'sort_order' => time(),
  6621. 'is_deleted' => 0,
  6622. 'created_at' => $now,
  6623. 'updated_at' => $now,
  6624. ]);
  6625. // 记录创建的资产ID
  6626. $createdProductIds[] = $product_id;
  6627. // 为每个序号创建映射记录
  6628. if (!empty($sequences)) {
  6629. foreach ($sequences as $sequence) {
  6630. $mappingRecords[] = [
  6631. 'script_id' => $script_id,
  6632. 'product_id' => $product_id,
  6633. 'episode_number' => $sequence,
  6634. 'created_at' => $now,
  6635. 'updated_at' => $now,
  6636. ];
  6637. }
  6638. } else {
  6639. // 如果没有指定序号,创建一个默认映射(序号为0)
  6640. $mappingRecords[] = [
  6641. 'script_id' => $script_id,
  6642. 'product_id' => $product_id,
  6643. 'episode_number' => 0,
  6644. 'created_at' => $now,
  6645. 'updated_at' => $now,
  6646. ];
  6647. }
  6648. }
  6649. }
  6650. if (empty($mappingRecords)) {
  6651. Utils::throwError('20003:没有有效的产品数据');
  6652. }
  6653. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6654. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6655. // 如果需要自动生成图片,在事务中创建图片生成任务
  6656. $productTaskMap = [];
  6657. if ($auto_generate_images && !empty($createdProductIds)) {
  6658. // 查询所有创建的资产
  6659. $productsToGenerate = DB::table('mp_products')
  6660. ->whereIn('id', $createdProductIds)
  6661. ->where('is_deleted', 0)
  6662. ->get();
  6663. foreach ($productsToGenerate as $product) {
  6664. if (empty($product->pic_prompt)) {
  6665. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6666. 'product_id' => $product->id,
  6667. 'product_name' => $product->product_name
  6668. ]);
  6669. continue;
  6670. }
  6671. try {
  6672. // 创建图片生成任务
  6673. $params = [
  6674. 'prompt' => $product->pic_prompt,
  6675. 'model' => $model,
  6676. 'ref_img_urls' => [],
  6677. 'width' => $width,
  6678. 'height' => $height
  6679. ];
  6680. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6681. $task_id = $task->id;
  6682. if ($task_id) {
  6683. $productTaskMap[$product->id] = $task_id;
  6684. // 在事务中更新资产表的任务ID和状态
  6685. DB::table('mp_products')
  6686. ->where('id', $product->id)
  6687. ->update([
  6688. 'pic_task_id' => $task_id,
  6689. 'pic_task_status' => '生成中',
  6690. 'updated_at' => now()
  6691. ]);
  6692. dLog('anime')->info('创建资产图片生成任务', [
  6693. 'product_id' => $product->id,
  6694. 'task_id' => $task_id
  6695. ]);
  6696. }
  6697. } catch (\Exception $e) {
  6698. dLog('anime')->error('创建资产图片生成任务失败', [
  6699. 'product_id' => $product->id,
  6700. 'error' => $e->getMessage()
  6701. ]);
  6702. // 标记为失败(仍在事务中)
  6703. DB::table('mp_products')
  6704. ->where('id', $product->id)
  6705. ->update([
  6706. 'pic_task_status' => '生成失败',
  6707. 'updated_at' => now()
  6708. ]);
  6709. }
  6710. }
  6711. }
  6712. // 提交事务
  6713. DB::commit();
  6714. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6715. if ($auto_generate_images && !empty($productTaskMap)) {
  6716. // 返回 SSE 流(事务外轮询)
  6717. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6718. }
  6719. // 如果不需要生成图片,返回普通结果
  6720. return [
  6721. 'success' => true,
  6722. 'type_folder_ids' => $typeFolderIds,
  6723. 'inserted_count' => $insertedCount,
  6724. 'total_records' => count($mappingRecords),
  6725. 'created_products' => count($createdProductIds),
  6726. 'image_tasks_created' => count($productTaskMap)
  6727. ];
  6728. } catch (\Exception $e) {
  6729. // 回滚事务
  6730. DB::rollback();
  6731. // 记录错误日志
  6732. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6733. 'script_id' => $script_id,
  6734. 'error' => $e->getMessage(),
  6735. 'trace' => $e->getTraceAsString()
  6736. ]);
  6737. // 统一使用 Utils::throwError 抛出错误
  6738. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6739. }
  6740. }
  6741. /**
  6742. * 批量为剧本资产生成图片
  6743. *
  6744. * @param array $data 请求参数
  6745. * @return \Generator 返回 SSE 流
  6746. */
  6747. public function batchGenerateProductImages($data) {
  6748. $script_id = getProp($data, 'script_id');
  6749. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6750. if (!$script_id) {
  6751. Utils::throwError('20003:请提供剧本ID');
  6752. }
  6753. // 验证剧本是否存在
  6754. $script = DB::table('mp_scripts')
  6755. ->where('id', $script_id)
  6756. ->where('is_deleted', 0)
  6757. ->first();
  6758. if (!$script) {
  6759. Utils::throwError('20003:剧本不存在');
  6760. }
  6761. $script_name = $script->script_name ?? 'script_' . $script_id;
  6762. // 获取需要生成图片的所有资产
  6763. $products = DB::table('mp_products')
  6764. ->whereIn('parent_id', array_values($type_folder_ids))
  6765. ->where('is_deleted', 0)
  6766. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6767. ->get();
  6768. if ($products->isEmpty()) {
  6769. Utils::throwError('20003:没有找到需要生成图片的资产');
  6770. }
  6771. // 默认参数
  6772. $model = 'doubao-seedream-5-0-lite-260128';
  6773. $width = 1600;
  6774. $height = 2848;
  6775. // 开始为每个资产创建图片生成任务
  6776. $taskIds = [];
  6777. $productTaskMap = []; // 资产ID到任务ID的映射
  6778. foreach ($products as $product) {
  6779. if (empty($product->pic_prompt)) {
  6780. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6781. continue;
  6782. }
  6783. try {
  6784. // 创建图片生成任务
  6785. $params = [
  6786. 'prompt' => $product->pic_prompt,
  6787. 'model' => $model,
  6788. 'ref_img_urls' => [],
  6789. 'width' => $width,
  6790. 'height' => $height
  6791. ];
  6792. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6793. $task_id = $task->id;
  6794. if ($task_id) {
  6795. $taskIds[] = $task_id;
  6796. $productTaskMap[$product->id] = $task_id;
  6797. // 更新资产表的任务ID和状态
  6798. DB::table('mp_products')
  6799. ->where('id', $product->id)
  6800. ->update([
  6801. 'pic_task_id' => $task_id,
  6802. 'pic_task_status' => '生成中',
  6803. 'updated_at' => now()
  6804. ]);
  6805. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6806. }
  6807. } catch (\Exception $e) {
  6808. dLog('anime')->error('创建资产图片生成任务失败', [
  6809. 'product_id' => $product->id,
  6810. 'error' => $e->getMessage()
  6811. ]);
  6812. // 标记为失败
  6813. DB::table('mp_products')
  6814. ->where('id', $product->id)
  6815. ->update([
  6816. 'pic_task_status' => '生成失败',
  6817. 'updated_at' => now()
  6818. ]);
  6819. }
  6820. }
  6821. if (empty($taskIds)) {
  6822. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6823. }
  6824. // 返回 SSE 流
  6825. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6826. }
  6827. /**
  6828. * 轮询资产图片生成任务状态(SSE流式返回)
  6829. * 只通过查询数据库获取任务状态,不主动调用API
  6830. *
  6831. * @param int $script_id 剧本ID
  6832. * @param string $script_name 剧本名称
  6833. * @param array $productTaskMap 资产ID到任务ID的映射
  6834. * @param array $type_folder_ids 类型文件夹ID映射
  6835. * @return \Generator
  6836. */
  6837. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6838. $startTime = time();
  6839. $timeout = 1800; // 30分钟超时
  6840. $pollInterval = 10; // 10秒轮询一次
  6841. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6842. // 定义类型名称映射
  6843. $typeNames = [
  6844. 1 => 'roles', // 角色
  6845. 2 => 'scenes', // 场景
  6846. 3 => 'props' // 道具
  6847. ];
  6848. while (time() - $startTime < $timeout) {
  6849. sleep($pollInterval);
  6850. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6851. $mappings = DB::table('mp_script_product_mappings')
  6852. ->where('script_id', $script_id)
  6853. ->pluck('product_id')
  6854. ->unique()
  6855. ->toArray();
  6856. if (empty($mappings)) {
  6857. dLog('anime')->warning('该剧本没有关联的资产', [
  6858. 'script_id' => $script_id,
  6859. 'script_name' => $script_name
  6860. ]);
  6861. break;
  6862. }
  6863. // 查询所有资产的当前状态
  6864. $products = DB::table('mp_products')
  6865. ->whereIn('id', $mappings)
  6866. ->where('is_deleted', 0)
  6867. ->get();
  6868. // 统计各类型的状态(使用类型名称作为键名)
  6869. $stats = [
  6870. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6871. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6872. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6873. ];
  6874. $allCompleted = true;
  6875. $hasStatusChange = false;
  6876. foreach ($products as $product) {
  6877. $type = $product->product;
  6878. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6879. // 如果类型名称不在 stats 中,初始化
  6880. if (!isset($stats[$typeName])) {
  6881. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6882. }
  6883. $stats[$typeName]['total']++;
  6884. $task_id = $product->pic_task_id;
  6885. $currentStatus = $product->pic_task_status;
  6886. // 检查状态是否有变化
  6887. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6888. $hasStatusChange = true;
  6889. $lastStatus[$product->id] = $currentStatus;
  6890. }
  6891. // 如果是生成中,查询任务表状态
  6892. if ($currentStatus === '生成中' && $task_id) {
  6893. // 只查询数据库,不调用API
  6894. $task = DB::table('mp_generate_pic_tasks')
  6895. ->where('id', $task_id)
  6896. ->first();
  6897. if ($task) {
  6898. // 检查任务状态
  6899. if ($task->status === 'success' && $task->result_url) {
  6900. // 解析图片URL
  6901. $result_urls = $task->result_url;
  6902. if (is_string($result_urls)) {
  6903. $result_urls = json_decode($result_urls, true);
  6904. }
  6905. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6906. // 更新资产表状态
  6907. DB::table('mp_products')
  6908. ->where('id', $product->id)
  6909. ->update([
  6910. 'pic_task_status' => '生成成功',
  6911. 'url' => $img_url,
  6912. 'updated_at' => now()
  6913. ]);
  6914. $stats[$typeName]['success']++;
  6915. $stats[$typeName]['completed']++;
  6916. $hasStatusChange = true;
  6917. dLog('anime')->info('资产图片生成成功', [
  6918. 'product_id' => $product->id,
  6919. 'task_id' => $task_id,
  6920. 'img_url' => $img_url
  6921. ]);
  6922. } elseif ($task->status === 'failed') {
  6923. // 更新资产表状态
  6924. DB::table('mp_products')
  6925. ->where('id', $product->id)
  6926. ->update([
  6927. 'pic_task_status' => '生成失败',
  6928. 'updated_at' => now()
  6929. ]);
  6930. $stats[$typeName]['completed']++;
  6931. $hasStatusChange = true;
  6932. dLog('anime')->warning('资产图片生成失败', [
  6933. 'product_id' => $product->id,
  6934. 'task_id' => $task_id,
  6935. 'error' => $task->error_message ?? '未知错误'
  6936. ]);
  6937. } else {
  6938. // 任务还在处理中
  6939. $allCompleted = false;
  6940. }
  6941. } else {
  6942. // 任务不存在,标记为失败
  6943. DB::table('mp_products')
  6944. ->where('id', $product->id)
  6945. ->update([
  6946. 'pic_task_status' => '生成失败',
  6947. 'updated_at' => now()
  6948. ]);
  6949. $stats[$type]['completed']++;
  6950. $hasStatusChange = true;
  6951. dLog('anime')->error('图片生成任务不存在', [
  6952. 'product_id' => $product->id,
  6953. 'task_id' => $task_id
  6954. ]);
  6955. }
  6956. } elseif ($currentStatus === '生成成功') {
  6957. $stats[$typeName]['success']++;
  6958. $stats[$typeName]['completed']++;
  6959. } elseif ($currentStatus === '生成失败') {
  6960. $stats[$typeName]['completed']++;
  6961. } else {
  6962. // 其他状态也认为未完成
  6963. $allCompleted = false;
  6964. }
  6965. }
  6966. // 移除没有数据的类型(total=0)
  6967. foreach ($stats as $typeName => $stat) {
  6968. if ($stat['total'] === 0) {
  6969. unset($stats[$typeName]);
  6970. }
  6971. }
  6972. // 如果有状态变化,发送 SSE 更新
  6973. if ($hasStatusChange) {
  6974. $eventType = $allCompleted ? 'complete' : 'update';
  6975. $response = [
  6976. 'type' => $eventType,
  6977. 'script_id' => $script_id,
  6978. 'script_name' => $script_name,
  6979. 'stats' => $stats,
  6980. 'timestamp' => date('Y-m-d H:i:s')
  6981. ];
  6982. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6983. dLog('anime')->info('SSE更新', [
  6984. 'event_type' => $eventType,
  6985. 'script_id' => $script_id,
  6986. 'script_name' => $script_name,
  6987. 'stats' => $stats
  6988. ]);
  6989. if ($allCompleted) {
  6990. dLog('anime')->info('所有资产图片生成任务已完成', [
  6991. 'script_id' => $script_id,
  6992. 'script_name' => $script_name,
  6993. 'stats' => $stats
  6994. ]);
  6995. break;
  6996. }
  6997. }
  6998. }
  6999. // 超时处理
  7000. if (time() - $startTime >= $timeout && !$allCompleted) {
  7001. $response = [
  7002. 'type' => 'timeout',
  7003. 'message' => '部分任务超时,请稍后查看结果',
  7004. 'script_id' => $script_id,
  7005. 'script_name' => $script_name,
  7006. 'timestamp' => date('Y-m-d H:i:s')
  7007. ];
  7008. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7009. dLog('anime')->warning('资产图片生成任务超时', [
  7010. 'script_id' => $script_id,
  7011. 'script_name' => $script_name,
  7012. 'timeout' => $timeout
  7013. ]);
  7014. }
  7015. }
  7016. /**
  7017. * 获取剧本关联的资产列表
  7018. * @param array $data 请求参数
  7019. * @return array
  7020. */
  7021. public function getScriptProducts($data) {
  7022. $uid = Site::getUid();
  7023. $cpid = Site::getCpid();
  7024. $script_id = getProp($data, 'script_id');
  7025. $episode_number = getProp($data, 'episode_number');
  7026. if (!$script_id) {
  7027. Utils::throwError('20003:请提供剧本ID');
  7028. }
  7029. // 验证剧本是否存在
  7030. $script = DB::table('mp_scripts')
  7031. ->where('id', $script_id)
  7032. ->where('is_deleted', 0)
  7033. ->first();
  7034. if (!$script) {
  7035. Utils::throwError('20003:剧本不存在');
  7036. }
  7037. // 联表查询资产信息
  7038. $query = DB::table('mp_script_product_mappings as mapping')
  7039. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7040. ->where('mapping.script_id', $script_id)
  7041. ->where('product.cpid', $cpid)
  7042. ->where('product.is_deleted', 0);
  7043. // 如果提供了 episode_number,则过滤指定集数
  7044. if ($episode_number !== null && $episode_number !== '') {
  7045. $query->where('mapping.episode_number', $episode_number);
  7046. }
  7047. $mappings = $query->select(
  7048. 'mapping.script_id',
  7049. 'mapping.product_id',
  7050. 'mapping.episode_number',
  7051. 'product.product_name',
  7052. 'product.type',
  7053. 'product.product',
  7054. 'product.pic_prompt',
  7055. 'product.url',
  7056. 'product.pic_task_id',
  7057. 'product.pic_task_status',
  7058. 'product.three_view_image_url',
  7059. 'mapping.created_at'
  7060. )
  7061. ->orderBy('mapping.product_id', 'asc')
  7062. ->orderBy('mapping.episode_number', 'asc')
  7063. ->get();
  7064. // 按 product_id 分组,合并 episode_number
  7065. $productMap = [];
  7066. foreach ($mappings as $item) {
  7067. $product_id = $item->product_id;
  7068. if (!isset($productMap[$product_id])) {
  7069. $productMap[$product_id] = [
  7070. 'product_id' => $product_id,
  7071. 'product_name' => $item->product_name,
  7072. 'type' => (int)$item->type,
  7073. 'product' => (int)$item->product,
  7074. 'pic_prompt' => $item->pic_prompt,
  7075. 'url' => $item->url,
  7076. 'pic_task_id' => $item->pic_task_id,
  7077. 'pic_task_status' => $item->pic_task_status,
  7078. 'episode_numbers' => [],
  7079. 'created_at' => $item->created_at,
  7080. ];
  7081. }
  7082. // 添加 episode_number(去重)
  7083. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7084. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7085. }
  7086. }
  7087. // 按类型分组
  7088. $roles = []; // type=1 角色/主体
  7089. $scenes = []; // type=2 场景
  7090. $props = []; // type=3 道具
  7091. foreach ($productMap as $product) {
  7092. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7093. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7094. // 构造返回数据
  7095. $productData = [
  7096. 'product_id' => $product['product_id'],
  7097. 'product_name' => $product['product_name'],
  7098. 'product' => $product['product'],
  7099. 'pic_prompt' => $product['pic_prompt'],
  7100. 'url' => $product['url'],
  7101. 'pic_task_id' => $product['pic_task_id'],
  7102. 'pic_task_status' => $product['pic_task_status'],
  7103. 'episode_numbers' => $episodeNumbersStr,
  7104. 'created_at' => $product['created_at'],
  7105. ];
  7106. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7107. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7108. switch ($product['product']) {
  7109. case 1:
  7110. $roles[] = $productData;
  7111. break;
  7112. case 2:
  7113. $scenes[] = $productData;
  7114. break;
  7115. case 3:
  7116. $props[] = $productData;
  7117. break;
  7118. }
  7119. }
  7120. return [
  7121. 'script_id' => $script_id,
  7122. 'script_name' => $script->script_name ?? '',
  7123. 'roles' => $roles, // 主体
  7124. 'scenes' => $scenes, // 场景
  7125. 'props' => $props, // 道具
  7126. ];
  7127. }
  7128. /**
  7129. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7130. * @param string $actContent 原始内容
  7131. * @param array $products 产品数组(包含product_name和url)
  7132. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7133. */
  7134. public function processActContentWithProducts($actContent, $products) {
  7135. if (empty($actContent) || empty($products)) {
  7136. return [
  7137. 'content' => $actContent,
  7138. 'reference_images' => []
  7139. ];
  7140. }
  7141. // 构建产品名称到产品信息的映射
  7142. $product_dict = [];
  7143. foreach ($products as $product) {
  7144. $product_name = getProp($product, 'product_name');
  7145. if ($product_name) {
  7146. $product_dict[$product_name] = [
  7147. 'url' => getProp($product, 'url'),
  7148. 'voice_prompt' => getProp($product, 'voice_prompt')
  7149. ];
  7150. }
  7151. }
  7152. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7153. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7154. $reference_images = [];
  7155. $product_index_map = []; // 产品名称 => 图片序号的映射
  7156. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7157. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7158. $current_index = 1;
  7159. if (!empty($matches[1])) {
  7160. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7161. $seen_products = []; // 用于去重
  7162. foreach ($matches[1] as $product_name) {
  7163. // 跳过已处理的产品
  7164. if (isset($seen_products[$product_name])) {
  7165. continue;
  7166. }
  7167. $seen_products[$product_name] = true;
  7168. // 检查产品是否在字典中
  7169. if (isset($product_dict[$product_name])) {
  7170. $url = $product_dict[$product_name]['url'];
  7171. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7172. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7173. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7174. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7175. }
  7176. // 只有URL非空才分配序号和添加到参考图片
  7177. if (!empty($url)) {
  7178. // 检查URL是否已经在reference_images中(去重)
  7179. if (!in_array($url, $reference_images)) {
  7180. $reference_images[] = $url;
  7181. $product_index_map[$product_name] = $current_index;
  7182. $current_index++;
  7183. } else {
  7184. // URL重复,找到已有的序号
  7185. $existing_index = array_search($url, $reference_images) + 1;
  7186. $product_index_map[$product_name] = $existing_index;
  7187. }
  7188. } else {
  7189. // URL为空,不分配序号(后续直接去掉{})
  7190. $product_index_map[$product_name] = 0;
  7191. }
  7192. } else {
  7193. // 产品不在字典中,不分配序号
  7194. $product_index_map[$product_name] = 0;
  7195. }
  7196. }
  7197. }
  7198. // 第二步:替换内容中的 {产品名称}
  7199. $processedContent = $actContent;
  7200. foreach ($product_index_map as $product_name => $index) {
  7201. $escaped_name = preg_quote($product_name, '/');
  7202. if ($index > 0) {
  7203. // 有图片,替换为:产品名称(图X)
  7204. $replacement = $product_name . '<图片' . $index . '>';
  7205. } else {
  7206. // 无图片,只保留产品名称
  7207. $replacement = $product_name;
  7208. }
  7209. // 替换所有 {产品名称} 为处理后的格式
  7210. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7211. }
  7212. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7213. foreach ($products as $product) {
  7214. $product_name = getProp($product, 'product_name');
  7215. $voice_prompt = getProp($product, 'voice_prompt');
  7216. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7217. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7218. break; // 找到旁白后退出循环
  7219. }
  7220. }
  7221. // 第四步:将voice_prompt信息添加到内容最前面
  7222. $voice_prompt_prefix = '';
  7223. if (!empty($voice_prompts)) {
  7224. $voice_prompt_prefix .= implode('', $voice_prompts);
  7225. }
  7226. // 旁白的voice_prompt放在最后
  7227. if (!empty($narrator_voice_prompt)) {
  7228. $voice_prompt_prefix .= $narrator_voice_prompt;
  7229. }
  7230. // 如果有voice_prompt信息,添加到内容开头
  7231. if (!empty($voice_prompt_prefix)) {
  7232. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7233. }
  7234. return [
  7235. 'content' => $processedContent,
  7236. 'reference_images' => $reference_images
  7237. ];
  7238. }
  7239. public function saveActVideoGenerateParams($data) {
  7240. $episode_id = getProp($data, 'episode_id');
  7241. $model = getProp($data, 'video_model');
  7242. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7243. Utils::throwError('20003:该模型不可用');
  7244. }
  7245. if (!$model) {
  7246. // 使用默认模型
  7247. $model = 'zhizhen-20';
  7248. }
  7249. // 验证模型是否在可用模型表中
  7250. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7251. Utils::throwError('20003:该模型已不可用,请更换!');
  7252. }
  7253. $video_resolution = getProp($data, 'video_resolution', '720p');
  7254. $ratio = getProp($data, 'ratio');
  7255. if (!$ratio) $ratio = '9:16';
  7256. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7257. 'video_model' => $model,
  7258. 'video_resolution' => $video_resolution,
  7259. 'ratio' => $ratio,
  7260. 'updated_at' => date('Y-m-d H:i:s')
  7261. ]);
  7262. }
  7263. public function confirmActs($data) {
  7264. $episode_id = getProp($data, 'episode_id');
  7265. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7266. if (!$episode) {
  7267. Utils::throwError('20003:分集不存在');
  7268. }
  7269. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7270. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7271. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7272. // 获取所有片段数据
  7273. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7274. // 构建角色、场景和道具名称数组
  7275. $role_names = [];
  7276. $scene_names = [];
  7277. $prop_names = [];
  7278. foreach ($roles as $role) {
  7279. $role_name = getProp($role, 'role');
  7280. if ($role_name && $role_name != '旁白') {
  7281. $role_names[] = $role_name;
  7282. }
  7283. }
  7284. foreach ($scenes as $scene) {
  7285. $scene_name = getProp($scene, 'scene');
  7286. if ($scene_name) {
  7287. $scene_names[] = $scene_name;
  7288. }
  7289. }
  7290. foreach ($props as $prop) {
  7291. $prop_name = getProp($prop, 'prop');
  7292. if ($prop_name) {
  7293. $prop_names[] = $prop_name;
  7294. }
  7295. }
  7296. // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
  7297. usort($role_names, function($a, $b) {
  7298. return mb_strlen($b) - mb_strlen($a);
  7299. });
  7300. usort($scene_names, function($a, $b) {
  7301. return mb_strlen($b) - mb_strlen($a);
  7302. });
  7303. usort($prop_names, function($a, $b) {
  7304. return mb_strlen($b) - mb_strlen($a);
  7305. });
  7306. try {
  7307. DB::beginTransaction();
  7308. // 处理每个片段
  7309. foreach ($acts as $act) {
  7310. $act_content = getProp($act, 'act_content');
  7311. if (!$act_content) continue;
  7312. $processed_content = $act_content;
  7313. // 标记已处理的位置,避免重复标记
  7314. $marked_positions = [];
  7315. // 先匹配场景(在"场景:"后面)
  7316. foreach ($scene_names as $scene_name) {
  7317. // 转义特殊字符
  7318. $escaped_scene = preg_quote($scene_name, '/');
  7319. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  7320. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  7321. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  7322. $full_match = $matches[0];
  7323. $prefix = $matches[1];
  7324. $scene_name = $matches[2];
  7325. // 检查是否已经被标记
  7326. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  7327. return $prefix . '{' . $scene_name . '}';
  7328. }
  7329. return $full_match;
  7330. }, $processed_content);
  7331. }
  7332. // 匹配道具(在"道具:"后面,逻辑与场景一致)
  7333. foreach ($prop_names as $prop_name) {
  7334. // 转义特殊字符
  7335. $escaped_prop = preg_quote($prop_name, '/');
  7336. // 匹配道具:后面的道具名称(可能换行,也可能不换行)
  7337. $pattern = '/(道具:[\s\r\n]*)(' . $escaped_prop . ')/u';
  7338. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  7339. $full_match = $matches[0];
  7340. $prefix = $matches[1];
  7341. $prop_name = $matches[2];
  7342. // 检查是否已经被标记
  7343. if (strpos($prop_name, '{') === false && strpos($prop_name, '}') === false) {
  7344. return $prefix . '{' . $prop_name . '}';
  7345. }
  7346. return $full_match;
  7347. }, $processed_content);
  7348. }
  7349. // 再匹配角色名称(在"画面:"部分和"角色:"部分)
  7350. foreach ($role_names as $role_name) {
  7351. // 转义特殊字符
  7352. $escaped_role = preg_quote($role_name, '/');
  7353. // 1. 匹配"画面:"开始到换行之前的内容
  7354. $pattern = '/(画面:[^\n]*)/u';
  7355. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  7356. $line = $matches[1]; // 整行"画面:xxxxx"
  7357. // 在这一行中匹配所有角色名(避免重复标记)
  7358. $new_line = preg_replace(
  7359. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  7360. '{$1}',
  7361. $line
  7362. );
  7363. return $new_line;
  7364. }, $processed_content);
  7365. // 2. 匹配"角色:"或"出场角色:"这一整行内的角色名称
  7366. $pattern = '/((?:出场)?角色:[^\n]*)/u';
  7367. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  7368. $line = $matches[1]; // 整行"角色:xxxxx"或"出场角色:xxxxx"
  7369. // 在这一行中匹配所有角色名(避免重复标记)
  7370. $new_line = preg_replace(
  7371. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  7372. '{$1}',
  7373. $line
  7374. );
  7375. return $new_line;
  7376. }, $processed_content);
  7377. }
  7378. // 匹配道具名称(在"画面:"部分,逻辑与角色一致)
  7379. foreach ($prop_names as $prop_name) {
  7380. // 转义特殊字符
  7381. $escaped_prop = preg_quote($prop_name, '/');
  7382. // 匹配"画面:"开始到换行之前的内容
  7383. $pattern = '/(画面:[^\n]*)/u';
  7384. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_prop) {
  7385. $line = $matches[1]; // 整行"画面:xxxxx"
  7386. // 在这一行中匹配所有道具名(避免重复标记)
  7387. $new_line = preg_replace(
  7388. '/(?<![{])(' . $escaped_prop . ')(?![}])/u',
  7389. '{$1}',
  7390. $line
  7391. );
  7392. return $new_line;
  7393. }, $processed_content);
  7394. }
  7395. // 匹配角色名称(在"运镜:"部分)
  7396. foreach ($role_names as $role_name) {
  7397. // 转义特殊字符
  7398. $escaped_role = preg_quote($role_name, '/');
  7399. // 匹配"运镜:"开始到换行之前的内容
  7400. $pattern = '/(运镜:[^\n]*)/u';
  7401. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  7402. $line = $matches[1]; // 整行"运镜:xxxxx"
  7403. // 在这一行中匹配所有角色名(避免重复标记)
  7404. $new_line = preg_replace(
  7405. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  7406. '{$1}',
  7407. $line
  7408. );
  7409. return $new_line;
  7410. }, $processed_content);
  7411. }
  7412. // 匹配道具名称(在"运镜:"部分)
  7413. foreach ($prop_names as $prop_name) {
  7414. // 转义特殊字符
  7415. $escaped_prop = preg_quote($prop_name, '/');
  7416. // 匹配"运镜:"开始到换行之前的内容
  7417. $pattern = '/(运镜:[^\n]*)/u';
  7418. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_prop) {
  7419. $line = $matches[1]; // 整行"运镜:xxxxx"
  7420. // 在这一行中匹配所有道具名(避免重复标记)
  7421. $new_line = preg_replace(
  7422. '/(?<![{])(' . $escaped_prop . ')(?![}])/u',
  7423. '{$1}',
  7424. $line
  7425. );
  7426. return $new_line;
  7427. }, $processed_content);
  7428. }
  7429. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7430. $shot_counter = 0;
  7431. $processed_content = preg_replace_callback(
  7432. '/【(?:镜头|分镜)(\d+)】/u',
  7433. function($matches) use (&$shot_counter) {
  7434. $shot_counter++;
  7435. return '【镜头' . $shot_counter . '】';
  7436. },
  7437. $processed_content
  7438. );
  7439. // 更新数据库
  7440. $boolen = DB::table('mp_episode_segments')
  7441. ->where('id', $act->id)
  7442. ->update([
  7443. 'act_show_content' => $processed_content,
  7444. 'updated_at' => date('Y-m-d H:i:s')
  7445. ]);
  7446. if (!$boolen) {
  7447. Utils::throwError('20003:片段处理失败');
  7448. }
  7449. }
  7450. }catch (\Exception $e) {
  7451. DB::rollBack();
  7452. Utils::throwError('20003:'.$e->getMessage());
  7453. }
  7454. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7455. 'is_generated' => 1,
  7456. 'updated_at' => date('Y-m-d H:i:s')
  7457. ]);
  7458. if (!$boolen1) {
  7459. DB::rollBack();
  7460. Utils::throwError('20003:分集处理失败!');
  7461. }
  7462. DB::commit();
  7463. // 重新查询更新后的片段数据
  7464. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7465. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7466. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7467. $products = [];
  7468. // 先处理角色数组
  7469. foreach ($roles as $role) {
  7470. $product = $role;
  7471. // 将role字段重命名为product_name
  7472. if (isset($product['role'])) {
  7473. $product['product_name'] = $product['role'];
  7474. unset($product['role']);
  7475. }
  7476. $product['product'] = 1; // 标记类型为角色
  7477. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7478. }
  7479. // 处理场景数组
  7480. foreach ($scenes as $scene) {
  7481. $product = $scene;
  7482. // 将scene字段重命名为product_name
  7483. if (isset($product['scene'])) {
  7484. $product['product_name'] = $product['scene'];
  7485. unset($product['scene']);
  7486. }
  7487. $product['product'] = 2; // 标记类型为场景
  7488. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7489. }
  7490. // 处理道具数组(逻辑与场景一致)
  7491. foreach ($props as $prop) {
  7492. $product = $prop;
  7493. // 将prop字段重命名为product_name
  7494. if (isset($product['prop'])) {
  7495. $product['product_name'] = $product['prop'];
  7496. unset($product['prop']);
  7497. }
  7498. $product['product'] = 3; // 标记类型为道具
  7499. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7500. }
  7501. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7502. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7503. foreach ($extra_products as $extra_product) {
  7504. $product_name = getProp($extra_product, 'product_name');
  7505. if ($product_name) {
  7506. $products[$product_name] = $extra_product; // 覆盖同名数据
  7507. }
  7508. }
  7509. // 重新索引数组(去除key)
  7510. $products = array_values($products);
  7511. // 构建返回的acts数组
  7512. $return_acts = [];
  7513. foreach ($acts as $act) {
  7514. $return_acts[] = [
  7515. 'act_id' => getProp($act, 'id'),
  7516. 'act_number' => getProp($act, 'act_number'),
  7517. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7518. 'act_show_content' => getProp($act, 'act_show_content'),
  7519. 'video_url' => getProp($act, 'video_url'),
  7520. 'video_duration' => getProp($act, 'video_duration'),
  7521. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7522. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7523. ];
  7524. }
  7525. return [
  7526. 'anime_id' => getProp($episode, 'anime_id'),
  7527. 'episode_id' => $episode_id,
  7528. 'title' => getProp($episode, 'title'),
  7529. 'episode_number' => getProp($episode, 'episode_number'),
  7530. 'is_generated' => getProp($episode, 'is_generated'),
  7531. 'products' => $products,
  7532. 'acts' => $return_acts
  7533. ];
  7534. }
  7535. }