AnimeService.php 343 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $input_art_style = getProp($data, 'art_style');
  181. $file = getProp($data, 'file');
  182. $content = getProp($data, 'content', '');
  183. $bid = getProp($data, 'bid', 0);
  184. $script_id = getProp($data, 'script_id', 0);
  185. $ace_mode = getProp($data, 'ace_mode', 0);
  186. $extra_products = getProp($data, 'products', []);
  187. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  188. if (!is_array($extra_products)) {
  189. Utils::throwError('20003:传入的资产格式不正确');
  190. }
  191. // 替换美术风格
  192. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  193. // 提取文件内容
  194. if ($file) {
  195. $content = $this->DeepSeekService->extractFileContent($file);
  196. if (!$content) {
  197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  198. }
  199. } elseif ($script_id) {
  200. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  201. if (!$content) {
  202. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  203. }
  204. } elseif ($bid) {
  205. $content = $this->DeepSeekService->getContentByBid($bid);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  208. }
  209. } elseif ($content) {
  210. $content = filterContent($content);
  211. }else {
  212. $content = '';
  213. }
  214. $anime_data = [
  215. 'user_id' => $uid,
  216. 'anime_name' => '新剧本策划',
  217. 'is_multi' => getProp($data, 'is_multi', 1),
  218. 'content' => $content,
  219. 'art_style_type' => $input_art_style,
  220. 'ace_mode' => $ace_mode,
  221. 'script_id' => $script_id,
  222. 'extra_products' => json_encode($extra_products, 256),
  223. 'created_at' => date('Y-m-d H:i:s'),
  224. 'updated_at' => date('Y-m-d H:i:s'),
  225. ];
  226. // 处理文本模型
  227. $model = getProp($data, 'model');
  228. if (!$model) {
  229. // 用户没有输入,使用默认值
  230. $model = 'doubao-seed-2-0-mini-260215';
  231. }
  232. // 验证模型是否在可用模型表中
  233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  234. $model = 'doubao-seed-2-0-mini-260215';
  235. }
  236. $anime_data['model'] = $model;
  237. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  238. return DB::table('mp_animes')->insertGetId($anime_data);
  239. }
  240. public function chatList($data) {
  241. $uid = Site::getUid();
  242. $anime_name = getProp($data, 'anime_name');
  243. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  244. if ($anime_name) {
  245. $query->where('anime_name', 'like', "%$anime_name%");
  246. }
  247. return $query->orderBy('id', 'desc')->paginate();
  248. }
  249. public function chatHistory($data) {
  250. $anime_id = getProp($data, 'anime_id');
  251. $sequence = getProp($data, 'sequence', 0);
  252. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  253. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  254. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  255. return $query->orderBy('ar.id')->get()->map(function ($value) {
  256. $value = (array)$value;
  257. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  258. $value['created_at'] = transDate($value['created_at']);
  259. $value['episode_created_at'] = transDate($value['episode_created_at']);
  260. return $value;
  261. })->toArray();
  262. }
  263. public function batchSetRoleImg($data) {
  264. $episode_id = getProp($data, 'episode_id');
  265. if (!$episode_id) Utils::throwError('1002:请选择分集');
  266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  267. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  268. $art_style = getProp($episode, 'art_style');
  269. $anime_id = getProp($episode, 'anime_id');
  270. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  271. $art_style_type = getProp($anime, 'art_style_type');
  272. $character_prefix = '';
  273. $scene_prefix = '';
  274. if ($art_style_type) {
  275. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  276. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  277. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  278. }
  279. foreach ($roles as &$role) {
  280. $role_name = getProp($role, 'role');
  281. if ($role_name == '旁白') continue;
  282. // 优先使用 pic_prompt,如果没有则使用 description
  283. $pic_prompt = getProp($role, 'pic_prompt');
  284. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  285. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  286. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  287. // 参考图地址
  288. $ref_img_url = getProp($role, 'url');
  289. if ($ref_img_url) continue; // 已有图片则跳过
  290. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  291. try {
  292. $params = [
  293. 'prompt' => $description,
  294. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  295. ];
  296. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  297. $task_id = $task->id;
  298. if (!$task_id) {
  299. Utils::throwError("20003:角色({$role_name})生成图片失败");
  300. }
  301. $role['task_id'] = $task_id;
  302. $role['task_status'] = 'processing';
  303. } catch (\Exception $e) {
  304. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  305. Utils::throwError("20003:" . $e->getMessage());
  306. }
  307. }
  308. // 保存角色信息
  309. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  310. 'roles' => json_encode($roles, 256),
  311. 'generate_status' => '执行中',
  312. 'generate_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$boolen) {
  316. Utils::throwError('20003:保存角色信息失败');
  317. }
  318. return $boolen;
  319. }
  320. public function batchSetSceneImg($data) {
  321. $episode_id = getProp($data, 'episode_id');
  322. if (!$episode_id) Utils::throwError('1002:请选择分集');
  323. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  324. $scenes = json_decode(getProp($episode, 'scenes'), true);
  325. $art_style = getProp($episode, 'art_style');
  326. $target_scene = getProp($data, 'target_scene');
  327. $anime_id = getProp($episode, 'anime_id');
  328. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  329. $art_style_type = getProp($anime, 'art_style_type');
  330. $character_prefix = '';
  331. $scene_prefix = '';
  332. if ($art_style_type) {
  333. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  334. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  335. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  336. }
  337. foreach ($scenes as &$scene) {
  338. $scene_name = getProp($scene, 'scene');
  339. if ($scene_name != $target_scene) continue;
  340. // 优先使用 pic_prompt,如果没有则使用 description
  341. $pic_prompt = getProp($scene, 'pic_prompt');
  342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  343. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  344. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  345. // 参考图地址
  346. $ref_img_url = getProp($scene, 'url');
  347. if ($ref_img_url) continue; // 已有图片则跳过
  348. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  349. try {
  350. $params = [
  351. 'prompt' => $description,
  352. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  353. ];
  354. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  355. $task_id = $task->id;
  356. if (!$task_id) {
  357. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  358. }
  359. $scene['task_id'] = $task_id;
  360. $scene['task_status'] = 'processing';
  361. } catch (\Exception $e) {
  362. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  363. Utils::throwError("20003:" . $e->getMessage());
  364. }
  365. }
  366. // 保存场景信息
  367. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  368. 'scenes' => json_encode($scenes, 256),
  369. 'generate_status' => '执行中',
  370. 'generate_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$boolen) {
  374. Utils::throwError('20003:保存角色信息失败');
  375. }
  376. return $boolen;
  377. }
  378. public function editAnime($data) {
  379. $anime_id = getProp($data, 'anime_id');
  380. $anime_name = trim(getProp($data, 'anime_name'));
  381. // 确认对话名称唯一性
  382. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  383. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  384. }
  385. if (!$anime_id || !$anime_name) {
  386. Utils::throwError('20003:参数异常');
  387. }
  388. return DB::table('mp_animes')->where('id', $anime_id)->update([
  389. 'anime_name' => $anime_name,
  390. 'updated_at' => date('Y-m-d H:i:s')
  391. ]);
  392. // $script_arr =getProp($data, 'script', []);
  393. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  394. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  395. // $anime_id = getProp($data, 'anime_id');
  396. // try {
  397. // DB::beginTransaction();
  398. // $table_data = [
  399. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  400. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  401. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  402. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  403. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  404. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  405. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  406. // 'status' => 3,
  407. // 'start_episode_sequence' => $start_episode_sequence,
  408. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  409. // 'episode_num' => count($script_arr['episodes']),
  410. // 'updated_at' => date('Y-m-d H:i:s')
  411. // ];
  412. // // 保存剧本内容
  413. // if (!empty($anime_id)) {
  414. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  415. // if (!$boolen) {
  416. // dLog('anime')->info('对话保存失败', $table_data);
  417. // Utils::throwError('20003:对话保存失败');
  418. // }
  419. // }else {
  420. // $table['created_at'] = $table_data['updated_at'];
  421. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  422. // if (!$anime_id) {
  423. // dLog('anime')->info('对话保存失败', $table_data);
  424. // Utils::throwError('20003:对话保存失败');
  425. // }
  426. // }
  427. // // 保存分集内容
  428. // // 删除历史分集内容
  429. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  430. // $episodes = [];
  431. // $sequence = 1;
  432. // foreach ($script_arr['episodes'] as $episode) {
  433. // $segment_number = 1;
  434. // foreach($episode['segments'] as $segment) {
  435. // $episodes[] = [
  436. // 'anime_id' => $anime_id,
  437. // 'episode_number' => $episode['episode_number'],
  438. // 'title' => $episode['title'],
  439. // // 'content' => $episode['content'],
  440. // 'content' => '',
  441. // 'segment_number' => $segment_number,
  442. // 'segment_content' => $segment['segment_content'],
  443. // 'sequence' => $sequence,
  444. // 'created_at' => date('Y-m-d H:i:s'),
  445. // 'updated_at' => date('Y-m-d H:i:s')
  446. // ];
  447. // $sequence++;
  448. // $segment_number++;
  449. // }
  450. // }
  451. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  452. // if (!$boolen2) {
  453. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  454. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  455. // Utils::throwError('20003:分集内容保存失败');
  456. // }
  457. // } catch (\Exception $e) {
  458. // DB::rollBack();
  459. // Utils::throwError('20003:'.$e->getMessage());
  460. // }
  461. // DB::commit();
  462. // return true;
  463. }
  464. public function delAnime($data) {
  465. $anime_id = getProp($data, 'anime_id');
  466. if (!$anime_id) {
  467. Utils::throwError('20003:请选择剧本');
  468. }
  469. return DB::table('mp_animes')->where('id', $anime_id)->update([
  470. 'is_deleted' => 1,
  471. 'updated_at' => date('Y-m-d H:i:s')
  472. ]);
  473. }
  474. public function animeDetail($data) {
  475. $uid = Site::getUid();
  476. $anime_id = getProp($data, 'anime_id');
  477. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  478. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode')->first();
  479. if (!$anime) Utils::throwError('20003:权限不足');
  480. $anime = (array)$anime;
  481. $anime['roles'] = json_decode($anime['roles']);
  482. $anime['scenes'] = json_decode($anime['scenes']);
  483. // 获取分集信息
  484. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  485. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  486. ->orderBy('episode_number')->get()->map(function ($value) {
  487. return (array)$value;
  488. })->toArray();
  489. $anime['episodes'] = $episodes;
  490. return $anime;
  491. }
  492. public function episodeInfo($data) {
  493. $uid = Site::getUid();
  494. $anime_id = getProp($data, 'anime_id');
  495. $episode_id = getProp($data, 'episode_id');
  496. if (!$anime_id || !$episode_id) {
  497. Utils::throwError('1002:请选择剧集');
  498. }
  499. // 验证用户权限
  500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  503. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  504. $episode = (array)$episode;
  505. $episode['roles'] = json_decode($episode['roles'], true);
  506. // foreach($episode['roles'] as &$item) {
  507. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  508. // }
  509. $episode['scenes'] = json_decode($episode['scenes'], true);
  510. // foreach($episode['scenes'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  512. // }
  513. // 获取分镜信息
  514. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  515. ->select('*')->get()->map(function ($value) {
  516. return (array)$value;
  517. })->toArray();
  518. // 使用公共方法构建分镜结构
  519. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  520. $episode['acts'] = $segmentsStructure['acts'];
  521. $episode['total_duration'] = $segmentsStructure['total_duration'];
  522. return $episode;
  523. }
  524. public function episodeInfoForAce($data) {
  525. $anime_id = getProp($data, 'anime_id');
  526. $episode_id = getProp($data, 'episode_id');
  527. if (!$anime_id || !$episode_id) {
  528. Utils::throwError('1002:请选择剧集');
  529. }
  530. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  531. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  532. $episode = (array)$episode;
  533. $episode['roles'] = json_decode($episode['roles'], true);
  534. // foreach($episode['roles'] as &$item) {
  535. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  536. // }
  537. $episode['scenes'] = json_decode($episode['scenes'], true);
  538. // foreach($episode['scenes'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  540. // }
  541. // 获取分镜信息
  542. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  543. ->select('*')->get()->map(function ($value) {
  544. return (array)$value;
  545. })->toArray();
  546. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  547. $episode['acts'] = $segmentsStructure['acts'];
  548. $episode['total_duration'] = $segmentsStructure['total_duration'];
  549. return $episode;
  550. }
  551. public function segmentInfo($data) {
  552. $uid = Site::getUid();
  553. $segment_id = getProp($data, 'segment_id');
  554. if (!$segment_id) {
  555. Utils::throwError('1002:请选择分镜');
  556. }
  557. // 获取分镜信息
  558. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  559. // 验证用户权限
  560. if ($segment) {
  561. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  562. if (!$anime) Utils::throwError('20003:权限不足');
  563. }
  564. $result = [
  565. 'segment_id' => getProp($segment, 'segment_id'),
  566. 'segment_number' => getProp($segment, 'segment_number'),
  567. 'segment_content' => getProp($segment, 'segment_content'),
  568. 'description' => getProp($segment, 'description'),
  569. 'composition' => getProp($segment, 'composition'),
  570. 'camera_movement' => getProp($segment, 'camera_movement'),
  571. 'voice_actor' => getProp($segment, 'voice_actor'),
  572. 'dialogue' => getProp($segment, 'dialogue'),
  573. 'frame_type' => getProp($segment, 'frame_type'),
  574. 'scene' => getProp($segment, 'scene'),
  575. 'characters' => getProp($segment, 'characters'),
  576. 'tail_frame' => getProp($segment, 'tail_frame'),
  577. 'emotion' => getProp($segment, 'emotion'),
  578. 'emotion_type' => getProp($segment, 'emotion_type'),
  579. 'gender' => getProp($segment, 'gender'),
  580. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  581. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  582. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  583. 'pitch' => getProp($segment, 'pitch'),
  584. 'voice_name' => getProp($segment, 'voice_name'),
  585. 'voice_type' => getProp($segment, 'voice_type'),
  586. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  587. 'img_url' => getProp($segment, 'img_url'),
  588. 'video_url' => getProp($segment, 'video_url'),
  589. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  590. ];
  591. return $result;
  592. }
  593. public function copyEpisodeVersion($data) {
  594. $episode_id = getProp($data, 'episode_id');
  595. $uid = Site::getUid();
  596. $cpid = Site::getCpid();
  597. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  598. if (!$episode) Utils::throwError('20003:该剧集不存在');
  599. $episode = (array)$episode;
  600. $anime_id = $episode['anime_id'];
  601. $episode_number = $episode['episode_number'];
  602. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  603. $sequence = $count + 1;
  604. unset($episode['id']);
  605. $now = date('Y-m-d H:i:s');
  606. $episode['created_at'] = $now;
  607. $episode['updated_at'] = $now;
  608. $episode['is_default'] = 1;
  609. // 获取版本中含有"(副本"字样的个数
  610. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  611. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  612. $episode['sequence'] = $sequence;
  613. $episode['is_generated'] = 0;
  614. $episode['cpid'] = $cpid;
  615. // 获取ace_mode
  616. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  617. try {
  618. DB::beginTransaction();
  619. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  620. // 新增副本
  621. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  622. if (!$new_episode_id) {
  623. Utils::throwError('20003:创建副本失败!');
  624. }
  625. // 获取分镜数据并准备插入
  626. $segments_for_insert = DB::table('mp_episode_segments')
  627. ->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')
  628. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  629. $item = (array)$item;
  630. $item['episode_id'] = $new_episode_id;
  631. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  632. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  633. return $item;
  634. })->toArray();
  635. // 写入分镜数据
  636. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  637. if (!$boolen2) {
  638. Utils::throwError('20003:写入分镜数据失败!');
  639. }
  640. // 写入对话历史
  641. $records = [
  642. [
  643. 'uid' => $uid,
  644. 'anime_id' => $anime_id,
  645. 'role' => 'user',
  646. 'content' => '创建副本',
  647. 'sequence' => $episode_number,
  648. 'episode_id' => $new_episode_id,
  649. 'created_at' => $now,
  650. 'updated_at' => $now
  651. ],
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'assistant',
  656. 'content' => '好的,已为您创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ]
  662. ];
  663. $boolen3 = DB::table('mp_anime_records')->insert($records);
  664. if (!$boolen3) {
  665. Utils::throwError('20003:对话记录保存失败');
  666. }
  667. }catch (\Exception $e) {
  668. DB::rollBack();
  669. Utils::throwError('20003:'.$e->getMessage());
  670. }
  671. DB::commit();
  672. // 构建与 episodeInfo 方法一致的返回数据结构
  673. $result = [
  674. 'episode_id' => $new_episode_id,
  675. 'anime_id' => $anime_id,
  676. 'episode_number' => $episode_number,
  677. 'title' => $episode['title'],
  678. 'intro' => $episode['intro'],
  679. 'art_style' => $episode['art_style'],
  680. 'roles' => json_decode($episode['roles'], true),
  681. 'scenes' => json_decode($episode['scenes'], true),
  682. 'is_generated' => (int)$episode['is_generated']
  683. ];
  684. if ((int)$ace_mode === 1) {
  685. // 获取分镜信息
  686. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  687. ->select('*')->get()->map(function ($value) {
  688. return (array)$value;
  689. })->toArray();
  690. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  691. }else {
  692. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  693. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  694. }
  695. $result['acts'] = $segmentsStructure['acts'];
  696. $result['total_duration'] = $segmentsStructure['total_duration'];
  697. return $result;
  698. }
  699. public function episodeVersions($data) {
  700. $anime_id = getProp($data, 'anime_id');
  701. $episode_id = getProp($data, 'episode_id');
  702. if (!$anime_id || !$episode_id) {
  703. Utils::throwError('1002:请选择剧集');
  704. }
  705. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  706. $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) {
  707. return (array)$value;
  708. })->toArray();
  709. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  710. foreach($episodes as &$episode) {
  711. $episode['version'] = 'V'.$episode['sequence'];
  712. $episode['roles'] = json_decode($episode['roles'], true);
  713. $episode['scenes'] = json_decode($episode['scenes'], true);
  714. // 获取分镜信息
  715. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  716. ->select('*')->get()->map(function ($value) {
  717. return (array)$value;
  718. })->toArray();
  719. // 使用公共方法构建分镜结构
  720. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  721. $episode['acts'] = $segmentsStructure['acts'];
  722. $episode['total_duration'] = $segmentsStructure['total_duration'];
  723. }
  724. return $episodes;
  725. }
  726. public function bindEpisodeVersion($data) {
  727. $episode_id = getProp($data, 'episode_id');
  728. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  729. if (!$episode) Utils::throwError('20003:该剧集不存在');
  730. $episode = (array)$episode;
  731. if ((int)$episode['is_default'] === 1) return true;
  732. try {
  733. DB::beginTransaction();
  734. // 移除is_default标志
  735. $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')]);
  736. if (!$boolen) {
  737. Utils::throwError('20003:更新失败!');
  738. }
  739. // 绑定副本
  740. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  741. if (!$boolen2) {
  742. Utils::throwError('20003:绑定失败!');
  743. }
  744. }catch (\Exception $e) {
  745. DB::rollBack();
  746. Utils::throwError('20003:'.$e->getMessage());
  747. }
  748. DB::commit();
  749. return true;
  750. }
  751. public function chatChangeImg($data) {
  752. $segment_id = getProp($data, 'segment_id');
  753. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  754. $prompt = getProp($data, 'prompt');
  755. if (!$prompt || !$segment_id) {
  756. Utils::throwError('1002:请输入提示词,并且选择分镜');
  757. }
  758. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  759. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  760. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  761. else $ref_img_url = '';
  762. // $ref_img_url = '';
  763. if (empty($prompt)) {
  764. if (empty($ref_img_url)) {
  765. $prompt = getProp($segment, 'segment_content');
  766. }else {
  767. $prompt = '请根据图片生成';
  768. }
  769. }
  770. $anime_id = getProp($segment, 'anime_id');
  771. $episode_id = getProp($segment, 'episode_id');
  772. $episode_number = getProp($segment, 'episode_number');
  773. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  774. $ratio = getProp($data, 'ratio');
  775. if (!$ratio) {
  776. $ratio = getProp($episode, 'ratio');
  777. if (!$ratio) $ratio = '9:16';
  778. }
  779. $art_style = getProp($episode, 'art_style');
  780. if ($art_style) {
  781. $prompt = "美术风格:{$art_style}\n{$prompt}";
  782. }
  783. $dimensions = $this->getRatioDimensions($ratio);
  784. $width = $dimensions['width'];
  785. $height = $dimensions['height'];
  786. try {
  787. $params = [
  788. 'alias_segment_id' => $segment_id,
  789. 'prompt' => $prompt,
  790. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  791. 'width' => $width,
  792. 'height' => $height
  793. ];
  794. // 优化提示词(不要生成字幕)
  795. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  796. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  797. $task_id = $task->id;
  798. if (!$task_id) {
  799. Utils::throwError("20003:生成图片失败");
  800. }
  801. // 更新任务ID
  802. $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')]);
  803. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  804. } catch (\Exception $e) {
  805. Utils::throwError("20003:" . $e->getMessage());
  806. }
  807. // 创建任务之后先暂停10s等待异步任务完成
  808. sleep(10);
  809. $img_url = $this->loopGetPicTaskResult($task_id);
  810. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  811. // 图片生成后新增对话记录
  812. try {
  813. $uid = Site::getUid();
  814. $now = date('Y-m-d H:i:s');
  815. // 使用AI反推图片提示词
  816. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  817. // 保存对话记录
  818. $records = [
  819. [
  820. 'uid' => $uid,
  821. 'anime_id' => $anime_id,
  822. 'sequence' => $episode_number,
  823. 'role' => 'user',
  824. 'content' => $prompt,
  825. 'segment_id' => $segment_id,
  826. 'image_url' => '',
  827. 'created_at' => $now,
  828. 'updated_at' => $now
  829. ],
  830. [
  831. 'uid' => $uid,
  832. 'anime_id' => $anime_id,
  833. 'sequence' => $episode_number,
  834. 'role' => 'assistant',
  835. 'content' => $pic_prompt,
  836. 'segment_id' => $segment_id,
  837. 'image_url' => $img_url,
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ]
  841. ];
  842. DB::table('mp_anime_records')->insert($records);
  843. } catch (\Exception $e) {
  844. // 记录日志但不影响主流程
  845. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  846. 'segment_id' => $segment_id,
  847. 'img_url' => $img_url
  848. ]);
  849. logDB('anime', 'error', '保存对话记录失败', [
  850. 'segment_id' => $segment_id,
  851. 'img_url' => $img_url,
  852. 'error' => $e->getMessage()
  853. ]);
  854. }
  855. return $img_url;
  856. }
  857. public function segmentChatHistory($data) {
  858. $segment_id = getProp($data, 'segment_id');
  859. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  860. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  861. $chat = $query->orderBy('id')->get()->map(function ($value) {
  862. $value = (array)$value;
  863. $value['created_at'] = transDate($value['created_at']);
  864. return $value;
  865. })->toArray();
  866. // 获取历史图片
  867. $url = [];
  868. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  869. foreach($pic_history as $task) {
  870. $result_url = getProp($task, 'result_url');
  871. if (is_json($result_url)) {
  872. $url = array_merge($url, json_decode($result_url, true));
  873. }else {
  874. $url[] = $result_url;
  875. }
  876. }
  877. // 获取历史视频
  878. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  879. foreach($video_history as $task) {
  880. $result_url = getProp($task, 'compressed_url');
  881. if (is_json($result_url)) {
  882. $url = array_merge($url, json_decode($result_url, true));
  883. }else {
  884. $url[] = $result_url;
  885. }
  886. }
  887. return compact('chat', 'url');
  888. }
  889. public function changeEpisodeRoles($data) {
  890. $anime_id = getProp($data, 'anime_id');
  891. $episode_id = getProp($data, 'episode_id');
  892. $target_roles = getProp($data, 'roles');
  893. $is_deleted = getProp($data, 'is_deleted', 0);
  894. // 参数验证
  895. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  896. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  897. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  898. // 验证剧集是否存在
  899. $episode = DB::table('mp_anime_episodes')
  900. ->where('anime_id', $anime_id)
  901. ->where('id', $episode_id)
  902. ->first();
  903. if (!$episode) Utils::throwError('20003:该剧集不存在');
  904. $roles = json_decode(getProp($episode, 'roles'), true);
  905. // 获取anime信息,检查是否有关联的script_id
  906. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  907. if (!$anime) Utils::throwError('20003:动漫不存在');
  908. $script_id = getProp($anime, 'script_id');
  909. $episode_number = getProp($episode, 'episode_number', 1);
  910. $uid = Site::getUid();
  911. $cpid = Site::getCpid();
  912. try {
  913. $target_role_name = getProp($target_roles, 'role');
  914. // 如果是删除操作
  915. if ($is_deleted == 1) {
  916. // 从角色列表中移除该角色
  917. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  918. return getProp($role, 'role') !== $target_role_name;
  919. }));
  920. // 更新角色列表
  921. $result = DB::table('mp_anime_episodes')
  922. ->where('anime_id', $anime_id)
  923. ->where('id', $episode_id)
  924. ->update([
  925. 'roles' => json_encode($roles, 256),
  926. 'updated_at' => date('Y-m-d H:i:s')
  927. ]);
  928. if ($result === false) {
  929. Utils::throwError('20003:删除角色失败');
  930. }
  931. } else {
  932. // 新增或更新操作
  933. $role_found = false;
  934. $is_new_role = false;
  935. // 查找并更新已存在的角色
  936. foreach($roles as &$role) {
  937. if (getProp($role, 'role') === $target_role_name) {
  938. $role = $target_roles;
  939. $role_found = true;
  940. break;
  941. }
  942. }
  943. // 如果角色不存在,则新增
  944. if (!$role_found) {
  945. $roles[] = $target_roles;
  946. $is_new_role = true;
  947. }
  948. // 更新角色列表
  949. $result = DB::table('mp_anime_episodes')
  950. ->where('anime_id', $anime_id)
  951. ->where('id', $episode_id)
  952. ->update([
  953. 'roles' => json_encode($roles, 256),
  954. 'updated_at' => date('Y-m-d H:i:s')
  955. ]);
  956. if ($result === false) {
  957. Utils::throwError('20003:更新角色列表失败');
  958. }
  959. // 同步更新分镜表中对应主体的音色信息
  960. $voice_name = getProp($target_roles, 'voice_name');
  961. $voice_type = getProp($target_roles, 'voice_type');
  962. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  963. DB::table('mp_episode_segments')
  964. ->where('anime_id', $anime_id)
  965. ->where('episode_id', $episode_id)
  966. ->where('voice_actor', $target_role_name)
  967. ->update([
  968. 'voice_name' => $voice_name,
  969. 'voice_type' => $voice_type,
  970. 'voice_audio_url' => $voice_audio_url,
  971. 'updated_at' => date('Y-m-d H:i:s')
  972. ]);
  973. // 如果有关联的script_id,则同步到mp_products表
  974. if ($script_id) {
  975. // 查询剧本信息
  976. $script = DB::table('mp_scripts')
  977. ->where('id', $script_id)
  978. ->where('is_deleted', 0)
  979. ->first();
  980. if ($script) {
  981. $script_name = $script->script_name ?? 'script_' . $script_id;
  982. $product_name = getProp($target_roles, 'role');
  983. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  984. $url = getProp($target_roles, 'url', '');
  985. $product_type = 1; // 1=角色
  986. // 查找或创建以script_name命名的文件夹
  987. $folder = DB::table('mp_products')
  988. ->where('cpid', $cpid)
  989. ->where('type', 2) // 文件夹类型
  990. ->where('product', $product_type) // 角色类型
  991. ->where('product_name', $script_name)
  992. ->where('parent_id', 0)
  993. ->where('is_deleted', 0)
  994. ->first();
  995. if (!$folder) {
  996. // 创建文件夹
  997. $folder_id = DB::table('mp_products')->insertGetId([
  998. 'user_id' => $uid,
  999. 'cpid' => $cpid,
  1000. 'type' => 2, // 文件夹
  1001. 'product' => $product_type, // 角色类型
  1002. 'parent_id' => 0,
  1003. 'level' => 1,
  1004. 'product_name' => $script_name,
  1005. 'sort_order' => time(),
  1006. 'is_deleted' => 0,
  1007. 'created_at' => date('Y-m-d H:i:s'),
  1008. 'updated_at' => date('Y-m-d H:i:s')
  1009. ]);
  1010. } else {
  1011. $folder_id = $folder->id;
  1012. }
  1013. // 查找该文件夹下是否已存在同名资产
  1014. $existing_product = DB::table('mp_products')
  1015. ->where('cpid', $cpid)
  1016. ->where('type', 1) // 资产类型
  1017. ->where('product', $product_type)
  1018. ->where('parent_id', $folder_id)
  1019. ->where('product_name', $product_name)
  1020. ->where('is_deleted', 0)
  1021. ->first();
  1022. if ($existing_product) {
  1023. // 更新已存在的资产
  1024. $updateData = [
  1025. 'pic_task_status' => '生成成功',
  1026. ];
  1027. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1028. if ($url) $updateData['url'] = $url;
  1029. // 处理versions字段
  1030. $versions = getProp($target_roles, 'versions', []);
  1031. if ($versions && is_array($versions)) {
  1032. $updateData['versions'] = json_encode($versions, 256);
  1033. }
  1034. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1035. DB::table('mp_products')
  1036. ->where('id', $existing_product->id)
  1037. ->update($updateData);
  1038. $product_id = $existing_product->id;
  1039. } else {
  1040. // 创建新资产
  1041. $versions = getProp($target_roles, 'versions', []);
  1042. $product_id = DB::table('mp_products')->insertGetId([
  1043. 'user_id' => $uid,
  1044. 'cpid' => $cpid,
  1045. 'type' => 1, // 资产
  1046. 'product' => $product_type, // 角色
  1047. 'parent_id' => $folder_id,
  1048. 'level' => 2,
  1049. 'product_name' => $product_name,
  1050. 'url' => $url,
  1051. 'pic_prompt' => $pic_prompt,
  1052. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1053. 'sort_order' => time(),
  1054. 'is_deleted' => 0,
  1055. 'pic_task_status' => '生成成功',
  1056. 'created_at' => date('Y-m-d H:i:s'),
  1057. 'updated_at' => date('Y-m-d H:i:s')
  1058. ]);
  1059. }
  1060. // 建立或更新绑定关系
  1061. $existing_mapping = DB::table('mp_script_product_mappings')
  1062. ->where('script_id', $script_id)
  1063. ->where('product_id', $product_id)
  1064. ->where('episode_number', $episode_number)
  1065. ->first();
  1066. if (!$existing_mapping) {
  1067. // 创建绑定关系
  1068. DB::table('mp_script_product_mappings')->insert([
  1069. 'script_id' => $script_id,
  1070. 'product_id' => $product_id,
  1071. 'episode_number' => $episode_number,
  1072. 'created_at' => date('Y-m-d H:i:s'),
  1073. 'updated_at' => date('Y-m-d H:i:s')
  1074. ]);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. } catch (\Exception $e) {
  1080. dLog('anime')->error('更新剧集角色失败', [
  1081. 'anime_id' => $anime_id,
  1082. 'episode_id' => $episode_id,
  1083. 'error' => $e->getMessage()
  1084. ]);
  1085. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1086. }
  1087. return true;
  1088. }
  1089. public function changeEpisodeScenes($data) {
  1090. $anime_id = getProp($data, 'anime_id');
  1091. $episode_id = getProp($data, 'episode_id');
  1092. $target_scenes = getProp($data, 'scenes');
  1093. $is_deleted = getProp($data, 'is_deleted', 0);
  1094. // 参数验证
  1095. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1096. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1097. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1098. // 验证剧集是否存在
  1099. $episode = DB::table('mp_anime_episodes')
  1100. ->where('anime_id', $anime_id)
  1101. ->where('id', $episode_id)
  1102. ->first();
  1103. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1104. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1105. // 获取anime信息,检查是否有关联的script_id
  1106. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1107. if (!$anime) Utils::throwError('20003:动漫不存在');
  1108. $script_id = getProp($anime, 'script_id');
  1109. $episode_number = getProp($episode, 'episode_number', 1);
  1110. $uid = Site::getUid();
  1111. $cpid = Site::getCpid();
  1112. try {
  1113. $target_scene_name = getProp($target_scenes, 'scene');
  1114. // 如果是删除操作
  1115. if ($is_deleted == 1) {
  1116. // 从场景列表中移除该场景
  1117. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1118. return getProp($scene, 'scene') !== $target_scene_name;
  1119. }));
  1120. // 更新场景列表
  1121. $result = DB::table('mp_anime_episodes')
  1122. ->where('anime_id', $anime_id)
  1123. ->where('id', $episode_id)
  1124. ->update([
  1125. 'scenes' => json_encode($scenes, 256),
  1126. 'updated_at' => date('Y-m-d H:i:s')
  1127. ]);
  1128. if ($result === false) {
  1129. Utils::throwError('20003:删除场景失败');
  1130. }
  1131. } else {
  1132. // 新增或更新操作
  1133. $scene_found = false;
  1134. $is_new_scene = false;
  1135. // 查找并更新已存在的场景
  1136. foreach($scenes as &$scene) {
  1137. if (getProp($scene, 'scene') === $target_scene_name) {
  1138. $scene = $target_scenes;
  1139. $scene_found = true;
  1140. break;
  1141. }
  1142. }
  1143. // 如果场景不存在,则新增
  1144. if (!$scene_found) {
  1145. $scenes[] = $target_scenes;
  1146. $is_new_scene = true;
  1147. }
  1148. // 更新场景列表
  1149. $result = DB::table('mp_anime_episodes')
  1150. ->where('anime_id', $anime_id)
  1151. ->where('id', $episode_id)
  1152. ->update([
  1153. 'scenes' => json_encode($scenes, 256),
  1154. 'updated_at' => date('Y-m-d H:i:s')
  1155. ]);
  1156. if ($result === false) {
  1157. Utils::throwError('20003:更新场景列表失败');
  1158. }
  1159. // 如果有关联的script_id,则同步到mp_products表
  1160. if ($script_id) {
  1161. // 查询剧本信息
  1162. $script = DB::table('mp_scripts')
  1163. ->where('id', $script_id)
  1164. ->where('is_deleted', 0)
  1165. ->first();
  1166. if ($script) {
  1167. $script_name = $script->script_name ?? 'script_' . $script_id;
  1168. $product_name = getProp($target_scenes, 'scene');
  1169. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1170. $url = getProp($target_scenes, 'url', '');
  1171. $product_type = 2; // 2=场景
  1172. // 查找或创建以script_name命名的文件夹
  1173. $folder = DB::table('mp_products')
  1174. ->where('cpid', $cpid)
  1175. ->where('type', 2) // 文件夹类型
  1176. ->where('product', $product_type) // 场景类型
  1177. ->where('product_name', $script_name)
  1178. ->where('parent_id', 0)
  1179. ->where('is_deleted', 0)
  1180. ->first();
  1181. if (!$folder) {
  1182. // 创建文件夹
  1183. $folder_id = DB::table('mp_products')->insertGetId([
  1184. 'user_id' => $uid,
  1185. 'cpid' => $cpid,
  1186. 'type' => 2, // 文件夹
  1187. 'product' => $product_type, // 场景类型
  1188. 'parent_id' => 0,
  1189. 'level' => 1,
  1190. 'product_name' => $script_name,
  1191. 'sort_order' => time(),
  1192. 'is_deleted' => 0,
  1193. 'created_at' => date('Y-m-d H:i:s'),
  1194. 'updated_at' => date('Y-m-d H:i:s')
  1195. ]);
  1196. } else {
  1197. $folder_id = $folder->id;
  1198. }
  1199. // 查找该文件夹下是否已存在同名资产
  1200. $existing_product = DB::table('mp_products')
  1201. ->where('cpid', $cpid)
  1202. ->where('type', 1) // 资产类型
  1203. ->where('product', $product_type)
  1204. ->where('parent_id', $folder_id)
  1205. ->where('product_name', $product_name)
  1206. ->where('is_deleted', 0)
  1207. ->first();
  1208. if ($existing_product) {
  1209. // 更新已存在的资产
  1210. $updateData = [
  1211. 'pic_task_status' => '生成成功'
  1212. ];
  1213. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1214. if ($url) $updateData['url'] = $url;
  1215. // 处理versions字段
  1216. $versions = getProp($target_scenes, 'versions', []);
  1217. if ($versions && is_array($versions)) {
  1218. $updateData['versions'] = json_encode($versions, 256);
  1219. }
  1220. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1221. DB::table('mp_products')
  1222. ->where('id', $existing_product->id)
  1223. ->update($updateData);
  1224. $product_id = $existing_product->id;
  1225. } else {
  1226. // 创建新资产
  1227. $versions = getProp($target_scenes, 'versions', []);
  1228. $product_id = DB::table('mp_products')->insertGetId([
  1229. 'user_id' => $uid,
  1230. 'cpid' => $cpid,
  1231. 'type' => 1, // 资产
  1232. 'product' => $product_type, // 场景
  1233. 'parent_id' => $folder_id,
  1234. 'level' => 2,
  1235. 'product_name' => $product_name,
  1236. 'url' => $url,
  1237. 'pic_prompt' => $pic_prompt,
  1238. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1239. 'sort_order' => time(),
  1240. 'is_deleted' => 0,
  1241. 'pic_task_status' => '生成成功',
  1242. 'created_at' => date('Y-m-d H:i:s'),
  1243. 'updated_at' => date('Y-m-d H:i:s')
  1244. ]);
  1245. }
  1246. // 建立或更新绑定关系
  1247. $existing_mapping = DB::table('mp_script_product_mappings')
  1248. ->where('script_id', $script_id)
  1249. ->where('product_id', $product_id)
  1250. ->where('episode_number', $episode_number)
  1251. ->first();
  1252. if (!$existing_mapping) {
  1253. // 创建绑定关系
  1254. DB::table('mp_script_product_mappings')->insert([
  1255. 'script_id' => $script_id,
  1256. 'product_id' => $product_id,
  1257. 'episode_number' => $episode_number,
  1258. 'created_at' => date('Y-m-d H:i:s'),
  1259. 'updated_at' => date('Y-m-d H:i:s')
  1260. ]);
  1261. }
  1262. }
  1263. }
  1264. }
  1265. } catch (\Exception $e) {
  1266. dLog('anime')->error('更新剧集场景失败', [
  1267. 'anime_id' => $anime_id,
  1268. 'episode_id' => $episode_id,
  1269. 'error' => $e->getMessage()
  1270. ]);
  1271. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1272. }
  1273. return true;
  1274. }
  1275. public function editSegment($data) {
  1276. $segment_id = getProp($data, 'segment_id');
  1277. $segment_content = getProp($data, 'segment_content');
  1278. $image_url = getProp($data, 'image_url');
  1279. $video_url = getProp($data, 'video_url');
  1280. // 参数验证
  1281. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1282. // 验证分镜是否存在
  1283. $segment = DB::table('mp_episode_segments')
  1284. ->where('segment_id', $segment_id)
  1285. ->first();
  1286. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1287. $dubTaskId = 0;
  1288. try {
  1289. DB::beginTransaction();
  1290. // 准备更新数据
  1291. $update_data = [
  1292. 'updated_at' => date('Y-m-d H:i:s')
  1293. ];
  1294. if ($segment_content) {
  1295. // 先将segment_content赋值到update_data
  1296. $update_data['segment_content'] = $segment_content;
  1297. // 使用现有方法分析segment_content,提取各个字段
  1298. $this->handleSegmentContent($update_data);
  1299. // 如果有对话内容,创建视频配音合成任务
  1300. $dialogue = getProp($update_data, 'dialogue');
  1301. if (!empty($dialogue)) {
  1302. $now = date('Y-m-d H:i:s');
  1303. $generate_json = [
  1304. 'text' => $dialogue,
  1305. 'role' => getProp($update_data, 'voice_actor'),
  1306. 'voice_type' => getProp($update_data, 'voice_type'),
  1307. 'voice_name' => getProp($update_data, 'voice_name'),
  1308. 'emotion' => getProp($update_data, 'emotion'),
  1309. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1310. 'gender' => getProp($update_data, 'gender'),
  1311. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1312. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1313. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1314. 'pitch' => getProp($update_data, 'pitch', 0),
  1315. ];
  1316. // 插入视频配音合成任务
  1317. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1318. 'alias_segment_id' => $segment_id,
  1319. 'generate_status' => '执行中',
  1320. 'audio_url' => '',
  1321. 'generate_json' => json_encode($generate_json, 256),
  1322. 'created_at' => $now,
  1323. 'updated_at' => $now,
  1324. ]);
  1325. if (!$dubTaskId) {
  1326. Utils::throwError('20003:创建配音任务失败!');
  1327. }
  1328. $update_data['audio_url'] = '';
  1329. } else {
  1330. // dialogue为空时,直接写入默认音频信息
  1331. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1332. $update_data['audio_duration'] = 2.0;
  1333. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1334. }
  1335. }
  1336. if ($image_url) {
  1337. $update_data['img_url'] = $image_url;
  1338. // 同时写入一个简单的图片生成任务
  1339. $pic_task = [
  1340. 'alias_segment_id' => $segment_id,
  1341. 'ref_img_url' => json_encode([]),
  1342. 'status' => 'success',
  1343. 'result_url' => json_encode([$image_url], 256),
  1344. 'model' => '',
  1345. 'created_at' => date('Y-m-d H:i:s'),
  1346. 'updated_at' => date('Y-m-d H:i:s'),
  1347. ];
  1348. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1349. }
  1350. if ($video_url) {
  1351. $update_data['origin_video_url'] = $video_url;
  1352. $compressed_video_url = compressVideo($video_url);
  1353. $update_data['current_type'] = 2;
  1354. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1355. // 同时写入一个简单的视频生成任务
  1356. $video_task = [
  1357. 'alias_segment_id' => $segment_id,
  1358. 'status' => 'success',
  1359. 'result_url' => $update_data['origin_video_url'],
  1360. 'compressed_url' => $update_data['video_url'],
  1361. 'created_at' => date('Y-m-d H:i:s'),
  1362. 'updated_at' => date('Y-m-d H:i:s'),
  1363. ];
  1364. DB::table('mp_generate_video_tasks')->insert($video_task);
  1365. }
  1366. // 更新分镜信息
  1367. $result = DB::table('mp_episode_segments')
  1368. ->where('segment_id', $segment_id)
  1369. ->update($update_data);
  1370. if ($result === false) {
  1371. Utils::throwError('20003:更新分镜剧本失败');
  1372. }
  1373. DB::commit();
  1374. // 如果有创建音频生成任务则调用API
  1375. if ($dubTaskId) {
  1376. // 请求远程服务器执行生成
  1377. $client = new Client(['timeout' => 300, 'verify' => false]);
  1378. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1379. $response = $result->getBody()->getContents();
  1380. $response_arr = json_decode($response, true);
  1381. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1382. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1383. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1384. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1385. Utils::throwError('20003:火山生成音频失败');
  1386. }
  1387. }
  1388. return true;
  1389. } catch (\Exception $e) {
  1390. DB::rollBack();
  1391. dLog('anime')->error('更新分镜剧本失败', [
  1392. 'segment_id' => $segment_id,
  1393. 'error' => $e->getMessage()
  1394. ]);
  1395. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1396. }
  1397. }
  1398. public function batchSetSegmentPics($data) {
  1399. $anime_id = getProp($data, 'anime_id');
  1400. $episode_id = getProp($data, 'episode_id');
  1401. $ratio = getProp($data, 'ratio');
  1402. $dimensions = $this->getRatioDimensions($ratio);
  1403. $width = $dimensions['width'];
  1404. $height = $dimensions['height'];
  1405. if (!$anime_id || !$episode_id) {
  1406. Utils::throwError('1002:请选择剧集');
  1407. }
  1408. // 获取剧集信息
  1409. $episode = DB::table('mp_anime_episodes')
  1410. ->where('anime_id', $anime_id)
  1411. ->where('id', $episode_id)
  1412. ->where('is_default', 1)
  1413. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1414. ->first();
  1415. if (!$episode) {
  1416. Utils::throwError('20003:该剧集不存在');
  1417. }
  1418. $model = getProp($data, 'model');
  1419. if (!$model) {
  1420. $model = getProp($episode, 'image_model');
  1421. if (!$model) {
  1422. // episode表也没有,使用默认值
  1423. $model = 'doubao-seedream-5-0-lite-260128';
  1424. }
  1425. }
  1426. // 验证模型是否在可用模型表中
  1427. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1428. $model = 'doubao-seedream-5-0-lite-260128';
  1429. }
  1430. $roles = json_decode(getProp($episode, 'roles'), true);
  1431. if (!$roles) {
  1432. Utils::throwError('20003:角色信息格式错误');
  1433. }
  1434. // 构建角色名称到参考图的映射
  1435. $role_map = [];
  1436. foreach ($roles as $role) {
  1437. $role_name = getProp($role, 'role');
  1438. $role_url = getProp($role, 'url');
  1439. if (!empty($role_name) && !empty($role_url)) {
  1440. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1441. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1442. // $role_map[$base_name] = $role_url;
  1443. // 同时保存完整名称的映射
  1444. $role_map[$role_name] = $role_url;
  1445. }
  1446. }
  1447. $scenes = json_decode(getProp($episode, 'roles'), true);
  1448. if (!$scenes) {
  1449. Utils::throwError('20003:场景信息格式错误');
  1450. }
  1451. // 构建角色名称到参考图的映射
  1452. $scene_map = [];
  1453. foreach ($scenes as $scene) {
  1454. $scene_name = getProp($scene, 'scene');
  1455. $scene_url = getProp($scene, 'url');
  1456. if (!empty($scene_name) && !empty($scene_url)) {
  1457. $scene_map[$scene_name] = $scene_url;
  1458. }
  1459. }
  1460. // 获取所有分镜信息
  1461. $segments = DB::table('mp_episode_segments')
  1462. ->where('anime_id', $anime_id)
  1463. ->where('episode_id', $episode_id)
  1464. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1465. ->orderBy('segment_number')
  1466. ->get()
  1467. ->toArray();
  1468. if (empty($segments)) {
  1469. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1470. }
  1471. // 保存图片比例
  1472. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1473. $updated_segments = [];
  1474. $failed_segments = [];
  1475. // 批量为每个分镜生成图片任务
  1476. foreach ($segments as $segment) {
  1477. $segment_id = $segment->segment_id;
  1478. $segment_content = $segment->segment_content;
  1479. if (empty($segment_content)) {
  1480. $failed_segments[] = [
  1481. 'segment_id' => $segment_id,
  1482. 'error' => '分镜内容为空'
  1483. ];
  1484. continue;
  1485. }
  1486. try {
  1487. $dubTaskId = 0;
  1488. // 解析分镜内容,提取画面描述作为主要提示词
  1489. $prompt = $segment_content;
  1490. $ref_img_urls = [];
  1491. // 分镜场景
  1492. $scene = getProp($segment, 'scene');
  1493. $matched_scene = '';
  1494. if (isset($scene_map[$scene])) {
  1495. $img_index = count($ref_img_urls) + 1;
  1496. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1497. $ref_img_urls[] = $scene_map[$scene];
  1498. $matched_scene = $scene;
  1499. }
  1500. // 分镜角色
  1501. $characters = getProp($segment, 'characters');
  1502. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1503. $roles = explode(',', $characters);
  1504. // 从分镜内容中提取涉及的角色
  1505. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1506. // 获取匹配角色的参考图
  1507. foreach ($segment_characters as $character) {
  1508. if (isset($role_map[$character])) {
  1509. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1510. $img_index = count($ref_img_urls) + 1;
  1511. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1512. $ref_img_urls[] = $role_map[$character];
  1513. }
  1514. }
  1515. // 如果没有找到匹配的角色参考图,不使用参考图
  1516. if (empty($ref_img_urls)) {
  1517. $ref_img_urls = [];
  1518. }
  1519. // 准备生成任务参数
  1520. $params = [
  1521. 'model' => $model,
  1522. 'alias_segment_id' => $segment_id,
  1523. 'prompt' => $prompt,
  1524. 'ref_img_urls' => $ref_img_urls,
  1525. 'width' => $width,
  1526. 'height' => $height,
  1527. ];
  1528. // 优化提示词(不要生成字幕)
  1529. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1530. // $task_id = mt_rand(100000, 999999);
  1531. // 调用AI图片生成服务
  1532. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1533. $task_id = $task->id;
  1534. if (!$task_id) {
  1535. $failed_segments[] = [
  1536. 'segment_id' => $segment_id,
  1537. 'error' => '创建生成任务失败'
  1538. ];
  1539. continue;
  1540. }
  1541. $update_data = [
  1542. 'pic_task_id' => $task_id,
  1543. 'pic_task_status' => '生成中',
  1544. 'audio_url' => '',
  1545. 'updated_at' => date('Y-m-d H:i:s')
  1546. ];
  1547. // 如果有对话内容,创建视频配音合成任务
  1548. $dialogue = getProp($segment, 'dialogue');
  1549. if (!empty($dialogue)) {
  1550. $now = date('Y-m-d H:i:s');
  1551. $generate_json = [
  1552. 'text' => $dialogue,
  1553. 'role' => getProp($segment, 'voice_actor'),
  1554. 'voice_type' => getProp($segment, 'voice_type'),
  1555. 'voice_name' => getProp($segment, 'voice_name'),
  1556. 'emotion' => getProp($segment, 'emotion'),
  1557. 'emotion_type' => getProp($segment, 'emotion_type'),
  1558. 'gender' => getProp($segment, 'gender'),
  1559. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1560. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1561. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1562. 'pitch' => getProp($segment, 'pitch', 0),
  1563. ];
  1564. // 插入视频配音合成任务
  1565. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1566. 'alias_segment_id' => $segment_id,
  1567. 'generate_status' => '执行中',
  1568. 'audio_url' => '',
  1569. 'generate_json' => json_encode($generate_json, 256),
  1570. 'created_at' => $now,
  1571. 'updated_at' => $now,
  1572. ]);
  1573. if (!$dubTaskId) {
  1574. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1575. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1576. // Utils::throwError('20003:创建配音任务失败!');
  1577. }
  1578. } else {
  1579. // dialogue为空时,直接写入默认音频信息到分镜表
  1580. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1581. $update_data['audio_duration'] = 2.0;
  1582. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1583. }
  1584. // 更新分镜的任务信息
  1585. $update_result = DB::table('mp_episode_segments')
  1586. ->where('segment_id', $segment_id)
  1587. ->update($update_data);
  1588. // 如果是第一集的首帧图片,则存入待更新数组
  1589. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1590. Redis::sadd('anime_first_frame_urls', $segment_id);
  1591. }
  1592. if ($update_result) {
  1593. $updated_segments[] = [
  1594. 'segment_id' => $segment_id,
  1595. 'task_id' => $task_id,
  1596. 'status' => '生成中',
  1597. 'matched_scenes' => $matched_scene,
  1598. 'matched_roles' => $segment_characters,
  1599. 'ref_urls_count' => count($ref_img_urls)
  1600. ];
  1601. } else {
  1602. $failed_segments[] = [
  1603. 'segment_id' => $segment_id,
  1604. 'error' => '更新分镜任务状态失败'
  1605. ];
  1606. }
  1607. if ($dubTaskId) {
  1608. sleep(1);
  1609. // 请求远程服务器执行生成
  1610. $client = new Client(['timeout' => 300, 'verify' => false]);
  1611. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1612. $response = $result->getBody()->getContents();
  1613. $response_arr = json_decode($response, true);
  1614. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1615. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1616. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1617. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1618. }
  1619. }
  1620. } catch (\Exception $e) {
  1621. $failed_segments[] = [
  1622. 'segment_id' => $segment_id,
  1623. 'error' => $e->getMessage()
  1624. ];
  1625. }
  1626. }
  1627. // 更新剧集生成状态
  1628. if (!empty($updated_segments)) {
  1629. DB::table('mp_anime_episodes')
  1630. ->where('id', $episode_id)
  1631. ->update([
  1632. 'is_generated' => 1,
  1633. 'updated_at' => date('Y-m-d H:i:s')
  1634. ]);
  1635. }
  1636. return [
  1637. 'success_count' => count($updated_segments),
  1638. 'failed_count' => count($failed_segments),
  1639. 'success_segments' => $updated_segments,
  1640. 'failed_segments' => $failed_segments,
  1641. 'total_segments' => count($segments)
  1642. ];
  1643. }
  1644. public function reGenerateSegment($data) {
  1645. $segment_id = getProp($data, 'segment_id');
  1646. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1647. $anime_id = getProp($segment, 'anime_id');
  1648. $episode_id = getProp($segment, 'episode_id');
  1649. $episode_number = getProp($segment, 'episode_number');
  1650. $segment_content = getProp($data, 'segment_content');
  1651. $ratio = getProp($data, 'ratio');
  1652. if (!$ratio) {
  1653. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1654. if (!$ratio) $ratio = '9:16';
  1655. }
  1656. $dimensions = $this->getRatioDimensions($ratio);
  1657. $width = $dimensions['width'];
  1658. $height = $dimensions['height'];
  1659. if (!$anime_id || !$episode_id) {
  1660. Utils::throwError('1002:请选择分镜');
  1661. }
  1662. // 使用文生文模型重新解析segment_content
  1663. if (!empty($segment_content)) {
  1664. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1665. }
  1666. // 获取动漫的角色信息(包含参考图)
  1667. $anime = DB::table('mp_animes')
  1668. ->where('id', $anime_id)
  1669. ->select('roles', 'scenes')
  1670. ->first();
  1671. if (!$anime || !$anime->roles) {
  1672. Utils::throwError('20003:未找到角色信息');
  1673. }
  1674. $roles = json_decode($anime->roles, true);
  1675. if (!$roles) {
  1676. Utils::throwError('20003:角色信息格式错误');
  1677. }
  1678. // 构建角色名称到参考图的映射
  1679. $role_map = [];
  1680. foreach ($roles as $role) {
  1681. $role_name = getProp($role, 'role');
  1682. $role_url = getProp($role, 'url');
  1683. if (!empty($role_name) && !empty($role_url)) {
  1684. $role_map[$role_name] = $role_url;
  1685. }
  1686. }
  1687. $scenes = json_decode($anime->scenes, true);
  1688. if (!$scenes) {
  1689. Utils::throwError('20003:角色信息格式错误');
  1690. }
  1691. // 构建角色名称到参考图的映射
  1692. $scene_map = [];
  1693. foreach ($scenes as $scene) {
  1694. $scene_name = getProp($scene, 'scene');
  1695. $scene_url = getProp($scene, 'url');
  1696. if (!empty($scene_name) && !empty($scene_url)) {
  1697. $scene_map[$scene_name] = $scene_url;
  1698. }
  1699. }
  1700. $segment_id = $segment->segment_id;
  1701. $original_segment_content = $segment->segment_content;
  1702. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1703. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1704. if (empty($final_segment_content)) {
  1705. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1706. }
  1707. try {
  1708. $dubTaskId = 0;
  1709. // 分镜剧本数组
  1710. $update_data = [
  1711. 'segment_content' => $final_segment_content,
  1712. 'pic_task_status' => '生成中',
  1713. 'updated_at' => date('Y-m-d H:i:s')
  1714. ];
  1715. // 解析分镜内容,提取画面描述作为主要提示词
  1716. $prompt = $final_segment_content;
  1717. $ref_img_urls = [];
  1718. // 分镜场景
  1719. $scene = getProp($data, 'scene');
  1720. if ($scene) {
  1721. $matched_scene = '';
  1722. if (isset($scene_map[$scene])) {
  1723. $img_index = count($ref_img_urls) + 1;
  1724. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1725. $ref_img_urls[] = $scene_map[$scene];
  1726. $matched_scene = $scene;
  1727. }
  1728. $update_data['scene'] = $scene;
  1729. }
  1730. // 分镜角色
  1731. $characters = getProp($data, 'characters');
  1732. if ($characters) {
  1733. $update_data['characters'] = $characters;
  1734. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1735. $characters = explode(',', $characters);
  1736. // 从分镜内容中提取涉及的角色
  1737. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1738. // 获取匹配角色的参考图
  1739. foreach ($segment_characters as $character) {
  1740. if (isset($role_map[$character])) {
  1741. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1742. $img_index = count($ref_img_urls) + 1;
  1743. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1744. $ref_img_urls[] = $role_map[$character];
  1745. }
  1746. }
  1747. }
  1748. // 如果没有找到匹配的角色参考图,不使用参考图
  1749. if (empty($ref_img_urls)) {
  1750. $ref_img_urls = [];
  1751. }
  1752. // 准备生成任务参数
  1753. $params = [
  1754. 'alias_segment_id' => $segment_id,
  1755. 'prompt' => $prompt,
  1756. 'ref_img_urls' => $ref_img_urls,
  1757. 'width' => $width,
  1758. 'height' => $height,
  1759. ];
  1760. // 优化提示词(不要生成字幕)
  1761. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1762. // 调用AI图片生成服务
  1763. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1764. $task_id = $task->id;
  1765. if (!$task_id) {
  1766. Utils::throwError('20003:创建生成任务失败!');
  1767. }
  1768. $update_data['pic_task_id'] = $task_id;
  1769. // 更新分镜剧本信息
  1770. $this->handleSegmentContent($update_data);
  1771. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1772. if ($segment_content) {
  1773. $dialogue = getProp($update_data, 'dialogue');
  1774. if (!empty($dialogue)) {
  1775. $now = date('Y-m-d H:i:s');
  1776. $generate_json = [
  1777. 'text' => $dialogue,
  1778. 'role' => getProp($update_data, 'voice_actor'),
  1779. 'voice_type' => getProp($update_data, 'voice_type'),
  1780. 'voice_name' => getProp($update_data, 'voice_name'),
  1781. 'emotion' => getProp($update_data, 'emotion'),
  1782. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1783. 'gender' => getProp($update_data, 'gender'),
  1784. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1785. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1786. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1787. 'pitch' => getProp($update_data, 'pitch', 0),
  1788. ];
  1789. // 插入视频配音合成任务
  1790. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1791. 'alias_segment_id' => $segment_id,
  1792. 'generate_status' => '执行中',
  1793. 'audio_url' => '',
  1794. 'generate_json' => json_encode($generate_json, 256),
  1795. 'created_at' => date('Y-m-d H:i:s'),
  1796. 'updated_at' => date('Y-m-d H:i:s'),
  1797. ]);
  1798. if (!$dubTaskId) {
  1799. Utils::throwError('20003:创建配音任务失败!');
  1800. }
  1801. $update_data['audio_url'] = '';
  1802. } else {
  1803. // dialogue为空时,直接写入默认音频信息
  1804. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1805. $update_data['audio_duration'] = 2.0;
  1806. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1807. }
  1808. }
  1809. $boolen = DB::table('mp_episode_segments')
  1810. ->where('segment_id', $segment_id)
  1811. ->update($update_data);
  1812. // 如果是第一集的首帧图片,则存入待更新数组
  1813. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1814. Redis::sadd('anime_first_frame_urls', $segment_id);
  1815. }
  1816. if ($dubTaskId) {
  1817. // 请求远程服务器执行生成
  1818. $client = new Client(['timeout' => 300, 'verify' => false]);
  1819. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1820. $response = $result->getBody()->getContents();
  1821. $response_arr = json_decode($response, true);
  1822. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1823. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1824. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1825. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1826. Utils::throwError('20003:火山生成音频失败');
  1827. }
  1828. }
  1829. } catch (\Exception $e) {
  1830. $failed_segments[] = [
  1831. 'segment_id' => $segment_id,
  1832. 'error' => $e->getMessage()
  1833. ];
  1834. }
  1835. // 创建任务之后先暂停10s等待异步任务完成
  1836. sleep(10);
  1837. $img_url = $this->loopGetPicTaskResult($task_id);
  1838. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  1839. // 图片生成后新增对话记录
  1840. try {
  1841. $uid = Site::getUid();
  1842. $now = date('Y-m-d H:i:s');
  1843. // 使用AI反推图片提示词
  1844. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  1845. // 保存对话记录
  1846. $records = [
  1847. [
  1848. 'uid' => $uid,
  1849. 'anime_id' => $anime_id,
  1850. 'sequence' => $episode_number,
  1851. 'role' => 'user',
  1852. 'content' => '重新生成',
  1853. 'segment_id' => $segment_id,
  1854. 'image_url' => '',
  1855. 'created_at' => $now,
  1856. 'updated_at' => $now
  1857. ],
  1858. [
  1859. 'uid' => $uid,
  1860. 'anime_id' => $anime_id,
  1861. 'sequence' => $episode_number,
  1862. 'role' => 'assistant',
  1863. 'content' => $pic_prompt,
  1864. 'segment_id' => $segment_id,
  1865. 'image_url' => $img_url,
  1866. 'created_at' => $now,
  1867. 'updated_at' => $now
  1868. ]
  1869. ];
  1870. DB::table('mp_anime_records')->insert($records);
  1871. } catch (\Exception $e) {
  1872. // 记录日志但不影响主流程
  1873. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  1874. 'segment_id' => $segment_id,
  1875. 'img_url' => $img_url
  1876. ]);
  1877. }
  1878. return $img_url;
  1879. }
  1880. public function addSegment($data) {
  1881. $prev_segment_id = getProp($data, 'prev_segment_id');
  1882. $img_url = getProp($data, 'img_url');
  1883. $video_url = getProp($data, 'video_url');
  1884. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  1885. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1886. $anime_id = getProp($segment, 'anime_id');
  1887. $episode_id = getProp($segment, 'episode_id');
  1888. $episode_number = getProp($segment, 'episode_number');
  1889. $segment_number = getProp($segment, 'segment_number');
  1890. $new_segment_number = $segment_number + 1;
  1891. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1892. // 分镜剧本数组
  1893. $insert_data = [
  1894. 'anime_id' => $anime_id,
  1895. 'episode_id' => $episode_id,
  1896. 'episode_number' => $episode_number,
  1897. 'act_number' => getProp($segment, 'act_number'),
  1898. 'act_title' => getProp($segment, 'act_title'),
  1899. 'segment_id' => $segment_id,
  1900. 'segment_number' => $new_segment_number,
  1901. 'segment_content' => '',
  1902. 'img_url' => '',
  1903. 'video_url' => '',
  1904. 'created_at' => date('Y-m-d H:i:s'),
  1905. 'updated_at' => date('Y-m-d H:i:s')
  1906. ];
  1907. if ($img_url) $insert_data['img_url'] = $img_url;
  1908. if ($video_url) {
  1909. $insert_data['origin_video_url'] = $video_url;
  1910. $insert_data['current_type'] = 2;
  1911. $compressed_video_url = compressVideo($video_url);
  1912. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  1913. }
  1914. try {
  1915. DB::beginTransaction();
  1916. // 先更新序号
  1917. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  1918. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  1919. if (!$id) {
  1920. Utils::throwError('20003:新增分镜失败!');
  1921. }
  1922. }catch (\Exception $e) {
  1923. DB::rollBack();
  1924. Utils::throwError('20003:'.$e->getMessage());
  1925. }
  1926. DB::commit();
  1927. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  1928. $segment = $segment ? (array)$segment : [];
  1929. return $segment;
  1930. // 以下代码暂弃用
  1931. $anime_id = getProp($segment, 'anime_id');
  1932. $episode_id = getProp($segment, 'episode_id');
  1933. $episode_number = getProp($segment, 'episode_number');
  1934. $segment_number = getProp($segment, 'segment_number');
  1935. $segment_content = getProp($data, 'segment_content');
  1936. $img_url = getProp($data, 'img_url');
  1937. $video_url = getProp($data, 'video_url');
  1938. $ratio = getProp($data, 'ratio');
  1939. $dimensions = $this->getRatioDimensions($ratio);
  1940. $width = $dimensions['width'];
  1941. $height = $dimensions['height'];
  1942. if (!$anime_id || !$episode_id) {
  1943. Utils::throwError('1002:请选择分镜');
  1944. }
  1945. // 使用文生文模型重新解析segment_content
  1946. if (!empty($segment_content)) {
  1947. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1948. }
  1949. // 获取动漫的角色信息(包含参考图)
  1950. $anime = DB::table('mp_animes')
  1951. ->where('id', $anime_id)
  1952. ->select('roles', 'scenes')
  1953. ->first();
  1954. if (!$anime || !$anime->roles) {
  1955. Utils::throwError('20003:未找到角色信息');
  1956. }
  1957. $roles = json_decode($anime->roles, true);
  1958. if (!$roles) {
  1959. Utils::throwError('20003:角色信息格式错误');
  1960. }
  1961. // 构建角色名称到参考图的映射
  1962. $role_map = [];
  1963. foreach ($roles as $role) {
  1964. $role_name = getProp($role, 'role');
  1965. $role_url = getProp($role, 'url');
  1966. if (!empty($role_name) && !empty($role_url)) {
  1967. $role_map[$role_name] = $role_url;
  1968. }
  1969. }
  1970. $scenes = json_decode($anime->scenes, true);
  1971. if (!$scenes) {
  1972. Utils::throwError('20003:角色信息格式错误');
  1973. }
  1974. // 构建角色名称到参考图的映射
  1975. $scene_map = [];
  1976. foreach ($scenes as $scene) {
  1977. $scene_name = getProp($scene, 'scene');
  1978. $scene_url = getProp($scene, 'url');
  1979. if (!empty($scene_name) && !empty($scene_url)) {
  1980. $scene_map[$scene_name] = $scene_url;
  1981. }
  1982. }
  1983. $segment_id = $segment->segment_id;
  1984. $original_segment_content = $segment->segment_content;
  1985. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1986. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1987. if (empty($final_segment_content)) {
  1988. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1989. }
  1990. try {
  1991. $dubTaskId = 0;
  1992. DB::beginTransaction();
  1993. $new_segment_number = $segment_number + 1;
  1994. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1995. // 分镜剧本数组
  1996. $insert_data = [
  1997. 'anime_id' => $anime_id,
  1998. 'episode_id' => $episode_id,
  1999. 'episode_number' => $episode_number,
  2000. 'act_number' => getProp($segment, 'act_number'),
  2001. 'act_title' => getProp($segment, 'act_title'),
  2002. 'segment_id' => $segment_id,
  2003. 'segment_number' => $new_segment_number,
  2004. 'segment_content' => $final_segment_content,
  2005. 'img_url' => $img_url,
  2006. 'video_url' => $video_url,
  2007. 'created_at' => date('Y-m-d H:i:s'),
  2008. 'updated_at' => date('Y-m-d H:i:s')
  2009. ];
  2010. // 更新分镜剧本信息
  2011. $this->handleSegmentContent($insert_data);
  2012. // 如果有对话内容,创建视频配音合成任务
  2013. $dialogue = getProp($insert_data, 'dialogue');
  2014. if (!empty($dialogue)) {
  2015. $now = date('Y-m-d H:i:s');
  2016. $generate_json = [
  2017. 'text' => $dialogue,
  2018. 'role' => getProp($insert_data, 'voice_actor'),
  2019. 'voice_type' => getProp($insert_data, 'voice_type'),
  2020. 'voice_name' => getProp($insert_data, 'voice_name'),
  2021. 'emotion' => getProp($insert_data, 'emotion'),
  2022. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2023. 'gender' => getProp($insert_data, 'gender'),
  2024. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2025. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2026. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2027. 'pitch' => getProp($insert_data, 'pitch', 0),
  2028. ];
  2029. // 插入视频配音合成任务
  2030. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2031. 'alias_segment_id' => $segment_id,
  2032. 'generate_status' => '执行中',
  2033. 'audio_url' => '',
  2034. 'generate_json' => json_encode($generate_json, 256),
  2035. 'created_at' => $now,
  2036. 'updated_at' => $now,
  2037. ]);
  2038. if (!$dubTaskId) {
  2039. Utils::throwError('20003:创建配音任务失败!');
  2040. }
  2041. $insert_data['audio_url'] = '';
  2042. } else {
  2043. // dialogue为空时,直接写入默认音频信息
  2044. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2045. $insert_data['audio_duration'] = 2.0;
  2046. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2047. }
  2048. // 如果没有上传图片则使用当前描述进行生成
  2049. if (!$img_url) {
  2050. // 解析分镜内容,提取画面描述作为主要提示词
  2051. $prompt = $final_segment_content;
  2052. $ref_img_urls = [];
  2053. // 分镜场景
  2054. $scene = getProp($insert_data, 'scene');
  2055. if ($scene) {
  2056. $matched_scene = '';
  2057. if (isset($scene_map[$scene])) {
  2058. $img_index = count($ref_img_urls) + 1;
  2059. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2060. $ref_img_urls[] = $scene_map[$scene];
  2061. $matched_scene = $scene;
  2062. }
  2063. $update_data['scene'] = $scene;
  2064. }
  2065. // 分镜角色
  2066. $characters = getProp($insert_data, 'characters');
  2067. if ($characters) {
  2068. $update_data['characters'] = $characters;
  2069. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2070. $characters = explode(',', $characters);
  2071. // 从分镜内容中提取涉及的角色
  2072. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2073. // 获取匹配角色的参考图
  2074. foreach ($segment_characters as $character) {
  2075. if (isset($role_map[$character])) {
  2076. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2077. $img_index = count($ref_img_urls) + 1;
  2078. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2079. $ref_img_urls[] = $role_map[$character];
  2080. }
  2081. }
  2082. }
  2083. // 如果没有找到匹配的角色参考图,不使用参考图
  2084. if (empty($ref_img_urls)) {
  2085. $ref_img_urls = [];
  2086. }
  2087. // 准备生成任务参数
  2088. $params = [
  2089. 'alias_segment_id' => $segment_id,
  2090. 'prompt' => $prompt,
  2091. 'ref_img_urls' => $ref_img_urls,
  2092. 'width' => $width,
  2093. 'height' => $height,
  2094. ];
  2095. // 调用AI图片生成服务
  2096. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2097. $task_id = $task->id;
  2098. // $task_id = 'whatever';
  2099. if (!$task_id) {
  2100. Utils::throwError('20003:创建生成任务失败!');
  2101. }
  2102. $insert_data['pic_task_status'] = '生成中';
  2103. $insert_data['pic_task_id'] = $task_id;
  2104. }
  2105. // 先更新序号
  2106. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2107. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2108. if (!$boolen) {
  2109. Utils::throwError('20003:新增分镜失败!');
  2110. }
  2111. // 如果是第一集的首帧图片,则存入待更新数组
  2112. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2113. Redis::sadd('anime_first_frame_urls', $segment_id);
  2114. }
  2115. if ($dubTaskId) {
  2116. // 请求远程服务器执行生成
  2117. $client = new Client(['timeout' => 300, 'verify' => false]);
  2118. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2119. $response = $result->getBody()->getContents();
  2120. $response_arr = json_decode($response, true);
  2121. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2122. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2123. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2124. Utils::throwError('20003:火山生成音频失败');
  2125. }
  2126. }
  2127. } catch (\Exception $e) {
  2128. DB::rollBack();
  2129. Utils::throwError('20003:'.$e->getMessage());
  2130. }
  2131. DB::commit();
  2132. // 创建任务之后先暂停10s等待异步任务完成
  2133. sleep(10);
  2134. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2135. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2136. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2137. $segment = $segment ? (array)$segment : [];
  2138. return $segment;
  2139. }
  2140. public function copySegment($data) {
  2141. $segment_id = getProp($data, 'segment_id');
  2142. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2143. if (!$segment) Utils::throwError('20003:请选择分镜');
  2144. $anime_id = getProp($segment, 'anime_id');
  2145. $episode_id = getProp($segment, 'episode_id');
  2146. $episode_number = getProp($segment, 'episode_number');
  2147. $segment_number = getProp($segment, 'segment_number');
  2148. $new_segment_id = 0;
  2149. try {
  2150. DB::beginTransaction();
  2151. $segment = (array)$segment;
  2152. unset($segment['id']);
  2153. $segment['segment_number'] += 1;
  2154. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2155. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2156. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2157. // 更新其他分镜序号
  2158. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2159. // 复制分镜
  2160. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2161. if (!$id) {
  2162. Utils::throwError('20003:复制分镜失败');
  2163. }
  2164. }catch (\Exception $e) {
  2165. DB::rollBack();
  2166. Utils::throwError('20003:'.$e->getMessage());
  2167. }
  2168. DB::commit();
  2169. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2170. $segment = $segment ? (array)$segment : [];
  2171. return $segment;
  2172. }
  2173. public function moveSegment($data) {
  2174. $segment_id = getProp($data, 'segment_id');
  2175. $target_segment_id = getProp($data, 'target_segment_id');
  2176. // 获取源分镜信息
  2177. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2178. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2179. // 获取目标分镜信息
  2180. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2181. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2182. $anime_id = getProp($source_segment, 'anime_id');
  2183. $episode_id = getProp($source_segment, 'episode_id');
  2184. $episode_number = getProp($source_segment, 'episode_number');
  2185. $source_segment_number = getProp($source_segment, 'segment_number');
  2186. $target_segment_number = getProp($target_segment, 'segment_number');
  2187. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2188. $target_anime_id = getProp($target_segment, 'anime_id');
  2189. $target_episode_number = getProp($target_segment, 'episode_number');
  2190. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2191. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2192. }
  2193. // 如果源分镜和目标分镜相同,无需移动
  2194. if ($source_segment_number == $target_segment_number) {
  2195. return true;
  2196. }
  2197. try {
  2198. DB::beginTransaction();
  2199. if ($source_segment_number < $target_segment_number) {
  2200. // 向后移动:源分镜移动到目标分镜之后
  2201. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2202. DB::table('mp_episode_segments')
  2203. ->where('anime_id', $anime_id)
  2204. ->where('episode_id', $episode_id)
  2205. ->where('segment_number', '>', $source_segment_number)
  2206. ->where('segment_number', '<=', $target_segment_number)
  2207. ->decrement('segment_number');
  2208. // 2. 将源分镜移动到目标分镜之后
  2209. $new_segment_number = $target_segment_number;
  2210. } else {
  2211. // 向前移动:源分镜移动到目标分镜之后
  2212. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2213. DB::table('mp_episode_segments')
  2214. ->where('anime_id', $anime_id)
  2215. ->where('episode_id', $episode_id)
  2216. ->where('segment_number', '>', $target_segment_number)
  2217. ->where('segment_number', '<', $source_segment_number)
  2218. ->increment('segment_number');
  2219. // 2. 将源分镜移动到目标分镜之后
  2220. $new_segment_number = $target_segment_number + 1;
  2221. }
  2222. // 3. 更新源分镜的序号
  2223. $update_result = DB::table('mp_episode_segments')
  2224. ->where('segment_id', $segment_id)
  2225. ->update([
  2226. 'segment_number' => $new_segment_number,
  2227. 'updated_at' => date('Y-m-d H:i:s')
  2228. ]);
  2229. if (!$update_result) {
  2230. Utils::throwError('20003:更新分镜序号失败');
  2231. }
  2232. DB::commit();
  2233. return true;
  2234. } catch (\Exception $e) {
  2235. DB::rollBack();
  2236. Utils::throwError('20003:' . $e->getMessage());
  2237. }
  2238. }
  2239. public function delSegment($data) {
  2240. $segment_id = getProp($data, 'segment_id');
  2241. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2242. if (!$segment) Utils::throwError('20003:请选择分镜');
  2243. $anime_id = getProp($segment, 'anime_id');
  2244. $episode_id = getProp($segment, 'episode_id');
  2245. $episode_number = getProp($segment, 'episode_number');
  2246. $segment_number = getProp($segment, 'segment_number');
  2247. try {
  2248. DB::beginTransaction();
  2249. // 删除分镜
  2250. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2251. if (!$boolen) {
  2252. Utils::throwError('20003:删除分镜失败');
  2253. }
  2254. // 更新其他分镜序号
  2255. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2256. }catch (\Exception $e) {
  2257. DB::rollBack();
  2258. Utils::throwError('20003:'.$e->getMessage());
  2259. }
  2260. DB::commit();
  2261. return true;
  2262. }
  2263. public function applySegment($data) {
  2264. $segment_id = getProp($data, 'segment_id');
  2265. $url = getProp($data, 'url');
  2266. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2267. if (!$url) Utils::throwError('20003:URL不能为空');
  2268. // 获取URL的文件扩展名
  2269. $urlPath = parse_url($url, PHP_URL_PATH);
  2270. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2271. // 定义图片和视频的扩展名
  2272. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2273. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2274. // 判断是图片还是视频
  2275. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2276. if (in_array($extension, $imageExtensions)) {
  2277. // 图片类型
  2278. $updateData['img_url'] = $url;
  2279. $updateData['current_type'] = 1;
  2280. } elseif (in_array($extension, $videoExtensions)) {
  2281. // 视频类型
  2282. $updateData['video_url'] = $url;
  2283. $updateData['current_type'] = 2;
  2284. } else {
  2285. Utils::throwError('20003:不支持的文件类型');
  2286. }
  2287. // 更新分镜表
  2288. $result = DB::table('mp_episode_segments')
  2289. ->where('segment_id', $segment_id)
  2290. ->update($updateData);
  2291. if (!$result) {
  2292. Utils::throwError('20003:更新分镜失败');
  2293. }
  2294. return true;
  2295. }
  2296. public function segmentHistory($data) {
  2297. $segment_id = getProp($data, 'segment_id');
  2298. // 获取历史图片
  2299. $pics = [];
  2300. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2301. foreach($pic_history as $task) {
  2302. $result_url = getProp($task, 'result_url');
  2303. if (is_json($result_url)) {
  2304. $pics = array_merge($pics, json_decode($result_url, true));
  2305. }else {
  2306. $pics[] = $result_url;
  2307. }
  2308. }
  2309. // 获取历史视频
  2310. $videos = [];
  2311. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2312. foreach($video_history as $task) {
  2313. $result_url = getProp($task, 'result_url');
  2314. if (is_json($result_url)) {
  2315. $videos = array_merge($videos, json_decode($result_url, true));
  2316. }else {
  2317. $videos[] = $result_url;
  2318. }
  2319. }
  2320. return compact('pics', 'videos');
  2321. }
  2322. public function addAct($data) {
  2323. $prev_act_id = getProp($data, 'prev_act_id');
  2324. $act_title = getProp($data, 'act_title', '');
  2325. $act_content = getProp($data, 'act_content', '');
  2326. $act_duration = getProp($data, 'act_duration', 5);
  2327. $video_url = getProp($data, 'video_url');
  2328. // 根据prev_act_id获取记录
  2329. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2330. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2331. $anime_id = getProp($prev_segment, 'anime_id');
  2332. $episode_id = getProp($prev_segment, 'episode_id');
  2333. $episode_number = getProp($prev_segment, 'episode_number');
  2334. $prev_act_number = getProp($prev_segment, 'act_number');
  2335. // 获取新的act_number
  2336. $new_act_number = $prev_act_number + 1;
  2337. try {
  2338. DB::beginTransaction();
  2339. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2340. DB::table('mp_episode_segments')
  2341. ->where('anime_id', $anime_id)
  2342. ->where('episode_id', $episode_id)
  2343. ->where('act_number', '>', $prev_act_number)
  2344. ->increment('act_number');
  2345. // 插入新片段记录
  2346. $insert_data = [
  2347. 'anime_id' => $anime_id,
  2348. 'episode_id' => $episode_id,
  2349. 'episode_number' => $episode_number,
  2350. 'act_number' => $new_act_number,
  2351. 'created_at' => date('Y-m-d H:i:s'),
  2352. 'updated_at' => date('Y-m-d H:i:s')
  2353. ];
  2354. if ($act_title) {
  2355. $insert_data['act_title'] = $act_title;
  2356. }
  2357. if ($act_content) {
  2358. $insert_data['act_content'] = $act_content;
  2359. }
  2360. if ($act_duration) {
  2361. $insert_data['act_duration'] = $act_duration;
  2362. }
  2363. if ($video_url) {
  2364. $insert_data['origin_video_url'] = $video_url;
  2365. $insert_data['current_type'] = 2;
  2366. $compressed_video_url = compressVideo($video_url);
  2367. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2368. }
  2369. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2370. if (!$id) {
  2371. Utils::throwError('20003:新增片段失败!');
  2372. }
  2373. DB::commit();
  2374. }catch (\Exception $e) {
  2375. DB::rollBack();
  2376. Utils::throwError('20003:'.$e->getMessage());
  2377. }
  2378. $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();
  2379. $segment = $segment ? (array)$segment : [];
  2380. return $segment;
  2381. }
  2382. public function editAct($data) {
  2383. $act_id = getProp($data, 'act_id');
  2384. $act_content = getProp($data, 'act_content');
  2385. $act_duration = getProp($data, 'act_duration');
  2386. $act_title = getProp($data, 'act_title');
  2387. $image_url = getProp($data, 'image_url');
  2388. $video_url = getProp($data, 'video_url');
  2389. // 参数验证
  2390. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2391. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2392. $segment = DB::table('mp_episode_segments')
  2393. ->where('id', $act_id)
  2394. ->first();
  2395. if (!$segment) Utils::throwError('20003:该片段不存在');
  2396. try {
  2397. DB::beginTransaction();
  2398. // 准备更新数据
  2399. $update_data = [
  2400. 'updated_at' => date('Y-m-d H:i:s')
  2401. ];
  2402. // 更新act相关字段
  2403. if (!empty($act_content)) {
  2404. $update_data['act_content'] = $act_content;
  2405. }
  2406. if (!empty($act_duration)) {
  2407. $update_data['act_duration'] = $act_duration;
  2408. }
  2409. if (!empty($act_title)) {
  2410. $update_data['act_title'] = $act_title;
  2411. }
  2412. // 处理图片上传
  2413. if ($image_url) {
  2414. $update_data['img_url'] = $image_url;
  2415. $update_data['current_type'] = 1;
  2416. // 同时写入一个图片生成任务记录
  2417. if ($act_id) {
  2418. $pic_task = [
  2419. 'alias_act_id' => $act_id,
  2420. 'ref_img_url' => json_encode([]),
  2421. 'status' => 'success',
  2422. 'result_url' => json_encode([$image_url], 256),
  2423. 'model' => '',
  2424. 'created_at' => date('Y-m-d H:i:s'),
  2425. 'updated_at' => date('Y-m-d H:i:s'),
  2426. ];
  2427. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2428. }
  2429. }
  2430. // 处理视频上传
  2431. if ($video_url) {
  2432. $update_data['origin_video_url'] = $video_url;
  2433. $compressed_video_url = compressVideo($video_url);
  2434. $update_data['current_type'] = 2;
  2435. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2436. // 同时写入一个视频生成任务记录
  2437. if ($act_id) {
  2438. $video_task = [
  2439. 'alias_act_id' => $act_id,
  2440. 'status' => 'success',
  2441. 'result_url' => $update_data['origin_video_url'],
  2442. 'compressed_url' => $update_data['video_url'],
  2443. 'created_at' => date('Y-m-d H:i:s'),
  2444. 'updated_at' => date('Y-m-d H:i:s'),
  2445. ];
  2446. DB::table('mp_generate_video_tasks')->insert($video_task);
  2447. }
  2448. }
  2449. // 更新片段信息
  2450. $result = DB::table('mp_episode_segments')
  2451. ->where('id', $act_id)
  2452. ->update($update_data);
  2453. if ($result === false) {
  2454. Utils::throwError('20003:更新片段失败');
  2455. }
  2456. DB::commit();
  2457. return true;
  2458. } catch (\Exception $e) {
  2459. DB::rollBack();
  2460. dLog('anime')->error('更新片段失败', [
  2461. 'act_id' => $act_id,
  2462. 'error' => $e->getMessage()
  2463. ]);
  2464. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2465. }
  2466. }
  2467. public function copyAct($data) {
  2468. $act_id = getProp($data, 'act_id');
  2469. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2470. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2471. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2472. $video_url = getProp($source_segment, 'video_url');
  2473. if (!$video_url) Utils::throwError('20003:该片段没有视频无法复制');
  2474. $anime_id = getProp($source_segment, 'anime_id');
  2475. $episode_id = getProp($source_segment, 'episode_id');
  2476. $episode_number = getProp($source_segment, 'episode_number');
  2477. $act_number = getProp($source_segment, 'act_number');
  2478. try {
  2479. DB::beginTransaction();
  2480. // 新act的编号
  2481. $new_act_number = $act_number + 1;
  2482. // 更新后续所有act的act_number
  2483. DB::table('mp_episode_segments')
  2484. ->where('anime_id', $anime_id)
  2485. ->where('episode_id', $episode_id)
  2486. ->where('act_number', '>', $act_number)
  2487. ->increment('act_number');
  2488. // 复制该片段记录
  2489. $segment_data = (array)$source_segment;
  2490. unset($segment_data['id']);
  2491. $segment_data['act_number'] = $new_act_number;
  2492. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2493. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2494. if (!$id) {
  2495. Utils::throwError('20003:复制片段失败');
  2496. }
  2497. DB::commit();
  2498. }catch (\Exception $e) {
  2499. DB::rollBack();
  2500. Utils::throwError('20003:'.$e->getMessage());
  2501. }
  2502. // 返回新复制的记录
  2503. $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,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2504. $new_segment = $new_segment ? (array)$new_segment : [];
  2505. $new_segment['act_id'] = $id;
  2506. return $new_segment;
  2507. }
  2508. public function moveAct($data) {
  2509. $act_id = getProp($data, 'act_id');
  2510. $target_act_id = getProp($data, 'target_act_id');
  2511. // 获取源片段信息
  2512. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2513. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2514. // 获取目标片段信息
  2515. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2516. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2517. $anime_id = getProp($source_segment, 'anime_id');
  2518. $episode_id = getProp($source_segment, 'episode_id');
  2519. $source_act_number = getProp($source_segment, 'act_number');
  2520. $target_act_number = getProp($target_segment, 'act_number');
  2521. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2522. $target_anime_id = getProp($target_segment, 'anime_id');
  2523. $target_episode_id = getProp($target_segment, 'episode_id');
  2524. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2525. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2526. }
  2527. // 如果源片段和目标片段相同,无需移动
  2528. if ($source_act_number == $target_act_number) {
  2529. return true;
  2530. }
  2531. try {
  2532. DB::beginTransaction();
  2533. if ($source_act_number < $target_act_number) {
  2534. // 向后移动:源片段移动到目标片段之后
  2535. // 1. 将源片段和目标片段之间的所有片段编号减1
  2536. DB::table('mp_episode_segments')
  2537. ->where('anime_id', $anime_id)
  2538. ->where('episode_id', $episode_id)
  2539. ->where('act_number', '>', $source_act_number)
  2540. ->where('act_number', '<=', $target_act_number)
  2541. ->decrement('act_number');
  2542. // 2. 将源片段移动到目标片段之后
  2543. $new_act_number = $target_act_number;
  2544. } else {
  2545. // 向前移动:源片段移动到目标片段之后
  2546. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2547. DB::table('mp_episode_segments')
  2548. ->where('anime_id', $anime_id)
  2549. ->where('episode_id', $episode_id)
  2550. ->where('act_number', '>', $target_act_number)
  2551. ->where('act_number', '<', $source_act_number)
  2552. ->increment('act_number');
  2553. // 2. 将源片段移动到目标片段之后
  2554. $new_act_number = $target_act_number + 1;
  2555. }
  2556. // 3. 更新源片段的编号
  2557. $update_result = DB::table('mp_episode_segments')
  2558. ->where('id', $act_id)
  2559. ->update([
  2560. 'act_number' => $new_act_number,
  2561. 'updated_at' => date('Y-m-d H:i:s')
  2562. ]);
  2563. if (!$update_result) {
  2564. Utils::throwError('20003:更新片段编号失败');
  2565. }
  2566. DB::commit();
  2567. return true;
  2568. } catch (\Exception $e) {
  2569. DB::rollBack();
  2570. Utils::throwError('20003:' . $e->getMessage());
  2571. }
  2572. }
  2573. public function delAct($data) {
  2574. $act_id = getProp($data, 'act_id');
  2575. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2576. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2577. if (!$segment) Utils::throwError('20003:请选择片段');
  2578. $anime_id = getProp($segment, 'anime_id');
  2579. $episode_id = getProp($segment, 'episode_id');
  2580. $act_number = getProp($segment, 'act_number');
  2581. try {
  2582. DB::beginTransaction();
  2583. // 删除该片段记录
  2584. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2585. if (!$deleted) {
  2586. Utils::throwError('20003:删除片段失败');
  2587. }
  2588. // 更新后续act的编号
  2589. DB::table('mp_episode_segments')
  2590. ->where('anime_id', $anime_id)
  2591. ->where('episode_id', $episode_id)
  2592. ->where('act_number', '>', $act_number)
  2593. ->decrement('act_number');
  2594. DB::commit();
  2595. }catch (\Exception $e) {
  2596. DB::rollBack();
  2597. Utils::throwError('20003:'.$e->getMessage());
  2598. }
  2599. return true;
  2600. }
  2601. public function applyAct($data) {
  2602. $act_id = getProp($data, 'act_id');
  2603. $url = getProp($data, 'url');
  2604. if (!$act_id) Utils::throwError('20003:请选择片段');
  2605. if (!$url) Utils::throwError('20003:URL不能为空');
  2606. // 获取URL的文件扩展名
  2607. $urlPath = parse_url($url, PHP_URL_PATH);
  2608. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2609. // 定义图片和视频的扩展名
  2610. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2611. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2612. // 判断是图片还是视频
  2613. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2614. if (in_array($extension, $imageExtensions)) {
  2615. // 图片类型
  2616. $updateData['img_url'] = $url;
  2617. $updateData['current_type'] = 1;
  2618. } elseif (in_array($extension, $videoExtensions)) {
  2619. // 视频类型
  2620. $updateData['video_url'] = $url;
  2621. $updateData['current_type'] = 2;
  2622. } else {
  2623. Utils::throwError('20003:不支持的文件类型');
  2624. }
  2625. // 更新片段记录(全能模式下每个act只有一条记录)
  2626. $result = DB::table('mp_episode_segments')
  2627. ->where('id', $act_id)
  2628. ->update($updateData);
  2629. if (!$result) {
  2630. Utils::throwError('20003:更新片段失败');
  2631. }
  2632. return true;
  2633. }
  2634. public function actChatHistory($data) {
  2635. $act_id = getProp($data, 'act_id');
  2636. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2637. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2638. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2639. $value = (array)$value;
  2640. $value['created_at'] = transDate($value['created_at']);
  2641. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2642. else $value['reference_images'] = [];
  2643. return $value;
  2644. })->toArray();
  2645. // 获取历史图片
  2646. $url = [];
  2647. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2648. foreach($pic_history as $task) {
  2649. $result_url = getProp($task, 'result_url');
  2650. if (is_json($result_url)) {
  2651. $url = array_merge($url, json_decode($result_url, true));
  2652. }else {
  2653. $url[] = $result_url;
  2654. }
  2655. }
  2656. // 获取历史视频
  2657. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2658. foreach($video_history as $task) {
  2659. $result_url = getProp($task, 'result_url');
  2660. if (is_json($result_url)) {
  2661. $url = array_merge($url, json_decode($result_url, true));
  2662. }else {
  2663. $url[] = $result_url;
  2664. }
  2665. }
  2666. // 获取资产库
  2667. $products = [];
  2668. // 通过act_id查询片段信息获取episode_id
  2669. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2670. if ($segment) {
  2671. $episode_id = getProp($segment, 'episode_id');
  2672. // 查询剧集信息获取roles、scenes和extra_products
  2673. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2674. if ($episode) {
  2675. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2676. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2677. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2678. // 先合并roles和scenes
  2679. // 处理角色数组
  2680. foreach ($roles as $role) {
  2681. $product = $role;
  2682. // 将role字段重命名为product_name
  2683. if (isset($product['role'])) {
  2684. $product['product_name'] = $product['role'];
  2685. unset($product['role']);
  2686. }
  2687. $product['product'] = 1; // 标记类型为角色
  2688. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2689. }
  2690. // 处理场景数组
  2691. foreach ($scenes as $scene) {
  2692. $product = $scene;
  2693. // 将scene字段重命名为product_name
  2694. if (isset($product['scene'])) {
  2695. $product['product_name'] = $product['scene'];
  2696. unset($product['scene']);
  2697. }
  2698. $product['product'] = 2; // 标记类型为场景
  2699. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2700. }
  2701. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2702. foreach ($extra_products as $extra_product) {
  2703. $product_name = getProp($extra_product, 'product_name');
  2704. if ($product_name) {
  2705. $products[$product_name] = $extra_product; // 覆盖同名数据
  2706. }
  2707. }
  2708. // 重新索引数组(去除key)
  2709. $products = array_values($products);
  2710. }
  2711. }
  2712. // 获取执行中的任务
  2713. $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) {
  2714. $value = (array)$value;
  2715. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2716. else $value['ref_image_url'] = [];
  2717. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2718. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2719. if (!empty($value['prompt'])) {
  2720. $prompt = $value['prompt'];
  2721. // 查找第一个【镜头】的位置
  2722. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2723. // 从【镜头】开始截取
  2724. $prompt = substr($prompt, $matches[0][1]);
  2725. }
  2726. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2727. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2728. $value['prompt'] = $prompt;
  2729. }
  2730. return $value;
  2731. })->toArray();
  2732. return compact('chat', 'url', 'products', 'tasks');
  2733. }
  2734. public function applyAudioData($data) {
  2735. $segment_id = getProp($data, 'segment_id');
  2736. $global_data = getProp($data, 'global_data');
  2737. $segment_data = getProp($data, 'segment_data');
  2738. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2739. $global_data = is_array($global_data) ? $global_data : [];
  2740. $segment_data = is_array($segment_data) ? $segment_data : [];
  2741. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2742. $dialogue_item = null;
  2743. foreach ($global_data as $key => $item) {
  2744. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2745. $dialogue_item = $item;
  2746. unset($global_data[$key]);
  2747. break;
  2748. }
  2749. }
  2750. if ($dialogue_item) {
  2751. $segment_data[] = $dialogue_item;
  2752. }
  2753. // 特殊参数: audio_url,audio_duration,subtitle_info
  2754. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2755. // 如果不是全部存在,则仍需创建音频任务
  2756. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2757. $special_update_data = [];
  2758. $has_all_special_params = false;
  2759. // 从segment_data中提取特殊参数
  2760. $filtered_segment_data = [];
  2761. foreach ($segment_data as $item) {
  2762. $field_name = trim((string)getProp($item, 'name'));
  2763. if (in_array($field_name, $special_fields)) {
  2764. $special_update_data[$field_name] = getProp($item, 'value');
  2765. } else {
  2766. // 非特殊参数保留,继续后续处理
  2767. $filtered_segment_data[] = $item;
  2768. }
  2769. }
  2770. // 检查是否三个特殊参数都存在
  2771. if (count($special_update_data) === 3 &&
  2772. isset($special_update_data['audio_url']) &&
  2773. isset($special_update_data['audio_duration']) &&
  2774. isset($special_update_data['subtitle_info'])) {
  2775. $has_all_special_params = true;
  2776. // 立即更新到当前分镜
  2777. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2778. DB::table('mp_episode_segments')
  2779. ->where('segment_id', $segment_id)
  2780. ->update($special_update_data);
  2781. }
  2782. // 使用过滤后的segment_data继续处理其他参数
  2783. $segment_data = $filtered_segment_data;
  2784. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2785. $global_update_data = [];
  2786. $segment_update_data = [];
  2787. $global_voice_type = '';
  2788. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2789. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2790. $episode_id = getProp($target_segment, 'episode_id');
  2791. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2792. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2793. if (!$episode) Utils::throwError('20003:分集不存在');
  2794. foreach ($global_data as $item) {
  2795. $field_name = trim((string)getProp($item, 'name'));
  2796. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2797. continue;
  2798. }
  2799. $global_update_data[$field_name] = getProp($item, 'value');
  2800. if ($field_name === 'voice_type') {
  2801. $global_voice_type = trim((string)getProp($item, 'value'));
  2802. }
  2803. }
  2804. foreach ($segment_data as $item) {
  2805. $field_name = trim((string)getProp($item, 'name'));
  2806. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2807. continue;
  2808. }
  2809. $segment_update_data[$field_name] = getProp($item, 'value');
  2810. }
  2811. if ($global_voice_type) {
  2812. $timbre_info = DB::table('mp_timbres')
  2813. ->where('timbre_type', $global_voice_type)
  2814. ->select('audio_url', 'timbre_name')
  2815. ->first();
  2816. if ($timbre_info) {
  2817. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  2818. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  2819. }
  2820. }
  2821. try {
  2822. DB::beginTransaction();
  2823. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  2824. $segment_ids_to_create_task = [];
  2825. $segments_data = [];
  2826. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  2827. if (!empty($global_update_data)) {
  2828. // 如果角色不存在,则只更新当前分镜
  2829. if (!$target_voice_actor) {
  2830. // 只处理当前分镜
  2831. $affected_segments = DB::table('mp_episode_segments')
  2832. ->where('segment_id', $segment_id)
  2833. ->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')
  2834. ->get();
  2835. } else {
  2836. // 获取该角色的所有分镜
  2837. $affected_segments = DB::table('mp_episode_segments')
  2838. ->where('episode_id', $episode_id)
  2839. ->where('voice_actor', $target_voice_actor)
  2840. ->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')
  2841. ->get();
  2842. }
  2843. foreach ($affected_segments as $seg) {
  2844. $seg = (array)$seg;
  2845. $sid = getProp($seg, 'segment_id');
  2846. // 检查参数是否发生变化
  2847. $has_changed = false;
  2848. foreach ($global_update_data as $field => $new_value) {
  2849. $old_value = getProp($seg, $field);
  2850. if ($old_value != $new_value) {
  2851. $has_changed = true;
  2852. break;
  2853. }
  2854. }
  2855. if ($has_changed) {
  2856. $segment_ids_to_create_task[] = $sid;
  2857. $segments_data[$sid] = $seg;
  2858. }
  2859. }
  2860. // 只有在有变化的分镜时才更新
  2861. if (!empty($segment_ids_to_create_task)) {
  2862. $global_segment_update_data = $global_update_data;
  2863. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  2864. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2865. DB::table('mp_episode_segments')
  2866. ->where('episode_id', $episode_id)
  2867. ->where('voice_actor', $target_voice_actor)
  2868. ->whereIn('segment_id', $segment_ids_to_create_task)
  2869. ->update($global_segment_update_data);
  2870. }
  2871. if ($global_voice_type) {
  2872. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  2873. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  2874. $roles_updated = false;
  2875. foreach ($episode_roles as &$role) {
  2876. // 通过 role 字段匹配角色名,而不是 voice_name
  2877. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  2878. continue;
  2879. }
  2880. $role['voice_type'] = $global_voice_type;
  2881. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  2882. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  2883. $roles_updated = true;
  2884. }
  2885. unset($role);
  2886. if ($roles_updated) {
  2887. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  2888. 'roles' => json_encode($episode_roles, 256),
  2889. 'updated_at' => date('Y-m-d H:i:s'),
  2890. ]);
  2891. }
  2892. }
  2893. }
  2894. // 如果有单个分镜更新,检查是否有变化
  2895. if (!empty($segment_update_data)) {
  2896. // 获取当前分镜数据
  2897. $current_segment = DB::table('mp_episode_segments')
  2898. ->where('segment_id', $segment_id)
  2899. ->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')
  2900. ->first();
  2901. if ($current_segment) {
  2902. $current_segment = (array)$current_segment;
  2903. // 检查参数是否发生变化
  2904. $has_changed = false;
  2905. foreach ($segment_update_data as $field => $new_value) {
  2906. $old_value = getProp($current_segment, $field);
  2907. if ($old_value != $new_value) {
  2908. $has_changed = true;
  2909. break;
  2910. }
  2911. }
  2912. if ($has_changed) {
  2913. // 如果该分镜还未在列表中,添加进去
  2914. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  2915. $segment_ids_to_create_task[] = $segment_id;
  2916. $segments_data[$segment_id] = $current_segment;
  2917. }
  2918. // 更新分镜数据并清空音频URL
  2919. $segment_update_data['audio_url'] = '';
  2920. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2921. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  2922. }
  2923. }
  2924. }
  2925. // 为所有有变化的分镜创建音频合成任务
  2926. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  2927. if (!empty($segment_ids_to_create_task)) {
  2928. foreach ($segment_ids_to_create_task as $sid) {
  2929. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  2930. if ($sid === $segment_id && $has_all_special_params) {
  2931. continue;
  2932. }
  2933. // 重新获取更新后的分镜数据
  2934. $updated_segment = DB::table('mp_episode_segments')
  2935. ->where('segment_id', $sid)
  2936. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  2937. ->first();
  2938. if (!$updated_segment) continue;
  2939. $updated_segment = (array)$updated_segment;
  2940. // 检查dialogue是否为空
  2941. $dialogue = getProp($updated_segment, 'dialogue');
  2942. if (empty($dialogue)) {
  2943. // dialogue为空时,直接写入默认音频信息
  2944. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  2945. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  2946. 'audio_duration' => 2.0,
  2947. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  2948. 'updated_at' => date('Y-m-d H:i:s')
  2949. ]);
  2950. continue;
  2951. }
  2952. $generate_json = [
  2953. 'text' => $dialogue,
  2954. 'role' => getProp($updated_segment, 'voice_actor'),
  2955. 'voice_type' => getProp($updated_segment, 'voice_type'),
  2956. 'voice_name' => getProp($updated_segment, 'voice_name'),
  2957. 'emotion' => getProp($updated_segment, 'emotion'),
  2958. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  2959. 'gender' => getProp($updated_segment, 'gender'),
  2960. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  2961. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  2962. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  2963. 'pitch' => getProp($updated_segment, 'pitch', 0),
  2964. ];
  2965. // 插入视频配音合成任务
  2966. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2967. 'alias_segment_id' => $sid,
  2968. 'generate_status' => '执行中',
  2969. 'audio_url' => '',
  2970. 'generate_json' => json_encode($generate_json, 256),
  2971. 'created_at' => date('Y-m-d H:i:s'),
  2972. 'updated_at' => date('Y-m-d H:i:s'),
  2973. ]);
  2974. if (!$dubTaskId) {
  2975. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  2976. continue;
  2977. }
  2978. // 将任务ID添加到Redis列表中
  2979. Redis::lpush('dub_video_task_queue', $dubTaskId);
  2980. // 请求远程服务器执行生成
  2981. try {
  2982. sleep(1);
  2983. $client = new Client(['timeout' => 300, 'verify' => false]);
  2984. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2985. $response = $result->getBody()->getContents();
  2986. $response_arr = json_decode($response, true);
  2987. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2988. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2989. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2990. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2991. }
  2992. } catch (\Exception $e) {
  2993. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2994. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2995. }
  2996. }
  2997. }
  2998. DB::commit();
  2999. } catch (\Exception $e) {
  3000. DB::rollBack();
  3001. Utils::throwError('20003:'.$e->getMessage());
  3002. }
  3003. return true;
  3004. }
  3005. public function episodePicsInfo($data) {
  3006. $anime_id = getProp($data, 'anime_id');
  3007. $episode_id = getProp($data, 'episode_id');
  3008. // 参数验证
  3009. if (!$anime_id && !$episode_id) {
  3010. Utils::throwError('20003:请提供动漫ID或分集ID');
  3011. }
  3012. // 根据参数获取数据源
  3013. if ($episode_id) {
  3014. // 从剧集表获取
  3015. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3016. if (!$source) Utils::throwError('20003:该剧集不存在');
  3017. $table_name = 'mp_anime_episodes';
  3018. $id_field = 'id';
  3019. $id_value = $episode_id;
  3020. // 获取剧集的anime_id用于继承全局数据
  3021. $anime_id = getProp($source, 'anime_id');
  3022. } else {
  3023. // 从动漫表获取
  3024. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3025. if (!$source) Utils::throwError('20003:该动漫不存在');
  3026. $table_name = 'mp_animes';
  3027. $id_field = 'id';
  3028. $id_value = $anime_id;
  3029. }
  3030. $source = (array)$source;
  3031. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3032. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3033. // 如果是分集数据,需要处理继承和任务创建逻辑
  3034. if ($episode_id) {
  3035. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3036. }
  3037. // 返回生成器函数,用于 SSE 流式输出
  3038. return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
  3039. $startTime = time();
  3040. $maxDuration = 600; // 10分钟超时
  3041. $checkInterval = 3; // 每3秒检查一次
  3042. // Redis 缓存键
  3043. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3044. // 生成当前数据的哈希值用于比较
  3045. $generateHash = function($roles, $scenes) {
  3046. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
  3047. };
  3048. // 发送初始数据
  3049. $currentHash = $generateHash($roles, $scenes);
  3050. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3051. echo "data: " . json_encode([
  3052. 'type' => 'init',
  3053. 'data' => [
  3054. 'roles' => $roles,
  3055. 'scenes' => $scenes,
  3056. 'start_time' => $startTime
  3057. ]
  3058. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3059. ob_flush();
  3060. flush();
  3061. // 持续轮询任务状态
  3062. while (time() - $startTime < $maxDuration) {
  3063. $hasProcessing = false;
  3064. $updated = false;
  3065. // 检查角色任务状态
  3066. foreach ($roles as $index => &$role) {
  3067. $task_id = getProp($role, 'task_id');
  3068. $task_status = getProp($role, 'task_status');
  3069. $existing_url = getProp($role, 'url');
  3070. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3071. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3072. $hasProcessing = ($task_status === 'processing');
  3073. // 查询任务状态
  3074. $task = DB::table('mp_generate_pic_tasks')
  3075. ->where('id', $task_id)
  3076. ->select('id', 'status', 'result_url', 'error_message')
  3077. ->first();
  3078. if ($task) {
  3079. $task = (array)$task;
  3080. $status = getProp($task, 'status');
  3081. // 如果任务完成或失败
  3082. if (in_array($status, ['success', 'failed'])) {
  3083. $role['task_status'] = $status;
  3084. if ($status === 'success') {
  3085. $result_url = getProp($task, 'result_url');
  3086. if ($result_url) {
  3087. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3088. if (is_array($result_urls) && !empty($result_urls[0])) {
  3089. $role['url'] = $result_urls[0];
  3090. }
  3091. }
  3092. }
  3093. $updated = true;
  3094. } else if ($status === 'processing') {
  3095. $hasProcessing = true;
  3096. }
  3097. }
  3098. }
  3099. }
  3100. // 检查场景任务状态
  3101. foreach ($scenes as $index => &$scene) {
  3102. $task_id = getProp($scene, 'task_id');
  3103. $task_status = getProp($scene, 'task_status');
  3104. $existing_url = getProp($scene, 'url');
  3105. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3106. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3107. $hasProcessing = ($task_status === 'processing');
  3108. // 查询任务状态
  3109. $task = DB::table('mp_generate_pic_tasks')
  3110. ->where('id', $task_id)
  3111. ->select('id', 'status', 'result_url', 'error_message')
  3112. ->first();
  3113. if ($task) {
  3114. $task = (array)$task;
  3115. $status = getProp($task, 'status');
  3116. // 如果任务完成或失败
  3117. if (in_array($status, ['success', 'failed'])) {
  3118. $scene['task_status'] = $status;
  3119. if ($status === 'success') {
  3120. $result_url = getProp($task, 'result_url');
  3121. if ($result_url) {
  3122. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3123. if (is_array($result_urls) && !empty($result_urls[0])) {
  3124. $scene['url'] = $result_urls[0];
  3125. }
  3126. }
  3127. }
  3128. $updated = true;
  3129. } else if ($status === 'processing') {
  3130. $hasProcessing = true;
  3131. }
  3132. }
  3133. }
  3134. }
  3135. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3136. if ($updated) {
  3137. $newHash = $generateHash($roles, $scenes);
  3138. $cachedHash = Redis::get($cacheKey);
  3139. // 只有当数据真正变化时才更新数据库和发送事件
  3140. if ($newHash !== $cachedHash) {
  3141. try {
  3142. // 更新数据库
  3143. DB::table($table_name)->where($id_field, $id_value)->update([
  3144. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3145. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3146. 'updated_at' => date('Y-m-d H:i:s')
  3147. ]);
  3148. // 更新缓存
  3149. Redis::setex($cacheKey, 600, $newHash);
  3150. // 发送更新事件
  3151. echo "data: " . json_encode([
  3152. 'type' => 'update',
  3153. 'data' => [
  3154. 'roles' => $roles,
  3155. 'scenes' => $scenes,
  3156. 'elapsed_time' => time() - $startTime
  3157. ]
  3158. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3159. ob_flush();
  3160. flush();
  3161. } catch (\Exception $e) {
  3162. dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
  3163. }
  3164. } else {
  3165. // 即使哈希相同,如果有URL更新也要发送事件
  3166. $hasUrlUpdate = false;
  3167. foreach ($roles as $role) {
  3168. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3169. $hasUrlUpdate = true;
  3170. break;
  3171. }
  3172. }
  3173. if (!$hasUrlUpdate) {
  3174. foreach ($scenes as $scene) {
  3175. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3176. $hasUrlUpdate = true;
  3177. break;
  3178. }
  3179. }
  3180. }
  3181. if ($hasUrlUpdate) {
  3182. // 强制更新数据库和发送事件
  3183. try {
  3184. DB::table($table_name)->where($id_field, $id_value)->update([
  3185. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3186. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3187. 'updated_at' => date('Y-m-d H:i:s')
  3188. ]);
  3189. // 更新缓存
  3190. Redis::setex($cacheKey, 600, $newHash);
  3191. // 发送更新事件
  3192. echo "data: " . json_encode([
  3193. 'type' => 'update',
  3194. 'data' => [
  3195. 'roles' => $roles,
  3196. 'scenes' => $scenes,
  3197. 'elapsed_time' => time() - $startTime
  3198. ]
  3199. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3200. ob_flush();
  3201. flush();
  3202. } catch (\Exception $e) {
  3203. dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
  3204. }
  3205. }
  3206. }
  3207. }
  3208. // 如果所有任务都已完成,发送完成事件并退出
  3209. if (!$hasProcessing) {
  3210. // 查询数据库中的最终数据,确保返回最新的完整数据
  3211. try {
  3212. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3213. if ($finalSource) {
  3214. $finalSource = (array)$finalSource;
  3215. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3216. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3217. // 使用数据库中的最终数据
  3218. $roles = $finalRoles;
  3219. $scenes = $finalScenes;
  3220. }
  3221. } catch (\Exception $e) {
  3222. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3223. // 如果查询失败,继续使用内存中的数据
  3224. }
  3225. // 清理缓存
  3226. Redis::del($cacheKey);
  3227. echo "data: " . json_encode([
  3228. 'type' => 'completed',
  3229. 'data' => [
  3230. 'roles' => $roles,
  3231. 'scenes' => $scenes,
  3232. 'total_time' => time() - $startTime
  3233. ]
  3234. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3235. ob_flush();
  3236. flush();
  3237. break;
  3238. }
  3239. // 等待下次检查
  3240. sleep($checkInterval);
  3241. }
  3242. // 超时处理
  3243. if (time() - $startTime >= $maxDuration) {
  3244. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3245. try {
  3246. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3247. if ($finalSource) {
  3248. $finalSource = (array)$finalSource;
  3249. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3250. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3251. // 使用数据库中的最终数据
  3252. $roles = $finalRoles;
  3253. $scenes = $finalScenes;
  3254. }
  3255. } catch (\Exception $e) {
  3256. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3257. // 如果查询失败,继续使用内存中的数据
  3258. }
  3259. // 清理缓存
  3260. Redis::del($cacheKey);
  3261. echo "data: " . json_encode([
  3262. 'type' => 'timeout',
  3263. 'message' => '轮询超时,请刷新页面查看最新状态',
  3264. 'data' => [
  3265. 'roles' => $roles,
  3266. 'scenes' => $scenes
  3267. ]
  3268. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3269. ob_flush();
  3270. flush();
  3271. }
  3272. };
  3273. }
  3274. public function clipSegmentVideo($data) {
  3275. $segment_id = getProp($data, 'segment_id');
  3276. $video_time_point_start = getProp($data, 'video_time_point_start');
  3277. $video_time_point_end = getProp($data, 'video_time_point_end');
  3278. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3279. Utils::throwError('20003:参数异常');
  3280. }
  3281. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3282. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3283. }
  3284. $video_duration = $video_time_point_end - $video_time_point_start;
  3285. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3286. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3287. 'video_duration' => $video_duration,
  3288. 'video_time_point_start' => $video_time_point_start,
  3289. 'video_time_point_end' => $video_time_point_end,
  3290. 'updated_at' => date('Y-m-d H:i:s')
  3291. ]);
  3292. }
  3293. // 轮训获取图片任务结果
  3294. private function loopGetPicTaskResult($task_id) {
  3295. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3296. if (!$task) {
  3297. return '';
  3298. }
  3299. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3300. $model = getProp($task, 'model');
  3301. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3302. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3303. $isSyncModel = $isVolcModel || $isGptModel;
  3304. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3305. $start_count = 0;
  3306. $img_url = '';
  3307. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3308. sleep(3);
  3309. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3310. // 如果任务已经完成,直接返回结果
  3311. if ($task->status === 'success' && $task->result_url) {
  3312. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3313. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3314. }
  3315. // 如果任务已失败,返回空
  3316. if ($task->status === 'failed') {
  3317. return '';
  3318. }
  3319. if ($isSyncModel) continue;
  3320. // 查询任务状态
  3321. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3322. if ($statusInfo['status'] === 'success') {
  3323. $task->updateStatus('success', [
  3324. 'result_url' => $statusInfo['result_url'],
  3325. 'result_json' => $statusInfo['result_json'] ?? []
  3326. ]);
  3327. // 同步调整分镜图片状态和结果
  3328. if (getProp($task, 'alias_segment_id')) {
  3329. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3330. 'img_url' => $statusInfo['result_url'][0],
  3331. 'pic_task_status' => '已完成',
  3332. ]);
  3333. }
  3334. $img_url = $statusInfo['result_url'][0];
  3335. break;
  3336. } elseif ($statusInfo['status'] === 'failed') {
  3337. $task->updateStatus('failed', [
  3338. 'error_message' => $statusInfo['error_message'],
  3339. 'result_json' => $statusInfo['result_json'] ?? []
  3340. ]);
  3341. if (getProp($task, 'alias_segment_id')) {
  3342. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3343. 'pic_task_status' => '失败',
  3344. ]);
  3345. }
  3346. break;
  3347. }
  3348. $start_count++;
  3349. }
  3350. return $img_url;
  3351. }
  3352. /**
  3353. * 从分镜内容中提取涉及的角色
  3354. */
  3355. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3356. $found_characters = [];
  3357. foreach ($available_characters as $character) {
  3358. // 检查角色名称是否在分镜内容中出现
  3359. if (strpos($segment_content, $character) !== false) {
  3360. $found_characters[] = $character;
  3361. }
  3362. }
  3363. if (!$found_characters) {
  3364. foreach ($roles as $character) {
  3365. // 检查角色名称是否在分镜内容中出现
  3366. if (strpos($segment_content, $character) !== false) {
  3367. $found_characters[] = $character;
  3368. }
  3369. }
  3370. }
  3371. return array_unique($found_characters);
  3372. }
  3373. // 从分镜剧本中提取关键字段
  3374. private function handleSegmentContent(&$data) {
  3375. $segmentContent = getProp($data, 'segment_content');
  3376. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3377. $segmentData = [
  3378. 'description' => '',
  3379. 'composition' => '',
  3380. 'camera_movement' => '',
  3381. 'voice_actor' => '',
  3382. 'dialogue' => '',
  3383. 'frame_type' => '',
  3384. 'scene' => '', // 场景
  3385. 'characters' => '', // 出镜角色
  3386. 'tail_frame' => '', // 尾帧描述
  3387. 'emotion' => '中性', // 情感
  3388. 'gender' => '0', // 性别(0未知,1男,2女)
  3389. 'speed_ratio' => 0, // 语速
  3390. 'loudness_ratio' => 0, // 音量
  3391. 'emotion_scale' => 4, // 情感强度
  3392. 'pitch' => 0, // 音调
  3393. ];
  3394. // 用于存储需要从 segment_content 中移除的匹配项
  3395. $replaceEmptyArr = [];
  3396. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3397. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3398. $segmentData['description'] = trim($descMatch[1]);
  3399. $data['description'] = trim($descMatch[1]);
  3400. }
  3401. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3402. $segmentData['composition'] = trim($compMatch[1]);
  3403. $data['composition'] = trim($compMatch[1]);
  3404. }
  3405. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3406. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3407. $data['camera_movement'] = trim($cameraMatch[1]);
  3408. }
  3409. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3410. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3411. $data['voice_actor'] = trim($voiceMatch[1]);
  3412. }
  3413. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3414. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3415. $data['dialogue'] = trim($dialogueMatch[1]);
  3416. }
  3417. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3418. $segmentData['frame_type'] = trim($frameMatch[1]);
  3419. $data['frame_type'] = trim($frameMatch[1]);
  3420. }
  3421. // 场景字段
  3422. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3423. $segmentData['scene'] = trim($sceneMatch[1]);
  3424. $data['scene'] = trim($sceneMatch[1]);
  3425. }
  3426. // 出镜角色字段
  3427. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3428. $segmentData['characters'] = trim($charactersMatch[1]);
  3429. $data['characters'] = trim($charactersMatch[1]);
  3430. }
  3431. // 尾帧描述字段
  3432. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3433. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3434. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3435. }
  3436. // 情感字段
  3437. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3438. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3439. $segmentData['emotion'] = trim($emotionMatch[1]);
  3440. $data['emotion'] = trim($emotionMatch[1]);
  3441. }
  3442. // 性别字段
  3443. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3444. $replaceEmptyArr[] = trim($genderMatch[0]);
  3445. $genderStr = trim($genderMatch[1]);
  3446. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3447. $segmentData['gender'] = '1';
  3448. $data['gender'] = '1';
  3449. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3450. $segmentData['gender'] = '2';
  3451. $data['gender'] = '2';
  3452. } else {
  3453. $segmentData['gender'] = '0';
  3454. $data['gender'] = '0';
  3455. }
  3456. }
  3457. // 语速字段
  3458. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3459. $replaceEmptyArr[] = trim($speedMatch[0]);
  3460. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3461. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3462. }
  3463. // 音量字段
  3464. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3465. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3466. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3467. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3468. }
  3469. // 情感强度字段
  3470. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3471. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3472. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3473. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3474. }
  3475. // 音调字段
  3476. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3477. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3478. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3479. $data['pitch'] = (int)trim($pitchMatch[1]);
  3480. }
  3481. // 从 segment_content 中移除已提取的配音参数字段
  3482. if (!empty($replaceEmptyArr)) {
  3483. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3484. }
  3485. // 如果有配音角色,查询音色信息并验证情感
  3486. $voice_actor = $segmentData['voice_actor'];
  3487. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3488. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3489. $anime_id = getProp($data, 'anime_id');
  3490. $episode_id = getProp($data, 'episode_id');
  3491. // 优先从剧集的角色列表中查找
  3492. $roles = [];
  3493. if ($episode_id) {
  3494. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3495. if ($episode && getProp($episode, 'roles')) {
  3496. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3497. }
  3498. }
  3499. // 如果剧集中没有,从动漫的角色列表中查找
  3500. if (empty($roles) && $anime_id) {
  3501. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3502. if ($anime && getProp($anime, 'roles')) {
  3503. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3504. }
  3505. }
  3506. // 查找匹配的角色音色信息
  3507. $timbre_info = null;
  3508. foreach ($roles as $role) {
  3509. if (getProp($role, 'role') === $voice_actor) {
  3510. $timbre_info = $role;
  3511. break;
  3512. }
  3513. }
  3514. // 如果找到音色信息,添加到数据中
  3515. if ($timbre_info) {
  3516. $voice_type = getProp($timbre_info, 'voice_type');
  3517. $voice_name = getProp($timbre_info, 'voice_name');
  3518. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3519. if ($voice_type) {
  3520. $data['voice_type'] = $voice_type;
  3521. $segmentData['voice_type'] = $voice_type;
  3522. }
  3523. if ($voice_name) {
  3524. $data['voice_name'] = $voice_name;
  3525. $segmentData['voice_name'] = $voice_name;
  3526. }
  3527. if ($voice_audio_url) {
  3528. $data['voice_audio_url'] = $voice_audio_url;
  3529. $segmentData['voice_audio_url'] = $voice_audio_url;
  3530. }
  3531. // 验证情感是否在音色支持的情感列表中
  3532. if ($voice_type) {
  3533. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3534. if ($timbre_emotion) {
  3535. $timbre_emotion = explode(',', $timbre_emotion);
  3536. } else {
  3537. $timbre_emotion = [];
  3538. }
  3539. $emotion = getProp($segmentData, 'emotion', '中性');
  3540. if (!in_array($emotion, $timbre_emotion)) {
  3541. $emotion = '中性';
  3542. }
  3543. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3544. $emotion_list = array_flip($emotion_list);
  3545. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3546. $data['emotion_type'] = $emotion_type;
  3547. $segmentData['emotion_type'] = $emotion_type;
  3548. }
  3549. }
  3550. }
  3551. return $segmentData;
  3552. }
  3553. public function createSegmentVideoTask($data) {
  3554. $segment_id = getProp($data, 'segment_id');
  3555. $tail_frame = getProp($data, 'tail_frame');
  3556. $first_frame_url = getProp($data, 'first_frame_url');
  3557. $tail_frame_url = getProp($data, 'tail_frame_url');
  3558. $generate_audio = getProp($data, 'generate_audio', 0);
  3559. if (!$segment_id) {
  3560. Utils::throwError('1002:分镜ID不能为空');
  3561. }
  3562. // 获取分镜信息
  3563. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3564. if (!$segment) {
  3565. Utils::throwError('20003:分镜不存在');
  3566. }
  3567. $segment = (array)$segment;
  3568. $episode_id = getProp($segment, 'episode_id');
  3569. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3570. if (!$ratio) $ratio = '9:16';
  3571. // 获取分镜内容
  3572. $segmentContent = getProp($segment, 'segment_content', '');
  3573. // 检查 $segmentContent 中是否已有尾帧描述
  3574. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3575. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3576. $finalTailFrame = '';
  3577. if ($tail_frame) {
  3578. // 用户输入了尾帧描述,优先使用
  3579. $finalTailFrame = $tail_frame;
  3580. // 如果 segmentContent 中已有尾帧描述,需要替换
  3581. if ($contentHasTailFrame) {
  3582. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3583. }
  3584. } elseif ($contentHasTailFrame) {
  3585. // segmentContent 中有尾帧描述,使用它
  3586. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3587. } else {
  3588. // 两者都没有,使用分镜表中的尾帧描述
  3589. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3590. }
  3591. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3592. $hasDialogue = false;
  3593. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3594. $dialogue = trim($dialogueMatch[1]);
  3595. // 如果台词不为空且不是"无"
  3596. if (!empty($dialogue) && $dialogue !== '无') {
  3597. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3598. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3599. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3600. $hasDialogue = true;
  3601. }
  3602. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3603. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3604. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3605. if (!preg_match('/^[“]/', $dialogue)) {
  3606. $dialogue = '“' . $dialogue;
  3607. }
  3608. if (!preg_match('/[”]$/', $dialogue)) {
  3609. $dialogue .= '”';
  3610. }
  3611. // 将修改后的台词替换回 $segmentContent
  3612. $originalDialogue = $dialogueMatch[1];
  3613. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3614. }
  3615. }
  3616. // 构建完整的提示词
  3617. $fullPrompt = $segmentContent;
  3618. if ($finalTailFrame && !$contentHasTailFrame) {
  3619. // 只有当 segmentContent 中没有尾帧描述时才追加
  3620. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3621. }
  3622. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3623. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3624. $fullPrompt = trim($fullPrompt);
  3625. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3626. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3627. // 智能选择视频时长
  3628. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3629. $videoDuration = -1;
  3630. // 处理视频模型
  3631. $model = getProp($data, 'model');
  3632. if (!$model) {
  3633. // 用户没有输入,从episode表获取
  3634. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3635. $model = getProp($episode, 'video_model');
  3636. if (!$model) {
  3637. // episode表也没有,使用默认值
  3638. $model = 'doubao-seedance-1-5-pro-251215';
  3639. }
  3640. }
  3641. // 验证模型是否在可用模型表中
  3642. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3643. $model = 'doubao-seedance-1-5-pro-251215';
  3644. }
  3645. // 保存到episode表
  3646. $episode_id = getProp($segment, 'episode_id');
  3647. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3648. 'video_model' => $model,
  3649. 'updated_at' => date('Y-m-d H:i:s')
  3650. ]);
  3651. // 构建视频生成参数
  3652. $videoParams = [
  3653. 'model' => $model,
  3654. 'alias_segment_id' => $segment_id,
  3655. 'prompt' => trim($fullPrompt),
  3656. 'video_duration' => $videoDuration,
  3657. 'video_resolution' => '720P',
  3658. 'seed' => -1,
  3659. 'ratio' => $ratio,
  3660. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3661. 'draft' => false,
  3662. 'watermark' => false,
  3663. 'camera_fixed' => false,
  3664. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3665. ];
  3666. // 如果分镜有图片,作为首帧
  3667. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3668. $hasVideo = !empty(getProp($segment, 'video_url'));
  3669. if ($hasImage) {
  3670. if ($first_frame_url) {
  3671. $videoParams['first_frame_url'] = $first_frame_url;
  3672. }else {
  3673. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3674. }
  3675. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3676. }
  3677. // 构建content数组
  3678. $videoParams['content'] = [
  3679. [
  3680. 'type' => 'text',
  3681. 'text' => $videoParams['prompt'],
  3682. ]
  3683. ];
  3684. // 如果有首帧图片,添加到content中
  3685. if ($hasImage) {
  3686. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3687. $videoParams['content'][] = [
  3688. 'type' => 'image_url',
  3689. 'image_url' => [
  3690. 'url' => $videoParams['first_frame_url'],
  3691. ],
  3692. 'role' => 'reference_image',
  3693. ];
  3694. if (isset($videoParams['tail_frame_url'])) {
  3695. $videoParams['content'][] = [
  3696. 'type' => 'image_url',
  3697. 'image_url' => [
  3698. 'url' => $videoParams['tail_frame_url'],
  3699. ],
  3700. 'role' => 'reference_image',
  3701. ];
  3702. }
  3703. }else {
  3704. $videoParams['content'][] = [
  3705. 'type' => 'image_url',
  3706. 'image_url' => [
  3707. 'url' => $videoParams['first_frame_url'],
  3708. ],
  3709. 'role' => 'first_frame',
  3710. ];
  3711. if (isset($videoParams['tail_frame_url'])) {
  3712. $videoParams['content'][] = [
  3713. 'type' => 'image_url',
  3714. 'image_url' => [
  3715. 'url' => $videoParams['tail_frame_url'],
  3716. ],
  3717. 'role' => 'last_frame',
  3718. ];
  3719. }
  3720. }
  3721. }
  3722. // 获取配音音频URL
  3723. $audioUrl = getProp($segment, 'audio_url');
  3724. $audioDuration = getProp($segment, 'audio_duration');
  3725. // 音频传入的前提:必须有至少一张图片或一个视频
  3726. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3727. // dd($videoParams);
  3728. // 根据模型选择不同的视频生成方法
  3729. if (strpos($model, 'jimeng') !== false) {
  3730. // 即梦模型参数调整
  3731. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3732. unset($videoParams['content']); // 即梦不使用content格式
  3733. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3734. } elseif (strpos($model, 'kling') !== false) {
  3735. // Keling模型参数调整
  3736. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  3737. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3738. unset($videoParams['ratio']);
  3739. unset($videoParams['content']); // Keling不使用content格式
  3740. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3741. } elseif (strpos($model, 'zhizhen') !== false) {
  3742. // 智帧20等新模型使用统一API
  3743. // 构建统一API参数
  3744. $unifiedParams = [
  3745. 'model_code' => $model,
  3746. 'alias_segment_id' => $segment_id,
  3747. 'prompt' => trim($fullPrompt),
  3748. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  3749. 'video_resolution' => strtolower($videoParams['video_resolution']),
  3750. 'video_ratio' => $ratio,
  3751. 'seed' => -1,
  3752. ];
  3753. // 构建parameters参数
  3754. $parameters = [
  3755. 'seconds' => $unifiedParams['video_duration'],
  3756. 'resolution' => $unifiedParams['video_resolution'],
  3757. 'ratio' => $ratio,
  3758. // 'video_mode' => 'multi_image',
  3759. // 'mode' => 'multi_image',
  3760. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  3761. ];
  3762. $hasImage = false;
  3763. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  3764. if ($hasImage) {
  3765. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  3766. if (isset($videoParams['tail_frame_url'])) {
  3767. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  3768. }
  3769. // 只有在有图片的情况下才能添加参考音频
  3770. if ($audioUrl) {
  3771. // $parameters['reference_audios'] = [$audioUrl];
  3772. }
  3773. } else {
  3774. // 没有图片时,记录错误日志
  3775. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  3776. 'segment_id' => $segment_id,
  3777. 'model' => $model
  3778. ]);
  3779. }
  3780. $unifiedParams['parameters'] = $parameters;
  3781. // 调用统一API创建任务
  3782. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  3783. } else {
  3784. // Seedance模型(默认)
  3785. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  3786. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3787. // 添加配音音频到content中
  3788. $videoParams['content'][] = [
  3789. 'type' => 'audio_url',
  3790. 'audio_url' => [
  3791. 'url' => $audioUrl,
  3792. ],
  3793. 'role' => 'reference_audio',
  3794. ];
  3795. // 优化提示词,增加音频相关描述
  3796. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  3797. $videoParams['prompt'] = $audioPrompt;
  3798. $videoParams['content'][0]['text'] = $audioPrompt;
  3799. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  3800. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  3801. }
  3802. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  3803. }
  3804. // 更新分镜表的视频任务信息
  3805. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3806. 'video_task_id' => $task->id,
  3807. 'video_task_status' => '生成中',
  3808. 'generate_audio' => $generate_audio,
  3809. 'updated_at' => date('Y-m-d H:i:s')
  3810. ]);
  3811. return [
  3812. 'task_id' => $task->id,
  3813. 'status' => $task->status,
  3814. 'segment_id' => $segment_id,
  3815. 'video_duration' => $videoDuration
  3816. ];
  3817. }
  3818. public function createActVideoTask($data) {
  3819. $act_id = getProp($data, 'act_id');
  3820. $first_frame_url = getProp($data, 'first_frame_url');
  3821. $tail_frame_url = getProp($data, 'tail_frame_url');
  3822. $generate_audio = getProp($data, 'generate_audio', 1);
  3823. $video_duration = getProp($data, 'video_duration');
  3824. $video_resolution = getProp($data, 'video_resolution');
  3825. $ratio = getProp($data, 'ratio');
  3826. $products = getProp($data, 'products', []);
  3827. $reference_images = array_unique(getProp($data, 'reference_images', []));
  3828. if (!is_array($reference_images) || !is_array($products)) {
  3829. Utils::throwError('20003:传入的参考图或资产格式不正确');
  3830. }
  3831. if (!$act_id) {
  3832. Utils::throwError('1002:片段ID不能为空');
  3833. }
  3834. // 获取片段信息
  3835. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3836. if (!$act) {
  3837. Utils::throwError('20003:片段不存在');
  3838. }
  3839. $act = (array)$act;
  3840. $anime_id = getProp($act, 'anime_id');
  3841. $episode_id = getProp($act, 'episode_id');
  3842. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3843. $ace_mode = getProp($anime, 'ace_mode');
  3844. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3845. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  3846. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  3847. // 将资产中新出现的资产放到extra_products中
  3848. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  3849. if (!empty($products) && $episode) {
  3850. // 获取剧集中的角色和场景列表
  3851. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3852. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3853. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3854. // 构建角色名称列表
  3855. $role_names = array_column($roles, 'role');
  3856. // 构建场景名称列表
  3857. $scene_names = array_column($scenes, 'scene');
  3858. // 遍历传入的products
  3859. foreach ($products as $product) {
  3860. $product_name = getProp($product, 'product_name');
  3861. // 如果product_name不在roles和scenes中
  3862. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
  3863. // 查找是否在extra_products中存在同名的
  3864. $found = false;
  3865. foreach ($extra_products as $key => $extra_product) {
  3866. if (getProp($extra_product, 'product_name') === $product_name) {
  3867. // 有同名的则覆盖
  3868. $extra_products[$key] = $product;
  3869. $found = true;
  3870. break;
  3871. }
  3872. }
  3873. // 没有则新增
  3874. if (!$found) {
  3875. $extra_products[] = $product;
  3876. }
  3877. }
  3878. }
  3879. if ($extra_products) {
  3880. // 保存到数据库
  3881. DB::table('mp_anime_episodes')
  3882. ->where('id', $episode_id)
  3883. ->update([
  3884. 'extra_products' => json_encode($extra_products, 256),
  3885. 'updated_at' => date('Y-m-d H:i:s')
  3886. ]);
  3887. }
  3888. }
  3889. // 获取分镜内容
  3890. $actContent = getProp($act, 'act_show_content', '');
  3891. // 音效同出(默认使用)
  3892. $current_generate_audio = $generate_audio ? 1 : 0;
  3893. // 构建完整的提示词
  3894. $processResult = $this->processActContentWithProducts($actContent, $products);
  3895. $fullPrompt = $processResult['content'];
  3896. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  3897. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  3898. // 处理视频模型
  3899. $model = getProp($data, 'model');
  3900. if (!$model) {
  3901. $model = getProp($episode, 'video_model');
  3902. if (!$model) {
  3903. // episode表也没有,使用默认值
  3904. $model = 'zhizhen-20-mini';
  3905. }
  3906. }
  3907. // 验证模型是否在可用模型表中
  3908. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3909. $model = 'zhizhen-20-mini';
  3910. }
  3911. // 保存到episode表
  3912. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3913. 'video_model' => $model,
  3914. 'updated_at' => date('Y-m-d H:i:s')
  3915. ]);
  3916. // 构建视频生成参数
  3917. $videoParams = [
  3918. 'model' => $model,
  3919. 'alias_act_id' => $act_id,
  3920. 'prompt' => trim($fullPrompt),
  3921. 'video_duration' => $videoDuration,
  3922. 'video_resolution' => $video_resolution,
  3923. 'seed' => -1,
  3924. 'ratio' => $ratio,
  3925. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3926. 'draft' => false,
  3927. 'watermark' => false,
  3928. 'camera_fixed' => false,
  3929. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3930. ];
  3931. // 如果分镜有图片,作为首帧
  3932. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  3933. $hasVideo = !empty(getProp($act, 'video_url'));
  3934. if ($hasImage) {
  3935. if ($first_frame_url) {
  3936. $videoParams['first_frame_url'] = $first_frame_url;
  3937. }else {
  3938. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  3939. }
  3940. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3941. }
  3942. // 构建content数组
  3943. $videoParams['content'] = [
  3944. [
  3945. 'type' => 'text',
  3946. 'text' => $videoParams['prompt'],
  3947. ]
  3948. ];
  3949. // 如果有首帧图片,添加到content中
  3950. if ($hasImage) {
  3951. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3952. $videoParams['content'][] = [
  3953. 'type' => 'image_url',
  3954. 'image_url' => [
  3955. 'url' => $videoParams['first_frame_url'],
  3956. ],
  3957. 'role' => 'reference_image',
  3958. ];
  3959. if (isset($videoParams['tail_frame_url'])) {
  3960. $videoParams['content'][] = [
  3961. 'type' => 'image_url',
  3962. 'image_url' => [
  3963. 'url' => $videoParams['tail_frame_url'],
  3964. ],
  3965. 'role' => 'reference_image',
  3966. ];
  3967. }
  3968. }else {
  3969. $videoParams['content'][] = [
  3970. 'type' => 'image_url',
  3971. 'image_url' => [
  3972. 'url' => $videoParams['first_frame_url'],
  3973. ],
  3974. 'role' => 'first_frame',
  3975. ];
  3976. if (isset($videoParams['tail_frame_url'])) {
  3977. $videoParams['content'][] = [
  3978. 'type' => 'image_url',
  3979. 'image_url' => [
  3980. 'url' => $videoParams['tail_frame_url'],
  3981. ],
  3982. 'role' => 'last_frame',
  3983. ];
  3984. }
  3985. }
  3986. }
  3987. // dd($videoParams);
  3988. // 根据模型选择不同的视频生成方法
  3989. if (strpos($model, 'jimeng') !== false) {
  3990. // 即梦模型参数调整
  3991. unset($videoParams['content']); // 即梦不使用content格式
  3992. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3993. } elseif (strpos($model, 'kling') !== false) {
  3994. // Keling模型参数调整
  3995. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3996. unset($videoParams['ratio']);
  3997. unset($videoParams['content']); // Keling不使用content格式
  3998. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3999. } elseif (strpos($model, 'zhizhen') !== false) {
  4000. // 智帧20等新模型使用统一API
  4001. // 构建统一API参数
  4002. $unifiedParams = [
  4003. 'model_code' => $model,
  4004. 'alias_act_id' => $act_id,
  4005. 'prompt' => trim($fullPrompt),
  4006. 'video_duration' => $videoDuration,
  4007. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4008. 'video_ratio' => $ratio,
  4009. 'seed' => -1,
  4010. ];
  4011. // 构建parameters参数
  4012. $parameters = [
  4013. 'seconds' => $unifiedParams['video_duration'],
  4014. 'resolution' => $unifiedParams['video_resolution'],
  4015. 'ratio' => $ratio,
  4016. // 'video_mode' => 'multi_image',
  4017. // 'mode' => 'multi_image',
  4018. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4019. ];
  4020. $hasImage = false;
  4021. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4022. if ($hasImage) {
  4023. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4024. if (isset($videoParams['tail_frame_url'])) {
  4025. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4026. }
  4027. } else {
  4028. // 没有图片时,记录错误日志
  4029. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4030. 'act_id' => $act_id,
  4031. 'model' => $model
  4032. ]);
  4033. }
  4034. if ($reference_images) {
  4035. // 限制只传入9张参考图
  4036. $reference_images = array_slice($reference_images, 0, 9);
  4037. // 在处理之前先保存原始reference_images到任务参数中
  4038. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4039. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4040. $parameters['reference_images'] = $reference_images;
  4041. $parameters['video_mode'] = 'multi_image';
  4042. $parameters['mode'] = 'multi_image';
  4043. }
  4044. $unifiedParams['parameters'] = $parameters;
  4045. // 调用统一API创建任务
  4046. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4047. } else {
  4048. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4049. }
  4050. // 更新分镜表的视频任务信息
  4051. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4052. 'video_task_id' => $task->id,
  4053. 'video_task_status' => '生成中',
  4054. 'generate_audio' => $generate_audio,
  4055. 'updated_at' => date('Y-m-d H:i:s')
  4056. ]);
  4057. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4058. $episode_number = getProp($act, 'episode_number');
  4059. $act_number = getProp($act, 'act_number');
  4060. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4061. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4062. }
  4063. return [
  4064. 'task_id' => $task->id,
  4065. 'status' => $task->status,
  4066. 'act_id' => $act_id,
  4067. 'video_duration' => $videoDuration
  4068. ];
  4069. }
  4070. /**
  4071. * 根据提示词内容智能计算最优视频时长
  4072. *
  4073. * @param string $segmentContent 分镜内容
  4074. * @param string $tailFrame 尾帧描述
  4075. * @return int 视频时长(2-12秒)
  4076. */
  4077. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4078. // 合并所有文本内容
  4079. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4080. // 如果没有内容,返回默认时长
  4081. if (empty($fullText)) {
  4082. return 5;
  4083. }
  4084. // 计算文本长度(中文字符按2个字符计算)
  4085. $textLength = mb_strlen($fullText, 'UTF-8');
  4086. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4087. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4088. // 分析内容复杂度
  4089. $complexityScore = $this->analyzeContentComplexity($fullText);
  4090. // 基础时长计算(根据文本长度)
  4091. $baseDuration = 3; // 默认2秒
  4092. // if ($adjustedLength <= 20) {
  4093. // $baseDuration = 3;
  4094. // } elseif ($adjustedLength <= 40) {
  4095. // $baseDuration = 4;
  4096. // } elseif ($adjustedLength <= 60) {
  4097. // $baseDuration = 5;
  4098. // } elseif ($adjustedLength <= 80) {
  4099. // $baseDuration = 6;
  4100. // } elseif ($adjustedLength <= 100) {
  4101. // $baseDuration = 7;
  4102. // } elseif ($adjustedLength <= 120) {
  4103. // $baseDuration = 8;
  4104. // } else {
  4105. // $baseDuration = 9;
  4106. // }
  4107. // 根据内容复杂度调整时长
  4108. $finalDuration = $baseDuration + $complexityScore;
  4109. // 确保时长在2-12秒范围内
  4110. return max(4, min(12, $finalDuration));
  4111. }
  4112. /**
  4113. * 分析内容复杂度,返回时长调整值
  4114. *
  4115. * @param string $text 文本内容
  4116. * @return int 调整值(-2到+3)
  4117. */
  4118. private function analyzeContentComplexity($text) {
  4119. $score = 0;
  4120. // 动作关键词(需要更长时间展现)
  4121. $actionKeywords = [
  4122. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4123. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4124. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4125. ];
  4126. // 静态关键词(可以用较短时间)
  4127. $staticKeywords = [
  4128. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4129. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4130. ];
  4131. // 复杂场景关键词(需要更长时间)
  4132. $complexSceneKeywords = [
  4133. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4134. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4135. ];
  4136. // 情感关键词(需要适中时间表现)
  4137. $emotionKeywords = [
  4138. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4139. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4140. ];
  4141. // 检查动作关键词
  4142. foreach ($actionKeywords as $keyword) {
  4143. if (strpos($text, $keyword) !== false) {
  4144. $score += 1;
  4145. break; // 避免重复加分
  4146. }
  4147. }
  4148. // 检查静态关键词
  4149. foreach ($staticKeywords as $keyword) {
  4150. if (strpos($text, $keyword) !== false) {
  4151. $score -= 1;
  4152. break;
  4153. }
  4154. }
  4155. // 检查复杂场景关键词
  4156. foreach ($complexSceneKeywords as $keyword) {
  4157. if (strpos($text, $keyword) !== false) {
  4158. $score += 1;
  4159. break;
  4160. }
  4161. }
  4162. // 检查情感关键词
  4163. foreach ($emotionKeywords as $keyword) {
  4164. if (strpos($text, $keyword) !== false) {
  4165. $score += 1;
  4166. break;
  4167. }
  4168. }
  4169. // 检查时间相关词汇
  4170. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4171. $score += 1;
  4172. }
  4173. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4174. $score -= 1;
  4175. }
  4176. // 检查转场词汇
  4177. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4178. $score += 1;
  4179. }
  4180. // 检查环境描述(复杂环境需要更多时间)
  4181. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4182. $score += 1;
  4183. }
  4184. // 检查对话内容(对话需要更多时间)
  4185. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4186. $score += 1;
  4187. }
  4188. // 限制调整范围
  4189. return max(-1, min(4, $score));
  4190. }
  4191. /**
  4192. * 创建完整视频合成任务
  4193. *
  4194. * @param array $data
  4195. * @return array
  4196. */
  4197. public function createCompleteVideoTask($data)
  4198. {
  4199. $animeId = getProp($data, 'anime_id');
  4200. $episodeId = getProp($data, 'episode_id');
  4201. // 验证参数
  4202. if (!$animeId || !$episodeId) {
  4203. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4204. }
  4205. // 检查是否已存在处理中的任务
  4206. $existingTask = DB::table('mp_complete_video_tasks')
  4207. ->where('anime_id', $animeId)
  4208. ->where('episode_id', $episodeId)
  4209. ->whereIn('generate_status', ['执行中'])
  4210. ->first();
  4211. if ($existingTask) {
  4212. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4213. }
  4214. // 获取全能模式状态
  4215. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4216. if ((int)$ace_mode === 1) {
  4217. // 获取所有片段的配音视频,按 act_number 排序
  4218. $segments = DB::table('mp_episode_segments')
  4219. ->where('anime_id', $animeId)
  4220. ->where('episode_id', $episodeId)
  4221. ->orderBy('segment_number')
  4222. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4223. ->get();
  4224. // 检查是否所有片段都有视频
  4225. $missingVideos = $segments->filter(function($segment) {
  4226. return empty($segment->video_url);
  4227. });
  4228. if ($missingVideos->isNotEmpty()) {
  4229. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4230. }
  4231. }else {
  4232. // 获取所有分镜的配音视频,按 segment_number 排序
  4233. $segments = DB::table('mp_episode_segments')
  4234. ->where('anime_id', $animeId)
  4235. ->where('episode_id', $episodeId)
  4236. ->orderBy('segment_number')
  4237. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4238. ->get();
  4239. // 检查是否所有分镜都有配音和视频
  4240. $missingVideos = $segments->filter(function($segment) {
  4241. return empty($segment->audio_url) || empty($segment->video_url);
  4242. });
  4243. if ($missingVideos->isNotEmpty()) {
  4244. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4245. }
  4246. }
  4247. if ($segments->isEmpty()) {
  4248. Utils::throwError('20003:未找到该剧集的分镜数据');
  4249. }
  4250. // 获取当前完整视频url
  4251. $completeVideoUrl = DB::table('mp_anime_episodes')
  4252. ->where('anime_id', $animeId)
  4253. ->where('id', $episodeId)
  4254. ->value('complete_video_url');
  4255. // 构建 generate_json
  4256. $generateJson = [];
  4257. $sequence = 1;
  4258. foreach ($segments as $segment) {
  4259. if ((int)$ace_mode === 1) {
  4260. $generateJson[] = [
  4261. 'sequence' => $sequence++,
  4262. 'video_url' => $segment->video_url,
  4263. 'video_time_point_start' => $segment->video_time_point_start,
  4264. 'video_time_point_end' => $segment->video_time_point_end
  4265. ];
  4266. }else {
  4267. $generateJson[] = [
  4268. 'sequence' => $sequence++,
  4269. 'video_url' => $segment->video_url,
  4270. 'audio_url' => $segment->audio_url,
  4271. 'video_time_point_start' => $segment->video_time_point_start,
  4272. 'video_time_point_end' => $segment->video_time_point_end
  4273. ];
  4274. }
  4275. }
  4276. // 创建任务
  4277. $now = date('Y-m-d H:i:s');
  4278. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4279. 'anime_id' => $animeId,
  4280. 'episode_id' => $episodeId,
  4281. 'generate_json' => json_encode($generateJson, 256),
  4282. 'generate_status' => '执行中',
  4283. 'complete_video_url' => '',
  4284. 'created_at' => $now,
  4285. 'updated_at' => $now
  4286. ]);
  4287. if (!$taskId) {
  4288. Utils::throwError('20003:创建任务失败');
  4289. }
  4290. // 更新剧集表的任务ID和状态
  4291. $boolen = DB::table('mp_anime_episodes')
  4292. ->where('anime_id', $animeId)
  4293. ->where('id', $episodeId)
  4294. ->update([
  4295. 'complete_video_task_id' => $taskId,
  4296. 'complete_video_task_status' => '执行中',
  4297. 'updated_at' => $now
  4298. ]);
  4299. if (!$boolen) {
  4300. Utils::throwError('20003:更新剧集表失败');
  4301. }
  4302. dLog('anime')->info('创建完整视频合成任务', [
  4303. 'task_id' => $taskId,
  4304. 'anime_id' => $animeId,
  4305. 'episode_id' => $episodeId,
  4306. 'segment_count' => count($generateJson)
  4307. ]);
  4308. // 请求远程服务器执行生成
  4309. $client = new Client(['timeout' => 600, 'verify' => false]);
  4310. try {
  4311. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4312. $response = $result->getBody()->getContents();
  4313. $response_arr = json_decode($response, true);
  4314. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4315. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4316. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4317. // // 更新任务状态为失败
  4318. // DB::table('mp_complete_video_tasks')
  4319. // ->where('id', $taskId)
  4320. // ->update([
  4321. // 'generate_status' => '执行失败',
  4322. // 'error_message' => $error_msg,
  4323. // 'updated_at' => date('Y-m-d H:i:s')
  4324. // ]);
  4325. // // 同步更新剧集表状态
  4326. // DB::table('mp_anime_episodes')
  4327. // ->where('complete_video_task_id', $taskId)
  4328. // ->update([
  4329. // 'complete_video_task_status' => '执行失败',
  4330. // 'updated_at' => date('Y-m-d H:i:s')
  4331. // ]);
  4332. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4333. }
  4334. } catch (\Exception $e) {
  4335. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4336. // 更新任务状态为失败
  4337. DB::table('mp_complete_video_tasks')
  4338. ->where('id', $taskId)
  4339. ->update([
  4340. 'generate_status' => '执行失败',
  4341. 'error_message' => $e->getMessage(),
  4342. 'updated_at' => date('Y-m-d H:i:s')
  4343. ]);
  4344. // 同步更新剧集表状态
  4345. DB::table('mp_anime_episodes')
  4346. ->where('complete_video_task_id', $taskId)
  4347. ->update([
  4348. 'complete_video_task_status' => '执行失败',
  4349. 'updated_at' => date('Y-m-d H:i:s')
  4350. ]);
  4351. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4352. }
  4353. // 开始轮询任务状态
  4354. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4355. $pollInterval = 5; // 每5秒轮询一次
  4356. $attempt = 0;
  4357. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4358. while ($attempt < $maxAttempts) {
  4359. sleep($pollInterval);
  4360. $attempt++;
  4361. // 查询任务状态
  4362. $task = DB::table('mp_complete_video_tasks')
  4363. ->where('id', $taskId)
  4364. ->first();
  4365. if (!$task) {
  4366. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4367. Utils::throwError('20003:任务不存在');
  4368. }
  4369. dLog('anime')->info('轮询任务状态', [
  4370. 'task_id' => $taskId,
  4371. 'attempt' => $attempt,
  4372. 'status' => $task->generate_status
  4373. ]);
  4374. // 检查任务是否完成
  4375. if ($task->generate_status === '执行成功') {
  4376. // 同步更新剧集表状态
  4377. $boolen3 = DB::table('mp_anime_episodes')
  4378. ->where('anime_id', $animeId)
  4379. ->where('id', $episodeId)
  4380. ->update([
  4381. 'complete_video_url' => $task->complete_video_url,
  4382. 'complete_video_task_status' => '执行成功',
  4383. 'updated_at' => date('Y-m-d H:i:s')
  4384. ]);
  4385. dLog('anime')->info('视频合成任务完成', [
  4386. 'task_id' => $taskId,
  4387. 'video_url' => $task->complete_video_url,
  4388. 'attempts' => $attempt
  4389. ]);
  4390. // 如果更新成功则远程删除之前的文件
  4391. if ($boolen3 && $completeVideoUrl) {
  4392. $encode_url = urlencode($completeVideoUrl);
  4393. $client = new Client(['timeout' => 300, 'verify' => false]);
  4394. // 根据ID通过API通知合成音频
  4395. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4396. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4397. $response = $result->getBody()->getContents();
  4398. $response_arr = json_decode($response, true);
  4399. Log::info('火山删除音频返回: '.$response);
  4400. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4401. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4402. Log::info('火山删除音频失败: '.$error_msg);
  4403. // Utils::throwError('20003:火山删除音频失败');
  4404. }
  4405. }
  4406. return [
  4407. 'task_id' => $taskId,
  4408. 'anime_id' => $animeId,
  4409. 'episode_id' => $episodeId,
  4410. 'segment_count' => count($generateJson),
  4411. 'generate_status' => '执行成功',
  4412. 'complete_video_url' => $task->complete_video_url,
  4413. ];
  4414. }
  4415. // 检查任务是否失败
  4416. if ($task->generate_status === '执行失败') {
  4417. // 同步更新剧集表状态
  4418. DB::table('mp_anime_episodes')
  4419. ->where('anime_id', $animeId)
  4420. ->where('id', $episodeId)
  4421. ->update([
  4422. 'complete_video_task_status' => '执行失败',
  4423. 'updated_at' => date('Y-m-d H:i:s')
  4424. ]);
  4425. $errorMessage = $task->error_message ?? '未知错误';
  4426. dLog('anime')->error('视频合成任务失败', [
  4427. 'task_id' => $taskId,
  4428. 'error' => $errorMessage,
  4429. 'attempts' => $attempt
  4430. ]);
  4431. return [
  4432. 'task_id' => $taskId,
  4433. 'anime_id' => $animeId,
  4434. 'episode_id' => $episodeId,
  4435. 'segment_count' => count($generateJson),
  4436. 'generate_status' => '执行失败',
  4437. 'error_message' => $errorMessage
  4438. ];
  4439. }
  4440. }
  4441. // 超时处理
  4442. dLog('anime')->warning('视频合成任务超时', [
  4443. 'task_id' => $taskId,
  4444. 'max_attempts' => $maxAttempts,
  4445. 'timeout_seconds' => $maxAttempts * $pollInterval
  4446. ]);
  4447. // 更新任务状态为超时
  4448. DB::table('mp_complete_video_tasks')
  4449. ->where('id', $taskId)
  4450. ->update([
  4451. 'generate_status' => '超时',
  4452. 'error_message' => '任务执行超时(5分钟)',
  4453. 'updated_at' => date('Y-m-d H:i:s')
  4454. ]);
  4455. return [
  4456. 'task_id' => $taskId,
  4457. 'anime_id' => $animeId,
  4458. 'episode_id' => $episodeId,
  4459. 'segment_count' => count($generateJson),
  4460. 'generate_status' => '超时',
  4461. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4462. ];
  4463. }
  4464. public function generateImg($data) {
  4465. $prompt = getProp($data, 'prompt');
  4466. $episode_id = getProp($data, 'episode_id');
  4467. $ref_img_urls = getProp($data, 'ref_img_urls');
  4468. $ratio = getProp($data, 'ratio', '9:16');
  4469. $resolution = getProp($data, 'resolution', '2k');
  4470. // 定义分辨率和宽高比对应的尺寸映射表
  4471. $sizeMap = [
  4472. '2k' => [
  4473. '1:1' => ['width' => 2048, 'height' => 2048],
  4474. '4:3' => ['width' => 2304, 'height' => 1728],
  4475. '3:4' => ['width' => 1728, 'height' => 2304],
  4476. '16:9' => ['width' => 2848, 'height' => 1600],
  4477. '9:16' => ['width' => 1600, 'height' => 2848],
  4478. '3:2' => ['width' => 2496, 'height' => 1664],
  4479. '2:3' => ['width' => 1664, 'height' => 2496],
  4480. '21:9' => ['width' => 3136, 'height' => 1344],
  4481. ],
  4482. '3k' => [
  4483. '1:1' => ['width' => 3072, 'height' => 3072],
  4484. '4:3' => ['width' => 3456, 'height' => 2592],
  4485. '3:4' => ['width' => 2592, 'height' => 3456],
  4486. '16:9' => ['width' => 4096, 'height' => 2304],
  4487. '9:16' => ['width' => 2304, 'height' => 4096],
  4488. '2:3' => ['width' => 2496, 'height' => 3744],
  4489. '3:2' => ['width' => 3744, 'height' => 2496],
  4490. '21:9' => ['width' => 4704, 'height' => 2016],
  4491. ],
  4492. '4k' => [
  4493. '1:1' => ['width' => 4096, 'height' => 4096],
  4494. '3:4' => ['width' => 3520, 'height' => 4704],
  4495. '4:3' => ['width' => 4704, 'height' => 3520],
  4496. '16:9' => ['width' => 5504, 'height' => 3040],
  4497. '9:16' => ['width' => 3040, 'height' => 5504],
  4498. '2:3' => ['width' => 3328, 'height' => 4992],
  4499. '3:2' => ['width' => 4992, 'height' => 3328],
  4500. '21:9' => ['width' => 6240, 'height' => 2656],
  4501. ],
  4502. ];
  4503. // 参数验证
  4504. $resolution = strtolower($resolution);
  4505. if (!isset($sizeMap[$resolution])) {
  4506. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4507. }
  4508. if (!isset($sizeMap[$resolution][$ratio])) {
  4509. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4510. }
  4511. // 根据 ratio 和 resolution 确定宽高
  4512. $width = $sizeMap[$resolution][$ratio]['width'];
  4513. $height = $sizeMap[$resolution][$ratio]['height'];
  4514. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4515. if (is_json($ref_img_urls)) {
  4516. $ref_img_urls = json_decode($ref_img_urls, true);
  4517. }else {
  4518. $ref_img_urls = explode(',', $ref_img_urls);
  4519. }
  4520. }
  4521. // 处理图片模型
  4522. $model = getProp($data, 'model');
  4523. if (!$model) {
  4524. // 用户没有输入,从episode表获取
  4525. if ($episode_id) {
  4526. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4527. $model = getProp($episode, 'image_model');
  4528. }
  4529. if (!$model) {
  4530. // episode表也没有,使用默认值
  4531. $model = 'doubao-seedream-5-0-lite-260128';
  4532. }
  4533. }
  4534. // 验证模型是否在可用模型表中
  4535. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4536. // $model = 'doubao-seedream-5-0-lite-260128';
  4537. Utils::throwError('20003:该模型已不可用,请更换!');
  4538. }
  4539. // 保存到episode表
  4540. if ($episode_id) {
  4541. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4542. 'image_model' => $model,
  4543. 'updated_at' => date('Y-m-d H:i:s')
  4544. ]);
  4545. }
  4546. // 参数验证
  4547. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4548. try {
  4549. // 创建图片生成任务
  4550. $params = [
  4551. 'prompt' => $prompt,
  4552. 'model' => $model,
  4553. 'ref_img_urls' => '',
  4554. 'width' => $width,
  4555. 'height' => $height
  4556. ];
  4557. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4558. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4559. $task_id = $task->id;
  4560. if (!$task_id) {
  4561. Utils::throwError('20003:创建图片生成任务失败');
  4562. }
  4563. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4564. $model = getProp($task, 'model');
  4565. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4566. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4567. $isSyncModel = $isVolcModel || $isGptModel;
  4568. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4569. $start_time = time();
  4570. $timeout = 300; // 5分钟
  4571. $img_url = '';
  4572. while (time() - $start_time < $timeout) {
  4573. sleep(3);
  4574. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4575. if ($isSyncModel) {
  4576. // 刷新任务状态
  4577. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4578. if ($task->status === 'success' && $task->result_url) {
  4579. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4580. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4581. break;
  4582. } elseif ($task->status === 'failed') {
  4583. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4584. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4585. }
  4586. // // 如果还在处理中,提示用户稍后查看
  4587. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4588. }else {
  4589. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4590. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4591. if ($statusInfo['status'] === 'success') {
  4592. $task->updateStatus('success', [
  4593. 'result_url' => $statusInfo['result_url'],
  4594. 'result_json' => $statusInfo['result_json'] ?? []
  4595. ]);
  4596. $img_url = $statusInfo['result_url'][0];
  4597. break;
  4598. } elseif ($statusInfo['status'] === 'failed') {
  4599. $task->updateStatus('failed', [
  4600. 'error_message' => $statusInfo['error_message'],
  4601. 'result_json' => $statusInfo['result_json'] ?? []
  4602. ]);
  4603. dLog('anime')->error('图片生成失败,', [
  4604. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4605. ]);
  4606. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4607. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4608. }
  4609. }
  4610. }
  4611. if (empty($img_url)) {
  4612. Utils::throwError('20003:图片生成超时,请稍后重试');
  4613. }
  4614. return $img_url;
  4615. } catch (\Exception $e) {
  4616. dLog('anime')->error('更新角色或场景失败', [
  4617. 'error' => $e->getMessage()
  4618. ]);
  4619. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4620. Utils::throwError('20003:' . $e->getMessage());
  4621. }
  4622. }
  4623. /**
  4624. * 使用文生文模型解析分镜内容
  4625. */
  4626. private function parseSegmentContentWithAI($segment_content) {
  4627. try {
  4628. // 使用DeepSeek服务的公开方法解析分镜内容
  4629. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4630. } catch (\Exception $e) {
  4631. // 如果AI解析失败,记录日志并返回原内容
  4632. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4633. return $segment_content;
  4634. }
  4635. }
  4636. /**
  4637. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4638. *
  4639. * @param int $episode_id 分集ID
  4640. * @param int $anime_id 动漫ID
  4641. * @param array $roles 分集角色数组(引用传递)
  4642. * @param array $scenes 分集场景数组(引用传递)
  4643. * @param array $episode 分集数据
  4644. */
  4645. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4646. // 获取全局动漫的角色和场景数据
  4647. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4648. if (!$anime) return;
  4649. $art_style_type = getProp($anime, 'art_style_type');
  4650. $character_prefix = '';
  4651. $scene_prefix = '';
  4652. if ($art_style_type) {
  4653. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4654. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4655. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4656. }
  4657. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4658. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4659. $roles_updated = false;
  4660. $scenes_updated = false;
  4661. // 处理角色
  4662. foreach ($roles as &$role) {
  4663. $role_name = getProp($role, 'role');
  4664. $role_description = getProp($role, 'description');
  4665. $role_pic_prompt = getProp($role, 'pic_prompt');
  4666. $role_url = getProp($role, 'url');
  4667. $role_task_id = getProp($role, 'task_id');
  4668. // 如果已有URL或已有任务ID,跳过
  4669. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4670. continue;
  4671. }
  4672. $url_inherited = false;
  4673. // 尝试从全局数据中继承
  4674. foreach ($global_roles as $global_role) {
  4675. $global_role_name = getProp($global_role, 'role');
  4676. $global_role_description = getProp($global_role, 'description');
  4677. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4678. $global_role_url = getProp($global_role, 'url');
  4679. $global_role_task_id = getProp($global_role, 'task_id');
  4680. $global_role_task_status = getProp($global_role, 'task_status');
  4681. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4682. if ($role_name === $global_role_name
  4683. && $role_description === $global_role_description
  4684. && $role_pic_prompt === $global_role_pic_prompt
  4685. && !empty($global_role_url)) {
  4686. // 继承 task_id、task_status 和 url
  4687. $role['task_id'] = $global_role_task_id;
  4688. $role['task_status'] = $global_role_task_status;
  4689. $role['url'] = $global_role_url;
  4690. $roles_updated = true;
  4691. $url_inherited = true;
  4692. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4693. break;
  4694. }
  4695. }
  4696. // 如果无法继承且没有任务ID,创建新任务
  4697. if (!$url_inherited && empty($role_task_id)) {
  4698. try {
  4699. $art_style = getProp($episode, 'art_style');
  4700. // 优先使用 pic_prompt,如果没有则使用 description
  4701. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4702. // if ($art_style) {
  4703. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4704. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4705. // }
  4706. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4707. $params = [
  4708. 'prompt' => $description,
  4709. 'ref_img_urls' => []
  4710. ];
  4711. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4712. $task_id = $task->id;
  4713. if ($task_id) {
  4714. $role['task_id'] = $task_id;
  4715. $role['task_status'] = 'processing';
  4716. $roles_updated = true;
  4717. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4718. }
  4719. } catch (\Exception $e) {
  4720. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4721. }
  4722. }
  4723. }
  4724. // 处理场景
  4725. foreach ($scenes as &$scene) {
  4726. $scene_name = getProp($scene, 'scene');
  4727. $scene_description = getProp($scene, 'description');
  4728. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4729. $scene_url = getProp($scene, 'url');
  4730. $scene_task_id = getProp($scene, 'task_id');
  4731. // 如果已有URL或已有任务ID,跳过
  4732. if (!empty($scene_url) || !empty($scene_task_id)) {
  4733. continue;
  4734. }
  4735. $url_inherited = false;
  4736. // 尝试从全局数据中继承
  4737. foreach ($global_scenes as $global_scene) {
  4738. $global_scene_name = getProp($global_scene, 'scene');
  4739. $global_scene_description = getProp($global_scene, 'description');
  4740. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  4741. $global_scene_url = getProp($global_scene, 'url');
  4742. $global_scene_task_id = getProp($global_scene, 'task_id');
  4743. $global_scene_task_status = getProp($global_scene, 'task_status');
  4744. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  4745. if ($scene_name === $global_scene_name
  4746. && $scene_description === $global_scene_description
  4747. && $scene_pic_prompt === $global_scene_pic_prompt
  4748. && !empty($global_scene_url)) {
  4749. // 继承 task_id、task_status 和 url
  4750. $scene['task_id'] = $global_scene_task_id;
  4751. $scene['task_status'] = $global_scene_task_status;
  4752. $scene['url'] = $global_scene_url;
  4753. $scenes_updated = true;
  4754. $url_inherited = true;
  4755. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  4756. break;
  4757. }
  4758. }
  4759. // 如果无法继承且没有任务ID,创建新任务
  4760. if (!$url_inherited && empty($scene_task_id)) {
  4761. try {
  4762. $art_style = getProp($episode, 'art_style');
  4763. // 优先使用 pic_prompt,如果没有则使用 description
  4764. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  4765. // if ($art_style) {
  4766. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4767. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4768. // }
  4769. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4770. $params = [
  4771. 'prompt' => $description,
  4772. 'ref_img_urls' => []
  4773. ];
  4774. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4775. $task_id = $task->id;
  4776. if ($task_id) {
  4777. $scene['task_id'] = $task_id;
  4778. $scene['task_status'] = 'processing';
  4779. $scenes_updated = true;
  4780. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  4781. }
  4782. } catch (\Exception $e) {
  4783. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  4784. }
  4785. }
  4786. }
  4787. // 如果有更新,保存到数据库
  4788. if ($roles_updated || $scenes_updated) {
  4789. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  4790. if ($roles_updated) {
  4791. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  4792. }
  4793. if ($scenes_updated) {
  4794. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  4795. }
  4796. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  4797. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  4798. }
  4799. }
  4800. /**
  4801. * 根据图片URL使用AI反推图片提示词
  4802. *
  4803. * @param string $img_url 图片URL
  4804. * @return string 反推的提示词
  4805. */
  4806. private function generateImagePromptFromUrl($img_url) {
  4807. try {
  4808. // 获取默认模型
  4809. $model = 'doubao-seed-2-0-mini-260215';
  4810. // 构建messages参数
  4811. $messages = [
  4812. [
  4813. 'role' => 'user',
  4814. 'content' => [
  4815. [
  4816. 'type' => 'text',
  4817. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  4818. ],
  4819. [
  4820. 'type' => 'image_url',
  4821. 'image_url' => [
  4822. 'url' => $img_url
  4823. ]
  4824. ]
  4825. ]
  4826. ]
  4827. ];
  4828. // 构建请求参数
  4829. $params = [
  4830. 'model' => $model,
  4831. 'messages' => $messages,
  4832. 'stream' => false,
  4833. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  4834. ];
  4835. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  4836. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  4837. // 返回生成的内容
  4838. return getProp($result, 'fullContent', '图片描述生成失败');
  4839. } catch (\Exception $e) {
  4840. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  4841. 'img_url' => $img_url
  4842. ]);
  4843. logDB('anime', 'error', 'AI反推图片提示词失败', [
  4844. 'error' => $e->getMessage(),
  4845. 'img_url' => $img_url
  4846. ]);
  4847. return '图片描述生成失败: ' . $e->getMessage();
  4848. }
  4849. }
  4850. /**
  4851. * 音频试听接口
  4852. * 创建音频任务并轮询获取结果
  4853. *
  4854. * @param array $data 参数数组
  4855. * @return array 返回音频URL或错误信息
  4856. */
  4857. public function previewAudio($data) {
  4858. $dialogue = getProp($data, 'dialogue');
  4859. // 必填参数验证
  4860. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  4861. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  4862. $voice_type = getProp($data, 'voice_type');
  4863. $voice_name = getProp($data, 'voice_name');
  4864. $voice_actor = getProp($data, 'voice_actor');
  4865. $emotion_type = getProp($data, 'emotion_type');
  4866. $gender = getProp($data, 'gender', 0);
  4867. $emotion = getProp($data, 'emotion');
  4868. $speed_ratio = getProp($data, 'speed_ratio', 0);
  4869. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  4870. $emotion_scale = getProp($data, 'emotion_scale', 0);
  4871. $pitch = getProp($data, 'pitch', 0);
  4872. try {
  4873. $now = date('Y-m-d H:i:s');
  4874. // 构建生成参数
  4875. $generate_json = json_encode([
  4876. 'text' => $dialogue,
  4877. 'role' => $voice_actor,
  4878. 'voice_type' => $voice_type,
  4879. 'voice_name' => $voice_name,
  4880. 'emotion' => $emotion,
  4881. 'emotion_type' => $emotion_type,
  4882. 'gender' => $gender,
  4883. 'speed_ratio' => $speed_ratio,
  4884. 'loudness_ratio' => $loudness_ratio,
  4885. 'emotion_scale' => $emotion_scale,
  4886. 'pitch' => $pitch,
  4887. ], 256);
  4888. // 请求远程服务器执行生成
  4889. $client = new Client(['timeout' => 600, 'verify' => false]);
  4890. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  4891. $response = $result->getBody()->getContents();
  4892. $response_arr = json_decode($response, true);
  4893. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4894. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4895. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  4896. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  4897. }
  4898. $arr = $response_arr['data'];
  4899. $subtitle_info = $arr['subtitle_info'];
  4900. $audio_duration = json_decode($subtitle_info, true)['duration'];
  4901. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  4902. return [
  4903. 'audio_url' => $arr['url'],
  4904. 'subtitle_info' => $subtitle_info,
  4905. 'audio_duration' => round($audio_duration, 2)
  4906. ];
  4907. } catch (\Exception $e) {
  4908. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  4909. Utils::throwError('20003:' . $e->getMessage());
  4910. }
  4911. }
  4912. /**
  4913. * 获取角色库列表(支持文件夹递归查询)
  4914. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)
  4915. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  4916. */
  4917. public function globalProducts($data) {
  4918. $uid = Site::getUid();
  4919. $cpid = Site::getCpid();
  4920. $id = getProp($data, 'id', 0);
  4921. $parent_id = getProp($data, 'parent_id', 0);
  4922. $product_name = getProp($data, 'product_name');
  4923. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  4924. if (!$product) {
  4925. Utils::throwError('20003:请选择产品类型');
  4926. }
  4927. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  4928. if ($id || $product_name) {
  4929. $query = DB::table('mp_products')
  4930. ->where('cpid', $cpid)
  4931. ->where('user_id', $uid)
  4932. ->where('is_deleted', 0);
  4933. // 如果指定了 id,按 id 精确查询
  4934. if ($id) {
  4935. $query->where('id', $id);
  4936. }
  4937. // 如果指定了 product_name,按名称模糊查询
  4938. if ($product_name) {
  4939. $query->where('product_name', 'like', "%{$product_name}%");
  4940. }
  4941. // 如果指定了 product,添加筛选条件
  4942. if ($product) {
  4943. $query->where('product', $product);
  4944. }
  4945. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4946. ->orderByRaw('sort_order DESC, created_at DESC')
  4947. ->get()
  4948. ->map(function($value) {
  4949. $value = (array)$value;
  4950. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  4951. $value['type'] = (int)$value['type'];
  4952. $value['parent_id'] = (int)$value['parent_id'];
  4953. $value['level'] = (int)$value['level'];
  4954. $value['product'] = (int)($value['product'] ?? 1);
  4955. $value['versions'] = json_decode($value['versions'], true) ?: [];
  4956. return $value;
  4957. })
  4958. ->toArray();
  4959. return $result;
  4960. }
  4961. // 递归获取所有子目录和角色
  4962. return $this->getChildrenRecursive($cpid, $parent_id, $product, $uid);
  4963. }
  4964. /**
  4965. * 递归获取指定目录下的所有子目录和角色
  4966. * @param int $cpid 公司ID
  4967. * @param int $parent_id 父目录ID
  4968. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  4969. * @param int $uid 用户ID
  4970. * @return array
  4971. */
  4972. private function getChildrenRecursive($cpid, $parent_id, $product = null, $uid = null) {
  4973. // 查询当前层级的所有项(文件夹和角色)
  4974. $query = DB::table('mp_products')
  4975. ->where('cpid', $cpid)
  4976. ->where('is_deleted', 0)
  4977. ->where('parent_id', $parent_id);
  4978. // 添加用户ID验证
  4979. if ($uid) {
  4980. $query->where('user_id', $uid);
  4981. }
  4982. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  4983. if ($product) {
  4984. $query->where('product', $product);
  4985. }
  4986. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4987. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  4988. ->get();
  4989. $result = [];
  4990. foreach ($items as $item) {
  4991. $itemArray = [
  4992. 'id' => $item->id,
  4993. 'type' => (int)$item->type,
  4994. 'parent_id' => (int)$item->parent_id,
  4995. 'level' => (int)$item->level,
  4996. 'product_name' => $item->product_name,
  4997. 'url' => $item->url,
  4998. 'pic_prompt' => $item->pic_prompt ?? '',
  4999. 'three_view_image_url' => $item->three_view_image_url,
  5000. 'product' => (int)($item->product ?? 1),
  5001. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5002. ];
  5003. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5004. // 如果是文件夹,递归获取其子项
  5005. if ($item->type == 2) {
  5006. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $uid);
  5007. if (!empty($children)) {
  5008. $itemArray['children'] = $children;
  5009. }
  5010. }
  5011. $result[] = $itemArray;
  5012. }
  5013. return $result;
  5014. }
  5015. /**
  5016. * 创建文件夹
  5017. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5018. * @return int 返回新建文件夹ID
  5019. */
  5020. public function createFolder($data) {
  5021. $uid = Site::getUid();
  5022. $cpid = Site::getCpid();
  5023. $parent_id = getProp($data, 'parent_id', 0);
  5024. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5025. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5026. $product = getProp($data, 'product');
  5027. if (!in_array($product, [1, 2, 3])) {
  5028. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5029. }
  5030. // 验证父文件夹
  5031. $parent_level = 0;
  5032. if ($parent_id > 0) {
  5033. $parent = DB::table('mp_products')
  5034. ->where('id', $parent_id)
  5035. ->where('type', 2)
  5036. ->where('is_deleted', 0)
  5037. ->first();
  5038. if (!$parent) {
  5039. Utils::throwError('20003:父文件夹不存在');
  5040. }
  5041. // 检查父文件夹的 product 类型是否一致
  5042. if ($parent->product != $product) {
  5043. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5044. }
  5045. $parent_level = $parent->level;
  5046. // 检查层级限制(最多3层)
  5047. if ($parent_level >= 3) {
  5048. Utils::throwError('20003:文件夹层级不能超过3层');
  5049. }
  5050. }
  5051. // 检查当前目录下是否已存在空白文件夹
  5052. $empty_folder_exists = DB::table('mp_products')
  5053. ->where('parent_id', $parent_id)
  5054. ->where('type', 2)
  5055. ->where('product', $product)
  5056. ->where('product_name', '新建文件夹')
  5057. ->where('is_deleted', 0)
  5058. ->exists();
  5059. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5060. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5061. }
  5062. // 创建文件夹
  5063. $folder_id = DB::table('mp_products')->insertGetId([
  5064. 'user_id' => $uid,
  5065. 'cpid' => $cpid,
  5066. 'type' => 2,
  5067. 'parent_id' => $parent_id,
  5068. 'level' => $parent_level + 1,
  5069. 'product_name' => $folder_name,
  5070. 'product' => $product,
  5071. 'sort_order' => time(), // 使用时间戳作为排序权重
  5072. 'is_deleted' => 0,
  5073. 'created_at' => date('Y-m-d H:i:s'),
  5074. 'updated_at' => date('Y-m-d H:i:s')
  5075. ]);
  5076. return [
  5077. 'id' => $folder_id,
  5078. 'type' => 2,
  5079. 'parent_id' => $parent_id,
  5080. 'level' => $parent_level + 1,
  5081. 'product_name' => $folder_name,
  5082. 'product' => $product,
  5083. ];
  5084. }
  5085. /**
  5086. * 重命名文件夹或角色
  5087. * @param array $data 包含 id、product_name(新名称)
  5088. * @return bool
  5089. */
  5090. public function renameFolder($data) {
  5091. $uid = Site::getUid();
  5092. $cpid = Site::getCpid();
  5093. $id = getProp($data, 'id');
  5094. $new_name = getProp($data, 'product_name');
  5095. if (!$id || !$new_name) {
  5096. Utils::throwError('20003:参数不完整');
  5097. }
  5098. // 检查是否存在
  5099. $item = DB::table('mp_products')
  5100. ->where('id', $id)
  5101. ->where('cpid', $cpid)
  5102. ->where('is_deleted', 0)
  5103. ->first();
  5104. if (!$item) {
  5105. Utils::throwError('20003:项目不存在');
  5106. }
  5107. return DB::table('mp_products')
  5108. ->where('id', $id)
  5109. ->where('cpid', $cpid)
  5110. ->update([
  5111. 'product_name' => $new_name,
  5112. 'updated_at' => date('Y-m-d H:i:s')
  5113. ]);
  5114. }
  5115. /**
  5116. * 移动角色或文件夹到指定文件夹
  5117. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5118. * @return bool
  5119. */
  5120. public function moveProductOrFolder($data) {
  5121. $cpid = Site::getCpid();
  5122. $id = getProp($data, 'id');
  5123. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5124. if (!$id) {
  5125. Utils::throwError('20003:请选择要移动的项目');
  5126. }
  5127. // 检查要移动的项目
  5128. $item = DB::table('mp_products')
  5129. ->where('id', $id)
  5130. ->where('cpid', $cpid)
  5131. ->where('is_deleted', 0)
  5132. ->first();
  5133. if (!$item) {
  5134. Utils::throwError('20003:项目不存在');
  5135. }
  5136. // 验证目标文件夹
  5137. $target_level = 0;
  5138. $target_product = $item->product; // 默认使用当前项目的 product
  5139. if ($target_parent_id > 0) {
  5140. $target_parent = DB::table('mp_products')
  5141. ->where('id', $target_parent_id)
  5142. ->where('cpid', $cpid)
  5143. ->where('type', 2)
  5144. ->where('is_deleted', 0)
  5145. ->first();
  5146. if (!$target_parent) {
  5147. Utils::throwError('20003:目标文件夹不存在');
  5148. }
  5149. // 检查 product 类型是否一致
  5150. if ($target_parent->product != $item->product) {
  5151. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5152. }
  5153. $target_level = $target_parent->level;
  5154. $target_product = $target_parent->product;
  5155. // 如果移动的是文件夹,需要检查层级
  5156. if ($item->type == 2) {
  5157. // 计算移动后的最大层级
  5158. $max_child_level = $this->getMaxChildLevel($id);
  5159. $depth = $max_child_level - $item->level;
  5160. if ($target_level + 1 + $depth > 3) {
  5161. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5162. }
  5163. // 不能移动到自己或自己的子文件夹下
  5164. if ($this->isDescendant($target_parent_id, $id)) {
  5165. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5166. }
  5167. }
  5168. }
  5169. // 更新父文件夹和层级
  5170. $new_level = $target_level + 1;
  5171. DB::table('mp_products')
  5172. ->where('id', $id)
  5173. ->update([
  5174. 'parent_id' => $target_parent_id,
  5175. 'level' => $new_level,
  5176. 'updated_at' => date('Y-m-d H:i:s')
  5177. ]);
  5178. // 如果是文件夹,需要递归更新所有子项的层级
  5179. if ($item->type == 2) {
  5180. $this->updateChildrenLevel($id, $new_level);
  5181. }
  5182. return true;
  5183. }
  5184. /**
  5185. * 获取文件夹下最大子层级
  5186. * @param int $folder_id
  5187. * @return int
  5188. */
  5189. private function getMaxChildLevel($folder_id) {
  5190. $max_level = DB::table('mp_products')
  5191. ->where('parent_id', $folder_id)
  5192. ->where('is_deleted', 0)
  5193. ->max('level');
  5194. if (!$max_level) {
  5195. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5196. }
  5197. // 递归查找子文件夹
  5198. $children = DB::table('mp_products')
  5199. ->where('parent_id', $folder_id)
  5200. ->where('type', 2)
  5201. ->where('is_deleted', 0)
  5202. ->pluck('id');
  5203. foreach ($children as $child_id) {
  5204. $child_max = $this->getMaxChildLevel($child_id);
  5205. if ($child_max > $max_level) {
  5206. $max_level = $child_max;
  5207. }
  5208. }
  5209. return $max_level;
  5210. }
  5211. /**
  5212. * 检查 target_id 是否是 folder_id 的后代
  5213. * @param int $target_id
  5214. * @param int $folder_id
  5215. * @return bool
  5216. */
  5217. private function isDescendant($target_id, $folder_id) {
  5218. if ($target_id == $folder_id) {
  5219. return true;
  5220. }
  5221. $parent = DB::table('mp_products')
  5222. ->where('id', $target_id)
  5223. ->where('is_deleted', 0)
  5224. ->first();
  5225. if (!$parent || $parent->parent_id == 0) {
  5226. return false;
  5227. }
  5228. return $this->isDescendant($parent->parent_id, $folder_id);
  5229. }
  5230. /**
  5231. * 递归更新子项层级
  5232. * @param int $parent_id
  5233. * @param int $parent_level
  5234. */
  5235. private function updateChildrenLevel($parent_id, $parent_level) {
  5236. $children = DB::table('mp_products')
  5237. ->where('parent_id', $parent_id)
  5238. ->where('is_deleted', 0)
  5239. ->get();
  5240. foreach ($children as $child) {
  5241. $new_level = $parent_level + 1;
  5242. DB::table('mp_products')
  5243. ->where('id', $child->id)
  5244. ->update([
  5245. 'level' => $new_level,
  5246. 'updated_at' => date('Y-m-d H:i:s')
  5247. ]);
  5248. // 如果是文件夹,继续递归
  5249. if ($child->type == 2) {
  5250. $this->updateChildrenLevel($child->id, $new_level);
  5251. }
  5252. }
  5253. }
  5254. /**
  5255. * 获取文件夹路径(面包屑导航)
  5256. * @param array $data 包含 folder_id
  5257. * @return array 返回路径数组
  5258. */
  5259. public function getFolderPath($data) {
  5260. $folder_id = getProp($data, 'id', 0);
  5261. if ($folder_id == 0) {
  5262. return [
  5263. ['id' => 0, 'name' => '根目录']
  5264. ];
  5265. }
  5266. $path = [];
  5267. $current_id = $folder_id;
  5268. while ($current_id > 0) {
  5269. $folder = DB::table('mp_products')
  5270. ->where('id', $current_id)
  5271. ->where('type', 2)
  5272. ->where('is_deleted', 0)
  5273. ->first();
  5274. if (!$folder) {
  5275. break;
  5276. }
  5277. array_unshift($path, [
  5278. 'id' => $folder->id,
  5279. 'name' => $folder->product_name
  5280. ]);
  5281. $current_id = $folder->parent_id;
  5282. }
  5283. // 添加根目录
  5284. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5285. return $path;
  5286. }
  5287. public function createProduct($data) {
  5288. $uid = Site::getUid();
  5289. $cpid = Site::getCpid();
  5290. $product_name = trim(getProp($data, 'product_name'));
  5291. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5292. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5293. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5294. $url = trim(getProp($data, 'url'));
  5295. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5296. $versions = getProp($data, 'versions');
  5297. // 检查是否是正确的图片格式
  5298. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5299. $urlPath = parse_url($url, PHP_URL_PATH);
  5300. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5301. if (!in_array($extension, $allowedExtensions)) {
  5302. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5303. }
  5304. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5305. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5306. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5307. $product = getProp($data, 'product');
  5308. if (!in_array($product, [1, 2, 3])) {
  5309. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5310. }
  5311. // 获取父文件夹ID和层级
  5312. $parent_id = getProp($data, 'parent_id', 0);
  5313. $parent_level = 0;
  5314. if ($parent_id > 0) {
  5315. $parent = DB::table('mp_products')
  5316. ->where('id', $parent_id)
  5317. ->where('cpid', $cpid)
  5318. ->where('type', 2)
  5319. ->where('is_deleted', 0)
  5320. ->first();
  5321. if (!$parent) {
  5322. Utils::throwError('20003:父文件夹不存在');
  5323. }
  5324. $parent_level = $parent->level;
  5325. }
  5326. $id = DB::table('mp_products')->insertGetId([
  5327. 'user_id' => $uid,
  5328. 'cpid' => $cpid,
  5329. 'type' => 1, // 1=角色图片
  5330. 'parent_id' => $parent_id,
  5331. 'level' => $parent_level + 1,
  5332. 'product_name' => $product_name,
  5333. 'url' => $url,
  5334. 'pic_prompt' => $pic_prompt,
  5335. 'product' => $product,
  5336. 'versions' => json_encode($versions, 256),
  5337. 'sort_order' => time(), // 使用时间戳作为排序权重
  5338. 'created_at' => date('Y-m-d H:i:s'),
  5339. 'updated_at' => date('Y-m-d H:i:s')
  5340. ]);
  5341. if (!$id) Utils::throwError('20003:创建失败');
  5342. return [
  5343. 'id' => $id,
  5344. 'type' => 1,
  5345. 'parent_id' => $parent_id,
  5346. 'level' => $parent_level + 1,
  5347. 'product_name' => $product_name,
  5348. 'url' => $url,
  5349. 'pic_prompt' => $pic_prompt,
  5350. 'product' => $product,
  5351. 'versions' => $versions
  5352. ];
  5353. }
  5354. public function editProduct($data) {
  5355. $uid = Site::getUid();
  5356. $cpid = Site::getCpid();
  5357. $id = getProp($data, 'id');
  5358. if (!$id) Utils::throwError('20003:ID不能为空');
  5359. $versions = getProp($data, 'versions');
  5360. // 检查是否存在且属于当前用户
  5361. $role = DB::table('mp_products')
  5362. ->where('id', $id)
  5363. ->where('cpid', $cpid)
  5364. ->where('type', 1)->first();
  5365. if (!$role) Utils::throwError('20003:记录不存在');
  5366. $updateData = [];
  5367. // $needVersionRecord = false; // 是否需要记录版本
  5368. // 名称
  5369. $product_name = trim(getProp($data, 'product_name'));
  5370. if ($product_name) {
  5371. $updateData['product_name'] = $product_name;
  5372. }
  5373. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5374. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5375. // 图片地址
  5376. $url = trim(getProp($data, 'url'));
  5377. if ($url) {
  5378. // 检查是否是正确的图片格式
  5379. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5380. $urlPath = parse_url($url, PHP_URL_PATH);
  5381. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5382. if (!in_array($extension, $allowedExtensions)) {
  5383. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5384. }
  5385. // // 如果 url 有变更,记录版本
  5386. // if ($url !== $role->url) {
  5387. // $needVersionRecord = true;
  5388. // }
  5389. $updateData['url'] = $url;
  5390. }
  5391. // 提示词
  5392. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5393. if ($pic_prompt) {
  5394. // // 如果 pic_prompt 有变更,记录版本
  5395. // if ($pic_prompt !== $role->pic_prompt) {
  5396. // $needVersionRecord = true;
  5397. // }
  5398. $updateData['pic_prompt'] = $pic_prompt;
  5399. }
  5400. if (empty($updateData)) {
  5401. Utils::throwError('20003:没有需要更新的数据');
  5402. }
  5403. // // 如果需要记录版本,将数据添加到 versions 数组
  5404. // if ($needVersionRecord) {
  5405. // // 获取现有的 versions 数据
  5406. // $versions = json_decode($role->versions, true) ?: [];
  5407. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5408. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5409. // if ($isFirstVersion) {
  5410. // $oldVersion = [
  5411. // 'url' => $role->url,
  5412. // 'description' => $role->pic_prompt,
  5413. // ];
  5414. // // 旧版本添加到数组末尾
  5415. // $versions[] = $oldVersion;
  5416. // }
  5417. // // 构建新版本(变更后)
  5418. // $newVersion = [
  5419. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5420. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5421. // ];
  5422. // // 检查新版本是否已存在于历史版本中
  5423. // $existingIndex = -1;
  5424. // foreach ($versions as $index => $version) {
  5425. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5426. // $existingIndex = $index;
  5427. // break;
  5428. // }
  5429. // }
  5430. // if ($existingIndex !== -1) {
  5431. // // 如果已存在,移除旧的位置
  5432. // array_splice($versions, $existingIndex, 1);
  5433. // }
  5434. // // 新版本添加到数组开头(最新的在前)
  5435. // array_unshift($versions, $newVersion);
  5436. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5437. // // if (count($versions) > 10) {
  5438. // // $versions = array_slice($versions, 0, 10);
  5439. // // }
  5440. // $updateData['versions'] = json_encode($versions, 256);
  5441. // }
  5442. if ($versions) {
  5443. $updateData['versions'] = json_encode($versions, 256);
  5444. }
  5445. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5446. return DB::table('mp_products')
  5447. ->where('cpid', $cpid)
  5448. ->where('id', $id)->update($updateData);
  5449. }
  5450. /**
  5451. * 获取角色版本历史
  5452. * @param array $data 包含 id(角色ID)
  5453. * @return array 返回版本历史列表
  5454. */
  5455. public function getProductVersions($data) {
  5456. $cpid = Site::getCpid();
  5457. $id = getProp($data, 'id');
  5458. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5459. $role = DB::table('mp_products')
  5460. ->where('id', $id)
  5461. ->where('cpid', $cpid)
  5462. ->where('type', 1)
  5463. ->first();
  5464. if (!$role) Utils::throwError('20003:角色不存在');
  5465. // 获取版本历史
  5466. $versions = json_decode($role->versions, true) ?: [];
  5467. // 添加当前版本作为最新版本
  5468. $currentVersion = [
  5469. 'version' => 0, // 0 表示当前版本
  5470. 'url' => $role->url,
  5471. 'pic_prompt' => $role->pic_prompt,
  5472. 'updated_at' => $role->updated_at,
  5473. 'is_current' => true
  5474. ];
  5475. array_unshift($versions, $currentVersion);
  5476. return $versions;
  5477. }
  5478. /**
  5479. * 恢复到指定版本
  5480. * @param array $data 包含 id(角色ID)、version(版本号)
  5481. * @return bool
  5482. */
  5483. public function restoreProductVersion($data) {
  5484. $uid = Site::getUid();
  5485. $cpid = Site::getCpid();
  5486. $id = getProp($data, 'id');
  5487. $version = getProp($data, 'version');
  5488. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5489. if (!$version) Utils::throwError('20003:版本号不能为空');
  5490. $role = DB::table('mp_products')
  5491. ->where('id', $id)
  5492. ->where('cpid', $cpid)
  5493. ->where('type', 1)
  5494. ->first();
  5495. if (!$role) Utils::throwError('20003:角色不存在');
  5496. // 获取版本历史
  5497. $versions = json_decode($role->versions, true) ?: [];
  5498. // 查找指定版本
  5499. $targetVersion = null;
  5500. foreach ($versions as $v) {
  5501. if ($v['version'] == $version) {
  5502. $targetVersion = $v;
  5503. break;
  5504. }
  5505. }
  5506. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5507. // 先将当前版本保存到历史
  5508. $newVersion = [
  5509. 'version' => count($versions) + 1,
  5510. 'url' => $role->url,
  5511. 'pic_prompt' => $role->pic_prompt,
  5512. 'updated_at' => date('Y-m-d H:i:s'),
  5513. 'updated_by' => $uid
  5514. ];
  5515. array_unshift($versions, $newVersion);
  5516. // 限制版本数量
  5517. if (count($versions) > 10) {
  5518. $versions = array_slice($versions, 0, 10);
  5519. }
  5520. // 恢复到指定版本
  5521. return DB::table('mp_products')
  5522. ->where('id', $id)
  5523. ->where('cpid', $cpid)
  5524. ->update([
  5525. 'url' => $targetVersion['url'],
  5526. 'pic_prompt' => $targetVersion['pic_prompt'],
  5527. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5528. 'updated_at' => date('Y-m-d H:i:s')
  5529. ]);
  5530. }
  5531. public function deleteProduct($data) {
  5532. $uid = Site::getUid();
  5533. $cpid = Site::getCpid();
  5534. $id = getProp($data, 'id');
  5535. if (!$id) Utils::throwError('20003:ID不能为空');
  5536. $ids = explode(',', $id);
  5537. // 检查是否存在且属于当前用户
  5538. $role = DB::table('mp_products')
  5539. ->whereIn('id', $ids)
  5540. ->where('cpid', $cpid)
  5541. ->get();
  5542. if (!$role) Utils::throwError('20003:记录不存在');
  5543. return DB::table('mp_products')
  5544. ->where('cpid', $cpid)
  5545. ->whereIn('id', $ids)
  5546. ->update([
  5547. 'is_deleted' => 1,
  5548. 'updated_at' => date('Y-m-d H:i:s')
  5549. ]);
  5550. }
  5551. public function generateThreeView($data) {
  5552. $uid = Site::getUid();
  5553. $cpid = Site::getCpid();
  5554. $id = getProp($data, 'id');
  5555. if (!$id) Utils::throwError('20003:ID不能为空');
  5556. // 检查是否存在且属于当前用户
  5557. $product = DB::table('mp_products')
  5558. ->where('id', $id)
  5559. ->where('cpid', $cpid)
  5560. ->where('type', 1)->first();
  5561. if (!$product) Utils::throwError('20003:资产不存在');
  5562. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5563. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5564. if (!$ref_img_url) {
  5565. // 如果没有传入参考图,使用角色表中的图片
  5566. $ref_img_url = $product->url ?? '';
  5567. if (!$ref_img_url) {
  5568. Utils::throwError('20003:参考图不能为空');
  5569. }
  5570. }
  5571. $pic_prompt = getProp($product, 'pic_prompt');
  5572. if ($pic_prompt) {
  5573. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  5574. }
  5575. // 检查参考图是否是正确的图片格式
  5576. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5577. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5578. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5579. if (!in_array($extension, $allowedExtensions)) {
  5580. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5581. }
  5582. // 处理图片模型
  5583. $model = getProp($data, 'model');
  5584. if (!$model) {
  5585. // 使用默认模型
  5586. $model = 'doubao-seedream-5-0-lite-260128';
  5587. }
  5588. // 验证模型是否在可用模型表中
  5589. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5590. Utils::throwError('20003:该模型已不可用,请更换!');
  5591. }
  5592. $ratio = getProp($data, 'ratio', '16:9');
  5593. $resolution = getProp($data, 'resolution', '2k');
  5594. // 定义分辨率和宽高比对应的尺寸映射表
  5595. $sizeMap = [
  5596. '2k' => [
  5597. '1:1' => ['width' => 2048, 'height' => 2048],
  5598. '4:3' => ['width' => 2304, 'height' => 1728],
  5599. '3:4' => ['width' => 1728, 'height' => 2304],
  5600. '16:9' => ['width' => 2848, 'height' => 1600],
  5601. '9:16' => ['width' => 1600, 'height' => 2848],
  5602. '3:2' => ['width' => 2496, 'height' => 1664],
  5603. '2:3' => ['width' => 1664, 'height' => 2496],
  5604. '21:9' => ['width' => 3136, 'height' => 1344],
  5605. ],
  5606. '3k' => [
  5607. '1:1' => ['width' => 3072, 'height' => 3072],
  5608. '4:3' => ['width' => 3456, 'height' => 2592],
  5609. '3:4' => ['width' => 2592, 'height' => 3456],
  5610. '16:9' => ['width' => 4096, 'height' => 2304],
  5611. '9:16' => ['width' => 2304, 'height' => 4096],
  5612. '2:3' => ['width' => 2496, 'height' => 3744],
  5613. '3:2' => ['width' => 3744, 'height' => 2496],
  5614. '21:9' => ['width' => 4704, 'height' => 2016],
  5615. ],
  5616. '4k' => [
  5617. '1:1' => ['width' => 4096, 'height' => 4096],
  5618. '3:4' => ['width' => 3520, 'height' => 4704],
  5619. '4:3' => ['width' => 4704, 'height' => 3520],
  5620. '16:9' => ['width' => 5504, 'height' => 3040],
  5621. '9:16' => ['width' => 3040, 'height' => 5504],
  5622. '2:3' => ['width' => 3328, 'height' => 4992],
  5623. '3:2' => ['width' => 4992, 'height' => 3328],
  5624. '21:9' => ['width' => 6240, 'height' => 2656],
  5625. ],
  5626. ];
  5627. // 参数验证
  5628. $resolution = strtolower($resolution);
  5629. if (!isset($sizeMap[$resolution])) {
  5630. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5631. }
  5632. if (!isset($sizeMap[$resolution][$ratio])) {
  5633. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5634. }
  5635. // 根据 ratio 和 resolution 确定宽高
  5636. $width = $sizeMap[$resolution][$ratio]['width'];
  5637. $height = $sizeMap[$resolution][$ratio]['height'];
  5638. try {
  5639. // 创建图片生成任务
  5640. $params = [
  5641. 'prompt' => $prompt,
  5642. 'model' => $model,
  5643. 'ref_img_urls' => [$ref_img_url],
  5644. 'width' => $width,
  5645. 'height' => $height
  5646. ];
  5647. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5648. $task_id = $task->id;
  5649. if (!$task_id) {
  5650. Utils::throwError('20003:创建图片生成任务失败');
  5651. }
  5652. // 轮询获取结果
  5653. // 只查询数据库,不调用API,不更新任务表
  5654. $start_time = time();
  5655. $timeout = 1800;
  5656. $img_url = '';
  5657. while (time() - $start_time < $timeout) {
  5658. sleep(5);
  5659. // 只查询数据库中的任务状态,不调用API,不更新任务表
  5660. $task = DB::table('mp_generate_pic_tasks')
  5661. ->where('id', $task_id)
  5662. ->first();
  5663. if (!$task) {
  5664. Utils::throwError('20003:任务不存在');
  5665. }
  5666. if ($task->status === 'success' && $task->result_url) {
  5667. $result_urls = is_string($task->result_url)
  5668. ? json_decode($task->result_url, true)
  5669. : $task->result_url;
  5670. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  5671. break;
  5672. } elseif ($task->status === 'failed') {
  5673. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  5674. }
  5675. // 其他状态继续轮询
  5676. }
  5677. if (empty($img_url)) {
  5678. Utils::throwError('20003:三视图生成超时,请稍后重试');
  5679. }
  5680. // 更新 mp_products 表(不是任务表)
  5681. DB::table('mp_products')
  5682. ->where('id', $id)
  5683. ->where('cpid', $cpid)
  5684. ->update([
  5685. 'three_view_image_url' => $img_url,
  5686. 'updated_at' => date('Y-m-d H:i:s')
  5687. ]);
  5688. return ['three_view_image_url' => $img_url];
  5689. } catch (\Exception $e) {
  5690. dLog('anime')->error('生成三视图失败', [
  5691. 'error' => $e->getMessage()
  5692. ]);
  5693. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  5694. Utils::throwError('20003:' . $e->getMessage());
  5695. }
  5696. }
  5697. /**
  5698. * 保存剧本资产关联关系
  5699. * @param array $data 请求参数
  5700. * @return bool
  5701. */
  5702. public function saveScriptProducts($data) {
  5703. $uid = Site::getUid();
  5704. $cpid = Site::getCpid();
  5705. $script_id = getProp($data, 'script_id');
  5706. $products = getProp($data, 'products', []);
  5707. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  5708. if (!$script_id) {
  5709. Utils::throwError('20003:请提供剧本ID');
  5710. }
  5711. // 验证剧本是否存在
  5712. $script = DB::table('mp_scripts')
  5713. ->where('id', $script_id)
  5714. ->where('is_deleted', 0)
  5715. ->first();
  5716. if (!$script) {
  5717. Utils::throwError('20003:剧本不存在');
  5718. }
  5719. $script_name = $script->script_name ?? 'script_' . $script_id;
  5720. // 检查是否已经有该剧本的资产数据
  5721. $existingMappings = DB::table('mp_script_product_mappings')
  5722. ->where('script_id', $script_id)
  5723. ->get();
  5724. if ($existingMappings->isNotEmpty()) {
  5725. // 已存在资产映射,检查是否所有资产都有图片生成任务
  5726. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  5727. // 查询这些资产的图片生成任务状态
  5728. $productsWithTasks = DB::table('mp_products')
  5729. ->whereIn('id', $productIds)
  5730. ->where('is_deleted', 0)
  5731. ->get();
  5732. $productTaskMap = [];
  5733. $typeFolderIds = [];
  5734. $hasAllTasks = true;
  5735. foreach ($productsWithTasks as $product) {
  5736. // 收集类型文件夹ID
  5737. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  5738. $parentFolder = DB::table('mp_products')
  5739. ->where('id', $product->parent_id)
  5740. ->where('type', 2)
  5741. ->first();
  5742. if ($parentFolder) {
  5743. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  5744. }
  5745. }
  5746. // 检查是否有图片生成任务
  5747. if (!empty($product->pic_task_id)) {
  5748. $productTaskMap[$product->id] = $product->pic_task_id;
  5749. } else if($product->url && $product->pic_task_status == '生成成功') {
  5750. continue;
  5751. }
  5752. else {
  5753. // 有资产没有图片任务
  5754. $hasAllTasks = false;
  5755. }
  5756. }
  5757. // 如果所有资产都有任务ID,直接轮询返回结果
  5758. if ($hasAllTasks && !empty($productTaskMap)) {
  5759. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  5760. 'script_id' => $script_id,
  5761. 'script_name' => $script_name,
  5762. 'product_count' => count($productTaskMap)
  5763. ]);
  5764. // 直接返回 SSE 流轮询结果
  5765. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5766. }
  5767. // 如果部分资产没有任务ID,只为这些资产创建任务
  5768. if (!$hasAllTasks && $auto_generate_images) {
  5769. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  5770. 'script_id' => $script_id,
  5771. 'script_name' => $script_name
  5772. ]);
  5773. // 处理图片模型
  5774. $model = getProp($data, 'model');
  5775. if (!$model) {
  5776. // 使用默认模型
  5777. $model = 'doubao-seedream-5-0-lite-260128';
  5778. }
  5779. // 验证模型是否在可用模型表中
  5780. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5781. Utils::throwError('20003:该模型已不可用,请更换!');
  5782. }
  5783. $ratio = getProp($data, 'ratio', '16:9');
  5784. $resolution = getProp($data, 'resolution', '2k');
  5785. // 定义分辨率和宽高比对应的尺寸映射表
  5786. $sizeMap = [
  5787. '2k' => [
  5788. '1:1' => ['width' => 2048, 'height' => 2048],
  5789. '4:3' => ['width' => 2304, 'height' => 1728],
  5790. '3:4' => ['width' => 1728, 'height' => 2304],
  5791. '16:9' => ['width' => 2848, 'height' => 1600],
  5792. '9:16' => ['width' => 1600, 'height' => 2848],
  5793. '3:2' => ['width' => 2496, 'height' => 1664],
  5794. '2:3' => ['width' => 1664, 'height' => 2496],
  5795. '21:9' => ['width' => 3136, 'height' => 1344],
  5796. ],
  5797. '3k' => [
  5798. '1:1' => ['width' => 3072, 'height' => 3072],
  5799. '4:3' => ['width' => 3456, 'height' => 2592],
  5800. '3:4' => ['width' => 2592, 'height' => 3456],
  5801. '16:9' => ['width' => 4096, 'height' => 2304],
  5802. '9:16' => ['width' => 2304, 'height' => 4096],
  5803. '2:3' => ['width' => 2496, 'height' => 3744],
  5804. '3:2' => ['width' => 3744, 'height' => 2496],
  5805. '21:9' => ['width' => 4704, 'height' => 2016],
  5806. ],
  5807. '4k' => [
  5808. '1:1' => ['width' => 4096, 'height' => 4096],
  5809. '3:4' => ['width' => 3520, 'height' => 4704],
  5810. '4:3' => ['width' => 4704, 'height' => 3520],
  5811. '16:9' => ['width' => 5504, 'height' => 3040],
  5812. '9:16' => ['width' => 3040, 'height' => 5504],
  5813. '2:3' => ['width' => 3328, 'height' => 4992],
  5814. '3:2' => ['width' => 4992, 'height' => 3328],
  5815. '21:9' => ['width' => 6240, 'height' => 2656],
  5816. ],
  5817. ];
  5818. // 参数验证
  5819. $resolution = strtolower($resolution);
  5820. if (!isset($sizeMap[$resolution])) {
  5821. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5822. }
  5823. if (!isset($sizeMap[$resolution][$ratio])) {
  5824. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5825. }
  5826. // 根据 ratio 和 resolution 确定宽高
  5827. $width = $sizeMap[$resolution][$ratio]['width'];
  5828. $height = $sizeMap[$resolution][$ratio]['height'];
  5829. // 开启事务
  5830. DB::beginTransaction();
  5831. try {
  5832. foreach ($productsWithTasks as $product) {
  5833. // 跳过已有任务的资产
  5834. if (!empty($product->pic_task_id)) {
  5835. continue;
  5836. }
  5837. // 跳过没有提示词的资产
  5838. if (empty($product->pic_prompt)) {
  5839. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  5840. 'product_id' => $product->id,
  5841. 'product_name' => $product->product_name
  5842. ]);
  5843. continue;
  5844. }
  5845. try {
  5846. // 创建图片生成任务
  5847. $params = [
  5848. 'prompt' => $product->pic_prompt,
  5849. 'model' => $model,
  5850. 'ref_img_urls' => [],
  5851. 'width' => $width,
  5852. 'height' => $height
  5853. ];
  5854. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5855. $task_id = $task->id;
  5856. if ($task_id) {
  5857. $productTaskMap[$product->id] = $task_id;
  5858. // 在事务中更新资产表的任务ID和状态
  5859. DB::table('mp_products')
  5860. ->where('id', $product->id)
  5861. ->update([
  5862. 'pic_task_id' => $task_id,
  5863. 'pic_task_status' => '生成中',
  5864. 'updated_at' => now()
  5865. ]);
  5866. dLog('anime')->info('为已存在资产创建图片生成任务', [
  5867. 'product_id' => $product->id,
  5868. 'task_id' => $task_id
  5869. ]);
  5870. }
  5871. } catch (\Exception $e) {
  5872. dLog('anime')->error('创建资产图片生成任务失败', [
  5873. 'product_id' => $product->id,
  5874. 'error' => $e->getMessage()
  5875. ]);
  5876. // 标记为失败(仍在事务中)
  5877. DB::table('mp_products')
  5878. ->where('id', $product->id)
  5879. ->update([
  5880. 'pic_task_status' => '生成失败',
  5881. 'updated_at' => now()
  5882. ]);
  5883. }
  5884. }
  5885. // 提交事务
  5886. DB::commit();
  5887. // 如果有新创建的任务,返回 SSE 流
  5888. if (!empty($productTaskMap)) {
  5889. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5890. }
  5891. } catch (\Exception $e) {
  5892. // 回滚事务
  5893. DB::rollback();
  5894. dLog('anime')->error('为已存在资产创建图片任务失败', [
  5895. 'script_id' => $script_id,
  5896. 'error' => $e->getMessage()
  5897. ]);
  5898. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  5899. }
  5900. }
  5901. // 如果不需要生成图片,返回已存在的信息
  5902. return [
  5903. 'success' => true,
  5904. 'message' => '剧本资产已存在',
  5905. 'script_id' => $script_id,
  5906. 'script_name' => $script_name,
  5907. 'type_folder_ids' => $typeFolderIds,
  5908. 'existing_products' => count($productIds),
  5909. 'tasks_count' => count($productTaskMap)
  5910. ];
  5911. }
  5912. // 解析 products(可能是 JSON 字符串或数组)
  5913. if (is_string($products)) {
  5914. $products = json_decode($products, true);
  5915. if (json_last_error() !== JSON_ERROR_NONE) {
  5916. Utils::throwError('20003:产品数据格式错误');
  5917. }
  5918. }
  5919. if (!is_array($products) || empty($products)) {
  5920. Utils::throwError('20003:产品数据不能为空');
  5921. }
  5922. // 以下是原有的创建逻辑...
  5923. // 开启事务
  5924. DB::beginTransaction();
  5925. try {
  5926. $now = now();
  5927. $mappingRecords = [];
  5928. $createdProductIds = []; // 记录所有创建的资产ID
  5929. // 获取剧本名称
  5930. $script_name = $script->script_name ?? 'script_' . $script_id;
  5931. // 存储每个类型的根文件夹ID
  5932. $typeFolderIds = [];
  5933. // 默认图片生成参数
  5934. $model = 'doubao-seedream-5-0-lite-260128';
  5935. $width = 1600;
  5936. $height = 2848;
  5937. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  5938. foreach ($products as $productGroup) {
  5939. $type = getProp($productGroup, 'type');
  5940. $title = getProp($productGroup, 'title', '');
  5941. $content = getProp($productGroup, 'content', []);
  5942. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  5943. continue;
  5944. }
  5945. // 为当前类型创建根文件夹(如果还未创建)
  5946. if (!isset($typeFolderIds[$type])) {
  5947. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  5948. 'user_id' => $uid,
  5949. 'cpid' => $cpid,
  5950. 'type' => 2, // 1.资产 2文件夹
  5951. 'product' => $type, // 1.主体 2.场景 3.道具
  5952. 'parent_id' => 0, // 根文件夹,parent_id=0
  5953. 'level' => 1, // 第一层级
  5954. 'product_name' => $script_name,
  5955. 'sort_order' => time() + $type,
  5956. 'is_deleted' => 0,
  5957. 'created_at' => $now,
  5958. 'updated_at' => $now
  5959. ]);
  5960. }
  5961. $folder_id = $typeFolderIds[$type];
  5962. // 获取表头(第一行)并查找关键列的位置
  5963. $headers = $content[0];
  5964. $nameColumnIndex = -1; // 资产名称列索引
  5965. $sequenceColumnIndex = -1; // 使用范围列索引
  5966. $promptColumnIndex = -1; // 参考提示词列索引
  5967. foreach ($headers as $index => $header) {
  5968. // 查找"资产名称"列
  5969. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  5970. $nameColumnIndex = $index;
  5971. }
  5972. // 查找"使用范围"列
  5973. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  5974. $sequenceColumnIndex = $index;
  5975. }
  5976. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  5977. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  5978. $promptColumnIndex = $index;
  5979. }
  5980. }
  5981. // 验证必要的列是否都找到了
  5982. if ($nameColumnIndex === -1) {
  5983. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  5984. continue;
  5985. }
  5986. if ($sequenceColumnIndex === -1) {
  5987. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  5988. continue;
  5989. }
  5990. // 跳过表头,解析每一行数据
  5991. for ($i = 1; $i < count($content); $i++) {
  5992. $row = $content[$i];
  5993. // 确保行数据有效
  5994. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  5995. continue;
  5996. }
  5997. // 根据动态查找的列索引提取数据
  5998. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  5999. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6000. $pic_prompt = '';
  6001. // 提取参考提示词(如果找到了该列)
  6002. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6003. $pic_prompt = trim($row[$promptColumnIndex]);
  6004. }
  6005. // 解析使用范围(逗号分隔的序号)
  6006. $sequences = [];
  6007. if (!empty($sequence_str)) {
  6008. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6009. foreach ($sequenceParts as $part) {
  6010. if (is_numeric($part)) {
  6011. $sequences[] = (int)$part;
  6012. }
  6013. }
  6014. }
  6015. if (empty($product_name)) {
  6016. continue;
  6017. }
  6018. // 处理product_name两边的符号
  6019. $product_name = preg_replace('/^[【】\s]+|[【】\s]+$/u', '', $product_name);
  6020. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6021. $product_id = DB::table('mp_products')->insertGetId([
  6022. 'product_name' => $product_name,
  6023. 'type' => 1, // 1=资产 2.文件夹
  6024. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6025. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6026. 'level' => 2, // 第二层级
  6027. 'pic_prompt' => $pic_prompt,
  6028. 'user_id' => $uid,
  6029. 'cpid' => $cpid,
  6030. 'sort_order' => time(),
  6031. 'is_deleted' => 0,
  6032. 'created_at' => $now,
  6033. 'updated_at' => $now,
  6034. ]);
  6035. // 记录创建的资产ID
  6036. $createdProductIds[] = $product_id;
  6037. // 为每个序号创建映射记录
  6038. if (!empty($sequences)) {
  6039. foreach ($sequences as $sequence) {
  6040. $mappingRecords[] = [
  6041. 'script_id' => $script_id,
  6042. 'product_id' => $product_id,
  6043. 'episode_number' => $sequence,
  6044. 'created_at' => $now,
  6045. 'updated_at' => $now,
  6046. ];
  6047. }
  6048. } else {
  6049. // 如果没有指定序号,创建一个默认映射(序号为0)
  6050. $mappingRecords[] = [
  6051. 'script_id' => $script_id,
  6052. 'product_id' => $product_id,
  6053. 'episode_number' => 0,
  6054. 'created_at' => $now,
  6055. 'updated_at' => $now,
  6056. ];
  6057. }
  6058. }
  6059. }
  6060. if (empty($mappingRecords)) {
  6061. Utils::throwError('20003:没有有效的产品数据');
  6062. }
  6063. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6064. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6065. // 如果需要自动生成图片,在事务中创建图片生成任务
  6066. $productTaskMap = [];
  6067. if ($auto_generate_images && !empty($createdProductIds)) {
  6068. // 查询所有创建的资产
  6069. $productsToGenerate = DB::table('mp_products')
  6070. ->whereIn('id', $createdProductIds)
  6071. ->where('is_deleted', 0)
  6072. ->get();
  6073. foreach ($productsToGenerate as $product) {
  6074. if (empty($product->pic_prompt)) {
  6075. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6076. 'product_id' => $product->id,
  6077. 'product_name' => $product->product_name
  6078. ]);
  6079. continue;
  6080. }
  6081. try {
  6082. // 创建图片生成任务
  6083. $params = [
  6084. 'prompt' => $product->pic_prompt,
  6085. 'model' => $model,
  6086. 'ref_img_urls' => [],
  6087. 'width' => $width,
  6088. 'height' => $height
  6089. ];
  6090. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6091. $task_id = $task->id;
  6092. if ($task_id) {
  6093. $productTaskMap[$product->id] = $task_id;
  6094. // 在事务中更新资产表的任务ID和状态
  6095. DB::table('mp_products')
  6096. ->where('id', $product->id)
  6097. ->update([
  6098. 'pic_task_id' => $task_id,
  6099. 'pic_task_status' => '生成中',
  6100. 'updated_at' => now()
  6101. ]);
  6102. dLog('anime')->info('创建资产图片生成任务', [
  6103. 'product_id' => $product->id,
  6104. 'task_id' => $task_id
  6105. ]);
  6106. }
  6107. } catch (\Exception $e) {
  6108. dLog('anime')->error('创建资产图片生成任务失败', [
  6109. 'product_id' => $product->id,
  6110. 'error' => $e->getMessage()
  6111. ]);
  6112. // 标记为失败(仍在事务中)
  6113. DB::table('mp_products')
  6114. ->where('id', $product->id)
  6115. ->update([
  6116. 'pic_task_status' => '生成失败',
  6117. 'updated_at' => now()
  6118. ]);
  6119. }
  6120. }
  6121. }
  6122. // 提交事务
  6123. DB::commit();
  6124. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6125. if ($auto_generate_images && !empty($productTaskMap)) {
  6126. // 返回 SSE 流(事务外轮询)
  6127. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6128. }
  6129. // 如果不需要生成图片,返回普通结果
  6130. return [
  6131. 'success' => true,
  6132. 'type_folder_ids' => $typeFolderIds,
  6133. 'inserted_count' => $insertedCount,
  6134. 'total_records' => count($mappingRecords),
  6135. 'created_products' => count($createdProductIds),
  6136. 'image_tasks_created' => count($productTaskMap)
  6137. ];
  6138. } catch (\Exception $e) {
  6139. // 回滚事务
  6140. DB::rollback();
  6141. // 记录错误日志
  6142. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6143. 'script_id' => $script_id,
  6144. 'error' => $e->getMessage(),
  6145. 'trace' => $e->getTraceAsString()
  6146. ]);
  6147. // 统一使用 Utils::throwError 抛出错误
  6148. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6149. }
  6150. }
  6151. /**
  6152. * 批量为剧本资产生成图片
  6153. *
  6154. * @param array $data 请求参数
  6155. * @return \Generator 返回 SSE 流
  6156. */
  6157. public function batchGenerateProductImages($data) {
  6158. $script_id = getProp($data, 'script_id');
  6159. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6160. if (!$script_id) {
  6161. Utils::throwError('20003:请提供剧本ID');
  6162. }
  6163. // 验证剧本是否存在
  6164. $script = DB::table('mp_scripts')
  6165. ->where('id', $script_id)
  6166. ->where('is_deleted', 0)
  6167. ->first();
  6168. if (!$script) {
  6169. Utils::throwError('20003:剧本不存在');
  6170. }
  6171. $script_name = $script->script_name ?? 'script_' . $script_id;
  6172. // 获取需要生成图片的所有资产
  6173. $products = DB::table('mp_products')
  6174. ->whereIn('parent_id', array_values($type_folder_ids))
  6175. ->where('is_deleted', 0)
  6176. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6177. ->get();
  6178. if ($products->isEmpty()) {
  6179. Utils::throwError('20003:没有找到需要生成图片的资产');
  6180. }
  6181. // 默认参数
  6182. $model = 'doubao-seedream-5-0-lite-260128';
  6183. $width = 1600;
  6184. $height = 2848;
  6185. // 开始为每个资产创建图片生成任务
  6186. $taskIds = [];
  6187. $productTaskMap = []; // 资产ID到任务ID的映射
  6188. foreach ($products as $product) {
  6189. if (empty($product->pic_prompt)) {
  6190. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6191. continue;
  6192. }
  6193. try {
  6194. // 创建图片生成任务
  6195. $params = [
  6196. 'prompt' => $product->pic_prompt,
  6197. 'model' => $model,
  6198. 'ref_img_urls' => [],
  6199. 'width' => $width,
  6200. 'height' => $height
  6201. ];
  6202. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6203. $task_id = $task->id;
  6204. if ($task_id) {
  6205. $taskIds[] = $task_id;
  6206. $productTaskMap[$product->id] = $task_id;
  6207. // 更新资产表的任务ID和状态
  6208. DB::table('mp_products')
  6209. ->where('id', $product->id)
  6210. ->update([
  6211. 'pic_task_id' => $task_id,
  6212. 'pic_task_status' => '生成中',
  6213. 'updated_at' => now()
  6214. ]);
  6215. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6216. }
  6217. } catch (\Exception $e) {
  6218. dLog('anime')->error('创建资产图片生成任务失败', [
  6219. 'product_id' => $product->id,
  6220. 'error' => $e->getMessage()
  6221. ]);
  6222. // 标记为失败
  6223. DB::table('mp_products')
  6224. ->where('id', $product->id)
  6225. ->update([
  6226. 'pic_task_status' => '生成失败',
  6227. 'updated_at' => now()
  6228. ]);
  6229. }
  6230. }
  6231. if (empty($taskIds)) {
  6232. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6233. }
  6234. // 返回 SSE 流
  6235. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6236. }
  6237. /**
  6238. * 轮询资产图片生成任务状态(SSE流式返回)
  6239. * 只通过查询数据库获取任务状态,不主动调用API
  6240. *
  6241. * @param int $script_id 剧本ID
  6242. * @param string $script_name 剧本名称
  6243. * @param array $productTaskMap 资产ID到任务ID的映射
  6244. * @param array $type_folder_ids 类型文件夹ID映射
  6245. * @return \Generator
  6246. */
  6247. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6248. $startTime = time();
  6249. $timeout = 1800; // 30分钟超时
  6250. $pollInterval = 10; // 10秒轮询一次
  6251. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6252. // 定义类型名称映射
  6253. $typeNames = [
  6254. 1 => 'roles', // 角色
  6255. 2 => 'scenes', // 场景
  6256. 3 => 'props' // 道具
  6257. ];
  6258. while (time() - $startTime < $timeout) {
  6259. sleep($pollInterval);
  6260. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6261. $mappings = DB::table('mp_script_product_mappings')
  6262. ->where('script_id', $script_id)
  6263. ->pluck('product_id')
  6264. ->unique()
  6265. ->toArray();
  6266. if (empty($mappings)) {
  6267. dLog('anime')->warning('该剧本没有关联的资产', [
  6268. 'script_id' => $script_id,
  6269. 'script_name' => $script_name
  6270. ]);
  6271. break;
  6272. }
  6273. // 查询所有资产的当前状态
  6274. $products = DB::table('mp_products')
  6275. ->whereIn('id', $mappings)
  6276. ->where('is_deleted', 0)
  6277. ->get();
  6278. // 统计各类型的状态(使用类型名称作为键名)
  6279. $stats = [
  6280. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6281. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6282. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6283. ];
  6284. $allCompleted = true;
  6285. $hasStatusChange = false;
  6286. foreach ($products as $product) {
  6287. $type = $product->product;
  6288. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6289. // 如果类型名称不在 stats 中,初始化
  6290. if (!isset($stats[$typeName])) {
  6291. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6292. }
  6293. $stats[$typeName]['total']++;
  6294. $task_id = $product->pic_task_id;
  6295. $currentStatus = $product->pic_task_status;
  6296. // 检查状态是否有变化
  6297. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6298. $hasStatusChange = true;
  6299. $lastStatus[$product->id] = $currentStatus;
  6300. }
  6301. // 如果是生成中,查询任务表状态
  6302. if ($currentStatus === '生成中' && $task_id) {
  6303. // 只查询数据库,不调用API
  6304. $task = DB::table('mp_generate_pic_tasks')
  6305. ->where('id', $task_id)
  6306. ->first();
  6307. if ($task) {
  6308. // 检查任务状态
  6309. if ($task->status === 'success' && $task->result_url) {
  6310. // 解析图片URL
  6311. $result_urls = $task->result_url;
  6312. if (is_string($result_urls)) {
  6313. $result_urls = json_decode($result_urls, true);
  6314. }
  6315. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6316. // 更新资产表状态
  6317. DB::table('mp_products')
  6318. ->where('id', $product->id)
  6319. ->update([
  6320. 'pic_task_status' => '生成成功',
  6321. 'url' => $img_url,
  6322. 'updated_at' => now()
  6323. ]);
  6324. $stats[$typeName]['success']++;
  6325. $stats[$typeName]['completed']++;
  6326. $hasStatusChange = true;
  6327. dLog('anime')->info('资产图片生成成功', [
  6328. 'product_id' => $product->id,
  6329. 'task_id' => $task_id,
  6330. 'img_url' => $img_url
  6331. ]);
  6332. } elseif ($task->status === 'failed') {
  6333. // 更新资产表状态
  6334. DB::table('mp_products')
  6335. ->where('id', $product->id)
  6336. ->update([
  6337. 'pic_task_status' => '生成失败',
  6338. 'updated_at' => now()
  6339. ]);
  6340. $stats[$typeName]['completed']++;
  6341. $hasStatusChange = true;
  6342. dLog('anime')->warning('资产图片生成失败', [
  6343. 'product_id' => $product->id,
  6344. 'task_id' => $task_id,
  6345. 'error' => $task->error_message ?? '未知错误'
  6346. ]);
  6347. } else {
  6348. // 任务还在处理中
  6349. $allCompleted = false;
  6350. }
  6351. } else {
  6352. // 任务不存在,标记为失败
  6353. DB::table('mp_products')
  6354. ->where('id', $product->id)
  6355. ->update([
  6356. 'pic_task_status' => '生成失败',
  6357. 'updated_at' => now()
  6358. ]);
  6359. $stats[$type]['completed']++;
  6360. $hasStatusChange = true;
  6361. dLog('anime')->error('图片生成任务不存在', [
  6362. 'product_id' => $product->id,
  6363. 'task_id' => $task_id
  6364. ]);
  6365. }
  6366. } elseif ($currentStatus === '生成成功') {
  6367. $stats[$typeName]['success']++;
  6368. $stats[$typeName]['completed']++;
  6369. } elseif ($currentStatus === '生成失败') {
  6370. $stats[$typeName]['completed']++;
  6371. } else {
  6372. // 其他状态也认为未完成
  6373. $allCompleted = false;
  6374. }
  6375. }
  6376. // 移除没有数据的类型(total=0)
  6377. foreach ($stats as $typeName => $stat) {
  6378. if ($stat['total'] === 0) {
  6379. unset($stats[$typeName]);
  6380. }
  6381. }
  6382. // 如果有状态变化,发送 SSE 更新
  6383. if ($hasStatusChange) {
  6384. $eventType = $allCompleted ? 'complete' : 'update';
  6385. $response = [
  6386. 'type' => $eventType,
  6387. 'script_id' => $script_id,
  6388. 'script_name' => $script_name,
  6389. 'stats' => $stats,
  6390. 'timestamp' => date('Y-m-d H:i:s')
  6391. ];
  6392. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6393. dLog('anime')->info('SSE更新', [
  6394. 'event_type' => $eventType,
  6395. 'script_id' => $script_id,
  6396. 'script_name' => $script_name,
  6397. 'stats' => $stats
  6398. ]);
  6399. if ($allCompleted) {
  6400. dLog('anime')->info('所有资产图片生成任务已完成', [
  6401. 'script_id' => $script_id,
  6402. 'script_name' => $script_name,
  6403. 'stats' => $stats
  6404. ]);
  6405. break;
  6406. }
  6407. }
  6408. }
  6409. // 超时处理
  6410. if (time() - $startTime >= $timeout && !$allCompleted) {
  6411. $response = [
  6412. 'type' => 'timeout',
  6413. 'message' => '部分任务超时,请稍后查看结果',
  6414. 'script_id' => $script_id,
  6415. 'script_name' => $script_name,
  6416. 'timestamp' => date('Y-m-d H:i:s')
  6417. ];
  6418. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6419. dLog('anime')->warning('资产图片生成任务超时', [
  6420. 'script_id' => $script_id,
  6421. 'script_name' => $script_name,
  6422. 'timeout' => $timeout
  6423. ]);
  6424. }
  6425. }
  6426. /**
  6427. * 获取剧本关联的资产列表
  6428. * @param array $data 请求参数
  6429. * @return array
  6430. */
  6431. public function getScriptProducts($data) {
  6432. $uid = Site::getUid();
  6433. $cpid = Site::getCpid();
  6434. $script_id = getProp($data, 'script_id');
  6435. $episode_number = getProp($data, 'episode_number');
  6436. if (!$script_id) {
  6437. Utils::throwError('20003:请提供剧本ID');
  6438. }
  6439. // 验证剧本是否存在
  6440. $script = DB::table('mp_scripts')
  6441. ->where('id', $script_id)
  6442. ->where('is_deleted', 0)
  6443. ->first();
  6444. if (!$script) {
  6445. Utils::throwError('20003:剧本不存在');
  6446. }
  6447. // 联表查询资产信息
  6448. $query = DB::table('mp_script_product_mappings as mapping')
  6449. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6450. ->where('mapping.script_id', $script_id)
  6451. ->where('product.cpid', $cpid)
  6452. ->where('product.is_deleted', 0);
  6453. // 如果提供了 episode_number,则过滤指定集数
  6454. if ($episode_number !== null && $episode_number !== '') {
  6455. $query->where('mapping.episode_number', $episode_number);
  6456. }
  6457. $mappings = $query->select(
  6458. 'mapping.script_id',
  6459. 'mapping.product_id',
  6460. 'mapping.episode_number',
  6461. 'product.product_name',
  6462. 'product.type',
  6463. 'product.product',
  6464. 'product.pic_prompt',
  6465. 'product.url',
  6466. 'product.pic_task_id',
  6467. 'product.pic_task_status',
  6468. 'product.three_view_image_url',
  6469. 'mapping.created_at'
  6470. )
  6471. ->orderBy('mapping.product_id', 'asc')
  6472. ->orderBy('mapping.episode_number', 'asc')
  6473. ->get();
  6474. // 按 product_id 分组,合并 episode_number
  6475. $productMap = [];
  6476. foreach ($mappings as $item) {
  6477. $product_id = $item->product_id;
  6478. if (!isset($productMap[$product_id])) {
  6479. $productMap[$product_id] = [
  6480. 'product_id' => $product_id,
  6481. 'product_name' => $item->product_name,
  6482. 'type' => (int)$item->type,
  6483. 'product' => (int)$item->product,
  6484. 'pic_prompt' => $item->pic_prompt,
  6485. 'url' => $item->url,
  6486. 'pic_task_id' => $item->pic_task_id,
  6487. 'pic_task_status' => $item->pic_task_status,
  6488. 'episode_numbers' => [],
  6489. 'created_at' => $item->created_at,
  6490. ];
  6491. }
  6492. // 添加 episode_number(去重)
  6493. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6494. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6495. }
  6496. }
  6497. // 按类型分组
  6498. $roles = []; // type=1 角色/主体
  6499. $scenes = []; // type=2 场景
  6500. $props = []; // type=3 道具
  6501. foreach ($productMap as $product) {
  6502. // 将 episode_numbers 数组转换为逗号分隔的字符串
  6503. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  6504. // 构造返回数据
  6505. $productData = [
  6506. 'product_id' => $product['product_id'],
  6507. 'product_name' => $product['product_name'],
  6508. 'product' => $product['product'],
  6509. 'pic_prompt' => $product['pic_prompt'],
  6510. 'url' => $product['url'],
  6511. 'pic_task_id' => $product['pic_task_id'],
  6512. 'pic_task_status' => $product['pic_task_status'],
  6513. 'episode_numbers' => $episodeNumbersStr,
  6514. 'created_at' => $product['created_at'],
  6515. ];
  6516. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  6517. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  6518. switch ($product['product']) {
  6519. case 1:
  6520. $roles[] = $productData;
  6521. break;
  6522. case 2:
  6523. $scenes[] = $productData;
  6524. break;
  6525. case 3:
  6526. $props[] = $productData;
  6527. break;
  6528. }
  6529. }
  6530. return [
  6531. 'script_id' => $script_id,
  6532. 'script_name' => $script->script_name ?? '',
  6533. 'roles' => $roles, // 主体
  6534. 'scenes' => $scenes, // 场景
  6535. 'props' => $props, // 道具
  6536. ];
  6537. }
  6538. /**
  6539. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  6540. * @param string $actContent 原始内容
  6541. * @param array $products 产品数组(包含product_name和url)
  6542. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  6543. */
  6544. public function processActContentWithProducts($actContent, $products) {
  6545. if (empty($actContent) || empty($products)) {
  6546. return [
  6547. 'content' => $actContent,
  6548. 'reference_images' => []
  6549. ];
  6550. }
  6551. // 构建产品名称到产品信息的映射
  6552. $product_dict = [];
  6553. foreach ($products as $product) {
  6554. $product_name = getProp($product, 'product_name');
  6555. if ($product_name) {
  6556. $product_dict[$product_name] = [
  6557. 'url' => getProp($product, 'url'),
  6558. 'voice_prompt' => getProp($product, 'voice_prompt')
  6559. ];
  6560. }
  6561. }
  6562. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  6563. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  6564. $reference_images = [];
  6565. $product_index_map = []; // 产品名称 => 图片序号的映射
  6566. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  6567. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  6568. $current_index = 1;
  6569. if (!empty($matches[1])) {
  6570. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  6571. $seen_products = []; // 用于去重
  6572. foreach ($matches[1] as $product_name) {
  6573. // 跳过已处理的产品
  6574. if (isset($seen_products[$product_name])) {
  6575. continue;
  6576. }
  6577. $seen_products[$product_name] = true;
  6578. // 检查产品是否在字典中
  6579. if (isset($product_dict[$product_name])) {
  6580. $url = $product_dict[$product_name]['url'];
  6581. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  6582. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  6583. if (!empty($voice_prompt) && $product_name !== '旁白') {
  6584. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  6585. }
  6586. // 只有URL非空才分配序号和添加到参考图片
  6587. if (!empty($url)) {
  6588. // 检查URL是否已经在reference_images中(去重)
  6589. if (!in_array($url, $reference_images)) {
  6590. $reference_images[] = $url;
  6591. $product_index_map[$product_name] = $current_index;
  6592. $current_index++;
  6593. } else {
  6594. // URL重复,找到已有的序号
  6595. $existing_index = array_search($url, $reference_images) + 1;
  6596. $product_index_map[$product_name] = $existing_index;
  6597. }
  6598. } else {
  6599. // URL为空,不分配序号(后续直接去掉{})
  6600. $product_index_map[$product_name] = 0;
  6601. }
  6602. } else {
  6603. // 产品不在字典中,不分配序号
  6604. $product_index_map[$product_name] = 0;
  6605. }
  6606. }
  6607. }
  6608. // 第二步:替换内容中的 {产品名称}
  6609. $processedContent = $actContent;
  6610. foreach ($product_index_map as $product_name => $index) {
  6611. $escaped_name = preg_quote($product_name, '/');
  6612. if ($index > 0) {
  6613. // 有图片,替换为:产品名称(图X)
  6614. $replacement = $product_name . '<图片' . $index . '>';
  6615. } else {
  6616. // 无图片,只保留产品名称
  6617. $replacement = $product_name;
  6618. }
  6619. // 替换所有 {产品名称} 为处理后的格式
  6620. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  6621. }
  6622. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  6623. foreach ($products as $product) {
  6624. $product_name = getProp($product, 'product_name');
  6625. $voice_prompt = getProp($product, 'voice_prompt');
  6626. if ($product_name === '旁白' && !empty($voice_prompt)) {
  6627. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  6628. break; // 找到旁白后退出循环
  6629. }
  6630. }
  6631. // 第四步:将voice_prompt信息添加到内容最前面
  6632. $voice_prompt_prefix = '';
  6633. if (!empty($voice_prompts)) {
  6634. $voice_prompt_prefix .= implode('', $voice_prompts);
  6635. }
  6636. // 旁白的voice_prompt放在最后
  6637. if (!empty($narrator_voice_prompt)) {
  6638. $voice_prompt_prefix .= $narrator_voice_prompt;
  6639. }
  6640. // 如果有voice_prompt信息,添加到内容开头
  6641. if (!empty($voice_prompt_prefix)) {
  6642. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  6643. }
  6644. return [
  6645. 'content' => $processedContent,
  6646. 'reference_images' => $reference_images
  6647. ];
  6648. }
  6649. public function saveActVideoGenerateParams($data) {
  6650. $episode_id = getProp($data, 'episode_id');
  6651. $model = getProp($data, 'video_model');
  6652. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  6653. Utils::throwError('20003:该模型不可用');
  6654. }
  6655. if (!$model) {
  6656. // 使用默认模型
  6657. $model = 'zhizhen-20-mini';
  6658. }
  6659. // 验证模型是否在可用模型表中
  6660. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6661. Utils::throwError('20003:该模型已不可用,请更换!');
  6662. }
  6663. $video_resolution = getProp($data, 'video_resolution', '720p');
  6664. $ratio = getProp($data, 'ratio');
  6665. if (!$ratio) $ratio = '9:16';
  6666. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6667. 'video_model' => $model,
  6668. 'video_resolution' => $video_resolution,
  6669. 'ratio' => $ratio,
  6670. 'updated_at' => date('Y-m-d H:i:s')
  6671. ]);
  6672. }
  6673. public function confirmActs($data) {
  6674. $episode_id = getProp($data, 'episode_id');
  6675. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  6676. if (!$episode) {
  6677. Utils::throwError('20003:分集不存在');
  6678. }
  6679. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  6680. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  6681. // 获取所有片段数据
  6682. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6683. // 构建角色和场景名称数组
  6684. $role_names = [];
  6685. $scene_names = [];
  6686. foreach ($roles as $role) {
  6687. $role_name = getProp($role, 'role');
  6688. if ($role_name && $role_name != '旁白') {
  6689. $role_names[] = $role_name;
  6690. }
  6691. }
  6692. foreach ($scenes as $scene) {
  6693. $scene_name = getProp($scene, 'scene');
  6694. if ($scene_name) {
  6695. $scene_names[] = $scene_name;
  6696. }
  6697. }
  6698. // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
  6699. usort($role_names, function($a, $b) {
  6700. return mb_strlen($b) - mb_strlen($a);
  6701. });
  6702. usort($scene_names, function($a, $b) {
  6703. return mb_strlen($b) - mb_strlen($a);
  6704. });
  6705. try {
  6706. DB::beginTransaction();
  6707. // 处理每个片段
  6708. foreach ($acts as $act) {
  6709. $act_content = getProp($act, 'act_content');
  6710. if (!$act_content) continue;
  6711. $processed_content = $act_content;
  6712. // 标记已处理的位置,避免重复标记
  6713. $marked_positions = [];
  6714. // 先匹配场景(在"场景:"后面)
  6715. foreach ($scene_names as $scene_name) {
  6716. // 转义特殊字符
  6717. $escaped_scene = preg_quote($scene_name, '/');
  6718. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  6719. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  6720. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  6721. $full_match = $matches[0];
  6722. $prefix = $matches[1];
  6723. $scene_name = $matches[2];
  6724. // 检查是否已经被标记
  6725. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  6726. return $prefix . '{' . $scene_name . '}';
  6727. }
  6728. return $full_match;
  6729. }, $processed_content);
  6730. }
  6731. // 再匹配角色名称(只在"画面:"部分)
  6732. foreach ($role_names as $role_name) {
  6733. // 转义特殊字符
  6734. $escaped_role = preg_quote($role_name, '/');
  6735. // 只匹配"画面:"开始到换行之前的内容
  6736. $pattern = '/(画面:[^\n]*)/u';
  6737. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  6738. $line = $matches[1]; // 整行"画面:xxxxx"
  6739. // 在这一行中匹配所有角色名(避免重复标记)
  6740. $new_line = preg_replace(
  6741. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  6742. '{$1}',
  6743. $line
  6744. );
  6745. return $new_line;
  6746. }, $processed_content);
  6747. }
  6748. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  6749. $shot_counter = 0;
  6750. $processed_content = preg_replace_callback(
  6751. '/【(?:镜头|分镜)(\d+)】/u',
  6752. function($matches) use (&$shot_counter) {
  6753. $shot_counter++;
  6754. return '【镜头' . $shot_counter . '】';
  6755. },
  6756. $processed_content
  6757. );
  6758. // 更新数据库
  6759. $boolen = DB::table('mp_episode_segments')
  6760. ->where('id', $act->id)
  6761. ->update([
  6762. 'act_show_content' => $processed_content,
  6763. 'updated_at' => date('Y-m-d H:i:s')
  6764. ]);
  6765. if (!$boolen) {
  6766. Utils::throwError('20003:片段处理失败');
  6767. }
  6768. }
  6769. }catch (\Exception $e) {
  6770. DB::rollBack();
  6771. Utils::throwError('20003:'.$e->getMessage());
  6772. }
  6773. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6774. 'is_generated' => 1,
  6775. 'updated_at' => date('Y-m-d H:i:s')
  6776. ]);
  6777. if (!$boolen1) {
  6778. DB::rollBack();
  6779. Utils::throwError('20003:分集处理失败!');
  6780. }
  6781. DB::commit();
  6782. // 重新查询更新后的片段数据
  6783. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6784. // 合并角色、场景和extra_products作为products,统一字段名为product_name
  6785. // extra_products优先级更高,会覆盖同名的roles和scenes
  6786. $products = [];
  6787. // 先处理角色数组
  6788. foreach ($roles as $role) {
  6789. $product = $role;
  6790. // 将role字段重命名为product_name
  6791. if (isset($product['role'])) {
  6792. $product['product_name'] = $product['role'];
  6793. unset($product['role']);
  6794. }
  6795. $product['product'] = 1; // 标记类型为角色
  6796. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6797. }
  6798. // 处理场景数组
  6799. foreach ($scenes as $scene) {
  6800. $product = $scene;
  6801. // 将scene字段重命名为product_name
  6802. if (isset($product['scene'])) {
  6803. $product['product_name'] = $product['scene'];
  6804. unset($product['scene']);
  6805. }
  6806. $product['product'] = 2; // 标记类型为场景
  6807. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6808. }
  6809. // extra_products优先级更高,直接覆盖同名的roles和scenes
  6810. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  6811. foreach ($extra_products as $extra_product) {
  6812. $product_name = getProp($extra_product, 'product_name');
  6813. if ($product_name) {
  6814. $products[$product_name] = $extra_product; // 覆盖同名数据
  6815. }
  6816. }
  6817. // 重新索引数组(去除key)
  6818. $products = array_values($products);
  6819. // 构建返回的acts数组
  6820. $return_acts = [];
  6821. foreach ($acts as $act) {
  6822. $return_acts[] = [
  6823. 'act_id' => getProp($act, 'id'),
  6824. 'act_number' => getProp($act, 'act_number'),
  6825. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  6826. 'act_show_content' => getProp($act, 'act_show_content'),
  6827. 'video_url' => getProp($act, 'video_url'),
  6828. 'video_duration' => getProp($act, 'video_duration'),
  6829. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  6830. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  6831. ];
  6832. }
  6833. return [
  6834. 'anime_id' => getProp($episode, 'anime_id'),
  6835. 'episode_id' => $episode_id,
  6836. 'title' => getProp($episode, 'title'),
  6837. 'episode_number' => getProp($episode, 'episode_number'),
  6838. 'is_generated' => getProp($episode, 'is_generated'),
  6839. 'products' => $products,
  6840. 'acts' => $return_acts
  6841. ];
  6842. }
  6843. }