AnimeService.php 386 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934
  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 App\Services\PointsService;
  12. use Dflydev\DotAccessData\Util;
  13. use GuzzleHttp\Client;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. class AnimeService
  20. {
  21. protected $aiImageGenerationService;
  22. protected $aiVideoGenerationService;
  23. protected $DeepSeekService;
  24. protected $pointsService;
  25. private $url;
  26. private $api_key;
  27. private $headers;
  28. public function __construct(
  29. AIImageGenerationService $aiImageGenerationService,
  30. AIVideoGenerationService $aiVideoGenerationService,
  31. DeepSeekService $DeepSeekService,
  32. PointsService $pointsService
  33. ) {
  34. $this->aiImageGenerationService = $aiImageGenerationService;
  35. $this->aiVideoGenerationService = $aiVideoGenerationService;
  36. $this->DeepSeekService = $DeepSeekService;
  37. $this->pointsService = $pointsService;
  38. $this->url = 'https://api.deepseek.com/chat/completions';
  39. $this->api_key = env('DEEPSEEK_API_KEY');
  40. $this->headers = [
  41. 'Authorization' => 'Bearer '.$this->api_key,
  42. 'Content-Type' => 'application/json; charset=UTF-8'
  43. ];
  44. }
  45. /**
  46. * 构建统一的分镜数据结构(episodeInfo格式)
  47. * @param array $segments 分镜数据数组
  48. * @return array 返回包含acts和total_duration的数组
  49. */
  50. public function buildEpisodeSegmentsStructure($segments) {
  51. $acts = [];
  52. $totalDuration = 0; // 初始化总时长
  53. foreach($segments as $segment) {
  54. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  55. $videoDuration = getProp($segment, 'video_duration');
  56. $audioDuration = getProp($segment, 'audio_duration');
  57. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  58. $totalDuration += floatval($videoDuration);
  59. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  60. $totalDuration += floatval($audioDuration);
  61. } else {
  62. $totalDuration += 5; // 默认5秒
  63. }
  64. $segment_content = getProp($segment, 'segment_content');
  65. // 判断是否有尾帧描述,如果有则去掉这部分内容
  66. if (strpos($segment_content, '尾帧') !== false) {
  67. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  68. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  69. }
  70. // 构建分镜信息
  71. $segmentInfo = [
  72. 'segment_id' => getProp($segment, 'segment_id'),
  73. 'segment_number' => getProp($segment, 'segment_number'),
  74. 'segment_content' => $segment_content,
  75. 'description' => getProp($segment, 'description'),
  76. 'composition' => getProp($segment, 'composition'),
  77. 'camera_movement' => getProp($segment, 'camera_movement'),
  78. 'voice_actor' => getProp($segment, 'voice_actor'),
  79. 'dialogue' => getProp($segment, 'dialogue'),
  80. 'frame_type' => getProp($segment, 'frame_type'),
  81. 'scene' => getProp($segment, 'scene'),
  82. 'characters' => getProp($segment, 'characters'),
  83. 'tail_frame' => getProp($segment, 'tail_frame'),
  84. 'emotion' => getProp($segment, 'emotion'),
  85. 'emotion_type' => getProp($segment, 'emotion_type'),
  86. 'gender' => getProp($segment, 'gender'),
  87. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  88. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  89. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  90. 'pitch' => getProp($segment, 'pitch'),
  91. 'voice_name' => getProp($segment, 'voice_name'),
  92. 'voice_type' => getProp($segment, 'voice_type'),
  93. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  94. 'img_url' => getProp($segment, 'img_url'),
  95. 'audio_url' => getProp($segment, 'audio_url'),
  96. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  97. 'video_url' => getProp($segment, 'video_url'),
  98. 'video_duration' => getProp($segment, 'video_duration', 0),
  99. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  100. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  101. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  102. 'current_type' => getProp($segment, 'current_type'),
  103. ];
  104. $actNumber = getProp($segment, 'act_number');
  105. if (isset($acts[$actNumber])) {
  106. $acts[$actNumber]['segments'][] = $segmentInfo;
  107. } else {
  108. $acts[$actNumber] = [
  109. 'act_number' => $actNumber,
  110. 'act_title' => getProp($segment, 'act_title'),
  111. 'act_duration' => getProp($segment, 'act_duration'),
  112. 'segments' => [$segmentInfo]
  113. ];
  114. }
  115. }
  116. return [
  117. 'acts' => array_values($acts),
  118. 'total_duration' => intval(round($totalDuration))
  119. ];
  120. }
  121. /**
  122. * 构建统一的分段数据结构(episodeInfoForAce格式)
  123. * @param array $segments 分段数据数组
  124. * @return array 返回包含acts和total_duration的数组
  125. */
  126. public function buildEpisodeActsStructureForAce($segments) {
  127. $acts = [];
  128. $totalDuration = 0; // 初始化总时长
  129. foreach($segments as $segment) {
  130. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  131. $videoDuration = getProp($segment, 'video_duration');
  132. $actDuration = getProp($segment, 'act_duration');
  133. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  134. $totalDuration += floatval($videoDuration);
  135. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  136. $totalDuration += floatval($actDuration);
  137. } else {
  138. $totalDuration += 5; // 默认5秒
  139. }
  140. // 构建分镜信息
  141. $segmentInfo = [
  142. 'act_id' => getProp($segment, 'id'),
  143. 'act_number' => getProp($segment, 'act_number'),
  144. 'act_title' => getProp($segment, 'act_title'),
  145. 'act_duration' => getProp($segment, 'act_duration'),
  146. 'act_content' => getProp($segment, 'act_content'),
  147. 'video_url' => getProp($segment, 'video_url'),
  148. 'video_duration' => getProp($segment, 'video_duration', 0),
  149. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  150. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  151. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  152. 'current_type' => getProp($segment, 'current_type'),
  153. ];
  154. $acts[] = $segmentInfo;
  155. }
  156. return [
  157. 'acts' => array_values($acts),
  158. 'total_duration' => intval(round($totalDuration))
  159. ];
  160. }
  161. /**
  162. * 验证画面比例是否有效
  163. * @param string $ratio 画面比例
  164. * @return bool
  165. */
  166. public function validateRatio($ratio) {
  167. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  168. }
  169. /**
  170. * 获取画面比例对应的宽高
  171. * @param string $ratio 画面比例
  172. * @return array ['width' => int, 'height' => int]
  173. * @throws \Exception
  174. */
  175. private function getRatioDimensions($ratio) {
  176. if ($ratio && !$this->validateRatio($ratio)) {
  177. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  178. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  179. }
  180. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  181. }
  182. public function createAnime($data) {
  183. $uid = Site::getUid();
  184. $cpid = Site::getCpid();
  185. $input_art_style = getProp($data, 'art_style');
  186. $file = getProp($data, 'file');
  187. $content = getProp($data, 'content', '');
  188. $bid = getProp($data, 'bid', 0);
  189. $script_id = getProp($data, 'script_id', 0);
  190. $ace_mode = getProp($data, 'ace_mode', 0);
  191. $extra_products = getProp($data, 'products', []);
  192. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  193. if (!is_array($extra_products)) {
  194. Utils::throwError('20003:传入的资产格式不正确');
  195. }
  196. // 替换美术风格
  197. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  198. // 提取文件内容
  199. if ($file) {
  200. $content = $this->DeepSeekService->extractFileContent($file);
  201. if (!$content) {
  202. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  203. }
  204. } elseif ($script_id) {
  205. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  208. }
  209. } elseif ($bid) {
  210. $content = $this->DeepSeekService->getContentByBid($bid);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  213. }
  214. } elseif ($content) {
  215. $content = filterContent($content);
  216. }else {
  217. $content = '';
  218. }
  219. $anime_data = [
  220. 'user_id' => $uid,
  221. 'cpid' => $cpid,
  222. 'anime_name' => '新剧本策划',
  223. 'is_multi' => getProp($data, 'is_multi', 1),
  224. 'content' => $content,
  225. 'art_style_type' => $input_art_style,
  226. 'ace_mode' => $ace_mode,
  227. 'script_id' => $script_id,
  228. 'extra_products' => json_encode($extra_products, 256),
  229. 'created_at' => date('Y-m-d H:i:s'),
  230. 'updated_at' => date('Y-m-d H:i:s'),
  231. ];
  232. // 处理文本模型
  233. $model = getProp($data, 'model');
  234. if (!$model) {
  235. // 用户没有输入,使用默认值
  236. $model = 'deepseek-v4-pro';
  237. }
  238. // 验证模型是否在可用模型表中
  239. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  240. $model = 'deepseek-v4-pro';
  241. }
  242. $anime_data['model'] = $model;
  243. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  244. return DB::table('mp_animes')->insertGetId($anime_data);
  245. }
  246. public function chatList($data) {
  247. $uid = Site::getUid();
  248. $anime_name = getProp($data, 'anime_name');
  249. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  250. if ($anime_name) {
  251. $query->where('anime_name', 'like', "%$anime_name%");
  252. }
  253. return $query->orderBy('id', 'desc')->paginate();
  254. }
  255. public function chatHistory($data) {
  256. $anime_id = getProp($data, 'anime_id');
  257. $sequence = getProp($data, 'sequence', 0);
  258. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  259. $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)
  260. ->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');
  261. return $query->orderBy('ar.id')->get()->map(function ($value) {
  262. $value = (array)$value;
  263. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  264. $value['created_at'] = transDate($value['created_at']);
  265. $value['episode_created_at'] = transDate($value['episode_created_at']);
  266. return $value;
  267. })->toArray();
  268. }
  269. public function batchSetRoleImg($data) {
  270. $episode_id = getProp($data, 'episode_id');
  271. if (!$episode_id) Utils::throwError('1002:请选择分集');
  272. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  273. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  274. $art_style = getProp($episode, 'art_style');
  275. $anime_id = getProp($episode, 'anime_id');
  276. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  277. $art_style_type = getProp($anime, 'art_style_type');
  278. $character_prefix = '';
  279. $scene_prefix = '';
  280. if ($art_style_type) {
  281. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  282. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  283. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  284. }
  285. foreach ($roles as &$role) {
  286. $role_name = getProp($role, 'role');
  287. if ($role_name == '旁白') continue;
  288. // 优先使用 pic_prompt,如果没有则使用 description
  289. $pic_prompt = getProp($role, 'pic_prompt');
  290. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  291. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  292. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  293. // 参考图地址
  294. $ref_img_url = getProp($role, 'url');
  295. if ($ref_img_url) continue; // 已有图片则跳过
  296. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  297. try {
  298. $params = [
  299. 'prompt' => $description,
  300. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  301. ];
  302. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  303. $task_id = $task->id;
  304. if (!$task_id) {
  305. Utils::throwError("20003:角色({$role_name})生成图片失败");
  306. }
  307. $role['task_id'] = $task_id;
  308. $role['task_status'] = 'processing';
  309. } catch (\Exception $e) {
  310. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  311. Utils::throwError("20003:" . $e->getMessage());
  312. }
  313. }
  314. // 保存角色信息
  315. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  316. 'roles' => json_encode($roles, 256),
  317. 'generate_status' => '执行中',
  318. 'generate_at' => date('Y-m-d H:i:s'),
  319. 'updated_at' => date('Y-m-d H:i:s')
  320. ]);
  321. if (!$boolen) {
  322. Utils::throwError('20003:保存角色信息失败');
  323. }
  324. return $boolen;
  325. }
  326. public function batchSetSceneImg($data) {
  327. $episode_id = getProp($data, 'episode_id');
  328. if (!$episode_id) Utils::throwError('1002:请选择分集');
  329. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  330. $scenes = json_decode(getProp($episode, 'scenes'), true);
  331. $art_style = getProp($episode, 'art_style');
  332. $target_scene = getProp($data, 'target_scene');
  333. $anime_id = getProp($episode, 'anime_id');
  334. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  335. $art_style_type = getProp($anime, 'art_style_type');
  336. $character_prefix = '';
  337. $scene_prefix = '';
  338. if ($art_style_type) {
  339. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  340. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  341. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  342. }
  343. foreach ($scenes as &$scene) {
  344. $scene_name = getProp($scene, 'scene');
  345. if ($scene_name != $target_scene) continue;
  346. // 优先使用 pic_prompt,如果没有则使用 description
  347. $pic_prompt = getProp($scene, 'pic_prompt');
  348. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  349. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  350. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  351. // 参考图地址
  352. $ref_img_url = getProp($scene, 'url');
  353. if ($ref_img_url) continue; // 已有图片则跳过
  354. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  355. try {
  356. $params = [
  357. 'prompt' => $description,
  358. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  359. ];
  360. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  361. $task_id = $task->id;
  362. if (!$task_id) {
  363. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  364. }
  365. $scene['task_id'] = $task_id;
  366. $scene['task_status'] = 'processing';
  367. } catch (\Exception $e) {
  368. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  369. Utils::throwError("20003:" . $e->getMessage());
  370. }
  371. }
  372. // 保存场景信息
  373. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  374. 'scenes' => json_encode($scenes, 256),
  375. 'generate_status' => '执行中',
  376. 'generate_at' => date('Y-m-d H:i:s'),
  377. 'updated_at' => date('Y-m-d H:i:s')
  378. ]);
  379. if (!$boolen) {
  380. Utils::throwError('20003:保存角色信息失败');
  381. }
  382. return $boolen;
  383. }
  384. public function editAnime($data) {
  385. $anime_id = getProp($data, 'anime_id');
  386. $anime_name = trim(getProp($data, 'anime_name'));
  387. // 确认对话名称唯一性
  388. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  389. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  390. }
  391. if (!$anime_id || !$anime_name) {
  392. Utils::throwError('20003:参数异常');
  393. }
  394. return DB::table('mp_animes')->where('id', $anime_id)->update([
  395. 'anime_name' => $anime_name,
  396. 'updated_at' => date('Y-m-d H:i:s')
  397. ]);
  398. // $script_arr =getProp($data, 'script', []);
  399. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  400. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  401. // $anime_id = getProp($data, 'anime_id');
  402. // try {
  403. // DB::beginTransaction();
  404. // $table_data = [
  405. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  406. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  407. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  408. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  409. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  410. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  411. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  412. // 'status' => 3,
  413. // 'start_episode_sequence' => $start_episode_sequence,
  414. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  415. // 'episode_num' => count($script_arr['episodes']),
  416. // 'updated_at' => date('Y-m-d H:i:s')
  417. // ];
  418. // // 保存剧本内容
  419. // if (!empty($anime_id)) {
  420. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  421. // if (!$boolen) {
  422. // dLog('anime')->info('对话保存失败', $table_data);
  423. // Utils::throwError('20003:对话保存失败');
  424. // }
  425. // }else {
  426. // $table['created_at'] = $table_data['updated_at'];
  427. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  428. // if (!$anime_id) {
  429. // dLog('anime')->info('对话保存失败', $table_data);
  430. // Utils::throwError('20003:对话保存失败');
  431. // }
  432. // }
  433. // // 保存分集内容
  434. // // 删除历史分集内容
  435. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  436. // $episodes = [];
  437. // $sequence = 1;
  438. // foreach ($script_arr['episodes'] as $episode) {
  439. // $segment_number = 1;
  440. // foreach($episode['segments'] as $segment) {
  441. // $episodes[] = [
  442. // 'anime_id' => $anime_id,
  443. // 'episode_number' => $episode['episode_number'],
  444. // 'title' => $episode['title'],
  445. // // 'content' => $episode['content'],
  446. // 'content' => '',
  447. // 'segment_number' => $segment_number,
  448. // 'segment_content' => $segment['segment_content'],
  449. // 'sequence' => $sequence,
  450. // 'created_at' => date('Y-m-d H:i:s'),
  451. // 'updated_at' => date('Y-m-d H:i:s')
  452. // ];
  453. // $sequence++;
  454. // $segment_number++;
  455. // }
  456. // }
  457. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  458. // if (!$boolen2) {
  459. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  460. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  461. // Utils::throwError('20003:分集内容保存失败');
  462. // }
  463. // } catch (\Exception $e) {
  464. // DB::rollBack();
  465. // Utils::throwError('20003:'.$e->getMessage());
  466. // }
  467. // DB::commit();
  468. // return true;
  469. }
  470. public function delAnime($data) {
  471. $anime_id = getProp($data, 'anime_id');
  472. if (!$anime_id) {
  473. Utils::throwError('20003:请选择剧本');
  474. }
  475. return DB::table('mp_animes')->where('id', $anime_id)->update([
  476. 'is_deleted' => 1,
  477. 'updated_at' => date('Y-m-d H:i:s')
  478. ]);
  479. }
  480. public function animeDetail($data) {
  481. $uid = Site::getUid();
  482. $anime_id = getProp($data, 'anime_id');
  483. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  484. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  485. if (!$anime) Utils::throwError('20003:权限不足');
  486. $anime = (array)$anime;
  487. $anime['roles'] = json_decode($anime['roles']);
  488. $anime['scenes'] = json_decode($anime['scenes']);
  489. // 获取分集信息
  490. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  491. ->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"))
  492. ->orderBy('episode_number')->get()->map(function ($value) {
  493. return (array)$value;
  494. })->toArray();
  495. $anime['episodes'] = $episodes;
  496. return $anime;
  497. }
  498. public function episodeInfo($data) {
  499. $uid = Site::getUid();
  500. $anime_id = getProp($data, 'anime_id');
  501. $episode_id = getProp($data, 'episode_id');
  502. if (!$anime_id || !$episode_id) {
  503. Utils::throwError('1002:请选择剧集');
  504. }
  505. // 验证用户权限
  506. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  507. if (!$anime) Utils::throwError('20003:权限不足');
  508. $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();
  509. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  510. $episode = (array)$episode;
  511. $episode['roles'] = json_decode($episode['roles'], true);
  512. // foreach($episode['roles'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  514. // }
  515. $episode['scenes'] = json_decode($episode['scenes'], true);
  516. // foreach($episode['scenes'] as &$item) {
  517. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  518. // }
  519. // 获取分镜信息
  520. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  521. ->select('*')->get()->map(function ($value) {
  522. return (array)$value;
  523. })->toArray();
  524. // 使用公共方法构建分镜结构
  525. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  526. $episode['acts'] = $segmentsStructure['acts'];
  527. $episode['total_duration'] = $segmentsStructure['total_duration'];
  528. return $episode;
  529. }
  530. public function episodeInfoForAce($data) {
  531. $anime_id = getProp($data, 'anime_id');
  532. $episode_id = getProp($data, 'episode_id');
  533. if (!$anime_id || !$episode_id) {
  534. Utils::throwError('1002:请选择剧集');
  535. }
  536. $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();
  537. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  538. $episode = (array)$episode;
  539. $episode['roles'] = json_decode($episode['roles'], true);
  540. // foreach($episode['roles'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  542. // }
  543. $episode['scenes'] = json_decode($episode['scenes'], true);
  544. // foreach($episode['scenes'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  546. // }
  547. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  548. // 获取分镜信息
  549. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  550. ->select('*')->get()->map(function ($value) {
  551. return (array)$value;
  552. })->toArray();
  553. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  554. $episode['acts'] = $segmentsStructure['acts'];
  555. $episode['total_duration'] = $segmentsStructure['total_duration'];
  556. return $episode;
  557. }
  558. public function segmentInfo($data) {
  559. $uid = Site::getUid();
  560. $segment_id = getProp($data, 'segment_id');
  561. if (!$segment_id) {
  562. Utils::throwError('1002:请选择分镜');
  563. }
  564. // 获取分镜信息
  565. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  566. // 验证用户权限
  567. if ($segment) {
  568. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  569. if (!$anime) Utils::throwError('20003:权限不足');
  570. }
  571. $result = [
  572. 'segment_id' => getProp($segment, 'segment_id'),
  573. 'segment_number' => getProp($segment, 'segment_number'),
  574. 'segment_content' => getProp($segment, 'segment_content'),
  575. 'description' => getProp($segment, 'description'),
  576. 'composition' => getProp($segment, 'composition'),
  577. 'camera_movement' => getProp($segment, 'camera_movement'),
  578. 'voice_actor' => getProp($segment, 'voice_actor'),
  579. 'dialogue' => getProp($segment, 'dialogue'),
  580. 'frame_type' => getProp($segment, 'frame_type'),
  581. 'scene' => getProp($segment, 'scene'),
  582. 'characters' => getProp($segment, 'characters'),
  583. 'tail_frame' => getProp($segment, 'tail_frame'),
  584. 'emotion' => getProp($segment, 'emotion'),
  585. 'emotion_type' => getProp($segment, 'emotion_type'),
  586. 'gender' => getProp($segment, 'gender'),
  587. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  588. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  589. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  590. 'pitch' => getProp($segment, 'pitch'),
  591. 'voice_name' => getProp($segment, 'voice_name'),
  592. 'voice_type' => getProp($segment, 'voice_type'),
  593. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  594. 'img_url' => getProp($segment, 'img_url'),
  595. 'video_url' => getProp($segment, 'video_url'),
  596. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  597. ];
  598. return $result;
  599. }
  600. public function copyEpisodeVersion($data) {
  601. $episode_id = getProp($data, 'episode_id');
  602. $uid = Site::getUid();
  603. $cpid = Site::getCpid();
  604. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  605. if (!$episode) Utils::throwError('20003:该剧集不存在');
  606. $episode = (array)$episode;
  607. $anime_id = $episode['anime_id'];
  608. $episode_number = $episode['episode_number'];
  609. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  610. $sequence = $count + 1;
  611. unset($episode['id']);
  612. $now = date('Y-m-d H:i:s');
  613. $episode['created_at'] = $now;
  614. $episode['updated_at'] = $now;
  615. $episode['is_default'] = 1;
  616. // 获取版本中含有"(副本"字样的个数
  617. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  618. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  619. $episode['sequence'] = $sequence;
  620. $episode['is_generated'] = 0;
  621. $episode['cpid'] = $cpid;
  622. // 获取ace_mode
  623. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  624. try {
  625. DB::beginTransaction();
  626. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  627. // 新增副本
  628. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  629. if (!$new_episode_id) {
  630. Utils::throwError('20003:创建副本失败!');
  631. }
  632. // 获取分镜数据并准备插入
  633. $segments_for_insert = DB::table('mp_episode_segments')
  634. ->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')
  635. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  636. $item = (array)$item;
  637. $item['episode_id'] = $new_episode_id;
  638. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  639. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  640. return $item;
  641. })->toArray();
  642. // 写入分镜数据
  643. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  644. if (!$boolen2) {
  645. Utils::throwError('20003:写入分镜数据失败!');
  646. }
  647. // 写入对话历史
  648. $records = [
  649. [
  650. 'uid' => $uid,
  651. 'anime_id' => $anime_id,
  652. 'role' => 'user',
  653. 'content' => '创建副本',
  654. 'sequence' => $episode_number,
  655. 'episode_id' => $new_episode_id,
  656. 'created_at' => $now,
  657. 'updated_at' => $now
  658. ],
  659. [
  660. 'uid' => $uid,
  661. 'anime_id' => $anime_id,
  662. 'role' => 'assistant',
  663. 'content' => '好的,已为您创建副本',
  664. 'sequence' => $episode_number,
  665. 'episode_id' => $new_episode_id,
  666. 'created_at' => $now,
  667. 'updated_at' => $now
  668. ]
  669. ];
  670. $boolen3 = DB::table('mp_anime_records')->insert($records);
  671. if (!$boolen3) {
  672. Utils::throwError('20003:对话记录保存失败');
  673. }
  674. }catch (\Exception $e) {
  675. DB::rollBack();
  676. Utils::throwError('20003:'.$e->getMessage());
  677. }
  678. DB::commit();
  679. // 构建与 episodeInfo 方法一致的返回数据结构
  680. $result = [
  681. 'episode_id' => $new_episode_id,
  682. 'anime_id' => $anime_id,
  683. 'episode_number' => $episode_number,
  684. 'title' => $episode['title'],
  685. 'intro' => $episode['intro'],
  686. 'art_style' => $episode['art_style'],
  687. 'roles' => json_decode($episode['roles'], true),
  688. 'scenes' => json_decode($episode['scenes'], true),
  689. 'is_generated' => (int)$episode['is_generated']
  690. ];
  691. if ((int)$ace_mode === 1) {
  692. // 获取分镜信息
  693. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  694. ->select('*')->get()->map(function ($value) {
  695. return (array)$value;
  696. })->toArray();
  697. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  698. }else {
  699. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  700. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  701. }
  702. $result['acts'] = $segmentsStructure['acts'];
  703. $result['total_duration'] = $segmentsStructure['total_duration'];
  704. return $result;
  705. }
  706. public function episodeVersions($data) {
  707. $anime_id = getProp($data, 'anime_id');
  708. $episode_id = getProp($data, 'episode_id');
  709. if (!$anime_id || !$episode_id) {
  710. Utils::throwError('1002:请选择剧集');
  711. }
  712. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  713. $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) {
  714. return (array)$value;
  715. })->toArray();
  716. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  717. foreach($episodes as &$episode) {
  718. $episode['version'] = 'V'.$episode['sequence'];
  719. $episode['roles'] = json_decode($episode['roles'], true);
  720. $episode['scenes'] = json_decode($episode['scenes'], true);
  721. // 获取分镜信息
  722. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  723. ->select('*')->get()->map(function ($value) {
  724. return (array)$value;
  725. })->toArray();
  726. // 使用公共方法构建分镜结构
  727. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  728. $episode['acts'] = $segmentsStructure['acts'];
  729. $episode['total_duration'] = $segmentsStructure['total_duration'];
  730. }
  731. return $episodes;
  732. }
  733. public function bindEpisodeVersion($data) {
  734. $episode_id = getProp($data, 'episode_id');
  735. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  736. if (!$episode) Utils::throwError('20003:该剧集不存在');
  737. $episode = (array)$episode;
  738. if ((int)$episode['is_default'] === 1) return true;
  739. try {
  740. DB::beginTransaction();
  741. // 移除is_default标志
  742. $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')]);
  743. if (!$boolen) {
  744. Utils::throwError('20003:更新失败!');
  745. }
  746. // 绑定副本
  747. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  748. if (!$boolen2) {
  749. Utils::throwError('20003:绑定失败!');
  750. }
  751. }catch (\Exception $e) {
  752. DB::rollBack();
  753. Utils::throwError('20003:'.$e->getMessage());
  754. }
  755. DB::commit();
  756. return true;
  757. }
  758. public function chatChangeImg($data) {
  759. $segment_id = getProp($data, 'segment_id');
  760. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  761. $prompt = getProp($data, 'prompt');
  762. if (!$prompt || !$segment_id) {
  763. Utils::throwError('1002:请输入提示词,并且选择分镜');
  764. }
  765. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  766. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  767. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  768. else $ref_img_url = '';
  769. // $ref_img_url = '';
  770. if (empty($prompt)) {
  771. if (empty($ref_img_url)) {
  772. $prompt = getProp($segment, 'segment_content');
  773. }else {
  774. $prompt = '请根据图片生成';
  775. }
  776. }
  777. $anime_id = getProp($segment, 'anime_id');
  778. $episode_id = getProp($segment, 'episode_id');
  779. $episode_number = getProp($segment, 'episode_number');
  780. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  781. $ratio = getProp($data, 'ratio');
  782. if (!$ratio) {
  783. $ratio = getProp($episode, 'ratio');
  784. if (!$ratio) $ratio = '9:16';
  785. }
  786. $art_style = getProp($episode, 'art_style');
  787. if ($art_style) {
  788. $prompt = "美术风格:{$art_style}\n{$prompt}";
  789. }
  790. $dimensions = $this->getRatioDimensions($ratio);
  791. $width = $dimensions['width'];
  792. $height = $dimensions['height'];
  793. try {
  794. $params = [
  795. 'alias_segment_id' => $segment_id,
  796. 'prompt' => $prompt,
  797. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  798. 'width' => $width,
  799. 'height' => $height
  800. ];
  801. // 优化提示词(不要生成字幕)
  802. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  803. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  804. $task_id = $task->id;
  805. if (!$task_id) {
  806. Utils::throwError("20003:生成图片失败");
  807. }
  808. // 更新任务ID
  809. $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')]);
  810. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  811. } catch (\Exception $e) {
  812. Utils::throwError("20003:" . $e->getMessage());
  813. }
  814. // 创建任务之后先暂停10s等待异步任务完成
  815. sleep(10);
  816. $img_url = $this->loopGetPicTaskResult($task_id);
  817. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  818. // 图片生成后新增对话记录
  819. try {
  820. $uid = Site::getUid();
  821. $now = date('Y-m-d H:i:s');
  822. // 使用AI反推图片提示词
  823. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  824. // 保存对话记录
  825. $records = [
  826. [
  827. 'uid' => $uid,
  828. 'anime_id' => $anime_id,
  829. 'sequence' => $episode_number,
  830. 'role' => 'user',
  831. 'content' => $prompt,
  832. 'segment_id' => $segment_id,
  833. 'image_url' => '',
  834. 'created_at' => $now,
  835. 'updated_at' => $now
  836. ],
  837. [
  838. 'uid' => $uid,
  839. 'anime_id' => $anime_id,
  840. 'sequence' => $episode_number,
  841. 'role' => 'assistant',
  842. 'content' => $pic_prompt,
  843. 'segment_id' => $segment_id,
  844. 'image_url' => $img_url,
  845. 'created_at' => $now,
  846. 'updated_at' => $now
  847. ]
  848. ];
  849. DB::table('mp_anime_records')->insert($records);
  850. } catch (\Exception $e) {
  851. // 记录日志但不影响主流程
  852. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  853. 'segment_id' => $segment_id,
  854. 'img_url' => $img_url
  855. ]);
  856. logDB('anime', 'error', '保存对话记录失败', [
  857. 'segment_id' => $segment_id,
  858. 'img_url' => $img_url,
  859. 'error' => $e->getMessage()
  860. ]);
  861. }
  862. return $img_url;
  863. }
  864. public function segmentChatHistory($data) {
  865. $segment_id = getProp($data, 'segment_id');
  866. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  867. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  868. $chat = $query->orderBy('id')->get()->map(function ($value) {
  869. $value = (array)$value;
  870. $value['created_at'] = transDate($value['created_at']);
  871. return $value;
  872. })->toArray();
  873. // 获取历史图片
  874. $url = [];
  875. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  876. foreach($pic_history as $task) {
  877. $result_url = getProp($task, 'result_url');
  878. if (is_json($result_url)) {
  879. $url = array_merge($url, json_decode($result_url, true));
  880. }else {
  881. $url[] = $result_url;
  882. }
  883. }
  884. // 获取历史视频
  885. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  886. foreach($video_history as $task) {
  887. $result_url = getProp($task, 'compressed_url');
  888. if (is_json($result_url)) {
  889. $url = array_merge($url, json_decode($result_url, true));
  890. }else {
  891. $url[] = $result_url;
  892. }
  893. }
  894. return compact('chat', 'url');
  895. }
  896. public function changeEpisodeRoles($data) {
  897. $anime_id = getProp($data, 'anime_id');
  898. $episode_id = getProp($data, 'episode_id');
  899. $target_roles = getProp($data, 'roles');
  900. $is_deleted = getProp($data, 'is_deleted', 0);
  901. // 参数验证
  902. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  903. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  904. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  905. // 验证剧集是否存在
  906. $episode = DB::table('mp_anime_episodes')
  907. ->where('anime_id', $anime_id)
  908. ->where('id', $episode_id)
  909. ->first();
  910. if (!$episode) Utils::throwError('20003:该剧集不存在');
  911. $roles = json_decode(getProp($episode, 'roles'), true);
  912. // 获取anime信息,检查是否有关联的script_id
  913. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  914. if (!$anime) Utils::throwError('20003:动漫不存在');
  915. $script_id = getProp($anime, 'script_id');
  916. $episode_number = getProp($episode, 'episode_number', 1);
  917. $uid = Site::getUid();
  918. $cpid = Site::getCpid();
  919. try {
  920. $target_role_name = getProp($target_roles, 'role');
  921. // 如果是删除操作
  922. if ($is_deleted == 1) {
  923. // 从角色列表中移除该角色
  924. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  925. return getProp($role, 'role') !== $target_role_name;
  926. }));
  927. // 更新角色列表
  928. $result = DB::table('mp_anime_episodes')
  929. ->where('anime_id', $anime_id)
  930. ->where('id', $episode_id)
  931. ->update([
  932. 'roles' => json_encode($roles, 256),
  933. 'updated_at' => date('Y-m-d H:i:s')
  934. ]);
  935. if ($result === false) {
  936. Utils::throwError('20003:删除角色失败');
  937. }
  938. } else {
  939. // 新增或更新操作
  940. $role_found = false;
  941. $is_new_role = false;
  942. // 查找并更新已存在的角色
  943. foreach($roles as &$role) {
  944. if (getProp($role, 'role') === $target_role_name) {
  945. $role = $target_roles;
  946. $role_found = true;
  947. break;
  948. }
  949. }
  950. // 如果角色不存在,则新增
  951. if (!$role_found) {
  952. $roles[] = $target_roles;
  953. $is_new_role = true;
  954. }
  955. // 更新角色列表
  956. $result = DB::table('mp_anime_episodes')
  957. ->where('anime_id', $anime_id)
  958. ->where('id', $episode_id)
  959. ->update([
  960. 'roles' => json_encode($roles, 256),
  961. 'updated_at' => date('Y-m-d H:i:s')
  962. ]);
  963. if ($result === false) {
  964. Utils::throwError('20003:更新角色列表失败');
  965. }
  966. // 同步更新分镜表中对应主体的音色信息
  967. $voice_name = getProp($target_roles, 'voice_name');
  968. $voice_type = getProp($target_roles, 'voice_type');
  969. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  970. DB::table('mp_episode_segments')
  971. ->where('anime_id', $anime_id)
  972. ->where('episode_id', $episode_id)
  973. ->where('voice_actor', $target_role_name)
  974. ->update([
  975. 'voice_name' => $voice_name,
  976. 'voice_type' => $voice_type,
  977. 'voice_audio_url' => $voice_audio_url,
  978. 'updated_at' => date('Y-m-d H:i:s')
  979. ]);
  980. // 如果有关联的script_id,则同步到mp_products表
  981. if ($script_id) {
  982. // 查询剧本信息
  983. $script = DB::table('mp_scripts')
  984. ->where('id', $script_id)
  985. ->where('is_deleted', 0)
  986. ->first();
  987. if ($script) {
  988. $script_name = $script->script_name ?? 'script_' . $script_id;
  989. $product_name = getProp($target_roles, 'role');
  990. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  991. $url = getProp($target_roles, 'url', '');
  992. $product_type = 1; // 1=角色
  993. // 查找或创建以script_name命名的文件夹
  994. $folder = DB::table('mp_products')
  995. ->where('cpid', $cpid)
  996. ->where('type', 2) // 文件夹类型
  997. ->where('product', $product_type) // 角色类型
  998. ->where('product_name', $script_name)
  999. ->where('parent_id', 0)
  1000. ->where('is_deleted', 0)
  1001. ->first();
  1002. if (!$folder) {
  1003. // 创建文件夹
  1004. $folder_id = DB::table('mp_products')->insertGetId([
  1005. 'user_id' => $uid,
  1006. 'cpid' => $cpid,
  1007. 'type' => 2, // 文件夹
  1008. 'product' => $product_type, // 角色类型
  1009. 'parent_id' => 0,
  1010. 'level' => 1,
  1011. 'product_name' => $script_name,
  1012. 'sort_order' => time(),
  1013. 'is_deleted' => 0,
  1014. 'created_at' => date('Y-m-d H:i:s'),
  1015. 'updated_at' => date('Y-m-d H:i:s')
  1016. ]);
  1017. } else {
  1018. $folder_id = $folder->id;
  1019. }
  1020. // 查找该文件夹下是否已存在同名资产
  1021. $existing_product = DB::table('mp_products')
  1022. ->where('cpid', $cpid)
  1023. ->where('type', 1) // 资产类型
  1024. ->where('product', $product_type)
  1025. ->where('parent_id', $folder_id)
  1026. ->where('product_name', $product_name)
  1027. ->where('is_deleted', 0)
  1028. ->first();
  1029. if ($existing_product) {
  1030. // 更新已存在的资产
  1031. $updateData = [
  1032. 'pic_task_status' => '生成成功',
  1033. ];
  1034. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1035. if ($url) $updateData['url'] = $url;
  1036. // 处理versions字段
  1037. $versions = getProp($target_roles, 'versions', []);
  1038. if ($versions && is_array($versions)) {
  1039. $updateData['versions'] = json_encode($versions, 256);
  1040. }
  1041. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1042. DB::table('mp_products')
  1043. ->where('id', $existing_product->id)
  1044. ->update($updateData);
  1045. $product_id = $existing_product->id;
  1046. } else {
  1047. // 创建新资产
  1048. $versions = getProp($target_roles, 'versions', []);
  1049. $product_id = DB::table('mp_products')->insertGetId([
  1050. 'user_id' => $uid,
  1051. 'cpid' => $cpid,
  1052. 'type' => 1, // 资产
  1053. 'product' => $product_type, // 角色
  1054. 'parent_id' => $folder_id,
  1055. 'level' => 2,
  1056. 'product_name' => $product_name,
  1057. 'url' => $url,
  1058. 'pic_prompt' => $pic_prompt,
  1059. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1060. 'sort_order' => time(),
  1061. 'is_deleted' => 0,
  1062. 'pic_task_status' => '生成成功',
  1063. 'created_at' => date('Y-m-d H:i:s'),
  1064. 'updated_at' => date('Y-m-d H:i:s')
  1065. ]);
  1066. }
  1067. // 建立或更新绑定关系
  1068. $existing_mapping = DB::table('mp_script_product_mappings')
  1069. ->where('script_id', $script_id)
  1070. ->where('product_id', $product_id)
  1071. ->where('episode_number', $episode_number)
  1072. ->first();
  1073. if (!$existing_mapping) {
  1074. // 创建绑定关系
  1075. DB::table('mp_script_product_mappings')->insert([
  1076. 'script_id' => $script_id,
  1077. 'product_id' => $product_id,
  1078. 'episode_number' => $episode_number,
  1079. 'created_at' => date('Y-m-d H:i:s'),
  1080. 'updated_at' => date('Y-m-d H:i:s')
  1081. ]);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. } catch (\Exception $e) {
  1087. dLog('anime')->error('更新剧集角色失败', [
  1088. 'anime_id' => $anime_id,
  1089. 'episode_id' => $episode_id,
  1090. 'error' => $e->getMessage()
  1091. ]);
  1092. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1093. }
  1094. return true;
  1095. }
  1096. public function changeEpisodeScenes($data) {
  1097. $anime_id = getProp($data, 'anime_id');
  1098. $episode_id = getProp($data, 'episode_id');
  1099. $target_scenes = getProp($data, 'scenes');
  1100. $is_deleted = getProp($data, 'is_deleted', 0);
  1101. // 参数验证
  1102. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1103. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1104. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1105. // 验证剧集是否存在
  1106. $episode = DB::table('mp_anime_episodes')
  1107. ->where('anime_id', $anime_id)
  1108. ->where('id', $episode_id)
  1109. ->first();
  1110. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1111. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1112. // 获取anime信息,检查是否有关联的script_id
  1113. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1114. if (!$anime) Utils::throwError('20003:动漫不存在');
  1115. $script_id = getProp($anime, 'script_id');
  1116. $episode_number = getProp($episode, 'episode_number', 1);
  1117. $uid = Site::getUid();
  1118. $cpid = Site::getCpid();
  1119. try {
  1120. $target_scene_name = getProp($target_scenes, 'scene');
  1121. // 如果是删除操作
  1122. if ($is_deleted == 1) {
  1123. // 从场景列表中移除该场景
  1124. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1125. return getProp($scene, 'scene') !== $target_scene_name;
  1126. }));
  1127. // 更新场景列表
  1128. $result = DB::table('mp_anime_episodes')
  1129. ->where('anime_id', $anime_id)
  1130. ->where('id', $episode_id)
  1131. ->update([
  1132. 'scenes' => json_encode($scenes, 256),
  1133. 'updated_at' => date('Y-m-d H:i:s')
  1134. ]);
  1135. if ($result === false) {
  1136. Utils::throwError('20003:删除场景失败');
  1137. }
  1138. } else {
  1139. // 新增或更新操作
  1140. $scene_found = false;
  1141. $is_new_scene = false;
  1142. // 查找并更新已存在的场景
  1143. foreach($scenes as &$scene) {
  1144. if (getProp($scene, 'scene') === $target_scene_name) {
  1145. $scene = $target_scenes;
  1146. $scene_found = true;
  1147. break;
  1148. }
  1149. }
  1150. // 如果场景不存在,则新增
  1151. if (!$scene_found) {
  1152. $scenes[] = $target_scenes;
  1153. $is_new_scene = true;
  1154. }
  1155. // 更新场景列表
  1156. $result = DB::table('mp_anime_episodes')
  1157. ->where('anime_id', $anime_id)
  1158. ->where('id', $episode_id)
  1159. ->update([
  1160. 'scenes' => json_encode($scenes, 256),
  1161. 'updated_at' => date('Y-m-d H:i:s')
  1162. ]);
  1163. if ($result === false) {
  1164. Utils::throwError('20003:更新场景列表失败');
  1165. }
  1166. // 如果有关联的script_id,则同步到mp_products表
  1167. if ($script_id) {
  1168. // 查询剧本信息
  1169. $script = DB::table('mp_scripts')
  1170. ->where('id', $script_id)
  1171. ->where('is_deleted', 0)
  1172. ->first();
  1173. if ($script) {
  1174. $script_name = $script->script_name ?? 'script_' . $script_id;
  1175. $product_name = getProp($target_scenes, 'scene');
  1176. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1177. $url = getProp($target_scenes, 'url', '');
  1178. $product_type = 2; // 2=场景
  1179. // 查找或创建以script_name命名的文件夹
  1180. $folder = DB::table('mp_products')
  1181. ->where('cpid', $cpid)
  1182. ->where('type', 2) // 文件夹类型
  1183. ->where('product', $product_type) // 场景类型
  1184. ->where('product_name', $script_name)
  1185. ->where('parent_id', 0)
  1186. ->where('is_deleted', 0)
  1187. ->first();
  1188. if (!$folder) {
  1189. // 创建文件夹
  1190. $folder_id = DB::table('mp_products')->insertGetId([
  1191. 'user_id' => $uid,
  1192. 'cpid' => $cpid,
  1193. 'type' => 2, // 文件夹
  1194. 'product' => $product_type, // 场景类型
  1195. 'parent_id' => 0,
  1196. 'level' => 1,
  1197. 'product_name' => $script_name,
  1198. 'sort_order' => time(),
  1199. 'is_deleted' => 0,
  1200. 'created_at' => date('Y-m-d H:i:s'),
  1201. 'updated_at' => date('Y-m-d H:i:s')
  1202. ]);
  1203. } else {
  1204. $folder_id = $folder->id;
  1205. }
  1206. // 查找该文件夹下是否已存在同名资产
  1207. $existing_product = DB::table('mp_products')
  1208. ->where('cpid', $cpid)
  1209. ->where('type', 1) // 资产类型
  1210. ->where('product', $product_type)
  1211. ->where('parent_id', $folder_id)
  1212. ->where('product_name', $product_name)
  1213. ->where('is_deleted', 0)
  1214. ->first();
  1215. if ($existing_product) {
  1216. // 更新已存在的资产
  1217. $updateData = [
  1218. 'pic_task_status' => '生成成功'
  1219. ];
  1220. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1221. if ($url) $updateData['url'] = $url;
  1222. // 处理versions字段
  1223. $versions = getProp($target_scenes, 'versions', []);
  1224. if ($versions && is_array($versions)) {
  1225. $updateData['versions'] = json_encode($versions, 256);
  1226. }
  1227. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1228. DB::table('mp_products')
  1229. ->where('id', $existing_product->id)
  1230. ->update($updateData);
  1231. $product_id = $existing_product->id;
  1232. } else {
  1233. // 创建新资产
  1234. $versions = getProp($target_scenes, 'versions', []);
  1235. $product_id = DB::table('mp_products')->insertGetId([
  1236. 'user_id' => $uid,
  1237. 'cpid' => $cpid,
  1238. 'type' => 1, // 资产
  1239. 'product' => $product_type, // 场景
  1240. 'parent_id' => $folder_id,
  1241. 'level' => 2,
  1242. 'product_name' => $product_name,
  1243. 'url' => $url,
  1244. 'pic_prompt' => $pic_prompt,
  1245. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1246. 'sort_order' => time(),
  1247. 'is_deleted' => 0,
  1248. 'pic_task_status' => '生成成功',
  1249. 'created_at' => date('Y-m-d H:i:s'),
  1250. 'updated_at' => date('Y-m-d H:i:s')
  1251. ]);
  1252. }
  1253. // 建立或更新绑定关系
  1254. $existing_mapping = DB::table('mp_script_product_mappings')
  1255. ->where('script_id', $script_id)
  1256. ->where('product_id', $product_id)
  1257. ->where('episode_number', $episode_number)
  1258. ->first();
  1259. if (!$existing_mapping) {
  1260. // 创建绑定关系
  1261. DB::table('mp_script_product_mappings')->insert([
  1262. 'script_id' => $script_id,
  1263. 'product_id' => $product_id,
  1264. 'episode_number' => $episode_number,
  1265. 'created_at' => date('Y-m-d H:i:s'),
  1266. 'updated_at' => date('Y-m-d H:i:s')
  1267. ]);
  1268. }
  1269. }
  1270. }
  1271. }
  1272. } catch (\Exception $e) {
  1273. dLog('anime')->error('更新剧集场景失败', [
  1274. 'anime_id' => $anime_id,
  1275. 'episode_id' => $episode_id,
  1276. 'error' => $e->getMessage()
  1277. ]);
  1278. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1279. }
  1280. return true;
  1281. }
  1282. public function changeEpisodeProps($data) {
  1283. $anime_id = getProp($data, 'anime_id');
  1284. $episode_id = getProp($data, 'episode_id');
  1285. $target_props = getProp($data, 'props');
  1286. $is_deleted = getProp($data, 'is_deleted', 0);
  1287. // 参数验证
  1288. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1289. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1290. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1291. // 验证剧集是否存在
  1292. $episode = DB::table('mp_anime_episodes')
  1293. ->where('anime_id', $anime_id)
  1294. ->where('id', $episode_id)
  1295. ->first();
  1296. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1297. $props = json_decode(getProp($episode, 'props'), true);
  1298. // 获取anime信息,检查是否有关联的script_id
  1299. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1300. if (!$anime) Utils::throwError('20003:动漫不存在');
  1301. $script_id = getProp($anime, 'script_id');
  1302. $episode_number = getProp($episode, 'episode_number', 1);
  1303. $uid = Site::getUid();
  1304. $cpid = Site::getCpid();
  1305. try {
  1306. $target_prop_name = getProp($target_props, 'prop');
  1307. // 如果是删除操作
  1308. if ($is_deleted == 1) {
  1309. // 从道具列表中移除该道具
  1310. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1311. return getProp($prop, 'prop') !== $target_prop_name;
  1312. }));
  1313. // 更新道具列表
  1314. $result = DB::table('mp_anime_episodes')
  1315. ->where('anime_id', $anime_id)
  1316. ->where('id', $episode_id)
  1317. ->update([
  1318. 'props' => json_encode($props, 256),
  1319. 'updated_at' => date('Y-m-d H:i:s')
  1320. ]);
  1321. if ($result === false) {
  1322. Utils::throwError('20003:删除道具失败');
  1323. }
  1324. } else {
  1325. // 新增或更新操作
  1326. $prop_found = false;
  1327. $is_new_prop = false;
  1328. // 查找并更新已存在的道具
  1329. foreach($props as &$prop) {
  1330. if (getProp($prop, 'prop') === $target_prop_name) {
  1331. $prop = $target_props;
  1332. $prop_found = true;
  1333. break;
  1334. }
  1335. }
  1336. // 如果道具不存在,则新增
  1337. if (!$prop_found) {
  1338. $props[] = $target_props;
  1339. $is_new_prop = true;
  1340. }
  1341. // 更新道具列表
  1342. $result = DB::table('mp_anime_episodes')
  1343. ->where('anime_id', $anime_id)
  1344. ->where('id', $episode_id)
  1345. ->update([
  1346. 'props' => json_encode($props, 256),
  1347. 'updated_at' => date('Y-m-d H:i:s')
  1348. ]);
  1349. if ($result === false) {
  1350. Utils::throwError('20003:更新道具列表失败');
  1351. }
  1352. // 如果有关联的script_id,则同步到mp_products表
  1353. if ($script_id) {
  1354. // 查询剧本信息
  1355. $script = DB::table('mp_scripts')
  1356. ->where('id', $script_id)
  1357. ->where('is_deleted', 0)
  1358. ->first();
  1359. if ($script) {
  1360. $script_name = $script->script_name ?? 'script_' . $script_id;
  1361. $product_name = getProp($target_props, 'prop');
  1362. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1363. $url = getProp($target_props, 'url', '');
  1364. $product_type = 3; // 3=道具
  1365. // 查找或创建以script_name命名的文件夹
  1366. $folder = DB::table('mp_products')
  1367. ->where('cpid', $cpid)
  1368. ->where('type', 2) // 文件夹类型
  1369. ->where('product', $product_type) // 道具类型
  1370. ->where('product_name', $script_name)
  1371. ->where('parent_id', 0)
  1372. ->where('is_deleted', 0)
  1373. ->first();
  1374. if (!$folder) {
  1375. // 创建文件夹
  1376. $folder_id = DB::table('mp_products')->insertGetId([
  1377. 'user_id' => $uid,
  1378. 'cpid' => $cpid,
  1379. 'type' => 2, // 文件夹
  1380. 'product' => $product_type, // 道具类型
  1381. 'parent_id' => 0,
  1382. 'level' => 1,
  1383. 'product_name' => $script_name,
  1384. 'sort_order' => time(),
  1385. 'is_deleted' => 0,
  1386. 'created_at' => date('Y-m-d H:i:s'),
  1387. 'updated_at' => date('Y-m-d H:i:s')
  1388. ]);
  1389. } else {
  1390. $folder_id = $folder->id;
  1391. }
  1392. // 查找该文件夹下是否已存在同名资产
  1393. $existing_product = DB::table('mp_products')
  1394. ->where('cpid', $cpid)
  1395. ->where('type', 1) // 资产类型
  1396. ->where('product', $product_type)
  1397. ->where('parent_id', $folder_id)
  1398. ->where('product_name', $product_name)
  1399. ->where('is_deleted', 0)
  1400. ->first();
  1401. if ($existing_product) {
  1402. // 更新已存在的资产
  1403. $updateData = [
  1404. 'pic_task_status' => '生成成功'
  1405. ];
  1406. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1407. if ($url) $updateData['url'] = $url;
  1408. // 处理versions字段
  1409. $versions = getProp($target_props, 'versions', []);
  1410. if ($versions && is_array($versions)) {
  1411. $updateData['versions'] = json_encode($versions, 256);
  1412. }
  1413. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1414. DB::table('mp_products')
  1415. ->where('id', $existing_product->id)
  1416. ->update($updateData);
  1417. $product_id = $existing_product->id;
  1418. } else {
  1419. // 创建新资产
  1420. $versions = getProp($target_props, 'versions', []);
  1421. $product_id = DB::table('mp_products')->insertGetId([
  1422. 'user_id' => $uid,
  1423. 'cpid' => $cpid,
  1424. 'type' => 1, // 资产
  1425. 'product' => $product_type, // 道具
  1426. 'parent_id' => $folder_id,
  1427. 'level' => 2,
  1428. 'product_name' => $product_name,
  1429. 'url' => $url,
  1430. 'pic_prompt' => $pic_prompt,
  1431. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1432. 'sort_order' => time(),
  1433. 'is_deleted' => 0,
  1434. 'pic_task_status' => '生成成功',
  1435. 'created_at' => date('Y-m-d H:i:s'),
  1436. 'updated_at' => date('Y-m-d H:i:s')
  1437. ]);
  1438. }
  1439. // 建立或更新绑定关系
  1440. $existing_mapping = DB::table('mp_script_product_mappings')
  1441. ->where('script_id', $script_id)
  1442. ->where('product_id', $product_id)
  1443. ->where('episode_number', $episode_number)
  1444. ->first();
  1445. if (!$existing_mapping) {
  1446. // 创建绑定关系
  1447. DB::table('mp_script_product_mappings')->insert([
  1448. 'script_id' => $script_id,
  1449. 'product_id' => $product_id,
  1450. 'episode_number' => $episode_number,
  1451. 'created_at' => date('Y-m-d H:i:s'),
  1452. 'updated_at' => date('Y-m-d H:i:s')
  1453. ]);
  1454. }
  1455. }
  1456. }
  1457. }
  1458. } catch (\Exception $e) {
  1459. dLog('anime')->error('更新剧集道具失败', [
  1460. 'anime_id' => $anime_id,
  1461. 'episode_id' => $episode_id,
  1462. 'error' => $e->getMessage()
  1463. ]);
  1464. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1465. }
  1466. return true;
  1467. }
  1468. public function editSegment($data) {
  1469. $segment_id = getProp($data, 'segment_id');
  1470. $segment_content = getProp($data, 'segment_content');
  1471. $image_url = getProp($data, 'image_url');
  1472. $video_url = getProp($data, 'video_url');
  1473. // 参数验证
  1474. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1475. // 验证分镜是否存在
  1476. $segment = DB::table('mp_episode_segments')
  1477. ->where('segment_id', $segment_id)
  1478. ->first();
  1479. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1480. $dubTaskId = 0;
  1481. try {
  1482. DB::beginTransaction();
  1483. // 准备更新数据
  1484. $update_data = [
  1485. 'updated_at' => date('Y-m-d H:i:s')
  1486. ];
  1487. if ($segment_content) {
  1488. // 先将segment_content赋值到update_data
  1489. $update_data['segment_content'] = $segment_content;
  1490. // 使用现有方法分析segment_content,提取各个字段
  1491. $this->handleSegmentContent($update_data);
  1492. // 如果有对话内容,创建视频配音合成任务
  1493. $dialogue = getProp($update_data, 'dialogue');
  1494. if (!empty($dialogue)) {
  1495. $now = date('Y-m-d H:i:s');
  1496. $generate_json = [
  1497. 'text' => $dialogue,
  1498. 'role' => getProp($update_data, 'voice_actor'),
  1499. 'voice_type' => getProp($update_data, 'voice_type'),
  1500. 'voice_name' => getProp($update_data, 'voice_name'),
  1501. 'emotion' => getProp($update_data, 'emotion'),
  1502. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1503. 'gender' => getProp($update_data, 'gender'),
  1504. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1505. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1506. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1507. 'pitch' => getProp($update_data, 'pitch', 0),
  1508. ];
  1509. // 插入视频配音合成任务
  1510. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1511. 'alias_segment_id' => $segment_id,
  1512. 'generate_status' => '执行中',
  1513. 'audio_url' => '',
  1514. 'generate_json' => json_encode($generate_json, 256),
  1515. 'created_at' => $now,
  1516. 'updated_at' => $now,
  1517. ]);
  1518. if (!$dubTaskId) {
  1519. Utils::throwError('20003:创建配音任务失败!');
  1520. }
  1521. $update_data['audio_url'] = '';
  1522. } else {
  1523. // dialogue为空时,直接写入默认音频信息
  1524. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1525. $update_data['audio_duration'] = 2.0;
  1526. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1527. }
  1528. }
  1529. if ($image_url) {
  1530. $update_data['img_url'] = $image_url;
  1531. // 同时写入一个简单的图片生成任务
  1532. $pic_task = [
  1533. 'alias_segment_id' => $segment_id,
  1534. 'ref_img_url' => json_encode([]),
  1535. 'status' => 'success',
  1536. 'result_url' => json_encode([$image_url], 256),
  1537. 'model' => '',
  1538. 'created_at' => date('Y-m-d H:i:s'),
  1539. 'updated_at' => date('Y-m-d H:i:s'),
  1540. ];
  1541. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1542. }
  1543. if ($video_url) {
  1544. $update_data['origin_video_url'] = $video_url;
  1545. $compressed_video_url = compressVideo($video_url);
  1546. $update_data['current_type'] = 2;
  1547. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1548. // 同时写入一个简单的视频生成任务
  1549. $video_task = [
  1550. 'alias_segment_id' => $segment_id,
  1551. 'status' => 'success',
  1552. 'result_url' => $update_data['origin_video_url'],
  1553. 'compressed_url' => $update_data['video_url'],
  1554. 'created_at' => date('Y-m-d H:i:s'),
  1555. 'updated_at' => date('Y-m-d H:i:s'),
  1556. ];
  1557. DB::table('mp_generate_video_tasks')->insert($video_task);
  1558. }
  1559. // 更新分镜信息
  1560. $result = DB::table('mp_episode_segments')
  1561. ->where('segment_id', $segment_id)
  1562. ->update($update_data);
  1563. if ($result === false) {
  1564. Utils::throwError('20003:更新分镜剧本失败');
  1565. }
  1566. DB::commit();
  1567. // 如果有创建音频生成任务则调用API
  1568. if ($dubTaskId) {
  1569. // 请求远程服务器执行生成
  1570. $client = new Client(['timeout' => 300, 'verify' => false]);
  1571. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1572. $response = $result->getBody()->getContents();
  1573. $response_arr = json_decode($response, true);
  1574. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1575. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1576. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1577. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1578. Utils::throwError('20003:火山生成音频失败');
  1579. }
  1580. }
  1581. return true;
  1582. } catch (\Exception $e) {
  1583. DB::rollBack();
  1584. dLog('anime')->error('更新分镜剧本失败', [
  1585. 'segment_id' => $segment_id,
  1586. 'error' => $e->getMessage()
  1587. ]);
  1588. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1589. }
  1590. }
  1591. public function batchSetSegmentPics($data) {
  1592. $anime_id = getProp($data, 'anime_id');
  1593. $episode_id = getProp($data, 'episode_id');
  1594. $ratio = getProp($data, 'ratio');
  1595. $dimensions = $this->getRatioDimensions($ratio);
  1596. $width = $dimensions['width'];
  1597. $height = $dimensions['height'];
  1598. if (!$anime_id || !$episode_id) {
  1599. Utils::throwError('1002:请选择剧集');
  1600. }
  1601. // 获取剧集信息
  1602. $episode = DB::table('mp_anime_episodes')
  1603. ->where('anime_id', $anime_id)
  1604. ->where('id', $episode_id)
  1605. ->where('is_default', 1)
  1606. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1607. ->first();
  1608. if (!$episode) {
  1609. Utils::throwError('20003:该剧集不存在');
  1610. }
  1611. $model = getProp($data, 'model');
  1612. if (!$model) {
  1613. $model = getProp($episode, 'image_model');
  1614. if (!$model) {
  1615. // episode表也没有,使用默认值
  1616. $model = 'doubao-seedream-5-0-lite-260128';
  1617. }
  1618. }
  1619. // 验证模型是否在可用模型表中
  1620. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1621. $model = 'doubao-seedream-5-0-lite-260128';
  1622. }
  1623. $roles = json_decode(getProp($episode, 'roles'), true);
  1624. if (!$roles) {
  1625. Utils::throwError('20003:角色信息格式错误');
  1626. }
  1627. // 构建角色名称到参考图的映射
  1628. $role_map = [];
  1629. foreach ($roles as $role) {
  1630. $role_name = getProp($role, 'role');
  1631. $role_url = getProp($role, 'url');
  1632. if (!empty($role_name) && !empty($role_url)) {
  1633. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1634. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1635. // $role_map[$base_name] = $role_url;
  1636. // 同时保存完整名称的映射
  1637. $role_map[$role_name] = $role_url;
  1638. }
  1639. }
  1640. $scenes = json_decode(getProp($episode, 'roles'), true);
  1641. if (!$scenes) {
  1642. Utils::throwError('20003:场景信息格式错误');
  1643. }
  1644. // 构建角色名称到参考图的映射
  1645. $scene_map = [];
  1646. foreach ($scenes as $scene) {
  1647. $scene_name = getProp($scene, 'scene');
  1648. $scene_url = getProp($scene, 'url');
  1649. if (!empty($scene_name) && !empty($scene_url)) {
  1650. $scene_map[$scene_name] = $scene_url;
  1651. }
  1652. }
  1653. // 获取所有分镜信息
  1654. $segments = DB::table('mp_episode_segments')
  1655. ->where('anime_id', $anime_id)
  1656. ->where('episode_id', $episode_id)
  1657. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1658. ->orderBy('segment_number')
  1659. ->get()
  1660. ->toArray();
  1661. if (empty($segments)) {
  1662. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1663. }
  1664. // 保存图片比例
  1665. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1666. $updated_segments = [];
  1667. $failed_segments = [];
  1668. // 批量为每个分镜生成图片任务
  1669. foreach ($segments as $segment) {
  1670. $segment_id = $segment->segment_id;
  1671. $segment_content = $segment->segment_content;
  1672. if (empty($segment_content)) {
  1673. $failed_segments[] = [
  1674. 'segment_id' => $segment_id,
  1675. 'error' => '分镜内容为空'
  1676. ];
  1677. continue;
  1678. }
  1679. try {
  1680. $dubTaskId = 0;
  1681. // 解析分镜内容,提取画面描述作为主要提示词
  1682. $prompt = $segment_content;
  1683. $ref_img_urls = [];
  1684. // 分镜场景
  1685. $scene = getProp($segment, 'scene');
  1686. $matched_scene = '';
  1687. if (isset($scene_map[$scene])) {
  1688. $img_index = count($ref_img_urls) + 1;
  1689. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1690. $ref_img_urls[] = $scene_map[$scene];
  1691. $matched_scene = $scene;
  1692. }
  1693. // 分镜角色
  1694. $characters = getProp($segment, 'characters');
  1695. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1696. $roles = explode(',', $characters);
  1697. // 从分镜内容中提取涉及的角色
  1698. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1699. // 获取匹配角色的参考图
  1700. foreach ($segment_characters as $character) {
  1701. if (isset($role_map[$character])) {
  1702. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1703. $img_index = count($ref_img_urls) + 1;
  1704. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1705. $ref_img_urls[] = $role_map[$character];
  1706. }
  1707. }
  1708. // 如果没有找到匹配的角色参考图,不使用参考图
  1709. if (empty($ref_img_urls)) {
  1710. $ref_img_urls = [];
  1711. }
  1712. // 准备生成任务参数
  1713. $params = [
  1714. 'model' => $model,
  1715. 'alias_segment_id' => $segment_id,
  1716. 'prompt' => $prompt,
  1717. 'ref_img_urls' => $ref_img_urls,
  1718. 'width' => $width,
  1719. 'height' => $height,
  1720. ];
  1721. // 优化提示词(不要生成字幕)
  1722. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1723. // $task_id = mt_rand(100000, 999999);
  1724. // 调用AI图片生成服务
  1725. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1726. $task_id = $task->id;
  1727. if (!$task_id) {
  1728. $failed_segments[] = [
  1729. 'segment_id' => $segment_id,
  1730. 'error' => '创建生成任务失败'
  1731. ];
  1732. continue;
  1733. }
  1734. $update_data = [
  1735. 'pic_task_id' => $task_id,
  1736. 'pic_task_status' => '生成中',
  1737. 'audio_url' => '',
  1738. 'updated_at' => date('Y-m-d H:i:s')
  1739. ];
  1740. // 如果有对话内容,创建视频配音合成任务
  1741. $dialogue = getProp($segment, 'dialogue');
  1742. if (!empty($dialogue)) {
  1743. $now = date('Y-m-d H:i:s');
  1744. $generate_json = [
  1745. 'text' => $dialogue,
  1746. 'role' => getProp($segment, 'voice_actor'),
  1747. 'voice_type' => getProp($segment, 'voice_type'),
  1748. 'voice_name' => getProp($segment, 'voice_name'),
  1749. 'emotion' => getProp($segment, 'emotion'),
  1750. 'emotion_type' => getProp($segment, 'emotion_type'),
  1751. 'gender' => getProp($segment, 'gender'),
  1752. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1753. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1754. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1755. 'pitch' => getProp($segment, 'pitch', 0),
  1756. ];
  1757. // 插入视频配音合成任务
  1758. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1759. 'alias_segment_id' => $segment_id,
  1760. 'generate_status' => '执行中',
  1761. 'audio_url' => '',
  1762. 'generate_json' => json_encode($generate_json, 256),
  1763. 'created_at' => $now,
  1764. 'updated_at' => $now,
  1765. ]);
  1766. if (!$dubTaskId) {
  1767. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1768. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1769. // Utils::throwError('20003:创建配音任务失败!');
  1770. }
  1771. } else {
  1772. // dialogue为空时,直接写入默认音频信息到分镜表
  1773. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1774. $update_data['audio_duration'] = 2.0;
  1775. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1776. }
  1777. // 更新分镜的任务信息
  1778. $update_result = DB::table('mp_episode_segments')
  1779. ->where('segment_id', $segment_id)
  1780. ->update($update_data);
  1781. // 如果是第一集的首帧图片,则存入待更新数组
  1782. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1783. Redis::sadd('anime_first_frame_urls', $segment_id);
  1784. }
  1785. if ($update_result) {
  1786. $updated_segments[] = [
  1787. 'segment_id' => $segment_id,
  1788. 'task_id' => $task_id,
  1789. 'status' => '生成中',
  1790. 'matched_scenes' => $matched_scene,
  1791. 'matched_roles' => $segment_characters,
  1792. 'ref_urls_count' => count($ref_img_urls)
  1793. ];
  1794. } else {
  1795. $failed_segments[] = [
  1796. 'segment_id' => $segment_id,
  1797. 'error' => '更新分镜任务状态失败'
  1798. ];
  1799. }
  1800. if ($dubTaskId) {
  1801. sleep(1);
  1802. // 请求远程服务器执行生成
  1803. $client = new Client(['timeout' => 300, 'verify' => false]);
  1804. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1805. $response = $result->getBody()->getContents();
  1806. $response_arr = json_decode($response, true);
  1807. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1808. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1809. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1810. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1811. }
  1812. }
  1813. } catch (\Exception $e) {
  1814. $failed_segments[] = [
  1815. 'segment_id' => $segment_id,
  1816. 'error' => $e->getMessage()
  1817. ];
  1818. }
  1819. }
  1820. // 更新剧集生成状态
  1821. if (!empty($updated_segments)) {
  1822. DB::table('mp_anime_episodes')
  1823. ->where('id', $episode_id)
  1824. ->update([
  1825. 'is_generated' => 1,
  1826. 'updated_at' => date('Y-m-d H:i:s')
  1827. ]);
  1828. }
  1829. return [
  1830. 'success_count' => count($updated_segments),
  1831. 'failed_count' => count($failed_segments),
  1832. 'success_segments' => $updated_segments,
  1833. 'failed_segments' => $failed_segments,
  1834. 'total_segments' => count($segments)
  1835. ];
  1836. }
  1837. public function reGenerateSegment($data) {
  1838. $segment_id = getProp($data, 'segment_id');
  1839. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1840. $anime_id = getProp($segment, 'anime_id');
  1841. $episode_id = getProp($segment, 'episode_id');
  1842. $episode_number = getProp($segment, 'episode_number');
  1843. $segment_content = getProp($data, 'segment_content');
  1844. $ratio = getProp($data, 'ratio');
  1845. if (!$ratio) {
  1846. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1847. if (!$ratio) $ratio = '9:16';
  1848. }
  1849. $dimensions = $this->getRatioDimensions($ratio);
  1850. $width = $dimensions['width'];
  1851. $height = $dimensions['height'];
  1852. if (!$anime_id || !$episode_id) {
  1853. Utils::throwError('1002:请选择分镜');
  1854. }
  1855. // 使用文生文模型重新解析segment_content
  1856. if (!empty($segment_content)) {
  1857. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1858. }
  1859. // 获取动漫的角色信息(包含参考图)
  1860. $anime = DB::table('mp_animes')
  1861. ->where('id', $anime_id)
  1862. ->select('roles', 'scenes')
  1863. ->first();
  1864. if (!$anime || !$anime->roles) {
  1865. Utils::throwError('20003:未找到角色信息');
  1866. }
  1867. $roles = json_decode($anime->roles, true);
  1868. if (!$roles) {
  1869. Utils::throwError('20003:角色信息格式错误');
  1870. }
  1871. // 构建角色名称到参考图的映射
  1872. $role_map = [];
  1873. foreach ($roles as $role) {
  1874. $role_name = getProp($role, 'role');
  1875. $role_url = getProp($role, 'url');
  1876. if (!empty($role_name) && !empty($role_url)) {
  1877. $role_map[$role_name] = $role_url;
  1878. }
  1879. }
  1880. $scenes = json_decode($anime->scenes, true);
  1881. if (!$scenes) {
  1882. Utils::throwError('20003:角色信息格式错误');
  1883. }
  1884. // 构建角色名称到参考图的映射
  1885. $scene_map = [];
  1886. foreach ($scenes as $scene) {
  1887. $scene_name = getProp($scene, 'scene');
  1888. $scene_url = getProp($scene, 'url');
  1889. if (!empty($scene_name) && !empty($scene_url)) {
  1890. $scene_map[$scene_name] = $scene_url;
  1891. }
  1892. }
  1893. $segment_id = $segment->segment_id;
  1894. $original_segment_content = $segment->segment_content;
  1895. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1896. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1897. if (empty($final_segment_content)) {
  1898. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1899. }
  1900. try {
  1901. $dubTaskId = 0;
  1902. // 分镜剧本数组
  1903. $update_data = [
  1904. 'segment_content' => $final_segment_content,
  1905. 'pic_task_status' => '生成中',
  1906. 'updated_at' => date('Y-m-d H:i:s')
  1907. ];
  1908. // 解析分镜内容,提取画面描述作为主要提示词
  1909. $prompt = $final_segment_content;
  1910. $ref_img_urls = [];
  1911. // 分镜场景
  1912. $scene = getProp($data, 'scene');
  1913. if ($scene) {
  1914. $matched_scene = '';
  1915. if (isset($scene_map[$scene])) {
  1916. $img_index = count($ref_img_urls) + 1;
  1917. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1918. $ref_img_urls[] = $scene_map[$scene];
  1919. $matched_scene = $scene;
  1920. }
  1921. $update_data['scene'] = $scene;
  1922. }
  1923. // 分镜角色
  1924. $characters = getProp($data, 'characters');
  1925. if ($characters) {
  1926. $update_data['characters'] = $characters;
  1927. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1928. $characters = explode(',', $characters);
  1929. // 从分镜内容中提取涉及的角色
  1930. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1931. // 获取匹配角色的参考图
  1932. foreach ($segment_characters as $character) {
  1933. if (isset($role_map[$character])) {
  1934. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1935. $img_index = count($ref_img_urls) + 1;
  1936. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1937. $ref_img_urls[] = $role_map[$character];
  1938. }
  1939. }
  1940. }
  1941. // 如果没有找到匹配的角色参考图,不使用参考图
  1942. if (empty($ref_img_urls)) {
  1943. $ref_img_urls = [];
  1944. }
  1945. // 准备生成任务参数
  1946. $params = [
  1947. 'alias_segment_id' => $segment_id,
  1948. 'prompt' => $prompt,
  1949. 'ref_img_urls' => $ref_img_urls,
  1950. 'width' => $width,
  1951. 'height' => $height,
  1952. ];
  1953. // 优化提示词(不要生成字幕)
  1954. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1955. // 调用AI图片生成服务
  1956. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1957. $task_id = $task->id;
  1958. if (!$task_id) {
  1959. Utils::throwError('20003:创建生成任务失败!');
  1960. }
  1961. $update_data['pic_task_id'] = $task_id;
  1962. // 更新分镜剧本信息
  1963. $this->handleSegmentContent($update_data);
  1964. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1965. if ($segment_content) {
  1966. $dialogue = getProp($update_data, 'dialogue');
  1967. if (!empty($dialogue)) {
  1968. $now = date('Y-m-d H:i:s');
  1969. $generate_json = [
  1970. 'text' => $dialogue,
  1971. 'role' => getProp($update_data, 'voice_actor'),
  1972. 'voice_type' => getProp($update_data, 'voice_type'),
  1973. 'voice_name' => getProp($update_data, 'voice_name'),
  1974. 'emotion' => getProp($update_data, 'emotion'),
  1975. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1976. 'gender' => getProp($update_data, 'gender'),
  1977. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1978. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1979. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1980. 'pitch' => getProp($update_data, 'pitch', 0),
  1981. ];
  1982. // 插入视频配音合成任务
  1983. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1984. 'alias_segment_id' => $segment_id,
  1985. 'generate_status' => '执行中',
  1986. 'audio_url' => '',
  1987. 'generate_json' => json_encode($generate_json, 256),
  1988. 'created_at' => date('Y-m-d H:i:s'),
  1989. 'updated_at' => date('Y-m-d H:i:s'),
  1990. ]);
  1991. if (!$dubTaskId) {
  1992. Utils::throwError('20003:创建配音任务失败!');
  1993. }
  1994. $update_data['audio_url'] = '';
  1995. } else {
  1996. // dialogue为空时,直接写入默认音频信息
  1997. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1998. $update_data['audio_duration'] = 2.0;
  1999. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2000. }
  2001. }
  2002. $boolen = DB::table('mp_episode_segments')
  2003. ->where('segment_id', $segment_id)
  2004. ->update($update_data);
  2005. // 如果是第一集的首帧图片,则存入待更新数组
  2006. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2007. Redis::sadd('anime_first_frame_urls', $segment_id);
  2008. }
  2009. if ($dubTaskId) {
  2010. // 请求远程服务器执行生成
  2011. $client = new Client(['timeout' => 300, 'verify' => false]);
  2012. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2013. $response = $result->getBody()->getContents();
  2014. $response_arr = json_decode($response, true);
  2015. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2016. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2017. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2018. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2019. Utils::throwError('20003:火山生成音频失败');
  2020. }
  2021. }
  2022. } catch (\Exception $e) {
  2023. $failed_segments[] = [
  2024. 'segment_id' => $segment_id,
  2025. 'error' => $e->getMessage()
  2026. ];
  2027. }
  2028. // 创建任务之后先暂停10s等待异步任务完成
  2029. sleep(10);
  2030. $img_url = $this->loopGetPicTaskResult($task_id);
  2031. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2032. // 图片生成后新增对话记录
  2033. try {
  2034. $uid = Site::getUid();
  2035. $now = date('Y-m-d H:i:s');
  2036. // 使用AI反推图片提示词
  2037. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2038. // 保存对话记录
  2039. $records = [
  2040. [
  2041. 'uid' => $uid,
  2042. 'anime_id' => $anime_id,
  2043. 'sequence' => $episode_number,
  2044. 'role' => 'user',
  2045. 'content' => '重新生成',
  2046. 'segment_id' => $segment_id,
  2047. 'image_url' => '',
  2048. 'created_at' => $now,
  2049. 'updated_at' => $now
  2050. ],
  2051. [
  2052. 'uid' => $uid,
  2053. 'anime_id' => $anime_id,
  2054. 'sequence' => $episode_number,
  2055. 'role' => 'assistant',
  2056. 'content' => $pic_prompt,
  2057. 'segment_id' => $segment_id,
  2058. 'image_url' => $img_url,
  2059. 'created_at' => $now,
  2060. 'updated_at' => $now
  2061. ]
  2062. ];
  2063. DB::table('mp_anime_records')->insert($records);
  2064. } catch (\Exception $e) {
  2065. // 记录日志但不影响主流程
  2066. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2067. 'segment_id' => $segment_id,
  2068. 'img_url' => $img_url
  2069. ]);
  2070. }
  2071. return $img_url;
  2072. }
  2073. public function addSegment($data) {
  2074. $prev_segment_id = getProp($data, 'prev_segment_id');
  2075. $img_url = getProp($data, 'img_url');
  2076. $video_url = getProp($data, 'video_url');
  2077. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2078. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2079. $anime_id = getProp($segment, 'anime_id');
  2080. $episode_id = getProp($segment, 'episode_id');
  2081. $episode_number = getProp($segment, 'episode_number');
  2082. $segment_number = getProp($segment, 'segment_number');
  2083. $new_segment_number = $segment_number + 1;
  2084. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2085. // 分镜剧本数组
  2086. $insert_data = [
  2087. 'anime_id' => $anime_id,
  2088. 'episode_id' => $episode_id,
  2089. 'episode_number' => $episode_number,
  2090. 'act_number' => getProp($segment, 'act_number'),
  2091. 'act_title' => getProp($segment, 'act_title'),
  2092. 'segment_id' => $segment_id,
  2093. 'segment_number' => $new_segment_number,
  2094. 'segment_content' => '',
  2095. 'img_url' => '',
  2096. 'video_url' => '',
  2097. 'created_at' => date('Y-m-d H:i:s'),
  2098. 'updated_at' => date('Y-m-d H:i:s')
  2099. ];
  2100. if ($img_url) $insert_data['img_url'] = $img_url;
  2101. if ($video_url) {
  2102. $insert_data['origin_video_url'] = $video_url;
  2103. $insert_data['current_type'] = 2;
  2104. $compressed_video_url = compressVideo($video_url);
  2105. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2106. }
  2107. try {
  2108. DB::beginTransaction();
  2109. // 先更新序号
  2110. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2111. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2112. if (!$id) {
  2113. Utils::throwError('20003:新增分镜失败!');
  2114. }
  2115. }catch (\Exception $e) {
  2116. DB::rollBack();
  2117. Utils::throwError('20003:'.$e->getMessage());
  2118. }
  2119. DB::commit();
  2120. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2121. $segment = $segment ? (array)$segment : [];
  2122. return $segment;
  2123. // 以下代码暂弃用
  2124. $anime_id = getProp($segment, 'anime_id');
  2125. $episode_id = getProp($segment, 'episode_id');
  2126. $episode_number = getProp($segment, 'episode_number');
  2127. $segment_number = getProp($segment, 'segment_number');
  2128. $segment_content = getProp($data, 'segment_content');
  2129. $img_url = getProp($data, 'img_url');
  2130. $video_url = getProp($data, 'video_url');
  2131. $ratio = getProp($data, 'ratio');
  2132. $dimensions = $this->getRatioDimensions($ratio);
  2133. $width = $dimensions['width'];
  2134. $height = $dimensions['height'];
  2135. if (!$anime_id || !$episode_id) {
  2136. Utils::throwError('1002:请选择分镜');
  2137. }
  2138. // 使用文生文模型重新解析segment_content
  2139. if (!empty($segment_content)) {
  2140. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2141. }
  2142. // 获取动漫的角色信息(包含参考图)
  2143. $anime = DB::table('mp_animes')
  2144. ->where('id', $anime_id)
  2145. ->select('roles', 'scenes')
  2146. ->first();
  2147. if (!$anime || !$anime->roles) {
  2148. Utils::throwError('20003:未找到角色信息');
  2149. }
  2150. $roles = json_decode($anime->roles, true);
  2151. if (!$roles) {
  2152. Utils::throwError('20003:角色信息格式错误');
  2153. }
  2154. // 构建角色名称到参考图的映射
  2155. $role_map = [];
  2156. foreach ($roles as $role) {
  2157. $role_name = getProp($role, 'role');
  2158. $role_url = getProp($role, 'url');
  2159. if (!empty($role_name) && !empty($role_url)) {
  2160. $role_map[$role_name] = $role_url;
  2161. }
  2162. }
  2163. $scenes = json_decode($anime->scenes, true);
  2164. if (!$scenes) {
  2165. Utils::throwError('20003:角色信息格式错误');
  2166. }
  2167. // 构建角色名称到参考图的映射
  2168. $scene_map = [];
  2169. foreach ($scenes as $scene) {
  2170. $scene_name = getProp($scene, 'scene');
  2171. $scene_url = getProp($scene, 'url');
  2172. if (!empty($scene_name) && !empty($scene_url)) {
  2173. $scene_map[$scene_name] = $scene_url;
  2174. }
  2175. }
  2176. $segment_id = $segment->segment_id;
  2177. $original_segment_content = $segment->segment_content;
  2178. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2179. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2180. if (empty($final_segment_content)) {
  2181. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2182. }
  2183. try {
  2184. $dubTaskId = 0;
  2185. DB::beginTransaction();
  2186. $new_segment_number = $segment_number + 1;
  2187. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2188. // 分镜剧本数组
  2189. $insert_data = [
  2190. 'anime_id' => $anime_id,
  2191. 'episode_id' => $episode_id,
  2192. 'episode_number' => $episode_number,
  2193. 'act_number' => getProp($segment, 'act_number'),
  2194. 'act_title' => getProp($segment, 'act_title'),
  2195. 'segment_id' => $segment_id,
  2196. 'segment_number' => $new_segment_number,
  2197. 'segment_content' => $final_segment_content,
  2198. 'img_url' => $img_url,
  2199. 'video_url' => $video_url,
  2200. 'created_at' => date('Y-m-d H:i:s'),
  2201. 'updated_at' => date('Y-m-d H:i:s')
  2202. ];
  2203. // 更新分镜剧本信息
  2204. $this->handleSegmentContent($insert_data);
  2205. // 如果有对话内容,创建视频配音合成任务
  2206. $dialogue = getProp($insert_data, 'dialogue');
  2207. if (!empty($dialogue)) {
  2208. $now = date('Y-m-d H:i:s');
  2209. $generate_json = [
  2210. 'text' => $dialogue,
  2211. 'role' => getProp($insert_data, 'voice_actor'),
  2212. 'voice_type' => getProp($insert_data, 'voice_type'),
  2213. 'voice_name' => getProp($insert_data, 'voice_name'),
  2214. 'emotion' => getProp($insert_data, 'emotion'),
  2215. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2216. 'gender' => getProp($insert_data, 'gender'),
  2217. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2218. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2219. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2220. 'pitch' => getProp($insert_data, 'pitch', 0),
  2221. ];
  2222. // 插入视频配音合成任务
  2223. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2224. 'alias_segment_id' => $segment_id,
  2225. 'generate_status' => '执行中',
  2226. 'audio_url' => '',
  2227. 'generate_json' => json_encode($generate_json, 256),
  2228. 'created_at' => $now,
  2229. 'updated_at' => $now,
  2230. ]);
  2231. if (!$dubTaskId) {
  2232. Utils::throwError('20003:创建配音任务失败!');
  2233. }
  2234. $insert_data['audio_url'] = '';
  2235. } else {
  2236. // dialogue为空时,直接写入默认音频信息
  2237. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2238. $insert_data['audio_duration'] = 2.0;
  2239. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2240. }
  2241. // 如果没有上传图片则使用当前描述进行生成
  2242. if (!$img_url) {
  2243. // 解析分镜内容,提取画面描述作为主要提示词
  2244. $prompt = $final_segment_content;
  2245. $ref_img_urls = [];
  2246. // 分镜场景
  2247. $scene = getProp($insert_data, 'scene');
  2248. if ($scene) {
  2249. $matched_scene = '';
  2250. if (isset($scene_map[$scene])) {
  2251. $img_index = count($ref_img_urls) + 1;
  2252. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2253. $ref_img_urls[] = $scene_map[$scene];
  2254. $matched_scene = $scene;
  2255. }
  2256. $update_data['scene'] = $scene;
  2257. }
  2258. // 分镜角色
  2259. $characters = getProp($insert_data, 'characters');
  2260. if ($characters) {
  2261. $update_data['characters'] = $characters;
  2262. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2263. $characters = explode(',', $characters);
  2264. // 从分镜内容中提取涉及的角色
  2265. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2266. // 获取匹配角色的参考图
  2267. foreach ($segment_characters as $character) {
  2268. if (isset($role_map[$character])) {
  2269. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2270. $img_index = count($ref_img_urls) + 1;
  2271. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2272. $ref_img_urls[] = $role_map[$character];
  2273. }
  2274. }
  2275. }
  2276. // 如果没有找到匹配的角色参考图,不使用参考图
  2277. if (empty($ref_img_urls)) {
  2278. $ref_img_urls = [];
  2279. }
  2280. // 准备生成任务参数
  2281. $params = [
  2282. 'alias_segment_id' => $segment_id,
  2283. 'prompt' => $prompt,
  2284. 'ref_img_urls' => $ref_img_urls,
  2285. 'width' => $width,
  2286. 'height' => $height,
  2287. ];
  2288. // 调用AI图片生成服务
  2289. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2290. $task_id = $task->id;
  2291. // $task_id = 'whatever';
  2292. if (!$task_id) {
  2293. Utils::throwError('20003:创建生成任务失败!');
  2294. }
  2295. $insert_data['pic_task_status'] = '生成中';
  2296. $insert_data['pic_task_id'] = $task_id;
  2297. }
  2298. // 先更新序号
  2299. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2300. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2301. if (!$boolen) {
  2302. Utils::throwError('20003:新增分镜失败!');
  2303. }
  2304. // 如果是第一集的首帧图片,则存入待更新数组
  2305. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2306. Redis::sadd('anime_first_frame_urls', $segment_id);
  2307. }
  2308. if ($dubTaskId) {
  2309. // 请求远程服务器执行生成
  2310. $client = new Client(['timeout' => 300, 'verify' => false]);
  2311. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2312. $response = $result->getBody()->getContents();
  2313. $response_arr = json_decode($response, true);
  2314. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2315. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2316. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2317. Utils::throwError('20003:火山生成音频失败');
  2318. }
  2319. }
  2320. } catch (\Exception $e) {
  2321. DB::rollBack();
  2322. Utils::throwError('20003:'.$e->getMessage());
  2323. }
  2324. DB::commit();
  2325. // 创建任务之后先暂停10s等待异步任务完成
  2326. sleep(10);
  2327. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2328. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2329. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2330. $segment = $segment ? (array)$segment : [];
  2331. return $segment;
  2332. }
  2333. public function copySegment($data) {
  2334. $segment_id = getProp($data, 'segment_id');
  2335. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2336. if (!$segment) Utils::throwError('20003:请选择分镜');
  2337. $anime_id = getProp($segment, 'anime_id');
  2338. $episode_id = getProp($segment, 'episode_id');
  2339. $episode_number = getProp($segment, 'episode_number');
  2340. $segment_number = getProp($segment, 'segment_number');
  2341. $new_segment_id = 0;
  2342. try {
  2343. DB::beginTransaction();
  2344. $segment = (array)$segment;
  2345. unset($segment['id']);
  2346. $segment['segment_number'] += 1;
  2347. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2348. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2349. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2350. // 更新其他分镜序号
  2351. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2352. // 复制分镜
  2353. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2354. if (!$id) {
  2355. Utils::throwError('20003:复制分镜失败');
  2356. }
  2357. }catch (\Exception $e) {
  2358. DB::rollBack();
  2359. Utils::throwError('20003:'.$e->getMessage());
  2360. }
  2361. DB::commit();
  2362. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2363. $segment = $segment ? (array)$segment : [];
  2364. return $segment;
  2365. }
  2366. public function moveSegment($data) {
  2367. $segment_id = getProp($data, 'segment_id');
  2368. $target_segment_id = getProp($data, 'target_segment_id');
  2369. // 获取源分镜信息
  2370. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2371. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2372. // 获取目标分镜信息
  2373. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2374. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2375. $anime_id = getProp($source_segment, 'anime_id');
  2376. $episode_id = getProp($source_segment, 'episode_id');
  2377. $episode_number = getProp($source_segment, 'episode_number');
  2378. $source_segment_number = getProp($source_segment, 'segment_number');
  2379. $target_segment_number = getProp($target_segment, 'segment_number');
  2380. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2381. $target_anime_id = getProp($target_segment, 'anime_id');
  2382. $target_episode_number = getProp($target_segment, 'episode_number');
  2383. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2384. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2385. }
  2386. // 如果源分镜和目标分镜相同,无需移动
  2387. if ($source_segment_number == $target_segment_number) {
  2388. return true;
  2389. }
  2390. try {
  2391. DB::beginTransaction();
  2392. if ($source_segment_number < $target_segment_number) {
  2393. // 向后移动:源分镜移动到目标分镜之后
  2394. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2395. DB::table('mp_episode_segments')
  2396. ->where('anime_id', $anime_id)
  2397. ->where('episode_id', $episode_id)
  2398. ->where('segment_number', '>', $source_segment_number)
  2399. ->where('segment_number', '<=', $target_segment_number)
  2400. ->decrement('segment_number');
  2401. // 2. 将源分镜移动到目标分镜之后
  2402. $new_segment_number = $target_segment_number;
  2403. } else {
  2404. // 向前移动:源分镜移动到目标分镜之后
  2405. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2406. DB::table('mp_episode_segments')
  2407. ->where('anime_id', $anime_id)
  2408. ->where('episode_id', $episode_id)
  2409. ->where('segment_number', '>', $target_segment_number)
  2410. ->where('segment_number', '<', $source_segment_number)
  2411. ->increment('segment_number');
  2412. // 2. 将源分镜移动到目标分镜之后
  2413. $new_segment_number = $target_segment_number + 1;
  2414. }
  2415. // 3. 更新源分镜的序号
  2416. $update_result = DB::table('mp_episode_segments')
  2417. ->where('segment_id', $segment_id)
  2418. ->update([
  2419. 'segment_number' => $new_segment_number,
  2420. 'updated_at' => date('Y-m-d H:i:s')
  2421. ]);
  2422. if (!$update_result) {
  2423. Utils::throwError('20003:更新分镜序号失败');
  2424. }
  2425. DB::commit();
  2426. return true;
  2427. } catch (\Exception $e) {
  2428. DB::rollBack();
  2429. Utils::throwError('20003:' . $e->getMessage());
  2430. }
  2431. }
  2432. public function delSegment($data) {
  2433. $segment_id = getProp($data, 'segment_id');
  2434. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2435. if (!$segment) Utils::throwError('20003:请选择分镜');
  2436. $anime_id = getProp($segment, 'anime_id');
  2437. $episode_id = getProp($segment, 'episode_id');
  2438. $episode_number = getProp($segment, 'episode_number');
  2439. $segment_number = getProp($segment, 'segment_number');
  2440. try {
  2441. DB::beginTransaction();
  2442. // 删除分镜
  2443. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2444. if (!$boolen) {
  2445. Utils::throwError('20003:删除分镜失败');
  2446. }
  2447. // 更新其他分镜序号
  2448. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2449. }catch (\Exception $e) {
  2450. DB::rollBack();
  2451. Utils::throwError('20003:'.$e->getMessage());
  2452. }
  2453. DB::commit();
  2454. return true;
  2455. }
  2456. public function applySegment($data) {
  2457. $segment_id = getProp($data, 'segment_id');
  2458. $url = getProp($data, 'url');
  2459. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2460. if (!$url) Utils::throwError('20003:URL不能为空');
  2461. // 获取URL的文件扩展名
  2462. $urlPath = parse_url($url, PHP_URL_PATH);
  2463. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2464. // 定义图片和视频的扩展名
  2465. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2466. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2467. // 判断是图片还是视频
  2468. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2469. if (in_array($extension, $imageExtensions)) {
  2470. // 图片类型
  2471. $updateData['img_url'] = $url;
  2472. $updateData['current_type'] = 1;
  2473. } elseif (in_array($extension, $videoExtensions)) {
  2474. // 视频类型
  2475. $updateData['video_url'] = $url;
  2476. $updateData['current_type'] = 2;
  2477. } else {
  2478. Utils::throwError('20003:不支持的文件类型');
  2479. }
  2480. // 更新分镜表
  2481. $result = DB::table('mp_episode_segments')
  2482. ->where('segment_id', $segment_id)
  2483. ->update($updateData);
  2484. if (!$result) {
  2485. Utils::throwError('20003:更新分镜失败');
  2486. }
  2487. return true;
  2488. }
  2489. public function segmentHistory($data) {
  2490. $segment_id = getProp($data, 'segment_id');
  2491. // 获取历史图片
  2492. $pics = [];
  2493. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2494. foreach($pic_history as $task) {
  2495. $result_url = getProp($task, 'result_url');
  2496. if (is_json($result_url)) {
  2497. $pics = array_merge($pics, json_decode($result_url, true));
  2498. }else {
  2499. $pics[] = $result_url;
  2500. }
  2501. }
  2502. // 获取历史视频
  2503. $videos = [];
  2504. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2505. foreach($video_history as $task) {
  2506. $result_url = getProp($task, 'result_url');
  2507. if (is_json($result_url)) {
  2508. $videos = array_merge($videos, json_decode($result_url, true));
  2509. }else {
  2510. $videos[] = $result_url;
  2511. }
  2512. }
  2513. return compact('pics', 'videos');
  2514. }
  2515. public function addAct($data) {
  2516. $prev_act_id = getProp($data, 'prev_act_id');
  2517. $act_title = getProp($data, 'act_title', '');
  2518. $act_content = getProp($data, 'act_content', '');
  2519. $act_duration = getProp($data, 'act_duration', 5);
  2520. $video_url = getProp($data, 'video_url');
  2521. // 根据prev_act_id获取记录
  2522. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2523. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2524. $anime_id = getProp($prev_segment, 'anime_id');
  2525. $episode_id = getProp($prev_segment, 'episode_id');
  2526. $episode_number = getProp($prev_segment, 'episode_number');
  2527. $prev_act_number = getProp($prev_segment, 'act_number');
  2528. // 获取新的act_number
  2529. $new_act_number = $prev_act_number + 1;
  2530. try {
  2531. DB::beginTransaction();
  2532. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2533. DB::table('mp_episode_segments')
  2534. ->where('anime_id', $anime_id)
  2535. ->where('episode_id', $episode_id)
  2536. ->where('act_number', '>', $prev_act_number)
  2537. ->increment('act_number');
  2538. // 插入新片段记录
  2539. $insert_data = [
  2540. 'anime_id' => $anime_id,
  2541. 'episode_id' => $episode_id,
  2542. 'episode_number' => $episode_number,
  2543. 'act_number' => $new_act_number,
  2544. 'created_at' => date('Y-m-d H:i:s'),
  2545. 'updated_at' => date('Y-m-d H:i:s')
  2546. ];
  2547. if ($act_title) {
  2548. $insert_data['act_title'] = $act_title;
  2549. }
  2550. if ($act_content) {
  2551. $insert_data['act_content'] = $act_content;
  2552. }
  2553. if ($act_duration) {
  2554. $insert_data['act_duration'] = $act_duration;
  2555. }
  2556. if ($video_url) {
  2557. $insert_data['origin_video_url'] = $video_url;
  2558. $insert_data['current_type'] = 2;
  2559. $compressed_video_url = compressVideo($video_url);
  2560. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2561. }
  2562. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2563. if (!$id) {
  2564. Utils::throwError('20003:新增片段失败!');
  2565. }
  2566. DB::commit();
  2567. }catch (\Exception $e) {
  2568. DB::rollBack();
  2569. Utils::throwError('20003:'.$e->getMessage());
  2570. }
  2571. $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();
  2572. $segment = $segment ? (array)$segment : [];
  2573. return $segment;
  2574. }
  2575. public function editAct($data) {
  2576. $act_id = getProp($data, 'act_id');
  2577. $act_content = getProp($data, 'act_content');
  2578. $act_duration = getProp($data, 'act_duration');
  2579. $act_title = getProp($data, 'act_title');
  2580. $image_url = getProp($data, 'image_url');
  2581. $video_url = getProp($data, 'video_url');
  2582. // 参数验证
  2583. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2584. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2585. $segment = DB::table('mp_episode_segments')
  2586. ->where('id', $act_id)
  2587. ->first();
  2588. if (!$segment) Utils::throwError('20003:该片段不存在');
  2589. try {
  2590. DB::beginTransaction();
  2591. // 准备更新数据
  2592. $update_data = [
  2593. 'updated_at' => date('Y-m-d H:i:s')
  2594. ];
  2595. // 更新act相关字段
  2596. if (!empty($act_content)) {
  2597. $update_data['act_show_content'] = $act_content;
  2598. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2599. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2600. $shot_counter = 0;
  2601. $update_data['act_show_content'] = preg_replace_callback(
  2602. '/【(?:镜头|分镜)(\d+)】/u',
  2603. function($matches) use (&$shot_counter) {
  2604. $shot_counter++;
  2605. return '【镜头' . $shot_counter . '】';
  2606. },
  2607. $update_data['act_show_content']
  2608. );
  2609. }
  2610. if (!empty($act_duration)) {
  2611. $update_data['act_duration'] = $act_duration;
  2612. }
  2613. if (!empty($act_title)) {
  2614. $update_data['act_title'] = $act_title;
  2615. }
  2616. // 处理图片上传
  2617. if ($image_url) {
  2618. $update_data['img_url'] = $image_url;
  2619. $update_data['current_type'] = 1;
  2620. // 同时写入一个图片生成任务记录
  2621. if ($act_id) {
  2622. $pic_task = [
  2623. 'alias_act_id' => $act_id,
  2624. 'ref_img_url' => json_encode([]),
  2625. 'status' => 'success',
  2626. 'result_url' => json_encode([$image_url], 256),
  2627. 'model' => '',
  2628. 'created_at' => date('Y-m-d H:i:s'),
  2629. 'updated_at' => date('Y-m-d H:i:s'),
  2630. ];
  2631. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2632. }
  2633. }
  2634. // 处理视频上传
  2635. if ($video_url) {
  2636. $update_data['origin_video_url'] = $video_url;
  2637. $compressed_video_url = compressVideo($video_url);
  2638. $update_data['current_type'] = 2;
  2639. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2640. // 同时写入一个视频生成任务记录
  2641. if ($act_id) {
  2642. $video_task = [
  2643. 'alias_act_id' => $act_id,
  2644. 'status' => 'success',
  2645. 'result_url' => $update_data['origin_video_url'],
  2646. 'compressed_url' => $update_data['video_url'],
  2647. 'created_at' => date('Y-m-d H:i:s'),
  2648. 'updated_at' => date('Y-m-d H:i:s'),
  2649. ];
  2650. DB::table('mp_generate_video_tasks')->insert($video_task);
  2651. }
  2652. }
  2653. // 更新片段信息
  2654. $result = DB::table('mp_episode_segments')
  2655. ->where('id', $act_id)
  2656. ->update($update_data);
  2657. if ($result === false) {
  2658. Utils::throwError('20003:更新片段失败');
  2659. }
  2660. DB::commit();
  2661. // 返回新复制的记录
  2662. $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();
  2663. $new_segment = (array)$new_segment;
  2664. return $new_segment;
  2665. } catch (\Exception $e) {
  2666. DB::rollBack();
  2667. dLog('anime')->error('更新片段失败', [
  2668. 'act_id' => $act_id,
  2669. 'error' => $e->getMessage()
  2670. ]);
  2671. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2672. }
  2673. }
  2674. public function copyAct($data) {
  2675. $act_id = getProp($data, 'act_id');
  2676. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2677. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2678. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2679. $anime_id = getProp($source_segment, 'anime_id');
  2680. $episode_id = getProp($source_segment, 'episode_id');
  2681. $episode_number = getProp($source_segment, 'episode_number');
  2682. $act_number = getProp($source_segment, 'act_number');
  2683. try {
  2684. DB::beginTransaction();
  2685. // 新act的编号
  2686. $new_act_number = $act_number + 1;
  2687. // 更新后续所有act的act_number
  2688. DB::table('mp_episode_segments')
  2689. ->where('anime_id', $anime_id)
  2690. ->where('episode_id', $episode_id)
  2691. ->where('act_number', '>', $act_number)
  2692. ->increment('act_number');
  2693. // 复制该片段记录
  2694. $segment_data = (array)$source_segment;
  2695. unset($segment_data['id']);
  2696. $segment_data['video_url'] = '';
  2697. $segment_data['video_task_id'] = '';
  2698. $segment_data['video_task_status'] = '';
  2699. $segment_data['act_number'] = $new_act_number;
  2700. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2701. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2702. if (!$id) {
  2703. Utils::throwError('20003:复制片段失败');
  2704. }
  2705. DB::commit();
  2706. }catch (\Exception $e) {
  2707. DB::rollBack();
  2708. Utils::throwError('20003:'.$e->getMessage());
  2709. }
  2710. // 返回新复制的记录
  2711. $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();
  2712. $new_segment = $new_segment ? (array)$new_segment : [];
  2713. $new_segment['act_id'] = $id;
  2714. return $new_segment;
  2715. }
  2716. public function moveAct($data) {
  2717. $act_id = getProp($data, 'act_id');
  2718. $target_act_id = getProp($data, 'target_act_id');
  2719. // 获取源片段信息
  2720. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2721. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2722. // 获取目标片段信息
  2723. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2724. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2725. $anime_id = getProp($source_segment, 'anime_id');
  2726. $episode_id = getProp($source_segment, 'episode_id');
  2727. $source_act_number = getProp($source_segment, 'act_number');
  2728. $target_act_number = getProp($target_segment, 'act_number');
  2729. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2730. $target_anime_id = getProp($target_segment, 'anime_id');
  2731. $target_episode_id = getProp($target_segment, 'episode_id');
  2732. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2733. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2734. }
  2735. // 如果源片段和目标片段相同,无需移动
  2736. if ($source_act_number == $target_act_number) {
  2737. return true;
  2738. }
  2739. try {
  2740. DB::beginTransaction();
  2741. if ($source_act_number < $target_act_number) {
  2742. // 向后移动:源片段移动到目标片段之后
  2743. // 1. 将源片段和目标片段之间的所有片段编号减1
  2744. DB::table('mp_episode_segments')
  2745. ->where('anime_id', $anime_id)
  2746. ->where('episode_id', $episode_id)
  2747. ->where('act_number', '>', $source_act_number)
  2748. ->where('act_number', '<=', $target_act_number)
  2749. ->decrement('act_number');
  2750. // 2. 将源片段移动到目标片段之后
  2751. $new_act_number = $target_act_number;
  2752. } else {
  2753. // 向前移动:源片段移动到目标片段之后
  2754. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2755. DB::table('mp_episode_segments')
  2756. ->where('anime_id', $anime_id)
  2757. ->where('episode_id', $episode_id)
  2758. ->where('act_number', '>', $target_act_number)
  2759. ->where('act_number', '<', $source_act_number)
  2760. ->increment('act_number');
  2761. // 2. 将源片段移动到目标片段之后
  2762. $new_act_number = $target_act_number + 1;
  2763. }
  2764. // 3. 更新源片段的编号
  2765. $update_result = DB::table('mp_episode_segments')
  2766. ->where('id', $act_id)
  2767. ->update([
  2768. 'act_number' => $new_act_number,
  2769. 'updated_at' => date('Y-m-d H:i:s')
  2770. ]);
  2771. if (!$update_result) {
  2772. Utils::throwError('20003:更新片段编号失败');
  2773. }
  2774. DB::commit();
  2775. return true;
  2776. } catch (\Exception $e) {
  2777. DB::rollBack();
  2778. Utils::throwError('20003:' . $e->getMessage());
  2779. }
  2780. }
  2781. public function delAct($data) {
  2782. $act_id = getProp($data, 'act_id');
  2783. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2784. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2785. if (!$segment) Utils::throwError('20003:请选择片段');
  2786. $anime_id = getProp($segment, 'anime_id');
  2787. $episode_id = getProp($segment, 'episode_id');
  2788. $act_number = getProp($segment, 'act_number');
  2789. try {
  2790. DB::beginTransaction();
  2791. // 删除该片段记录
  2792. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2793. if (!$deleted) {
  2794. Utils::throwError('20003:删除片段失败');
  2795. }
  2796. // 更新后续act的编号
  2797. DB::table('mp_episode_segments')
  2798. ->where('anime_id', $anime_id)
  2799. ->where('episode_id', $episode_id)
  2800. ->where('act_number', '>', $act_number)
  2801. ->decrement('act_number');
  2802. DB::commit();
  2803. }catch (\Exception $e) {
  2804. DB::rollBack();
  2805. Utils::throwError('20003:'.$e->getMessage());
  2806. }
  2807. return true;
  2808. }
  2809. public function applyAct($data) {
  2810. $act_id = getProp($data, 'act_id');
  2811. $url = getProp($data, 'url');
  2812. if (!$act_id) Utils::throwError('20003:请选择片段');
  2813. if (!$url) Utils::throwError('20003:URL不能为空');
  2814. // 获取URL的文件扩展名
  2815. $urlPath = parse_url($url, PHP_URL_PATH);
  2816. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2817. // 定义图片和视频的扩展名
  2818. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2819. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2820. // 判断是图片还是视频
  2821. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2822. if (in_array($extension, $imageExtensions)) {
  2823. // 图片类型
  2824. $updateData['img_url'] = $url;
  2825. $updateData['current_type'] = 1;
  2826. } elseif (in_array($extension, $videoExtensions)) {
  2827. // 视频类型
  2828. $updateData['video_url'] = $url;
  2829. $updateData['current_type'] = 2;
  2830. } else {
  2831. Utils::throwError('20003:不支持的文件类型');
  2832. }
  2833. // 更新片段记录(全能模式下每个act只有一条记录)
  2834. $result = DB::table('mp_episode_segments')
  2835. ->where('id', $act_id)
  2836. ->update($updateData);
  2837. if (!$result) {
  2838. Utils::throwError('20003:更新片段失败');
  2839. }
  2840. return true;
  2841. }
  2842. public function actChatHistory($data) {
  2843. $act_id = getProp($data, 'act_id');
  2844. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2845. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2846. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2847. $value = (array)$value;
  2848. $value['created_at'] = transDate($value['created_at']);
  2849. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2850. else $value['reference_images'] = [];
  2851. return $value;
  2852. })->toArray();
  2853. // 获取历史图片
  2854. $url = [];
  2855. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2856. foreach($pic_history as $task) {
  2857. $result_url = getProp($task, 'result_url');
  2858. if (is_json($result_url)) {
  2859. $url = array_merge($url, json_decode($result_url, true));
  2860. }else {
  2861. $url[] = $result_url;
  2862. }
  2863. }
  2864. // 获取历史视频
  2865. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2866. foreach($video_history as $task) {
  2867. $result_url = getProp($task, 'result_url');
  2868. if (is_json($result_url)) {
  2869. $url = array_merge($url, json_decode($result_url, true));
  2870. }else {
  2871. $url[] = $result_url;
  2872. }
  2873. }
  2874. // 获取资产库
  2875. $products = [];
  2876. // 通过act_id查询片段信息获取episode_id
  2877. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2878. if ($segment) {
  2879. $episode_id = getProp($segment, 'episode_id');
  2880. // 查询剧集信息获取roles、scenes和extra_products
  2881. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2882. if ($episode) {
  2883. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2884. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2885. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2886. // 先合并roles和scenes
  2887. // 处理角色数组
  2888. foreach ($roles as $role) {
  2889. $product = $role;
  2890. // 将role字段重命名为product_name
  2891. if (isset($product['role'])) {
  2892. $product['product_name'] = $product['role'];
  2893. unset($product['role']);
  2894. }
  2895. $product['product'] = 1; // 标记类型为角色
  2896. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2897. }
  2898. // 处理场景数组
  2899. foreach ($scenes as $scene) {
  2900. $product = $scene;
  2901. // 将scene字段重命名为product_name
  2902. if (isset($product['scene'])) {
  2903. $product['product_name'] = $product['scene'];
  2904. unset($product['scene']);
  2905. }
  2906. $product['product'] = 2; // 标记类型为场景
  2907. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2908. }
  2909. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2910. foreach ($extra_products as $extra_product) {
  2911. $product_name = getProp($extra_product, 'product_name');
  2912. if ($product_name) {
  2913. $products[$product_name] = $extra_product; // 覆盖同名数据
  2914. }
  2915. }
  2916. // 重新索引数组(去除key)
  2917. $products = array_values($products);
  2918. }
  2919. }
  2920. // 获取执行中的任务
  2921. $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) {
  2922. $value = (array)$value;
  2923. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2924. else $value['ref_image_url'] = [];
  2925. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2926. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2927. if (!empty($value['prompt'])) {
  2928. $prompt = $value['prompt'];
  2929. // 查找第一个【镜头】的位置
  2930. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2931. // 从【镜头】开始截取
  2932. $prompt = substr($prompt, $matches[0][1]);
  2933. }
  2934. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2935. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2936. $value['prompt'] = $prompt;
  2937. }
  2938. return $value;
  2939. })->toArray();
  2940. return compact('chat', 'url', 'products', 'tasks');
  2941. }
  2942. public function applyAudioData($data) {
  2943. $segment_id = getProp($data, 'segment_id');
  2944. $global_data = getProp($data, 'global_data');
  2945. $segment_data = getProp($data, 'segment_data');
  2946. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2947. $global_data = is_array($global_data) ? $global_data : [];
  2948. $segment_data = is_array($segment_data) ? $segment_data : [];
  2949. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2950. $dialogue_item = null;
  2951. foreach ($global_data as $key => $item) {
  2952. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2953. $dialogue_item = $item;
  2954. unset($global_data[$key]);
  2955. break;
  2956. }
  2957. }
  2958. if ($dialogue_item) {
  2959. $segment_data[] = $dialogue_item;
  2960. }
  2961. // 特殊参数: audio_url,audio_duration,subtitle_info
  2962. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2963. // 如果不是全部存在,则仍需创建音频任务
  2964. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2965. $special_update_data = [];
  2966. $has_all_special_params = false;
  2967. // 从segment_data中提取特殊参数
  2968. $filtered_segment_data = [];
  2969. foreach ($segment_data as $item) {
  2970. $field_name = trim((string)getProp($item, 'name'));
  2971. if (in_array($field_name, $special_fields)) {
  2972. $special_update_data[$field_name] = getProp($item, 'value');
  2973. } else {
  2974. // 非特殊参数保留,继续后续处理
  2975. $filtered_segment_data[] = $item;
  2976. }
  2977. }
  2978. // 检查是否三个特殊参数都存在
  2979. if (count($special_update_data) === 3 &&
  2980. isset($special_update_data['audio_url']) &&
  2981. isset($special_update_data['audio_duration']) &&
  2982. isset($special_update_data['subtitle_info'])) {
  2983. $has_all_special_params = true;
  2984. // 立即更新到当前分镜
  2985. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2986. DB::table('mp_episode_segments')
  2987. ->where('segment_id', $segment_id)
  2988. ->update($special_update_data);
  2989. }
  2990. // 使用过滤后的segment_data继续处理其他参数
  2991. $segment_data = $filtered_segment_data;
  2992. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2993. $global_update_data = [];
  2994. $segment_update_data = [];
  2995. $global_voice_type = '';
  2996. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2997. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2998. $episode_id = getProp($target_segment, 'episode_id');
  2999. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3000. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3001. if (!$episode) Utils::throwError('20003:分集不存在');
  3002. foreach ($global_data as $item) {
  3003. $field_name = trim((string)getProp($item, 'name'));
  3004. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3005. continue;
  3006. }
  3007. $global_update_data[$field_name] = getProp($item, 'value');
  3008. if ($field_name === 'voice_type') {
  3009. $global_voice_type = trim((string)getProp($item, 'value'));
  3010. }
  3011. }
  3012. foreach ($segment_data as $item) {
  3013. $field_name = trim((string)getProp($item, 'name'));
  3014. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3015. continue;
  3016. }
  3017. $segment_update_data[$field_name] = getProp($item, 'value');
  3018. }
  3019. if ($global_voice_type) {
  3020. $timbre_info = DB::table('mp_timbres')
  3021. ->where('timbre_type', $global_voice_type)
  3022. ->select('audio_url', 'timbre_name')
  3023. ->first();
  3024. if ($timbre_info) {
  3025. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3026. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3027. }
  3028. }
  3029. try {
  3030. DB::beginTransaction();
  3031. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3032. $segment_ids_to_create_task = [];
  3033. $segments_data = [];
  3034. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3035. if (!empty($global_update_data)) {
  3036. // 如果角色不存在,则只更新当前分镜
  3037. if (!$target_voice_actor) {
  3038. // 只处理当前分镜
  3039. $affected_segments = DB::table('mp_episode_segments')
  3040. ->where('segment_id', $segment_id)
  3041. ->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')
  3042. ->get();
  3043. } else {
  3044. // 获取该角色的所有分镜
  3045. $affected_segments = DB::table('mp_episode_segments')
  3046. ->where('episode_id', $episode_id)
  3047. ->where('voice_actor', $target_voice_actor)
  3048. ->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')
  3049. ->get();
  3050. }
  3051. foreach ($affected_segments as $seg) {
  3052. $seg = (array)$seg;
  3053. $sid = getProp($seg, 'segment_id');
  3054. // 检查参数是否发生变化
  3055. $has_changed = false;
  3056. foreach ($global_update_data as $field => $new_value) {
  3057. $old_value = getProp($seg, $field);
  3058. if ($old_value != $new_value) {
  3059. $has_changed = true;
  3060. break;
  3061. }
  3062. }
  3063. if ($has_changed) {
  3064. $segment_ids_to_create_task[] = $sid;
  3065. $segments_data[$sid] = $seg;
  3066. }
  3067. }
  3068. // 只有在有变化的分镜时才更新
  3069. if (!empty($segment_ids_to_create_task)) {
  3070. $global_segment_update_data = $global_update_data;
  3071. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3072. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3073. DB::table('mp_episode_segments')
  3074. ->where('episode_id', $episode_id)
  3075. ->where('voice_actor', $target_voice_actor)
  3076. ->whereIn('segment_id', $segment_ids_to_create_task)
  3077. ->update($global_segment_update_data);
  3078. }
  3079. if ($global_voice_type) {
  3080. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3081. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3082. $roles_updated = false;
  3083. foreach ($episode_roles as &$role) {
  3084. // 通过 role 字段匹配角色名,而不是 voice_name
  3085. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3086. continue;
  3087. }
  3088. $role['voice_type'] = $global_voice_type;
  3089. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3090. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3091. $roles_updated = true;
  3092. }
  3093. unset($role);
  3094. if ($roles_updated) {
  3095. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3096. 'roles' => json_encode($episode_roles, 256),
  3097. 'updated_at' => date('Y-m-d H:i:s'),
  3098. ]);
  3099. }
  3100. }
  3101. }
  3102. // 如果有单个分镜更新,检查是否有变化
  3103. if (!empty($segment_update_data)) {
  3104. // 获取当前分镜数据
  3105. $current_segment = DB::table('mp_episode_segments')
  3106. ->where('segment_id', $segment_id)
  3107. ->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')
  3108. ->first();
  3109. if ($current_segment) {
  3110. $current_segment = (array)$current_segment;
  3111. // 检查参数是否发生变化
  3112. $has_changed = false;
  3113. foreach ($segment_update_data as $field => $new_value) {
  3114. $old_value = getProp($current_segment, $field);
  3115. if ($old_value != $new_value) {
  3116. $has_changed = true;
  3117. break;
  3118. }
  3119. }
  3120. if ($has_changed) {
  3121. // 如果该分镜还未在列表中,添加进去
  3122. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3123. $segment_ids_to_create_task[] = $segment_id;
  3124. $segments_data[$segment_id] = $current_segment;
  3125. }
  3126. // 更新分镜数据并清空音频URL
  3127. $segment_update_data['audio_url'] = '';
  3128. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3129. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3130. }
  3131. }
  3132. }
  3133. // 为所有有变化的分镜创建音频合成任务
  3134. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3135. if (!empty($segment_ids_to_create_task)) {
  3136. foreach ($segment_ids_to_create_task as $sid) {
  3137. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3138. if ($sid === $segment_id && $has_all_special_params) {
  3139. continue;
  3140. }
  3141. // 重新获取更新后的分镜数据
  3142. $updated_segment = DB::table('mp_episode_segments')
  3143. ->where('segment_id', $sid)
  3144. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3145. ->first();
  3146. if (!$updated_segment) continue;
  3147. $updated_segment = (array)$updated_segment;
  3148. // 检查dialogue是否为空
  3149. $dialogue = getProp($updated_segment, 'dialogue');
  3150. if (empty($dialogue)) {
  3151. // dialogue为空时,直接写入默认音频信息
  3152. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3153. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3154. 'audio_duration' => 2.0,
  3155. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3156. 'updated_at' => date('Y-m-d H:i:s')
  3157. ]);
  3158. continue;
  3159. }
  3160. $generate_json = [
  3161. 'text' => $dialogue,
  3162. 'role' => getProp($updated_segment, 'voice_actor'),
  3163. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3164. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3165. 'emotion' => getProp($updated_segment, 'emotion'),
  3166. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3167. 'gender' => getProp($updated_segment, 'gender'),
  3168. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3169. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3170. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3171. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3172. ];
  3173. // 插入视频配音合成任务
  3174. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3175. 'alias_segment_id' => $sid,
  3176. 'generate_status' => '执行中',
  3177. 'audio_url' => '',
  3178. 'generate_json' => json_encode($generate_json, 256),
  3179. 'created_at' => date('Y-m-d H:i:s'),
  3180. 'updated_at' => date('Y-m-d H:i:s'),
  3181. ]);
  3182. if (!$dubTaskId) {
  3183. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3184. continue;
  3185. }
  3186. // 将任务ID添加到Redis列表中
  3187. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3188. // 请求远程服务器执行生成
  3189. try {
  3190. sleep(1);
  3191. $client = new Client(['timeout' => 300, 'verify' => false]);
  3192. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3193. $response = $result->getBody()->getContents();
  3194. $response_arr = json_decode($response, true);
  3195. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3196. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3197. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3198. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3199. }
  3200. } catch (\Exception $e) {
  3201. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3202. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3203. }
  3204. }
  3205. }
  3206. DB::commit();
  3207. } catch (\Exception $e) {
  3208. DB::rollBack();
  3209. Utils::throwError('20003:'.$e->getMessage());
  3210. }
  3211. return true;
  3212. }
  3213. public function episodePicsInfo($data) {
  3214. $anime_id = getProp($data, 'anime_id');
  3215. $episode_id = getProp($data, 'episode_id');
  3216. // 参数验证
  3217. if (!$anime_id && !$episode_id) {
  3218. Utils::throwError('20003:请提供动漫ID或分集ID');
  3219. }
  3220. // 根据参数获取数据源
  3221. if ($episode_id) {
  3222. // 从剧集表获取
  3223. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3224. if (!$source) Utils::throwError('20003:该剧集不存在');
  3225. $table_name = 'mp_anime_episodes';
  3226. $id_field = 'id';
  3227. $id_value = $episode_id;
  3228. // 获取剧集的anime_id用于继承全局数据
  3229. $anime_id = getProp($source, 'anime_id');
  3230. } else {
  3231. // 从动漫表获取
  3232. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3233. if (!$source) Utils::throwError('20003:该动漫不存在');
  3234. $table_name = 'mp_animes';
  3235. $id_field = 'id';
  3236. $id_value = $anime_id;
  3237. }
  3238. $source = (array)$source;
  3239. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3240. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3241. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3242. // 如果是分集数据,需要处理继承和任务创建逻辑
  3243. if ($episode_id) {
  3244. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3245. }
  3246. // 返回生成器函数,用于 SSE 流式输出
  3247. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3248. $startTime = time();
  3249. $maxDuration = 600; // 10分钟超时
  3250. $checkInterval = 3; // 每3秒检查一次
  3251. // Redis 缓存键
  3252. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3253. // 生成当前数据的哈希值用于比较
  3254. $generateHash = function($roles, $scenes, $props) {
  3255. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3256. };
  3257. // 发送初始数据
  3258. $currentHash = $generateHash($roles, $scenes, $props);
  3259. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3260. echo "data: " . json_encode([
  3261. 'type' => 'init',
  3262. 'data' => [
  3263. 'roles' => $roles,
  3264. 'scenes' => $scenes,
  3265. 'props' => $props,
  3266. 'start_time' => $startTime
  3267. ]
  3268. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3269. if (ob_get_level() > 0) {
  3270. ob_flush();
  3271. }
  3272. flush();
  3273. // 持续轮询任务状态
  3274. while (time() - $startTime < $maxDuration) {
  3275. $hasProcessing = false;
  3276. $updated = false;
  3277. // 检查角色任务状态
  3278. foreach ($roles as $index => &$role) {
  3279. $task_id = getProp($role, 'task_id');
  3280. $task_status = getProp($role, 'task_status');
  3281. $existing_url = getProp($role, 'url');
  3282. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3283. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3284. $hasProcessing = ($task_status === 'processing');
  3285. // 查询任务状态
  3286. $task = DB::table('mp_generate_pic_tasks')
  3287. ->where('id', $task_id)
  3288. ->select('id', 'status', 'result_url', 'error_message')
  3289. ->first();
  3290. if ($task) {
  3291. $task = (array)$task;
  3292. $status = getProp($task, 'status');
  3293. // 如果任务完成或失败
  3294. if (in_array($status, ['success', 'failed'])) {
  3295. $role['task_status'] = $status;
  3296. if ($status === 'success') {
  3297. $result_url = getProp($task, 'result_url');
  3298. if ($result_url) {
  3299. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3300. if (is_array($result_urls) && !empty($result_urls[0])) {
  3301. $role['url'] = $result_urls[0];
  3302. }
  3303. }
  3304. }
  3305. $updated = true;
  3306. } else if ($status === 'processing') {
  3307. $hasProcessing = true;
  3308. }
  3309. }
  3310. }
  3311. }
  3312. // 检查场景任务状态
  3313. foreach ($scenes as $index => &$scene) {
  3314. $task_id = getProp($scene, 'task_id');
  3315. $task_status = getProp($scene, 'task_status');
  3316. $existing_url = getProp($scene, 'url');
  3317. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3318. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3319. $hasProcessing = ($task_status === 'processing');
  3320. // 查询任务状态
  3321. $task = DB::table('mp_generate_pic_tasks')
  3322. ->where('id', $task_id)
  3323. ->select('id', 'status', 'result_url', 'error_message')
  3324. ->first();
  3325. if ($task) {
  3326. $task = (array)$task;
  3327. $status = getProp($task, 'status');
  3328. // 如果任务完成或失败
  3329. if (in_array($status, ['success', 'failed'])) {
  3330. $scene['task_status'] = $status;
  3331. if ($status === 'success') {
  3332. $result_url = getProp($task, 'result_url');
  3333. if ($result_url) {
  3334. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3335. if (is_array($result_urls) && !empty($result_urls[0])) {
  3336. $scene['url'] = $result_urls[0];
  3337. }
  3338. }
  3339. }
  3340. $updated = true;
  3341. } else if ($status === 'processing') {
  3342. $hasProcessing = true;
  3343. }
  3344. }
  3345. }
  3346. }
  3347. // 检查道具任务状态
  3348. foreach ($props as $index => &$prop) {
  3349. $task_id = getProp($prop, 'task_id');
  3350. $task_status = getProp($prop, 'task_status');
  3351. $existing_url = getProp($prop, 'url');
  3352. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3353. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3354. $hasProcessing = ($task_status === 'processing');
  3355. // 查询任务状态
  3356. $task = DB::table('mp_generate_pic_tasks')
  3357. ->where('id', $task_id)
  3358. ->select('id', 'status', 'result_url', 'error_message')
  3359. ->first();
  3360. if ($task) {
  3361. $task = (array)$task;
  3362. $status = getProp($task, 'status');
  3363. // 如果任务完成或失败
  3364. if (in_array($status, ['success', 'failed'])) {
  3365. $prop['task_status'] = $status;
  3366. if ($status === 'success') {
  3367. $result_url = getProp($task, 'result_url');
  3368. if ($result_url) {
  3369. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3370. if (is_array($result_urls) && !empty($result_urls[0])) {
  3371. $prop['url'] = $result_urls[0];
  3372. }
  3373. }
  3374. }
  3375. $updated = true;
  3376. } else if ($status === 'processing') {
  3377. $hasProcessing = true;
  3378. }
  3379. }
  3380. }
  3381. }
  3382. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3383. if ($updated) {
  3384. $newHash = $generateHash($roles, $scenes, $props);
  3385. $cachedHash = Redis::get($cacheKey);
  3386. // 只有当数据真正变化时才更新数据库和发送事件
  3387. if ($newHash !== $cachedHash) {
  3388. try {
  3389. // 更新数据库
  3390. DB::table($table_name)->where($id_field, $id_value)->update([
  3391. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3392. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3393. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3394. 'updated_at' => date('Y-m-d H:i:s')
  3395. ]);
  3396. // 更新缓存
  3397. Redis::setex($cacheKey, 600, $newHash);
  3398. // 发送更新事件
  3399. echo "data: " . json_encode([
  3400. 'type' => 'update',
  3401. 'data' => [
  3402. 'roles' => $roles,
  3403. 'scenes' => $scenes,
  3404. 'props' => $props,
  3405. 'elapsed_time' => time() - $startTime
  3406. ]
  3407. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3408. if (ob_get_level() > 0) {
  3409. ob_flush();
  3410. }
  3411. flush();
  3412. } catch (\Exception $e) {
  3413. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3414. }
  3415. } else {
  3416. // 即使哈希相同,如果有URL更新也要发送事件
  3417. $hasUrlUpdate = false;
  3418. foreach ($roles as $role) {
  3419. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3420. $hasUrlUpdate = true;
  3421. break;
  3422. }
  3423. }
  3424. if (!$hasUrlUpdate) {
  3425. foreach ($scenes as $scene) {
  3426. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3427. $hasUrlUpdate = true;
  3428. break;
  3429. }
  3430. }
  3431. }
  3432. if (!$hasUrlUpdate) {
  3433. foreach ($props as $prop) {
  3434. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3435. $hasUrlUpdate = true;
  3436. break;
  3437. }
  3438. }
  3439. }
  3440. if ($hasUrlUpdate) {
  3441. // 强制更新数据库和发送事件
  3442. try {
  3443. DB::table($table_name)->where($id_field, $id_value)->update([
  3444. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3445. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3446. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3447. 'updated_at' => date('Y-m-d H:i:s')
  3448. ]);
  3449. // 更新缓存
  3450. Redis::setex($cacheKey, 600, $newHash);
  3451. // 发送更新事件
  3452. echo "data: " . json_encode([
  3453. 'type' => 'update',
  3454. 'data' => [
  3455. 'roles' => $roles,
  3456. 'scenes' => $scenes,
  3457. 'props' => $props,
  3458. 'elapsed_time' => time() - $startTime
  3459. ]
  3460. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3461. if (ob_get_level() > 0) {
  3462. ob_flush();
  3463. }
  3464. flush();
  3465. } catch (\Exception $e) {
  3466. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3467. }
  3468. }
  3469. }
  3470. }
  3471. // 如果所有任务都已完成,发送完成事件并退出
  3472. if (!$hasProcessing) {
  3473. // 查询数据库中的最终数据,确保返回最新的完整数据
  3474. try {
  3475. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3476. if ($finalSource) {
  3477. $finalSource = (array)$finalSource;
  3478. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3479. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3480. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3481. // 使用数据库中的最终数据
  3482. $roles = $finalRoles;
  3483. $scenes = $finalScenes;
  3484. $props = $finalProps;
  3485. }
  3486. } catch (\Exception $e) {
  3487. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3488. // 如果查询失败,继续使用内存中的数据
  3489. }
  3490. // 清理缓存
  3491. Redis::del($cacheKey);
  3492. echo "data: " . json_encode([
  3493. 'type' => 'completed',
  3494. 'data' => [
  3495. 'roles' => $roles,
  3496. 'scenes' => $scenes,
  3497. 'props' => $props,
  3498. 'total_time' => time() - $startTime
  3499. ]
  3500. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3501. if (ob_get_level() > 0) {
  3502. ob_flush();
  3503. }
  3504. flush();
  3505. break;
  3506. }
  3507. // 等待下次检查
  3508. sleep($checkInterval);
  3509. }
  3510. // 超时处理
  3511. if (time() - $startTime >= $maxDuration) {
  3512. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3513. try {
  3514. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3515. if ($finalSource) {
  3516. $finalSource = (array)$finalSource;
  3517. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3518. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3519. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3520. // 使用数据库中的最终数据
  3521. $roles = $finalRoles;
  3522. $scenes = $finalScenes;
  3523. $props = $finalProps;
  3524. }
  3525. } catch (\Exception $e) {
  3526. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3527. // 如果查询失败,继续使用内存中的数据
  3528. }
  3529. // 清理缓存
  3530. Redis::del($cacheKey);
  3531. echo "data: " . json_encode([
  3532. 'type' => 'timeout',
  3533. 'message' => '轮询超时,请刷新页面查看最新状态',
  3534. 'data' => [
  3535. 'roles' => $roles,
  3536. 'scenes' => $scenes,
  3537. 'props' => $props
  3538. ]
  3539. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3540. if (ob_get_level() > 0) {
  3541. ob_flush();
  3542. }
  3543. flush();
  3544. }
  3545. };
  3546. }
  3547. public function clipSegmentVideo($data) {
  3548. $segment_id = getProp($data, 'segment_id');
  3549. $video_time_point_start = getProp($data, 'video_time_point_start');
  3550. $video_time_point_end = getProp($data, 'video_time_point_end');
  3551. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3552. Utils::throwError('20003:参数异常');
  3553. }
  3554. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3555. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3556. }
  3557. $video_duration = $video_time_point_end - $video_time_point_start;
  3558. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3559. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3560. 'video_duration' => $video_duration,
  3561. 'video_time_point_start' => $video_time_point_start,
  3562. 'video_time_point_end' => $video_time_point_end,
  3563. 'updated_at' => date('Y-m-d H:i:s')
  3564. ]);
  3565. }
  3566. // 轮训获取图片任务结果
  3567. private function loopGetPicTaskResult($task_id) {
  3568. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3569. if (!$task) {
  3570. return '';
  3571. }
  3572. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3573. $model = getProp($task, 'model');
  3574. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3575. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3576. $isSyncModel = $isVolcModel || $isGptModel;
  3577. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3578. $start_count = 0;
  3579. $img_url = '';
  3580. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3581. sleep(3);
  3582. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3583. // 如果任务已经完成,直接返回结果
  3584. if ($task->status === 'success' && $task->result_url) {
  3585. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3586. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3587. }
  3588. // 如果任务已失败,返回空
  3589. if ($task->status === 'failed') {
  3590. return '';
  3591. }
  3592. if ($isSyncModel) continue;
  3593. // 查询任务状态
  3594. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3595. if ($statusInfo['status'] === 'success') {
  3596. $task->updateStatus('success', [
  3597. 'result_url' => $statusInfo['result_url'],
  3598. 'result_json' => $statusInfo['result_json'] ?? []
  3599. ]);
  3600. // 同步调整分镜图片状态和结果
  3601. if (getProp($task, 'alias_segment_id')) {
  3602. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3603. 'img_url' => $statusInfo['result_url'][0],
  3604. 'pic_task_status' => '已完成',
  3605. ]);
  3606. }
  3607. $img_url = $statusInfo['result_url'][0];
  3608. break;
  3609. } elseif ($statusInfo['status'] === 'failed') {
  3610. $task->updateStatus('failed', [
  3611. 'error_message' => $statusInfo['error_message'],
  3612. 'result_json' => $statusInfo['result_json'] ?? []
  3613. ]);
  3614. if (getProp($task, 'alias_segment_id')) {
  3615. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3616. 'pic_task_status' => '失败',
  3617. ]);
  3618. }
  3619. break;
  3620. }
  3621. $start_count++;
  3622. }
  3623. return $img_url;
  3624. }
  3625. /**
  3626. * 从分镜内容中提取涉及的角色
  3627. */
  3628. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3629. $found_characters = [];
  3630. foreach ($available_characters as $character) {
  3631. // 检查角色名称是否在分镜内容中出现
  3632. if (strpos($segment_content, $character) !== false) {
  3633. $found_characters[] = $character;
  3634. }
  3635. }
  3636. if (!$found_characters) {
  3637. foreach ($roles as $character) {
  3638. // 检查角色名称是否在分镜内容中出现
  3639. if (strpos($segment_content, $character) !== false) {
  3640. $found_characters[] = $character;
  3641. }
  3642. }
  3643. }
  3644. return array_unique($found_characters);
  3645. }
  3646. // 从分镜剧本中提取关键字段
  3647. private function handleSegmentContent(&$data) {
  3648. $segmentContent = getProp($data, 'segment_content');
  3649. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3650. $segmentData = [
  3651. 'description' => '',
  3652. 'composition' => '',
  3653. 'camera_movement' => '',
  3654. 'voice_actor' => '',
  3655. 'dialogue' => '',
  3656. 'frame_type' => '',
  3657. 'scene' => '', // 场景
  3658. 'characters' => '', // 出镜角色
  3659. 'tail_frame' => '', // 尾帧描述
  3660. 'emotion' => '中性', // 情感
  3661. 'gender' => '0', // 性别(0未知,1男,2女)
  3662. 'speed_ratio' => 0, // 语速
  3663. 'loudness_ratio' => 0, // 音量
  3664. 'emotion_scale' => 4, // 情感强度
  3665. 'pitch' => 0, // 音调
  3666. ];
  3667. // 用于存储需要从 segment_content 中移除的匹配项
  3668. $replaceEmptyArr = [];
  3669. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3670. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3671. $segmentData['description'] = trim($descMatch[1]);
  3672. $data['description'] = trim($descMatch[1]);
  3673. }
  3674. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3675. $segmentData['composition'] = trim($compMatch[1]);
  3676. $data['composition'] = trim($compMatch[1]);
  3677. }
  3678. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3679. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3680. $data['camera_movement'] = trim($cameraMatch[1]);
  3681. }
  3682. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3683. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3684. $data['voice_actor'] = trim($voiceMatch[1]);
  3685. }
  3686. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3687. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3688. $data['dialogue'] = trim($dialogueMatch[1]);
  3689. }
  3690. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3691. $segmentData['frame_type'] = trim($frameMatch[1]);
  3692. $data['frame_type'] = trim($frameMatch[1]);
  3693. }
  3694. // 场景字段
  3695. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3696. $segmentData['scene'] = trim($sceneMatch[1]);
  3697. $data['scene'] = trim($sceneMatch[1]);
  3698. }
  3699. // 出镜角色字段
  3700. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3701. $segmentData['characters'] = trim($charactersMatch[1]);
  3702. $data['characters'] = trim($charactersMatch[1]);
  3703. }
  3704. // 尾帧描述字段
  3705. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3706. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3707. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3708. }
  3709. // 情感字段
  3710. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3711. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3712. $segmentData['emotion'] = trim($emotionMatch[1]);
  3713. $data['emotion'] = trim($emotionMatch[1]);
  3714. }
  3715. // 性别字段
  3716. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3717. $replaceEmptyArr[] = trim($genderMatch[0]);
  3718. $genderStr = trim($genderMatch[1]);
  3719. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3720. $segmentData['gender'] = '1';
  3721. $data['gender'] = '1';
  3722. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3723. $segmentData['gender'] = '2';
  3724. $data['gender'] = '2';
  3725. } else {
  3726. $segmentData['gender'] = '0';
  3727. $data['gender'] = '0';
  3728. }
  3729. }
  3730. // 语速字段
  3731. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3732. $replaceEmptyArr[] = trim($speedMatch[0]);
  3733. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3734. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3735. }
  3736. // 音量字段
  3737. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3738. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3739. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3740. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3741. }
  3742. // 情感强度字段
  3743. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3744. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3745. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3746. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3747. }
  3748. // 音调字段
  3749. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3750. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3751. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3752. $data['pitch'] = (int)trim($pitchMatch[1]);
  3753. }
  3754. // 从 segment_content 中移除已提取的配音参数字段
  3755. if (!empty($replaceEmptyArr)) {
  3756. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3757. }
  3758. // 如果有配音角色,查询音色信息并验证情感
  3759. $voice_actor = $segmentData['voice_actor'];
  3760. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3761. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3762. $anime_id = getProp($data, 'anime_id');
  3763. $episode_id = getProp($data, 'episode_id');
  3764. // 优先从剧集的角色列表中查找
  3765. $roles = [];
  3766. if ($episode_id) {
  3767. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3768. if ($episode && getProp($episode, 'roles')) {
  3769. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3770. }
  3771. }
  3772. // 如果剧集中没有,从动漫的角色列表中查找
  3773. if (empty($roles) && $anime_id) {
  3774. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3775. if ($anime && getProp($anime, 'roles')) {
  3776. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3777. }
  3778. }
  3779. // 查找匹配的角色音色信息
  3780. $timbre_info = null;
  3781. foreach ($roles as $role) {
  3782. if (getProp($role, 'role') === $voice_actor) {
  3783. $timbre_info = $role;
  3784. break;
  3785. }
  3786. }
  3787. // 如果找到音色信息,添加到数据中
  3788. if ($timbre_info) {
  3789. $voice_type = getProp($timbre_info, 'voice_type');
  3790. $voice_name = getProp($timbre_info, 'voice_name');
  3791. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3792. if ($voice_type) {
  3793. $data['voice_type'] = $voice_type;
  3794. $segmentData['voice_type'] = $voice_type;
  3795. }
  3796. if ($voice_name) {
  3797. $data['voice_name'] = $voice_name;
  3798. $segmentData['voice_name'] = $voice_name;
  3799. }
  3800. if ($voice_audio_url) {
  3801. $data['voice_audio_url'] = $voice_audio_url;
  3802. $segmentData['voice_audio_url'] = $voice_audio_url;
  3803. }
  3804. // 验证情感是否在音色支持的情感列表中
  3805. if ($voice_type) {
  3806. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3807. if ($timbre_emotion) {
  3808. $timbre_emotion = explode(',', $timbre_emotion);
  3809. } else {
  3810. $timbre_emotion = [];
  3811. }
  3812. $emotion = getProp($segmentData, 'emotion', '中性');
  3813. if (!in_array($emotion, $timbre_emotion)) {
  3814. $emotion = '中性';
  3815. }
  3816. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3817. $emotion_list = array_flip($emotion_list);
  3818. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3819. $data['emotion_type'] = $emotion_type;
  3820. $segmentData['emotion_type'] = $emotion_type;
  3821. }
  3822. }
  3823. }
  3824. return $segmentData;
  3825. }
  3826. public function createSegmentVideoTask($data) {
  3827. $segment_id = getProp($data, 'segment_id');
  3828. $tail_frame = getProp($data, 'tail_frame');
  3829. $first_frame_url = getProp($data, 'first_frame_url');
  3830. $tail_frame_url = getProp($data, 'tail_frame_url');
  3831. $generate_audio = getProp($data, 'generate_audio', 0);
  3832. if (!$segment_id) {
  3833. Utils::throwError('1002:分镜ID不能为空');
  3834. }
  3835. // 获取分镜信息
  3836. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3837. if (!$segment) {
  3838. Utils::throwError('20003:分镜不存在');
  3839. }
  3840. $segment = (array)$segment;
  3841. $episode_id = getProp($segment, 'episode_id');
  3842. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3843. if (!$ratio) $ratio = '9:16';
  3844. // 获取分镜内容
  3845. $segmentContent = getProp($segment, 'segment_content', '');
  3846. // 检查 $segmentContent 中是否已有尾帧描述
  3847. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3848. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3849. $finalTailFrame = '';
  3850. if ($tail_frame) {
  3851. // 用户输入了尾帧描述,优先使用
  3852. $finalTailFrame = $tail_frame;
  3853. // 如果 segmentContent 中已有尾帧描述,需要替换
  3854. if ($contentHasTailFrame) {
  3855. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3856. }
  3857. } elseif ($contentHasTailFrame) {
  3858. // segmentContent 中有尾帧描述,使用它
  3859. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3860. } else {
  3861. // 两者都没有,使用分镜表中的尾帧描述
  3862. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3863. }
  3864. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3865. $hasDialogue = false;
  3866. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3867. $dialogue = trim($dialogueMatch[1]);
  3868. // 如果台词不为空且不是"无"
  3869. if (!empty($dialogue) && $dialogue !== '无') {
  3870. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3871. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3872. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3873. $hasDialogue = true;
  3874. }
  3875. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3876. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3877. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3878. if (!preg_match('/^[“]/', $dialogue)) {
  3879. $dialogue = '“' . $dialogue;
  3880. }
  3881. if (!preg_match('/[”]$/', $dialogue)) {
  3882. $dialogue .= '”';
  3883. }
  3884. // 将修改后的台词替换回 $segmentContent
  3885. $originalDialogue = $dialogueMatch[1];
  3886. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3887. }
  3888. }
  3889. // 构建完整的提示词
  3890. $fullPrompt = $segmentContent;
  3891. if ($finalTailFrame && !$contentHasTailFrame) {
  3892. // 只有当 segmentContent 中没有尾帧描述时才追加
  3893. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3894. }
  3895. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3896. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3897. $fullPrompt = trim($fullPrompt);
  3898. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3899. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3900. // 智能选择视频时长
  3901. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3902. $videoDuration = -1;
  3903. // 处理视频模型
  3904. $model = getProp($data, 'model');
  3905. if (!$model) {
  3906. // 用户没有输入,从episode表获取
  3907. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3908. $model = getProp($episode, 'video_model');
  3909. if (!$model) {
  3910. // episode表也没有,使用默认值
  3911. $model = 'doubao-seedance-1-5-pro-251215';
  3912. }
  3913. }
  3914. // 验证模型是否在可用模型表中
  3915. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3916. $model = 'doubao-seedance-1-5-pro-251215';
  3917. }
  3918. // 保存到episode表
  3919. $episode_id = getProp($segment, 'episode_id');
  3920. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3921. 'video_model' => $model,
  3922. 'updated_at' => date('Y-m-d H:i:s')
  3923. ]);
  3924. // 构建视频生成参数
  3925. $videoParams = [
  3926. 'model' => $model,
  3927. 'alias_segment_id' => $segment_id,
  3928. 'prompt' => trim($fullPrompt),
  3929. 'video_duration' => $videoDuration,
  3930. 'video_resolution' => '720P',
  3931. 'seed' => -1,
  3932. 'ratio' => $ratio,
  3933. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3934. 'draft' => false,
  3935. 'watermark' => false,
  3936. 'camera_fixed' => false,
  3937. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3938. ];
  3939. // 如果分镜有图片,作为首帧
  3940. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3941. $hasVideo = !empty(getProp($segment, 'video_url'));
  3942. if ($hasImage) {
  3943. if ($first_frame_url) {
  3944. $videoParams['first_frame_url'] = $first_frame_url;
  3945. }else {
  3946. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3947. }
  3948. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3949. }
  3950. // 构建content数组
  3951. $videoParams['content'] = [
  3952. [
  3953. 'type' => 'text',
  3954. 'text' => $videoParams['prompt'],
  3955. ]
  3956. ];
  3957. // 如果有首帧图片,添加到content中
  3958. if ($hasImage) {
  3959. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3960. $videoParams['content'][] = [
  3961. 'type' => 'image_url',
  3962. 'image_url' => [
  3963. 'url' => $videoParams['first_frame_url'],
  3964. ],
  3965. 'role' => 'reference_image',
  3966. ];
  3967. if (isset($videoParams['tail_frame_url'])) {
  3968. $videoParams['content'][] = [
  3969. 'type' => 'image_url',
  3970. 'image_url' => [
  3971. 'url' => $videoParams['tail_frame_url'],
  3972. ],
  3973. 'role' => 'reference_image',
  3974. ];
  3975. }
  3976. }else {
  3977. $videoParams['content'][] = [
  3978. 'type' => 'image_url',
  3979. 'image_url' => [
  3980. 'url' => $videoParams['first_frame_url'],
  3981. ],
  3982. 'role' => 'first_frame',
  3983. ];
  3984. if (isset($videoParams['tail_frame_url'])) {
  3985. $videoParams['content'][] = [
  3986. 'type' => 'image_url',
  3987. 'image_url' => [
  3988. 'url' => $videoParams['tail_frame_url'],
  3989. ],
  3990. 'role' => 'last_frame',
  3991. ];
  3992. }
  3993. }
  3994. }
  3995. // 获取配音音频URL
  3996. $audioUrl = getProp($segment, 'audio_url');
  3997. $audioDuration = getProp($segment, 'audio_duration');
  3998. // 音频传入的前提:必须有至少一张图片或一个视频
  3999. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4000. // 余额预检:按预估时长计算所需积分,不足直接报错
  4001. $chargeDuration = (int)ceil((float)$audioDuration);
  4002. if ($chargeDuration <= 0) {
  4003. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4004. }
  4005. $this->pointsService->checkUserPointsEnough(
  4006. $this->pointsService->getVideoChargePoints([
  4007. 'model' => $model,
  4008. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4009. 'video_duration' => $chargeDuration,
  4010. 'ratio' => $ratio,
  4011. 'generate_audio' => $current_generate_audio,
  4012. ])
  4013. );
  4014. // dd($videoParams);
  4015. // 根据模型选择不同的视频生成方法
  4016. if (strpos($model, 'jimeng') !== false) {
  4017. // 即梦模型参数调整
  4018. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4019. unset($videoParams['content']); // 即梦不使用content格式
  4020. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4021. } elseif (strpos($model, 'kling') !== false) {
  4022. // Keling模型参数调整
  4023. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4024. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4025. unset($videoParams['ratio']);
  4026. unset($videoParams['content']); // Keling不使用content格式
  4027. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4028. } elseif (strpos($model, 'zhizhen') !== false) {
  4029. // 智帧20等新模型使用统一API
  4030. // 构建统一API参数
  4031. $unifiedParams = [
  4032. 'model_code' => $model,
  4033. 'alias_segment_id' => $segment_id,
  4034. 'prompt' => trim($fullPrompt),
  4035. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4036. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4037. 'video_ratio' => $ratio,
  4038. 'seed' => -1,
  4039. ];
  4040. // 构建parameters参数
  4041. $parameters = [
  4042. 'seconds' => $unifiedParams['video_duration'],
  4043. 'resolution' => $unifiedParams['video_resolution'],
  4044. 'ratio' => $ratio,
  4045. // 'video_mode' => 'multi_image',
  4046. // 'mode' => 'multi_image',
  4047. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4048. ];
  4049. $hasImage = false;
  4050. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4051. if ($hasImage) {
  4052. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4053. if (isset($videoParams['tail_frame_url'])) {
  4054. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4055. }
  4056. // 只有在有图片的情况下才能添加参考音频
  4057. if ($audioUrl) {
  4058. // $parameters['reference_audios'] = [$audioUrl];
  4059. }
  4060. } else {
  4061. // 没有图片时,记录错误日志
  4062. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4063. 'segment_id' => $segment_id,
  4064. 'model' => $model
  4065. ]);
  4066. }
  4067. $unifiedParams['parameters'] = $parameters;
  4068. // 调用统一API创建任务
  4069. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4070. } else {
  4071. // Seedance模型(默认)
  4072. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4073. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4074. // 添加配音音频到content中
  4075. $videoParams['content'][] = [
  4076. 'type' => 'audio_url',
  4077. 'audio_url' => [
  4078. 'url' => $audioUrl,
  4079. ],
  4080. 'role' => 'reference_audio',
  4081. ];
  4082. // 优化提示词,增加音频相关描述
  4083. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4084. $videoParams['prompt'] = $audioPrompt;
  4085. $videoParams['content'][0]['text'] = $audioPrompt;
  4086. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4087. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4088. }
  4089. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4090. }
  4091. // 更新分镜表的视频任务信息
  4092. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4093. 'video_task_id' => $task->id,
  4094. 'video_task_status' => '生成中',
  4095. 'generate_audio' => $generate_audio,
  4096. 'updated_at' => date('Y-m-d H:i:s')
  4097. ]);
  4098. return [
  4099. 'task_id' => $task->id,
  4100. 'status' => $task->status,
  4101. 'segment_id' => $segment_id,
  4102. 'video_duration' => $videoDuration
  4103. ];
  4104. }
  4105. public function createActVideoTask($data) {
  4106. $act_id = getProp($data, 'act_id');
  4107. $first_frame_url = getProp($data, 'first_frame_url');
  4108. $tail_frame_url = getProp($data, 'tail_frame_url');
  4109. $generate_audio = getProp($data, 'generate_audio', 1);
  4110. $video_duration = getProp($data, 'video_duration');
  4111. $video_resolution = getProp($data, 'video_resolution');
  4112. $ratio = getProp($data, 'ratio');
  4113. $products = getProp($data, 'products', []);
  4114. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4115. if (!is_array($reference_images) || !is_array($products)) {
  4116. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4117. }
  4118. if (!$act_id) {
  4119. Utils::throwError('1002:片段ID不能为空');
  4120. }
  4121. // 获取片段信息
  4122. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4123. if (!$act) {
  4124. Utils::throwError('20003:片段不存在');
  4125. }
  4126. $act = (array)$act;
  4127. $anime_id = getProp($act, 'anime_id');
  4128. $episode_id = getProp($act, 'episode_id');
  4129. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4130. $ace_mode = getProp($anime, 'ace_mode');
  4131. $art_style_type = getProp($anime, 'art_style_type');
  4132. $art_style = getProp($anime, 'art_style');
  4133. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4134. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4135. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4136. // 将资产中新出现的资产放到extra_products中
  4137. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4138. if (!empty($products) && $episode) {
  4139. // 获取剧集中的角色、场景和道具列表
  4140. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4141. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4142. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4143. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4144. // 构建角色名称列表
  4145. $role_names = array_column($roles, 'role');
  4146. // 构建场景名称列表
  4147. $scene_names = array_column($scenes, 'scene');
  4148. // 构建道具名称列表
  4149. $prop_names = array_column($props, 'prop');
  4150. // 遍历传入的products
  4151. foreach ($products as $product) {
  4152. $product_name = getProp($product, 'product_name');
  4153. // 如果product_name不在roles、scenes和props中
  4154. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4155. // 查找是否在extra_products中存在同名的
  4156. $found = false;
  4157. foreach ($extra_products as $key => $extra_product) {
  4158. if (getProp($extra_product, 'product_name') === $product_name) {
  4159. // 有同名的则覆盖
  4160. $extra_products[$key] = $product;
  4161. $found = true;
  4162. break;
  4163. }
  4164. }
  4165. // 没有则新增
  4166. if (!$found) {
  4167. $extra_products[] = $product;
  4168. }
  4169. }
  4170. }
  4171. if ($extra_products) {
  4172. // 保存到数据库
  4173. DB::table('mp_anime_episodes')
  4174. ->where('id', $episode_id)
  4175. ->update([
  4176. 'extra_products' => json_encode($extra_products, 256),
  4177. 'updated_at' => date('Y-m-d H:i:s')
  4178. ]);
  4179. }
  4180. }
  4181. // 获取分镜内容
  4182. $actContent = getProp($act, 'act_show_content', '');
  4183. // 音效同出(默认使用)
  4184. $current_generate_audio = $generate_audio ? 1 : 0;
  4185. // 构建完整的提示词
  4186. $processResult = $this->processActContentWithProducts($actContent, $products);
  4187. $fullPrompt = $processResult['content'];
  4188. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4189. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4190. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4191. // 处理视频模型
  4192. $model = getProp($data, 'model');
  4193. if (!$model) {
  4194. $model = getProp($episode, 'video_model');
  4195. if (!$model) {
  4196. // episode表也没有,使用默认值
  4197. $model = 'zhizhen-20';
  4198. }
  4199. }
  4200. // 验证模型是否在可用模型表中
  4201. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4202. $model = 'zhizhen-20';
  4203. }
  4204. // 保存到episode表(仅在专用方法中更新模型)
  4205. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4206. // 'video_model' => $model,
  4207. // 'updated_at' => date('Y-m-d H:i:s')
  4208. // ]);
  4209. // 余额预检:按预估时长计算所需积分,不足直接报错
  4210. $chargeDuration = (int)$videoDuration;
  4211. if ($chargeDuration <= 0) {
  4212. $chargeDuration = 5; // 无时长时按默认5秒预估
  4213. }
  4214. $this->pointsService->checkUserPointsEnough(
  4215. $this->pointsService->getVideoChargePoints([
  4216. 'model' => $model,
  4217. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4218. 'video_duration' => $chargeDuration,
  4219. 'ratio' => $ratio,
  4220. 'generate_audio' => $current_generate_audio,
  4221. ])
  4222. );
  4223. // 构建视频生成参数
  4224. $videoParams = [
  4225. 'model' => $model,
  4226. 'alias_act_id' => $act_id,
  4227. 'prompt' => trim($fullPrompt),
  4228. 'video_duration' => $videoDuration,
  4229. 'video_resolution' => $video_resolution,
  4230. 'seed' => -1,
  4231. 'ratio' => $ratio,
  4232. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4233. 'draft' => false,
  4234. 'watermark' => false,
  4235. 'camera_fixed' => false,
  4236. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4237. ];
  4238. // 如果分镜有图片,作为首帧
  4239. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4240. $hasVideo = !empty(getProp($act, 'video_url'));
  4241. if ($hasImage) {
  4242. if ($first_frame_url) {
  4243. $videoParams['first_frame_url'] = $first_frame_url;
  4244. }else {
  4245. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4246. }
  4247. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4248. }
  4249. // 构建content数组
  4250. $videoParams['content'] = [
  4251. [
  4252. 'type' => 'text',
  4253. 'text' => $videoParams['prompt'],
  4254. ]
  4255. ];
  4256. // 如果有首帧图片,添加到content中
  4257. if ($hasImage) {
  4258. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4259. $videoParams['content'][] = [
  4260. 'type' => 'image_url',
  4261. 'image_url' => [
  4262. 'url' => $videoParams['first_frame_url'],
  4263. ],
  4264. 'role' => 'reference_image',
  4265. ];
  4266. if (isset($videoParams['tail_frame_url'])) {
  4267. $videoParams['content'][] = [
  4268. 'type' => 'image_url',
  4269. 'image_url' => [
  4270. 'url' => $videoParams['tail_frame_url'],
  4271. ],
  4272. 'role' => 'reference_image',
  4273. ];
  4274. }
  4275. }else {
  4276. $videoParams['content'][] = [
  4277. 'type' => 'image_url',
  4278. 'image_url' => [
  4279. 'url' => $videoParams['first_frame_url'],
  4280. ],
  4281. 'role' => 'first_frame',
  4282. ];
  4283. if (isset($videoParams['tail_frame_url'])) {
  4284. $videoParams['content'][] = [
  4285. 'type' => 'image_url',
  4286. 'image_url' => [
  4287. 'url' => $videoParams['tail_frame_url'],
  4288. ],
  4289. 'role' => 'last_frame',
  4290. ];
  4291. }
  4292. }
  4293. }
  4294. // dd($videoParams);
  4295. // 根据模型选择不同的视频生成方法
  4296. if (strpos($model, 'jimeng') !== false) {
  4297. // 即梦模型参数调整
  4298. unset($videoParams['content']); // 即梦不使用content格式
  4299. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4300. } elseif (strpos($model, 'kling') !== false) {
  4301. // Keling模型参数调整
  4302. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4303. unset($videoParams['ratio']);
  4304. unset($videoParams['content']); // Keling不使用content格式
  4305. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4306. } elseif (strpos($model, 'zhizhen') !== false) {
  4307. // 智帧20等新模型使用统一API
  4308. // 构建统一API参数
  4309. $unifiedParams = [
  4310. 'model_code' => $model,
  4311. 'alias_act_id' => $act_id,
  4312. 'prompt' => trim($fullPrompt),
  4313. 'video_duration' => $videoDuration,
  4314. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4315. 'video_ratio' => $ratio,
  4316. 'seed' => -1,
  4317. ];
  4318. // 构建parameters参数
  4319. $parameters = [
  4320. 'seconds' => $unifiedParams['video_duration'],
  4321. 'resolution' => $unifiedParams['video_resolution'],
  4322. 'ratio' => $ratio,
  4323. // 'video_mode' => 'multi_image',
  4324. // 'mode' => 'multi_image',
  4325. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4326. ];
  4327. $hasImage = false;
  4328. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4329. if ($hasImage) {
  4330. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4331. if (isset($videoParams['tail_frame_url'])) {
  4332. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4333. }
  4334. } else {
  4335. // 没有图片时,记录错误日志
  4336. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4337. 'act_id' => $act_id,
  4338. 'model' => $model
  4339. ]);
  4340. }
  4341. if ($reference_images) {
  4342. // 限制只传入9张参考图
  4343. $reference_images = array_slice($reference_images, 0, 9);
  4344. // 在处理之前先保存原始reference_images到任务参数中
  4345. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4346. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4347. $parameters['reference_images'] = $reference_images;
  4348. $parameters['video_mode'] = 'multi_image';
  4349. $parameters['mode'] = 'multi_image';
  4350. }
  4351. $unifiedParams['parameters'] = $parameters;
  4352. // 调用统一API创建任务
  4353. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4354. } else {
  4355. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4356. }
  4357. // 更新分镜表的视频任务信息
  4358. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4359. 'video_task_id' => $task->id,
  4360. 'video_task_status' => '生成中',
  4361. 'generate_audio' => $generate_audio,
  4362. 'updated_at' => date('Y-m-d H:i:s')
  4363. ]);
  4364. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4365. $episode_number = getProp($act, 'episode_number');
  4366. $act_number = getProp($act, 'act_number');
  4367. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4368. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4369. }
  4370. return [
  4371. 'task_id' => $task->id,
  4372. 'status' => $task->status,
  4373. 'act_id' => $act_id,
  4374. 'video_duration' => $videoDuration
  4375. ];
  4376. }
  4377. /**
  4378. * 预估视频生成所需积分(支持单一/批量)
  4379. *
  4380. * 传参与对应创建接口一致,另支持 type 参数区分场景:
  4381. * segment-单分镜转视频、act-单片段转视频、batch_segment-分镜批量、batch_act-片段批量;
  4382. * type 缺省时按 segment_id / act_id 自动推断,批量场景需显式传入。
  4383. *
  4384. * @param array $data
  4385. * @return array
  4386. */
  4387. public function previewVideoCharge(array $data): array
  4388. {
  4389. $type = (string)getProp($data, 'type', '');
  4390. if (!$type) {
  4391. if (getProp($data, 'segment_id')) {
  4392. $type = 'segment';
  4393. } elseif (getProp($data, 'act_id')) {
  4394. $type = 'act';
  4395. } else {
  4396. Utils::throwError('1003:请传入type参数(segment/act/batch_segment/batch_act)');
  4397. }
  4398. }
  4399. $mode = (string)getProp($data, 'mode', 'video_generation');
  4400. $items = [];
  4401. $model = '';
  4402. $resolution = '720p';
  4403. $buildCharge = function ($itemId, $duration, $model, $resolution, $mode) {
  4404. return $this->pointsService->getVideoChargePoints([
  4405. 'model' => $model,
  4406. 'video_resolution' => $resolution,
  4407. 'video_duration' => $duration,
  4408. 'mode' => $mode,
  4409. ]);
  4410. };
  4411. if ($type === 'segment') {
  4412. // 单分镜转视频
  4413. $segmentId = getProp($data, 'segment_id');
  4414. if (!$segmentId) {
  4415. Utils::throwError('1002:分镜ID不能为空');
  4416. }
  4417. $segment = DB::table('mp_episode_segments')->where('segment_id', $segmentId)->first();
  4418. if (!$segment) {
  4419. Utils::throwError('20003:分镜不存在');
  4420. }
  4421. $episode = DB::table('mp_anime_episodes')->where('id', $segment->episode_id)->first();
  4422. $model = getProp($data, 'model') ?: getProp($episode, 'video_model', 'doubao-seedance-1-5-pro-251215');
  4423. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4424. $model = 'doubao-seedance-1-5-pro-251215';
  4425. }
  4426. $duration = (int)ceil((float)$segment->audio_duration);
  4427. if ($duration <= 0) {
  4428. $duration = 5;
  4429. }
  4430. $items[] = [
  4431. 'id' => $segment->segment_id,
  4432. 'duration' => $duration,
  4433. 'points' => $buildCharge($segment->segment_id, $duration, $model, '720p', $mode),
  4434. ];
  4435. } elseif ($type === 'act') {
  4436. // 单片段转视频
  4437. $actId = getProp($data, 'act_id');
  4438. if (!$actId) {
  4439. Utils::throwError('1002:片段ID不能为空');
  4440. }
  4441. $act = DB::table('mp_episode_segments')->where('id', $actId)->first();
  4442. if (!$act) {
  4443. Utils::throwError('20003:片段不存在');
  4444. }
  4445. $episode = DB::table('mp_anime_episodes')->where('id', $act->episode_id)->first();
  4446. $model = getProp($data, 'model') ?: getProp($episode, 'video_model', 'zhizhen-20');
  4447. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4448. $model = 'zhizhen-20';
  4449. }
  4450. $resolution = strtolower((string)getProp($data, 'video_resolution', ''));
  4451. if (!$resolution) {
  4452. $resolution = strtolower((string)getProp($episode, 'video_resolution', '720p'));
  4453. }
  4454. $duration = (int)getProp($data, 'video_duration', 0);
  4455. if ($duration <= 0) {
  4456. $duration = (int)ceil((float)$act->act_duration);
  4457. }
  4458. if ($duration <= 0) {
  4459. $duration = 5;
  4460. }
  4461. $items[] = [
  4462. 'id' => $act->id,
  4463. 'duration' => $duration,
  4464. 'points' => $buildCharge($act->id, $duration, $model, $resolution, $mode),
  4465. ];
  4466. } elseif (in_array($type, ['batch_segment', 'batch_act'])) {
  4467. // 批量场景
  4468. $animeId = getProp($data, 'anime_id');
  4469. $episodeId = getProp($data, 'episode_id');
  4470. if (!$animeId || !$episodeId) {
  4471. Utils::throwError('1002:anime_id和episode_id不能为空');
  4472. }
  4473. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  4474. if (!$episode) {
  4475. Utils::throwError('20003:分集不存在');
  4476. }
  4477. if ($type === 'batch_segment') {
  4478. $model = getProp($data, 'model') ?: getProp($episode, 'video_model', 'doubao-seedance-1-5-pro-251215');
  4479. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4480. $model = 'doubao-seedance-1-5-pro-251215';
  4481. }
  4482. $segments = DB::table('mp_episode_segments')
  4483. ->where('anime_id', $animeId)
  4484. ->where('episode_id', $episodeId)
  4485. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  4486. ->orderBy('segment_number')
  4487. ->get();
  4488. foreach ($segments as $segment) {
  4489. if ((int)$segment->current_type === 2) {
  4490. continue;
  4491. }
  4492. $duration = (int)ceil((float)$segment->audio_duration);
  4493. if ($duration <= 0) {
  4494. $duration = 5;
  4495. }
  4496. $items[] = [
  4497. 'id' => $segment->segment_id,
  4498. 'duration' => $duration,
  4499. 'points' => $buildCharge($segment->segment_id, $duration, $model, '720p', $mode),
  4500. ];
  4501. }
  4502. } else {
  4503. // 片段批量固定智帧20
  4504. $model = 'zhizhen-20';
  4505. $acts = DB::table('mp_episode_segments')
  4506. ->where('anime_id', $animeId)
  4507. ->where('episode_id', $episodeId)
  4508. ->orderBy('act_number')
  4509. ->get();
  4510. foreach ($acts as $act) {
  4511. if ($act->video_task_status === '生成中' || (int)$act->current_type === 2) {
  4512. continue;
  4513. }
  4514. $duration = (int)ceil((float)$act->act_duration);
  4515. if ($duration <= 0) {
  4516. $duration = 5;
  4517. }
  4518. $items[] = [
  4519. 'id' => $act->id,
  4520. 'duration' => $duration,
  4521. 'points' => $buildCharge($act->id, $duration, $model, '720p', $mode),
  4522. ];
  4523. }
  4524. }
  4525. } else {
  4526. Utils::throwError('1003:type参数不正确');
  4527. }
  4528. $totalPoints = 0;
  4529. foreach ($items as $item) {
  4530. $totalPoints += $item['points'];
  4531. }
  4532. return [
  4533. 'type' => $type,
  4534. 'model' => $model,
  4535. 'video_resolution' => $resolution,
  4536. 'mode' => $mode,
  4537. 'count' => count($items),
  4538. 'total_points' => $totalPoints,
  4539. 'items' => $items,
  4540. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4541. 'remark' => '积分为预估值,按预估时长计算;实际扣费以视频生成完成后的实际时长为准',
  4542. ];
  4543. }
  4544. /**
  4545. * 根据提示词内容智能计算最优视频时长
  4546. *
  4547. * @param string $segmentContent 分镜内容
  4548. * @param string $tailFrame 尾帧描述
  4549. * @return int 视频时长(2-12秒)
  4550. */
  4551. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4552. // 合并所有文本内容
  4553. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4554. // 如果没有内容,返回默认时长
  4555. if (empty($fullText)) {
  4556. return 5;
  4557. }
  4558. // 计算文本长度(中文字符按2个字符计算)
  4559. $textLength = mb_strlen($fullText, 'UTF-8');
  4560. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4561. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4562. // 分析内容复杂度
  4563. $complexityScore = $this->analyzeContentComplexity($fullText);
  4564. // 基础时长计算(根据文本长度)
  4565. $baseDuration = 3; // 默认2秒
  4566. // if ($adjustedLength <= 20) {
  4567. // $baseDuration = 3;
  4568. // } elseif ($adjustedLength <= 40) {
  4569. // $baseDuration = 4;
  4570. // } elseif ($adjustedLength <= 60) {
  4571. // $baseDuration = 5;
  4572. // } elseif ($adjustedLength <= 80) {
  4573. // $baseDuration = 6;
  4574. // } elseif ($adjustedLength <= 100) {
  4575. // $baseDuration = 7;
  4576. // } elseif ($adjustedLength <= 120) {
  4577. // $baseDuration = 8;
  4578. // } else {
  4579. // $baseDuration = 9;
  4580. // }
  4581. // 根据内容复杂度调整时长
  4582. $finalDuration = $baseDuration + $complexityScore;
  4583. // 确保时长在2-12秒范围内
  4584. return max(4, min(12, $finalDuration));
  4585. }
  4586. /**
  4587. * 分析内容复杂度,返回时长调整值
  4588. *
  4589. * @param string $text 文本内容
  4590. * @return int 调整值(-2到+3)
  4591. */
  4592. private function analyzeContentComplexity($text) {
  4593. $score = 0;
  4594. // 动作关键词(需要更长时间展现)
  4595. $actionKeywords = [
  4596. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4597. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4598. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4599. ];
  4600. // 静态关键词(可以用较短时间)
  4601. $staticKeywords = [
  4602. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4603. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4604. ];
  4605. // 复杂场景关键词(需要更长时间)
  4606. $complexSceneKeywords = [
  4607. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4608. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4609. ];
  4610. // 情感关键词(需要适中时间表现)
  4611. $emotionKeywords = [
  4612. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4613. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4614. ];
  4615. // 检查动作关键词
  4616. foreach ($actionKeywords as $keyword) {
  4617. if (strpos($text, $keyword) !== false) {
  4618. $score += 1;
  4619. break; // 避免重复加分
  4620. }
  4621. }
  4622. // 检查静态关键词
  4623. foreach ($staticKeywords as $keyword) {
  4624. if (strpos($text, $keyword) !== false) {
  4625. $score -= 1;
  4626. break;
  4627. }
  4628. }
  4629. // 检查复杂场景关键词
  4630. foreach ($complexSceneKeywords as $keyword) {
  4631. if (strpos($text, $keyword) !== false) {
  4632. $score += 1;
  4633. break;
  4634. }
  4635. }
  4636. // 检查情感关键词
  4637. foreach ($emotionKeywords as $keyword) {
  4638. if (strpos($text, $keyword) !== false) {
  4639. $score += 1;
  4640. break;
  4641. }
  4642. }
  4643. // 检查时间相关词汇
  4644. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4645. $score += 1;
  4646. }
  4647. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4648. $score -= 1;
  4649. }
  4650. // 检查转场词汇
  4651. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4652. $score += 1;
  4653. }
  4654. // 检查环境描述(复杂环境需要更多时间)
  4655. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4656. $score += 1;
  4657. }
  4658. // 检查对话内容(对话需要更多时间)
  4659. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4660. $score += 1;
  4661. }
  4662. // 限制调整范围
  4663. return max(-1, min(4, $score));
  4664. }
  4665. /**
  4666. * 创建完整视频合成任务
  4667. *
  4668. * @param array $data
  4669. * @return array
  4670. */
  4671. public function createCompleteVideoTask($data)
  4672. {
  4673. $animeId = getProp($data, 'anime_id');
  4674. $episodeId = getProp($data, 'episode_id');
  4675. // 验证参数
  4676. if (!$animeId || !$episodeId) {
  4677. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4678. }
  4679. // 检查是否已存在处理中的任务
  4680. $existingTask = DB::table('mp_complete_video_tasks')
  4681. ->where('anime_id', $animeId)
  4682. ->where('episode_id', $episodeId)
  4683. ->whereIn('generate_status', ['执行中'])
  4684. ->first();
  4685. if ($existingTask) {
  4686. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4687. }
  4688. // 获取全能模式状态
  4689. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4690. if ((int)$ace_mode === 1) {
  4691. // 获取所有片段的配音视频,按 act_number 排序
  4692. $segments = DB::table('mp_episode_segments')
  4693. ->where('anime_id', $animeId)
  4694. ->where('episode_id', $episodeId)
  4695. ->orderBy('segment_number')
  4696. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4697. ->get();
  4698. // 检查是否所有片段都有视频
  4699. $missingVideos = $segments->filter(function($segment) {
  4700. return empty($segment->video_url);
  4701. });
  4702. if ($missingVideos->isNotEmpty()) {
  4703. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4704. }
  4705. }else {
  4706. // 获取所有分镜的配音视频,按 segment_number 排序
  4707. $segments = DB::table('mp_episode_segments')
  4708. ->where('anime_id', $animeId)
  4709. ->where('episode_id', $episodeId)
  4710. ->orderBy('segment_number')
  4711. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4712. ->get();
  4713. // 检查是否所有分镜都有配音和视频
  4714. $missingVideos = $segments->filter(function($segment) {
  4715. return empty($segment->audio_url) || empty($segment->video_url);
  4716. });
  4717. if ($missingVideos->isNotEmpty()) {
  4718. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4719. }
  4720. }
  4721. if ($segments->isEmpty()) {
  4722. Utils::throwError('20003:未找到该剧集的分镜数据');
  4723. }
  4724. // 获取当前完整视频url
  4725. $completeVideoUrl = DB::table('mp_anime_episodes')
  4726. ->where('anime_id', $animeId)
  4727. ->where('id', $episodeId)
  4728. ->value('complete_video_url');
  4729. // 构建 generate_json
  4730. $generateJson = [];
  4731. $sequence = 1;
  4732. foreach ($segments as $segment) {
  4733. if ((int)$ace_mode === 1) {
  4734. $generateJson[] = [
  4735. 'sequence' => $sequence++,
  4736. 'video_url' => $segment->video_url,
  4737. 'video_time_point_start' => $segment->video_time_point_start,
  4738. 'video_time_point_end' => $segment->video_time_point_end
  4739. ];
  4740. }else {
  4741. $generateJson[] = [
  4742. 'sequence' => $sequence++,
  4743. 'video_url' => $segment->video_url,
  4744. 'audio_url' => $segment->audio_url,
  4745. 'video_time_point_start' => $segment->video_time_point_start,
  4746. 'video_time_point_end' => $segment->video_time_point_end
  4747. ];
  4748. }
  4749. }
  4750. // 创建任务
  4751. $now = date('Y-m-d H:i:s');
  4752. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4753. 'anime_id' => $animeId,
  4754. 'episode_id' => $episodeId,
  4755. 'generate_json' => json_encode($generateJson, 256),
  4756. 'generate_status' => '执行中',
  4757. 'complete_video_url' => '',
  4758. 'created_at' => $now,
  4759. 'updated_at' => $now
  4760. ]);
  4761. if (!$taskId) {
  4762. Utils::throwError('20003:创建任务失败');
  4763. }
  4764. // 更新剧集表的任务ID和状态
  4765. $boolen = DB::table('mp_anime_episodes')
  4766. ->where('anime_id', $animeId)
  4767. ->where('id', $episodeId)
  4768. ->update([
  4769. 'complete_video_task_id' => $taskId,
  4770. 'complete_video_task_status' => '执行中',
  4771. 'updated_at' => $now
  4772. ]);
  4773. if (!$boolen) {
  4774. Utils::throwError('20003:更新剧集表失败');
  4775. }
  4776. dLog('anime')->info('创建完整视频合成任务', [
  4777. 'task_id' => $taskId,
  4778. 'anime_id' => $animeId,
  4779. 'episode_id' => $episodeId,
  4780. 'segment_count' => count($generateJson)
  4781. ]);
  4782. // 请求远程服务器执行生成
  4783. $client = new Client(['timeout' => 600, 'verify' => false]);
  4784. try {
  4785. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4786. $response = $result->getBody()->getContents();
  4787. $response_arr = json_decode($response, true);
  4788. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4789. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4790. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4791. // // 更新任务状态为失败
  4792. // DB::table('mp_complete_video_tasks')
  4793. // ->where('id', $taskId)
  4794. // ->update([
  4795. // 'generate_status' => '执行失败',
  4796. // 'error_message' => $error_msg,
  4797. // 'updated_at' => date('Y-m-d H:i:s')
  4798. // ]);
  4799. // // 同步更新剧集表状态
  4800. // DB::table('mp_anime_episodes')
  4801. // ->where('complete_video_task_id', $taskId)
  4802. // ->update([
  4803. // 'complete_video_task_status' => '执行失败',
  4804. // 'updated_at' => date('Y-m-d H:i:s')
  4805. // ]);
  4806. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4807. }
  4808. } catch (\Exception $e) {
  4809. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4810. // 更新任务状态为失败
  4811. DB::table('mp_complete_video_tasks')
  4812. ->where('id', $taskId)
  4813. ->update([
  4814. 'generate_status' => '执行失败',
  4815. 'error_message' => $e->getMessage(),
  4816. 'updated_at' => date('Y-m-d H:i:s')
  4817. ]);
  4818. // 同步更新剧集表状态
  4819. DB::table('mp_anime_episodes')
  4820. ->where('complete_video_task_id', $taskId)
  4821. ->update([
  4822. 'complete_video_task_status' => '执行失败',
  4823. 'updated_at' => date('Y-m-d H:i:s')
  4824. ]);
  4825. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4826. }
  4827. // 开始轮询任务状态
  4828. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4829. $pollInterval = 5; // 每5秒轮询一次
  4830. $attempt = 0;
  4831. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4832. while ($attempt < $maxAttempts) {
  4833. sleep($pollInterval);
  4834. $attempt++;
  4835. // 查询任务状态
  4836. $task = DB::table('mp_complete_video_tasks')
  4837. ->where('id', $taskId)
  4838. ->first();
  4839. if (!$task) {
  4840. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4841. Utils::throwError('20003:任务不存在');
  4842. }
  4843. dLog('anime')->info('轮询任务状态', [
  4844. 'task_id' => $taskId,
  4845. 'attempt' => $attempt,
  4846. 'status' => $task->generate_status
  4847. ]);
  4848. // 检查任务是否完成
  4849. if ($task->generate_status === '执行成功') {
  4850. // 同步更新剧集表状态
  4851. $boolen3 = DB::table('mp_anime_episodes')
  4852. ->where('anime_id', $animeId)
  4853. ->where('id', $episodeId)
  4854. ->update([
  4855. 'complete_video_url' => $task->complete_video_url,
  4856. 'complete_video_task_status' => '执行成功',
  4857. 'updated_at' => date('Y-m-d H:i:s')
  4858. ]);
  4859. dLog('anime')->info('视频合成任务完成', [
  4860. 'task_id' => $taskId,
  4861. 'video_url' => $task->complete_video_url,
  4862. 'attempts' => $attempt
  4863. ]);
  4864. // 如果更新成功则远程删除之前的文件
  4865. if ($boolen3 && $completeVideoUrl) {
  4866. $encode_url = urlencode($completeVideoUrl);
  4867. $client = new Client(['timeout' => 300, 'verify' => false]);
  4868. // 根据ID通过API通知合成音频
  4869. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4870. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4871. $response = $result->getBody()->getContents();
  4872. $response_arr = json_decode($response, true);
  4873. Log::info('火山删除音频返回: '.$response);
  4874. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4875. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4876. Log::info('火山删除音频失败: '.$error_msg);
  4877. // Utils::throwError('20003:火山删除音频失败');
  4878. }
  4879. }
  4880. return [
  4881. 'task_id' => $taskId,
  4882. 'anime_id' => $animeId,
  4883. 'episode_id' => $episodeId,
  4884. 'segment_count' => count($generateJson),
  4885. 'generate_status' => '执行成功',
  4886. 'complete_video_url' => $task->complete_video_url,
  4887. ];
  4888. }
  4889. // 检查任务是否失败
  4890. if ($task->generate_status === '执行失败') {
  4891. // 同步更新剧集表状态
  4892. DB::table('mp_anime_episodes')
  4893. ->where('anime_id', $animeId)
  4894. ->where('id', $episodeId)
  4895. ->update([
  4896. 'complete_video_task_status' => '执行失败',
  4897. 'updated_at' => date('Y-m-d H:i:s')
  4898. ]);
  4899. $errorMessage = $task->error_message ?? '未知错误';
  4900. dLog('anime')->error('视频合成任务失败', [
  4901. 'task_id' => $taskId,
  4902. 'error' => $errorMessage,
  4903. 'attempts' => $attempt
  4904. ]);
  4905. return [
  4906. 'task_id' => $taskId,
  4907. 'anime_id' => $animeId,
  4908. 'episode_id' => $episodeId,
  4909. 'segment_count' => count($generateJson),
  4910. 'generate_status' => '执行失败',
  4911. 'error_message' => $errorMessage
  4912. ];
  4913. }
  4914. }
  4915. // 超时处理
  4916. dLog('anime')->warning('视频合成任务超时', [
  4917. 'task_id' => $taskId,
  4918. 'max_attempts' => $maxAttempts,
  4919. 'timeout_seconds' => $maxAttempts * $pollInterval
  4920. ]);
  4921. // 更新任务状态为超时
  4922. DB::table('mp_complete_video_tasks')
  4923. ->where('id', $taskId)
  4924. ->update([
  4925. 'generate_status' => '超时',
  4926. 'error_message' => '任务执行超时(5分钟)',
  4927. 'updated_at' => date('Y-m-d H:i:s')
  4928. ]);
  4929. return [
  4930. 'task_id' => $taskId,
  4931. 'anime_id' => $animeId,
  4932. 'episode_id' => $episodeId,
  4933. 'segment_count' => count($generateJson),
  4934. 'generate_status' => '超时',
  4935. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4936. ];
  4937. }
  4938. /**
  4939. * 根据 inner_prompt_type 附加内置提示词
  4940. *
  4941. * @param string $prompt 用户提示词
  4942. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4943. * @return string 合并后的提示词
  4944. */
  4945. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4946. {
  4947. $innerPromptMap = [
  4948. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4949. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4950. ];
  4951. if (!isset($innerPromptMap[$innerPromptType])) {
  4952. return $prompt;
  4953. }
  4954. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4955. }
  4956. /**
  4957. * 根据 inner_prompt_type 获取生成图片数量
  4958. *
  4959. * @param int $innerPromptType 内置提示词类型
  4960. * @return int 图片数量
  4961. */
  4962. public static function getInnerImageNum($innerPromptType = 0)
  4963. {
  4964. return (int)$innerPromptType === 2 ? 9 : 1;
  4965. }
  4966. /**
  4967. * 提取图片生成结果URL
  4968. *
  4969. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4970. * @param int $innerPromptType 内置提示词类型
  4971. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4972. */
  4973. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4974. {
  4975. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4976. if (is_array($resultUrls) && !empty($resultUrls)) {
  4977. $resultUrls = array_values($resultUrls);
  4978. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4979. }
  4980. if (!empty($resultUrl)) {
  4981. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4982. }
  4983. return (int)$innerPromptType === 2 ? [] : '';
  4984. }
  4985. public function generateImg($data) {
  4986. $prompt = getProp($data, 'prompt');
  4987. $episode_id = getProp($data, 'episode_id');
  4988. $ref_img_urls = getProp($data, 'ref_img_urls');
  4989. $ratio = getProp($data, 'ratio', '9:16');
  4990. $resolution = getProp($data, 'resolution', '2k');
  4991. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4992. // 定义分辨率和宽高比对应的尺寸映射表
  4993. $sizeMap = [
  4994. '2k' => [
  4995. '1:1' => ['width' => 2048, 'height' => 2048],
  4996. '4:3' => ['width' => 2304, 'height' => 1728],
  4997. '3:4' => ['width' => 1728, 'height' => 2304],
  4998. '16:9' => ['width' => 2848, 'height' => 1600],
  4999. '9:16' => ['width' => 1600, 'height' => 2848],
  5000. '3:2' => ['width' => 2496, 'height' => 1664],
  5001. '2:3' => ['width' => 1664, 'height' => 2496],
  5002. '21:9' => ['width' => 3136, 'height' => 1344],
  5003. ],
  5004. '3k' => [
  5005. '1:1' => ['width' => 3072, 'height' => 3072],
  5006. '4:3' => ['width' => 3456, 'height' => 2592],
  5007. '3:4' => ['width' => 2592, 'height' => 3456],
  5008. '16:9' => ['width' => 4096, 'height' => 2304],
  5009. '9:16' => ['width' => 2304, 'height' => 4096],
  5010. '2:3' => ['width' => 2496, 'height' => 3744],
  5011. '3:2' => ['width' => 3744, 'height' => 2496],
  5012. '21:9' => ['width' => 4704, 'height' => 2016],
  5013. ],
  5014. '4k' => [
  5015. '1:1' => ['width' => 4096, 'height' => 4096],
  5016. '3:4' => ['width' => 3520, 'height' => 4704],
  5017. '4:3' => ['width' => 4704, 'height' => 3520],
  5018. '16:9' => ['width' => 5504, 'height' => 3040],
  5019. '9:16' => ['width' => 3040, 'height' => 5504],
  5020. '2:3' => ['width' => 3328, 'height' => 4992],
  5021. '3:2' => ['width' => 4992, 'height' => 3328],
  5022. '21:9' => ['width' => 6240, 'height' => 2656],
  5023. ],
  5024. ];
  5025. // 参数验证
  5026. $resolution = strtolower($resolution);
  5027. if (!isset($sizeMap[$resolution])) {
  5028. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5029. }
  5030. if (!isset($sizeMap[$resolution][$ratio])) {
  5031. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5032. }
  5033. // 根据 ratio 和 resolution 确定宽高
  5034. $width = $sizeMap[$resolution][$ratio]['width'];
  5035. $height = $sizeMap[$resolution][$ratio]['height'];
  5036. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5037. if (is_json($ref_img_urls)) {
  5038. $ref_img_urls = json_decode($ref_img_urls, true);
  5039. }else {
  5040. $ref_img_urls = explode(',', $ref_img_urls);
  5041. }
  5042. }
  5043. // 处理图片模型
  5044. $model = getProp($data, 'model');
  5045. if (!$model) {
  5046. // 用户没有输入,从episode表获取
  5047. if ($episode_id) {
  5048. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5049. $model = getProp($episode, 'image_model');
  5050. }
  5051. if (!$model) {
  5052. // episode表也没有,使用默认值
  5053. $model = 'doubao-seedream-5-0-lite-260128';
  5054. }
  5055. }
  5056. // 验证模型是否在可用模型表中
  5057. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5058. // $model = 'doubao-seedream-5-0-lite-260128';
  5059. Utils::throwError('20003:该模型已不可用,请更换!');
  5060. }
  5061. // 保存到episode表
  5062. if ($episode_id) {
  5063. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5064. 'image_model' => $model,
  5065. 'updated_at' => date('Y-m-d H:i:s')
  5066. ]);
  5067. }
  5068. // 参数验证
  5069. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5070. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5071. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5072. $imageNum = self::getInnerImageNum($inner_prompt_type);
  5073. try {
  5074. // 创建图片生成任务
  5075. $params = [
  5076. 'prompt' => $prompt,
  5077. 'model' => $model,
  5078. 'ref_img_urls' => '',
  5079. 'width' => $width,
  5080. 'height' => $height,
  5081. 'image_num' => $imageNum
  5082. ];
  5083. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5084. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5085. $task_id = $task->id;
  5086. if (!$task_id) {
  5087. Utils::throwError('20003:创建图片生成任务失败');
  5088. }
  5089. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5090. $model = getProp($task, 'model');
  5091. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5092. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5093. $isSyncModel = $isVolcModel || $isGptModel;
  5094. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5095. $start_time = time();
  5096. $timeout = 300; // 5分钟
  5097. $img_url = '';
  5098. while (time() - $start_time < $timeout) {
  5099. sleep(3);
  5100. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5101. if ($isSyncModel) {
  5102. // 刷新任务状态
  5103. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5104. if ($task->status === 'success' && $task->result_url) {
  5105. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  5106. break;
  5107. } elseif ($task->status === 'failed') {
  5108. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5109. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5110. }
  5111. // // 如果还在处理中,提示用户稍后查看
  5112. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5113. }else {
  5114. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5115. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5116. if ($statusInfo['status'] === 'success') {
  5117. $task->updateStatus('success', [
  5118. 'result_url' => $statusInfo['result_url'],
  5119. 'result_json' => $statusInfo['result_json'] ?? []
  5120. ]);
  5121. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  5122. break;
  5123. } elseif ($statusInfo['status'] === 'failed') {
  5124. $task->updateStatus('failed', [
  5125. 'error_message' => $statusInfo['error_message'],
  5126. 'result_json' => $statusInfo['result_json'] ?? []
  5127. ]);
  5128. dLog('anime')->error('图片生成失败,', [
  5129. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5130. ]);
  5131. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5132. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5133. }
  5134. }
  5135. }
  5136. if (empty($img_url)) {
  5137. Utils::throwError('20003:图片生成超时,请稍后重试');
  5138. }
  5139. return $img_url;
  5140. } catch (\Exception $e) {
  5141. dLog('anime')->error('更新角色或场景失败', [
  5142. 'error' => $e->getMessage()
  5143. ]);
  5144. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5145. Utils::throwError('20003:' . $e->getMessage());
  5146. }
  5147. }
  5148. /**
  5149. * 使用文生文模型解析分镜内容
  5150. */
  5151. private function parseSegmentContentWithAI($segment_content) {
  5152. try {
  5153. // 使用DeepSeek服务的公开方法解析分镜内容
  5154. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5155. } catch (\Exception $e) {
  5156. // 如果AI解析失败,记录日志并返回原内容
  5157. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5158. return $segment_content;
  5159. }
  5160. }
  5161. /**
  5162. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5163. *
  5164. * @param int $episode_id 分集ID
  5165. * @param int $anime_id 动漫ID
  5166. * @param array $roles 分集角色数组(引用传递)
  5167. * @param array $scenes 分集场景数组(引用传递)
  5168. * @param array $episode 分集数据
  5169. */
  5170. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5171. // 获取全局动漫的角色和场景数据
  5172. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5173. if (!$anime) return;
  5174. $art_style_type = getProp($anime, 'art_style_type');
  5175. $character_prefix = '';
  5176. $scene_prefix = '';
  5177. if ($art_style_type) {
  5178. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5179. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5180. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5181. }
  5182. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5183. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5184. $roles_updated = false;
  5185. $scenes_updated = false;
  5186. // 处理角色
  5187. foreach ($roles as &$role) {
  5188. $role_name = getProp($role, 'role');
  5189. $role_description = getProp($role, 'description');
  5190. $role_pic_prompt = getProp($role, 'pic_prompt');
  5191. $role_url = getProp($role, 'url');
  5192. $role_task_id = getProp($role, 'task_id');
  5193. // 如果已有URL或已有任务ID,跳过
  5194. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5195. continue;
  5196. }
  5197. $url_inherited = false;
  5198. // 尝试从全局数据中继承
  5199. foreach ($global_roles as $global_role) {
  5200. $global_role_name = getProp($global_role, 'role');
  5201. $global_role_description = getProp($global_role, 'description');
  5202. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5203. $global_role_url = getProp($global_role, 'url');
  5204. $global_role_task_id = getProp($global_role, 'task_id');
  5205. $global_role_task_status = getProp($global_role, 'task_status');
  5206. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5207. if ($role_name === $global_role_name
  5208. && $role_description === $global_role_description
  5209. && $role_pic_prompt === $global_role_pic_prompt
  5210. && !empty($global_role_url)) {
  5211. // 继承 task_id、task_status 和 url
  5212. $role['task_id'] = $global_role_task_id;
  5213. $role['task_status'] = $global_role_task_status;
  5214. $role['url'] = $global_role_url;
  5215. $roles_updated = true;
  5216. $url_inherited = true;
  5217. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5218. break;
  5219. }
  5220. }
  5221. // 如果无法继承且没有任务ID,创建新任务
  5222. if (!$url_inherited && empty($role_task_id)) {
  5223. try {
  5224. $art_style = getProp($episode, 'art_style');
  5225. // 优先使用 pic_prompt,如果没有则使用 description
  5226. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5227. // if ($art_style) {
  5228. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5229. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5230. // }
  5231. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5232. $params = [
  5233. 'prompt' => $description,
  5234. 'ref_img_urls' => []
  5235. ];
  5236. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5237. $task_id = $task->id;
  5238. if ($task_id) {
  5239. $role['task_id'] = $task_id;
  5240. $role['task_status'] = 'processing';
  5241. $roles_updated = true;
  5242. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5243. }
  5244. } catch (\Exception $e) {
  5245. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5246. }
  5247. }
  5248. }
  5249. // 处理场景
  5250. foreach ($scenes as &$scene) {
  5251. $scene_name = getProp($scene, 'scene');
  5252. $scene_description = getProp($scene, 'description');
  5253. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5254. $scene_url = getProp($scene, 'url');
  5255. $scene_task_id = getProp($scene, 'task_id');
  5256. // 如果已有URL或已有任务ID,跳过
  5257. if (!empty($scene_url) || !empty($scene_task_id)) {
  5258. continue;
  5259. }
  5260. $url_inherited = false;
  5261. // 尝试从全局数据中继承
  5262. foreach ($global_scenes as $global_scene) {
  5263. $global_scene_name = getProp($global_scene, 'scene');
  5264. $global_scene_description = getProp($global_scene, 'description');
  5265. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5266. $global_scene_url = getProp($global_scene, 'url');
  5267. $global_scene_task_id = getProp($global_scene, 'task_id');
  5268. $global_scene_task_status = getProp($global_scene, 'task_status');
  5269. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5270. if ($scene_name === $global_scene_name
  5271. && $scene_description === $global_scene_description
  5272. && $scene_pic_prompt === $global_scene_pic_prompt
  5273. && !empty($global_scene_url)) {
  5274. // 继承 task_id、task_status 和 url
  5275. $scene['task_id'] = $global_scene_task_id;
  5276. $scene['task_status'] = $global_scene_task_status;
  5277. $scene['url'] = $global_scene_url;
  5278. $scenes_updated = true;
  5279. $url_inherited = true;
  5280. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5281. break;
  5282. }
  5283. }
  5284. // 如果无法继承且没有任务ID,创建新任务
  5285. if (!$url_inherited && empty($scene_task_id)) {
  5286. try {
  5287. $art_style = getProp($episode, 'art_style');
  5288. // 优先使用 pic_prompt,如果没有则使用 description
  5289. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5290. // if ($art_style) {
  5291. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5292. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5293. // }
  5294. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5295. $params = [
  5296. 'prompt' => $description,
  5297. 'ref_img_urls' => []
  5298. ];
  5299. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5300. $task_id = $task->id;
  5301. if ($task_id) {
  5302. $scene['task_id'] = $task_id;
  5303. $scene['task_status'] = 'processing';
  5304. $scenes_updated = true;
  5305. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5306. }
  5307. } catch (\Exception $e) {
  5308. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5309. }
  5310. }
  5311. }
  5312. // 如果有更新,保存到数据库
  5313. if ($roles_updated || $scenes_updated) {
  5314. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5315. if ($roles_updated) {
  5316. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5317. }
  5318. if ($scenes_updated) {
  5319. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5320. }
  5321. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5322. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5323. }
  5324. }
  5325. /**
  5326. * 根据图片URL使用AI反推图片提示词
  5327. *
  5328. * @param string $img_url 图片URL
  5329. * @return string 反推的提示词
  5330. */
  5331. private function generateImagePromptFromUrl($img_url) {
  5332. try {
  5333. // 获取默认模型
  5334. $model = 'doubao-seed-2-0-mini-260215';
  5335. // 构建messages参数
  5336. $messages = [
  5337. [
  5338. 'role' => 'user',
  5339. 'content' => [
  5340. [
  5341. 'type' => 'text',
  5342. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5343. ],
  5344. [
  5345. 'type' => 'image_url',
  5346. 'image_url' => [
  5347. 'url' => $img_url
  5348. ]
  5349. ]
  5350. ]
  5351. ]
  5352. ];
  5353. // 构建请求参数
  5354. $params = [
  5355. 'model' => $model,
  5356. 'messages' => $messages,
  5357. 'stream' => false,
  5358. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5359. ];
  5360. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5361. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5362. // 返回生成的内容
  5363. return getProp($result, 'fullContent', '图片描述生成失败');
  5364. } catch (\Exception $e) {
  5365. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5366. 'img_url' => $img_url
  5367. ]);
  5368. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5369. 'error' => $e->getMessage(),
  5370. 'img_url' => $img_url
  5371. ]);
  5372. return '图片描述生成失败: ' . $e->getMessage();
  5373. }
  5374. }
  5375. /**
  5376. * 音频试听接口
  5377. * 创建音频任务并轮询获取结果
  5378. *
  5379. * @param array $data 参数数组
  5380. * @return array 返回音频URL或错误信息
  5381. */
  5382. public function previewAudio($data) {
  5383. $dialogue = getProp($data, 'dialogue');
  5384. // 必填参数验证
  5385. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5386. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5387. $voice_type = getProp($data, 'voice_type');
  5388. $voice_name = getProp($data, 'voice_name');
  5389. $voice_actor = getProp($data, 'voice_actor');
  5390. $emotion_type = getProp($data, 'emotion_type');
  5391. $gender = getProp($data, 'gender', 0);
  5392. $emotion = getProp($data, 'emotion');
  5393. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5394. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5395. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5396. $pitch = getProp($data, 'pitch', 0);
  5397. try {
  5398. $now = date('Y-m-d H:i:s');
  5399. // 构建生成参数
  5400. $generate_json = json_encode([
  5401. 'text' => $dialogue,
  5402. 'role' => $voice_actor,
  5403. 'voice_type' => $voice_type,
  5404. 'voice_name' => $voice_name,
  5405. 'emotion' => $emotion,
  5406. 'emotion_type' => $emotion_type,
  5407. 'gender' => $gender,
  5408. 'speed_ratio' => $speed_ratio,
  5409. 'loudness_ratio' => $loudness_ratio,
  5410. 'emotion_scale' => $emotion_scale,
  5411. 'pitch' => $pitch,
  5412. ], 256);
  5413. // 请求远程服务器执行生成
  5414. $client = new Client(['timeout' => 600, 'verify' => false]);
  5415. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5416. $response = $result->getBody()->getContents();
  5417. $response_arr = json_decode($response, true);
  5418. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5419. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5420. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5421. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5422. }
  5423. $arr = $response_arr['data'];
  5424. $subtitle_info = $arr['subtitle_info'];
  5425. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5426. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5427. return [
  5428. 'audio_url' => $arr['url'],
  5429. 'subtitle_info' => $subtitle_info,
  5430. 'audio_duration' => round($audio_duration, 2)
  5431. ];
  5432. } catch (\Exception $e) {
  5433. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5434. Utils::throwError('20003:' . $e->getMessage());
  5435. }
  5436. }
  5437. /**
  5438. * 获取角色库列表(支持文件夹递归查询)
  5439. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5440. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5441. */
  5442. public function globalProducts($data) {
  5443. $uid = Site::getUid();
  5444. $cpid = Site::getCpid();
  5445. $role = Site::getRole();
  5446. $id = getProp($data, 'id', 0);
  5447. $parent_id = getProp($data, 'parent_id', 0);
  5448. $product_name = getProp($data, 'product_name');
  5449. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5450. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5451. if (!$product) {
  5452. Utils::throwError('20003:请选择产品类型');
  5453. }
  5454. // 根据角色和is_public参数确定查询范围
  5455. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5456. // user角色:根据is_public参数筛选
  5457. $query_user_ids = [];
  5458. if ($role === 'admin') {
  5459. // admin获取所有个人库和公共库
  5460. $query_user_ids = [$uid, 0];
  5461. } else {
  5462. // user角色根据is_public参数筛选
  5463. if ($is_public == 2) {
  5464. // 个人库+公共库
  5465. $query_user_ids = [$uid, 0];
  5466. } elseif ($is_public == 0) {
  5467. // 仅个人库
  5468. $query_user_ids = [$uid];
  5469. } elseif ($is_public == 1) {
  5470. // 仅公共库
  5471. $query_user_ids = [0];
  5472. }
  5473. }
  5474. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5475. if ($id || $product_name) {
  5476. $query = DB::table('mp_products')
  5477. ->where('cpid', $cpid)
  5478. ->whereIn('user_id', $query_user_ids)
  5479. ->where('is_deleted', 0);
  5480. // 如果指定了 id,按 id 精确查询
  5481. if ($id) {
  5482. $query->where('id', $id);
  5483. }
  5484. // 如果指定了 product_name,按名称模糊查询
  5485. if ($product_name) {
  5486. $query->where('product_name', 'like', "%{$product_name}%");
  5487. }
  5488. // 如果指定了 product,添加筛选条件
  5489. if ($product) {
  5490. $query->where('product', $product);
  5491. }
  5492. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5493. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5494. ->get()
  5495. ->map(function($value) {
  5496. $value = (array)$value;
  5497. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5498. $value['type'] = (int)$value['type'];
  5499. $value['parent_id'] = (int)$value['parent_id'];
  5500. $value['level'] = (int)$value['level'];
  5501. $value['product'] = (int)($value['product'] ?? 1);
  5502. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5503. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5504. unset($value['user_id']);
  5505. return $value;
  5506. })
  5507. ->toArray();
  5508. return $result;
  5509. }
  5510. // 递归获取所有子目录和角色
  5511. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5512. }
  5513. /**
  5514. * 递归获取指定目录下的所有子目录和角色
  5515. * @param int $cpid 公司ID
  5516. * @param int $parent_id 父目录ID
  5517. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5518. * @param array $query_user_ids 用户ID数组(支持多个)
  5519. * @param int $current_uid 当前用户ID(用于排序)
  5520. * @return array
  5521. */
  5522. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5523. // 查询当前层级的所有项(文件夹和角色)
  5524. $query = DB::table('mp_products')
  5525. ->where('cpid', $cpid)
  5526. ->where('is_deleted', 0)
  5527. ->where('parent_id', $parent_id);
  5528. // 添加用户ID验证(支持多个user_id)
  5529. if (!empty($query_user_ids)) {
  5530. $query->whereIn('user_id', $query_user_ids);
  5531. }
  5532. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5533. if ($product) {
  5534. $query->where('product', $product);
  5535. }
  5536. // 排序规则:
  5537. // 1. 文件夹在前(type DESC)
  5538. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5539. // 3. 其他排序规则
  5540. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5541. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5542. ->get();
  5543. $result = [];
  5544. foreach ($items as $item) {
  5545. $itemArray = [
  5546. 'id' => $item->id,
  5547. 'type' => (int)$item->type,
  5548. 'parent_id' => (int)$item->parent_id,
  5549. 'level' => (int)$item->level,
  5550. 'product_name' => $item->product_name,
  5551. 'url' => $item->url,
  5552. 'pic_prompt' => $item->pic_prompt ?? '',
  5553. 'three_view_image_url' => $item->three_view_image_url,
  5554. 'product' => (int)($item->product ?? 1),
  5555. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5556. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5557. ];
  5558. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5559. // 如果是文件夹,递归获取其子项
  5560. if ($item->type == 2) {
  5561. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5562. if (!empty($children)) {
  5563. $itemArray['children'] = $children;
  5564. }
  5565. }
  5566. $result[] = $itemArray;
  5567. }
  5568. return $result;
  5569. }
  5570. /**
  5571. * 创建文件夹
  5572. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5573. * @return int 返回新建文件夹ID
  5574. */
  5575. public function createFolder($data) {
  5576. $uid = Site::getUid();
  5577. $cpid = Site::getCpid();
  5578. $role = Site::getRole();
  5579. $parent_id = getProp($data, 'parent_id', 0);
  5580. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5581. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5582. // 如果是公共库操作,需要admin权限
  5583. if ($is_public && $role !== 'admin') {
  5584. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5585. }
  5586. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5587. $store_uid = $is_public ? 0 : $uid;
  5588. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5589. $product = getProp($data, 'product');
  5590. if (!in_array($product, [1, 2, 3])) {
  5591. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5592. }
  5593. // 验证父文件夹
  5594. $parent_level = 0;
  5595. if ($parent_id > 0) {
  5596. $parent = DB::table('mp_products')
  5597. ->where('id', $parent_id)
  5598. ->where('cpid', $cpid)
  5599. ->where('user_id', $store_uid)
  5600. ->where('type', 2)
  5601. ->where('is_deleted', 0)
  5602. ->first();
  5603. if (!$parent) {
  5604. Utils::throwError('20003:父文件夹不存在');
  5605. }
  5606. // 检查父文件夹的 product 类型是否一致
  5607. if ($parent->product != $product) {
  5608. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5609. }
  5610. $parent_level = $parent->level;
  5611. // 检查层级限制(最多3层)
  5612. if ($parent_level >= 3) {
  5613. Utils::throwError('20003:文件夹层级不能超过3层');
  5614. }
  5615. }
  5616. // 检查当前目录下是否已存在空白文件夹
  5617. $empty_folder_exists = DB::table('mp_products')
  5618. ->where('parent_id', $parent_id)
  5619. ->where('cpid', $cpid)
  5620. ->where('user_id', $store_uid)
  5621. ->where('type', 2)
  5622. ->where('product', $product)
  5623. ->where('product_name', '新建文件夹')
  5624. ->where('is_deleted', 0)
  5625. ->exists();
  5626. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5627. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5628. }
  5629. // 创建文件夹
  5630. $folder_id = DB::table('mp_products')->insertGetId([
  5631. 'user_id' => $store_uid,
  5632. 'cpid' => $cpid,
  5633. 'type' => 2,
  5634. 'parent_id' => $parent_id,
  5635. 'level' => $parent_level + 1,
  5636. 'product_name' => $folder_name,
  5637. 'product' => $product,
  5638. 'sort_order' => time(), // 使用时间戳作为排序权重
  5639. 'is_deleted' => 0,
  5640. 'created_at' => date('Y-m-d H:i:s'),
  5641. 'updated_at' => date('Y-m-d H:i:s')
  5642. ]);
  5643. return [
  5644. 'id' => $folder_id,
  5645. 'type' => 2,
  5646. 'parent_id' => $parent_id,
  5647. 'level' => $parent_level + 1,
  5648. 'product_name' => $folder_name,
  5649. 'product' => $product,
  5650. ];
  5651. }
  5652. /**
  5653. * 重命名文件夹或角色
  5654. * @param array $data 包含 id、product_name(新名称)
  5655. * @return bool
  5656. */
  5657. public function renameFolder($data) {
  5658. $uid = Site::getUid();
  5659. $cpid = Site::getCpid();
  5660. $role = Site::getRole();
  5661. $id = getProp($data, 'id');
  5662. $new_name = getProp($data, 'product_name');
  5663. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5664. if (!$id || !$new_name) {
  5665. Utils::throwError('20003:参数不完整');
  5666. }
  5667. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5668. $query_uid = $is_public ? 0 : $uid;
  5669. // 如果是公共库操作,需要admin权限
  5670. if ($is_public && $role !== 'admin') {
  5671. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5672. }
  5673. // 检查是否存在
  5674. $item = DB::table('mp_products')
  5675. ->where('id', $id)
  5676. ->where('cpid', $cpid)
  5677. ->where('user_id', $query_uid)
  5678. ->where('is_deleted', 0)
  5679. ->first();
  5680. if (!$item) {
  5681. Utils::throwError('20003:项目不存在');
  5682. }
  5683. return DB::table('mp_products')
  5684. ->where('id', $id)
  5685. ->where('cpid', $cpid)
  5686. ->where('user_id', $query_uid)
  5687. ->update([
  5688. 'product_name' => $new_name,
  5689. 'updated_at' => date('Y-m-d H:i:s')
  5690. ]);
  5691. }
  5692. /**
  5693. * 移动角色或文件夹到指定文件夹
  5694. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5695. * @return bool
  5696. */
  5697. public function moveProductOrFolder($data) {
  5698. $uid = Site::getUid();
  5699. $cpid = Site::getCpid();
  5700. $role = Site::getRole();
  5701. $id = getProp($data, 'id');
  5702. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5703. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5704. if (!$id) {
  5705. Utils::throwError('20003:请选择要移动的项目');
  5706. }
  5707. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5708. $query_uid = $is_public ? 0 : $uid;
  5709. // 如果是公共库操作,需要admin权限
  5710. if ($is_public && $role !== 'admin') {
  5711. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5712. }
  5713. // 检查要移动的项目
  5714. $item = DB::table('mp_products')
  5715. ->where('id', $id)
  5716. ->where('cpid', $cpid)
  5717. ->where('user_id', $query_uid)
  5718. ->where('is_deleted', 0)
  5719. ->first();
  5720. if (!$item) {
  5721. Utils::throwError('20003:项目不存在');
  5722. }
  5723. // 验证目标文件夹
  5724. $target_level = 0;
  5725. $target_product = $item->product; // 默认使用当前项目的 product
  5726. if ($target_parent_id > 0) {
  5727. $target_parent = DB::table('mp_products')
  5728. ->where('id', $target_parent_id)
  5729. ->where('cpid', $cpid)
  5730. ->where('user_id', $query_uid)
  5731. ->where('type', 2)
  5732. ->where('is_deleted', 0)
  5733. ->first();
  5734. if (!$target_parent) {
  5735. Utils::throwError('20003:目标文件夹不存在');
  5736. }
  5737. // 检查 product 类型是否一致
  5738. if ($target_parent->product != $item->product) {
  5739. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5740. }
  5741. $target_level = $target_parent->level;
  5742. $target_product = $target_parent->product;
  5743. // 如果移动的是文件夹,需要检查层级
  5744. if ($item->type == 2) {
  5745. // 计算移动后的最大层级
  5746. $max_child_level = $this->getMaxChildLevel($id);
  5747. $depth = $max_child_level - $item->level;
  5748. if ($target_level + 1 + $depth > 3) {
  5749. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5750. }
  5751. // 不能移动到自己或自己的子文件夹下
  5752. if ($this->isDescendant($target_parent_id, $id)) {
  5753. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5754. }
  5755. }
  5756. }
  5757. // 更新父文件夹和层级
  5758. $new_level = $target_level + 1;
  5759. DB::table('mp_products')
  5760. ->where('id', $id)
  5761. ->update([
  5762. 'parent_id' => $target_parent_id,
  5763. 'level' => $new_level,
  5764. 'updated_at' => date('Y-m-d H:i:s')
  5765. ]);
  5766. // 如果是文件夹,需要递归更新所有子项的层级
  5767. if ($item->type == 2) {
  5768. $this->updateChildrenLevel($id, $new_level);
  5769. }
  5770. return true;
  5771. }
  5772. /**
  5773. * 获取文件夹下最大子层级
  5774. * @param int $folder_id
  5775. * @return int
  5776. */
  5777. private function getMaxChildLevel($folder_id) {
  5778. $max_level = DB::table('mp_products')
  5779. ->where('parent_id', $folder_id)
  5780. ->where('is_deleted', 0)
  5781. ->max('level');
  5782. if (!$max_level) {
  5783. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5784. }
  5785. // 递归查找子文件夹
  5786. $children = DB::table('mp_products')
  5787. ->where('parent_id', $folder_id)
  5788. ->where('type', 2)
  5789. ->where('is_deleted', 0)
  5790. ->pluck('id');
  5791. foreach ($children as $child_id) {
  5792. $child_max = $this->getMaxChildLevel($child_id);
  5793. if ($child_max > $max_level) {
  5794. $max_level = $child_max;
  5795. }
  5796. }
  5797. return $max_level;
  5798. }
  5799. /**
  5800. * 检查 target_id 是否是 folder_id 的后代
  5801. * @param int $target_id
  5802. * @param int $folder_id
  5803. * @return bool
  5804. */
  5805. private function isDescendant($target_id, $folder_id) {
  5806. if ($target_id == $folder_id) {
  5807. return true;
  5808. }
  5809. $parent = DB::table('mp_products')
  5810. ->where('id', $target_id)
  5811. ->where('is_deleted', 0)
  5812. ->first();
  5813. if (!$parent || $parent->parent_id == 0) {
  5814. return false;
  5815. }
  5816. return $this->isDescendant($parent->parent_id, $folder_id);
  5817. }
  5818. /**
  5819. * 递归更新子项层级
  5820. * @param int $parent_id
  5821. * @param int $parent_level
  5822. */
  5823. private function updateChildrenLevel($parent_id, $parent_level) {
  5824. $children = DB::table('mp_products')
  5825. ->where('parent_id', $parent_id)
  5826. ->where('is_deleted', 0)
  5827. ->get();
  5828. foreach ($children as $child) {
  5829. $new_level = $parent_level + 1;
  5830. DB::table('mp_products')
  5831. ->where('id', $child->id)
  5832. ->update([
  5833. 'level' => $new_level,
  5834. 'updated_at' => date('Y-m-d H:i:s')
  5835. ]);
  5836. // 如果是文件夹,继续递归
  5837. if ($child->type == 2) {
  5838. $this->updateChildrenLevel($child->id, $new_level);
  5839. }
  5840. }
  5841. }
  5842. /**
  5843. * 获取文件夹路径(面包屑导航)
  5844. * @param array $data 包含 folder_id
  5845. * @return array 返回路径数组
  5846. */
  5847. public function getFolderPath($data) {
  5848. $uid = Site::getUid();
  5849. $cpid = Site::getCpid();
  5850. $folder_id = getProp($data, 'id', 0);
  5851. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5852. if ($folder_id == 0) {
  5853. return [
  5854. ['id' => 0, 'name' => '根目录']
  5855. ];
  5856. }
  5857. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5858. $query_uid = $is_public ? 0 : $uid;
  5859. $path = [];
  5860. $current_id = $folder_id;
  5861. while ($current_id > 0) {
  5862. $folder = DB::table('mp_products')
  5863. ->where('id', $current_id)
  5864. ->where('cpid', $cpid)
  5865. ->where('user_id', $query_uid)
  5866. ->where('type', 2)
  5867. ->where('is_deleted', 0)
  5868. ->first();
  5869. if (!$folder) {
  5870. break;
  5871. }
  5872. array_unshift($path, [
  5873. 'id' => $folder->id,
  5874. 'name' => $folder->product_name
  5875. ]);
  5876. $current_id = $folder->parent_id;
  5877. }
  5878. // 添加根目录
  5879. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5880. return $path;
  5881. }
  5882. public function createProduct($data) {
  5883. $uid = Site::getUid();
  5884. $cpid = Site::getCpid();
  5885. $role = Site::getRole();
  5886. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5887. // 如果是公共库操作,需要admin权限
  5888. if ($is_public && $role !== 'admin') {
  5889. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5890. }
  5891. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5892. $store_uid = $is_public ? 0 : $uid;
  5893. $product_name = trim(getProp($data, 'product_name'));
  5894. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5895. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5896. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5897. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5898. $url = trim(getProp($data, 'url'));
  5899. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5900. $versions = getProp($data, 'versions');
  5901. // 检查是否是正确的图片格式
  5902. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5903. $urlPath = parse_url($url, PHP_URL_PATH);
  5904. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5905. if (!in_array($extension, $allowedExtensions)) {
  5906. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5907. }
  5908. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5909. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5910. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5911. $product = getProp($data, 'product');
  5912. if (!in_array($product, [1, 2, 3])) {
  5913. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5914. }
  5915. // 获取父文件夹ID和层级
  5916. $parent_id = getProp($data, 'parent_id', 0);
  5917. $parent_level = 0;
  5918. if ($parent_id > 0) {
  5919. $parent = DB::table('mp_products')
  5920. ->where('id', $parent_id)
  5921. ->where('cpid', $cpid)
  5922. ->where('user_id', $store_uid)
  5923. ->where('type', 2)
  5924. ->where('is_deleted', 0)
  5925. ->first();
  5926. if (!$parent) {
  5927. Utils::throwError('20003:父文件夹不存在');
  5928. }
  5929. $parent_level = $parent->level;
  5930. }
  5931. $id = DB::table('mp_products')->insertGetId([
  5932. 'user_id' => $store_uid,
  5933. 'cpid' => $cpid,
  5934. 'type' => 1, // 1=角色图片
  5935. 'parent_id' => $parent_id,
  5936. 'level' => $parent_level + 1,
  5937. 'product_name' => $product_name,
  5938. 'url' => $url,
  5939. 'pic_prompt' => $pic_prompt,
  5940. 'product' => $product,
  5941. 'versions' => json_encode($versions, 256),
  5942. 'sort_order' => time(), // 使用时间戳作为排序权重
  5943. 'created_at' => date('Y-m-d H:i:s'),
  5944. 'updated_at' => date('Y-m-d H:i:s')
  5945. ]);
  5946. if (!$id) Utils::throwError('20003:创建失败');
  5947. return [
  5948. 'id' => $id,
  5949. 'type' => 1,
  5950. 'parent_id' => $parent_id,
  5951. 'level' => $parent_level + 1,
  5952. 'product_name' => $product_name,
  5953. 'url' => $url,
  5954. 'pic_prompt' => $pic_prompt,
  5955. 'product' => $product,
  5956. 'versions' => $versions
  5957. ];
  5958. }
  5959. public function editProduct($data) {
  5960. $uid = Site::getUid();
  5961. $cpid = Site::getCpid();
  5962. $role = Site::getRole();
  5963. $id = getProp($data, 'id');
  5964. if (!$id) Utils::throwError('20003:ID不能为空');
  5965. $versions = getProp($data, 'versions');
  5966. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5967. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5968. $query_uid = $is_public ? 0 : $uid;
  5969. // 如果是公共库操作,需要admin权限
  5970. if ($is_public && $role !== 'admin') {
  5971. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5972. }
  5973. // 检查是否存在且属于当前用户或公共库
  5974. $role = DB::table('mp_products')
  5975. ->where('id', $id)
  5976. ->where('cpid', $cpid)
  5977. ->where('user_id', $query_uid)
  5978. ->where('type', 1)->first();
  5979. if (!$role) Utils::throwError('20003:记录不存在');
  5980. $updateData = [];
  5981. // $needVersionRecord = false; // 是否需要记录版本
  5982. // 名称
  5983. $product_name = trim(getProp($data, 'product_name'));
  5984. if ($product_name) {
  5985. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5986. $updateData['product_name'] = $product_name;
  5987. }
  5988. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5989. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5990. // 图片地址
  5991. $url = trim(getProp($data, 'url'));
  5992. if ($url) {
  5993. // 检查是否是正确的图片格式
  5994. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5995. $urlPath = parse_url($url, PHP_URL_PATH);
  5996. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5997. if (!in_array($extension, $allowedExtensions)) {
  5998. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5999. }
  6000. // // 如果 url 有变更,记录版本
  6001. // if ($url !== $role->url) {
  6002. // $needVersionRecord = true;
  6003. // }
  6004. $updateData['url'] = $url;
  6005. }
  6006. // 提示词
  6007. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6008. if ($pic_prompt) {
  6009. // // 如果 pic_prompt 有变更,记录版本
  6010. // if ($pic_prompt !== $role->pic_prompt) {
  6011. // $needVersionRecord = true;
  6012. // }
  6013. $updateData['pic_prompt'] = $pic_prompt;
  6014. }
  6015. if (empty($updateData)) {
  6016. Utils::throwError('20003:没有需要更新的数据');
  6017. }
  6018. // // 如果需要记录版本,将数据添加到 versions 数组
  6019. // if ($needVersionRecord) {
  6020. // // 获取现有的 versions 数据
  6021. // $versions = json_decode($role->versions, true) ?: [];
  6022. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6023. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6024. // if ($isFirstVersion) {
  6025. // $oldVersion = [
  6026. // 'url' => $role->url,
  6027. // 'description' => $role->pic_prompt,
  6028. // ];
  6029. // // 旧版本添加到数组末尾
  6030. // $versions[] = $oldVersion;
  6031. // }
  6032. // // 构建新版本(变更后)
  6033. // $newVersion = [
  6034. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6035. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6036. // ];
  6037. // // 检查新版本是否已存在于历史版本中
  6038. // $existingIndex = -1;
  6039. // foreach ($versions as $index => $version) {
  6040. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6041. // $existingIndex = $index;
  6042. // break;
  6043. // }
  6044. // }
  6045. // if ($existingIndex !== -1) {
  6046. // // 如果已存在,移除旧的位置
  6047. // array_splice($versions, $existingIndex, 1);
  6048. // }
  6049. // // 新版本添加到数组开头(最新的在前)
  6050. // array_unshift($versions, $newVersion);
  6051. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6052. // // if (count($versions) > 10) {
  6053. // // $versions = array_slice($versions, 0, 10);
  6054. // // }
  6055. // $updateData['versions'] = json_encode($versions, 256);
  6056. // }
  6057. if ($versions) {
  6058. $updateData['versions'] = json_encode($versions, 256);
  6059. }
  6060. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6061. return DB::table('mp_products')
  6062. ->where('cpid', $cpid)
  6063. ->where('id', $id)->update($updateData);
  6064. }
  6065. /**
  6066. * 获取角色版本历史
  6067. * @param array $data 包含 id(角色ID)
  6068. * @return array 返回版本历史列表
  6069. */
  6070. public function getProductVersions($data) {
  6071. $cpid = Site::getCpid();
  6072. $id = getProp($data, 'id');
  6073. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6074. $role = DB::table('mp_products')
  6075. ->where('id', $id)
  6076. ->where('cpid', $cpid)
  6077. ->where('type', 1)
  6078. ->first();
  6079. if (!$role) Utils::throwError('20003:角色不存在');
  6080. // 获取版本历史
  6081. $versions = json_decode($role->versions, true) ?: [];
  6082. // 添加当前版本作为最新版本
  6083. $currentVersion = [
  6084. 'version' => 0, // 0 表示当前版本
  6085. 'url' => $role->url,
  6086. 'pic_prompt' => $role->pic_prompt,
  6087. 'updated_at' => $role->updated_at,
  6088. 'is_current' => true
  6089. ];
  6090. array_unshift($versions, $currentVersion);
  6091. return $versions;
  6092. }
  6093. /**
  6094. * 恢复到指定版本
  6095. * @param array $data 包含 id(角色ID)、version(版本号)
  6096. * @return bool
  6097. */
  6098. public function restoreProductVersion($data) {
  6099. $uid = Site::getUid();
  6100. $cpid = Site::getCpid();
  6101. $id = getProp($data, 'id');
  6102. $version = getProp($data, 'version');
  6103. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6104. if (!$version) Utils::throwError('20003:版本号不能为空');
  6105. $role = DB::table('mp_products')
  6106. ->where('id', $id)
  6107. ->where('cpid', $cpid)
  6108. ->where('type', 1)
  6109. ->first();
  6110. if (!$role) Utils::throwError('20003:角色不存在');
  6111. // 获取版本历史
  6112. $versions = json_decode($role->versions, true) ?: [];
  6113. // 查找指定版本
  6114. $targetVersion = null;
  6115. foreach ($versions as $v) {
  6116. if ($v['version'] == $version) {
  6117. $targetVersion = $v;
  6118. break;
  6119. }
  6120. }
  6121. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6122. // 先将当前版本保存到历史
  6123. $newVersion = [
  6124. 'version' => count($versions) + 1,
  6125. 'url' => $role->url,
  6126. 'pic_prompt' => $role->pic_prompt,
  6127. 'updated_at' => date('Y-m-d H:i:s'),
  6128. 'updated_by' => $uid
  6129. ];
  6130. array_unshift($versions, $newVersion);
  6131. // 限制版本数量
  6132. if (count($versions) > 10) {
  6133. $versions = array_slice($versions, 0, 10);
  6134. }
  6135. // 恢复到指定版本
  6136. return DB::table('mp_products')
  6137. ->where('id', $id)
  6138. ->where('cpid', $cpid)
  6139. ->update([
  6140. 'url' => $targetVersion['url'],
  6141. 'pic_prompt' => $targetVersion['pic_prompt'],
  6142. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6143. 'updated_at' => date('Y-m-d H:i:s')
  6144. ]);
  6145. }
  6146. public function deleteProduct($data) {
  6147. $uid = Site::getUid();
  6148. $cpid = Site::getCpid();
  6149. $role = Site::getRole();
  6150. $id = getProp($data, 'id');
  6151. if (!$id) Utils::throwError('20003:ID不能为空');
  6152. $ids = explode(',', $id);
  6153. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6154. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6155. $query_uid = $is_public ? 0 : $uid;
  6156. // 如果是公共库操作,需要admin权限
  6157. if ($is_public && $role !== 'admin') {
  6158. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6159. }
  6160. // 检查是否存在且属于当前用户或公共库
  6161. $role = DB::table('mp_products')
  6162. ->whereIn('id', $ids)
  6163. ->where('cpid', $cpid)
  6164. ->where('user_id', $query_uid)
  6165. ->get();
  6166. if (!$role) Utils::throwError('20003:记录不存在');
  6167. return DB::table('mp_products')
  6168. ->where('cpid', $cpid)
  6169. ->where('user_id', $query_uid)
  6170. ->whereIn('id', $ids)
  6171. ->update([
  6172. 'is_deleted' => 1,
  6173. 'updated_at' => date('Y-m-d H:i:s')
  6174. ]);
  6175. }
  6176. public function generateThreeView($data) {
  6177. $uid = Site::getUid();
  6178. $cpid = Site::getCpid();
  6179. $role = Site::getRole();
  6180. $id = getProp($data, 'id');
  6181. if (!$id) Utils::throwError('20003:ID不能为空');
  6182. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6183. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6184. $query_uid = $is_public ? 0 : $uid;
  6185. // 如果是公共库操作,需要admin权限
  6186. if ($is_public && $role !== 'admin') {
  6187. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6188. }
  6189. // 检查是否存在且属于当前用户或公共库
  6190. $product = DB::table('mp_products')
  6191. ->where('id', $id)
  6192. ->where('cpid', $cpid)
  6193. ->where('user_id', $query_uid)
  6194. ->where('type', 1)->first();
  6195. if (!$product) Utils::throwError('20003:资产不存在');
  6196. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6197. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6198. if (!$ref_img_url) {
  6199. // 如果没有传入参考图,使用角色表中的图片
  6200. $ref_img_url = $product->url ?? '';
  6201. if (!$ref_img_url) {
  6202. Utils::throwError('20003:参考图不能为空');
  6203. }
  6204. }
  6205. $pic_prompt = getProp($product, 'pic_prompt');
  6206. if ($pic_prompt) {
  6207. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6208. }
  6209. // 检查参考图是否是正确的图片格式
  6210. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6211. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6212. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6213. if (!in_array($extension, $allowedExtensions)) {
  6214. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6215. }
  6216. // 处理图片模型
  6217. $model = getProp($data, 'model');
  6218. if (!$model) {
  6219. // 使用默认模型
  6220. $model = 'doubao-seedream-5-0-lite-260128';
  6221. }
  6222. // 验证模型是否在可用模型表中
  6223. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6224. Utils::throwError('20003:该模型已不可用,请更换!');
  6225. }
  6226. $ratio = getProp($data, 'ratio', '16:9');
  6227. $resolution = getProp($data, 'resolution', '2k');
  6228. // 定义分辨率和宽高比对应的尺寸映射表
  6229. $sizeMap = [
  6230. '2k' => [
  6231. '1:1' => ['width' => 2048, 'height' => 2048],
  6232. '4:3' => ['width' => 2304, 'height' => 1728],
  6233. '3:4' => ['width' => 1728, 'height' => 2304],
  6234. '16:9' => ['width' => 2848, 'height' => 1600],
  6235. '9:16' => ['width' => 1600, 'height' => 2848],
  6236. '3:2' => ['width' => 2496, 'height' => 1664],
  6237. '2:3' => ['width' => 1664, 'height' => 2496],
  6238. '21:9' => ['width' => 3136, 'height' => 1344],
  6239. ],
  6240. '3k' => [
  6241. '1:1' => ['width' => 3072, 'height' => 3072],
  6242. '4:3' => ['width' => 3456, 'height' => 2592],
  6243. '3:4' => ['width' => 2592, 'height' => 3456],
  6244. '16:9' => ['width' => 4096, 'height' => 2304],
  6245. '9:16' => ['width' => 2304, 'height' => 4096],
  6246. '2:3' => ['width' => 2496, 'height' => 3744],
  6247. '3:2' => ['width' => 3744, 'height' => 2496],
  6248. '21:9' => ['width' => 4704, 'height' => 2016],
  6249. ],
  6250. '4k' => [
  6251. '1:1' => ['width' => 4096, 'height' => 4096],
  6252. '3:4' => ['width' => 3520, 'height' => 4704],
  6253. '4:3' => ['width' => 4704, 'height' => 3520],
  6254. '16:9' => ['width' => 5504, 'height' => 3040],
  6255. '9:16' => ['width' => 3040, 'height' => 5504],
  6256. '2:3' => ['width' => 3328, 'height' => 4992],
  6257. '3:2' => ['width' => 4992, 'height' => 3328],
  6258. '21:9' => ['width' => 6240, 'height' => 2656],
  6259. ],
  6260. ];
  6261. // 参数验证
  6262. $resolution = strtolower($resolution);
  6263. if (!isset($sizeMap[$resolution])) {
  6264. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6265. }
  6266. if (!isset($sizeMap[$resolution][$ratio])) {
  6267. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6268. }
  6269. // 根据 ratio 和 resolution 确定宽高
  6270. $width = $sizeMap[$resolution][$ratio]['width'];
  6271. $height = $sizeMap[$resolution][$ratio]['height'];
  6272. try {
  6273. // 创建图片生成任务
  6274. $params = [
  6275. 'prompt' => $prompt,
  6276. 'model' => $model,
  6277. 'ref_img_urls' => [$ref_img_url],
  6278. 'width' => $width,
  6279. 'height' => $height
  6280. ];
  6281. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6282. $task_id = $task->id;
  6283. if (!$task_id) {
  6284. Utils::throwError('20003:创建图片生成任务失败');
  6285. }
  6286. // 轮询获取结果
  6287. // 只查询数据库,不调用API,不更新任务表
  6288. $start_time = time();
  6289. $timeout = 1800;
  6290. $img_url = '';
  6291. while (time() - $start_time < $timeout) {
  6292. sleep(5);
  6293. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6294. $task = DB::table('mp_generate_pic_tasks')
  6295. ->where('id', $task_id)
  6296. ->first();
  6297. if (!$task) {
  6298. Utils::throwError('20003:任务不存在');
  6299. }
  6300. if ($task->status === 'success' && $task->result_url) {
  6301. $result_urls = is_string($task->result_url)
  6302. ? json_decode($task->result_url, true)
  6303. : $task->result_url;
  6304. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6305. break;
  6306. } elseif ($task->status === 'failed') {
  6307. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6308. }
  6309. // 其他状态继续轮询
  6310. }
  6311. if (empty($img_url)) {
  6312. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6313. }
  6314. // 更新 mp_products 表(不是任务表)
  6315. DB::table('mp_products')
  6316. ->where('id', $id)
  6317. ->where('cpid', $cpid)
  6318. ->update([
  6319. 'three_view_image_url' => $img_url,
  6320. 'updated_at' => date('Y-m-d H:i:s')
  6321. ]);
  6322. return ['three_view_image_url' => $img_url];
  6323. } catch (\Exception $e) {
  6324. dLog('anime')->error('生成三视图失败', [
  6325. 'error' => $e->getMessage()
  6326. ]);
  6327. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6328. Utils::throwError('20003:' . $e->getMessage());
  6329. }
  6330. }
  6331. /**
  6332. * 推送(复制)资产或文件夹到目标位置
  6333. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6334. * @return array 返回推送结果
  6335. */
  6336. public function pushProductOrFolder($data) {
  6337. $uid = Site::getUid();
  6338. $cpid = Site::getCpid();
  6339. $role = Site::getRole();
  6340. $product_id = getProp($data, 'product_id');
  6341. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6342. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6343. if (!$product_id) {
  6344. Utils::throwError('20003:请选择要推送的项目');
  6345. }
  6346. // 查询源项目(只通过cpid查询,不限制user_id)
  6347. $sourceItem = DB::table('mp_products')
  6348. ->where('id', $product_id)
  6349. ->where('cpid', $cpid)
  6350. ->where('is_deleted', 0)
  6351. ->first();
  6352. if (!$sourceItem) {
  6353. Utils::throwError('20003:要推送的项目不存在');
  6354. }
  6355. // 通过user_id判断源是公共库还是个人库
  6356. $source_uid = $sourceItem->user_id;
  6357. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6358. // 验证目标文件夹并确定目标是公共库还是个人库
  6359. $target_level = 0;
  6360. $target_uid = $uid; // 默认推送到个人库
  6361. $target_is_public = 0;
  6362. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6363. if ($target_parent_id > 0) {
  6364. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6365. $targetParent = DB::table('mp_products')
  6366. ->where('id', $target_parent_id)
  6367. ->where('cpid', $cpid)
  6368. ->where('type', 2)
  6369. ->where('is_deleted', 0)
  6370. ->first();
  6371. if (!$targetParent) {
  6372. Utils::throwError('20003:目标文件夹不存在');
  6373. }
  6374. // 通过user_id判断目标是公共库还是个人库
  6375. $target_level = $targetParent->level;
  6376. $target_uid = $targetParent->user_id;
  6377. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6378. // 使用目标文件夹的 product 类型
  6379. $final_product_type = $targetParent->product;
  6380. }
  6381. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6382. else {
  6383. $push_to_public = getProp($data, 'push_to_public');
  6384. if ($push_to_public === '') {
  6385. Utils::throwError('20003:请选择是否推送到公共库');
  6386. }
  6387. if ($push_to_public) {
  6388. $target_uid = 0;
  6389. $target_is_public = 1;
  6390. }
  6391. // 推送到根目录时,必须指定 product 类型
  6392. if ($target_product === null || $target_product === '') {
  6393. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6394. }
  6395. $final_product_type = $target_product;
  6396. }
  6397. // 如果目标是公共库,需要admin权限
  6398. if ($target_is_public && $role !== 'admin') {
  6399. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6400. }
  6401. // 权限验证:验证是否符合允许的推送规则
  6402. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6403. try {
  6404. DB::beginTransaction();
  6405. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6406. if ($sourceItem->type == 1) {
  6407. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6408. DB::commit();
  6409. return [
  6410. 'product_id' => $newId,
  6411. ];
  6412. }
  6413. // 如果是文件夹,递归复制(支持跨类型推送)
  6414. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6415. DB::commit();
  6416. return [
  6417. 'product_id' => $newFolderId,
  6418. ];
  6419. } catch (\Exception $e) {
  6420. DB::rollBack();
  6421. dLog('anime')->error('推送失败', [
  6422. 'error' => $e->getMessage(),
  6423. 'product_id' => $product_id
  6424. ]);
  6425. Utils::throwError('20003:' . $e->getMessage());
  6426. }
  6427. }
  6428. /**
  6429. * 验证推送权限
  6430. * 允许的推送规则:
  6431. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6432. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6433. * 3. 公共库推送给公共库(公共库 → 公共库)
  6434. *
  6435. * @param int $source_uid 源的user_id
  6436. * @param int $target_uid 目标的user_id
  6437. * @param int $current_uid 当前用户ID
  6438. * @throws \Exception
  6439. */
  6440. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6441. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6442. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6443. return; // 允许
  6444. }
  6445. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6446. if ($source_uid == 0 && $target_uid == $current_uid) {
  6447. return; // 允许
  6448. }
  6449. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6450. if ($source_uid == 0 && $target_uid == 0) {
  6451. return; // 允许
  6452. }
  6453. // 其他情况都不允许
  6454. if ($source_uid != 0 && $source_uid != $current_uid) {
  6455. // 源是别人的个人库
  6456. Utils::throwError('20003:无权限访问该资产');
  6457. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6458. // 个人库推送给公共库(不允许)
  6459. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6460. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6461. // 不同用户的个人库之间推送(不允许)
  6462. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6463. } else {
  6464. // 其他未知情况
  6465. Utils::throwError('20003:不允许的推送操作');
  6466. }
  6467. }
  6468. /**
  6469. * 复制单个资产
  6470. * @param object $sourceProduct 源资产对象
  6471. * @param int $targetParentId 目标父文件夹ID
  6472. * @param int $targetLevel 目标层级
  6473. * @param int $cpid 公司ID
  6474. * @param int $targetUid 目标用户ID
  6475. * @return int 返回新资产ID
  6476. */
  6477. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6478. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6479. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6480. $newProductData = [
  6481. 'user_id' => $targetUid,
  6482. 'cpid' => $cpid,
  6483. 'type' => 1,
  6484. 'parent_id' => $targetParentId,
  6485. 'level' => $targetLevel,
  6486. 'product_name' => $sourceProduct->product_name,
  6487. 'url' => $sourceProduct->url,
  6488. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6489. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6490. 'product' => $finalProductType,
  6491. 'versions' => $sourceProduct->versions ?? '',
  6492. 'sort_order' => time(),
  6493. 'is_deleted' => 0,
  6494. 'created_at' => date('Y-m-d H:i:s'),
  6495. 'updated_at' => date('Y-m-d H:i:s')
  6496. ];
  6497. return DB::table('mp_products')->insertGetId($newProductData);
  6498. }
  6499. /**
  6500. * 递归复制文件夹及其子项
  6501. * @param object $sourceFolder 源文件夹对象
  6502. * @param int $targetParentId 目标父文件夹ID
  6503. * @param int $targetLevel 目标层级
  6504. * @param int $cpid 公司ID
  6505. * @param int $targetUid 目标用户ID
  6506. * @param int $sourceUid 源用户ID
  6507. * @return int 返回新文件夹ID
  6508. */
  6509. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6510. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6511. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6512. // 创建新文件夹
  6513. $newFolderData = [
  6514. 'user_id' => $targetUid,
  6515. 'cpid' => $cpid,
  6516. 'type' => 2,
  6517. 'parent_id' => $targetParentId,
  6518. 'level' => $targetLevel,
  6519. 'product_name' => $sourceFolder->product_name,
  6520. 'product' => $finalProductType,
  6521. 'sort_order' => time(),
  6522. 'is_deleted' => 0,
  6523. 'created_at' => date('Y-m-d H:i:s'),
  6524. 'updated_at' => date('Y-m-d H:i:s')
  6525. ];
  6526. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6527. // 获取源文件夹下的所有子项
  6528. $children = DB::table('mp_products')
  6529. ->where('parent_id', $sourceFolder->id)
  6530. ->where('cpid', $cpid)
  6531. ->where('user_id', $sourceUid)
  6532. ->where('is_deleted', 0)
  6533. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6534. ->get();
  6535. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6536. foreach ($children as $child) {
  6537. if ($child->type == 1) {
  6538. // 资产
  6539. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6540. } else {
  6541. // 文件夹
  6542. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6543. }
  6544. }
  6545. return $newFolderId;
  6546. }
  6547. /**
  6548. * 保存剧本资产关联关系
  6549. * @param array $data 请求参数
  6550. * @return bool
  6551. */
  6552. public function saveScriptProducts($data) {
  6553. $uid = Site::getUid();
  6554. $cpid = Site::getCpid();
  6555. $script_id = getProp($data, 'script_id');
  6556. $products = getProp($data, 'products', []);
  6557. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6558. if (!$script_id) {
  6559. Utils::throwError('20003:请提供剧本ID');
  6560. }
  6561. // 验证剧本是否存在
  6562. $script = DB::table('mp_scripts')
  6563. ->where('id', $script_id)
  6564. ->where('is_deleted', 0)
  6565. ->first();
  6566. if (!$script) {
  6567. Utils::throwError('20003:剧本不存在');
  6568. }
  6569. // 处理图片模型
  6570. $model = getProp($data, 'model');
  6571. if (!$model) {
  6572. // 使用默认模型
  6573. $model = 'doubao-seedream-5-0-lite-260128';
  6574. }
  6575. // 验证模型是否在可用模型表中
  6576. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6577. Utils::throwError('20003:该模型已不可用,请更换!');
  6578. }
  6579. $ratio = getProp($data, 'ratio', '9:16');
  6580. $resolution = getProp($data, 'resolution', '2k');
  6581. // 定义分辨率和宽高比对应的尺寸映射表
  6582. $sizeMap = [
  6583. '2k' => [
  6584. '1:1' => ['width' => 2048, 'height' => 2048],
  6585. '4:3' => ['width' => 2304, 'height' => 1728],
  6586. '3:4' => ['width' => 1728, 'height' => 2304],
  6587. '16:9' => ['width' => 2848, 'height' => 1600],
  6588. '9:16' => ['width' => 1600, 'height' => 2848],
  6589. '3:2' => ['width' => 2496, 'height' => 1664],
  6590. '2:3' => ['width' => 1664, 'height' => 2496],
  6591. '21:9' => ['width' => 3136, 'height' => 1344],
  6592. ],
  6593. '3k' => [
  6594. '1:1' => ['width' => 3072, 'height' => 3072],
  6595. '4:3' => ['width' => 3456, 'height' => 2592],
  6596. '3:4' => ['width' => 2592, 'height' => 3456],
  6597. '16:9' => ['width' => 4096, 'height' => 2304],
  6598. '9:16' => ['width' => 2304, 'height' => 4096],
  6599. '2:3' => ['width' => 2496, 'height' => 3744],
  6600. '3:2' => ['width' => 3744, 'height' => 2496],
  6601. '21:9' => ['width' => 4704, 'height' => 2016],
  6602. ],
  6603. '4k' => [
  6604. '1:1' => ['width' => 4096, 'height' => 4096],
  6605. '3:4' => ['width' => 3520, 'height' => 4704],
  6606. '4:3' => ['width' => 4704, 'height' => 3520],
  6607. '16:9' => ['width' => 5504, 'height' => 3040],
  6608. '9:16' => ['width' => 3040, 'height' => 5504],
  6609. '2:3' => ['width' => 3328, 'height' => 4992],
  6610. '3:2' => ['width' => 4992, 'height' => 3328],
  6611. '21:9' => ['width' => 6240, 'height' => 2656],
  6612. ],
  6613. ];
  6614. // 参数验证
  6615. $resolution = strtolower($resolution);
  6616. if (!isset($sizeMap[$resolution])) {
  6617. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6618. }
  6619. if (!isset($sizeMap[$resolution][$ratio])) {
  6620. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6621. }
  6622. // 根据 ratio 和 resolution 确定宽高
  6623. $width = $sizeMap[$resolution][$ratio]['width'];
  6624. $height = $sizeMap[$resolution][$ratio]['height'];
  6625. $script_name = $script->script_name ?? 'script_' . $script_id;
  6626. // 检查是否已经有该剧本的资产数据
  6627. $existingMappings = DB::table('mp_script_product_mappings')
  6628. ->where('script_id', $script_id)
  6629. ->get();
  6630. if ($existingMappings->isNotEmpty()) {
  6631. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6632. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6633. // 查询这些资产的图片生成任务状态
  6634. $productsWithTasks = DB::table('mp_products')
  6635. ->whereIn('id', $productIds)
  6636. ->where('is_deleted', 0)
  6637. ->get();
  6638. $productTaskMap = [];
  6639. $typeFolderIds = [];
  6640. $hasAllTasks = true;
  6641. foreach ($productsWithTasks as $product) {
  6642. // 收集类型文件夹ID
  6643. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6644. $parentFolder = DB::table('mp_products')
  6645. ->where('id', $product->parent_id)
  6646. ->where('type', 2)
  6647. ->first();
  6648. if ($parentFolder) {
  6649. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6650. }
  6651. }
  6652. // 检查是否有图片生成任务
  6653. if (!empty($product->pic_task_id)) {
  6654. $productTaskMap[$product->id] = $product->pic_task_id;
  6655. } else if($product->url && $product->pic_task_status == '生成成功') {
  6656. continue;
  6657. } else {
  6658. // 有资产没有图片任务
  6659. $hasAllTasks = false;
  6660. }
  6661. }
  6662. // 如果所有资产都有任务ID,直接轮询返回结果
  6663. if ($hasAllTasks && !empty($productTaskMap)) {
  6664. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6665. 'script_id' => $script_id,
  6666. 'script_name' => $script_name,
  6667. 'product_count' => count($productTaskMap)
  6668. ]);
  6669. // 直接返回 SSE 流轮询结果
  6670. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6671. }
  6672. // 如果部分资产没有任务ID,只为这些资产创建任务
  6673. if (!$hasAllTasks && $auto_generate_images) {
  6674. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6675. 'script_id' => $script_id,
  6676. 'script_name' => $script_name
  6677. ]);
  6678. // 开启事务
  6679. DB::beginTransaction();
  6680. try {
  6681. foreach ($productsWithTasks as $product) {
  6682. // 跳过已有任务的资产
  6683. if (!empty($product->pic_task_id)) {
  6684. continue;
  6685. }
  6686. // 跳过没有提示词的资产
  6687. if (empty($product->pic_prompt)) {
  6688. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6689. 'product_id' => $product->id,
  6690. 'product_name' => $product->product_name
  6691. ]);
  6692. continue;
  6693. }
  6694. try {
  6695. // 创建图片生成任务
  6696. $params = [
  6697. 'prompt' => $product->pic_prompt,
  6698. 'model' => $model,
  6699. 'ref_img_urls' => [],
  6700. 'width' => $width,
  6701. 'height' => $height
  6702. ];
  6703. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6704. $task_id = $task->id;
  6705. if ($task_id) {
  6706. $productTaskMap[$product->id] = $task_id;
  6707. // 在事务中更新资产表的任务ID和状态
  6708. DB::table('mp_products')
  6709. ->where('id', $product->id)
  6710. ->update([
  6711. 'pic_task_id' => $task_id,
  6712. 'pic_task_status' => '生成中',
  6713. 'updated_at' => now()
  6714. ]);
  6715. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6716. 'product_id' => $product->id,
  6717. 'task_id' => $task_id
  6718. ]);
  6719. }
  6720. } catch (\Exception $e) {
  6721. dLog('anime')->error('创建资产图片生成任务失败', [
  6722. 'product_id' => $product->id,
  6723. 'error' => $e->getMessage()
  6724. ]);
  6725. // 标记为失败(仍在事务中)
  6726. DB::table('mp_products')
  6727. ->where('id', $product->id)
  6728. ->update([
  6729. 'pic_task_status' => '生成失败',
  6730. 'updated_at' => now()
  6731. ]);
  6732. }
  6733. }
  6734. // 提交事务
  6735. DB::commit();
  6736. // 如果有新创建的任务,返回 SSE 流
  6737. if (!empty($productTaskMap)) {
  6738. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6739. }
  6740. } catch (\Exception $e) {
  6741. // 回滚事务
  6742. DB::rollback();
  6743. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6744. 'script_id' => $script_id,
  6745. 'error' => $e->getMessage()
  6746. ]);
  6747. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6748. }
  6749. }
  6750. // 如果不需要生成图片,返回已存在的信息
  6751. return [
  6752. 'success' => true,
  6753. 'message' => '剧本资产已存在',
  6754. 'script_id' => $script_id,
  6755. 'script_name' => $script_name,
  6756. 'type_folder_ids' => $typeFolderIds,
  6757. 'existing_products' => count($productIds),
  6758. 'tasks_count' => count($productTaskMap)
  6759. ];
  6760. }
  6761. // 解析 products(可能是 JSON 字符串或数组)
  6762. if (is_string($products)) {
  6763. $products = json_decode($products, true);
  6764. if (json_last_error() !== JSON_ERROR_NONE) {
  6765. Utils::throwError('20003:产品数据格式错误');
  6766. }
  6767. }
  6768. if (!is_array($products) || empty($products)) {
  6769. Utils::throwError('20003:产品数据不能为空');
  6770. }
  6771. // 以下是原有的创建逻辑...
  6772. // 开启事务
  6773. DB::beginTransaction();
  6774. try {
  6775. $now = now();
  6776. $mappingRecords = [];
  6777. $createdProductIds = []; // 记录所有创建的资产ID
  6778. // 获取剧本名称
  6779. $script_name = $script->script_name ?? 'script_' . $script_id;
  6780. // 存储每个类型的根文件夹ID
  6781. $typeFolderIds = [];
  6782. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6783. foreach ($products as $productGroup) {
  6784. $type = getProp($productGroup, 'type');
  6785. $title = getProp($productGroup, 'title', '');
  6786. $content = getProp($productGroup, 'content', []);
  6787. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6788. continue;
  6789. }
  6790. // 为当前类型创建根文件夹(如果还未创建)
  6791. if (!isset($typeFolderIds[$type])) {
  6792. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6793. 'user_id' => $uid,
  6794. 'cpid' => $cpid,
  6795. 'type' => 2, // 1.资产 2文件夹
  6796. 'product' => $type, // 1.主体 2.场景 3.道具
  6797. 'parent_id' => 0, // 根文件夹,parent_id=0
  6798. 'level' => 1, // 第一层级
  6799. 'product_name' => $script_name,
  6800. 'sort_order' => time() + $type,
  6801. 'is_deleted' => 0,
  6802. 'created_at' => $now,
  6803. 'updated_at' => $now
  6804. ]);
  6805. }
  6806. $folder_id = $typeFolderIds[$type];
  6807. // 获取表头(第一行)并查找关键列的位置
  6808. $headers = $content[0];
  6809. $nameColumnIndex = -1; // 资产名称列索引
  6810. $sequenceColumnIndex = -1; // 使用范围列索引
  6811. $promptColumnIndex = -1; // 参考提示词列索引
  6812. foreach ($headers as $index => $header) {
  6813. // 查找"资产名称"列
  6814. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6815. $nameColumnIndex = $index;
  6816. }
  6817. // 查找"使用范围"列
  6818. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6819. $sequenceColumnIndex = $index;
  6820. }
  6821. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6822. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6823. $promptColumnIndex = $index;
  6824. }
  6825. }
  6826. // 验证必要的列是否都找到了
  6827. if ($nameColumnIndex === -1) {
  6828. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6829. continue;
  6830. }
  6831. if ($sequenceColumnIndex === -1) {
  6832. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6833. continue;
  6834. }
  6835. // 跳过表头,解析每一行数据
  6836. for ($i = 1; $i < count($content); $i++) {
  6837. $row = $content[$i];
  6838. // 确保行数据有效
  6839. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6840. continue;
  6841. }
  6842. // 根据动态查找的列索引提取数据
  6843. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6844. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6845. $pic_prompt = '';
  6846. // 提取参考提示词(如果找到了该列)
  6847. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6848. $pic_prompt = trim($row[$promptColumnIndex]);
  6849. }
  6850. // 解析使用范围(逗号分隔的序号)
  6851. $sequences = [];
  6852. if (!empty($sequence_str)) {
  6853. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6854. foreach ($sequenceParts as $part) {
  6855. if (is_numeric($part)) {
  6856. $sequences[] = (int)$part;
  6857. }
  6858. }
  6859. }
  6860. if (empty($product_name)) {
  6861. continue;
  6862. }
  6863. // 处理product_name两边的符号
  6864. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6865. // 如果名称不存在则跳过
  6866. if (!$product_name) continue;
  6867. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6868. $product_id = DB::table('mp_products')->insertGetId([
  6869. 'product_name' => $product_name,
  6870. 'type' => 1, // 1=资产 2.文件夹
  6871. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6872. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6873. 'level' => 2, // 第二层级
  6874. 'pic_prompt' => $pic_prompt,
  6875. 'user_id' => $uid,
  6876. 'cpid' => $cpid,
  6877. 'sort_order' => time(),
  6878. 'is_deleted' => 0,
  6879. 'created_at' => $now,
  6880. 'updated_at' => $now,
  6881. ]);
  6882. // 记录创建的资产ID
  6883. $createdProductIds[] = $product_id;
  6884. // 为每个序号创建映射记录
  6885. if (!empty($sequences)) {
  6886. foreach ($sequences as $sequence) {
  6887. $mappingRecords[] = [
  6888. 'script_id' => $script_id,
  6889. 'product_id' => $product_id,
  6890. 'episode_number' => $sequence,
  6891. 'created_at' => $now,
  6892. 'updated_at' => $now,
  6893. ];
  6894. }
  6895. } else {
  6896. // 如果没有指定序号,创建一个默认映射(序号为0)
  6897. $mappingRecords[] = [
  6898. 'script_id' => $script_id,
  6899. 'product_id' => $product_id,
  6900. 'episode_number' => 0,
  6901. 'created_at' => $now,
  6902. 'updated_at' => $now,
  6903. ];
  6904. }
  6905. }
  6906. }
  6907. if (empty($mappingRecords)) {
  6908. Utils::throwError('20003:没有有效的产品数据');
  6909. }
  6910. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6911. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6912. // 如果需要自动生成图片,在事务中创建图片生成任务
  6913. $productTaskMap = [];
  6914. if ($auto_generate_images && !empty($createdProductIds)) {
  6915. // 查询所有创建的资产
  6916. $productsToGenerate = DB::table('mp_products')
  6917. ->whereIn('id', $createdProductIds)
  6918. ->where('is_deleted', 0)
  6919. ->get();
  6920. foreach ($productsToGenerate as $product) {
  6921. if (empty($product->pic_prompt)) {
  6922. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6923. 'product_id' => $product->id,
  6924. 'product_name' => $product->product_name
  6925. ]);
  6926. continue;
  6927. }
  6928. try {
  6929. // 创建图片生成任务
  6930. $params = [
  6931. 'prompt' => $product->pic_prompt,
  6932. 'model' => $model,
  6933. 'ref_img_urls' => [],
  6934. 'width' => $width,
  6935. 'height' => $height
  6936. ];
  6937. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6938. $task_id = $task->id;
  6939. if ($task_id) {
  6940. $productTaskMap[$product->id] = $task_id;
  6941. // 在事务中更新资产表的任务ID和状态
  6942. DB::table('mp_products')
  6943. ->where('id', $product->id)
  6944. ->update([
  6945. 'pic_task_id' => $task_id,
  6946. 'pic_task_status' => '生成中',
  6947. 'updated_at' => now()
  6948. ]);
  6949. dLog('anime')->info('创建资产图片生成任务', [
  6950. 'product_id' => $product->id,
  6951. 'task_id' => $task_id
  6952. ]);
  6953. }
  6954. } catch (\Exception $e) {
  6955. dLog('anime')->error('创建资产图片生成任务失败', [
  6956. 'product_id' => $product->id,
  6957. 'error' => $e->getMessage()
  6958. ]);
  6959. // 标记为失败(仍在事务中)
  6960. DB::table('mp_products')
  6961. ->where('id', $product->id)
  6962. ->update([
  6963. 'pic_task_status' => '生成失败',
  6964. 'updated_at' => now()
  6965. ]);
  6966. }
  6967. }
  6968. }
  6969. // 提交事务
  6970. DB::commit();
  6971. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6972. if ($auto_generate_images && !empty($productTaskMap)) {
  6973. // 返回 SSE 流(事务外轮询)
  6974. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6975. }
  6976. // 如果不需要生成图片,返回普通结果
  6977. return [
  6978. 'success' => true,
  6979. 'type_folder_ids' => $typeFolderIds,
  6980. 'inserted_count' => $insertedCount,
  6981. 'total_records' => count($mappingRecords),
  6982. 'created_products' => count($createdProductIds),
  6983. 'image_tasks_created' => count($productTaskMap)
  6984. ];
  6985. } catch (\Exception $e) {
  6986. // 回滚事务
  6987. DB::rollback();
  6988. // 记录错误日志
  6989. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6990. 'script_id' => $script_id,
  6991. 'error' => $e->getMessage(),
  6992. 'trace' => $e->getTraceAsString()
  6993. ]);
  6994. // 统一使用 Utils::throwError 抛出错误
  6995. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6996. }
  6997. }
  6998. /**
  6999. * 批量为剧本资产生成图片
  7000. *
  7001. * @param array $data 请求参数
  7002. * @return \Generator 返回 SSE 流
  7003. */
  7004. public function batchGenerateProductImages($data) {
  7005. $script_id = getProp($data, 'script_id');
  7006. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7007. if (!$script_id) {
  7008. Utils::throwError('20003:请提供剧本ID');
  7009. }
  7010. // 验证剧本是否存在
  7011. $script = DB::table('mp_scripts')
  7012. ->where('id', $script_id)
  7013. ->where('is_deleted', 0)
  7014. ->first();
  7015. if (!$script) {
  7016. Utils::throwError('20003:剧本不存在');
  7017. }
  7018. $script_name = $script->script_name ?? 'script_' . $script_id;
  7019. // 获取需要生成图片的所有资产
  7020. $products = DB::table('mp_products')
  7021. ->whereIn('parent_id', array_values($type_folder_ids))
  7022. ->where('is_deleted', 0)
  7023. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7024. ->get();
  7025. if ($products->isEmpty()) {
  7026. Utils::throwError('20003:没有找到需要生成图片的资产');
  7027. }
  7028. // 默认参数
  7029. $model = 'doubao-seedream-5-0-lite-260128';
  7030. $width = 1600;
  7031. $height = 2848;
  7032. // 开始为每个资产创建图片生成任务
  7033. $taskIds = [];
  7034. $productTaskMap = []; // 资产ID到任务ID的映射
  7035. foreach ($products as $product) {
  7036. if (empty($product->pic_prompt)) {
  7037. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7038. continue;
  7039. }
  7040. try {
  7041. // 创建图片生成任务
  7042. $params = [
  7043. 'prompt' => $product->pic_prompt,
  7044. 'model' => $model,
  7045. 'ref_img_urls' => [],
  7046. 'width' => $width,
  7047. 'height' => $height
  7048. ];
  7049. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7050. $task_id = $task->id;
  7051. if ($task_id) {
  7052. $taskIds[] = $task_id;
  7053. $productTaskMap[$product->id] = $task_id;
  7054. // 更新资产表的任务ID和状态
  7055. DB::table('mp_products')
  7056. ->where('id', $product->id)
  7057. ->update([
  7058. 'pic_task_id' => $task_id,
  7059. 'pic_task_status' => '生成中',
  7060. 'updated_at' => now()
  7061. ]);
  7062. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7063. }
  7064. } catch (\Exception $e) {
  7065. dLog('anime')->error('创建资产图片生成任务失败', [
  7066. 'product_id' => $product->id,
  7067. 'error' => $e->getMessage()
  7068. ]);
  7069. // 标记为失败
  7070. DB::table('mp_products')
  7071. ->where('id', $product->id)
  7072. ->update([
  7073. 'pic_task_status' => '生成失败',
  7074. 'updated_at' => now()
  7075. ]);
  7076. }
  7077. }
  7078. if (empty($taskIds)) {
  7079. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7080. }
  7081. // 返回 SSE 流
  7082. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7083. }
  7084. /**
  7085. * 轮询资产图片生成任务状态(SSE流式返回)
  7086. * 只通过查询数据库获取任务状态,不主动调用API
  7087. *
  7088. * @param int $script_id 剧本ID
  7089. * @param string $script_name 剧本名称
  7090. * @param array $productTaskMap 资产ID到任务ID的映射
  7091. * @param array $type_folder_ids 类型文件夹ID映射
  7092. * @return \Generator
  7093. */
  7094. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7095. $startTime = time();
  7096. $timeout = 1800; // 30分钟超时
  7097. $pollInterval = 10; // 10秒轮询一次
  7098. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7099. // 定义类型名称映射
  7100. $typeNames = [
  7101. 1 => 'roles', // 角色
  7102. 2 => 'scenes', // 场景
  7103. 3 => 'props' // 道具
  7104. ];
  7105. while (time() - $startTime < $timeout) {
  7106. sleep($pollInterval);
  7107. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7108. $mappings = DB::table('mp_script_product_mappings')
  7109. ->where('script_id', $script_id)
  7110. ->pluck('product_id')
  7111. ->unique()
  7112. ->toArray();
  7113. if (empty($mappings)) {
  7114. dLog('anime')->warning('该剧本没有关联的资产', [
  7115. 'script_id' => $script_id,
  7116. 'script_name' => $script_name
  7117. ]);
  7118. break;
  7119. }
  7120. // 查询所有资产的当前状态
  7121. $products = DB::table('mp_products')
  7122. ->whereIn('id', $mappings)
  7123. ->where('is_deleted', 0)
  7124. ->get();
  7125. // 统计各类型的状态(使用类型名称作为键名)
  7126. $stats = [
  7127. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7128. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7129. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7130. ];
  7131. $allCompleted = true;
  7132. $hasStatusChange = false;
  7133. foreach ($products as $product) {
  7134. $type = $product->product;
  7135. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7136. // 如果类型名称不在 stats 中,初始化
  7137. if (!isset($stats[$typeName])) {
  7138. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7139. }
  7140. $stats[$typeName]['total']++;
  7141. $task_id = $product->pic_task_id;
  7142. $currentStatus = $product->pic_task_status;
  7143. // 检查状态是否有变化
  7144. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7145. $hasStatusChange = true;
  7146. $lastStatus[$product->id] = $currentStatus;
  7147. }
  7148. // 如果是生成中,查询任务表状态
  7149. if ($currentStatus === '生成中' && $task_id) {
  7150. // 只查询数据库,不调用API
  7151. $task = DB::table('mp_generate_pic_tasks')
  7152. ->where('id', $task_id)
  7153. ->first();
  7154. if ($task) {
  7155. // 检查任务状态
  7156. if ($task->status === 'success' && $task->result_url) {
  7157. // 解析图片URL
  7158. $result_urls = $task->result_url;
  7159. if (is_string($result_urls)) {
  7160. $result_urls = json_decode($result_urls, true);
  7161. }
  7162. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7163. // 更新资产表状态
  7164. DB::table('mp_products')
  7165. ->where('id', $product->id)
  7166. ->update([
  7167. 'pic_task_status' => '生成成功',
  7168. 'url' => $img_url,
  7169. 'updated_at' => now()
  7170. ]);
  7171. $stats[$typeName]['success']++;
  7172. $stats[$typeName]['completed']++;
  7173. $hasStatusChange = true;
  7174. dLog('anime')->info('资产图片生成成功', [
  7175. 'product_id' => $product->id,
  7176. 'task_id' => $task_id,
  7177. 'img_url' => $img_url
  7178. ]);
  7179. } elseif ($task->status === 'failed') {
  7180. // 更新资产表状态
  7181. DB::table('mp_products')
  7182. ->where('id', $product->id)
  7183. ->update([
  7184. 'pic_task_status' => '生成失败',
  7185. 'updated_at' => now()
  7186. ]);
  7187. $stats[$typeName]['completed']++;
  7188. $hasStatusChange = true;
  7189. dLog('anime')->warning('资产图片生成失败', [
  7190. 'product_id' => $product->id,
  7191. 'task_id' => $task_id,
  7192. 'error' => $task->error_message ?? '未知错误'
  7193. ]);
  7194. } else {
  7195. // 任务还在处理中
  7196. $allCompleted = false;
  7197. }
  7198. } else {
  7199. // 任务不存在,标记为失败
  7200. DB::table('mp_products')
  7201. ->where('id', $product->id)
  7202. ->update([
  7203. 'pic_task_status' => '生成失败',
  7204. 'updated_at' => now()
  7205. ]);
  7206. $stats[$type]['completed']++;
  7207. $hasStatusChange = true;
  7208. dLog('anime')->error('图片生成任务不存在', [
  7209. 'product_id' => $product->id,
  7210. 'task_id' => $task_id
  7211. ]);
  7212. }
  7213. } elseif ($currentStatus === '生成成功') {
  7214. $stats[$typeName]['success']++;
  7215. $stats[$typeName]['completed']++;
  7216. } elseif ($currentStatus === '生成失败') {
  7217. $stats[$typeName]['completed']++;
  7218. } else {
  7219. // 其他状态也认为未完成
  7220. $allCompleted = false;
  7221. }
  7222. }
  7223. // 移除没有数据的类型(total=0)
  7224. foreach ($stats as $typeName => $stat) {
  7225. if ($stat['total'] === 0) {
  7226. unset($stats[$typeName]);
  7227. }
  7228. }
  7229. // 如果有状态变化,发送 SSE 更新
  7230. if ($hasStatusChange) {
  7231. $eventType = $allCompleted ? 'complete' : 'update';
  7232. $response = [
  7233. 'type' => $eventType,
  7234. 'script_id' => $script_id,
  7235. 'script_name' => $script_name,
  7236. 'stats' => $stats,
  7237. 'timestamp' => date('Y-m-d H:i:s')
  7238. ];
  7239. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7240. dLog('anime')->info('SSE更新', [
  7241. 'event_type' => $eventType,
  7242. 'script_id' => $script_id,
  7243. 'script_name' => $script_name,
  7244. 'stats' => $stats
  7245. ]);
  7246. if ($allCompleted) {
  7247. dLog('anime')->info('所有资产图片生成任务已完成', [
  7248. 'script_id' => $script_id,
  7249. 'script_name' => $script_name,
  7250. 'stats' => $stats
  7251. ]);
  7252. break;
  7253. }
  7254. }
  7255. }
  7256. // 超时处理
  7257. if (time() - $startTime >= $timeout && !$allCompleted) {
  7258. $response = [
  7259. 'type' => 'timeout',
  7260. 'message' => '部分任务超时,请稍后查看结果',
  7261. 'script_id' => $script_id,
  7262. 'script_name' => $script_name,
  7263. 'timestamp' => date('Y-m-d H:i:s')
  7264. ];
  7265. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7266. dLog('anime')->warning('资产图片生成任务超时', [
  7267. 'script_id' => $script_id,
  7268. 'script_name' => $script_name,
  7269. 'timeout' => $timeout
  7270. ]);
  7271. }
  7272. }
  7273. /**
  7274. * 获取剧本关联的资产列表
  7275. * @param array $data 请求参数
  7276. * @return array
  7277. */
  7278. public function getScriptProducts($data) {
  7279. $uid = Site::getUid();
  7280. $cpid = Site::getCpid();
  7281. $script_id = getProp($data, 'script_id');
  7282. $episode_number = getProp($data, 'episode_number');
  7283. if (!$script_id) {
  7284. Utils::throwError('20003:请提供剧本ID');
  7285. }
  7286. // 验证剧本是否存在
  7287. $script = DB::table('mp_scripts')
  7288. ->where('id', $script_id)
  7289. ->where('is_deleted', 0)
  7290. ->first();
  7291. if (!$script) {
  7292. Utils::throwError('20003:剧本不存在');
  7293. }
  7294. // 联表查询资产信息
  7295. $query = DB::table('mp_script_product_mappings as mapping')
  7296. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7297. ->where('mapping.script_id', $script_id)
  7298. ->where('product.cpid', $cpid)
  7299. ->where('product.is_deleted', 0);
  7300. // 如果提供了 episode_number,则过滤指定集数
  7301. if ($episode_number !== null && $episode_number !== '') {
  7302. $query->where('mapping.episode_number', $episode_number);
  7303. }
  7304. $mappings = $query->select(
  7305. 'mapping.script_id',
  7306. 'mapping.product_id',
  7307. 'mapping.episode_number',
  7308. 'product.product_name',
  7309. 'product.type',
  7310. 'product.product',
  7311. 'product.pic_prompt',
  7312. 'product.url',
  7313. 'product.pic_task_id',
  7314. 'product.pic_task_status',
  7315. 'product.three_view_image_url',
  7316. 'mapping.created_at'
  7317. )
  7318. ->orderBy('mapping.product_id', 'asc')
  7319. ->orderBy('mapping.episode_number', 'asc')
  7320. ->get();
  7321. // 按 product_id 分组,合并 episode_number
  7322. $productMap = [];
  7323. foreach ($mappings as $item) {
  7324. $product_id = $item->product_id;
  7325. if (!isset($productMap[$product_id])) {
  7326. $productMap[$product_id] = [
  7327. 'product_id' => $product_id,
  7328. 'product_name' => $item->product_name,
  7329. 'type' => (int)$item->type,
  7330. 'product' => (int)$item->product,
  7331. 'pic_prompt' => $item->pic_prompt,
  7332. 'url' => $item->url,
  7333. 'pic_task_id' => $item->pic_task_id,
  7334. 'pic_task_status' => $item->pic_task_status,
  7335. 'episode_numbers' => [],
  7336. 'created_at' => $item->created_at,
  7337. ];
  7338. }
  7339. // 添加 episode_number(去重)
  7340. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7341. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7342. }
  7343. }
  7344. // 按类型分组
  7345. $roles = []; // type=1 角色/主体
  7346. $scenes = []; // type=2 场景
  7347. $props = []; // type=3 道具
  7348. foreach ($productMap as $product) {
  7349. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7350. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7351. // 构造返回数据
  7352. $productData = [
  7353. 'product_id' => $product['product_id'],
  7354. 'product_name' => $product['product_name'],
  7355. 'product' => $product['product'],
  7356. 'pic_prompt' => $product['pic_prompt'],
  7357. 'url' => $product['url'],
  7358. 'pic_task_id' => $product['pic_task_id'],
  7359. 'pic_task_status' => $product['pic_task_status'],
  7360. 'episode_numbers' => $episodeNumbersStr,
  7361. 'created_at' => $product['created_at'],
  7362. ];
  7363. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7364. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7365. switch ($product['product']) {
  7366. case 1:
  7367. $roles[] = $productData;
  7368. break;
  7369. case 2:
  7370. $scenes[] = $productData;
  7371. break;
  7372. case 3:
  7373. $props[] = $productData;
  7374. break;
  7375. }
  7376. }
  7377. return [
  7378. 'script_id' => $script_id,
  7379. 'script_name' => $script->script_name ?? '',
  7380. 'roles' => $roles, // 主体
  7381. 'scenes' => $scenes, // 场景
  7382. 'props' => $props, // 道具
  7383. ];
  7384. }
  7385. /**
  7386. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7387. * @param string $actContent 原始内容
  7388. * @param array $products 产品数组(包含product_name和url)
  7389. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7390. */
  7391. public function processActContentWithProducts($actContent, $products) {
  7392. if (empty($actContent) || empty($products)) {
  7393. return [
  7394. 'content' => $actContent,
  7395. 'reference_images' => []
  7396. ];
  7397. }
  7398. // 构建产品名称到产品信息的映射
  7399. $product_dict = [];
  7400. foreach ($products as $product) {
  7401. $product_name = getProp($product, 'product_name');
  7402. if ($product_name) {
  7403. $product_dict[$product_name] = [
  7404. 'url' => getProp($product, 'url'),
  7405. 'voice_prompt' => getProp($product, 'voice_prompt')
  7406. ];
  7407. }
  7408. }
  7409. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7410. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7411. $reference_images = [];
  7412. $product_index_map = []; // 产品名称 => 图片序号的映射
  7413. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7414. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7415. $current_index = 1;
  7416. if (!empty($matches[1])) {
  7417. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7418. $seen_products = []; // 用于去重
  7419. foreach ($matches[1] as $product_name) {
  7420. // 跳过已处理的产品
  7421. if (isset($seen_products[$product_name])) {
  7422. continue;
  7423. }
  7424. $seen_products[$product_name] = true;
  7425. // 检查产品是否在字典中
  7426. if (isset($product_dict[$product_name])) {
  7427. $url = $product_dict[$product_name]['url'];
  7428. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7429. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7430. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7431. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7432. }
  7433. // 只有URL非空才分配序号和添加到参考图片
  7434. if (!empty($url)) {
  7435. // 检查URL是否已经在reference_images中(去重)
  7436. if (!in_array($url, $reference_images)) {
  7437. $reference_images[] = $url;
  7438. $product_index_map[$product_name] = $current_index;
  7439. $current_index++;
  7440. } else {
  7441. // URL重复,找到已有的序号
  7442. $existing_index = array_search($url, $reference_images) + 1;
  7443. $product_index_map[$product_name] = $existing_index;
  7444. }
  7445. } else {
  7446. // URL为空,不分配序号(后续直接去掉{})
  7447. $product_index_map[$product_name] = 0;
  7448. }
  7449. } else {
  7450. // 产品不在字典中,不分配序号
  7451. $product_index_map[$product_name] = 0;
  7452. }
  7453. }
  7454. }
  7455. // 第二步:替换内容中的 {产品名称}
  7456. $processedContent = $actContent;
  7457. foreach ($product_index_map as $product_name => $index) {
  7458. $escaped_name = preg_quote($product_name, '/');
  7459. if ($index > 0) {
  7460. // 有图片,替换为:产品名称(图X)
  7461. $replacement = $product_name . '<图片' . $index . '>';
  7462. } else {
  7463. // 无图片,只保留产品名称
  7464. $replacement = $product_name;
  7465. }
  7466. // 替换所有 {产品名称} 为处理后的格式
  7467. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7468. }
  7469. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7470. foreach ($products as $product) {
  7471. $product_name = getProp($product, 'product_name');
  7472. $voice_prompt = getProp($product, 'voice_prompt');
  7473. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7474. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7475. break; // 找到旁白后退出循环
  7476. }
  7477. }
  7478. // 第四步:将voice_prompt信息添加到内容最前面
  7479. $voice_prompt_prefix = '';
  7480. if (!empty($voice_prompts)) {
  7481. $voice_prompt_prefix .= implode('', $voice_prompts);
  7482. }
  7483. // 旁白的voice_prompt放在最后
  7484. if (!empty($narrator_voice_prompt)) {
  7485. $voice_prompt_prefix .= $narrator_voice_prompt;
  7486. }
  7487. // 如果有voice_prompt信息,添加到内容开头
  7488. if (!empty($voice_prompt_prefix)) {
  7489. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7490. }
  7491. return [
  7492. 'content' => $processedContent,
  7493. 'reference_images' => $reference_images
  7494. ];
  7495. }
  7496. public function saveActVideoGenerateParams($data) {
  7497. $episode_id = getProp($data, 'episode_id');
  7498. $model = getProp($data, 'video_model');
  7499. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7500. Utils::throwError('20003:该模型不可用');
  7501. }
  7502. if (!$model) {
  7503. // 使用默认模型
  7504. $model = 'zhizhen-20';
  7505. }
  7506. // 验证模型是否在可用模型表中
  7507. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7508. Utils::throwError('20003:该模型已不可用,请更换!');
  7509. }
  7510. $video_resolution = getProp($data, 'video_resolution', '720p');
  7511. $ratio = getProp($data, 'ratio');
  7512. if (!$ratio) $ratio = '9:16';
  7513. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7514. 'video_model' => $model,
  7515. 'video_resolution' => $video_resolution,
  7516. 'ratio' => $ratio,
  7517. 'updated_at' => date('Y-m-d H:i:s')
  7518. ]);
  7519. }
  7520. public function confirmActs($data) {
  7521. $episode_id = getProp($data, 'episode_id');
  7522. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7523. if (!$episode) {
  7524. Utils::throwError('20003:分集不存在');
  7525. }
  7526. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7527. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7528. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7529. // 获取所有片段数据
  7530. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7531. // 收集所有资产名称(角色、场景、道具)
  7532. $product_names = [];
  7533. // 收集角色名称
  7534. foreach ($roles as $role) {
  7535. $role_name = getProp($role, 'role');
  7536. if ($role_name && $role_name != '旁白') {
  7537. $product_names[] = $role_name;
  7538. }
  7539. }
  7540. // 收集场景名称
  7541. foreach ($scenes as $scene) {
  7542. $scene_name = getProp($scene, 'scene');
  7543. if ($scene_name) {
  7544. $product_names[] = $scene_name;
  7545. }
  7546. }
  7547. // 收集道具名称
  7548. foreach ($props as $prop) {
  7549. $prop_name = getProp($prop, 'prop');
  7550. if ($prop_name) {
  7551. $product_names[] = $prop_name;
  7552. }
  7553. }
  7554. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7555. $product_names = array_unique($product_names);
  7556. usort($product_names, function($a, $b) {
  7557. return mb_strlen($b) - mb_strlen($a);
  7558. });
  7559. try {
  7560. DB::beginTransaction();
  7561. // 处理每个片段
  7562. foreach ($acts as $act) {
  7563. $act_content = getProp($act, 'act_content');
  7564. if (!$act_content) continue;
  7565. $processed_content = $act_content;
  7566. // 统一替换所有资产名称为 {资产名} 格式
  7567. // 使用占位符避免嵌套替换问题
  7568. $placeholder_map = [];
  7569. $placeholder_index = 0;
  7570. foreach ($product_names as $product_name) {
  7571. // 转义特殊字符
  7572. $escaped_product = preg_quote($product_name, '/');
  7573. // 检查是否匹配且未被 {} 包裹
  7574. $processed_content = preg_replace_callback(
  7575. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7576. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7577. // 使用唯一占位符
  7578. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7579. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7580. $placeholder_index++;
  7581. return $placeholder;
  7582. },
  7583. $processed_content
  7584. );
  7585. }
  7586. // 将所有占位符替换回实际内容
  7587. foreach ($placeholder_map as $placeholder => $replacement) {
  7588. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7589. }
  7590. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7591. $shot_counter = 0;
  7592. $processed_content = preg_replace_callback(
  7593. '/【(?:镜头|分镜)(\d+)】/u',
  7594. function($matches) use (&$shot_counter) {
  7595. $shot_counter++;
  7596. return '【镜头' . $shot_counter . '】';
  7597. },
  7598. $processed_content
  7599. );
  7600. // 更新数据库
  7601. $boolen = DB::table('mp_episode_segments')
  7602. ->where('id', $act->id)
  7603. ->update([
  7604. 'act_show_content' => $processed_content,
  7605. 'updated_at' => date('Y-m-d H:i:s')
  7606. ]);
  7607. if (!$boolen) {
  7608. Utils::throwError('20003:片段处理失败');
  7609. }
  7610. }
  7611. }catch (\Exception $e) {
  7612. DB::rollBack();
  7613. Utils::throwError('20003:'.$e->getMessage());
  7614. }
  7615. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7616. 'is_generated' => 1,
  7617. 'updated_at' => date('Y-m-d H:i:s')
  7618. ]);
  7619. if (!$boolen1) {
  7620. DB::rollBack();
  7621. Utils::throwError('20003:分集处理失败!');
  7622. }
  7623. DB::commit();
  7624. // 重新查询更新后的片段数据
  7625. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7626. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7627. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7628. $products = [];
  7629. // 先处理角色数组
  7630. foreach ($roles as $role) {
  7631. $product = $role;
  7632. // 将role字段重命名为product_name
  7633. if (isset($product['role'])) {
  7634. $product['product_name'] = $product['role'];
  7635. unset($product['role']);
  7636. $product['product'] = 1; // 标记类型为角色
  7637. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7638. }
  7639. }
  7640. // 处理场景数组
  7641. foreach ($scenes as $scene) {
  7642. $product = $scene;
  7643. // 将scene字段重命名为product_name
  7644. if (isset($product['scene'])) {
  7645. $product['product_name'] = $product['scene'];
  7646. unset($product['scene']);
  7647. $product['product'] = 2; // 标记类型为场景
  7648. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7649. }
  7650. }
  7651. // 处理道具数组(逻辑与场景一致)
  7652. foreach ($props as $prop) {
  7653. $product = $prop;
  7654. // 将prop字段重命名为product_name
  7655. if (isset($product['prop'])) {
  7656. $product['product_name'] = $product['prop'];
  7657. unset($product['prop']);
  7658. $product['product'] = 3; // 标记类型为道具
  7659. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7660. }
  7661. }
  7662. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7663. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7664. foreach ($extra_products as $extra_product) {
  7665. $product_name = getProp($extra_product, 'product_name');
  7666. if ($product_name) {
  7667. $products[$product_name] = $extra_product; // 覆盖同名数据
  7668. }
  7669. }
  7670. // 重新索引数组(去除key)
  7671. $products = array_values($products);
  7672. // 构建返回的acts数组
  7673. $return_acts = [];
  7674. foreach ($acts as $act) {
  7675. $return_acts[] = [
  7676. 'act_id' => getProp($act, 'id'),
  7677. 'act_number' => getProp($act, 'act_number'),
  7678. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7679. 'act_show_content' => getProp($act, 'act_show_content'),
  7680. 'video_url' => getProp($act, 'video_url'),
  7681. 'video_duration' => getProp($act, 'video_duration'),
  7682. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7683. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7684. ];
  7685. }
  7686. return [
  7687. 'anime_id' => getProp($episode, 'anime_id'),
  7688. 'episode_id' => $episode_id,
  7689. 'title' => getProp($episode, 'title'),
  7690. 'episode_number' => getProp($episode, 'episode_number'),
  7691. 'is_generated' => getProp($episode, 'is_generated'),
  7692. 'products' => $products,
  7693. 'acts' => $return_acts
  7694. ];
  7695. }
  7696. }