AnimeService.php 384 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883
  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. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4379. *
  4380. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4381. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4382. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4383. *
  4384. * @param array $data
  4385. * @return array
  4386. */
  4387. public function previewCharge(array $data): array
  4388. {
  4389. $mode = (string)getProp($data, 'mode', '');
  4390. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4391. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4392. }
  4393. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4394. $scene = (string)getProp($data, 'scene', 'video_generation');
  4395. $items = [];
  4396. $model = '';
  4397. $resolution = '';
  4398. if ($mode === 'video') {
  4399. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4400. $model = (string)getProp($data, 'model', '');
  4401. if (!$model) {
  4402. Utils::throwError('1002:model参数不能为空');
  4403. }
  4404. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4405. $duration = (int)getProp($data, 'video_duration', 5);
  4406. if ($duration <= 0) {
  4407. $duration = 5;
  4408. }
  4409. $count = max(1, (int)getProp($data, 'count', 1));
  4410. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4411. 'model' => $model,
  4412. 'video_resolution' => $resolution,
  4413. 'video_duration' => $duration,
  4414. 'mode' => $scene,
  4415. ]);
  4416. $points = $pointsPerVideo * $count;
  4417. $items[] = [
  4418. 'type' => 'video',
  4419. 'model' => $model,
  4420. 'video_resolution' => $resolution,
  4421. 'video_duration' => $duration,
  4422. 'count' => $count,
  4423. 'points' => $points,
  4424. ];
  4425. } elseif ($mode === 'image') {
  4426. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4427. $model = (string)getProp($data, 'model', '');
  4428. if (!$model) {
  4429. Utils::throwError('1002:model参数不能为空');
  4430. }
  4431. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4432. if (!$resolution) {
  4433. $width = (int)getProp($data, 'width', 0);
  4434. $height = (int)getProp($data, 'height', 0);
  4435. if ($width <= 0 || $height <= 0) {
  4436. $width = 1600;
  4437. $height = 2848;
  4438. }
  4439. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4440. }
  4441. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4442. $points = $this->pointsService->getImageChargePoints([
  4443. 'model' => $model,
  4444. 'resolution' => $resolution,
  4445. ]) * $imageNum;
  4446. $items[] = [
  4447. 'type' => 'image',
  4448. 'model' => $model,
  4449. 'resolution' => $resolution,
  4450. 'image_num' => $imageNum,
  4451. 'points' => $points,
  4452. ];
  4453. } else {
  4454. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4455. $count = max(1, (int)getProp($data, 'count', 1));
  4456. $animeId = getProp($data, 'anime_id');
  4457. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4458. if ($animeId && $generateEpisodes > 0) {
  4459. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4460. ->where('anime_id', $animeId)
  4461. ->where('is_default', 1)
  4462. ->max('episode_number');
  4463. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4464. $startEpisodeNumber = $currentMaxEpisode + 1;
  4465. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4466. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4467. ->where('anime_id', $animeId)
  4468. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4469. ->whereIn('status', ['pending', 'processing', 'completed'])
  4470. ->count();
  4471. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4472. if ($count < 0) {
  4473. $count = 0;
  4474. }
  4475. }
  4476. $points = PointsService::CHAT_CHARGE_POINTS * $count;
  4477. $items[] = [
  4478. 'type' => 'chat',
  4479. 'count' => $count,
  4480. 'points' => $points,
  4481. ];
  4482. }
  4483. $totalPoints = 0;
  4484. foreach ($items as $item) {
  4485. $totalPoints += $item['points'];
  4486. }
  4487. return [
  4488. 'mode' => $mode,
  4489. 'total_points' => $totalPoints,
  4490. 'items' => $items,
  4491. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4492. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4493. ];
  4494. }
  4495. /**
  4496. * 根据提示词内容智能计算最优视频时长
  4497. *
  4498. * @param string $segmentContent 分镜内容
  4499. * @param string $tailFrame 尾帧描述
  4500. * @return int 视频时长(2-12秒)
  4501. */
  4502. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4503. // 合并所有文本内容
  4504. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4505. // 如果没有内容,返回默认时长
  4506. if (empty($fullText)) {
  4507. return 5;
  4508. }
  4509. // 计算文本长度(中文字符按2个字符计算)
  4510. $textLength = mb_strlen($fullText, 'UTF-8');
  4511. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4512. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4513. // 分析内容复杂度
  4514. $complexityScore = $this->analyzeContentComplexity($fullText);
  4515. // 基础时长计算(根据文本长度)
  4516. $baseDuration = 3; // 默认2秒
  4517. // if ($adjustedLength <= 20) {
  4518. // $baseDuration = 3;
  4519. // } elseif ($adjustedLength <= 40) {
  4520. // $baseDuration = 4;
  4521. // } elseif ($adjustedLength <= 60) {
  4522. // $baseDuration = 5;
  4523. // } elseif ($adjustedLength <= 80) {
  4524. // $baseDuration = 6;
  4525. // } elseif ($adjustedLength <= 100) {
  4526. // $baseDuration = 7;
  4527. // } elseif ($adjustedLength <= 120) {
  4528. // $baseDuration = 8;
  4529. // } else {
  4530. // $baseDuration = 9;
  4531. // }
  4532. // 根据内容复杂度调整时长
  4533. $finalDuration = $baseDuration + $complexityScore;
  4534. // 确保时长在2-12秒范围内
  4535. return max(4, min(12, $finalDuration));
  4536. }
  4537. /**
  4538. * 分析内容复杂度,返回时长调整值
  4539. *
  4540. * @param string $text 文本内容
  4541. * @return int 调整值(-2到+3)
  4542. */
  4543. private function analyzeContentComplexity($text) {
  4544. $score = 0;
  4545. // 动作关键词(需要更长时间展现)
  4546. $actionKeywords = [
  4547. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4548. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4549. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4550. ];
  4551. // 静态关键词(可以用较短时间)
  4552. $staticKeywords = [
  4553. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4554. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4555. ];
  4556. // 复杂场景关键词(需要更长时间)
  4557. $complexSceneKeywords = [
  4558. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4559. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4560. ];
  4561. // 情感关键词(需要适中时间表现)
  4562. $emotionKeywords = [
  4563. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4564. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4565. ];
  4566. // 检查动作关键词
  4567. foreach ($actionKeywords as $keyword) {
  4568. if (strpos($text, $keyword) !== false) {
  4569. $score += 1;
  4570. break; // 避免重复加分
  4571. }
  4572. }
  4573. // 检查静态关键词
  4574. foreach ($staticKeywords as $keyword) {
  4575. if (strpos($text, $keyword) !== false) {
  4576. $score -= 1;
  4577. break;
  4578. }
  4579. }
  4580. // 检查复杂场景关键词
  4581. foreach ($complexSceneKeywords as $keyword) {
  4582. if (strpos($text, $keyword) !== false) {
  4583. $score += 1;
  4584. break;
  4585. }
  4586. }
  4587. // 检查情感关键词
  4588. foreach ($emotionKeywords as $keyword) {
  4589. if (strpos($text, $keyword) !== false) {
  4590. $score += 1;
  4591. break;
  4592. }
  4593. }
  4594. // 检查时间相关词汇
  4595. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4596. $score += 1;
  4597. }
  4598. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4599. $score -= 1;
  4600. }
  4601. // 检查转场词汇
  4602. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4603. $score += 1;
  4604. }
  4605. // 检查环境描述(复杂环境需要更多时间)
  4606. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4607. $score += 1;
  4608. }
  4609. // 检查对话内容(对话需要更多时间)
  4610. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4611. $score += 1;
  4612. }
  4613. // 限制调整范围
  4614. return max(-1, min(4, $score));
  4615. }
  4616. /**
  4617. * 创建完整视频合成任务
  4618. *
  4619. * @param array $data
  4620. * @return array
  4621. */
  4622. public function createCompleteVideoTask($data)
  4623. {
  4624. $animeId = getProp($data, 'anime_id');
  4625. $episodeId = getProp($data, 'episode_id');
  4626. // 验证参数
  4627. if (!$animeId || !$episodeId) {
  4628. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4629. }
  4630. // 检查是否已存在处理中的任务
  4631. $existingTask = DB::table('mp_complete_video_tasks')
  4632. ->where('anime_id', $animeId)
  4633. ->where('episode_id', $episodeId)
  4634. ->whereIn('generate_status', ['执行中'])
  4635. ->first();
  4636. if ($existingTask) {
  4637. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4638. }
  4639. // 获取全能模式状态
  4640. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4641. if ((int)$ace_mode === 1) {
  4642. // 获取所有片段的配音视频,按 act_number 排序
  4643. $segments = DB::table('mp_episode_segments')
  4644. ->where('anime_id', $animeId)
  4645. ->where('episode_id', $episodeId)
  4646. ->orderBy('segment_number')
  4647. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4648. ->get();
  4649. // 检查是否所有片段都有视频
  4650. $missingVideos = $segments->filter(function($segment) {
  4651. return empty($segment->video_url);
  4652. });
  4653. if ($missingVideos->isNotEmpty()) {
  4654. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4655. }
  4656. }else {
  4657. // 获取所有分镜的配音视频,按 segment_number 排序
  4658. $segments = DB::table('mp_episode_segments')
  4659. ->where('anime_id', $animeId)
  4660. ->where('episode_id', $episodeId)
  4661. ->orderBy('segment_number')
  4662. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4663. ->get();
  4664. // 检查是否所有分镜都有配音和视频
  4665. $missingVideos = $segments->filter(function($segment) {
  4666. return empty($segment->audio_url) || empty($segment->video_url);
  4667. });
  4668. if ($missingVideos->isNotEmpty()) {
  4669. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4670. }
  4671. }
  4672. if ($segments->isEmpty()) {
  4673. Utils::throwError('20003:未找到该剧集的分镜数据');
  4674. }
  4675. // 获取当前完整视频url
  4676. $completeVideoUrl = DB::table('mp_anime_episodes')
  4677. ->where('anime_id', $animeId)
  4678. ->where('id', $episodeId)
  4679. ->value('complete_video_url');
  4680. // 构建 generate_json
  4681. $generateJson = [];
  4682. $sequence = 1;
  4683. foreach ($segments as $segment) {
  4684. if ((int)$ace_mode === 1) {
  4685. $generateJson[] = [
  4686. 'sequence' => $sequence++,
  4687. 'video_url' => $segment->video_url,
  4688. 'video_time_point_start' => $segment->video_time_point_start,
  4689. 'video_time_point_end' => $segment->video_time_point_end
  4690. ];
  4691. }else {
  4692. $generateJson[] = [
  4693. 'sequence' => $sequence++,
  4694. 'video_url' => $segment->video_url,
  4695. 'audio_url' => $segment->audio_url,
  4696. 'video_time_point_start' => $segment->video_time_point_start,
  4697. 'video_time_point_end' => $segment->video_time_point_end
  4698. ];
  4699. }
  4700. }
  4701. // 创建任务
  4702. $now = date('Y-m-d H:i:s');
  4703. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4704. 'anime_id' => $animeId,
  4705. 'episode_id' => $episodeId,
  4706. 'generate_json' => json_encode($generateJson, 256),
  4707. 'generate_status' => '执行中',
  4708. 'complete_video_url' => '',
  4709. 'created_at' => $now,
  4710. 'updated_at' => $now
  4711. ]);
  4712. if (!$taskId) {
  4713. Utils::throwError('20003:创建任务失败');
  4714. }
  4715. // 更新剧集表的任务ID和状态
  4716. $boolen = DB::table('mp_anime_episodes')
  4717. ->where('anime_id', $animeId)
  4718. ->where('id', $episodeId)
  4719. ->update([
  4720. 'complete_video_task_id' => $taskId,
  4721. 'complete_video_task_status' => '执行中',
  4722. 'updated_at' => $now
  4723. ]);
  4724. if (!$boolen) {
  4725. Utils::throwError('20003:更新剧集表失败');
  4726. }
  4727. dLog('anime')->info('创建完整视频合成任务', [
  4728. 'task_id' => $taskId,
  4729. 'anime_id' => $animeId,
  4730. 'episode_id' => $episodeId,
  4731. 'segment_count' => count($generateJson)
  4732. ]);
  4733. // 请求远程服务器执行生成
  4734. $client = new Client(['timeout' => 600, 'verify' => false]);
  4735. try {
  4736. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4737. $response = $result->getBody()->getContents();
  4738. $response_arr = json_decode($response, true);
  4739. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4740. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4741. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4742. // // 更新任务状态为失败
  4743. // DB::table('mp_complete_video_tasks')
  4744. // ->where('id', $taskId)
  4745. // ->update([
  4746. // 'generate_status' => '执行失败',
  4747. // 'error_message' => $error_msg,
  4748. // 'updated_at' => date('Y-m-d H:i:s')
  4749. // ]);
  4750. // // 同步更新剧集表状态
  4751. // DB::table('mp_anime_episodes')
  4752. // ->where('complete_video_task_id', $taskId)
  4753. // ->update([
  4754. // 'complete_video_task_status' => '执行失败',
  4755. // 'updated_at' => date('Y-m-d H:i:s')
  4756. // ]);
  4757. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4758. }
  4759. } catch (\Exception $e) {
  4760. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4761. // 更新任务状态为失败
  4762. DB::table('mp_complete_video_tasks')
  4763. ->where('id', $taskId)
  4764. ->update([
  4765. 'generate_status' => '执行失败',
  4766. 'error_message' => $e->getMessage(),
  4767. 'updated_at' => date('Y-m-d H:i:s')
  4768. ]);
  4769. // 同步更新剧集表状态
  4770. DB::table('mp_anime_episodes')
  4771. ->where('complete_video_task_id', $taskId)
  4772. ->update([
  4773. 'complete_video_task_status' => '执行失败',
  4774. 'updated_at' => date('Y-m-d H:i:s')
  4775. ]);
  4776. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4777. }
  4778. // 开始轮询任务状态
  4779. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4780. $pollInterval = 5; // 每5秒轮询一次
  4781. $attempt = 0;
  4782. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4783. while ($attempt < $maxAttempts) {
  4784. sleep($pollInterval);
  4785. $attempt++;
  4786. // 查询任务状态
  4787. $task = DB::table('mp_complete_video_tasks')
  4788. ->where('id', $taskId)
  4789. ->first();
  4790. if (!$task) {
  4791. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4792. Utils::throwError('20003:任务不存在');
  4793. }
  4794. dLog('anime')->info('轮询任务状态', [
  4795. 'task_id' => $taskId,
  4796. 'attempt' => $attempt,
  4797. 'status' => $task->generate_status
  4798. ]);
  4799. // 检查任务是否完成
  4800. if ($task->generate_status === '执行成功') {
  4801. // 同步更新剧集表状态
  4802. $boolen3 = DB::table('mp_anime_episodes')
  4803. ->where('anime_id', $animeId)
  4804. ->where('id', $episodeId)
  4805. ->update([
  4806. 'complete_video_url' => $task->complete_video_url,
  4807. 'complete_video_task_status' => '执行成功',
  4808. 'updated_at' => date('Y-m-d H:i:s')
  4809. ]);
  4810. dLog('anime')->info('视频合成任务完成', [
  4811. 'task_id' => $taskId,
  4812. 'video_url' => $task->complete_video_url,
  4813. 'attempts' => $attempt
  4814. ]);
  4815. // 如果更新成功则远程删除之前的文件
  4816. if ($boolen3 && $completeVideoUrl) {
  4817. $encode_url = urlencode($completeVideoUrl);
  4818. $client = new Client(['timeout' => 300, 'verify' => false]);
  4819. // 根据ID通过API通知合成音频
  4820. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4821. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4822. $response = $result->getBody()->getContents();
  4823. $response_arr = json_decode($response, true);
  4824. Log::info('火山删除音频返回: '.$response);
  4825. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4826. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4827. Log::info('火山删除音频失败: '.$error_msg);
  4828. // Utils::throwError('20003:火山删除音频失败');
  4829. }
  4830. }
  4831. return [
  4832. 'task_id' => $taskId,
  4833. 'anime_id' => $animeId,
  4834. 'episode_id' => $episodeId,
  4835. 'segment_count' => count($generateJson),
  4836. 'generate_status' => '执行成功',
  4837. 'complete_video_url' => $task->complete_video_url,
  4838. ];
  4839. }
  4840. // 检查任务是否失败
  4841. if ($task->generate_status === '执行失败') {
  4842. // 同步更新剧集表状态
  4843. DB::table('mp_anime_episodes')
  4844. ->where('anime_id', $animeId)
  4845. ->where('id', $episodeId)
  4846. ->update([
  4847. 'complete_video_task_status' => '执行失败',
  4848. 'updated_at' => date('Y-m-d H:i:s')
  4849. ]);
  4850. $errorMessage = $task->error_message ?? '未知错误';
  4851. dLog('anime')->error('视频合成任务失败', [
  4852. 'task_id' => $taskId,
  4853. 'error' => $errorMessage,
  4854. 'attempts' => $attempt
  4855. ]);
  4856. return [
  4857. 'task_id' => $taskId,
  4858. 'anime_id' => $animeId,
  4859. 'episode_id' => $episodeId,
  4860. 'segment_count' => count($generateJson),
  4861. 'generate_status' => '执行失败',
  4862. 'error_message' => $errorMessage
  4863. ];
  4864. }
  4865. }
  4866. // 超时处理
  4867. dLog('anime')->warning('视频合成任务超时', [
  4868. 'task_id' => $taskId,
  4869. 'max_attempts' => $maxAttempts,
  4870. 'timeout_seconds' => $maxAttempts * $pollInterval
  4871. ]);
  4872. // 更新任务状态为超时
  4873. DB::table('mp_complete_video_tasks')
  4874. ->where('id', $taskId)
  4875. ->update([
  4876. 'generate_status' => '超时',
  4877. 'error_message' => '任务执行超时(5分钟)',
  4878. 'updated_at' => date('Y-m-d H:i:s')
  4879. ]);
  4880. return [
  4881. 'task_id' => $taskId,
  4882. 'anime_id' => $animeId,
  4883. 'episode_id' => $episodeId,
  4884. 'segment_count' => count($generateJson),
  4885. 'generate_status' => '超时',
  4886. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4887. ];
  4888. }
  4889. /**
  4890. * 根据 inner_prompt_type 附加内置提示词
  4891. *
  4892. * @param string $prompt 用户提示词
  4893. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4894. * @return string 合并后的提示词
  4895. */
  4896. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4897. {
  4898. $innerPromptMap = [
  4899. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4900. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4901. ];
  4902. if (!isset($innerPromptMap[$innerPromptType])) {
  4903. return $prompt;
  4904. }
  4905. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4906. }
  4907. /**
  4908. * 根据 inner_prompt_type 获取生成图片数量
  4909. *
  4910. * @param int $innerPromptType 内置提示词类型
  4911. * @return int 图片数量
  4912. */
  4913. public static function getInnerImageNum($innerPromptType = 0)
  4914. {
  4915. return (int)$innerPromptType === 2 ? 9 : 1;
  4916. }
  4917. /**
  4918. * 提取图片生成结果URL
  4919. *
  4920. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4921. * @param int $innerPromptType 内置提示词类型
  4922. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4923. */
  4924. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4925. {
  4926. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4927. if (is_array($resultUrls) && !empty($resultUrls)) {
  4928. $resultUrls = array_values($resultUrls);
  4929. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4930. }
  4931. if (!empty($resultUrl)) {
  4932. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4933. }
  4934. return (int)$innerPromptType === 2 ? [] : '';
  4935. }
  4936. public function generateImg($data) {
  4937. $prompt = getProp($data, 'prompt');
  4938. $episode_id = getProp($data, 'episode_id');
  4939. $ref_img_urls = getProp($data, 'ref_img_urls');
  4940. $ratio = getProp($data, 'ratio', '9:16');
  4941. $resolution = getProp($data, 'resolution', '2k');
  4942. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4943. // 定义分辨率和宽高比对应的尺寸映射表
  4944. $sizeMap = [
  4945. '2k' => [
  4946. '1:1' => ['width' => 2048, 'height' => 2048],
  4947. '4:3' => ['width' => 2304, 'height' => 1728],
  4948. '3:4' => ['width' => 1728, 'height' => 2304],
  4949. '16:9' => ['width' => 2848, 'height' => 1600],
  4950. '9:16' => ['width' => 1600, 'height' => 2848],
  4951. '3:2' => ['width' => 2496, 'height' => 1664],
  4952. '2:3' => ['width' => 1664, 'height' => 2496],
  4953. '21:9' => ['width' => 3136, 'height' => 1344],
  4954. ],
  4955. '3k' => [
  4956. '1:1' => ['width' => 3072, 'height' => 3072],
  4957. '4:3' => ['width' => 3456, 'height' => 2592],
  4958. '3:4' => ['width' => 2592, 'height' => 3456],
  4959. '16:9' => ['width' => 4096, 'height' => 2304],
  4960. '9:16' => ['width' => 2304, 'height' => 4096],
  4961. '2:3' => ['width' => 2496, 'height' => 3744],
  4962. '3:2' => ['width' => 3744, 'height' => 2496],
  4963. '21:9' => ['width' => 4704, 'height' => 2016],
  4964. ],
  4965. '4k' => [
  4966. '1:1' => ['width' => 4096, 'height' => 4096],
  4967. '3:4' => ['width' => 3520, 'height' => 4704],
  4968. '4:3' => ['width' => 4704, 'height' => 3520],
  4969. '16:9' => ['width' => 5504, 'height' => 3040],
  4970. '9:16' => ['width' => 3040, 'height' => 5504],
  4971. '2:3' => ['width' => 3328, 'height' => 4992],
  4972. '3:2' => ['width' => 4992, 'height' => 3328],
  4973. '21:9' => ['width' => 6240, 'height' => 2656],
  4974. ],
  4975. ];
  4976. // 参数验证
  4977. $resolution = strtolower($resolution);
  4978. if (!isset($sizeMap[$resolution])) {
  4979. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4980. }
  4981. if (!isset($sizeMap[$resolution][$ratio])) {
  4982. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4983. }
  4984. // 根据 ratio 和 resolution 确定宽高
  4985. $width = $sizeMap[$resolution][$ratio]['width'];
  4986. $height = $sizeMap[$resolution][$ratio]['height'];
  4987. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4988. if (is_json($ref_img_urls)) {
  4989. $ref_img_urls = json_decode($ref_img_urls, true);
  4990. }else {
  4991. $ref_img_urls = explode(',', $ref_img_urls);
  4992. }
  4993. }
  4994. // 处理图片模型
  4995. $model = getProp($data, 'model');
  4996. if (!$model) {
  4997. // 用户没有输入,从episode表获取
  4998. if ($episode_id) {
  4999. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5000. $model = getProp($episode, 'image_model');
  5001. }
  5002. if (!$model) {
  5003. // episode表也没有,使用默认值
  5004. $model = 'doubao-seedream-5-0-lite-260128';
  5005. }
  5006. }
  5007. // 验证模型是否在可用模型表中
  5008. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5009. // $model = 'doubao-seedream-5-0-lite-260128';
  5010. Utils::throwError('20003:该模型已不可用,请更换!');
  5011. }
  5012. // 保存到episode表
  5013. if ($episode_id) {
  5014. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5015. 'image_model' => $model,
  5016. 'updated_at' => date('Y-m-d H:i:s')
  5017. ]);
  5018. }
  5019. // 参数验证
  5020. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5021. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5022. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5023. $imageNum = self::getInnerImageNum($inner_prompt_type);
  5024. try {
  5025. // 创建图片生成任务
  5026. $params = [
  5027. 'prompt' => $prompt,
  5028. 'model' => $model,
  5029. 'ref_img_urls' => '',
  5030. 'width' => $width,
  5031. 'height' => $height,
  5032. 'image_num' => $imageNum
  5033. ];
  5034. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5035. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5036. $task_id = $task->id;
  5037. if (!$task_id) {
  5038. Utils::throwError('20003:创建图片生成任务失败');
  5039. }
  5040. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5041. $model = getProp($task, 'model');
  5042. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5043. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5044. $isSyncModel = $isVolcModel || $isGptModel;
  5045. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5046. $start_time = time();
  5047. $timeout = 300; // 5分钟
  5048. $img_url = '';
  5049. while (time() - $start_time < $timeout) {
  5050. sleep(3);
  5051. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5052. if ($isSyncModel) {
  5053. // 刷新任务状态
  5054. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5055. if ($task->status === 'success' && $task->result_url) {
  5056. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  5057. break;
  5058. } elseif ($task->status === 'failed') {
  5059. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5060. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5061. }
  5062. // // 如果还在处理中,提示用户稍后查看
  5063. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5064. }else {
  5065. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5066. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5067. if ($statusInfo['status'] === 'success') {
  5068. $task->updateStatus('success', [
  5069. 'result_url' => $statusInfo['result_url'],
  5070. 'result_json' => $statusInfo['result_json'] ?? []
  5071. ]);
  5072. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  5073. break;
  5074. } elseif ($statusInfo['status'] === 'failed') {
  5075. $task->updateStatus('failed', [
  5076. 'error_message' => $statusInfo['error_message'],
  5077. 'result_json' => $statusInfo['result_json'] ?? []
  5078. ]);
  5079. dLog('anime')->error('图片生成失败,', [
  5080. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5081. ]);
  5082. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5083. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5084. }
  5085. }
  5086. }
  5087. if (empty($img_url)) {
  5088. Utils::throwError('20003:图片生成超时,请稍后重试');
  5089. }
  5090. return $img_url;
  5091. } catch (\Exception $e) {
  5092. dLog('anime')->error('更新角色或场景失败', [
  5093. 'error' => $e->getMessage()
  5094. ]);
  5095. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5096. Utils::throwError('20003:' . $e->getMessage());
  5097. }
  5098. }
  5099. /**
  5100. * 使用文生文模型解析分镜内容
  5101. */
  5102. private function parseSegmentContentWithAI($segment_content) {
  5103. try {
  5104. // 使用DeepSeek服务的公开方法解析分镜内容
  5105. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5106. } catch (\Exception $e) {
  5107. // 如果AI解析失败,记录日志并返回原内容
  5108. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5109. return $segment_content;
  5110. }
  5111. }
  5112. /**
  5113. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5114. *
  5115. * @param int $episode_id 分集ID
  5116. * @param int $anime_id 动漫ID
  5117. * @param array $roles 分集角色数组(引用传递)
  5118. * @param array $scenes 分集场景数组(引用传递)
  5119. * @param array $episode 分集数据
  5120. */
  5121. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5122. // 获取全局动漫的角色和场景数据
  5123. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5124. if (!$anime) return;
  5125. $art_style_type = getProp($anime, 'art_style_type');
  5126. $character_prefix = '';
  5127. $scene_prefix = '';
  5128. if ($art_style_type) {
  5129. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5130. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5131. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5132. }
  5133. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5134. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5135. $roles_updated = false;
  5136. $scenes_updated = false;
  5137. // 处理角色
  5138. foreach ($roles as &$role) {
  5139. $role_name = getProp($role, 'role');
  5140. $role_description = getProp($role, 'description');
  5141. $role_pic_prompt = getProp($role, 'pic_prompt');
  5142. $role_url = getProp($role, 'url');
  5143. $role_task_id = getProp($role, 'task_id');
  5144. // 如果已有URL或已有任务ID,跳过
  5145. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5146. continue;
  5147. }
  5148. $url_inherited = false;
  5149. // 尝试从全局数据中继承
  5150. foreach ($global_roles as $global_role) {
  5151. $global_role_name = getProp($global_role, 'role');
  5152. $global_role_description = getProp($global_role, 'description');
  5153. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5154. $global_role_url = getProp($global_role, 'url');
  5155. $global_role_task_id = getProp($global_role, 'task_id');
  5156. $global_role_task_status = getProp($global_role, 'task_status');
  5157. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5158. if ($role_name === $global_role_name
  5159. && $role_description === $global_role_description
  5160. && $role_pic_prompt === $global_role_pic_prompt
  5161. && !empty($global_role_url)) {
  5162. // 继承 task_id、task_status 和 url
  5163. $role['task_id'] = $global_role_task_id;
  5164. $role['task_status'] = $global_role_task_status;
  5165. $role['url'] = $global_role_url;
  5166. $roles_updated = true;
  5167. $url_inherited = true;
  5168. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5169. break;
  5170. }
  5171. }
  5172. // 如果无法继承且没有任务ID,创建新任务
  5173. if (!$url_inherited && empty($role_task_id)) {
  5174. try {
  5175. $art_style = getProp($episode, 'art_style');
  5176. // 优先使用 pic_prompt,如果没有则使用 description
  5177. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5178. // if ($art_style) {
  5179. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5180. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5181. // }
  5182. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5183. $params = [
  5184. 'prompt' => $description,
  5185. 'ref_img_urls' => []
  5186. ];
  5187. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5188. $task_id = $task->id;
  5189. if ($task_id) {
  5190. $role['task_id'] = $task_id;
  5191. $role['task_status'] = 'processing';
  5192. $roles_updated = true;
  5193. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5194. }
  5195. } catch (\Exception $e) {
  5196. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5197. }
  5198. }
  5199. }
  5200. // 处理场景
  5201. foreach ($scenes as &$scene) {
  5202. $scene_name = getProp($scene, 'scene');
  5203. $scene_description = getProp($scene, 'description');
  5204. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5205. $scene_url = getProp($scene, 'url');
  5206. $scene_task_id = getProp($scene, 'task_id');
  5207. // 如果已有URL或已有任务ID,跳过
  5208. if (!empty($scene_url) || !empty($scene_task_id)) {
  5209. continue;
  5210. }
  5211. $url_inherited = false;
  5212. // 尝试从全局数据中继承
  5213. foreach ($global_scenes as $global_scene) {
  5214. $global_scene_name = getProp($global_scene, 'scene');
  5215. $global_scene_description = getProp($global_scene, 'description');
  5216. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5217. $global_scene_url = getProp($global_scene, 'url');
  5218. $global_scene_task_id = getProp($global_scene, 'task_id');
  5219. $global_scene_task_status = getProp($global_scene, 'task_status');
  5220. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5221. if ($scene_name === $global_scene_name
  5222. && $scene_description === $global_scene_description
  5223. && $scene_pic_prompt === $global_scene_pic_prompt
  5224. && !empty($global_scene_url)) {
  5225. // 继承 task_id、task_status 和 url
  5226. $scene['task_id'] = $global_scene_task_id;
  5227. $scene['task_status'] = $global_scene_task_status;
  5228. $scene['url'] = $global_scene_url;
  5229. $scenes_updated = true;
  5230. $url_inherited = true;
  5231. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5232. break;
  5233. }
  5234. }
  5235. // 如果无法继承且没有任务ID,创建新任务
  5236. if (!$url_inherited && empty($scene_task_id)) {
  5237. try {
  5238. $art_style = getProp($episode, 'art_style');
  5239. // 优先使用 pic_prompt,如果没有则使用 description
  5240. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5241. // if ($art_style) {
  5242. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5243. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5244. // }
  5245. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5246. $params = [
  5247. 'prompt' => $description,
  5248. 'ref_img_urls' => []
  5249. ];
  5250. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5251. $task_id = $task->id;
  5252. if ($task_id) {
  5253. $scene['task_id'] = $task_id;
  5254. $scene['task_status'] = 'processing';
  5255. $scenes_updated = true;
  5256. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5257. }
  5258. } catch (\Exception $e) {
  5259. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5260. }
  5261. }
  5262. }
  5263. // 如果有更新,保存到数据库
  5264. if ($roles_updated || $scenes_updated) {
  5265. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5266. if ($roles_updated) {
  5267. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5268. }
  5269. if ($scenes_updated) {
  5270. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5271. }
  5272. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5273. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5274. }
  5275. }
  5276. /**
  5277. * 根据图片URL使用AI反推图片提示词
  5278. *
  5279. * @param string $img_url 图片URL
  5280. * @return string 反推的提示词
  5281. */
  5282. private function generateImagePromptFromUrl($img_url) {
  5283. try {
  5284. // 获取默认模型
  5285. $model = 'doubao-seed-2-0-mini-260215';
  5286. // 构建messages参数
  5287. $messages = [
  5288. [
  5289. 'role' => 'user',
  5290. 'content' => [
  5291. [
  5292. 'type' => 'text',
  5293. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5294. ],
  5295. [
  5296. 'type' => 'image_url',
  5297. 'image_url' => [
  5298. 'url' => $img_url
  5299. ]
  5300. ]
  5301. ]
  5302. ]
  5303. ];
  5304. // 构建请求参数
  5305. $params = [
  5306. 'model' => $model,
  5307. 'messages' => $messages,
  5308. 'stream' => false,
  5309. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5310. ];
  5311. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5312. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5313. // 返回生成的内容
  5314. return getProp($result, 'fullContent', '图片描述生成失败');
  5315. } catch (\Exception $e) {
  5316. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5317. 'img_url' => $img_url
  5318. ]);
  5319. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5320. 'error' => $e->getMessage(),
  5321. 'img_url' => $img_url
  5322. ]);
  5323. return '图片描述生成失败: ' . $e->getMessage();
  5324. }
  5325. }
  5326. /**
  5327. * 音频试听接口
  5328. * 创建音频任务并轮询获取结果
  5329. *
  5330. * @param array $data 参数数组
  5331. * @return array 返回音频URL或错误信息
  5332. */
  5333. public function previewAudio($data) {
  5334. $dialogue = getProp($data, 'dialogue');
  5335. // 必填参数验证
  5336. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5337. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5338. $voice_type = getProp($data, 'voice_type');
  5339. $voice_name = getProp($data, 'voice_name');
  5340. $voice_actor = getProp($data, 'voice_actor');
  5341. $emotion_type = getProp($data, 'emotion_type');
  5342. $gender = getProp($data, 'gender', 0);
  5343. $emotion = getProp($data, 'emotion');
  5344. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5345. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5346. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5347. $pitch = getProp($data, 'pitch', 0);
  5348. try {
  5349. $now = date('Y-m-d H:i:s');
  5350. // 构建生成参数
  5351. $generate_json = json_encode([
  5352. 'text' => $dialogue,
  5353. 'role' => $voice_actor,
  5354. 'voice_type' => $voice_type,
  5355. 'voice_name' => $voice_name,
  5356. 'emotion' => $emotion,
  5357. 'emotion_type' => $emotion_type,
  5358. 'gender' => $gender,
  5359. 'speed_ratio' => $speed_ratio,
  5360. 'loudness_ratio' => $loudness_ratio,
  5361. 'emotion_scale' => $emotion_scale,
  5362. 'pitch' => $pitch,
  5363. ], 256);
  5364. // 请求远程服务器执行生成
  5365. $client = new Client(['timeout' => 600, 'verify' => false]);
  5366. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5367. $response = $result->getBody()->getContents();
  5368. $response_arr = json_decode($response, true);
  5369. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5370. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5371. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5372. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5373. }
  5374. $arr = $response_arr['data'];
  5375. $subtitle_info = $arr['subtitle_info'];
  5376. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5377. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5378. return [
  5379. 'audio_url' => $arr['url'],
  5380. 'subtitle_info' => $subtitle_info,
  5381. 'audio_duration' => round($audio_duration, 2)
  5382. ];
  5383. } catch (\Exception $e) {
  5384. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5385. Utils::throwError('20003:' . $e->getMessage());
  5386. }
  5387. }
  5388. /**
  5389. * 获取角色库列表(支持文件夹递归查询)
  5390. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5391. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5392. */
  5393. public function globalProducts($data) {
  5394. $uid = Site::getUid();
  5395. $cpid = Site::getCpid();
  5396. $role = Site::getRole();
  5397. $id = getProp($data, 'id', 0);
  5398. $parent_id = getProp($data, 'parent_id', 0);
  5399. $product_name = getProp($data, 'product_name');
  5400. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5401. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5402. if (!$product) {
  5403. Utils::throwError('20003:请选择产品类型');
  5404. }
  5405. // 根据角色和is_public参数确定查询范围
  5406. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5407. // user角色:根据is_public参数筛选
  5408. $query_user_ids = [];
  5409. if ($role === 'admin') {
  5410. // admin获取所有个人库和公共库
  5411. $query_user_ids = [$uid, 0];
  5412. } else {
  5413. // user角色根据is_public参数筛选
  5414. if ($is_public == 2) {
  5415. // 个人库+公共库
  5416. $query_user_ids = [$uid, 0];
  5417. } elseif ($is_public == 0) {
  5418. // 仅个人库
  5419. $query_user_ids = [$uid];
  5420. } elseif ($is_public == 1) {
  5421. // 仅公共库
  5422. $query_user_ids = [0];
  5423. }
  5424. }
  5425. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5426. if ($id || $product_name) {
  5427. $query = DB::table('mp_products')
  5428. ->where('cpid', $cpid)
  5429. ->whereIn('user_id', $query_user_ids)
  5430. ->where('is_deleted', 0);
  5431. // 如果指定了 id,按 id 精确查询
  5432. if ($id) {
  5433. $query->where('id', $id);
  5434. }
  5435. // 如果指定了 product_name,按名称模糊查询
  5436. if ($product_name) {
  5437. $query->where('product_name', 'like', "%{$product_name}%");
  5438. }
  5439. // 如果指定了 product,添加筛选条件
  5440. if ($product) {
  5441. $query->where('product', $product);
  5442. }
  5443. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5444. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5445. ->get()
  5446. ->map(function($value) {
  5447. $value = (array)$value;
  5448. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5449. $value['type'] = (int)$value['type'];
  5450. $value['parent_id'] = (int)$value['parent_id'];
  5451. $value['level'] = (int)$value['level'];
  5452. $value['product'] = (int)($value['product'] ?? 1);
  5453. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5454. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5455. unset($value['user_id']);
  5456. return $value;
  5457. })
  5458. ->toArray();
  5459. return $result;
  5460. }
  5461. // 递归获取所有子目录和角色
  5462. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5463. }
  5464. /**
  5465. * 递归获取指定目录下的所有子目录和角色
  5466. * @param int $cpid 公司ID
  5467. * @param int $parent_id 父目录ID
  5468. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5469. * @param array $query_user_ids 用户ID数组(支持多个)
  5470. * @param int $current_uid 当前用户ID(用于排序)
  5471. * @return array
  5472. */
  5473. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5474. // 查询当前层级的所有项(文件夹和角色)
  5475. $query = DB::table('mp_products')
  5476. ->where('cpid', $cpid)
  5477. ->where('is_deleted', 0)
  5478. ->where('parent_id', $parent_id);
  5479. // 添加用户ID验证(支持多个user_id)
  5480. if (!empty($query_user_ids)) {
  5481. $query->whereIn('user_id', $query_user_ids);
  5482. }
  5483. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5484. if ($product) {
  5485. $query->where('product', $product);
  5486. }
  5487. // 排序规则:
  5488. // 1. 文件夹在前(type DESC)
  5489. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5490. // 3. 其他排序规则
  5491. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5492. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5493. ->get();
  5494. $result = [];
  5495. foreach ($items as $item) {
  5496. $itemArray = [
  5497. 'id' => $item->id,
  5498. 'type' => (int)$item->type,
  5499. 'parent_id' => (int)$item->parent_id,
  5500. 'level' => (int)$item->level,
  5501. 'product_name' => $item->product_name,
  5502. 'url' => $item->url,
  5503. 'pic_prompt' => $item->pic_prompt ?? '',
  5504. 'three_view_image_url' => $item->three_view_image_url,
  5505. 'product' => (int)($item->product ?? 1),
  5506. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5507. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5508. ];
  5509. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5510. // 如果是文件夹,递归获取其子项
  5511. if ($item->type == 2) {
  5512. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5513. if (!empty($children)) {
  5514. $itemArray['children'] = $children;
  5515. }
  5516. }
  5517. $result[] = $itemArray;
  5518. }
  5519. return $result;
  5520. }
  5521. /**
  5522. * 创建文件夹
  5523. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5524. * @return int 返回新建文件夹ID
  5525. */
  5526. public function createFolder($data) {
  5527. $uid = Site::getUid();
  5528. $cpid = Site::getCpid();
  5529. $role = Site::getRole();
  5530. $parent_id = getProp($data, 'parent_id', 0);
  5531. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5532. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5533. // 如果是公共库操作,需要admin权限
  5534. if ($is_public && $role !== 'admin') {
  5535. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5536. }
  5537. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5538. $store_uid = $is_public ? 0 : $uid;
  5539. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5540. $product = getProp($data, 'product');
  5541. if (!in_array($product, [1, 2, 3])) {
  5542. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5543. }
  5544. // 验证父文件夹
  5545. $parent_level = 0;
  5546. if ($parent_id > 0) {
  5547. $parent = DB::table('mp_products')
  5548. ->where('id', $parent_id)
  5549. ->where('cpid', $cpid)
  5550. ->where('user_id', $store_uid)
  5551. ->where('type', 2)
  5552. ->where('is_deleted', 0)
  5553. ->first();
  5554. if (!$parent) {
  5555. Utils::throwError('20003:父文件夹不存在');
  5556. }
  5557. // 检查父文件夹的 product 类型是否一致
  5558. if ($parent->product != $product) {
  5559. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5560. }
  5561. $parent_level = $parent->level;
  5562. // 检查层级限制(最多3层)
  5563. if ($parent_level >= 3) {
  5564. Utils::throwError('20003:文件夹层级不能超过3层');
  5565. }
  5566. }
  5567. // 检查当前目录下是否已存在空白文件夹
  5568. $empty_folder_exists = DB::table('mp_products')
  5569. ->where('parent_id', $parent_id)
  5570. ->where('cpid', $cpid)
  5571. ->where('user_id', $store_uid)
  5572. ->where('type', 2)
  5573. ->where('product', $product)
  5574. ->where('product_name', '新建文件夹')
  5575. ->where('is_deleted', 0)
  5576. ->exists();
  5577. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5578. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5579. }
  5580. // 创建文件夹
  5581. $folder_id = DB::table('mp_products')->insertGetId([
  5582. 'user_id' => $store_uid,
  5583. 'cpid' => $cpid,
  5584. 'type' => 2,
  5585. 'parent_id' => $parent_id,
  5586. 'level' => $parent_level + 1,
  5587. 'product_name' => $folder_name,
  5588. 'product' => $product,
  5589. 'sort_order' => time(), // 使用时间戳作为排序权重
  5590. 'is_deleted' => 0,
  5591. 'created_at' => date('Y-m-d H:i:s'),
  5592. 'updated_at' => date('Y-m-d H:i:s')
  5593. ]);
  5594. return [
  5595. 'id' => $folder_id,
  5596. 'type' => 2,
  5597. 'parent_id' => $parent_id,
  5598. 'level' => $parent_level + 1,
  5599. 'product_name' => $folder_name,
  5600. 'product' => $product,
  5601. ];
  5602. }
  5603. /**
  5604. * 重命名文件夹或角色
  5605. * @param array $data 包含 id、product_name(新名称)
  5606. * @return bool
  5607. */
  5608. public function renameFolder($data) {
  5609. $uid = Site::getUid();
  5610. $cpid = Site::getCpid();
  5611. $role = Site::getRole();
  5612. $id = getProp($data, 'id');
  5613. $new_name = getProp($data, 'product_name');
  5614. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5615. if (!$id || !$new_name) {
  5616. Utils::throwError('20003:参数不完整');
  5617. }
  5618. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5619. $query_uid = $is_public ? 0 : $uid;
  5620. // 如果是公共库操作,需要admin权限
  5621. if ($is_public && $role !== 'admin') {
  5622. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5623. }
  5624. // 检查是否存在
  5625. $item = DB::table('mp_products')
  5626. ->where('id', $id)
  5627. ->where('cpid', $cpid)
  5628. ->where('user_id', $query_uid)
  5629. ->where('is_deleted', 0)
  5630. ->first();
  5631. if (!$item) {
  5632. Utils::throwError('20003:项目不存在');
  5633. }
  5634. return DB::table('mp_products')
  5635. ->where('id', $id)
  5636. ->where('cpid', $cpid)
  5637. ->where('user_id', $query_uid)
  5638. ->update([
  5639. 'product_name' => $new_name,
  5640. 'updated_at' => date('Y-m-d H:i:s')
  5641. ]);
  5642. }
  5643. /**
  5644. * 移动角色或文件夹到指定文件夹
  5645. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5646. * @return bool
  5647. */
  5648. public function moveProductOrFolder($data) {
  5649. $uid = Site::getUid();
  5650. $cpid = Site::getCpid();
  5651. $role = Site::getRole();
  5652. $id = getProp($data, 'id');
  5653. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5654. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5655. if (!$id) {
  5656. Utils::throwError('20003:请选择要移动的项目');
  5657. }
  5658. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5659. $query_uid = $is_public ? 0 : $uid;
  5660. // 如果是公共库操作,需要admin权限
  5661. if ($is_public && $role !== 'admin') {
  5662. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5663. }
  5664. // 检查要移动的项目
  5665. $item = DB::table('mp_products')
  5666. ->where('id', $id)
  5667. ->where('cpid', $cpid)
  5668. ->where('user_id', $query_uid)
  5669. ->where('is_deleted', 0)
  5670. ->first();
  5671. if (!$item) {
  5672. Utils::throwError('20003:项目不存在');
  5673. }
  5674. // 验证目标文件夹
  5675. $target_level = 0;
  5676. $target_product = $item->product; // 默认使用当前项目的 product
  5677. if ($target_parent_id > 0) {
  5678. $target_parent = DB::table('mp_products')
  5679. ->where('id', $target_parent_id)
  5680. ->where('cpid', $cpid)
  5681. ->where('user_id', $query_uid)
  5682. ->where('type', 2)
  5683. ->where('is_deleted', 0)
  5684. ->first();
  5685. if (!$target_parent) {
  5686. Utils::throwError('20003:目标文件夹不存在');
  5687. }
  5688. // 检查 product 类型是否一致
  5689. if ($target_parent->product != $item->product) {
  5690. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5691. }
  5692. $target_level = $target_parent->level;
  5693. $target_product = $target_parent->product;
  5694. // 如果移动的是文件夹,需要检查层级
  5695. if ($item->type == 2) {
  5696. // 计算移动后的最大层级
  5697. $max_child_level = $this->getMaxChildLevel($id);
  5698. $depth = $max_child_level - $item->level;
  5699. if ($target_level + 1 + $depth > 3) {
  5700. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5701. }
  5702. // 不能移动到自己或自己的子文件夹下
  5703. if ($this->isDescendant($target_parent_id, $id)) {
  5704. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5705. }
  5706. }
  5707. }
  5708. // 更新父文件夹和层级
  5709. $new_level = $target_level + 1;
  5710. DB::table('mp_products')
  5711. ->where('id', $id)
  5712. ->update([
  5713. 'parent_id' => $target_parent_id,
  5714. 'level' => $new_level,
  5715. 'updated_at' => date('Y-m-d H:i:s')
  5716. ]);
  5717. // 如果是文件夹,需要递归更新所有子项的层级
  5718. if ($item->type == 2) {
  5719. $this->updateChildrenLevel($id, $new_level);
  5720. }
  5721. return true;
  5722. }
  5723. /**
  5724. * 获取文件夹下最大子层级
  5725. * @param int $folder_id
  5726. * @return int
  5727. */
  5728. private function getMaxChildLevel($folder_id) {
  5729. $max_level = DB::table('mp_products')
  5730. ->where('parent_id', $folder_id)
  5731. ->where('is_deleted', 0)
  5732. ->max('level');
  5733. if (!$max_level) {
  5734. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5735. }
  5736. // 递归查找子文件夹
  5737. $children = DB::table('mp_products')
  5738. ->where('parent_id', $folder_id)
  5739. ->where('type', 2)
  5740. ->where('is_deleted', 0)
  5741. ->pluck('id');
  5742. foreach ($children as $child_id) {
  5743. $child_max = $this->getMaxChildLevel($child_id);
  5744. if ($child_max > $max_level) {
  5745. $max_level = $child_max;
  5746. }
  5747. }
  5748. return $max_level;
  5749. }
  5750. /**
  5751. * 检查 target_id 是否是 folder_id 的后代
  5752. * @param int $target_id
  5753. * @param int $folder_id
  5754. * @return bool
  5755. */
  5756. private function isDescendant($target_id, $folder_id) {
  5757. if ($target_id == $folder_id) {
  5758. return true;
  5759. }
  5760. $parent = DB::table('mp_products')
  5761. ->where('id', $target_id)
  5762. ->where('is_deleted', 0)
  5763. ->first();
  5764. if (!$parent || $parent->parent_id == 0) {
  5765. return false;
  5766. }
  5767. return $this->isDescendant($parent->parent_id, $folder_id);
  5768. }
  5769. /**
  5770. * 递归更新子项层级
  5771. * @param int $parent_id
  5772. * @param int $parent_level
  5773. */
  5774. private function updateChildrenLevel($parent_id, $parent_level) {
  5775. $children = DB::table('mp_products')
  5776. ->where('parent_id', $parent_id)
  5777. ->where('is_deleted', 0)
  5778. ->get();
  5779. foreach ($children as $child) {
  5780. $new_level = $parent_level + 1;
  5781. DB::table('mp_products')
  5782. ->where('id', $child->id)
  5783. ->update([
  5784. 'level' => $new_level,
  5785. 'updated_at' => date('Y-m-d H:i:s')
  5786. ]);
  5787. // 如果是文件夹,继续递归
  5788. if ($child->type == 2) {
  5789. $this->updateChildrenLevel($child->id, $new_level);
  5790. }
  5791. }
  5792. }
  5793. /**
  5794. * 获取文件夹路径(面包屑导航)
  5795. * @param array $data 包含 folder_id
  5796. * @return array 返回路径数组
  5797. */
  5798. public function getFolderPath($data) {
  5799. $uid = Site::getUid();
  5800. $cpid = Site::getCpid();
  5801. $folder_id = getProp($data, 'id', 0);
  5802. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5803. if ($folder_id == 0) {
  5804. return [
  5805. ['id' => 0, 'name' => '根目录']
  5806. ];
  5807. }
  5808. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5809. $query_uid = $is_public ? 0 : $uid;
  5810. $path = [];
  5811. $current_id = $folder_id;
  5812. while ($current_id > 0) {
  5813. $folder = DB::table('mp_products')
  5814. ->where('id', $current_id)
  5815. ->where('cpid', $cpid)
  5816. ->where('user_id', $query_uid)
  5817. ->where('type', 2)
  5818. ->where('is_deleted', 0)
  5819. ->first();
  5820. if (!$folder) {
  5821. break;
  5822. }
  5823. array_unshift($path, [
  5824. 'id' => $folder->id,
  5825. 'name' => $folder->product_name
  5826. ]);
  5827. $current_id = $folder->parent_id;
  5828. }
  5829. // 添加根目录
  5830. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5831. return $path;
  5832. }
  5833. public function createProduct($data) {
  5834. $uid = Site::getUid();
  5835. $cpid = Site::getCpid();
  5836. $role = Site::getRole();
  5837. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5838. // 如果是公共库操作,需要admin权限
  5839. if ($is_public && $role !== 'admin') {
  5840. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5841. }
  5842. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5843. $store_uid = $is_public ? 0 : $uid;
  5844. $product_name = trim(getProp($data, 'product_name'));
  5845. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5846. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5847. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5848. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5849. $url = trim(getProp($data, 'url'));
  5850. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5851. $versions = getProp($data, 'versions');
  5852. // 检查是否是正确的图片格式
  5853. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5854. $urlPath = parse_url($url, PHP_URL_PATH);
  5855. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5856. if (!in_array($extension, $allowedExtensions)) {
  5857. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5858. }
  5859. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5860. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5861. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5862. $product = getProp($data, 'product');
  5863. if (!in_array($product, [1, 2, 3])) {
  5864. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5865. }
  5866. // 获取父文件夹ID和层级
  5867. $parent_id = getProp($data, 'parent_id', 0);
  5868. $parent_level = 0;
  5869. if ($parent_id > 0) {
  5870. $parent = DB::table('mp_products')
  5871. ->where('id', $parent_id)
  5872. ->where('cpid', $cpid)
  5873. ->where('user_id', $store_uid)
  5874. ->where('type', 2)
  5875. ->where('is_deleted', 0)
  5876. ->first();
  5877. if (!$parent) {
  5878. Utils::throwError('20003:父文件夹不存在');
  5879. }
  5880. $parent_level = $parent->level;
  5881. }
  5882. $id = DB::table('mp_products')->insertGetId([
  5883. 'user_id' => $store_uid,
  5884. 'cpid' => $cpid,
  5885. 'type' => 1, // 1=角色图片
  5886. 'parent_id' => $parent_id,
  5887. 'level' => $parent_level + 1,
  5888. 'product_name' => $product_name,
  5889. 'url' => $url,
  5890. 'pic_prompt' => $pic_prompt,
  5891. 'product' => $product,
  5892. 'versions' => json_encode($versions, 256),
  5893. 'sort_order' => time(), // 使用时间戳作为排序权重
  5894. 'created_at' => date('Y-m-d H:i:s'),
  5895. 'updated_at' => date('Y-m-d H:i:s')
  5896. ]);
  5897. if (!$id) Utils::throwError('20003:创建失败');
  5898. return [
  5899. 'id' => $id,
  5900. 'type' => 1,
  5901. 'parent_id' => $parent_id,
  5902. 'level' => $parent_level + 1,
  5903. 'product_name' => $product_name,
  5904. 'url' => $url,
  5905. 'pic_prompt' => $pic_prompt,
  5906. 'product' => $product,
  5907. 'versions' => $versions
  5908. ];
  5909. }
  5910. public function editProduct($data) {
  5911. $uid = Site::getUid();
  5912. $cpid = Site::getCpid();
  5913. $role = Site::getRole();
  5914. $id = getProp($data, 'id');
  5915. if (!$id) Utils::throwError('20003:ID不能为空');
  5916. $versions = getProp($data, 'versions');
  5917. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5918. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5919. $query_uid = $is_public ? 0 : $uid;
  5920. // 如果是公共库操作,需要admin权限
  5921. if ($is_public && $role !== 'admin') {
  5922. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5923. }
  5924. // 检查是否存在且属于当前用户或公共库
  5925. $role = DB::table('mp_products')
  5926. ->where('id', $id)
  5927. ->where('cpid', $cpid)
  5928. ->where('user_id', $query_uid)
  5929. ->where('type', 1)->first();
  5930. if (!$role) Utils::throwError('20003:记录不存在');
  5931. $updateData = [];
  5932. // $needVersionRecord = false; // 是否需要记录版本
  5933. // 名称
  5934. $product_name = trim(getProp($data, 'product_name'));
  5935. if ($product_name) {
  5936. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5937. $updateData['product_name'] = $product_name;
  5938. }
  5939. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5940. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5941. // 图片地址
  5942. $url = trim(getProp($data, 'url'));
  5943. if ($url) {
  5944. // 检查是否是正确的图片格式
  5945. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5946. $urlPath = parse_url($url, PHP_URL_PATH);
  5947. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5948. if (!in_array($extension, $allowedExtensions)) {
  5949. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5950. }
  5951. // // 如果 url 有变更,记录版本
  5952. // if ($url !== $role->url) {
  5953. // $needVersionRecord = true;
  5954. // }
  5955. $updateData['url'] = $url;
  5956. }
  5957. // 提示词
  5958. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5959. if ($pic_prompt) {
  5960. // // 如果 pic_prompt 有变更,记录版本
  5961. // if ($pic_prompt !== $role->pic_prompt) {
  5962. // $needVersionRecord = true;
  5963. // }
  5964. $updateData['pic_prompt'] = $pic_prompt;
  5965. }
  5966. if (empty($updateData)) {
  5967. Utils::throwError('20003:没有需要更新的数据');
  5968. }
  5969. // // 如果需要记录版本,将数据添加到 versions 数组
  5970. // if ($needVersionRecord) {
  5971. // // 获取现有的 versions 数据
  5972. // $versions = json_decode($role->versions, true) ?: [];
  5973. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5974. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5975. // if ($isFirstVersion) {
  5976. // $oldVersion = [
  5977. // 'url' => $role->url,
  5978. // 'description' => $role->pic_prompt,
  5979. // ];
  5980. // // 旧版本添加到数组末尾
  5981. // $versions[] = $oldVersion;
  5982. // }
  5983. // // 构建新版本(变更后)
  5984. // $newVersion = [
  5985. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5986. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5987. // ];
  5988. // // 检查新版本是否已存在于历史版本中
  5989. // $existingIndex = -1;
  5990. // foreach ($versions as $index => $version) {
  5991. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5992. // $existingIndex = $index;
  5993. // break;
  5994. // }
  5995. // }
  5996. // if ($existingIndex !== -1) {
  5997. // // 如果已存在,移除旧的位置
  5998. // array_splice($versions, $existingIndex, 1);
  5999. // }
  6000. // // 新版本添加到数组开头(最新的在前)
  6001. // array_unshift($versions, $newVersion);
  6002. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6003. // // if (count($versions) > 10) {
  6004. // // $versions = array_slice($versions, 0, 10);
  6005. // // }
  6006. // $updateData['versions'] = json_encode($versions, 256);
  6007. // }
  6008. if ($versions) {
  6009. $updateData['versions'] = json_encode($versions, 256);
  6010. }
  6011. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6012. return DB::table('mp_products')
  6013. ->where('cpid', $cpid)
  6014. ->where('id', $id)->update($updateData);
  6015. }
  6016. /**
  6017. * 获取角色版本历史
  6018. * @param array $data 包含 id(角色ID)
  6019. * @return array 返回版本历史列表
  6020. */
  6021. public function getProductVersions($data) {
  6022. $cpid = Site::getCpid();
  6023. $id = getProp($data, 'id');
  6024. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6025. $role = DB::table('mp_products')
  6026. ->where('id', $id)
  6027. ->where('cpid', $cpid)
  6028. ->where('type', 1)
  6029. ->first();
  6030. if (!$role) Utils::throwError('20003:角色不存在');
  6031. // 获取版本历史
  6032. $versions = json_decode($role->versions, true) ?: [];
  6033. // 添加当前版本作为最新版本
  6034. $currentVersion = [
  6035. 'version' => 0, // 0 表示当前版本
  6036. 'url' => $role->url,
  6037. 'pic_prompt' => $role->pic_prompt,
  6038. 'updated_at' => $role->updated_at,
  6039. 'is_current' => true
  6040. ];
  6041. array_unshift($versions, $currentVersion);
  6042. return $versions;
  6043. }
  6044. /**
  6045. * 恢复到指定版本
  6046. * @param array $data 包含 id(角色ID)、version(版本号)
  6047. * @return bool
  6048. */
  6049. public function restoreProductVersion($data) {
  6050. $uid = Site::getUid();
  6051. $cpid = Site::getCpid();
  6052. $id = getProp($data, 'id');
  6053. $version = getProp($data, 'version');
  6054. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6055. if (!$version) Utils::throwError('20003:版本号不能为空');
  6056. $role = DB::table('mp_products')
  6057. ->where('id', $id)
  6058. ->where('cpid', $cpid)
  6059. ->where('type', 1)
  6060. ->first();
  6061. if (!$role) Utils::throwError('20003:角色不存在');
  6062. // 获取版本历史
  6063. $versions = json_decode($role->versions, true) ?: [];
  6064. // 查找指定版本
  6065. $targetVersion = null;
  6066. foreach ($versions as $v) {
  6067. if ($v['version'] == $version) {
  6068. $targetVersion = $v;
  6069. break;
  6070. }
  6071. }
  6072. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6073. // 先将当前版本保存到历史
  6074. $newVersion = [
  6075. 'version' => count($versions) + 1,
  6076. 'url' => $role->url,
  6077. 'pic_prompt' => $role->pic_prompt,
  6078. 'updated_at' => date('Y-m-d H:i:s'),
  6079. 'updated_by' => $uid
  6080. ];
  6081. array_unshift($versions, $newVersion);
  6082. // 限制版本数量
  6083. if (count($versions) > 10) {
  6084. $versions = array_slice($versions, 0, 10);
  6085. }
  6086. // 恢复到指定版本
  6087. return DB::table('mp_products')
  6088. ->where('id', $id)
  6089. ->where('cpid', $cpid)
  6090. ->update([
  6091. 'url' => $targetVersion['url'],
  6092. 'pic_prompt' => $targetVersion['pic_prompt'],
  6093. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6094. 'updated_at' => date('Y-m-d H:i:s')
  6095. ]);
  6096. }
  6097. public function deleteProduct($data) {
  6098. $uid = Site::getUid();
  6099. $cpid = Site::getCpid();
  6100. $role = Site::getRole();
  6101. $id = getProp($data, 'id');
  6102. if (!$id) Utils::throwError('20003:ID不能为空');
  6103. $ids = explode(',', $id);
  6104. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6105. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6106. $query_uid = $is_public ? 0 : $uid;
  6107. // 如果是公共库操作,需要admin权限
  6108. if ($is_public && $role !== 'admin') {
  6109. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6110. }
  6111. // 检查是否存在且属于当前用户或公共库
  6112. $role = DB::table('mp_products')
  6113. ->whereIn('id', $ids)
  6114. ->where('cpid', $cpid)
  6115. ->where('user_id', $query_uid)
  6116. ->get();
  6117. if (!$role) Utils::throwError('20003:记录不存在');
  6118. return DB::table('mp_products')
  6119. ->where('cpid', $cpid)
  6120. ->where('user_id', $query_uid)
  6121. ->whereIn('id', $ids)
  6122. ->update([
  6123. 'is_deleted' => 1,
  6124. 'updated_at' => date('Y-m-d H:i:s')
  6125. ]);
  6126. }
  6127. public function generateThreeView($data) {
  6128. $uid = Site::getUid();
  6129. $cpid = Site::getCpid();
  6130. $role = Site::getRole();
  6131. $id = getProp($data, 'id');
  6132. if (!$id) Utils::throwError('20003:ID不能为空');
  6133. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6134. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6135. $query_uid = $is_public ? 0 : $uid;
  6136. // 如果是公共库操作,需要admin权限
  6137. if ($is_public && $role !== 'admin') {
  6138. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6139. }
  6140. // 检查是否存在且属于当前用户或公共库
  6141. $product = DB::table('mp_products')
  6142. ->where('id', $id)
  6143. ->where('cpid', $cpid)
  6144. ->where('user_id', $query_uid)
  6145. ->where('type', 1)->first();
  6146. if (!$product) Utils::throwError('20003:资产不存在');
  6147. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6148. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6149. if (!$ref_img_url) {
  6150. // 如果没有传入参考图,使用角色表中的图片
  6151. $ref_img_url = $product->url ?? '';
  6152. if (!$ref_img_url) {
  6153. Utils::throwError('20003:参考图不能为空');
  6154. }
  6155. }
  6156. $pic_prompt = getProp($product, 'pic_prompt');
  6157. if ($pic_prompt) {
  6158. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6159. }
  6160. // 检查参考图是否是正确的图片格式
  6161. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6162. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6163. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6164. if (!in_array($extension, $allowedExtensions)) {
  6165. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6166. }
  6167. // 处理图片模型
  6168. $model = getProp($data, 'model');
  6169. if (!$model) {
  6170. // 使用默认模型
  6171. $model = 'doubao-seedream-5-0-lite-260128';
  6172. }
  6173. // 验证模型是否在可用模型表中
  6174. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6175. Utils::throwError('20003:该模型已不可用,请更换!');
  6176. }
  6177. $ratio = getProp($data, 'ratio', '16:9');
  6178. $resolution = getProp($data, 'resolution', '2k');
  6179. // 定义分辨率和宽高比对应的尺寸映射表
  6180. $sizeMap = [
  6181. '2k' => [
  6182. '1:1' => ['width' => 2048, 'height' => 2048],
  6183. '4:3' => ['width' => 2304, 'height' => 1728],
  6184. '3:4' => ['width' => 1728, 'height' => 2304],
  6185. '16:9' => ['width' => 2848, 'height' => 1600],
  6186. '9:16' => ['width' => 1600, 'height' => 2848],
  6187. '3:2' => ['width' => 2496, 'height' => 1664],
  6188. '2:3' => ['width' => 1664, 'height' => 2496],
  6189. '21:9' => ['width' => 3136, 'height' => 1344],
  6190. ],
  6191. '3k' => [
  6192. '1:1' => ['width' => 3072, 'height' => 3072],
  6193. '4:3' => ['width' => 3456, 'height' => 2592],
  6194. '3:4' => ['width' => 2592, 'height' => 3456],
  6195. '16:9' => ['width' => 4096, 'height' => 2304],
  6196. '9:16' => ['width' => 2304, 'height' => 4096],
  6197. '2:3' => ['width' => 2496, 'height' => 3744],
  6198. '3:2' => ['width' => 3744, 'height' => 2496],
  6199. '21:9' => ['width' => 4704, 'height' => 2016],
  6200. ],
  6201. '4k' => [
  6202. '1:1' => ['width' => 4096, 'height' => 4096],
  6203. '3:4' => ['width' => 3520, 'height' => 4704],
  6204. '4:3' => ['width' => 4704, 'height' => 3520],
  6205. '16:9' => ['width' => 5504, 'height' => 3040],
  6206. '9:16' => ['width' => 3040, 'height' => 5504],
  6207. '2:3' => ['width' => 3328, 'height' => 4992],
  6208. '3:2' => ['width' => 4992, 'height' => 3328],
  6209. '21:9' => ['width' => 6240, 'height' => 2656],
  6210. ],
  6211. ];
  6212. // 参数验证
  6213. $resolution = strtolower($resolution);
  6214. if (!isset($sizeMap[$resolution])) {
  6215. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6216. }
  6217. if (!isset($sizeMap[$resolution][$ratio])) {
  6218. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6219. }
  6220. // 根据 ratio 和 resolution 确定宽高
  6221. $width = $sizeMap[$resolution][$ratio]['width'];
  6222. $height = $sizeMap[$resolution][$ratio]['height'];
  6223. try {
  6224. // 创建图片生成任务
  6225. $params = [
  6226. 'prompt' => $prompt,
  6227. 'model' => $model,
  6228. 'ref_img_urls' => [$ref_img_url],
  6229. 'width' => $width,
  6230. 'height' => $height
  6231. ];
  6232. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6233. $task_id = $task->id;
  6234. if (!$task_id) {
  6235. Utils::throwError('20003:创建图片生成任务失败');
  6236. }
  6237. // 轮询获取结果
  6238. // 只查询数据库,不调用API,不更新任务表
  6239. $start_time = time();
  6240. $timeout = 1800;
  6241. $img_url = '';
  6242. while (time() - $start_time < $timeout) {
  6243. sleep(5);
  6244. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6245. $task = DB::table('mp_generate_pic_tasks')
  6246. ->where('id', $task_id)
  6247. ->first();
  6248. if (!$task) {
  6249. Utils::throwError('20003:任务不存在');
  6250. }
  6251. if ($task->status === 'success' && $task->result_url) {
  6252. $result_urls = is_string($task->result_url)
  6253. ? json_decode($task->result_url, true)
  6254. : $task->result_url;
  6255. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6256. break;
  6257. } elseif ($task->status === 'failed') {
  6258. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6259. }
  6260. // 其他状态继续轮询
  6261. }
  6262. if (empty($img_url)) {
  6263. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6264. }
  6265. // 更新 mp_products 表(不是任务表)
  6266. DB::table('mp_products')
  6267. ->where('id', $id)
  6268. ->where('cpid', $cpid)
  6269. ->update([
  6270. 'three_view_image_url' => $img_url,
  6271. 'updated_at' => date('Y-m-d H:i:s')
  6272. ]);
  6273. return ['three_view_image_url' => $img_url];
  6274. } catch (\Exception $e) {
  6275. dLog('anime')->error('生成三视图失败', [
  6276. 'error' => $e->getMessage()
  6277. ]);
  6278. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6279. Utils::throwError('20003:' . $e->getMessage());
  6280. }
  6281. }
  6282. /**
  6283. * 推送(复制)资产或文件夹到目标位置
  6284. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6285. * @return array 返回推送结果
  6286. */
  6287. public function pushProductOrFolder($data) {
  6288. $uid = Site::getUid();
  6289. $cpid = Site::getCpid();
  6290. $role = Site::getRole();
  6291. $product_id = getProp($data, 'product_id');
  6292. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6293. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6294. if (!$product_id) {
  6295. Utils::throwError('20003:请选择要推送的项目');
  6296. }
  6297. // 查询源项目(只通过cpid查询,不限制user_id)
  6298. $sourceItem = DB::table('mp_products')
  6299. ->where('id', $product_id)
  6300. ->where('cpid', $cpid)
  6301. ->where('is_deleted', 0)
  6302. ->first();
  6303. if (!$sourceItem) {
  6304. Utils::throwError('20003:要推送的项目不存在');
  6305. }
  6306. // 通过user_id判断源是公共库还是个人库
  6307. $source_uid = $sourceItem->user_id;
  6308. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6309. // 验证目标文件夹并确定目标是公共库还是个人库
  6310. $target_level = 0;
  6311. $target_uid = $uid; // 默认推送到个人库
  6312. $target_is_public = 0;
  6313. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6314. if ($target_parent_id > 0) {
  6315. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6316. $targetParent = DB::table('mp_products')
  6317. ->where('id', $target_parent_id)
  6318. ->where('cpid', $cpid)
  6319. ->where('type', 2)
  6320. ->where('is_deleted', 0)
  6321. ->first();
  6322. if (!$targetParent) {
  6323. Utils::throwError('20003:目标文件夹不存在');
  6324. }
  6325. // 通过user_id判断目标是公共库还是个人库
  6326. $target_level = $targetParent->level;
  6327. $target_uid = $targetParent->user_id;
  6328. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6329. // 使用目标文件夹的 product 类型
  6330. $final_product_type = $targetParent->product;
  6331. }
  6332. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6333. else {
  6334. $push_to_public = getProp($data, 'push_to_public');
  6335. if ($push_to_public === '') {
  6336. Utils::throwError('20003:请选择是否推送到公共库');
  6337. }
  6338. if ($push_to_public) {
  6339. $target_uid = 0;
  6340. $target_is_public = 1;
  6341. }
  6342. // 推送到根目录时,必须指定 product 类型
  6343. if ($target_product === null || $target_product === '') {
  6344. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6345. }
  6346. $final_product_type = $target_product;
  6347. }
  6348. // 如果目标是公共库,需要admin权限
  6349. if ($target_is_public && $role !== 'admin') {
  6350. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6351. }
  6352. // 权限验证:验证是否符合允许的推送规则
  6353. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6354. try {
  6355. DB::beginTransaction();
  6356. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6357. if ($sourceItem->type == 1) {
  6358. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6359. DB::commit();
  6360. return [
  6361. 'product_id' => $newId,
  6362. ];
  6363. }
  6364. // 如果是文件夹,递归复制(支持跨类型推送)
  6365. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6366. DB::commit();
  6367. return [
  6368. 'product_id' => $newFolderId,
  6369. ];
  6370. } catch (\Exception $e) {
  6371. DB::rollBack();
  6372. dLog('anime')->error('推送失败', [
  6373. 'error' => $e->getMessage(),
  6374. 'product_id' => $product_id
  6375. ]);
  6376. Utils::throwError('20003:' . $e->getMessage());
  6377. }
  6378. }
  6379. /**
  6380. * 验证推送权限
  6381. * 允许的推送规则:
  6382. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6383. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6384. * 3. 公共库推送给公共库(公共库 → 公共库)
  6385. *
  6386. * @param int $source_uid 源的user_id
  6387. * @param int $target_uid 目标的user_id
  6388. * @param int $current_uid 当前用户ID
  6389. * @throws \Exception
  6390. */
  6391. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6392. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6393. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6394. return; // 允许
  6395. }
  6396. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6397. if ($source_uid == 0 && $target_uid == $current_uid) {
  6398. return; // 允许
  6399. }
  6400. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6401. if ($source_uid == 0 && $target_uid == 0) {
  6402. return; // 允许
  6403. }
  6404. // 其他情况都不允许
  6405. if ($source_uid != 0 && $source_uid != $current_uid) {
  6406. // 源是别人的个人库
  6407. Utils::throwError('20003:无权限访问该资产');
  6408. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6409. // 个人库推送给公共库(不允许)
  6410. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6411. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6412. // 不同用户的个人库之间推送(不允许)
  6413. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6414. } else {
  6415. // 其他未知情况
  6416. Utils::throwError('20003:不允许的推送操作');
  6417. }
  6418. }
  6419. /**
  6420. * 复制单个资产
  6421. * @param object $sourceProduct 源资产对象
  6422. * @param int $targetParentId 目标父文件夹ID
  6423. * @param int $targetLevel 目标层级
  6424. * @param int $cpid 公司ID
  6425. * @param int $targetUid 目标用户ID
  6426. * @return int 返回新资产ID
  6427. */
  6428. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6429. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6430. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6431. $newProductData = [
  6432. 'user_id' => $targetUid,
  6433. 'cpid' => $cpid,
  6434. 'type' => 1,
  6435. 'parent_id' => $targetParentId,
  6436. 'level' => $targetLevel,
  6437. 'product_name' => $sourceProduct->product_name,
  6438. 'url' => $sourceProduct->url,
  6439. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6440. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6441. 'product' => $finalProductType,
  6442. 'versions' => $sourceProduct->versions ?? '',
  6443. 'sort_order' => time(),
  6444. 'is_deleted' => 0,
  6445. 'created_at' => date('Y-m-d H:i:s'),
  6446. 'updated_at' => date('Y-m-d H:i:s')
  6447. ];
  6448. return DB::table('mp_products')->insertGetId($newProductData);
  6449. }
  6450. /**
  6451. * 递归复制文件夹及其子项
  6452. * @param object $sourceFolder 源文件夹对象
  6453. * @param int $targetParentId 目标父文件夹ID
  6454. * @param int $targetLevel 目标层级
  6455. * @param int $cpid 公司ID
  6456. * @param int $targetUid 目标用户ID
  6457. * @param int $sourceUid 源用户ID
  6458. * @return int 返回新文件夹ID
  6459. */
  6460. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6461. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6462. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6463. // 创建新文件夹
  6464. $newFolderData = [
  6465. 'user_id' => $targetUid,
  6466. 'cpid' => $cpid,
  6467. 'type' => 2,
  6468. 'parent_id' => $targetParentId,
  6469. 'level' => $targetLevel,
  6470. 'product_name' => $sourceFolder->product_name,
  6471. 'product' => $finalProductType,
  6472. 'sort_order' => time(),
  6473. 'is_deleted' => 0,
  6474. 'created_at' => date('Y-m-d H:i:s'),
  6475. 'updated_at' => date('Y-m-d H:i:s')
  6476. ];
  6477. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6478. // 获取源文件夹下的所有子项
  6479. $children = DB::table('mp_products')
  6480. ->where('parent_id', $sourceFolder->id)
  6481. ->where('cpid', $cpid)
  6482. ->where('user_id', $sourceUid)
  6483. ->where('is_deleted', 0)
  6484. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6485. ->get();
  6486. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6487. foreach ($children as $child) {
  6488. if ($child->type == 1) {
  6489. // 资产
  6490. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6491. } else {
  6492. // 文件夹
  6493. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6494. }
  6495. }
  6496. return $newFolderId;
  6497. }
  6498. /**
  6499. * 保存剧本资产关联关系
  6500. * @param array $data 请求参数
  6501. * @return bool
  6502. */
  6503. public function saveScriptProducts($data) {
  6504. $uid = Site::getUid();
  6505. $cpid = Site::getCpid();
  6506. $script_id = getProp($data, 'script_id');
  6507. $products = getProp($data, 'products', []);
  6508. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6509. if (!$script_id) {
  6510. Utils::throwError('20003:请提供剧本ID');
  6511. }
  6512. // 验证剧本是否存在
  6513. $script = DB::table('mp_scripts')
  6514. ->where('id', $script_id)
  6515. ->where('is_deleted', 0)
  6516. ->first();
  6517. if (!$script) {
  6518. Utils::throwError('20003:剧本不存在');
  6519. }
  6520. // 处理图片模型
  6521. $model = getProp($data, 'model');
  6522. if (!$model) {
  6523. // 使用默认模型
  6524. $model = 'doubao-seedream-5-0-lite-260128';
  6525. }
  6526. // 验证模型是否在可用模型表中
  6527. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6528. Utils::throwError('20003:该模型已不可用,请更换!');
  6529. }
  6530. $ratio = getProp($data, 'ratio', '9:16');
  6531. $resolution = getProp($data, 'resolution', '2k');
  6532. // 定义分辨率和宽高比对应的尺寸映射表
  6533. $sizeMap = [
  6534. '2k' => [
  6535. '1:1' => ['width' => 2048, 'height' => 2048],
  6536. '4:3' => ['width' => 2304, 'height' => 1728],
  6537. '3:4' => ['width' => 1728, 'height' => 2304],
  6538. '16:9' => ['width' => 2848, 'height' => 1600],
  6539. '9:16' => ['width' => 1600, 'height' => 2848],
  6540. '3:2' => ['width' => 2496, 'height' => 1664],
  6541. '2:3' => ['width' => 1664, 'height' => 2496],
  6542. '21:9' => ['width' => 3136, 'height' => 1344],
  6543. ],
  6544. '3k' => [
  6545. '1:1' => ['width' => 3072, 'height' => 3072],
  6546. '4:3' => ['width' => 3456, 'height' => 2592],
  6547. '3:4' => ['width' => 2592, 'height' => 3456],
  6548. '16:9' => ['width' => 4096, 'height' => 2304],
  6549. '9:16' => ['width' => 2304, 'height' => 4096],
  6550. '2:3' => ['width' => 2496, 'height' => 3744],
  6551. '3:2' => ['width' => 3744, 'height' => 2496],
  6552. '21:9' => ['width' => 4704, 'height' => 2016],
  6553. ],
  6554. '4k' => [
  6555. '1:1' => ['width' => 4096, 'height' => 4096],
  6556. '3:4' => ['width' => 3520, 'height' => 4704],
  6557. '4:3' => ['width' => 4704, 'height' => 3520],
  6558. '16:9' => ['width' => 5504, 'height' => 3040],
  6559. '9:16' => ['width' => 3040, 'height' => 5504],
  6560. '2:3' => ['width' => 3328, 'height' => 4992],
  6561. '3:2' => ['width' => 4992, 'height' => 3328],
  6562. '21:9' => ['width' => 6240, 'height' => 2656],
  6563. ],
  6564. ];
  6565. // 参数验证
  6566. $resolution = strtolower($resolution);
  6567. if (!isset($sizeMap[$resolution])) {
  6568. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6569. }
  6570. if (!isset($sizeMap[$resolution][$ratio])) {
  6571. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6572. }
  6573. // 根据 ratio 和 resolution 确定宽高
  6574. $width = $sizeMap[$resolution][$ratio]['width'];
  6575. $height = $sizeMap[$resolution][$ratio]['height'];
  6576. $script_name = $script->script_name ?? 'script_' . $script_id;
  6577. // 检查是否已经有该剧本的资产数据
  6578. $existingMappings = DB::table('mp_script_product_mappings')
  6579. ->where('script_id', $script_id)
  6580. ->get();
  6581. if ($existingMappings->isNotEmpty()) {
  6582. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6583. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6584. // 查询这些资产的图片生成任务状态
  6585. $productsWithTasks = DB::table('mp_products')
  6586. ->whereIn('id', $productIds)
  6587. ->where('is_deleted', 0)
  6588. ->get();
  6589. $productTaskMap = [];
  6590. $typeFolderIds = [];
  6591. $hasAllTasks = true;
  6592. foreach ($productsWithTasks as $product) {
  6593. // 收集类型文件夹ID
  6594. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6595. $parentFolder = DB::table('mp_products')
  6596. ->where('id', $product->parent_id)
  6597. ->where('type', 2)
  6598. ->first();
  6599. if ($parentFolder) {
  6600. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6601. }
  6602. }
  6603. // 检查是否有图片生成任务
  6604. if (!empty($product->pic_task_id)) {
  6605. $productTaskMap[$product->id] = $product->pic_task_id;
  6606. } else if($product->url && $product->pic_task_status == '生成成功') {
  6607. continue;
  6608. } else {
  6609. // 有资产没有图片任务
  6610. $hasAllTasks = false;
  6611. }
  6612. }
  6613. // 如果所有资产都有任务ID,直接轮询返回结果
  6614. if ($hasAllTasks && !empty($productTaskMap)) {
  6615. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6616. 'script_id' => $script_id,
  6617. 'script_name' => $script_name,
  6618. 'product_count' => count($productTaskMap)
  6619. ]);
  6620. // 直接返回 SSE 流轮询结果
  6621. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6622. }
  6623. // 如果部分资产没有任务ID,只为这些资产创建任务
  6624. if (!$hasAllTasks && $auto_generate_images) {
  6625. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6626. 'script_id' => $script_id,
  6627. 'script_name' => $script_name
  6628. ]);
  6629. // 开启事务
  6630. DB::beginTransaction();
  6631. try {
  6632. foreach ($productsWithTasks as $product) {
  6633. // 跳过已有任务的资产
  6634. if (!empty($product->pic_task_id)) {
  6635. continue;
  6636. }
  6637. // 跳过没有提示词的资产
  6638. if (empty($product->pic_prompt)) {
  6639. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6640. 'product_id' => $product->id,
  6641. 'product_name' => $product->product_name
  6642. ]);
  6643. continue;
  6644. }
  6645. try {
  6646. // 创建图片生成任务
  6647. $params = [
  6648. 'prompt' => $product->pic_prompt,
  6649. 'model' => $model,
  6650. 'ref_img_urls' => [],
  6651. 'width' => $width,
  6652. 'height' => $height
  6653. ];
  6654. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6655. $task_id = $task->id;
  6656. if ($task_id) {
  6657. $productTaskMap[$product->id] = $task_id;
  6658. // 在事务中更新资产表的任务ID和状态
  6659. DB::table('mp_products')
  6660. ->where('id', $product->id)
  6661. ->update([
  6662. 'pic_task_id' => $task_id,
  6663. 'pic_task_status' => '生成中',
  6664. 'updated_at' => now()
  6665. ]);
  6666. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6667. 'product_id' => $product->id,
  6668. 'task_id' => $task_id
  6669. ]);
  6670. }
  6671. } catch (\Exception $e) {
  6672. dLog('anime')->error('创建资产图片生成任务失败', [
  6673. 'product_id' => $product->id,
  6674. 'error' => $e->getMessage()
  6675. ]);
  6676. // 标记为失败(仍在事务中)
  6677. DB::table('mp_products')
  6678. ->where('id', $product->id)
  6679. ->update([
  6680. 'pic_task_status' => '生成失败',
  6681. 'updated_at' => now()
  6682. ]);
  6683. }
  6684. }
  6685. // 提交事务
  6686. DB::commit();
  6687. // 如果有新创建的任务,返回 SSE 流
  6688. if (!empty($productTaskMap)) {
  6689. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6690. }
  6691. } catch (\Exception $e) {
  6692. // 回滚事务
  6693. DB::rollback();
  6694. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6695. 'script_id' => $script_id,
  6696. 'error' => $e->getMessage()
  6697. ]);
  6698. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6699. }
  6700. }
  6701. // 如果不需要生成图片,返回已存在的信息
  6702. return [
  6703. 'success' => true,
  6704. 'message' => '剧本资产已存在',
  6705. 'script_id' => $script_id,
  6706. 'script_name' => $script_name,
  6707. 'type_folder_ids' => $typeFolderIds,
  6708. 'existing_products' => count($productIds),
  6709. 'tasks_count' => count($productTaskMap)
  6710. ];
  6711. }
  6712. // 解析 products(可能是 JSON 字符串或数组)
  6713. if (is_string($products)) {
  6714. $products = json_decode($products, true);
  6715. if (json_last_error() !== JSON_ERROR_NONE) {
  6716. Utils::throwError('20003:产品数据格式错误');
  6717. }
  6718. }
  6719. if (!is_array($products) || empty($products)) {
  6720. Utils::throwError('20003:产品数据不能为空');
  6721. }
  6722. // 以下是原有的创建逻辑...
  6723. // 开启事务
  6724. DB::beginTransaction();
  6725. try {
  6726. $now = now();
  6727. $mappingRecords = [];
  6728. $createdProductIds = []; // 记录所有创建的资产ID
  6729. // 获取剧本名称
  6730. $script_name = $script->script_name ?? 'script_' . $script_id;
  6731. // 存储每个类型的根文件夹ID
  6732. $typeFolderIds = [];
  6733. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6734. foreach ($products as $productGroup) {
  6735. $type = getProp($productGroup, 'type');
  6736. $title = getProp($productGroup, 'title', '');
  6737. $content = getProp($productGroup, 'content', []);
  6738. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6739. continue;
  6740. }
  6741. // 为当前类型创建根文件夹(如果还未创建)
  6742. if (!isset($typeFolderIds[$type])) {
  6743. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6744. 'user_id' => $uid,
  6745. 'cpid' => $cpid,
  6746. 'type' => 2, // 1.资产 2文件夹
  6747. 'product' => $type, // 1.主体 2.场景 3.道具
  6748. 'parent_id' => 0, // 根文件夹,parent_id=0
  6749. 'level' => 1, // 第一层级
  6750. 'product_name' => $script_name,
  6751. 'sort_order' => time() + $type,
  6752. 'is_deleted' => 0,
  6753. 'created_at' => $now,
  6754. 'updated_at' => $now
  6755. ]);
  6756. }
  6757. $folder_id = $typeFolderIds[$type];
  6758. // 获取表头(第一行)并查找关键列的位置
  6759. $headers = $content[0];
  6760. $nameColumnIndex = -1; // 资产名称列索引
  6761. $sequenceColumnIndex = -1; // 使用范围列索引
  6762. $promptColumnIndex = -1; // 参考提示词列索引
  6763. foreach ($headers as $index => $header) {
  6764. // 查找"资产名称"列
  6765. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6766. $nameColumnIndex = $index;
  6767. }
  6768. // 查找"使用范围"列
  6769. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6770. $sequenceColumnIndex = $index;
  6771. }
  6772. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6773. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6774. $promptColumnIndex = $index;
  6775. }
  6776. }
  6777. // 验证必要的列是否都找到了
  6778. if ($nameColumnIndex === -1) {
  6779. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6780. continue;
  6781. }
  6782. if ($sequenceColumnIndex === -1) {
  6783. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6784. continue;
  6785. }
  6786. // 跳过表头,解析每一行数据
  6787. for ($i = 1; $i < count($content); $i++) {
  6788. $row = $content[$i];
  6789. // 确保行数据有效
  6790. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6791. continue;
  6792. }
  6793. // 根据动态查找的列索引提取数据
  6794. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6795. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6796. $pic_prompt = '';
  6797. // 提取参考提示词(如果找到了该列)
  6798. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6799. $pic_prompt = trim($row[$promptColumnIndex]);
  6800. }
  6801. // 解析使用范围(逗号分隔的序号)
  6802. $sequences = [];
  6803. if (!empty($sequence_str)) {
  6804. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6805. foreach ($sequenceParts as $part) {
  6806. if (is_numeric($part)) {
  6807. $sequences[] = (int)$part;
  6808. }
  6809. }
  6810. }
  6811. if (empty($product_name)) {
  6812. continue;
  6813. }
  6814. // 处理product_name两边的符号
  6815. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6816. // 如果名称不存在则跳过
  6817. if (!$product_name) continue;
  6818. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6819. $product_id = DB::table('mp_products')->insertGetId([
  6820. 'product_name' => $product_name,
  6821. 'type' => 1, // 1=资产 2.文件夹
  6822. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6823. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6824. 'level' => 2, // 第二层级
  6825. 'pic_prompt' => $pic_prompt,
  6826. 'user_id' => $uid,
  6827. 'cpid' => $cpid,
  6828. 'sort_order' => time(),
  6829. 'is_deleted' => 0,
  6830. 'created_at' => $now,
  6831. 'updated_at' => $now,
  6832. ]);
  6833. // 记录创建的资产ID
  6834. $createdProductIds[] = $product_id;
  6835. // 为每个序号创建映射记录
  6836. if (!empty($sequences)) {
  6837. foreach ($sequences as $sequence) {
  6838. $mappingRecords[] = [
  6839. 'script_id' => $script_id,
  6840. 'product_id' => $product_id,
  6841. 'episode_number' => $sequence,
  6842. 'created_at' => $now,
  6843. 'updated_at' => $now,
  6844. ];
  6845. }
  6846. } else {
  6847. // 如果没有指定序号,创建一个默认映射(序号为0)
  6848. $mappingRecords[] = [
  6849. 'script_id' => $script_id,
  6850. 'product_id' => $product_id,
  6851. 'episode_number' => 0,
  6852. 'created_at' => $now,
  6853. 'updated_at' => $now,
  6854. ];
  6855. }
  6856. }
  6857. }
  6858. if (empty($mappingRecords)) {
  6859. Utils::throwError('20003:没有有效的产品数据');
  6860. }
  6861. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6862. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6863. // 如果需要自动生成图片,在事务中创建图片生成任务
  6864. $productTaskMap = [];
  6865. if ($auto_generate_images && !empty($createdProductIds)) {
  6866. // 查询所有创建的资产
  6867. $productsToGenerate = DB::table('mp_products')
  6868. ->whereIn('id', $createdProductIds)
  6869. ->where('is_deleted', 0)
  6870. ->get();
  6871. foreach ($productsToGenerate as $product) {
  6872. if (empty($product->pic_prompt)) {
  6873. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6874. 'product_id' => $product->id,
  6875. 'product_name' => $product->product_name
  6876. ]);
  6877. continue;
  6878. }
  6879. try {
  6880. // 创建图片生成任务
  6881. $params = [
  6882. 'prompt' => $product->pic_prompt,
  6883. 'model' => $model,
  6884. 'ref_img_urls' => [],
  6885. 'width' => $width,
  6886. 'height' => $height
  6887. ];
  6888. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6889. $task_id = $task->id;
  6890. if ($task_id) {
  6891. $productTaskMap[$product->id] = $task_id;
  6892. // 在事务中更新资产表的任务ID和状态
  6893. DB::table('mp_products')
  6894. ->where('id', $product->id)
  6895. ->update([
  6896. 'pic_task_id' => $task_id,
  6897. 'pic_task_status' => '生成中',
  6898. 'updated_at' => now()
  6899. ]);
  6900. dLog('anime')->info('创建资产图片生成任务', [
  6901. 'product_id' => $product->id,
  6902. 'task_id' => $task_id
  6903. ]);
  6904. }
  6905. } catch (\Exception $e) {
  6906. dLog('anime')->error('创建资产图片生成任务失败', [
  6907. 'product_id' => $product->id,
  6908. 'error' => $e->getMessage()
  6909. ]);
  6910. // 标记为失败(仍在事务中)
  6911. DB::table('mp_products')
  6912. ->where('id', $product->id)
  6913. ->update([
  6914. 'pic_task_status' => '生成失败',
  6915. 'updated_at' => now()
  6916. ]);
  6917. }
  6918. }
  6919. }
  6920. // 提交事务
  6921. DB::commit();
  6922. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6923. if ($auto_generate_images && !empty($productTaskMap)) {
  6924. // 返回 SSE 流(事务外轮询)
  6925. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6926. }
  6927. // 如果不需要生成图片,返回普通结果
  6928. return [
  6929. 'success' => true,
  6930. 'type_folder_ids' => $typeFolderIds,
  6931. 'inserted_count' => $insertedCount,
  6932. 'total_records' => count($mappingRecords),
  6933. 'created_products' => count($createdProductIds),
  6934. 'image_tasks_created' => count($productTaskMap)
  6935. ];
  6936. } catch (\Exception $e) {
  6937. // 回滚事务
  6938. DB::rollback();
  6939. // 记录错误日志
  6940. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6941. 'script_id' => $script_id,
  6942. 'error' => $e->getMessage(),
  6943. 'trace' => $e->getTraceAsString()
  6944. ]);
  6945. // 统一使用 Utils::throwError 抛出错误
  6946. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6947. }
  6948. }
  6949. /**
  6950. * 批量为剧本资产生成图片
  6951. *
  6952. * @param array $data 请求参数
  6953. * @return \Generator 返回 SSE 流
  6954. */
  6955. public function batchGenerateProductImages($data) {
  6956. $script_id = getProp($data, 'script_id');
  6957. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6958. if (!$script_id) {
  6959. Utils::throwError('20003:请提供剧本ID');
  6960. }
  6961. // 验证剧本是否存在
  6962. $script = DB::table('mp_scripts')
  6963. ->where('id', $script_id)
  6964. ->where('is_deleted', 0)
  6965. ->first();
  6966. if (!$script) {
  6967. Utils::throwError('20003:剧本不存在');
  6968. }
  6969. $script_name = $script->script_name ?? 'script_' . $script_id;
  6970. // 获取需要生成图片的所有资产
  6971. $products = DB::table('mp_products')
  6972. ->whereIn('parent_id', array_values($type_folder_ids))
  6973. ->where('is_deleted', 0)
  6974. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6975. ->get();
  6976. if ($products->isEmpty()) {
  6977. Utils::throwError('20003:没有找到需要生成图片的资产');
  6978. }
  6979. // 默认参数
  6980. $model = 'doubao-seedream-5-0-lite-260128';
  6981. $width = 1600;
  6982. $height = 2848;
  6983. // 开始为每个资产创建图片生成任务
  6984. $taskIds = [];
  6985. $productTaskMap = []; // 资产ID到任务ID的映射
  6986. foreach ($products as $product) {
  6987. if (empty($product->pic_prompt)) {
  6988. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6989. continue;
  6990. }
  6991. try {
  6992. // 创建图片生成任务
  6993. $params = [
  6994. 'prompt' => $product->pic_prompt,
  6995. 'model' => $model,
  6996. 'ref_img_urls' => [],
  6997. 'width' => $width,
  6998. 'height' => $height
  6999. ];
  7000. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7001. $task_id = $task->id;
  7002. if ($task_id) {
  7003. $taskIds[] = $task_id;
  7004. $productTaskMap[$product->id] = $task_id;
  7005. // 更新资产表的任务ID和状态
  7006. DB::table('mp_products')
  7007. ->where('id', $product->id)
  7008. ->update([
  7009. 'pic_task_id' => $task_id,
  7010. 'pic_task_status' => '生成中',
  7011. 'updated_at' => now()
  7012. ]);
  7013. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7014. }
  7015. } catch (\Exception $e) {
  7016. dLog('anime')->error('创建资产图片生成任务失败', [
  7017. 'product_id' => $product->id,
  7018. 'error' => $e->getMessage()
  7019. ]);
  7020. // 标记为失败
  7021. DB::table('mp_products')
  7022. ->where('id', $product->id)
  7023. ->update([
  7024. 'pic_task_status' => '生成失败',
  7025. 'updated_at' => now()
  7026. ]);
  7027. }
  7028. }
  7029. if (empty($taskIds)) {
  7030. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7031. }
  7032. // 返回 SSE 流
  7033. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7034. }
  7035. /**
  7036. * 轮询资产图片生成任务状态(SSE流式返回)
  7037. * 只通过查询数据库获取任务状态,不主动调用API
  7038. *
  7039. * @param int $script_id 剧本ID
  7040. * @param string $script_name 剧本名称
  7041. * @param array $productTaskMap 资产ID到任务ID的映射
  7042. * @param array $type_folder_ids 类型文件夹ID映射
  7043. * @return \Generator
  7044. */
  7045. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7046. $startTime = time();
  7047. $timeout = 1800; // 30分钟超时
  7048. $pollInterval = 10; // 10秒轮询一次
  7049. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7050. // 定义类型名称映射
  7051. $typeNames = [
  7052. 1 => 'roles', // 角色
  7053. 2 => 'scenes', // 场景
  7054. 3 => 'props' // 道具
  7055. ];
  7056. while (time() - $startTime < $timeout) {
  7057. sleep($pollInterval);
  7058. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7059. $mappings = DB::table('mp_script_product_mappings')
  7060. ->where('script_id', $script_id)
  7061. ->pluck('product_id')
  7062. ->unique()
  7063. ->toArray();
  7064. if (empty($mappings)) {
  7065. dLog('anime')->warning('该剧本没有关联的资产', [
  7066. 'script_id' => $script_id,
  7067. 'script_name' => $script_name
  7068. ]);
  7069. break;
  7070. }
  7071. // 查询所有资产的当前状态
  7072. $products = DB::table('mp_products')
  7073. ->whereIn('id', $mappings)
  7074. ->where('is_deleted', 0)
  7075. ->get();
  7076. // 统计各类型的状态(使用类型名称作为键名)
  7077. $stats = [
  7078. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7079. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7080. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7081. ];
  7082. $allCompleted = true;
  7083. $hasStatusChange = false;
  7084. foreach ($products as $product) {
  7085. $type = $product->product;
  7086. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7087. // 如果类型名称不在 stats 中,初始化
  7088. if (!isset($stats[$typeName])) {
  7089. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7090. }
  7091. $stats[$typeName]['total']++;
  7092. $task_id = $product->pic_task_id;
  7093. $currentStatus = $product->pic_task_status;
  7094. // 检查状态是否有变化
  7095. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7096. $hasStatusChange = true;
  7097. $lastStatus[$product->id] = $currentStatus;
  7098. }
  7099. // 如果是生成中,查询任务表状态
  7100. if ($currentStatus === '生成中' && $task_id) {
  7101. // 只查询数据库,不调用API
  7102. $task = DB::table('mp_generate_pic_tasks')
  7103. ->where('id', $task_id)
  7104. ->first();
  7105. if ($task) {
  7106. // 检查任务状态
  7107. if ($task->status === 'success' && $task->result_url) {
  7108. // 解析图片URL
  7109. $result_urls = $task->result_url;
  7110. if (is_string($result_urls)) {
  7111. $result_urls = json_decode($result_urls, true);
  7112. }
  7113. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7114. // 更新资产表状态
  7115. DB::table('mp_products')
  7116. ->where('id', $product->id)
  7117. ->update([
  7118. 'pic_task_status' => '生成成功',
  7119. 'url' => $img_url,
  7120. 'updated_at' => now()
  7121. ]);
  7122. $stats[$typeName]['success']++;
  7123. $stats[$typeName]['completed']++;
  7124. $hasStatusChange = true;
  7125. dLog('anime')->info('资产图片生成成功', [
  7126. 'product_id' => $product->id,
  7127. 'task_id' => $task_id,
  7128. 'img_url' => $img_url
  7129. ]);
  7130. } elseif ($task->status === 'failed') {
  7131. // 更新资产表状态
  7132. DB::table('mp_products')
  7133. ->where('id', $product->id)
  7134. ->update([
  7135. 'pic_task_status' => '生成失败',
  7136. 'updated_at' => now()
  7137. ]);
  7138. $stats[$typeName]['completed']++;
  7139. $hasStatusChange = true;
  7140. dLog('anime')->warning('资产图片生成失败', [
  7141. 'product_id' => $product->id,
  7142. 'task_id' => $task_id,
  7143. 'error' => $task->error_message ?? '未知错误'
  7144. ]);
  7145. } else {
  7146. // 任务还在处理中
  7147. $allCompleted = false;
  7148. }
  7149. } else {
  7150. // 任务不存在,标记为失败
  7151. DB::table('mp_products')
  7152. ->where('id', $product->id)
  7153. ->update([
  7154. 'pic_task_status' => '生成失败',
  7155. 'updated_at' => now()
  7156. ]);
  7157. $stats[$type]['completed']++;
  7158. $hasStatusChange = true;
  7159. dLog('anime')->error('图片生成任务不存在', [
  7160. 'product_id' => $product->id,
  7161. 'task_id' => $task_id
  7162. ]);
  7163. }
  7164. } elseif ($currentStatus === '生成成功') {
  7165. $stats[$typeName]['success']++;
  7166. $stats[$typeName]['completed']++;
  7167. } elseif ($currentStatus === '生成失败') {
  7168. $stats[$typeName]['completed']++;
  7169. } else {
  7170. // 其他状态也认为未完成
  7171. $allCompleted = false;
  7172. }
  7173. }
  7174. // 移除没有数据的类型(total=0)
  7175. foreach ($stats as $typeName => $stat) {
  7176. if ($stat['total'] === 0) {
  7177. unset($stats[$typeName]);
  7178. }
  7179. }
  7180. // 如果有状态变化,发送 SSE 更新
  7181. if ($hasStatusChange) {
  7182. $eventType = $allCompleted ? 'complete' : 'update';
  7183. $response = [
  7184. 'type' => $eventType,
  7185. 'script_id' => $script_id,
  7186. 'script_name' => $script_name,
  7187. 'stats' => $stats,
  7188. 'timestamp' => date('Y-m-d H:i:s')
  7189. ];
  7190. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7191. dLog('anime')->info('SSE更新', [
  7192. 'event_type' => $eventType,
  7193. 'script_id' => $script_id,
  7194. 'script_name' => $script_name,
  7195. 'stats' => $stats
  7196. ]);
  7197. if ($allCompleted) {
  7198. dLog('anime')->info('所有资产图片生成任务已完成', [
  7199. 'script_id' => $script_id,
  7200. 'script_name' => $script_name,
  7201. 'stats' => $stats
  7202. ]);
  7203. break;
  7204. }
  7205. }
  7206. }
  7207. // 超时处理
  7208. if (time() - $startTime >= $timeout && !$allCompleted) {
  7209. $response = [
  7210. 'type' => 'timeout',
  7211. 'message' => '部分任务超时,请稍后查看结果',
  7212. 'script_id' => $script_id,
  7213. 'script_name' => $script_name,
  7214. 'timestamp' => date('Y-m-d H:i:s')
  7215. ];
  7216. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7217. dLog('anime')->warning('资产图片生成任务超时', [
  7218. 'script_id' => $script_id,
  7219. 'script_name' => $script_name,
  7220. 'timeout' => $timeout
  7221. ]);
  7222. }
  7223. }
  7224. /**
  7225. * 获取剧本关联的资产列表
  7226. * @param array $data 请求参数
  7227. * @return array
  7228. */
  7229. public function getScriptProducts($data) {
  7230. $uid = Site::getUid();
  7231. $cpid = Site::getCpid();
  7232. $script_id = getProp($data, 'script_id');
  7233. $episode_number = getProp($data, 'episode_number');
  7234. if (!$script_id) {
  7235. Utils::throwError('20003:请提供剧本ID');
  7236. }
  7237. // 验证剧本是否存在
  7238. $script = DB::table('mp_scripts')
  7239. ->where('id', $script_id)
  7240. ->where('is_deleted', 0)
  7241. ->first();
  7242. if (!$script) {
  7243. Utils::throwError('20003:剧本不存在');
  7244. }
  7245. // 联表查询资产信息
  7246. $query = DB::table('mp_script_product_mappings as mapping')
  7247. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7248. ->where('mapping.script_id', $script_id)
  7249. ->where('product.cpid', $cpid)
  7250. ->where('product.is_deleted', 0);
  7251. // 如果提供了 episode_number,则过滤指定集数
  7252. if ($episode_number !== null && $episode_number !== '') {
  7253. $query->where('mapping.episode_number', $episode_number);
  7254. }
  7255. $mappings = $query->select(
  7256. 'mapping.script_id',
  7257. 'mapping.product_id',
  7258. 'mapping.episode_number',
  7259. 'product.product_name',
  7260. 'product.type',
  7261. 'product.product',
  7262. 'product.pic_prompt',
  7263. 'product.url',
  7264. 'product.pic_task_id',
  7265. 'product.pic_task_status',
  7266. 'product.three_view_image_url',
  7267. 'mapping.created_at'
  7268. )
  7269. ->orderBy('mapping.product_id', 'asc')
  7270. ->orderBy('mapping.episode_number', 'asc')
  7271. ->get();
  7272. // 按 product_id 分组,合并 episode_number
  7273. $productMap = [];
  7274. foreach ($mappings as $item) {
  7275. $product_id = $item->product_id;
  7276. if (!isset($productMap[$product_id])) {
  7277. $productMap[$product_id] = [
  7278. 'product_id' => $product_id,
  7279. 'product_name' => $item->product_name,
  7280. 'type' => (int)$item->type,
  7281. 'product' => (int)$item->product,
  7282. 'pic_prompt' => $item->pic_prompt,
  7283. 'url' => $item->url,
  7284. 'pic_task_id' => $item->pic_task_id,
  7285. 'pic_task_status' => $item->pic_task_status,
  7286. 'episode_numbers' => [],
  7287. 'created_at' => $item->created_at,
  7288. ];
  7289. }
  7290. // 添加 episode_number(去重)
  7291. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7292. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7293. }
  7294. }
  7295. // 按类型分组
  7296. $roles = []; // type=1 角色/主体
  7297. $scenes = []; // type=2 场景
  7298. $props = []; // type=3 道具
  7299. foreach ($productMap as $product) {
  7300. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7301. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7302. // 构造返回数据
  7303. $productData = [
  7304. 'product_id' => $product['product_id'],
  7305. 'product_name' => $product['product_name'],
  7306. 'product' => $product['product'],
  7307. 'pic_prompt' => $product['pic_prompt'],
  7308. 'url' => $product['url'],
  7309. 'pic_task_id' => $product['pic_task_id'],
  7310. 'pic_task_status' => $product['pic_task_status'],
  7311. 'episode_numbers' => $episodeNumbersStr,
  7312. 'created_at' => $product['created_at'],
  7313. ];
  7314. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7315. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7316. switch ($product['product']) {
  7317. case 1:
  7318. $roles[] = $productData;
  7319. break;
  7320. case 2:
  7321. $scenes[] = $productData;
  7322. break;
  7323. case 3:
  7324. $props[] = $productData;
  7325. break;
  7326. }
  7327. }
  7328. return [
  7329. 'script_id' => $script_id,
  7330. 'script_name' => $script->script_name ?? '',
  7331. 'roles' => $roles, // 主体
  7332. 'scenes' => $scenes, // 场景
  7333. 'props' => $props, // 道具
  7334. ];
  7335. }
  7336. /**
  7337. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7338. * @param string $actContent 原始内容
  7339. * @param array $products 产品数组(包含product_name和url)
  7340. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7341. */
  7342. public function processActContentWithProducts($actContent, $products) {
  7343. if (empty($actContent) || empty($products)) {
  7344. return [
  7345. 'content' => $actContent,
  7346. 'reference_images' => []
  7347. ];
  7348. }
  7349. // 构建产品名称到产品信息的映射
  7350. $product_dict = [];
  7351. foreach ($products as $product) {
  7352. $product_name = getProp($product, 'product_name');
  7353. if ($product_name) {
  7354. $product_dict[$product_name] = [
  7355. 'url' => getProp($product, 'url'),
  7356. 'voice_prompt' => getProp($product, 'voice_prompt')
  7357. ];
  7358. }
  7359. }
  7360. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7361. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7362. $reference_images = [];
  7363. $product_index_map = []; // 产品名称 => 图片序号的映射
  7364. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7365. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7366. $current_index = 1;
  7367. if (!empty($matches[1])) {
  7368. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7369. $seen_products = []; // 用于去重
  7370. foreach ($matches[1] as $product_name) {
  7371. // 跳过已处理的产品
  7372. if (isset($seen_products[$product_name])) {
  7373. continue;
  7374. }
  7375. $seen_products[$product_name] = true;
  7376. // 检查产品是否在字典中
  7377. if (isset($product_dict[$product_name])) {
  7378. $url = $product_dict[$product_name]['url'];
  7379. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7380. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7381. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7382. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7383. }
  7384. // 只有URL非空才分配序号和添加到参考图片
  7385. if (!empty($url)) {
  7386. // 检查URL是否已经在reference_images中(去重)
  7387. if (!in_array($url, $reference_images)) {
  7388. $reference_images[] = $url;
  7389. $product_index_map[$product_name] = $current_index;
  7390. $current_index++;
  7391. } else {
  7392. // URL重复,找到已有的序号
  7393. $existing_index = array_search($url, $reference_images) + 1;
  7394. $product_index_map[$product_name] = $existing_index;
  7395. }
  7396. } else {
  7397. // URL为空,不分配序号(后续直接去掉{})
  7398. $product_index_map[$product_name] = 0;
  7399. }
  7400. } else {
  7401. // 产品不在字典中,不分配序号
  7402. $product_index_map[$product_name] = 0;
  7403. }
  7404. }
  7405. }
  7406. // 第二步:替换内容中的 {产品名称}
  7407. $processedContent = $actContent;
  7408. foreach ($product_index_map as $product_name => $index) {
  7409. $escaped_name = preg_quote($product_name, '/');
  7410. if ($index > 0) {
  7411. // 有图片,替换为:产品名称(图X)
  7412. $replacement = $product_name . '<图片' . $index . '>';
  7413. } else {
  7414. // 无图片,只保留产品名称
  7415. $replacement = $product_name;
  7416. }
  7417. // 替换所有 {产品名称} 为处理后的格式
  7418. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7419. }
  7420. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7421. foreach ($products as $product) {
  7422. $product_name = getProp($product, 'product_name');
  7423. $voice_prompt = getProp($product, 'voice_prompt');
  7424. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7425. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7426. break; // 找到旁白后退出循环
  7427. }
  7428. }
  7429. // 第四步:将voice_prompt信息添加到内容最前面
  7430. $voice_prompt_prefix = '';
  7431. if (!empty($voice_prompts)) {
  7432. $voice_prompt_prefix .= implode('', $voice_prompts);
  7433. }
  7434. // 旁白的voice_prompt放在最后
  7435. if (!empty($narrator_voice_prompt)) {
  7436. $voice_prompt_prefix .= $narrator_voice_prompt;
  7437. }
  7438. // 如果有voice_prompt信息,添加到内容开头
  7439. if (!empty($voice_prompt_prefix)) {
  7440. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7441. }
  7442. return [
  7443. 'content' => $processedContent,
  7444. 'reference_images' => $reference_images
  7445. ];
  7446. }
  7447. public function saveActVideoGenerateParams($data) {
  7448. $episode_id = getProp($data, 'episode_id');
  7449. $model = getProp($data, 'video_model');
  7450. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7451. Utils::throwError('20003:该模型不可用');
  7452. }
  7453. if (!$model) {
  7454. // 使用默认模型
  7455. $model = 'zhizhen-20';
  7456. }
  7457. // 验证模型是否在可用模型表中
  7458. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7459. Utils::throwError('20003:该模型已不可用,请更换!');
  7460. }
  7461. $video_resolution = getProp($data, 'video_resolution', '720p');
  7462. $ratio = getProp($data, 'ratio');
  7463. if (!$ratio) $ratio = '9:16';
  7464. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7465. 'video_model' => $model,
  7466. 'video_resolution' => $video_resolution,
  7467. 'ratio' => $ratio,
  7468. 'updated_at' => date('Y-m-d H:i:s')
  7469. ]);
  7470. }
  7471. public function confirmActs($data) {
  7472. $episode_id = getProp($data, 'episode_id');
  7473. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7474. if (!$episode) {
  7475. Utils::throwError('20003:分集不存在');
  7476. }
  7477. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7478. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7479. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7480. // 获取所有片段数据
  7481. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7482. // 收集所有资产名称(角色、场景、道具)
  7483. $product_names = [];
  7484. // 收集角色名称
  7485. foreach ($roles as $role) {
  7486. $role_name = getProp($role, 'role');
  7487. if ($role_name && $role_name != '旁白') {
  7488. $product_names[] = $role_name;
  7489. }
  7490. }
  7491. // 收集场景名称
  7492. foreach ($scenes as $scene) {
  7493. $scene_name = getProp($scene, 'scene');
  7494. if ($scene_name) {
  7495. $product_names[] = $scene_name;
  7496. }
  7497. }
  7498. // 收集道具名称
  7499. foreach ($props as $prop) {
  7500. $prop_name = getProp($prop, 'prop');
  7501. if ($prop_name) {
  7502. $product_names[] = $prop_name;
  7503. }
  7504. }
  7505. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7506. $product_names = array_unique($product_names);
  7507. usort($product_names, function($a, $b) {
  7508. return mb_strlen($b) - mb_strlen($a);
  7509. });
  7510. try {
  7511. DB::beginTransaction();
  7512. // 处理每个片段
  7513. foreach ($acts as $act) {
  7514. $act_content = getProp($act, 'act_content');
  7515. if (!$act_content) continue;
  7516. $processed_content = $act_content;
  7517. // 统一替换所有资产名称为 {资产名} 格式
  7518. // 使用占位符避免嵌套替换问题
  7519. $placeholder_map = [];
  7520. $placeholder_index = 0;
  7521. foreach ($product_names as $product_name) {
  7522. // 转义特殊字符
  7523. $escaped_product = preg_quote($product_name, '/');
  7524. // 检查是否匹配且未被 {} 包裹
  7525. $processed_content = preg_replace_callback(
  7526. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7527. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7528. // 使用唯一占位符
  7529. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7530. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7531. $placeholder_index++;
  7532. return $placeholder;
  7533. },
  7534. $processed_content
  7535. );
  7536. }
  7537. // 将所有占位符替换回实际内容
  7538. foreach ($placeholder_map as $placeholder => $replacement) {
  7539. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7540. }
  7541. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7542. $shot_counter = 0;
  7543. $processed_content = preg_replace_callback(
  7544. '/【(?:镜头|分镜)(\d+)】/u',
  7545. function($matches) use (&$shot_counter) {
  7546. $shot_counter++;
  7547. return '【镜头' . $shot_counter . '】';
  7548. },
  7549. $processed_content
  7550. );
  7551. // 更新数据库
  7552. $boolen = DB::table('mp_episode_segments')
  7553. ->where('id', $act->id)
  7554. ->update([
  7555. 'act_show_content' => $processed_content,
  7556. 'updated_at' => date('Y-m-d H:i:s')
  7557. ]);
  7558. if (!$boolen) {
  7559. Utils::throwError('20003:片段处理失败');
  7560. }
  7561. }
  7562. }catch (\Exception $e) {
  7563. DB::rollBack();
  7564. Utils::throwError('20003:'.$e->getMessage());
  7565. }
  7566. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7567. 'is_generated' => 1,
  7568. 'updated_at' => date('Y-m-d H:i:s')
  7569. ]);
  7570. if (!$boolen1) {
  7571. DB::rollBack();
  7572. Utils::throwError('20003:分集处理失败!');
  7573. }
  7574. DB::commit();
  7575. // 重新查询更新后的片段数据
  7576. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7577. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7578. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7579. $products = [];
  7580. // 先处理角色数组
  7581. foreach ($roles as $role) {
  7582. $product = $role;
  7583. // 将role字段重命名为product_name
  7584. if (isset($product['role'])) {
  7585. $product['product_name'] = $product['role'];
  7586. unset($product['role']);
  7587. $product['product'] = 1; // 标记类型为角色
  7588. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7589. }
  7590. }
  7591. // 处理场景数组
  7592. foreach ($scenes as $scene) {
  7593. $product = $scene;
  7594. // 将scene字段重命名为product_name
  7595. if (isset($product['scene'])) {
  7596. $product['product_name'] = $product['scene'];
  7597. unset($product['scene']);
  7598. $product['product'] = 2; // 标记类型为场景
  7599. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7600. }
  7601. }
  7602. // 处理道具数组(逻辑与场景一致)
  7603. foreach ($props as $prop) {
  7604. $product = $prop;
  7605. // 将prop字段重命名为product_name
  7606. if (isset($product['prop'])) {
  7607. $product['product_name'] = $product['prop'];
  7608. unset($product['prop']);
  7609. $product['product'] = 3; // 标记类型为道具
  7610. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7611. }
  7612. }
  7613. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7614. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7615. foreach ($extra_products as $extra_product) {
  7616. $product_name = getProp($extra_product, 'product_name');
  7617. if ($product_name) {
  7618. $products[$product_name] = $extra_product; // 覆盖同名数据
  7619. }
  7620. }
  7621. // 重新索引数组(去除key)
  7622. $products = array_values($products);
  7623. // 构建返回的acts数组
  7624. $return_acts = [];
  7625. foreach ($acts as $act) {
  7626. $return_acts[] = [
  7627. 'act_id' => getProp($act, 'id'),
  7628. 'act_number' => getProp($act, 'act_number'),
  7629. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7630. 'act_show_content' => getProp($act, 'act_show_content'),
  7631. 'video_url' => getProp($act, 'video_url'),
  7632. 'video_duration' => getProp($act, 'video_duration'),
  7633. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7634. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7635. ];
  7636. }
  7637. return [
  7638. 'anime_id' => getProp($episode, 'anime_id'),
  7639. 'episode_id' => $episode_id,
  7640. 'title' => getProp($episode, 'title'),
  7641. 'episode_number' => getProp($episode, 'episode_number'),
  7642. 'is_generated' => getProp($episode, 'is_generated'),
  7643. 'products' => $products,
  7644. 'acts' => $return_acts
  7645. ];
  7646. }
  7647. }