AnimeService.php 343 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980
  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_show_content'] = $act_content;
  2405. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2406. }
  2407. if (!empty($act_duration)) {
  2408. $update_data['act_duration'] = $act_duration;
  2409. }
  2410. if (!empty($act_title)) {
  2411. $update_data['act_title'] = $act_title;
  2412. }
  2413. // 处理图片上传
  2414. if ($image_url) {
  2415. $update_data['img_url'] = $image_url;
  2416. $update_data['current_type'] = 1;
  2417. // 同时写入一个图片生成任务记录
  2418. if ($act_id) {
  2419. $pic_task = [
  2420. 'alias_act_id' => $act_id,
  2421. 'ref_img_url' => json_encode([]),
  2422. 'status' => 'success',
  2423. 'result_url' => json_encode([$image_url], 256),
  2424. 'model' => '',
  2425. 'created_at' => date('Y-m-d H:i:s'),
  2426. 'updated_at' => date('Y-m-d H:i:s'),
  2427. ];
  2428. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2429. }
  2430. }
  2431. // 处理视频上传
  2432. if ($video_url) {
  2433. $update_data['origin_video_url'] = $video_url;
  2434. $compressed_video_url = compressVideo($video_url);
  2435. $update_data['current_type'] = 2;
  2436. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2437. // 同时写入一个视频生成任务记录
  2438. if ($act_id) {
  2439. $video_task = [
  2440. 'alias_act_id' => $act_id,
  2441. 'status' => 'success',
  2442. 'result_url' => $update_data['origin_video_url'],
  2443. 'compressed_url' => $update_data['video_url'],
  2444. 'created_at' => date('Y-m-d H:i:s'),
  2445. 'updated_at' => date('Y-m-d H:i:s'),
  2446. ];
  2447. DB::table('mp_generate_video_tasks')->insert($video_task);
  2448. }
  2449. }
  2450. // 更新片段信息
  2451. $result = DB::table('mp_episode_segments')
  2452. ->where('id', $act_id)
  2453. ->update($update_data);
  2454. if ($result === false) {
  2455. Utils::throwError('20003:更新片段失败');
  2456. }
  2457. DB::commit();
  2458. return true;
  2459. } catch (\Exception $e) {
  2460. DB::rollBack();
  2461. dLog('anime')->error('更新片段失败', [
  2462. 'act_id' => $act_id,
  2463. 'error' => $e->getMessage()
  2464. ]);
  2465. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2466. }
  2467. }
  2468. public function copyAct($data) {
  2469. $act_id = getProp($data, 'act_id');
  2470. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2471. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2472. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2473. $video_url = getProp($source_segment, 'video_url');
  2474. if (!$video_url) Utils::throwError('20003:该片段没有视频无法复制');
  2475. $anime_id = getProp($source_segment, 'anime_id');
  2476. $episode_id = getProp($source_segment, 'episode_id');
  2477. $episode_number = getProp($source_segment, 'episode_number');
  2478. $act_number = getProp($source_segment, 'act_number');
  2479. try {
  2480. DB::beginTransaction();
  2481. // 新act的编号
  2482. $new_act_number = $act_number + 1;
  2483. // 更新后续所有act的act_number
  2484. DB::table('mp_episode_segments')
  2485. ->where('anime_id', $anime_id)
  2486. ->where('episode_id', $episode_id)
  2487. ->where('act_number', '>', $act_number)
  2488. ->increment('act_number');
  2489. // 复制该片段记录
  2490. $segment_data = (array)$source_segment;
  2491. unset($segment_data['id']);
  2492. $segment_data['act_number'] = $new_act_number;
  2493. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2494. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2495. if (!$id) {
  2496. Utils::throwError('20003:复制片段失败');
  2497. }
  2498. DB::commit();
  2499. }catch (\Exception $e) {
  2500. DB::rollBack();
  2501. Utils::throwError('20003:'.$e->getMessage());
  2502. }
  2503. // 返回新复制的记录
  2504. $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();
  2505. $new_segment = $new_segment ? (array)$new_segment : [];
  2506. $new_segment['act_id'] = $id;
  2507. return $new_segment;
  2508. }
  2509. public function moveAct($data) {
  2510. $act_id = getProp($data, 'act_id');
  2511. $target_act_id = getProp($data, 'target_act_id');
  2512. // 获取源片段信息
  2513. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2514. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2515. // 获取目标片段信息
  2516. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2517. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2518. $anime_id = getProp($source_segment, 'anime_id');
  2519. $episode_id = getProp($source_segment, 'episode_id');
  2520. $source_act_number = getProp($source_segment, 'act_number');
  2521. $target_act_number = getProp($target_segment, 'act_number');
  2522. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2523. $target_anime_id = getProp($target_segment, 'anime_id');
  2524. $target_episode_id = getProp($target_segment, 'episode_id');
  2525. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2526. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2527. }
  2528. // 如果源片段和目标片段相同,无需移动
  2529. if ($source_act_number == $target_act_number) {
  2530. return true;
  2531. }
  2532. try {
  2533. DB::beginTransaction();
  2534. if ($source_act_number < $target_act_number) {
  2535. // 向后移动:源片段移动到目标片段之后
  2536. // 1. 将源片段和目标片段之间的所有片段编号减1
  2537. DB::table('mp_episode_segments')
  2538. ->where('anime_id', $anime_id)
  2539. ->where('episode_id', $episode_id)
  2540. ->where('act_number', '>', $source_act_number)
  2541. ->where('act_number', '<=', $target_act_number)
  2542. ->decrement('act_number');
  2543. // 2. 将源片段移动到目标片段之后
  2544. $new_act_number = $target_act_number;
  2545. } else {
  2546. // 向前移动:源片段移动到目标片段之后
  2547. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2548. DB::table('mp_episode_segments')
  2549. ->where('anime_id', $anime_id)
  2550. ->where('episode_id', $episode_id)
  2551. ->where('act_number', '>', $target_act_number)
  2552. ->where('act_number', '<', $source_act_number)
  2553. ->increment('act_number');
  2554. // 2. 将源片段移动到目标片段之后
  2555. $new_act_number = $target_act_number + 1;
  2556. }
  2557. // 3. 更新源片段的编号
  2558. $update_result = DB::table('mp_episode_segments')
  2559. ->where('id', $act_id)
  2560. ->update([
  2561. 'act_number' => $new_act_number,
  2562. 'updated_at' => date('Y-m-d H:i:s')
  2563. ]);
  2564. if (!$update_result) {
  2565. Utils::throwError('20003:更新片段编号失败');
  2566. }
  2567. DB::commit();
  2568. return true;
  2569. } catch (\Exception $e) {
  2570. DB::rollBack();
  2571. Utils::throwError('20003:' . $e->getMessage());
  2572. }
  2573. }
  2574. public function delAct($data) {
  2575. $act_id = getProp($data, 'act_id');
  2576. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2577. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2578. if (!$segment) Utils::throwError('20003:请选择片段');
  2579. $anime_id = getProp($segment, 'anime_id');
  2580. $episode_id = getProp($segment, 'episode_id');
  2581. $act_number = getProp($segment, 'act_number');
  2582. try {
  2583. DB::beginTransaction();
  2584. // 删除该片段记录
  2585. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2586. if (!$deleted) {
  2587. Utils::throwError('20003:删除片段失败');
  2588. }
  2589. // 更新后续act的编号
  2590. DB::table('mp_episode_segments')
  2591. ->where('anime_id', $anime_id)
  2592. ->where('episode_id', $episode_id)
  2593. ->where('act_number', '>', $act_number)
  2594. ->decrement('act_number');
  2595. DB::commit();
  2596. }catch (\Exception $e) {
  2597. DB::rollBack();
  2598. Utils::throwError('20003:'.$e->getMessage());
  2599. }
  2600. return true;
  2601. }
  2602. public function applyAct($data) {
  2603. $act_id = getProp($data, 'act_id');
  2604. $url = getProp($data, 'url');
  2605. if (!$act_id) Utils::throwError('20003:请选择片段');
  2606. if (!$url) Utils::throwError('20003:URL不能为空');
  2607. // 获取URL的文件扩展名
  2608. $urlPath = parse_url($url, PHP_URL_PATH);
  2609. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2610. // 定义图片和视频的扩展名
  2611. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2612. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2613. // 判断是图片还是视频
  2614. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2615. if (in_array($extension, $imageExtensions)) {
  2616. // 图片类型
  2617. $updateData['img_url'] = $url;
  2618. $updateData['current_type'] = 1;
  2619. } elseif (in_array($extension, $videoExtensions)) {
  2620. // 视频类型
  2621. $updateData['video_url'] = $url;
  2622. $updateData['current_type'] = 2;
  2623. } else {
  2624. Utils::throwError('20003:不支持的文件类型');
  2625. }
  2626. // 更新片段记录(全能模式下每个act只有一条记录)
  2627. $result = DB::table('mp_episode_segments')
  2628. ->where('id', $act_id)
  2629. ->update($updateData);
  2630. if (!$result) {
  2631. Utils::throwError('20003:更新片段失败');
  2632. }
  2633. return true;
  2634. }
  2635. public function actChatHistory($data) {
  2636. $act_id = getProp($data, 'act_id');
  2637. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2638. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2639. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2640. $value = (array)$value;
  2641. $value['created_at'] = transDate($value['created_at']);
  2642. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2643. else $value['reference_images'] = [];
  2644. return $value;
  2645. })->toArray();
  2646. // 获取历史图片
  2647. $url = [];
  2648. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2649. foreach($pic_history as $task) {
  2650. $result_url = getProp($task, 'result_url');
  2651. if (is_json($result_url)) {
  2652. $url = array_merge($url, json_decode($result_url, true));
  2653. }else {
  2654. $url[] = $result_url;
  2655. }
  2656. }
  2657. // 获取历史视频
  2658. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2659. foreach($video_history as $task) {
  2660. $result_url = getProp($task, 'result_url');
  2661. if (is_json($result_url)) {
  2662. $url = array_merge($url, json_decode($result_url, true));
  2663. }else {
  2664. $url[] = $result_url;
  2665. }
  2666. }
  2667. // 获取资产库
  2668. $products = [];
  2669. // 通过act_id查询片段信息获取episode_id
  2670. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2671. if ($segment) {
  2672. $episode_id = getProp($segment, 'episode_id');
  2673. // 查询剧集信息获取roles、scenes和extra_products
  2674. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2675. if ($episode) {
  2676. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2677. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2678. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2679. // 先合并roles和scenes
  2680. // 处理角色数组
  2681. foreach ($roles as $role) {
  2682. $product = $role;
  2683. // 将role字段重命名为product_name
  2684. if (isset($product['role'])) {
  2685. $product['product_name'] = $product['role'];
  2686. unset($product['role']);
  2687. }
  2688. $product['product'] = 1; // 标记类型为角色
  2689. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2690. }
  2691. // 处理场景数组
  2692. foreach ($scenes as $scene) {
  2693. $product = $scene;
  2694. // 将scene字段重命名为product_name
  2695. if (isset($product['scene'])) {
  2696. $product['product_name'] = $product['scene'];
  2697. unset($product['scene']);
  2698. }
  2699. $product['product'] = 2; // 标记类型为场景
  2700. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2701. }
  2702. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2703. foreach ($extra_products as $extra_product) {
  2704. $product_name = getProp($extra_product, 'product_name');
  2705. if ($product_name) {
  2706. $products[$product_name] = $extra_product; // 覆盖同名数据
  2707. }
  2708. }
  2709. // 重新索引数组(去除key)
  2710. $products = array_values($products);
  2711. }
  2712. }
  2713. // 获取执行中的任务
  2714. $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) {
  2715. $value = (array)$value;
  2716. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2717. else $value['ref_image_url'] = [];
  2718. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2719. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2720. if (!empty($value['prompt'])) {
  2721. $prompt = $value['prompt'];
  2722. // 查找第一个【镜头】的位置
  2723. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2724. // 从【镜头】开始截取
  2725. $prompt = substr($prompt, $matches[0][1]);
  2726. }
  2727. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2728. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2729. $value['prompt'] = $prompt;
  2730. }
  2731. return $value;
  2732. })->toArray();
  2733. return compact('chat', 'url', 'products', 'tasks');
  2734. }
  2735. public function applyAudioData($data) {
  2736. $segment_id = getProp($data, 'segment_id');
  2737. $global_data = getProp($data, 'global_data');
  2738. $segment_data = getProp($data, 'segment_data');
  2739. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2740. $global_data = is_array($global_data) ? $global_data : [];
  2741. $segment_data = is_array($segment_data) ? $segment_data : [];
  2742. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2743. $dialogue_item = null;
  2744. foreach ($global_data as $key => $item) {
  2745. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2746. $dialogue_item = $item;
  2747. unset($global_data[$key]);
  2748. break;
  2749. }
  2750. }
  2751. if ($dialogue_item) {
  2752. $segment_data[] = $dialogue_item;
  2753. }
  2754. // 特殊参数: audio_url,audio_duration,subtitle_info
  2755. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2756. // 如果不是全部存在,则仍需创建音频任务
  2757. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2758. $special_update_data = [];
  2759. $has_all_special_params = false;
  2760. // 从segment_data中提取特殊参数
  2761. $filtered_segment_data = [];
  2762. foreach ($segment_data as $item) {
  2763. $field_name = trim((string)getProp($item, 'name'));
  2764. if (in_array($field_name, $special_fields)) {
  2765. $special_update_data[$field_name] = getProp($item, 'value');
  2766. } else {
  2767. // 非特殊参数保留,继续后续处理
  2768. $filtered_segment_data[] = $item;
  2769. }
  2770. }
  2771. // 检查是否三个特殊参数都存在
  2772. if (count($special_update_data) === 3 &&
  2773. isset($special_update_data['audio_url']) &&
  2774. isset($special_update_data['audio_duration']) &&
  2775. isset($special_update_data['subtitle_info'])) {
  2776. $has_all_special_params = true;
  2777. // 立即更新到当前分镜
  2778. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2779. DB::table('mp_episode_segments')
  2780. ->where('segment_id', $segment_id)
  2781. ->update($special_update_data);
  2782. }
  2783. // 使用过滤后的segment_data继续处理其他参数
  2784. $segment_data = $filtered_segment_data;
  2785. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2786. $global_update_data = [];
  2787. $segment_update_data = [];
  2788. $global_voice_type = '';
  2789. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2790. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2791. $episode_id = getProp($target_segment, 'episode_id');
  2792. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2793. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2794. if (!$episode) Utils::throwError('20003:分集不存在');
  2795. foreach ($global_data as $item) {
  2796. $field_name = trim((string)getProp($item, 'name'));
  2797. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2798. continue;
  2799. }
  2800. $global_update_data[$field_name] = getProp($item, 'value');
  2801. if ($field_name === 'voice_type') {
  2802. $global_voice_type = trim((string)getProp($item, 'value'));
  2803. }
  2804. }
  2805. foreach ($segment_data as $item) {
  2806. $field_name = trim((string)getProp($item, 'name'));
  2807. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2808. continue;
  2809. }
  2810. $segment_update_data[$field_name] = getProp($item, 'value');
  2811. }
  2812. if ($global_voice_type) {
  2813. $timbre_info = DB::table('mp_timbres')
  2814. ->where('timbre_type', $global_voice_type)
  2815. ->select('audio_url', 'timbre_name')
  2816. ->first();
  2817. if ($timbre_info) {
  2818. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  2819. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  2820. }
  2821. }
  2822. try {
  2823. DB::beginTransaction();
  2824. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  2825. $segment_ids_to_create_task = [];
  2826. $segments_data = [];
  2827. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  2828. if (!empty($global_update_data)) {
  2829. // 如果角色不存在,则只更新当前分镜
  2830. if (!$target_voice_actor) {
  2831. // 只处理当前分镜
  2832. $affected_segments = DB::table('mp_episode_segments')
  2833. ->where('segment_id', $segment_id)
  2834. ->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')
  2835. ->get();
  2836. } else {
  2837. // 获取该角色的所有分镜
  2838. $affected_segments = DB::table('mp_episode_segments')
  2839. ->where('episode_id', $episode_id)
  2840. ->where('voice_actor', $target_voice_actor)
  2841. ->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')
  2842. ->get();
  2843. }
  2844. foreach ($affected_segments as $seg) {
  2845. $seg = (array)$seg;
  2846. $sid = getProp($seg, 'segment_id');
  2847. // 检查参数是否发生变化
  2848. $has_changed = false;
  2849. foreach ($global_update_data as $field => $new_value) {
  2850. $old_value = getProp($seg, $field);
  2851. if ($old_value != $new_value) {
  2852. $has_changed = true;
  2853. break;
  2854. }
  2855. }
  2856. if ($has_changed) {
  2857. $segment_ids_to_create_task[] = $sid;
  2858. $segments_data[$sid] = $seg;
  2859. }
  2860. }
  2861. // 只有在有变化的分镜时才更新
  2862. if (!empty($segment_ids_to_create_task)) {
  2863. $global_segment_update_data = $global_update_data;
  2864. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  2865. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2866. DB::table('mp_episode_segments')
  2867. ->where('episode_id', $episode_id)
  2868. ->where('voice_actor', $target_voice_actor)
  2869. ->whereIn('segment_id', $segment_ids_to_create_task)
  2870. ->update($global_segment_update_data);
  2871. }
  2872. if ($global_voice_type) {
  2873. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  2874. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  2875. $roles_updated = false;
  2876. foreach ($episode_roles as &$role) {
  2877. // 通过 role 字段匹配角色名,而不是 voice_name
  2878. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  2879. continue;
  2880. }
  2881. $role['voice_type'] = $global_voice_type;
  2882. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  2883. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  2884. $roles_updated = true;
  2885. }
  2886. unset($role);
  2887. if ($roles_updated) {
  2888. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  2889. 'roles' => json_encode($episode_roles, 256),
  2890. 'updated_at' => date('Y-m-d H:i:s'),
  2891. ]);
  2892. }
  2893. }
  2894. }
  2895. // 如果有单个分镜更新,检查是否有变化
  2896. if (!empty($segment_update_data)) {
  2897. // 获取当前分镜数据
  2898. $current_segment = DB::table('mp_episode_segments')
  2899. ->where('segment_id', $segment_id)
  2900. ->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')
  2901. ->first();
  2902. if ($current_segment) {
  2903. $current_segment = (array)$current_segment;
  2904. // 检查参数是否发生变化
  2905. $has_changed = false;
  2906. foreach ($segment_update_data as $field => $new_value) {
  2907. $old_value = getProp($current_segment, $field);
  2908. if ($old_value != $new_value) {
  2909. $has_changed = true;
  2910. break;
  2911. }
  2912. }
  2913. if ($has_changed) {
  2914. // 如果该分镜还未在列表中,添加进去
  2915. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  2916. $segment_ids_to_create_task[] = $segment_id;
  2917. $segments_data[$segment_id] = $current_segment;
  2918. }
  2919. // 更新分镜数据并清空音频URL
  2920. $segment_update_data['audio_url'] = '';
  2921. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2922. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  2923. }
  2924. }
  2925. }
  2926. // 为所有有变化的分镜创建音频合成任务
  2927. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  2928. if (!empty($segment_ids_to_create_task)) {
  2929. foreach ($segment_ids_to_create_task as $sid) {
  2930. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  2931. if ($sid === $segment_id && $has_all_special_params) {
  2932. continue;
  2933. }
  2934. // 重新获取更新后的分镜数据
  2935. $updated_segment = DB::table('mp_episode_segments')
  2936. ->where('segment_id', $sid)
  2937. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  2938. ->first();
  2939. if (!$updated_segment) continue;
  2940. $updated_segment = (array)$updated_segment;
  2941. // 检查dialogue是否为空
  2942. $dialogue = getProp($updated_segment, 'dialogue');
  2943. if (empty($dialogue)) {
  2944. // dialogue为空时,直接写入默认音频信息
  2945. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  2946. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  2947. 'audio_duration' => 2.0,
  2948. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  2949. 'updated_at' => date('Y-m-d H:i:s')
  2950. ]);
  2951. continue;
  2952. }
  2953. $generate_json = [
  2954. 'text' => $dialogue,
  2955. 'role' => getProp($updated_segment, 'voice_actor'),
  2956. 'voice_type' => getProp($updated_segment, 'voice_type'),
  2957. 'voice_name' => getProp($updated_segment, 'voice_name'),
  2958. 'emotion' => getProp($updated_segment, 'emotion'),
  2959. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  2960. 'gender' => getProp($updated_segment, 'gender'),
  2961. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  2962. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  2963. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  2964. 'pitch' => getProp($updated_segment, 'pitch', 0),
  2965. ];
  2966. // 插入视频配音合成任务
  2967. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2968. 'alias_segment_id' => $sid,
  2969. 'generate_status' => '执行中',
  2970. 'audio_url' => '',
  2971. 'generate_json' => json_encode($generate_json, 256),
  2972. 'created_at' => date('Y-m-d H:i:s'),
  2973. 'updated_at' => date('Y-m-d H:i:s'),
  2974. ]);
  2975. if (!$dubTaskId) {
  2976. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  2977. continue;
  2978. }
  2979. // 将任务ID添加到Redis列表中
  2980. Redis::lpush('dub_video_task_queue', $dubTaskId);
  2981. // 请求远程服务器执行生成
  2982. try {
  2983. sleep(1);
  2984. $client = new Client(['timeout' => 300, 'verify' => false]);
  2985. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2986. $response = $result->getBody()->getContents();
  2987. $response_arr = json_decode($response, true);
  2988. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2989. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2990. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2991. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2992. }
  2993. } catch (\Exception $e) {
  2994. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2995. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2996. }
  2997. }
  2998. }
  2999. DB::commit();
  3000. } catch (\Exception $e) {
  3001. DB::rollBack();
  3002. Utils::throwError('20003:'.$e->getMessage());
  3003. }
  3004. return true;
  3005. }
  3006. public function episodePicsInfo($data) {
  3007. $anime_id = getProp($data, 'anime_id');
  3008. $episode_id = getProp($data, 'episode_id');
  3009. // 参数验证
  3010. if (!$anime_id && !$episode_id) {
  3011. Utils::throwError('20003:请提供动漫ID或分集ID');
  3012. }
  3013. // 根据参数获取数据源
  3014. if ($episode_id) {
  3015. // 从剧集表获取
  3016. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3017. if (!$source) Utils::throwError('20003:该剧集不存在');
  3018. $table_name = 'mp_anime_episodes';
  3019. $id_field = 'id';
  3020. $id_value = $episode_id;
  3021. // 获取剧集的anime_id用于继承全局数据
  3022. $anime_id = getProp($source, 'anime_id');
  3023. } else {
  3024. // 从动漫表获取
  3025. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3026. if (!$source) Utils::throwError('20003:该动漫不存在');
  3027. $table_name = 'mp_animes';
  3028. $id_field = 'id';
  3029. $id_value = $anime_id;
  3030. }
  3031. $source = (array)$source;
  3032. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3033. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3034. // 如果是分集数据,需要处理继承和任务创建逻辑
  3035. if ($episode_id) {
  3036. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3037. }
  3038. // 返回生成器函数,用于 SSE 流式输出
  3039. return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
  3040. $startTime = time();
  3041. $maxDuration = 600; // 10分钟超时
  3042. $checkInterval = 3; // 每3秒检查一次
  3043. // Redis 缓存键
  3044. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3045. // 生成当前数据的哈希值用于比较
  3046. $generateHash = function($roles, $scenes) {
  3047. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
  3048. };
  3049. // 发送初始数据
  3050. $currentHash = $generateHash($roles, $scenes);
  3051. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3052. echo "data: " . json_encode([
  3053. 'type' => 'init',
  3054. 'data' => [
  3055. 'roles' => $roles,
  3056. 'scenes' => $scenes,
  3057. 'start_time' => $startTime
  3058. ]
  3059. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3060. ob_flush();
  3061. flush();
  3062. // 持续轮询任务状态
  3063. while (time() - $startTime < $maxDuration) {
  3064. $hasProcessing = false;
  3065. $updated = false;
  3066. // 检查角色任务状态
  3067. foreach ($roles as $index => &$role) {
  3068. $task_id = getProp($role, 'task_id');
  3069. $task_status = getProp($role, 'task_status');
  3070. $existing_url = getProp($role, 'url');
  3071. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3072. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3073. $hasProcessing = ($task_status === 'processing');
  3074. // 查询任务状态
  3075. $task = DB::table('mp_generate_pic_tasks')
  3076. ->where('id', $task_id)
  3077. ->select('id', 'status', 'result_url', 'error_message')
  3078. ->first();
  3079. if ($task) {
  3080. $task = (array)$task;
  3081. $status = getProp($task, 'status');
  3082. // 如果任务完成或失败
  3083. if (in_array($status, ['success', 'failed'])) {
  3084. $role['task_status'] = $status;
  3085. if ($status === 'success') {
  3086. $result_url = getProp($task, 'result_url');
  3087. if ($result_url) {
  3088. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3089. if (is_array($result_urls) && !empty($result_urls[0])) {
  3090. $role['url'] = $result_urls[0];
  3091. }
  3092. }
  3093. }
  3094. $updated = true;
  3095. } else if ($status === 'processing') {
  3096. $hasProcessing = true;
  3097. }
  3098. }
  3099. }
  3100. }
  3101. // 检查场景任务状态
  3102. foreach ($scenes as $index => &$scene) {
  3103. $task_id = getProp($scene, 'task_id');
  3104. $task_status = getProp($scene, 'task_status');
  3105. $existing_url = getProp($scene, 'url');
  3106. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3107. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3108. $hasProcessing = ($task_status === 'processing');
  3109. // 查询任务状态
  3110. $task = DB::table('mp_generate_pic_tasks')
  3111. ->where('id', $task_id)
  3112. ->select('id', 'status', 'result_url', 'error_message')
  3113. ->first();
  3114. if ($task) {
  3115. $task = (array)$task;
  3116. $status = getProp($task, 'status');
  3117. // 如果任务完成或失败
  3118. if (in_array($status, ['success', 'failed'])) {
  3119. $scene['task_status'] = $status;
  3120. if ($status === 'success') {
  3121. $result_url = getProp($task, 'result_url');
  3122. if ($result_url) {
  3123. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3124. if (is_array($result_urls) && !empty($result_urls[0])) {
  3125. $scene['url'] = $result_urls[0];
  3126. }
  3127. }
  3128. }
  3129. $updated = true;
  3130. } else if ($status === 'processing') {
  3131. $hasProcessing = true;
  3132. }
  3133. }
  3134. }
  3135. }
  3136. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3137. if ($updated) {
  3138. $newHash = $generateHash($roles, $scenes);
  3139. $cachedHash = Redis::get($cacheKey);
  3140. // 只有当数据真正变化时才更新数据库和发送事件
  3141. if ($newHash !== $cachedHash) {
  3142. try {
  3143. // 更新数据库
  3144. DB::table($table_name)->where($id_field, $id_value)->update([
  3145. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3146. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3147. 'updated_at' => date('Y-m-d H:i:s')
  3148. ]);
  3149. // 更新缓存
  3150. Redis::setex($cacheKey, 600, $newHash);
  3151. // 发送更新事件
  3152. echo "data: " . json_encode([
  3153. 'type' => 'update',
  3154. 'data' => [
  3155. 'roles' => $roles,
  3156. 'scenes' => $scenes,
  3157. 'elapsed_time' => time() - $startTime
  3158. ]
  3159. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3160. ob_flush();
  3161. flush();
  3162. } catch (\Exception $e) {
  3163. dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
  3164. }
  3165. } else {
  3166. // 即使哈希相同,如果有URL更新也要发送事件
  3167. $hasUrlUpdate = false;
  3168. foreach ($roles as $role) {
  3169. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3170. $hasUrlUpdate = true;
  3171. break;
  3172. }
  3173. }
  3174. if (!$hasUrlUpdate) {
  3175. foreach ($scenes as $scene) {
  3176. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3177. $hasUrlUpdate = true;
  3178. break;
  3179. }
  3180. }
  3181. }
  3182. if ($hasUrlUpdate) {
  3183. // 强制更新数据库和发送事件
  3184. try {
  3185. DB::table($table_name)->where($id_field, $id_value)->update([
  3186. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3187. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3188. 'updated_at' => date('Y-m-d H:i:s')
  3189. ]);
  3190. // 更新缓存
  3191. Redis::setex($cacheKey, 600, $newHash);
  3192. // 发送更新事件
  3193. echo "data: " . json_encode([
  3194. 'type' => 'update',
  3195. 'data' => [
  3196. 'roles' => $roles,
  3197. 'scenes' => $scenes,
  3198. 'elapsed_time' => time() - $startTime
  3199. ]
  3200. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3201. ob_flush();
  3202. flush();
  3203. } catch (\Exception $e) {
  3204. dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
  3205. }
  3206. }
  3207. }
  3208. }
  3209. // 如果所有任务都已完成,发送完成事件并退出
  3210. if (!$hasProcessing) {
  3211. // 查询数据库中的最终数据,确保返回最新的完整数据
  3212. try {
  3213. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3214. if ($finalSource) {
  3215. $finalSource = (array)$finalSource;
  3216. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3217. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3218. // 使用数据库中的最终数据
  3219. $roles = $finalRoles;
  3220. $scenes = $finalScenes;
  3221. }
  3222. } catch (\Exception $e) {
  3223. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3224. // 如果查询失败,继续使用内存中的数据
  3225. }
  3226. // 清理缓存
  3227. Redis::del($cacheKey);
  3228. echo "data: " . json_encode([
  3229. 'type' => 'completed',
  3230. 'data' => [
  3231. 'roles' => $roles,
  3232. 'scenes' => $scenes,
  3233. 'total_time' => time() - $startTime
  3234. ]
  3235. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3236. ob_flush();
  3237. flush();
  3238. break;
  3239. }
  3240. // 等待下次检查
  3241. sleep($checkInterval);
  3242. }
  3243. // 超时处理
  3244. if (time() - $startTime >= $maxDuration) {
  3245. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3246. try {
  3247. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3248. if ($finalSource) {
  3249. $finalSource = (array)$finalSource;
  3250. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3251. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3252. // 使用数据库中的最终数据
  3253. $roles = $finalRoles;
  3254. $scenes = $finalScenes;
  3255. }
  3256. } catch (\Exception $e) {
  3257. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3258. // 如果查询失败,继续使用内存中的数据
  3259. }
  3260. // 清理缓存
  3261. Redis::del($cacheKey);
  3262. echo "data: " . json_encode([
  3263. 'type' => 'timeout',
  3264. 'message' => '轮询超时,请刷新页面查看最新状态',
  3265. 'data' => [
  3266. 'roles' => $roles,
  3267. 'scenes' => $scenes
  3268. ]
  3269. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3270. ob_flush();
  3271. flush();
  3272. }
  3273. };
  3274. }
  3275. public function clipSegmentVideo($data) {
  3276. $segment_id = getProp($data, 'segment_id');
  3277. $video_time_point_start = getProp($data, 'video_time_point_start');
  3278. $video_time_point_end = getProp($data, 'video_time_point_end');
  3279. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3280. Utils::throwError('20003:参数异常');
  3281. }
  3282. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3283. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3284. }
  3285. $video_duration = $video_time_point_end - $video_time_point_start;
  3286. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3287. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3288. 'video_duration' => $video_duration,
  3289. 'video_time_point_start' => $video_time_point_start,
  3290. 'video_time_point_end' => $video_time_point_end,
  3291. 'updated_at' => date('Y-m-d H:i:s')
  3292. ]);
  3293. }
  3294. // 轮训获取图片任务结果
  3295. private function loopGetPicTaskResult($task_id) {
  3296. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3297. if (!$task) {
  3298. return '';
  3299. }
  3300. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3301. $model = getProp($task, 'model');
  3302. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3303. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3304. $isSyncModel = $isVolcModel || $isGptModel;
  3305. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3306. $start_count = 0;
  3307. $img_url = '';
  3308. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3309. sleep(3);
  3310. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3311. // 如果任务已经完成,直接返回结果
  3312. if ($task->status === 'success' && $task->result_url) {
  3313. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3314. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3315. }
  3316. // 如果任务已失败,返回空
  3317. if ($task->status === 'failed') {
  3318. return '';
  3319. }
  3320. if ($isSyncModel) continue;
  3321. // 查询任务状态
  3322. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3323. if ($statusInfo['status'] === 'success') {
  3324. $task->updateStatus('success', [
  3325. 'result_url' => $statusInfo['result_url'],
  3326. 'result_json' => $statusInfo['result_json'] ?? []
  3327. ]);
  3328. // 同步调整分镜图片状态和结果
  3329. if (getProp($task, 'alias_segment_id')) {
  3330. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3331. 'img_url' => $statusInfo['result_url'][0],
  3332. 'pic_task_status' => '已完成',
  3333. ]);
  3334. }
  3335. $img_url = $statusInfo['result_url'][0];
  3336. break;
  3337. } elseif ($statusInfo['status'] === 'failed') {
  3338. $task->updateStatus('failed', [
  3339. 'error_message' => $statusInfo['error_message'],
  3340. 'result_json' => $statusInfo['result_json'] ?? []
  3341. ]);
  3342. if (getProp($task, 'alias_segment_id')) {
  3343. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3344. 'pic_task_status' => '失败',
  3345. ]);
  3346. }
  3347. break;
  3348. }
  3349. $start_count++;
  3350. }
  3351. return $img_url;
  3352. }
  3353. /**
  3354. * 从分镜内容中提取涉及的角色
  3355. */
  3356. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3357. $found_characters = [];
  3358. foreach ($available_characters as $character) {
  3359. // 检查角色名称是否在分镜内容中出现
  3360. if (strpos($segment_content, $character) !== false) {
  3361. $found_characters[] = $character;
  3362. }
  3363. }
  3364. if (!$found_characters) {
  3365. foreach ($roles as $character) {
  3366. // 检查角色名称是否在分镜内容中出现
  3367. if (strpos($segment_content, $character) !== false) {
  3368. $found_characters[] = $character;
  3369. }
  3370. }
  3371. }
  3372. return array_unique($found_characters);
  3373. }
  3374. // 从分镜剧本中提取关键字段
  3375. private function handleSegmentContent(&$data) {
  3376. $segmentContent = getProp($data, 'segment_content');
  3377. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3378. $segmentData = [
  3379. 'description' => '',
  3380. 'composition' => '',
  3381. 'camera_movement' => '',
  3382. 'voice_actor' => '',
  3383. 'dialogue' => '',
  3384. 'frame_type' => '',
  3385. 'scene' => '', // 场景
  3386. 'characters' => '', // 出镜角色
  3387. 'tail_frame' => '', // 尾帧描述
  3388. 'emotion' => '中性', // 情感
  3389. 'gender' => '0', // 性别(0未知,1男,2女)
  3390. 'speed_ratio' => 0, // 语速
  3391. 'loudness_ratio' => 0, // 音量
  3392. 'emotion_scale' => 4, // 情感强度
  3393. 'pitch' => 0, // 音调
  3394. ];
  3395. // 用于存储需要从 segment_content 中移除的匹配项
  3396. $replaceEmptyArr = [];
  3397. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3398. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3399. $segmentData['description'] = trim($descMatch[1]);
  3400. $data['description'] = trim($descMatch[1]);
  3401. }
  3402. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3403. $segmentData['composition'] = trim($compMatch[1]);
  3404. $data['composition'] = trim($compMatch[1]);
  3405. }
  3406. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3407. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3408. $data['camera_movement'] = trim($cameraMatch[1]);
  3409. }
  3410. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3411. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3412. $data['voice_actor'] = trim($voiceMatch[1]);
  3413. }
  3414. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3415. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3416. $data['dialogue'] = trim($dialogueMatch[1]);
  3417. }
  3418. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3419. $segmentData['frame_type'] = trim($frameMatch[1]);
  3420. $data['frame_type'] = trim($frameMatch[1]);
  3421. }
  3422. // 场景字段
  3423. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3424. $segmentData['scene'] = trim($sceneMatch[1]);
  3425. $data['scene'] = trim($sceneMatch[1]);
  3426. }
  3427. // 出镜角色字段
  3428. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3429. $segmentData['characters'] = trim($charactersMatch[1]);
  3430. $data['characters'] = trim($charactersMatch[1]);
  3431. }
  3432. // 尾帧描述字段
  3433. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3434. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3435. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3436. }
  3437. // 情感字段
  3438. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3439. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3440. $segmentData['emotion'] = trim($emotionMatch[1]);
  3441. $data['emotion'] = trim($emotionMatch[1]);
  3442. }
  3443. // 性别字段
  3444. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3445. $replaceEmptyArr[] = trim($genderMatch[0]);
  3446. $genderStr = trim($genderMatch[1]);
  3447. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3448. $segmentData['gender'] = '1';
  3449. $data['gender'] = '1';
  3450. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3451. $segmentData['gender'] = '2';
  3452. $data['gender'] = '2';
  3453. } else {
  3454. $segmentData['gender'] = '0';
  3455. $data['gender'] = '0';
  3456. }
  3457. }
  3458. // 语速字段
  3459. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3460. $replaceEmptyArr[] = trim($speedMatch[0]);
  3461. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3462. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3463. }
  3464. // 音量字段
  3465. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3466. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3467. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3468. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3469. }
  3470. // 情感强度字段
  3471. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3472. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3473. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3474. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3475. }
  3476. // 音调字段
  3477. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3478. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3479. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3480. $data['pitch'] = (int)trim($pitchMatch[1]);
  3481. }
  3482. // 从 segment_content 中移除已提取的配音参数字段
  3483. if (!empty($replaceEmptyArr)) {
  3484. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3485. }
  3486. // 如果有配音角色,查询音色信息并验证情感
  3487. $voice_actor = $segmentData['voice_actor'];
  3488. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3489. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3490. $anime_id = getProp($data, 'anime_id');
  3491. $episode_id = getProp($data, 'episode_id');
  3492. // 优先从剧集的角色列表中查找
  3493. $roles = [];
  3494. if ($episode_id) {
  3495. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3496. if ($episode && getProp($episode, 'roles')) {
  3497. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3498. }
  3499. }
  3500. // 如果剧集中没有,从动漫的角色列表中查找
  3501. if (empty($roles) && $anime_id) {
  3502. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3503. if ($anime && getProp($anime, 'roles')) {
  3504. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3505. }
  3506. }
  3507. // 查找匹配的角色音色信息
  3508. $timbre_info = null;
  3509. foreach ($roles as $role) {
  3510. if (getProp($role, 'role') === $voice_actor) {
  3511. $timbre_info = $role;
  3512. break;
  3513. }
  3514. }
  3515. // 如果找到音色信息,添加到数据中
  3516. if ($timbre_info) {
  3517. $voice_type = getProp($timbre_info, 'voice_type');
  3518. $voice_name = getProp($timbre_info, 'voice_name');
  3519. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3520. if ($voice_type) {
  3521. $data['voice_type'] = $voice_type;
  3522. $segmentData['voice_type'] = $voice_type;
  3523. }
  3524. if ($voice_name) {
  3525. $data['voice_name'] = $voice_name;
  3526. $segmentData['voice_name'] = $voice_name;
  3527. }
  3528. if ($voice_audio_url) {
  3529. $data['voice_audio_url'] = $voice_audio_url;
  3530. $segmentData['voice_audio_url'] = $voice_audio_url;
  3531. }
  3532. // 验证情感是否在音色支持的情感列表中
  3533. if ($voice_type) {
  3534. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3535. if ($timbre_emotion) {
  3536. $timbre_emotion = explode(',', $timbre_emotion);
  3537. } else {
  3538. $timbre_emotion = [];
  3539. }
  3540. $emotion = getProp($segmentData, 'emotion', '中性');
  3541. if (!in_array($emotion, $timbre_emotion)) {
  3542. $emotion = '中性';
  3543. }
  3544. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3545. $emotion_list = array_flip($emotion_list);
  3546. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3547. $data['emotion_type'] = $emotion_type;
  3548. $segmentData['emotion_type'] = $emotion_type;
  3549. }
  3550. }
  3551. }
  3552. return $segmentData;
  3553. }
  3554. public function createSegmentVideoTask($data) {
  3555. $segment_id = getProp($data, 'segment_id');
  3556. $tail_frame = getProp($data, 'tail_frame');
  3557. $first_frame_url = getProp($data, 'first_frame_url');
  3558. $tail_frame_url = getProp($data, 'tail_frame_url');
  3559. $generate_audio = getProp($data, 'generate_audio', 0);
  3560. if (!$segment_id) {
  3561. Utils::throwError('1002:分镜ID不能为空');
  3562. }
  3563. // 获取分镜信息
  3564. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3565. if (!$segment) {
  3566. Utils::throwError('20003:分镜不存在');
  3567. }
  3568. $segment = (array)$segment;
  3569. $episode_id = getProp($segment, 'episode_id');
  3570. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3571. if (!$ratio) $ratio = '9:16';
  3572. // 获取分镜内容
  3573. $segmentContent = getProp($segment, 'segment_content', '');
  3574. // 检查 $segmentContent 中是否已有尾帧描述
  3575. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3576. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3577. $finalTailFrame = '';
  3578. if ($tail_frame) {
  3579. // 用户输入了尾帧描述,优先使用
  3580. $finalTailFrame = $tail_frame;
  3581. // 如果 segmentContent 中已有尾帧描述,需要替换
  3582. if ($contentHasTailFrame) {
  3583. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3584. }
  3585. } elseif ($contentHasTailFrame) {
  3586. // segmentContent 中有尾帧描述,使用它
  3587. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3588. } else {
  3589. // 两者都没有,使用分镜表中的尾帧描述
  3590. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3591. }
  3592. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3593. $hasDialogue = false;
  3594. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3595. $dialogue = trim($dialogueMatch[1]);
  3596. // 如果台词不为空且不是"无"
  3597. if (!empty($dialogue) && $dialogue !== '无') {
  3598. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3599. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3600. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3601. $hasDialogue = true;
  3602. }
  3603. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3604. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3605. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3606. if (!preg_match('/^[“]/', $dialogue)) {
  3607. $dialogue = '“' . $dialogue;
  3608. }
  3609. if (!preg_match('/[”]$/', $dialogue)) {
  3610. $dialogue .= '”';
  3611. }
  3612. // 将修改后的台词替换回 $segmentContent
  3613. $originalDialogue = $dialogueMatch[1];
  3614. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3615. }
  3616. }
  3617. // 构建完整的提示词
  3618. $fullPrompt = $segmentContent;
  3619. if ($finalTailFrame && !$contentHasTailFrame) {
  3620. // 只有当 segmentContent 中没有尾帧描述时才追加
  3621. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3622. }
  3623. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3624. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3625. $fullPrompt = trim($fullPrompt);
  3626. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3627. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3628. // 智能选择视频时长
  3629. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3630. $videoDuration = -1;
  3631. // 处理视频模型
  3632. $model = getProp($data, 'model');
  3633. if (!$model) {
  3634. // 用户没有输入,从episode表获取
  3635. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3636. $model = getProp($episode, 'video_model');
  3637. if (!$model) {
  3638. // episode表也没有,使用默认值
  3639. $model = 'doubao-seedance-1-5-pro-251215';
  3640. }
  3641. }
  3642. // 验证模型是否在可用模型表中
  3643. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3644. $model = 'doubao-seedance-1-5-pro-251215';
  3645. }
  3646. // 保存到episode表
  3647. $episode_id = getProp($segment, 'episode_id');
  3648. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3649. 'video_model' => $model,
  3650. 'updated_at' => date('Y-m-d H:i:s')
  3651. ]);
  3652. // 构建视频生成参数
  3653. $videoParams = [
  3654. 'model' => $model,
  3655. 'alias_segment_id' => $segment_id,
  3656. 'prompt' => trim($fullPrompt),
  3657. 'video_duration' => $videoDuration,
  3658. 'video_resolution' => '720P',
  3659. 'seed' => -1,
  3660. 'ratio' => $ratio,
  3661. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3662. 'draft' => false,
  3663. 'watermark' => false,
  3664. 'camera_fixed' => false,
  3665. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3666. ];
  3667. // 如果分镜有图片,作为首帧
  3668. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3669. $hasVideo = !empty(getProp($segment, 'video_url'));
  3670. if ($hasImage) {
  3671. if ($first_frame_url) {
  3672. $videoParams['first_frame_url'] = $first_frame_url;
  3673. }else {
  3674. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3675. }
  3676. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3677. }
  3678. // 构建content数组
  3679. $videoParams['content'] = [
  3680. [
  3681. 'type' => 'text',
  3682. 'text' => $videoParams['prompt'],
  3683. ]
  3684. ];
  3685. // 如果有首帧图片,添加到content中
  3686. if ($hasImage) {
  3687. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3688. $videoParams['content'][] = [
  3689. 'type' => 'image_url',
  3690. 'image_url' => [
  3691. 'url' => $videoParams['first_frame_url'],
  3692. ],
  3693. 'role' => 'reference_image',
  3694. ];
  3695. if (isset($videoParams['tail_frame_url'])) {
  3696. $videoParams['content'][] = [
  3697. 'type' => 'image_url',
  3698. 'image_url' => [
  3699. 'url' => $videoParams['tail_frame_url'],
  3700. ],
  3701. 'role' => 'reference_image',
  3702. ];
  3703. }
  3704. }else {
  3705. $videoParams['content'][] = [
  3706. 'type' => 'image_url',
  3707. 'image_url' => [
  3708. 'url' => $videoParams['first_frame_url'],
  3709. ],
  3710. 'role' => 'first_frame',
  3711. ];
  3712. if (isset($videoParams['tail_frame_url'])) {
  3713. $videoParams['content'][] = [
  3714. 'type' => 'image_url',
  3715. 'image_url' => [
  3716. 'url' => $videoParams['tail_frame_url'],
  3717. ],
  3718. 'role' => 'last_frame',
  3719. ];
  3720. }
  3721. }
  3722. }
  3723. // 获取配音音频URL
  3724. $audioUrl = getProp($segment, 'audio_url');
  3725. $audioDuration = getProp($segment, 'audio_duration');
  3726. // 音频传入的前提:必须有至少一张图片或一个视频
  3727. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3728. // dd($videoParams);
  3729. // 根据模型选择不同的视频生成方法
  3730. if (strpos($model, 'jimeng') !== false) {
  3731. // 即梦模型参数调整
  3732. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3733. unset($videoParams['content']); // 即梦不使用content格式
  3734. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3735. } elseif (strpos($model, 'kling') !== false) {
  3736. // Keling模型参数调整
  3737. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  3738. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3739. unset($videoParams['ratio']);
  3740. unset($videoParams['content']); // Keling不使用content格式
  3741. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3742. } elseif (strpos($model, 'zhizhen') !== false) {
  3743. // 智帧20等新模型使用统一API
  3744. // 构建统一API参数
  3745. $unifiedParams = [
  3746. 'model_code' => $model,
  3747. 'alias_segment_id' => $segment_id,
  3748. 'prompt' => trim($fullPrompt),
  3749. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  3750. 'video_resolution' => strtolower($videoParams['video_resolution']),
  3751. 'video_ratio' => $ratio,
  3752. 'seed' => -1,
  3753. ];
  3754. // 构建parameters参数
  3755. $parameters = [
  3756. 'seconds' => $unifiedParams['video_duration'],
  3757. 'resolution' => $unifiedParams['video_resolution'],
  3758. 'ratio' => $ratio,
  3759. // 'video_mode' => 'multi_image',
  3760. // 'mode' => 'multi_image',
  3761. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  3762. ];
  3763. $hasImage = false;
  3764. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  3765. if ($hasImage) {
  3766. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  3767. if (isset($videoParams['tail_frame_url'])) {
  3768. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  3769. }
  3770. // 只有在有图片的情况下才能添加参考音频
  3771. if ($audioUrl) {
  3772. // $parameters['reference_audios'] = [$audioUrl];
  3773. }
  3774. } else {
  3775. // 没有图片时,记录错误日志
  3776. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  3777. 'segment_id' => $segment_id,
  3778. 'model' => $model
  3779. ]);
  3780. }
  3781. $unifiedParams['parameters'] = $parameters;
  3782. // 调用统一API创建任务
  3783. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  3784. } else {
  3785. // Seedance模型(默认)
  3786. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  3787. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3788. // 添加配音音频到content中
  3789. $videoParams['content'][] = [
  3790. 'type' => 'audio_url',
  3791. 'audio_url' => [
  3792. 'url' => $audioUrl,
  3793. ],
  3794. 'role' => 'reference_audio',
  3795. ];
  3796. // 优化提示词,增加音频相关描述
  3797. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  3798. $videoParams['prompt'] = $audioPrompt;
  3799. $videoParams['content'][0]['text'] = $audioPrompt;
  3800. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  3801. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  3802. }
  3803. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  3804. }
  3805. // 更新分镜表的视频任务信息
  3806. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3807. 'video_task_id' => $task->id,
  3808. 'video_task_status' => '生成中',
  3809. 'generate_audio' => $generate_audio,
  3810. 'updated_at' => date('Y-m-d H:i:s')
  3811. ]);
  3812. return [
  3813. 'task_id' => $task->id,
  3814. 'status' => $task->status,
  3815. 'segment_id' => $segment_id,
  3816. 'video_duration' => $videoDuration
  3817. ];
  3818. }
  3819. public function createActVideoTask($data) {
  3820. $act_id = getProp($data, 'act_id');
  3821. $first_frame_url = getProp($data, 'first_frame_url');
  3822. $tail_frame_url = getProp($data, 'tail_frame_url');
  3823. $generate_audio = getProp($data, 'generate_audio', 1);
  3824. $video_duration = getProp($data, 'video_duration');
  3825. $video_resolution = getProp($data, 'video_resolution');
  3826. $ratio = getProp($data, 'ratio');
  3827. $products = getProp($data, 'products', []);
  3828. $reference_images = array_unique(getProp($data, 'reference_images', []));
  3829. if (!is_array($reference_images) || !is_array($products)) {
  3830. Utils::throwError('20003:传入的参考图或资产格式不正确');
  3831. }
  3832. if (!$act_id) {
  3833. Utils::throwError('1002:片段ID不能为空');
  3834. }
  3835. // 获取片段信息
  3836. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3837. if (!$act) {
  3838. Utils::throwError('20003:片段不存在');
  3839. }
  3840. $act = (array)$act;
  3841. $anime_id = getProp($act, 'anime_id');
  3842. $episode_id = getProp($act, 'episode_id');
  3843. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3844. $ace_mode = getProp($anime, 'ace_mode');
  3845. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3846. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  3847. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  3848. // 将资产中新出现的资产放到extra_products中
  3849. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  3850. if (!empty($products) && $episode) {
  3851. // 获取剧集中的角色和场景列表
  3852. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3853. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3854. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3855. // 构建角色名称列表
  3856. $role_names = array_column($roles, 'role');
  3857. // 构建场景名称列表
  3858. $scene_names = array_column($scenes, 'scene');
  3859. // 遍历传入的products
  3860. foreach ($products as $product) {
  3861. $product_name = getProp($product, 'product_name');
  3862. // 如果product_name不在roles和scenes中
  3863. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
  3864. // 查找是否在extra_products中存在同名的
  3865. $found = false;
  3866. foreach ($extra_products as $key => $extra_product) {
  3867. if (getProp($extra_product, 'product_name') === $product_name) {
  3868. // 有同名的则覆盖
  3869. $extra_products[$key] = $product;
  3870. $found = true;
  3871. break;
  3872. }
  3873. }
  3874. // 没有则新增
  3875. if (!$found) {
  3876. $extra_products[] = $product;
  3877. }
  3878. }
  3879. }
  3880. if ($extra_products) {
  3881. // 保存到数据库
  3882. DB::table('mp_anime_episodes')
  3883. ->where('id', $episode_id)
  3884. ->update([
  3885. 'extra_products' => json_encode($extra_products, 256),
  3886. 'updated_at' => date('Y-m-d H:i:s')
  3887. ]);
  3888. }
  3889. }
  3890. // 获取分镜内容
  3891. $actContent = getProp($act, 'act_show_content', '');
  3892. // 音效同出(默认使用)
  3893. $current_generate_audio = $generate_audio ? 1 : 0;
  3894. // 构建完整的提示词
  3895. $processResult = $this->processActContentWithProducts($actContent, $products);
  3896. $fullPrompt = $processResult['content'];
  3897. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  3898. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  3899. // 处理视频模型
  3900. $model = getProp($data, 'model');
  3901. if (!$model) {
  3902. $model = getProp($episode, 'video_model');
  3903. if (!$model) {
  3904. // episode表也没有,使用默认值
  3905. $model = 'zhizhen-20-mini';
  3906. }
  3907. }
  3908. // 验证模型是否在可用模型表中
  3909. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3910. $model = 'zhizhen-20-mini';
  3911. }
  3912. // 保存到episode表
  3913. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3914. 'video_model' => $model,
  3915. 'updated_at' => date('Y-m-d H:i:s')
  3916. ]);
  3917. // 构建视频生成参数
  3918. $videoParams = [
  3919. 'model' => $model,
  3920. 'alias_act_id' => $act_id,
  3921. 'prompt' => trim($fullPrompt),
  3922. 'video_duration' => $videoDuration,
  3923. 'video_resolution' => $video_resolution,
  3924. 'seed' => -1,
  3925. 'ratio' => $ratio,
  3926. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3927. 'draft' => false,
  3928. 'watermark' => false,
  3929. 'camera_fixed' => false,
  3930. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3931. ];
  3932. // 如果分镜有图片,作为首帧
  3933. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  3934. $hasVideo = !empty(getProp($act, 'video_url'));
  3935. if ($hasImage) {
  3936. if ($first_frame_url) {
  3937. $videoParams['first_frame_url'] = $first_frame_url;
  3938. }else {
  3939. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  3940. }
  3941. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3942. }
  3943. // 构建content数组
  3944. $videoParams['content'] = [
  3945. [
  3946. 'type' => 'text',
  3947. 'text' => $videoParams['prompt'],
  3948. ]
  3949. ];
  3950. // 如果有首帧图片,添加到content中
  3951. if ($hasImage) {
  3952. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3953. $videoParams['content'][] = [
  3954. 'type' => 'image_url',
  3955. 'image_url' => [
  3956. 'url' => $videoParams['first_frame_url'],
  3957. ],
  3958. 'role' => 'reference_image',
  3959. ];
  3960. if (isset($videoParams['tail_frame_url'])) {
  3961. $videoParams['content'][] = [
  3962. 'type' => 'image_url',
  3963. 'image_url' => [
  3964. 'url' => $videoParams['tail_frame_url'],
  3965. ],
  3966. 'role' => 'reference_image',
  3967. ];
  3968. }
  3969. }else {
  3970. $videoParams['content'][] = [
  3971. 'type' => 'image_url',
  3972. 'image_url' => [
  3973. 'url' => $videoParams['first_frame_url'],
  3974. ],
  3975. 'role' => 'first_frame',
  3976. ];
  3977. if (isset($videoParams['tail_frame_url'])) {
  3978. $videoParams['content'][] = [
  3979. 'type' => 'image_url',
  3980. 'image_url' => [
  3981. 'url' => $videoParams['tail_frame_url'],
  3982. ],
  3983. 'role' => 'last_frame',
  3984. ];
  3985. }
  3986. }
  3987. }
  3988. // dd($videoParams);
  3989. // 根据模型选择不同的视频生成方法
  3990. if (strpos($model, 'jimeng') !== false) {
  3991. // 即梦模型参数调整
  3992. unset($videoParams['content']); // 即梦不使用content格式
  3993. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3994. } elseif (strpos($model, 'kling') !== false) {
  3995. // Keling模型参数调整
  3996. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3997. unset($videoParams['ratio']);
  3998. unset($videoParams['content']); // Keling不使用content格式
  3999. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4000. } elseif (strpos($model, 'zhizhen') !== false) {
  4001. // 智帧20等新模型使用统一API
  4002. // 构建统一API参数
  4003. $unifiedParams = [
  4004. 'model_code' => $model,
  4005. 'alias_act_id' => $act_id,
  4006. 'prompt' => trim($fullPrompt),
  4007. 'video_duration' => $videoDuration,
  4008. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4009. 'video_ratio' => $ratio,
  4010. 'seed' => -1,
  4011. ];
  4012. // 构建parameters参数
  4013. $parameters = [
  4014. 'seconds' => $unifiedParams['video_duration'],
  4015. 'resolution' => $unifiedParams['video_resolution'],
  4016. 'ratio' => $ratio,
  4017. // 'video_mode' => 'multi_image',
  4018. // 'mode' => 'multi_image',
  4019. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4020. ];
  4021. $hasImage = false;
  4022. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4023. if ($hasImage) {
  4024. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4025. if (isset($videoParams['tail_frame_url'])) {
  4026. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4027. }
  4028. } else {
  4029. // 没有图片时,记录错误日志
  4030. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4031. 'act_id' => $act_id,
  4032. 'model' => $model
  4033. ]);
  4034. }
  4035. if ($reference_images) {
  4036. // 限制只传入9张参考图
  4037. $reference_images = array_slice($reference_images, 0, 9);
  4038. // 在处理之前先保存原始reference_images到任务参数中
  4039. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4040. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4041. $parameters['reference_images'] = $reference_images;
  4042. $parameters['video_mode'] = 'multi_image';
  4043. $parameters['mode'] = 'multi_image';
  4044. }
  4045. $unifiedParams['parameters'] = $parameters;
  4046. // 调用统一API创建任务
  4047. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4048. } else {
  4049. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4050. }
  4051. // 更新分镜表的视频任务信息
  4052. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4053. 'video_task_id' => $task->id,
  4054. 'video_task_status' => '生成中',
  4055. 'generate_audio' => $generate_audio,
  4056. 'updated_at' => date('Y-m-d H:i:s')
  4057. ]);
  4058. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4059. $episode_number = getProp($act, 'episode_number');
  4060. $act_number = getProp($act, 'act_number');
  4061. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4062. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4063. }
  4064. return [
  4065. 'task_id' => $task->id,
  4066. 'status' => $task->status,
  4067. 'act_id' => $act_id,
  4068. 'video_duration' => $videoDuration
  4069. ];
  4070. }
  4071. /**
  4072. * 根据提示词内容智能计算最优视频时长
  4073. *
  4074. * @param string $segmentContent 分镜内容
  4075. * @param string $tailFrame 尾帧描述
  4076. * @return int 视频时长(2-12秒)
  4077. */
  4078. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4079. // 合并所有文本内容
  4080. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4081. // 如果没有内容,返回默认时长
  4082. if (empty($fullText)) {
  4083. return 5;
  4084. }
  4085. // 计算文本长度(中文字符按2个字符计算)
  4086. $textLength = mb_strlen($fullText, 'UTF-8');
  4087. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4088. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4089. // 分析内容复杂度
  4090. $complexityScore = $this->analyzeContentComplexity($fullText);
  4091. // 基础时长计算(根据文本长度)
  4092. $baseDuration = 3; // 默认2秒
  4093. // if ($adjustedLength <= 20) {
  4094. // $baseDuration = 3;
  4095. // } elseif ($adjustedLength <= 40) {
  4096. // $baseDuration = 4;
  4097. // } elseif ($adjustedLength <= 60) {
  4098. // $baseDuration = 5;
  4099. // } elseif ($adjustedLength <= 80) {
  4100. // $baseDuration = 6;
  4101. // } elseif ($adjustedLength <= 100) {
  4102. // $baseDuration = 7;
  4103. // } elseif ($adjustedLength <= 120) {
  4104. // $baseDuration = 8;
  4105. // } else {
  4106. // $baseDuration = 9;
  4107. // }
  4108. // 根据内容复杂度调整时长
  4109. $finalDuration = $baseDuration + $complexityScore;
  4110. // 确保时长在2-12秒范围内
  4111. return max(4, min(12, $finalDuration));
  4112. }
  4113. /**
  4114. * 分析内容复杂度,返回时长调整值
  4115. *
  4116. * @param string $text 文本内容
  4117. * @return int 调整值(-2到+3)
  4118. */
  4119. private function analyzeContentComplexity($text) {
  4120. $score = 0;
  4121. // 动作关键词(需要更长时间展现)
  4122. $actionKeywords = [
  4123. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4124. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4125. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4126. ];
  4127. // 静态关键词(可以用较短时间)
  4128. $staticKeywords = [
  4129. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4130. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4131. ];
  4132. // 复杂场景关键词(需要更长时间)
  4133. $complexSceneKeywords = [
  4134. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4135. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4136. ];
  4137. // 情感关键词(需要适中时间表现)
  4138. $emotionKeywords = [
  4139. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4140. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4141. ];
  4142. // 检查动作关键词
  4143. foreach ($actionKeywords as $keyword) {
  4144. if (strpos($text, $keyword) !== false) {
  4145. $score += 1;
  4146. break; // 避免重复加分
  4147. }
  4148. }
  4149. // 检查静态关键词
  4150. foreach ($staticKeywords as $keyword) {
  4151. if (strpos($text, $keyword) !== false) {
  4152. $score -= 1;
  4153. break;
  4154. }
  4155. }
  4156. // 检查复杂场景关键词
  4157. foreach ($complexSceneKeywords as $keyword) {
  4158. if (strpos($text, $keyword) !== false) {
  4159. $score += 1;
  4160. break;
  4161. }
  4162. }
  4163. // 检查情感关键词
  4164. foreach ($emotionKeywords as $keyword) {
  4165. if (strpos($text, $keyword) !== false) {
  4166. $score += 1;
  4167. break;
  4168. }
  4169. }
  4170. // 检查时间相关词汇
  4171. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4172. $score += 1;
  4173. }
  4174. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4175. $score -= 1;
  4176. }
  4177. // 检查转场词汇
  4178. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4179. $score += 1;
  4180. }
  4181. // 检查环境描述(复杂环境需要更多时间)
  4182. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4183. $score += 1;
  4184. }
  4185. // 检查对话内容(对话需要更多时间)
  4186. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4187. $score += 1;
  4188. }
  4189. // 限制调整范围
  4190. return max(-1, min(4, $score));
  4191. }
  4192. /**
  4193. * 创建完整视频合成任务
  4194. *
  4195. * @param array $data
  4196. * @return array
  4197. */
  4198. public function createCompleteVideoTask($data)
  4199. {
  4200. $animeId = getProp($data, 'anime_id');
  4201. $episodeId = getProp($data, 'episode_id');
  4202. // 验证参数
  4203. if (!$animeId || !$episodeId) {
  4204. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4205. }
  4206. // 检查是否已存在处理中的任务
  4207. $existingTask = DB::table('mp_complete_video_tasks')
  4208. ->where('anime_id', $animeId)
  4209. ->where('episode_id', $episodeId)
  4210. ->whereIn('generate_status', ['执行中'])
  4211. ->first();
  4212. if ($existingTask) {
  4213. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4214. }
  4215. // 获取全能模式状态
  4216. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4217. if ((int)$ace_mode === 1) {
  4218. // 获取所有片段的配音视频,按 act_number 排序
  4219. $segments = DB::table('mp_episode_segments')
  4220. ->where('anime_id', $animeId)
  4221. ->where('episode_id', $episodeId)
  4222. ->orderBy('segment_number')
  4223. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4224. ->get();
  4225. // 检查是否所有片段都有视频
  4226. $missingVideos = $segments->filter(function($segment) {
  4227. return empty($segment->video_url);
  4228. });
  4229. if ($missingVideos->isNotEmpty()) {
  4230. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4231. }
  4232. }else {
  4233. // 获取所有分镜的配音视频,按 segment_number 排序
  4234. $segments = DB::table('mp_episode_segments')
  4235. ->where('anime_id', $animeId)
  4236. ->where('episode_id', $episodeId)
  4237. ->orderBy('segment_number')
  4238. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4239. ->get();
  4240. // 检查是否所有分镜都有配音和视频
  4241. $missingVideos = $segments->filter(function($segment) {
  4242. return empty($segment->audio_url) || empty($segment->video_url);
  4243. });
  4244. if ($missingVideos->isNotEmpty()) {
  4245. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4246. }
  4247. }
  4248. if ($segments->isEmpty()) {
  4249. Utils::throwError('20003:未找到该剧集的分镜数据');
  4250. }
  4251. // 获取当前完整视频url
  4252. $completeVideoUrl = DB::table('mp_anime_episodes')
  4253. ->where('anime_id', $animeId)
  4254. ->where('id', $episodeId)
  4255. ->value('complete_video_url');
  4256. // 构建 generate_json
  4257. $generateJson = [];
  4258. $sequence = 1;
  4259. foreach ($segments as $segment) {
  4260. if ((int)$ace_mode === 1) {
  4261. $generateJson[] = [
  4262. 'sequence' => $sequence++,
  4263. 'video_url' => $segment->video_url,
  4264. 'video_time_point_start' => $segment->video_time_point_start,
  4265. 'video_time_point_end' => $segment->video_time_point_end
  4266. ];
  4267. }else {
  4268. $generateJson[] = [
  4269. 'sequence' => $sequence++,
  4270. 'video_url' => $segment->video_url,
  4271. 'audio_url' => $segment->audio_url,
  4272. 'video_time_point_start' => $segment->video_time_point_start,
  4273. 'video_time_point_end' => $segment->video_time_point_end
  4274. ];
  4275. }
  4276. }
  4277. // 创建任务
  4278. $now = date('Y-m-d H:i:s');
  4279. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4280. 'anime_id' => $animeId,
  4281. 'episode_id' => $episodeId,
  4282. 'generate_json' => json_encode($generateJson, 256),
  4283. 'generate_status' => '执行中',
  4284. 'complete_video_url' => '',
  4285. 'created_at' => $now,
  4286. 'updated_at' => $now
  4287. ]);
  4288. if (!$taskId) {
  4289. Utils::throwError('20003:创建任务失败');
  4290. }
  4291. // 更新剧集表的任务ID和状态
  4292. $boolen = DB::table('mp_anime_episodes')
  4293. ->where('anime_id', $animeId)
  4294. ->where('id', $episodeId)
  4295. ->update([
  4296. 'complete_video_task_id' => $taskId,
  4297. 'complete_video_task_status' => '执行中',
  4298. 'updated_at' => $now
  4299. ]);
  4300. if (!$boolen) {
  4301. Utils::throwError('20003:更新剧集表失败');
  4302. }
  4303. dLog('anime')->info('创建完整视频合成任务', [
  4304. 'task_id' => $taskId,
  4305. 'anime_id' => $animeId,
  4306. 'episode_id' => $episodeId,
  4307. 'segment_count' => count($generateJson)
  4308. ]);
  4309. // 请求远程服务器执行生成
  4310. $client = new Client(['timeout' => 600, 'verify' => false]);
  4311. try {
  4312. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4313. $response = $result->getBody()->getContents();
  4314. $response_arr = json_decode($response, true);
  4315. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4316. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4317. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4318. // // 更新任务状态为失败
  4319. // DB::table('mp_complete_video_tasks')
  4320. // ->where('id', $taskId)
  4321. // ->update([
  4322. // 'generate_status' => '执行失败',
  4323. // 'error_message' => $error_msg,
  4324. // 'updated_at' => date('Y-m-d H:i:s')
  4325. // ]);
  4326. // // 同步更新剧集表状态
  4327. // DB::table('mp_anime_episodes')
  4328. // ->where('complete_video_task_id', $taskId)
  4329. // ->update([
  4330. // 'complete_video_task_status' => '执行失败',
  4331. // 'updated_at' => date('Y-m-d H:i:s')
  4332. // ]);
  4333. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4334. }
  4335. } catch (\Exception $e) {
  4336. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4337. // 更新任务状态为失败
  4338. DB::table('mp_complete_video_tasks')
  4339. ->where('id', $taskId)
  4340. ->update([
  4341. 'generate_status' => '执行失败',
  4342. 'error_message' => $e->getMessage(),
  4343. 'updated_at' => date('Y-m-d H:i:s')
  4344. ]);
  4345. // 同步更新剧集表状态
  4346. DB::table('mp_anime_episodes')
  4347. ->where('complete_video_task_id', $taskId)
  4348. ->update([
  4349. 'complete_video_task_status' => '执行失败',
  4350. 'updated_at' => date('Y-m-d H:i:s')
  4351. ]);
  4352. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4353. }
  4354. // 开始轮询任务状态
  4355. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4356. $pollInterval = 5; // 每5秒轮询一次
  4357. $attempt = 0;
  4358. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4359. while ($attempt < $maxAttempts) {
  4360. sleep($pollInterval);
  4361. $attempt++;
  4362. // 查询任务状态
  4363. $task = DB::table('mp_complete_video_tasks')
  4364. ->where('id', $taskId)
  4365. ->first();
  4366. if (!$task) {
  4367. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4368. Utils::throwError('20003:任务不存在');
  4369. }
  4370. dLog('anime')->info('轮询任务状态', [
  4371. 'task_id' => $taskId,
  4372. 'attempt' => $attempt,
  4373. 'status' => $task->generate_status
  4374. ]);
  4375. // 检查任务是否完成
  4376. if ($task->generate_status === '执行成功') {
  4377. // 同步更新剧集表状态
  4378. $boolen3 = DB::table('mp_anime_episodes')
  4379. ->where('anime_id', $animeId)
  4380. ->where('id', $episodeId)
  4381. ->update([
  4382. 'complete_video_url' => $task->complete_video_url,
  4383. 'complete_video_task_status' => '执行成功',
  4384. 'updated_at' => date('Y-m-d H:i:s')
  4385. ]);
  4386. dLog('anime')->info('视频合成任务完成', [
  4387. 'task_id' => $taskId,
  4388. 'video_url' => $task->complete_video_url,
  4389. 'attempts' => $attempt
  4390. ]);
  4391. // 如果更新成功则远程删除之前的文件
  4392. if ($boolen3 && $completeVideoUrl) {
  4393. $encode_url = urlencode($completeVideoUrl);
  4394. $client = new Client(['timeout' => 300, 'verify' => false]);
  4395. // 根据ID通过API通知合成音频
  4396. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4397. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4398. $response = $result->getBody()->getContents();
  4399. $response_arr = json_decode($response, true);
  4400. Log::info('火山删除音频返回: '.$response);
  4401. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4402. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4403. Log::info('火山删除音频失败: '.$error_msg);
  4404. // Utils::throwError('20003:火山删除音频失败');
  4405. }
  4406. }
  4407. return [
  4408. 'task_id' => $taskId,
  4409. 'anime_id' => $animeId,
  4410. 'episode_id' => $episodeId,
  4411. 'segment_count' => count($generateJson),
  4412. 'generate_status' => '执行成功',
  4413. 'complete_video_url' => $task->complete_video_url,
  4414. ];
  4415. }
  4416. // 检查任务是否失败
  4417. if ($task->generate_status === '执行失败') {
  4418. // 同步更新剧集表状态
  4419. DB::table('mp_anime_episodes')
  4420. ->where('anime_id', $animeId)
  4421. ->where('id', $episodeId)
  4422. ->update([
  4423. 'complete_video_task_status' => '执行失败',
  4424. 'updated_at' => date('Y-m-d H:i:s')
  4425. ]);
  4426. $errorMessage = $task->error_message ?? '未知错误';
  4427. dLog('anime')->error('视频合成任务失败', [
  4428. 'task_id' => $taskId,
  4429. 'error' => $errorMessage,
  4430. 'attempts' => $attempt
  4431. ]);
  4432. return [
  4433. 'task_id' => $taskId,
  4434. 'anime_id' => $animeId,
  4435. 'episode_id' => $episodeId,
  4436. 'segment_count' => count($generateJson),
  4437. 'generate_status' => '执行失败',
  4438. 'error_message' => $errorMessage
  4439. ];
  4440. }
  4441. }
  4442. // 超时处理
  4443. dLog('anime')->warning('视频合成任务超时', [
  4444. 'task_id' => $taskId,
  4445. 'max_attempts' => $maxAttempts,
  4446. 'timeout_seconds' => $maxAttempts * $pollInterval
  4447. ]);
  4448. // 更新任务状态为超时
  4449. DB::table('mp_complete_video_tasks')
  4450. ->where('id', $taskId)
  4451. ->update([
  4452. 'generate_status' => '超时',
  4453. 'error_message' => '任务执行超时(5分钟)',
  4454. 'updated_at' => date('Y-m-d H:i:s')
  4455. ]);
  4456. return [
  4457. 'task_id' => $taskId,
  4458. 'anime_id' => $animeId,
  4459. 'episode_id' => $episodeId,
  4460. 'segment_count' => count($generateJson),
  4461. 'generate_status' => '超时',
  4462. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4463. ];
  4464. }
  4465. public function generateImg($data) {
  4466. $prompt = getProp($data, 'prompt');
  4467. $episode_id = getProp($data, 'episode_id');
  4468. $ref_img_urls = getProp($data, 'ref_img_urls');
  4469. $ratio = getProp($data, 'ratio', '9:16');
  4470. $resolution = getProp($data, 'resolution', '2k');
  4471. // 定义分辨率和宽高比对应的尺寸映射表
  4472. $sizeMap = [
  4473. '2k' => [
  4474. '1:1' => ['width' => 2048, 'height' => 2048],
  4475. '4:3' => ['width' => 2304, 'height' => 1728],
  4476. '3:4' => ['width' => 1728, 'height' => 2304],
  4477. '16:9' => ['width' => 2848, 'height' => 1600],
  4478. '9:16' => ['width' => 1600, 'height' => 2848],
  4479. '3:2' => ['width' => 2496, 'height' => 1664],
  4480. '2:3' => ['width' => 1664, 'height' => 2496],
  4481. '21:9' => ['width' => 3136, 'height' => 1344],
  4482. ],
  4483. '3k' => [
  4484. '1:1' => ['width' => 3072, 'height' => 3072],
  4485. '4:3' => ['width' => 3456, 'height' => 2592],
  4486. '3:4' => ['width' => 2592, 'height' => 3456],
  4487. '16:9' => ['width' => 4096, 'height' => 2304],
  4488. '9:16' => ['width' => 2304, 'height' => 4096],
  4489. '2:3' => ['width' => 2496, 'height' => 3744],
  4490. '3:2' => ['width' => 3744, 'height' => 2496],
  4491. '21:9' => ['width' => 4704, 'height' => 2016],
  4492. ],
  4493. '4k' => [
  4494. '1:1' => ['width' => 4096, 'height' => 4096],
  4495. '3:4' => ['width' => 3520, 'height' => 4704],
  4496. '4:3' => ['width' => 4704, 'height' => 3520],
  4497. '16:9' => ['width' => 5504, 'height' => 3040],
  4498. '9:16' => ['width' => 3040, 'height' => 5504],
  4499. '2:3' => ['width' => 3328, 'height' => 4992],
  4500. '3:2' => ['width' => 4992, 'height' => 3328],
  4501. '21:9' => ['width' => 6240, 'height' => 2656],
  4502. ],
  4503. ];
  4504. // 参数验证
  4505. $resolution = strtolower($resolution);
  4506. if (!isset($sizeMap[$resolution])) {
  4507. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4508. }
  4509. if (!isset($sizeMap[$resolution][$ratio])) {
  4510. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4511. }
  4512. // 根据 ratio 和 resolution 确定宽高
  4513. $width = $sizeMap[$resolution][$ratio]['width'];
  4514. $height = $sizeMap[$resolution][$ratio]['height'];
  4515. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4516. if (is_json($ref_img_urls)) {
  4517. $ref_img_urls = json_decode($ref_img_urls, true);
  4518. }else {
  4519. $ref_img_urls = explode(',', $ref_img_urls);
  4520. }
  4521. }
  4522. // 处理图片模型
  4523. $model = getProp($data, 'model');
  4524. if (!$model) {
  4525. // 用户没有输入,从episode表获取
  4526. if ($episode_id) {
  4527. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4528. $model = getProp($episode, 'image_model');
  4529. }
  4530. if (!$model) {
  4531. // episode表也没有,使用默认值
  4532. $model = 'doubao-seedream-5-0-lite-260128';
  4533. }
  4534. }
  4535. // 验证模型是否在可用模型表中
  4536. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4537. // $model = 'doubao-seedream-5-0-lite-260128';
  4538. Utils::throwError('20003:该模型已不可用,请更换!');
  4539. }
  4540. // 保存到episode表
  4541. if ($episode_id) {
  4542. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4543. 'image_model' => $model,
  4544. 'updated_at' => date('Y-m-d H:i:s')
  4545. ]);
  4546. }
  4547. // 参数验证
  4548. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4549. try {
  4550. // 创建图片生成任务
  4551. $params = [
  4552. 'prompt' => $prompt,
  4553. 'model' => $model,
  4554. 'ref_img_urls' => '',
  4555. 'width' => $width,
  4556. 'height' => $height
  4557. ];
  4558. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4559. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4560. $task_id = $task->id;
  4561. if (!$task_id) {
  4562. Utils::throwError('20003:创建图片生成任务失败');
  4563. }
  4564. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4565. $model = getProp($task, 'model');
  4566. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4567. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4568. $isSyncModel = $isVolcModel || $isGptModel;
  4569. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4570. $start_time = time();
  4571. $timeout = 300; // 5分钟
  4572. $img_url = '';
  4573. while (time() - $start_time < $timeout) {
  4574. sleep(3);
  4575. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4576. if ($isSyncModel) {
  4577. // 刷新任务状态
  4578. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4579. if ($task->status === 'success' && $task->result_url) {
  4580. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4581. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4582. break;
  4583. } elseif ($task->status === 'failed') {
  4584. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4585. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4586. }
  4587. // // 如果还在处理中,提示用户稍后查看
  4588. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4589. }else {
  4590. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4591. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4592. if ($statusInfo['status'] === 'success') {
  4593. $task->updateStatus('success', [
  4594. 'result_url' => $statusInfo['result_url'],
  4595. 'result_json' => $statusInfo['result_json'] ?? []
  4596. ]);
  4597. $img_url = $statusInfo['result_url'][0];
  4598. break;
  4599. } elseif ($statusInfo['status'] === 'failed') {
  4600. $task->updateStatus('failed', [
  4601. 'error_message' => $statusInfo['error_message'],
  4602. 'result_json' => $statusInfo['result_json'] ?? []
  4603. ]);
  4604. dLog('anime')->error('图片生成失败,', [
  4605. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4606. ]);
  4607. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4608. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4609. }
  4610. }
  4611. }
  4612. if (empty($img_url)) {
  4613. Utils::throwError('20003:图片生成超时,请稍后重试');
  4614. }
  4615. return $img_url;
  4616. } catch (\Exception $e) {
  4617. dLog('anime')->error('更新角色或场景失败', [
  4618. 'error' => $e->getMessage()
  4619. ]);
  4620. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4621. Utils::throwError('20003:' . $e->getMessage());
  4622. }
  4623. }
  4624. /**
  4625. * 使用文生文模型解析分镜内容
  4626. */
  4627. private function parseSegmentContentWithAI($segment_content) {
  4628. try {
  4629. // 使用DeepSeek服务的公开方法解析分镜内容
  4630. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4631. } catch (\Exception $e) {
  4632. // 如果AI解析失败,记录日志并返回原内容
  4633. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4634. return $segment_content;
  4635. }
  4636. }
  4637. /**
  4638. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4639. *
  4640. * @param int $episode_id 分集ID
  4641. * @param int $anime_id 动漫ID
  4642. * @param array $roles 分集角色数组(引用传递)
  4643. * @param array $scenes 分集场景数组(引用传递)
  4644. * @param array $episode 分集数据
  4645. */
  4646. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4647. // 获取全局动漫的角色和场景数据
  4648. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4649. if (!$anime) return;
  4650. $art_style_type = getProp($anime, 'art_style_type');
  4651. $character_prefix = '';
  4652. $scene_prefix = '';
  4653. if ($art_style_type) {
  4654. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4655. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4656. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4657. }
  4658. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4659. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4660. $roles_updated = false;
  4661. $scenes_updated = false;
  4662. // 处理角色
  4663. foreach ($roles as &$role) {
  4664. $role_name = getProp($role, 'role');
  4665. $role_description = getProp($role, 'description');
  4666. $role_pic_prompt = getProp($role, 'pic_prompt');
  4667. $role_url = getProp($role, 'url');
  4668. $role_task_id = getProp($role, 'task_id');
  4669. // 如果已有URL或已有任务ID,跳过
  4670. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4671. continue;
  4672. }
  4673. $url_inherited = false;
  4674. // 尝试从全局数据中继承
  4675. foreach ($global_roles as $global_role) {
  4676. $global_role_name = getProp($global_role, 'role');
  4677. $global_role_description = getProp($global_role, 'description');
  4678. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4679. $global_role_url = getProp($global_role, 'url');
  4680. $global_role_task_id = getProp($global_role, 'task_id');
  4681. $global_role_task_status = getProp($global_role, 'task_status');
  4682. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4683. if ($role_name === $global_role_name
  4684. && $role_description === $global_role_description
  4685. && $role_pic_prompt === $global_role_pic_prompt
  4686. && !empty($global_role_url)) {
  4687. // 继承 task_id、task_status 和 url
  4688. $role['task_id'] = $global_role_task_id;
  4689. $role['task_status'] = $global_role_task_status;
  4690. $role['url'] = $global_role_url;
  4691. $roles_updated = true;
  4692. $url_inherited = true;
  4693. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4694. break;
  4695. }
  4696. }
  4697. // 如果无法继承且没有任务ID,创建新任务
  4698. if (!$url_inherited && empty($role_task_id)) {
  4699. try {
  4700. $art_style = getProp($episode, 'art_style');
  4701. // 优先使用 pic_prompt,如果没有则使用 description
  4702. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4703. // if ($art_style) {
  4704. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4705. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4706. // }
  4707. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4708. $params = [
  4709. 'prompt' => $description,
  4710. 'ref_img_urls' => []
  4711. ];
  4712. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4713. $task_id = $task->id;
  4714. if ($task_id) {
  4715. $role['task_id'] = $task_id;
  4716. $role['task_status'] = 'processing';
  4717. $roles_updated = true;
  4718. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4719. }
  4720. } catch (\Exception $e) {
  4721. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4722. }
  4723. }
  4724. }
  4725. // 处理场景
  4726. foreach ($scenes as &$scene) {
  4727. $scene_name = getProp($scene, 'scene');
  4728. $scene_description = getProp($scene, 'description');
  4729. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4730. $scene_url = getProp($scene, 'url');
  4731. $scene_task_id = getProp($scene, 'task_id');
  4732. // 如果已有URL或已有任务ID,跳过
  4733. if (!empty($scene_url) || !empty($scene_task_id)) {
  4734. continue;
  4735. }
  4736. $url_inherited = false;
  4737. // 尝试从全局数据中继承
  4738. foreach ($global_scenes as $global_scene) {
  4739. $global_scene_name = getProp($global_scene, 'scene');
  4740. $global_scene_description = getProp($global_scene, 'description');
  4741. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  4742. $global_scene_url = getProp($global_scene, 'url');
  4743. $global_scene_task_id = getProp($global_scene, 'task_id');
  4744. $global_scene_task_status = getProp($global_scene, 'task_status');
  4745. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  4746. if ($scene_name === $global_scene_name
  4747. && $scene_description === $global_scene_description
  4748. && $scene_pic_prompt === $global_scene_pic_prompt
  4749. && !empty($global_scene_url)) {
  4750. // 继承 task_id、task_status 和 url
  4751. $scene['task_id'] = $global_scene_task_id;
  4752. $scene['task_status'] = $global_scene_task_status;
  4753. $scene['url'] = $global_scene_url;
  4754. $scenes_updated = true;
  4755. $url_inherited = true;
  4756. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  4757. break;
  4758. }
  4759. }
  4760. // 如果无法继承且没有任务ID,创建新任务
  4761. if (!$url_inherited && empty($scene_task_id)) {
  4762. try {
  4763. $art_style = getProp($episode, 'art_style');
  4764. // 优先使用 pic_prompt,如果没有则使用 description
  4765. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  4766. // if ($art_style) {
  4767. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4768. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4769. // }
  4770. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4771. $params = [
  4772. 'prompt' => $description,
  4773. 'ref_img_urls' => []
  4774. ];
  4775. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4776. $task_id = $task->id;
  4777. if ($task_id) {
  4778. $scene['task_id'] = $task_id;
  4779. $scene['task_status'] = 'processing';
  4780. $scenes_updated = true;
  4781. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  4782. }
  4783. } catch (\Exception $e) {
  4784. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  4785. }
  4786. }
  4787. }
  4788. // 如果有更新,保存到数据库
  4789. if ($roles_updated || $scenes_updated) {
  4790. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  4791. if ($roles_updated) {
  4792. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  4793. }
  4794. if ($scenes_updated) {
  4795. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  4796. }
  4797. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  4798. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  4799. }
  4800. }
  4801. /**
  4802. * 根据图片URL使用AI反推图片提示词
  4803. *
  4804. * @param string $img_url 图片URL
  4805. * @return string 反推的提示词
  4806. */
  4807. private function generateImagePromptFromUrl($img_url) {
  4808. try {
  4809. // 获取默认模型
  4810. $model = 'doubao-seed-2-0-mini-260215';
  4811. // 构建messages参数
  4812. $messages = [
  4813. [
  4814. 'role' => 'user',
  4815. 'content' => [
  4816. [
  4817. 'type' => 'text',
  4818. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  4819. ],
  4820. [
  4821. 'type' => 'image_url',
  4822. 'image_url' => [
  4823. 'url' => $img_url
  4824. ]
  4825. ]
  4826. ]
  4827. ]
  4828. ];
  4829. // 构建请求参数
  4830. $params = [
  4831. 'model' => $model,
  4832. 'messages' => $messages,
  4833. 'stream' => false,
  4834. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  4835. ];
  4836. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  4837. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  4838. // 返回生成的内容
  4839. return getProp($result, 'fullContent', '图片描述生成失败');
  4840. } catch (\Exception $e) {
  4841. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  4842. 'img_url' => $img_url
  4843. ]);
  4844. logDB('anime', 'error', 'AI反推图片提示词失败', [
  4845. 'error' => $e->getMessage(),
  4846. 'img_url' => $img_url
  4847. ]);
  4848. return '图片描述生成失败: ' . $e->getMessage();
  4849. }
  4850. }
  4851. /**
  4852. * 音频试听接口
  4853. * 创建音频任务并轮询获取结果
  4854. *
  4855. * @param array $data 参数数组
  4856. * @return array 返回音频URL或错误信息
  4857. */
  4858. public function previewAudio($data) {
  4859. $dialogue = getProp($data, 'dialogue');
  4860. // 必填参数验证
  4861. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  4862. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  4863. $voice_type = getProp($data, 'voice_type');
  4864. $voice_name = getProp($data, 'voice_name');
  4865. $voice_actor = getProp($data, 'voice_actor');
  4866. $emotion_type = getProp($data, 'emotion_type');
  4867. $gender = getProp($data, 'gender', 0);
  4868. $emotion = getProp($data, 'emotion');
  4869. $speed_ratio = getProp($data, 'speed_ratio', 0);
  4870. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  4871. $emotion_scale = getProp($data, 'emotion_scale', 0);
  4872. $pitch = getProp($data, 'pitch', 0);
  4873. try {
  4874. $now = date('Y-m-d H:i:s');
  4875. // 构建生成参数
  4876. $generate_json = json_encode([
  4877. 'text' => $dialogue,
  4878. 'role' => $voice_actor,
  4879. 'voice_type' => $voice_type,
  4880. 'voice_name' => $voice_name,
  4881. 'emotion' => $emotion,
  4882. 'emotion_type' => $emotion_type,
  4883. 'gender' => $gender,
  4884. 'speed_ratio' => $speed_ratio,
  4885. 'loudness_ratio' => $loudness_ratio,
  4886. 'emotion_scale' => $emotion_scale,
  4887. 'pitch' => $pitch,
  4888. ], 256);
  4889. // 请求远程服务器执行生成
  4890. $client = new Client(['timeout' => 600, 'verify' => false]);
  4891. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  4892. $response = $result->getBody()->getContents();
  4893. $response_arr = json_decode($response, true);
  4894. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4895. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4896. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  4897. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  4898. }
  4899. $arr = $response_arr['data'];
  4900. $subtitle_info = $arr['subtitle_info'];
  4901. $audio_duration = json_decode($subtitle_info, true)['duration'];
  4902. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  4903. return [
  4904. 'audio_url' => $arr['url'],
  4905. 'subtitle_info' => $subtitle_info,
  4906. 'audio_duration' => round($audio_duration, 2)
  4907. ];
  4908. } catch (\Exception $e) {
  4909. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  4910. Utils::throwError('20003:' . $e->getMessage());
  4911. }
  4912. }
  4913. /**
  4914. * 获取角色库列表(支持文件夹递归查询)
  4915. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)
  4916. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  4917. */
  4918. public function globalProducts($data) {
  4919. $uid = Site::getUid();
  4920. $cpid = Site::getCpid();
  4921. $id = getProp($data, 'id', 0);
  4922. $parent_id = getProp($data, 'parent_id', 0);
  4923. $product_name = getProp($data, 'product_name');
  4924. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  4925. if (!$product) {
  4926. Utils::throwError('20003:请选择产品类型');
  4927. }
  4928. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  4929. if ($id || $product_name) {
  4930. $query = DB::table('mp_products')
  4931. ->where('cpid', $cpid)
  4932. ->where('user_id', $uid)
  4933. ->where('is_deleted', 0);
  4934. // 如果指定了 id,按 id 精确查询
  4935. if ($id) {
  4936. $query->where('id', $id);
  4937. }
  4938. // 如果指定了 product_name,按名称模糊查询
  4939. if ($product_name) {
  4940. $query->where('product_name', 'like', "%{$product_name}%");
  4941. }
  4942. // 如果指定了 product,添加筛选条件
  4943. if ($product) {
  4944. $query->where('product', $product);
  4945. }
  4946. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4947. ->orderByRaw('sort_order DESC, created_at DESC')
  4948. ->get()
  4949. ->map(function($value) {
  4950. $value = (array)$value;
  4951. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  4952. $value['type'] = (int)$value['type'];
  4953. $value['parent_id'] = (int)$value['parent_id'];
  4954. $value['level'] = (int)$value['level'];
  4955. $value['product'] = (int)($value['product'] ?? 1);
  4956. $value['versions'] = json_decode($value['versions'], true) ?: [];
  4957. return $value;
  4958. })
  4959. ->toArray();
  4960. return $result;
  4961. }
  4962. // 递归获取所有子目录和角色
  4963. return $this->getChildrenRecursive($cpid, $parent_id, $product, $uid);
  4964. }
  4965. /**
  4966. * 递归获取指定目录下的所有子目录和角色
  4967. * @param int $cpid 公司ID
  4968. * @param int $parent_id 父目录ID
  4969. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  4970. * @param int $uid 用户ID
  4971. * @return array
  4972. */
  4973. private function getChildrenRecursive($cpid, $parent_id, $product = null, $uid = null) {
  4974. // 查询当前层级的所有项(文件夹和角色)
  4975. $query = DB::table('mp_products')
  4976. ->where('cpid', $cpid)
  4977. ->where('is_deleted', 0)
  4978. ->where('parent_id', $parent_id);
  4979. // 添加用户ID验证
  4980. if ($uid) {
  4981. $query->where('user_id', $uid);
  4982. }
  4983. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  4984. if ($product) {
  4985. $query->where('product', $product);
  4986. }
  4987. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4988. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  4989. ->get();
  4990. $result = [];
  4991. foreach ($items as $item) {
  4992. $itemArray = [
  4993. 'id' => $item->id,
  4994. 'type' => (int)$item->type,
  4995. 'parent_id' => (int)$item->parent_id,
  4996. 'level' => (int)$item->level,
  4997. 'product_name' => $item->product_name,
  4998. 'url' => $item->url,
  4999. 'pic_prompt' => $item->pic_prompt ?? '',
  5000. 'three_view_image_url' => $item->three_view_image_url,
  5001. 'product' => (int)($item->product ?? 1),
  5002. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5003. ];
  5004. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5005. // 如果是文件夹,递归获取其子项
  5006. if ($item->type == 2) {
  5007. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $uid);
  5008. if (!empty($children)) {
  5009. $itemArray['children'] = $children;
  5010. }
  5011. }
  5012. $result[] = $itemArray;
  5013. }
  5014. return $result;
  5015. }
  5016. /**
  5017. * 创建文件夹
  5018. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5019. * @return int 返回新建文件夹ID
  5020. */
  5021. public function createFolder($data) {
  5022. $uid = Site::getUid();
  5023. $cpid = Site::getCpid();
  5024. $parent_id = getProp($data, 'parent_id', 0);
  5025. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5026. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5027. $product = getProp($data, 'product');
  5028. if (!in_array($product, [1, 2, 3])) {
  5029. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5030. }
  5031. // 验证父文件夹
  5032. $parent_level = 0;
  5033. if ($parent_id > 0) {
  5034. $parent = DB::table('mp_products')
  5035. ->where('id', $parent_id)
  5036. ->where('type', 2)
  5037. ->where('is_deleted', 0)
  5038. ->first();
  5039. if (!$parent) {
  5040. Utils::throwError('20003:父文件夹不存在');
  5041. }
  5042. // 检查父文件夹的 product 类型是否一致
  5043. if ($parent->product != $product) {
  5044. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5045. }
  5046. $parent_level = $parent->level;
  5047. // 检查层级限制(最多3层)
  5048. if ($parent_level >= 3) {
  5049. Utils::throwError('20003:文件夹层级不能超过3层');
  5050. }
  5051. }
  5052. // 检查当前目录下是否已存在空白文件夹
  5053. $empty_folder_exists = DB::table('mp_products')
  5054. ->where('parent_id', $parent_id)
  5055. ->where('type', 2)
  5056. ->where('product', $product)
  5057. ->where('product_name', '新建文件夹')
  5058. ->where('is_deleted', 0)
  5059. ->exists();
  5060. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5061. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5062. }
  5063. // 创建文件夹
  5064. $folder_id = DB::table('mp_products')->insertGetId([
  5065. 'user_id' => $uid,
  5066. 'cpid' => $cpid,
  5067. 'type' => 2,
  5068. 'parent_id' => $parent_id,
  5069. 'level' => $parent_level + 1,
  5070. 'product_name' => $folder_name,
  5071. 'product' => $product,
  5072. 'sort_order' => time(), // 使用时间戳作为排序权重
  5073. 'is_deleted' => 0,
  5074. 'created_at' => date('Y-m-d H:i:s'),
  5075. 'updated_at' => date('Y-m-d H:i:s')
  5076. ]);
  5077. return [
  5078. 'id' => $folder_id,
  5079. 'type' => 2,
  5080. 'parent_id' => $parent_id,
  5081. 'level' => $parent_level + 1,
  5082. 'product_name' => $folder_name,
  5083. 'product' => $product,
  5084. ];
  5085. }
  5086. /**
  5087. * 重命名文件夹或角色
  5088. * @param array $data 包含 id、product_name(新名称)
  5089. * @return bool
  5090. */
  5091. public function renameFolder($data) {
  5092. $uid = Site::getUid();
  5093. $cpid = Site::getCpid();
  5094. $id = getProp($data, 'id');
  5095. $new_name = getProp($data, 'product_name');
  5096. if (!$id || !$new_name) {
  5097. Utils::throwError('20003:参数不完整');
  5098. }
  5099. // 检查是否存在
  5100. $item = DB::table('mp_products')
  5101. ->where('id', $id)
  5102. ->where('cpid', $cpid)
  5103. ->where('is_deleted', 0)
  5104. ->first();
  5105. if (!$item) {
  5106. Utils::throwError('20003:项目不存在');
  5107. }
  5108. return DB::table('mp_products')
  5109. ->where('id', $id)
  5110. ->where('cpid', $cpid)
  5111. ->update([
  5112. 'product_name' => $new_name,
  5113. 'updated_at' => date('Y-m-d H:i:s')
  5114. ]);
  5115. }
  5116. /**
  5117. * 移动角色或文件夹到指定文件夹
  5118. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5119. * @return bool
  5120. */
  5121. public function moveProductOrFolder($data) {
  5122. $cpid = Site::getCpid();
  5123. $id = getProp($data, 'id');
  5124. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5125. if (!$id) {
  5126. Utils::throwError('20003:请选择要移动的项目');
  5127. }
  5128. // 检查要移动的项目
  5129. $item = DB::table('mp_products')
  5130. ->where('id', $id)
  5131. ->where('cpid', $cpid)
  5132. ->where('is_deleted', 0)
  5133. ->first();
  5134. if (!$item) {
  5135. Utils::throwError('20003:项目不存在');
  5136. }
  5137. // 验证目标文件夹
  5138. $target_level = 0;
  5139. $target_product = $item->product; // 默认使用当前项目的 product
  5140. if ($target_parent_id > 0) {
  5141. $target_parent = DB::table('mp_products')
  5142. ->where('id', $target_parent_id)
  5143. ->where('cpid', $cpid)
  5144. ->where('type', 2)
  5145. ->where('is_deleted', 0)
  5146. ->first();
  5147. if (!$target_parent) {
  5148. Utils::throwError('20003:目标文件夹不存在');
  5149. }
  5150. // 检查 product 类型是否一致
  5151. if ($target_parent->product != $item->product) {
  5152. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5153. }
  5154. $target_level = $target_parent->level;
  5155. $target_product = $target_parent->product;
  5156. // 如果移动的是文件夹,需要检查层级
  5157. if ($item->type == 2) {
  5158. // 计算移动后的最大层级
  5159. $max_child_level = $this->getMaxChildLevel($id);
  5160. $depth = $max_child_level - $item->level;
  5161. if ($target_level + 1 + $depth > 3) {
  5162. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5163. }
  5164. // 不能移动到自己或自己的子文件夹下
  5165. if ($this->isDescendant($target_parent_id, $id)) {
  5166. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5167. }
  5168. }
  5169. }
  5170. // 更新父文件夹和层级
  5171. $new_level = $target_level + 1;
  5172. DB::table('mp_products')
  5173. ->where('id', $id)
  5174. ->update([
  5175. 'parent_id' => $target_parent_id,
  5176. 'level' => $new_level,
  5177. 'updated_at' => date('Y-m-d H:i:s')
  5178. ]);
  5179. // 如果是文件夹,需要递归更新所有子项的层级
  5180. if ($item->type == 2) {
  5181. $this->updateChildrenLevel($id, $new_level);
  5182. }
  5183. return true;
  5184. }
  5185. /**
  5186. * 获取文件夹下最大子层级
  5187. * @param int $folder_id
  5188. * @return int
  5189. */
  5190. private function getMaxChildLevel($folder_id) {
  5191. $max_level = DB::table('mp_products')
  5192. ->where('parent_id', $folder_id)
  5193. ->where('is_deleted', 0)
  5194. ->max('level');
  5195. if (!$max_level) {
  5196. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5197. }
  5198. // 递归查找子文件夹
  5199. $children = DB::table('mp_products')
  5200. ->where('parent_id', $folder_id)
  5201. ->where('type', 2)
  5202. ->where('is_deleted', 0)
  5203. ->pluck('id');
  5204. foreach ($children as $child_id) {
  5205. $child_max = $this->getMaxChildLevel($child_id);
  5206. if ($child_max > $max_level) {
  5207. $max_level = $child_max;
  5208. }
  5209. }
  5210. return $max_level;
  5211. }
  5212. /**
  5213. * 检查 target_id 是否是 folder_id 的后代
  5214. * @param int $target_id
  5215. * @param int $folder_id
  5216. * @return bool
  5217. */
  5218. private function isDescendant($target_id, $folder_id) {
  5219. if ($target_id == $folder_id) {
  5220. return true;
  5221. }
  5222. $parent = DB::table('mp_products')
  5223. ->where('id', $target_id)
  5224. ->where('is_deleted', 0)
  5225. ->first();
  5226. if (!$parent || $parent->parent_id == 0) {
  5227. return false;
  5228. }
  5229. return $this->isDescendant($parent->parent_id, $folder_id);
  5230. }
  5231. /**
  5232. * 递归更新子项层级
  5233. * @param int $parent_id
  5234. * @param int $parent_level
  5235. */
  5236. private function updateChildrenLevel($parent_id, $parent_level) {
  5237. $children = DB::table('mp_products')
  5238. ->where('parent_id', $parent_id)
  5239. ->where('is_deleted', 0)
  5240. ->get();
  5241. foreach ($children as $child) {
  5242. $new_level = $parent_level + 1;
  5243. DB::table('mp_products')
  5244. ->where('id', $child->id)
  5245. ->update([
  5246. 'level' => $new_level,
  5247. 'updated_at' => date('Y-m-d H:i:s')
  5248. ]);
  5249. // 如果是文件夹,继续递归
  5250. if ($child->type == 2) {
  5251. $this->updateChildrenLevel($child->id, $new_level);
  5252. }
  5253. }
  5254. }
  5255. /**
  5256. * 获取文件夹路径(面包屑导航)
  5257. * @param array $data 包含 folder_id
  5258. * @return array 返回路径数组
  5259. */
  5260. public function getFolderPath($data) {
  5261. $folder_id = getProp($data, 'id', 0);
  5262. if ($folder_id == 0) {
  5263. return [
  5264. ['id' => 0, 'name' => '根目录']
  5265. ];
  5266. }
  5267. $path = [];
  5268. $current_id = $folder_id;
  5269. while ($current_id > 0) {
  5270. $folder = DB::table('mp_products')
  5271. ->where('id', $current_id)
  5272. ->where('type', 2)
  5273. ->where('is_deleted', 0)
  5274. ->first();
  5275. if (!$folder) {
  5276. break;
  5277. }
  5278. array_unshift($path, [
  5279. 'id' => $folder->id,
  5280. 'name' => $folder->product_name
  5281. ]);
  5282. $current_id = $folder->parent_id;
  5283. }
  5284. // 添加根目录
  5285. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5286. return $path;
  5287. }
  5288. public function createProduct($data) {
  5289. $uid = Site::getUid();
  5290. $cpid = Site::getCpid();
  5291. $product_name = trim(getProp($data, 'product_name'));
  5292. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5293. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5294. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5295. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5296. $url = trim(getProp($data, 'url'));
  5297. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5298. $versions = getProp($data, 'versions');
  5299. // 检查是否是正确的图片格式
  5300. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5301. $urlPath = parse_url($url, PHP_URL_PATH);
  5302. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5303. if (!in_array($extension, $allowedExtensions)) {
  5304. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5305. }
  5306. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5307. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5308. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5309. $product = getProp($data, 'product');
  5310. if (!in_array($product, [1, 2, 3])) {
  5311. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5312. }
  5313. // 获取父文件夹ID和层级
  5314. $parent_id = getProp($data, 'parent_id', 0);
  5315. $parent_level = 0;
  5316. if ($parent_id > 0) {
  5317. $parent = DB::table('mp_products')
  5318. ->where('id', $parent_id)
  5319. ->where('cpid', $cpid)
  5320. ->where('type', 2)
  5321. ->where('is_deleted', 0)
  5322. ->first();
  5323. if (!$parent) {
  5324. Utils::throwError('20003:父文件夹不存在');
  5325. }
  5326. $parent_level = $parent->level;
  5327. }
  5328. $id = DB::table('mp_products')->insertGetId([
  5329. 'user_id' => $uid,
  5330. 'cpid' => $cpid,
  5331. 'type' => 1, // 1=角色图片
  5332. 'parent_id' => $parent_id,
  5333. 'level' => $parent_level + 1,
  5334. 'product_name' => $product_name,
  5335. 'url' => $url,
  5336. 'pic_prompt' => $pic_prompt,
  5337. 'product' => $product,
  5338. 'versions' => json_encode($versions, 256),
  5339. 'sort_order' => time(), // 使用时间戳作为排序权重
  5340. 'created_at' => date('Y-m-d H:i:s'),
  5341. 'updated_at' => date('Y-m-d H:i:s')
  5342. ]);
  5343. if (!$id) Utils::throwError('20003:创建失败');
  5344. return [
  5345. 'id' => $id,
  5346. 'type' => 1,
  5347. 'parent_id' => $parent_id,
  5348. 'level' => $parent_level + 1,
  5349. 'product_name' => $product_name,
  5350. 'url' => $url,
  5351. 'pic_prompt' => $pic_prompt,
  5352. 'product' => $product,
  5353. 'versions' => $versions
  5354. ];
  5355. }
  5356. public function editProduct($data) {
  5357. $uid = Site::getUid();
  5358. $cpid = Site::getCpid();
  5359. $id = getProp($data, 'id');
  5360. if (!$id) Utils::throwError('20003:ID不能为空');
  5361. $versions = getProp($data, 'versions');
  5362. // 检查是否存在且属于当前用户
  5363. $role = DB::table('mp_products')
  5364. ->where('id', $id)
  5365. ->where('cpid', $cpid)
  5366. ->where('type', 1)->first();
  5367. if (!$role) Utils::throwError('20003:记录不存在');
  5368. $updateData = [];
  5369. // $needVersionRecord = false; // 是否需要记录版本
  5370. // 名称
  5371. $product_name = trim(getProp($data, 'product_name'));
  5372. if ($product_name) {
  5373. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5374. $updateData['product_name'] = $product_name;
  5375. }
  5376. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5377. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5378. // 图片地址
  5379. $url = trim(getProp($data, 'url'));
  5380. if ($url) {
  5381. // 检查是否是正确的图片格式
  5382. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5383. $urlPath = parse_url($url, PHP_URL_PATH);
  5384. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5385. if (!in_array($extension, $allowedExtensions)) {
  5386. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5387. }
  5388. // // 如果 url 有变更,记录版本
  5389. // if ($url !== $role->url) {
  5390. // $needVersionRecord = true;
  5391. // }
  5392. $updateData['url'] = $url;
  5393. }
  5394. // 提示词
  5395. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5396. if ($pic_prompt) {
  5397. // // 如果 pic_prompt 有变更,记录版本
  5398. // if ($pic_prompt !== $role->pic_prompt) {
  5399. // $needVersionRecord = true;
  5400. // }
  5401. $updateData['pic_prompt'] = $pic_prompt;
  5402. }
  5403. if (empty($updateData)) {
  5404. Utils::throwError('20003:没有需要更新的数据');
  5405. }
  5406. // // 如果需要记录版本,将数据添加到 versions 数组
  5407. // if ($needVersionRecord) {
  5408. // // 获取现有的 versions 数据
  5409. // $versions = json_decode($role->versions, true) ?: [];
  5410. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5411. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5412. // if ($isFirstVersion) {
  5413. // $oldVersion = [
  5414. // 'url' => $role->url,
  5415. // 'description' => $role->pic_prompt,
  5416. // ];
  5417. // // 旧版本添加到数组末尾
  5418. // $versions[] = $oldVersion;
  5419. // }
  5420. // // 构建新版本(变更后)
  5421. // $newVersion = [
  5422. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5423. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5424. // ];
  5425. // // 检查新版本是否已存在于历史版本中
  5426. // $existingIndex = -1;
  5427. // foreach ($versions as $index => $version) {
  5428. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5429. // $existingIndex = $index;
  5430. // break;
  5431. // }
  5432. // }
  5433. // if ($existingIndex !== -1) {
  5434. // // 如果已存在,移除旧的位置
  5435. // array_splice($versions, $existingIndex, 1);
  5436. // }
  5437. // // 新版本添加到数组开头(最新的在前)
  5438. // array_unshift($versions, $newVersion);
  5439. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5440. // // if (count($versions) > 10) {
  5441. // // $versions = array_slice($versions, 0, 10);
  5442. // // }
  5443. // $updateData['versions'] = json_encode($versions, 256);
  5444. // }
  5445. if ($versions) {
  5446. $updateData['versions'] = json_encode($versions, 256);
  5447. }
  5448. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5449. return DB::table('mp_products')
  5450. ->where('cpid', $cpid)
  5451. ->where('id', $id)->update($updateData);
  5452. }
  5453. /**
  5454. * 获取角色版本历史
  5455. * @param array $data 包含 id(角色ID)
  5456. * @return array 返回版本历史列表
  5457. */
  5458. public function getProductVersions($data) {
  5459. $cpid = Site::getCpid();
  5460. $id = getProp($data, 'id');
  5461. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5462. $role = DB::table('mp_products')
  5463. ->where('id', $id)
  5464. ->where('cpid', $cpid)
  5465. ->where('type', 1)
  5466. ->first();
  5467. if (!$role) Utils::throwError('20003:角色不存在');
  5468. // 获取版本历史
  5469. $versions = json_decode($role->versions, true) ?: [];
  5470. // 添加当前版本作为最新版本
  5471. $currentVersion = [
  5472. 'version' => 0, // 0 表示当前版本
  5473. 'url' => $role->url,
  5474. 'pic_prompt' => $role->pic_prompt,
  5475. 'updated_at' => $role->updated_at,
  5476. 'is_current' => true
  5477. ];
  5478. array_unshift($versions, $currentVersion);
  5479. return $versions;
  5480. }
  5481. /**
  5482. * 恢复到指定版本
  5483. * @param array $data 包含 id(角色ID)、version(版本号)
  5484. * @return bool
  5485. */
  5486. public function restoreProductVersion($data) {
  5487. $uid = Site::getUid();
  5488. $cpid = Site::getCpid();
  5489. $id = getProp($data, 'id');
  5490. $version = getProp($data, 'version');
  5491. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5492. if (!$version) Utils::throwError('20003:版本号不能为空');
  5493. $role = DB::table('mp_products')
  5494. ->where('id', $id)
  5495. ->where('cpid', $cpid)
  5496. ->where('type', 1)
  5497. ->first();
  5498. if (!$role) Utils::throwError('20003:角色不存在');
  5499. // 获取版本历史
  5500. $versions = json_decode($role->versions, true) ?: [];
  5501. // 查找指定版本
  5502. $targetVersion = null;
  5503. foreach ($versions as $v) {
  5504. if ($v['version'] == $version) {
  5505. $targetVersion = $v;
  5506. break;
  5507. }
  5508. }
  5509. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5510. // 先将当前版本保存到历史
  5511. $newVersion = [
  5512. 'version' => count($versions) + 1,
  5513. 'url' => $role->url,
  5514. 'pic_prompt' => $role->pic_prompt,
  5515. 'updated_at' => date('Y-m-d H:i:s'),
  5516. 'updated_by' => $uid
  5517. ];
  5518. array_unshift($versions, $newVersion);
  5519. // 限制版本数量
  5520. if (count($versions) > 10) {
  5521. $versions = array_slice($versions, 0, 10);
  5522. }
  5523. // 恢复到指定版本
  5524. return DB::table('mp_products')
  5525. ->where('id', $id)
  5526. ->where('cpid', $cpid)
  5527. ->update([
  5528. 'url' => $targetVersion['url'],
  5529. 'pic_prompt' => $targetVersion['pic_prompt'],
  5530. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5531. 'updated_at' => date('Y-m-d H:i:s')
  5532. ]);
  5533. }
  5534. public function deleteProduct($data) {
  5535. $uid = Site::getUid();
  5536. $cpid = Site::getCpid();
  5537. $id = getProp($data, 'id');
  5538. if (!$id) Utils::throwError('20003:ID不能为空');
  5539. $ids = explode(',', $id);
  5540. // 检查是否存在且属于当前用户
  5541. $role = DB::table('mp_products')
  5542. ->whereIn('id', $ids)
  5543. ->where('cpid', $cpid)
  5544. ->get();
  5545. if (!$role) Utils::throwError('20003:记录不存在');
  5546. return DB::table('mp_products')
  5547. ->where('cpid', $cpid)
  5548. ->whereIn('id', $ids)
  5549. ->update([
  5550. 'is_deleted' => 1,
  5551. 'updated_at' => date('Y-m-d H:i:s')
  5552. ]);
  5553. }
  5554. public function generateThreeView($data) {
  5555. $uid = Site::getUid();
  5556. $cpid = Site::getCpid();
  5557. $id = getProp($data, 'id');
  5558. if (!$id) Utils::throwError('20003:ID不能为空');
  5559. // 检查是否存在且属于当前用户
  5560. $product = DB::table('mp_products')
  5561. ->where('id', $id)
  5562. ->where('cpid', $cpid)
  5563. ->where('type', 1)->first();
  5564. if (!$product) Utils::throwError('20003:资产不存在');
  5565. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5566. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5567. if (!$ref_img_url) {
  5568. // 如果没有传入参考图,使用角色表中的图片
  5569. $ref_img_url = $product->url ?? '';
  5570. if (!$ref_img_url) {
  5571. Utils::throwError('20003:参考图不能为空');
  5572. }
  5573. }
  5574. $pic_prompt = getProp($product, 'pic_prompt');
  5575. if ($pic_prompt) {
  5576. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  5577. }
  5578. // 检查参考图是否是正确的图片格式
  5579. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5580. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5581. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5582. if (!in_array($extension, $allowedExtensions)) {
  5583. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5584. }
  5585. // 处理图片模型
  5586. $model = getProp($data, 'model');
  5587. if (!$model) {
  5588. // 使用默认模型
  5589. $model = 'doubao-seedream-5-0-lite-260128';
  5590. }
  5591. // 验证模型是否在可用模型表中
  5592. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5593. Utils::throwError('20003:该模型已不可用,请更换!');
  5594. }
  5595. $ratio = getProp($data, 'ratio', '16:9');
  5596. $resolution = getProp($data, 'resolution', '2k');
  5597. // 定义分辨率和宽高比对应的尺寸映射表
  5598. $sizeMap = [
  5599. '2k' => [
  5600. '1:1' => ['width' => 2048, 'height' => 2048],
  5601. '4:3' => ['width' => 2304, 'height' => 1728],
  5602. '3:4' => ['width' => 1728, 'height' => 2304],
  5603. '16:9' => ['width' => 2848, 'height' => 1600],
  5604. '9:16' => ['width' => 1600, 'height' => 2848],
  5605. '3:2' => ['width' => 2496, 'height' => 1664],
  5606. '2:3' => ['width' => 1664, 'height' => 2496],
  5607. '21:9' => ['width' => 3136, 'height' => 1344],
  5608. ],
  5609. '3k' => [
  5610. '1:1' => ['width' => 3072, 'height' => 3072],
  5611. '4:3' => ['width' => 3456, 'height' => 2592],
  5612. '3:4' => ['width' => 2592, 'height' => 3456],
  5613. '16:9' => ['width' => 4096, 'height' => 2304],
  5614. '9:16' => ['width' => 2304, 'height' => 4096],
  5615. '2:3' => ['width' => 2496, 'height' => 3744],
  5616. '3:2' => ['width' => 3744, 'height' => 2496],
  5617. '21:9' => ['width' => 4704, 'height' => 2016],
  5618. ],
  5619. '4k' => [
  5620. '1:1' => ['width' => 4096, 'height' => 4096],
  5621. '3:4' => ['width' => 3520, 'height' => 4704],
  5622. '4:3' => ['width' => 4704, 'height' => 3520],
  5623. '16:9' => ['width' => 5504, 'height' => 3040],
  5624. '9:16' => ['width' => 3040, 'height' => 5504],
  5625. '2:3' => ['width' => 3328, 'height' => 4992],
  5626. '3:2' => ['width' => 4992, 'height' => 3328],
  5627. '21:9' => ['width' => 6240, 'height' => 2656],
  5628. ],
  5629. ];
  5630. // 参数验证
  5631. $resolution = strtolower($resolution);
  5632. if (!isset($sizeMap[$resolution])) {
  5633. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5634. }
  5635. if (!isset($sizeMap[$resolution][$ratio])) {
  5636. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5637. }
  5638. // 根据 ratio 和 resolution 确定宽高
  5639. $width = $sizeMap[$resolution][$ratio]['width'];
  5640. $height = $sizeMap[$resolution][$ratio]['height'];
  5641. try {
  5642. // 创建图片生成任务
  5643. $params = [
  5644. 'prompt' => $prompt,
  5645. 'model' => $model,
  5646. 'ref_img_urls' => [$ref_img_url],
  5647. 'width' => $width,
  5648. 'height' => $height
  5649. ];
  5650. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5651. $task_id = $task->id;
  5652. if (!$task_id) {
  5653. Utils::throwError('20003:创建图片生成任务失败');
  5654. }
  5655. // 轮询获取结果
  5656. // 只查询数据库,不调用API,不更新任务表
  5657. $start_time = time();
  5658. $timeout = 1800;
  5659. $img_url = '';
  5660. while (time() - $start_time < $timeout) {
  5661. sleep(5);
  5662. // 只查询数据库中的任务状态,不调用API,不更新任务表
  5663. $task = DB::table('mp_generate_pic_tasks')
  5664. ->where('id', $task_id)
  5665. ->first();
  5666. if (!$task) {
  5667. Utils::throwError('20003:任务不存在');
  5668. }
  5669. if ($task->status === 'success' && $task->result_url) {
  5670. $result_urls = is_string($task->result_url)
  5671. ? json_decode($task->result_url, true)
  5672. : $task->result_url;
  5673. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  5674. break;
  5675. } elseif ($task->status === 'failed') {
  5676. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  5677. }
  5678. // 其他状态继续轮询
  5679. }
  5680. if (empty($img_url)) {
  5681. Utils::throwError('20003:三视图生成超时,请稍后重试');
  5682. }
  5683. // 更新 mp_products 表(不是任务表)
  5684. DB::table('mp_products')
  5685. ->where('id', $id)
  5686. ->where('cpid', $cpid)
  5687. ->update([
  5688. 'three_view_image_url' => $img_url,
  5689. 'updated_at' => date('Y-m-d H:i:s')
  5690. ]);
  5691. return ['three_view_image_url' => $img_url];
  5692. } catch (\Exception $e) {
  5693. dLog('anime')->error('生成三视图失败', [
  5694. 'error' => $e->getMessage()
  5695. ]);
  5696. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  5697. Utils::throwError('20003:' . $e->getMessage());
  5698. }
  5699. }
  5700. /**
  5701. * 保存剧本资产关联关系
  5702. * @param array $data 请求参数
  5703. * @return bool
  5704. */
  5705. public function saveScriptProducts($data) {
  5706. $uid = Site::getUid();
  5707. $cpid = Site::getCpid();
  5708. $script_id = getProp($data, 'script_id');
  5709. $products = getProp($data, 'products', []);
  5710. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  5711. if (!$script_id) {
  5712. Utils::throwError('20003:请提供剧本ID');
  5713. }
  5714. // 验证剧本是否存在
  5715. $script = DB::table('mp_scripts')
  5716. ->where('id', $script_id)
  5717. ->where('is_deleted', 0)
  5718. ->first();
  5719. if (!$script) {
  5720. Utils::throwError('20003:剧本不存在');
  5721. }
  5722. $script_name = $script->script_name ?? 'script_' . $script_id;
  5723. // 检查是否已经有该剧本的资产数据
  5724. $existingMappings = DB::table('mp_script_product_mappings')
  5725. ->where('script_id', $script_id)
  5726. ->get();
  5727. if ($existingMappings->isNotEmpty()) {
  5728. // 已存在资产映射,检查是否所有资产都有图片生成任务
  5729. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  5730. // 查询这些资产的图片生成任务状态
  5731. $productsWithTasks = DB::table('mp_products')
  5732. ->whereIn('id', $productIds)
  5733. ->where('is_deleted', 0)
  5734. ->get();
  5735. $productTaskMap = [];
  5736. $typeFolderIds = [];
  5737. $hasAllTasks = true;
  5738. foreach ($productsWithTasks as $product) {
  5739. // 收集类型文件夹ID
  5740. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  5741. $parentFolder = DB::table('mp_products')
  5742. ->where('id', $product->parent_id)
  5743. ->where('type', 2)
  5744. ->first();
  5745. if ($parentFolder) {
  5746. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  5747. }
  5748. }
  5749. // 检查是否有图片生成任务
  5750. if (!empty($product->pic_task_id)) {
  5751. $productTaskMap[$product->id] = $product->pic_task_id;
  5752. } else if($product->url && $product->pic_task_status == '生成成功') {
  5753. continue;
  5754. }
  5755. else {
  5756. // 有资产没有图片任务
  5757. $hasAllTasks = false;
  5758. }
  5759. }
  5760. // 如果所有资产都有任务ID,直接轮询返回结果
  5761. if ($hasAllTasks && !empty($productTaskMap)) {
  5762. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  5763. 'script_id' => $script_id,
  5764. 'script_name' => $script_name,
  5765. 'product_count' => count($productTaskMap)
  5766. ]);
  5767. // 直接返回 SSE 流轮询结果
  5768. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5769. }
  5770. // 如果部分资产没有任务ID,只为这些资产创建任务
  5771. if (!$hasAllTasks && $auto_generate_images) {
  5772. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  5773. 'script_id' => $script_id,
  5774. 'script_name' => $script_name
  5775. ]);
  5776. // 处理图片模型
  5777. $model = getProp($data, 'model');
  5778. if (!$model) {
  5779. // 使用默认模型
  5780. $model = 'doubao-seedream-5-0-lite-260128';
  5781. }
  5782. // 验证模型是否在可用模型表中
  5783. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5784. Utils::throwError('20003:该模型已不可用,请更换!');
  5785. }
  5786. $ratio = getProp($data, 'ratio', '16:9');
  5787. $resolution = getProp($data, 'resolution', '2k');
  5788. // 定义分辨率和宽高比对应的尺寸映射表
  5789. $sizeMap = [
  5790. '2k' => [
  5791. '1:1' => ['width' => 2048, 'height' => 2048],
  5792. '4:3' => ['width' => 2304, 'height' => 1728],
  5793. '3:4' => ['width' => 1728, 'height' => 2304],
  5794. '16:9' => ['width' => 2848, 'height' => 1600],
  5795. '9:16' => ['width' => 1600, 'height' => 2848],
  5796. '3:2' => ['width' => 2496, 'height' => 1664],
  5797. '2:3' => ['width' => 1664, 'height' => 2496],
  5798. '21:9' => ['width' => 3136, 'height' => 1344],
  5799. ],
  5800. '3k' => [
  5801. '1:1' => ['width' => 3072, 'height' => 3072],
  5802. '4:3' => ['width' => 3456, 'height' => 2592],
  5803. '3:4' => ['width' => 2592, 'height' => 3456],
  5804. '16:9' => ['width' => 4096, 'height' => 2304],
  5805. '9:16' => ['width' => 2304, 'height' => 4096],
  5806. '2:3' => ['width' => 2496, 'height' => 3744],
  5807. '3:2' => ['width' => 3744, 'height' => 2496],
  5808. '21:9' => ['width' => 4704, 'height' => 2016],
  5809. ],
  5810. '4k' => [
  5811. '1:1' => ['width' => 4096, 'height' => 4096],
  5812. '3:4' => ['width' => 3520, 'height' => 4704],
  5813. '4:3' => ['width' => 4704, 'height' => 3520],
  5814. '16:9' => ['width' => 5504, 'height' => 3040],
  5815. '9:16' => ['width' => 3040, 'height' => 5504],
  5816. '2:3' => ['width' => 3328, 'height' => 4992],
  5817. '3:2' => ['width' => 4992, 'height' => 3328],
  5818. '21:9' => ['width' => 6240, 'height' => 2656],
  5819. ],
  5820. ];
  5821. // 参数验证
  5822. $resolution = strtolower($resolution);
  5823. if (!isset($sizeMap[$resolution])) {
  5824. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5825. }
  5826. if (!isset($sizeMap[$resolution][$ratio])) {
  5827. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5828. }
  5829. // 根据 ratio 和 resolution 确定宽高
  5830. $width = $sizeMap[$resolution][$ratio]['width'];
  5831. $height = $sizeMap[$resolution][$ratio]['height'];
  5832. // 开启事务
  5833. DB::beginTransaction();
  5834. try {
  5835. foreach ($productsWithTasks as $product) {
  5836. // 跳过已有任务的资产
  5837. if (!empty($product->pic_task_id)) {
  5838. continue;
  5839. }
  5840. // 跳过没有提示词的资产
  5841. if (empty($product->pic_prompt)) {
  5842. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  5843. 'product_id' => $product->id,
  5844. 'product_name' => $product->product_name
  5845. ]);
  5846. continue;
  5847. }
  5848. try {
  5849. // 创建图片生成任务
  5850. $params = [
  5851. 'prompt' => $product->pic_prompt,
  5852. 'model' => $model,
  5853. 'ref_img_urls' => [],
  5854. 'width' => $width,
  5855. 'height' => $height
  5856. ];
  5857. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5858. $task_id = $task->id;
  5859. if ($task_id) {
  5860. $productTaskMap[$product->id] = $task_id;
  5861. // 在事务中更新资产表的任务ID和状态
  5862. DB::table('mp_products')
  5863. ->where('id', $product->id)
  5864. ->update([
  5865. 'pic_task_id' => $task_id,
  5866. 'pic_task_status' => '生成中',
  5867. 'updated_at' => now()
  5868. ]);
  5869. dLog('anime')->info('为已存在资产创建图片生成任务', [
  5870. 'product_id' => $product->id,
  5871. 'task_id' => $task_id
  5872. ]);
  5873. }
  5874. } catch (\Exception $e) {
  5875. dLog('anime')->error('创建资产图片生成任务失败', [
  5876. 'product_id' => $product->id,
  5877. 'error' => $e->getMessage()
  5878. ]);
  5879. // 标记为失败(仍在事务中)
  5880. DB::table('mp_products')
  5881. ->where('id', $product->id)
  5882. ->update([
  5883. 'pic_task_status' => '生成失败',
  5884. 'updated_at' => now()
  5885. ]);
  5886. }
  5887. }
  5888. // 提交事务
  5889. DB::commit();
  5890. // 如果有新创建的任务,返回 SSE 流
  5891. if (!empty($productTaskMap)) {
  5892. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5893. }
  5894. } catch (\Exception $e) {
  5895. // 回滚事务
  5896. DB::rollback();
  5897. dLog('anime')->error('为已存在资产创建图片任务失败', [
  5898. 'script_id' => $script_id,
  5899. 'error' => $e->getMessage()
  5900. ]);
  5901. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  5902. }
  5903. }
  5904. // 如果不需要生成图片,返回已存在的信息
  5905. return [
  5906. 'success' => true,
  5907. 'message' => '剧本资产已存在',
  5908. 'script_id' => $script_id,
  5909. 'script_name' => $script_name,
  5910. 'type_folder_ids' => $typeFolderIds,
  5911. 'existing_products' => count($productIds),
  5912. 'tasks_count' => count($productTaskMap)
  5913. ];
  5914. }
  5915. // 解析 products(可能是 JSON 字符串或数组)
  5916. if (is_string($products)) {
  5917. $products = json_decode($products, true);
  5918. if (json_last_error() !== JSON_ERROR_NONE) {
  5919. Utils::throwError('20003:产品数据格式错误');
  5920. }
  5921. }
  5922. if (!is_array($products) || empty($products)) {
  5923. Utils::throwError('20003:产品数据不能为空');
  5924. }
  5925. // 以下是原有的创建逻辑...
  5926. // 开启事务
  5927. DB::beginTransaction();
  5928. try {
  5929. $now = now();
  5930. $mappingRecords = [];
  5931. $createdProductIds = []; // 记录所有创建的资产ID
  5932. // 获取剧本名称
  5933. $script_name = $script->script_name ?? 'script_' . $script_id;
  5934. // 存储每个类型的根文件夹ID
  5935. $typeFolderIds = [];
  5936. // 默认图片生成参数
  5937. $model = 'doubao-seedream-5-0-lite-260128';
  5938. $width = 1600;
  5939. $height = 2848;
  5940. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  5941. foreach ($products as $productGroup) {
  5942. $type = getProp($productGroup, 'type');
  5943. $title = getProp($productGroup, 'title', '');
  5944. $content = getProp($productGroup, 'content', []);
  5945. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  5946. continue;
  5947. }
  5948. // 为当前类型创建根文件夹(如果还未创建)
  5949. if (!isset($typeFolderIds[$type])) {
  5950. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  5951. 'user_id' => $uid,
  5952. 'cpid' => $cpid,
  5953. 'type' => 2, // 1.资产 2文件夹
  5954. 'product' => $type, // 1.主体 2.场景 3.道具
  5955. 'parent_id' => 0, // 根文件夹,parent_id=0
  5956. 'level' => 1, // 第一层级
  5957. 'product_name' => $script_name,
  5958. 'sort_order' => time() + $type,
  5959. 'is_deleted' => 0,
  5960. 'created_at' => $now,
  5961. 'updated_at' => $now
  5962. ]);
  5963. }
  5964. $folder_id = $typeFolderIds[$type];
  5965. // 获取表头(第一行)并查找关键列的位置
  5966. $headers = $content[0];
  5967. $nameColumnIndex = -1; // 资产名称列索引
  5968. $sequenceColumnIndex = -1; // 使用范围列索引
  5969. $promptColumnIndex = -1; // 参考提示词列索引
  5970. foreach ($headers as $index => $header) {
  5971. // 查找"资产名称"列
  5972. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  5973. $nameColumnIndex = $index;
  5974. }
  5975. // 查找"使用范围"列
  5976. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  5977. $sequenceColumnIndex = $index;
  5978. }
  5979. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  5980. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  5981. $promptColumnIndex = $index;
  5982. }
  5983. }
  5984. // 验证必要的列是否都找到了
  5985. if ($nameColumnIndex === -1) {
  5986. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  5987. continue;
  5988. }
  5989. if ($sequenceColumnIndex === -1) {
  5990. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  5991. continue;
  5992. }
  5993. // 跳过表头,解析每一行数据
  5994. for ($i = 1; $i < count($content); $i++) {
  5995. $row = $content[$i];
  5996. // 确保行数据有效
  5997. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  5998. continue;
  5999. }
  6000. // 根据动态查找的列索引提取数据
  6001. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6002. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6003. $pic_prompt = '';
  6004. // 提取参考提示词(如果找到了该列)
  6005. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6006. $pic_prompt = trim($row[$promptColumnIndex]);
  6007. }
  6008. // 解析使用范围(逗号分隔的序号)
  6009. $sequences = [];
  6010. if (!empty($sequence_str)) {
  6011. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6012. foreach ($sequenceParts as $part) {
  6013. if (is_numeric($part)) {
  6014. $sequences[] = (int)$part;
  6015. }
  6016. }
  6017. }
  6018. if (empty($product_name)) {
  6019. continue;
  6020. }
  6021. // 处理product_name两边的符号
  6022. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6023. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6024. $product_id = DB::table('mp_products')->insertGetId([
  6025. 'product_name' => $product_name,
  6026. 'type' => 1, // 1=资产 2.文件夹
  6027. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6028. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6029. 'level' => 2, // 第二层级
  6030. 'pic_prompt' => $pic_prompt,
  6031. 'user_id' => $uid,
  6032. 'cpid' => $cpid,
  6033. 'sort_order' => time(),
  6034. 'is_deleted' => 0,
  6035. 'created_at' => $now,
  6036. 'updated_at' => $now,
  6037. ]);
  6038. // 记录创建的资产ID
  6039. $createdProductIds[] = $product_id;
  6040. // 为每个序号创建映射记录
  6041. if (!empty($sequences)) {
  6042. foreach ($sequences as $sequence) {
  6043. $mappingRecords[] = [
  6044. 'script_id' => $script_id,
  6045. 'product_id' => $product_id,
  6046. 'episode_number' => $sequence,
  6047. 'created_at' => $now,
  6048. 'updated_at' => $now,
  6049. ];
  6050. }
  6051. } else {
  6052. // 如果没有指定序号,创建一个默认映射(序号为0)
  6053. $mappingRecords[] = [
  6054. 'script_id' => $script_id,
  6055. 'product_id' => $product_id,
  6056. 'episode_number' => 0,
  6057. 'created_at' => $now,
  6058. 'updated_at' => $now,
  6059. ];
  6060. }
  6061. }
  6062. }
  6063. if (empty($mappingRecords)) {
  6064. Utils::throwError('20003:没有有效的产品数据');
  6065. }
  6066. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6067. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6068. // 如果需要自动生成图片,在事务中创建图片生成任务
  6069. $productTaskMap = [];
  6070. if ($auto_generate_images && !empty($createdProductIds)) {
  6071. // 查询所有创建的资产
  6072. $productsToGenerate = DB::table('mp_products')
  6073. ->whereIn('id', $createdProductIds)
  6074. ->where('is_deleted', 0)
  6075. ->get();
  6076. foreach ($productsToGenerate as $product) {
  6077. if (empty($product->pic_prompt)) {
  6078. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6079. 'product_id' => $product->id,
  6080. 'product_name' => $product->product_name
  6081. ]);
  6082. continue;
  6083. }
  6084. try {
  6085. // 创建图片生成任务
  6086. $params = [
  6087. 'prompt' => $product->pic_prompt,
  6088. 'model' => $model,
  6089. 'ref_img_urls' => [],
  6090. 'width' => $width,
  6091. 'height' => $height
  6092. ];
  6093. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6094. $task_id = $task->id;
  6095. if ($task_id) {
  6096. $productTaskMap[$product->id] = $task_id;
  6097. // 在事务中更新资产表的任务ID和状态
  6098. DB::table('mp_products')
  6099. ->where('id', $product->id)
  6100. ->update([
  6101. 'pic_task_id' => $task_id,
  6102. 'pic_task_status' => '生成中',
  6103. 'updated_at' => now()
  6104. ]);
  6105. dLog('anime')->info('创建资产图片生成任务', [
  6106. 'product_id' => $product->id,
  6107. 'task_id' => $task_id
  6108. ]);
  6109. }
  6110. } catch (\Exception $e) {
  6111. dLog('anime')->error('创建资产图片生成任务失败', [
  6112. 'product_id' => $product->id,
  6113. 'error' => $e->getMessage()
  6114. ]);
  6115. // 标记为失败(仍在事务中)
  6116. DB::table('mp_products')
  6117. ->where('id', $product->id)
  6118. ->update([
  6119. 'pic_task_status' => '生成失败',
  6120. 'updated_at' => now()
  6121. ]);
  6122. }
  6123. }
  6124. }
  6125. // 提交事务
  6126. DB::commit();
  6127. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6128. if ($auto_generate_images && !empty($productTaskMap)) {
  6129. // 返回 SSE 流(事务外轮询)
  6130. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6131. }
  6132. // 如果不需要生成图片,返回普通结果
  6133. return [
  6134. 'success' => true,
  6135. 'type_folder_ids' => $typeFolderIds,
  6136. 'inserted_count' => $insertedCount,
  6137. 'total_records' => count($mappingRecords),
  6138. 'created_products' => count($createdProductIds),
  6139. 'image_tasks_created' => count($productTaskMap)
  6140. ];
  6141. } catch (\Exception $e) {
  6142. // 回滚事务
  6143. DB::rollback();
  6144. // 记录错误日志
  6145. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6146. 'script_id' => $script_id,
  6147. 'error' => $e->getMessage(),
  6148. 'trace' => $e->getTraceAsString()
  6149. ]);
  6150. // 统一使用 Utils::throwError 抛出错误
  6151. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6152. }
  6153. }
  6154. /**
  6155. * 批量为剧本资产生成图片
  6156. *
  6157. * @param array $data 请求参数
  6158. * @return \Generator 返回 SSE 流
  6159. */
  6160. public function batchGenerateProductImages($data) {
  6161. $script_id = getProp($data, 'script_id');
  6162. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6163. if (!$script_id) {
  6164. Utils::throwError('20003:请提供剧本ID');
  6165. }
  6166. // 验证剧本是否存在
  6167. $script = DB::table('mp_scripts')
  6168. ->where('id', $script_id)
  6169. ->where('is_deleted', 0)
  6170. ->first();
  6171. if (!$script) {
  6172. Utils::throwError('20003:剧本不存在');
  6173. }
  6174. $script_name = $script->script_name ?? 'script_' . $script_id;
  6175. // 获取需要生成图片的所有资产
  6176. $products = DB::table('mp_products')
  6177. ->whereIn('parent_id', array_values($type_folder_ids))
  6178. ->where('is_deleted', 0)
  6179. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6180. ->get();
  6181. if ($products->isEmpty()) {
  6182. Utils::throwError('20003:没有找到需要生成图片的资产');
  6183. }
  6184. // 默认参数
  6185. $model = 'doubao-seedream-5-0-lite-260128';
  6186. $width = 1600;
  6187. $height = 2848;
  6188. // 开始为每个资产创建图片生成任务
  6189. $taskIds = [];
  6190. $productTaskMap = []; // 资产ID到任务ID的映射
  6191. foreach ($products as $product) {
  6192. if (empty($product->pic_prompt)) {
  6193. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6194. continue;
  6195. }
  6196. try {
  6197. // 创建图片生成任务
  6198. $params = [
  6199. 'prompt' => $product->pic_prompt,
  6200. 'model' => $model,
  6201. 'ref_img_urls' => [],
  6202. 'width' => $width,
  6203. 'height' => $height
  6204. ];
  6205. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6206. $task_id = $task->id;
  6207. if ($task_id) {
  6208. $taskIds[] = $task_id;
  6209. $productTaskMap[$product->id] = $task_id;
  6210. // 更新资产表的任务ID和状态
  6211. DB::table('mp_products')
  6212. ->where('id', $product->id)
  6213. ->update([
  6214. 'pic_task_id' => $task_id,
  6215. 'pic_task_status' => '生成中',
  6216. 'updated_at' => now()
  6217. ]);
  6218. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6219. }
  6220. } catch (\Exception $e) {
  6221. dLog('anime')->error('创建资产图片生成任务失败', [
  6222. 'product_id' => $product->id,
  6223. 'error' => $e->getMessage()
  6224. ]);
  6225. // 标记为失败
  6226. DB::table('mp_products')
  6227. ->where('id', $product->id)
  6228. ->update([
  6229. 'pic_task_status' => '生成失败',
  6230. 'updated_at' => now()
  6231. ]);
  6232. }
  6233. }
  6234. if (empty($taskIds)) {
  6235. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6236. }
  6237. // 返回 SSE 流
  6238. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6239. }
  6240. /**
  6241. * 轮询资产图片生成任务状态(SSE流式返回)
  6242. * 只通过查询数据库获取任务状态,不主动调用API
  6243. *
  6244. * @param int $script_id 剧本ID
  6245. * @param string $script_name 剧本名称
  6246. * @param array $productTaskMap 资产ID到任务ID的映射
  6247. * @param array $type_folder_ids 类型文件夹ID映射
  6248. * @return \Generator
  6249. */
  6250. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6251. $startTime = time();
  6252. $timeout = 1800; // 30分钟超时
  6253. $pollInterval = 10; // 10秒轮询一次
  6254. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6255. // 定义类型名称映射
  6256. $typeNames = [
  6257. 1 => 'roles', // 角色
  6258. 2 => 'scenes', // 场景
  6259. 3 => 'props' // 道具
  6260. ];
  6261. while (time() - $startTime < $timeout) {
  6262. sleep($pollInterval);
  6263. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6264. $mappings = DB::table('mp_script_product_mappings')
  6265. ->where('script_id', $script_id)
  6266. ->pluck('product_id')
  6267. ->unique()
  6268. ->toArray();
  6269. if (empty($mappings)) {
  6270. dLog('anime')->warning('该剧本没有关联的资产', [
  6271. 'script_id' => $script_id,
  6272. 'script_name' => $script_name
  6273. ]);
  6274. break;
  6275. }
  6276. // 查询所有资产的当前状态
  6277. $products = DB::table('mp_products')
  6278. ->whereIn('id', $mappings)
  6279. ->where('is_deleted', 0)
  6280. ->get();
  6281. // 统计各类型的状态(使用类型名称作为键名)
  6282. $stats = [
  6283. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6284. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6285. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6286. ];
  6287. $allCompleted = true;
  6288. $hasStatusChange = false;
  6289. foreach ($products as $product) {
  6290. $type = $product->product;
  6291. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6292. // 如果类型名称不在 stats 中,初始化
  6293. if (!isset($stats[$typeName])) {
  6294. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6295. }
  6296. $stats[$typeName]['total']++;
  6297. $task_id = $product->pic_task_id;
  6298. $currentStatus = $product->pic_task_status;
  6299. // 检查状态是否有变化
  6300. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6301. $hasStatusChange = true;
  6302. $lastStatus[$product->id] = $currentStatus;
  6303. }
  6304. // 如果是生成中,查询任务表状态
  6305. if ($currentStatus === '生成中' && $task_id) {
  6306. // 只查询数据库,不调用API
  6307. $task = DB::table('mp_generate_pic_tasks')
  6308. ->where('id', $task_id)
  6309. ->first();
  6310. if ($task) {
  6311. // 检查任务状态
  6312. if ($task->status === 'success' && $task->result_url) {
  6313. // 解析图片URL
  6314. $result_urls = $task->result_url;
  6315. if (is_string($result_urls)) {
  6316. $result_urls = json_decode($result_urls, true);
  6317. }
  6318. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6319. // 更新资产表状态
  6320. DB::table('mp_products')
  6321. ->where('id', $product->id)
  6322. ->update([
  6323. 'pic_task_status' => '生成成功',
  6324. 'url' => $img_url,
  6325. 'updated_at' => now()
  6326. ]);
  6327. $stats[$typeName]['success']++;
  6328. $stats[$typeName]['completed']++;
  6329. $hasStatusChange = true;
  6330. dLog('anime')->info('资产图片生成成功', [
  6331. 'product_id' => $product->id,
  6332. 'task_id' => $task_id,
  6333. 'img_url' => $img_url
  6334. ]);
  6335. } elseif ($task->status === 'failed') {
  6336. // 更新资产表状态
  6337. DB::table('mp_products')
  6338. ->where('id', $product->id)
  6339. ->update([
  6340. 'pic_task_status' => '生成失败',
  6341. 'updated_at' => now()
  6342. ]);
  6343. $stats[$typeName]['completed']++;
  6344. $hasStatusChange = true;
  6345. dLog('anime')->warning('资产图片生成失败', [
  6346. 'product_id' => $product->id,
  6347. 'task_id' => $task_id,
  6348. 'error' => $task->error_message ?? '未知错误'
  6349. ]);
  6350. } else {
  6351. // 任务还在处理中
  6352. $allCompleted = false;
  6353. }
  6354. } else {
  6355. // 任务不存在,标记为失败
  6356. DB::table('mp_products')
  6357. ->where('id', $product->id)
  6358. ->update([
  6359. 'pic_task_status' => '生成失败',
  6360. 'updated_at' => now()
  6361. ]);
  6362. $stats[$type]['completed']++;
  6363. $hasStatusChange = true;
  6364. dLog('anime')->error('图片生成任务不存在', [
  6365. 'product_id' => $product->id,
  6366. 'task_id' => $task_id
  6367. ]);
  6368. }
  6369. } elseif ($currentStatus === '生成成功') {
  6370. $stats[$typeName]['success']++;
  6371. $stats[$typeName]['completed']++;
  6372. } elseif ($currentStatus === '生成失败') {
  6373. $stats[$typeName]['completed']++;
  6374. } else {
  6375. // 其他状态也认为未完成
  6376. $allCompleted = false;
  6377. }
  6378. }
  6379. // 移除没有数据的类型(total=0)
  6380. foreach ($stats as $typeName => $stat) {
  6381. if ($stat['total'] === 0) {
  6382. unset($stats[$typeName]);
  6383. }
  6384. }
  6385. // 如果有状态变化,发送 SSE 更新
  6386. if ($hasStatusChange) {
  6387. $eventType = $allCompleted ? 'complete' : 'update';
  6388. $response = [
  6389. 'type' => $eventType,
  6390. 'script_id' => $script_id,
  6391. 'script_name' => $script_name,
  6392. 'stats' => $stats,
  6393. 'timestamp' => date('Y-m-d H:i:s')
  6394. ];
  6395. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6396. dLog('anime')->info('SSE更新', [
  6397. 'event_type' => $eventType,
  6398. 'script_id' => $script_id,
  6399. 'script_name' => $script_name,
  6400. 'stats' => $stats
  6401. ]);
  6402. if ($allCompleted) {
  6403. dLog('anime')->info('所有资产图片生成任务已完成', [
  6404. 'script_id' => $script_id,
  6405. 'script_name' => $script_name,
  6406. 'stats' => $stats
  6407. ]);
  6408. break;
  6409. }
  6410. }
  6411. }
  6412. // 超时处理
  6413. if (time() - $startTime >= $timeout && !$allCompleted) {
  6414. $response = [
  6415. 'type' => 'timeout',
  6416. 'message' => '部分任务超时,请稍后查看结果',
  6417. 'script_id' => $script_id,
  6418. 'script_name' => $script_name,
  6419. 'timestamp' => date('Y-m-d H:i:s')
  6420. ];
  6421. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6422. dLog('anime')->warning('资产图片生成任务超时', [
  6423. 'script_id' => $script_id,
  6424. 'script_name' => $script_name,
  6425. 'timeout' => $timeout
  6426. ]);
  6427. }
  6428. }
  6429. /**
  6430. * 获取剧本关联的资产列表
  6431. * @param array $data 请求参数
  6432. * @return array
  6433. */
  6434. public function getScriptProducts($data) {
  6435. $uid = Site::getUid();
  6436. $cpid = Site::getCpid();
  6437. $script_id = getProp($data, 'script_id');
  6438. $episode_number = getProp($data, 'episode_number');
  6439. if (!$script_id) {
  6440. Utils::throwError('20003:请提供剧本ID');
  6441. }
  6442. // 验证剧本是否存在
  6443. $script = DB::table('mp_scripts')
  6444. ->where('id', $script_id)
  6445. ->where('is_deleted', 0)
  6446. ->first();
  6447. if (!$script) {
  6448. Utils::throwError('20003:剧本不存在');
  6449. }
  6450. // 联表查询资产信息
  6451. $query = DB::table('mp_script_product_mappings as mapping')
  6452. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6453. ->where('mapping.script_id', $script_id)
  6454. ->where('product.cpid', $cpid)
  6455. ->where('product.is_deleted', 0);
  6456. // 如果提供了 episode_number,则过滤指定集数
  6457. if ($episode_number !== null && $episode_number !== '') {
  6458. $query->where('mapping.episode_number', $episode_number);
  6459. }
  6460. $mappings = $query->select(
  6461. 'mapping.script_id',
  6462. 'mapping.product_id',
  6463. 'mapping.episode_number',
  6464. 'product.product_name',
  6465. 'product.type',
  6466. 'product.product',
  6467. 'product.pic_prompt',
  6468. 'product.url',
  6469. 'product.pic_task_id',
  6470. 'product.pic_task_status',
  6471. 'product.three_view_image_url',
  6472. 'mapping.created_at'
  6473. )
  6474. ->orderBy('mapping.product_id', 'asc')
  6475. ->orderBy('mapping.episode_number', 'asc')
  6476. ->get();
  6477. // 按 product_id 分组,合并 episode_number
  6478. $productMap = [];
  6479. foreach ($mappings as $item) {
  6480. $product_id = $item->product_id;
  6481. if (!isset($productMap[$product_id])) {
  6482. $productMap[$product_id] = [
  6483. 'product_id' => $product_id,
  6484. 'product_name' => $item->product_name,
  6485. 'type' => (int)$item->type,
  6486. 'product' => (int)$item->product,
  6487. 'pic_prompt' => $item->pic_prompt,
  6488. 'url' => $item->url,
  6489. 'pic_task_id' => $item->pic_task_id,
  6490. 'pic_task_status' => $item->pic_task_status,
  6491. 'episode_numbers' => [],
  6492. 'created_at' => $item->created_at,
  6493. ];
  6494. }
  6495. // 添加 episode_number(去重)
  6496. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6497. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6498. }
  6499. }
  6500. // 按类型分组
  6501. $roles = []; // type=1 角色/主体
  6502. $scenes = []; // type=2 场景
  6503. $props = []; // type=3 道具
  6504. foreach ($productMap as $product) {
  6505. // 将 episode_numbers 数组转换为逗号分隔的字符串
  6506. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  6507. // 构造返回数据
  6508. $productData = [
  6509. 'product_id' => $product['product_id'],
  6510. 'product_name' => $product['product_name'],
  6511. 'product' => $product['product'],
  6512. 'pic_prompt' => $product['pic_prompt'],
  6513. 'url' => $product['url'],
  6514. 'pic_task_id' => $product['pic_task_id'],
  6515. 'pic_task_status' => $product['pic_task_status'],
  6516. 'episode_numbers' => $episodeNumbersStr,
  6517. 'created_at' => $product['created_at'],
  6518. ];
  6519. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  6520. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  6521. switch ($product['product']) {
  6522. case 1:
  6523. $roles[] = $productData;
  6524. break;
  6525. case 2:
  6526. $scenes[] = $productData;
  6527. break;
  6528. case 3:
  6529. $props[] = $productData;
  6530. break;
  6531. }
  6532. }
  6533. return [
  6534. 'script_id' => $script_id,
  6535. 'script_name' => $script->script_name ?? '',
  6536. 'roles' => $roles, // 主体
  6537. 'scenes' => $scenes, // 场景
  6538. 'props' => $props, // 道具
  6539. ];
  6540. }
  6541. /**
  6542. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  6543. * @param string $actContent 原始内容
  6544. * @param array $products 产品数组(包含product_name和url)
  6545. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  6546. */
  6547. public function processActContentWithProducts($actContent, $products) {
  6548. if (empty($actContent) || empty($products)) {
  6549. return [
  6550. 'content' => $actContent,
  6551. 'reference_images' => []
  6552. ];
  6553. }
  6554. // 构建产品名称到产品信息的映射
  6555. $product_dict = [];
  6556. foreach ($products as $product) {
  6557. $product_name = getProp($product, 'product_name');
  6558. if ($product_name) {
  6559. $product_dict[$product_name] = [
  6560. 'url' => getProp($product, 'url'),
  6561. 'voice_prompt' => getProp($product, 'voice_prompt')
  6562. ];
  6563. }
  6564. }
  6565. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  6566. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  6567. $reference_images = [];
  6568. $product_index_map = []; // 产品名称 => 图片序号的映射
  6569. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  6570. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  6571. $current_index = 1;
  6572. if (!empty($matches[1])) {
  6573. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  6574. $seen_products = []; // 用于去重
  6575. foreach ($matches[1] as $product_name) {
  6576. // 跳过已处理的产品
  6577. if (isset($seen_products[$product_name])) {
  6578. continue;
  6579. }
  6580. $seen_products[$product_name] = true;
  6581. // 检查产品是否在字典中
  6582. if (isset($product_dict[$product_name])) {
  6583. $url = $product_dict[$product_name]['url'];
  6584. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  6585. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  6586. if (!empty($voice_prompt) && $product_name !== '旁白') {
  6587. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  6588. }
  6589. // 只有URL非空才分配序号和添加到参考图片
  6590. if (!empty($url)) {
  6591. // 检查URL是否已经在reference_images中(去重)
  6592. if (!in_array($url, $reference_images)) {
  6593. $reference_images[] = $url;
  6594. $product_index_map[$product_name] = $current_index;
  6595. $current_index++;
  6596. } else {
  6597. // URL重复,找到已有的序号
  6598. $existing_index = array_search($url, $reference_images) + 1;
  6599. $product_index_map[$product_name] = $existing_index;
  6600. }
  6601. } else {
  6602. // URL为空,不分配序号(后续直接去掉{})
  6603. $product_index_map[$product_name] = 0;
  6604. }
  6605. } else {
  6606. // 产品不在字典中,不分配序号
  6607. $product_index_map[$product_name] = 0;
  6608. }
  6609. }
  6610. }
  6611. // 第二步:替换内容中的 {产品名称}
  6612. $processedContent = $actContent;
  6613. foreach ($product_index_map as $product_name => $index) {
  6614. $escaped_name = preg_quote($product_name, '/');
  6615. if ($index > 0) {
  6616. // 有图片,替换为:产品名称(图X)
  6617. $replacement = $product_name . '<图片' . $index . '>';
  6618. } else {
  6619. // 无图片,只保留产品名称
  6620. $replacement = $product_name;
  6621. }
  6622. // 替换所有 {产品名称} 为处理后的格式
  6623. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  6624. }
  6625. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  6626. foreach ($products as $product) {
  6627. $product_name = getProp($product, 'product_name');
  6628. $voice_prompt = getProp($product, 'voice_prompt');
  6629. if ($product_name === '旁白' && !empty($voice_prompt)) {
  6630. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  6631. break; // 找到旁白后退出循环
  6632. }
  6633. }
  6634. // 第四步:将voice_prompt信息添加到内容最前面
  6635. $voice_prompt_prefix = '';
  6636. if (!empty($voice_prompts)) {
  6637. $voice_prompt_prefix .= implode('', $voice_prompts);
  6638. }
  6639. // 旁白的voice_prompt放在最后
  6640. if (!empty($narrator_voice_prompt)) {
  6641. $voice_prompt_prefix .= $narrator_voice_prompt;
  6642. }
  6643. // 如果有voice_prompt信息,添加到内容开头
  6644. if (!empty($voice_prompt_prefix)) {
  6645. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  6646. }
  6647. return [
  6648. 'content' => $processedContent,
  6649. 'reference_images' => $reference_images
  6650. ];
  6651. }
  6652. public function saveActVideoGenerateParams($data) {
  6653. $episode_id = getProp($data, 'episode_id');
  6654. $model = getProp($data, 'video_model');
  6655. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  6656. Utils::throwError('20003:该模型不可用');
  6657. }
  6658. if (!$model) {
  6659. // 使用默认模型
  6660. $model = 'zhizhen-20-mini';
  6661. }
  6662. // 验证模型是否在可用模型表中
  6663. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6664. Utils::throwError('20003:该模型已不可用,请更换!');
  6665. }
  6666. $video_resolution = getProp($data, 'video_resolution', '720p');
  6667. $ratio = getProp($data, 'ratio');
  6668. if (!$ratio) $ratio = '9:16';
  6669. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6670. 'video_model' => $model,
  6671. 'video_resolution' => $video_resolution,
  6672. 'ratio' => $ratio,
  6673. 'updated_at' => date('Y-m-d H:i:s')
  6674. ]);
  6675. }
  6676. public function confirmActs($data) {
  6677. $episode_id = getProp($data, 'episode_id');
  6678. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  6679. if (!$episode) {
  6680. Utils::throwError('20003:分集不存在');
  6681. }
  6682. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  6683. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  6684. // 获取所有片段数据
  6685. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6686. // 构建角色和场景名称数组
  6687. $role_names = [];
  6688. $scene_names = [];
  6689. foreach ($roles as $role) {
  6690. $role_name = getProp($role, 'role');
  6691. if ($role_name && $role_name != '旁白') {
  6692. $role_names[] = $role_name;
  6693. }
  6694. }
  6695. foreach ($scenes as $scene) {
  6696. $scene_name = getProp($scene, 'scene');
  6697. if ($scene_name) {
  6698. $scene_names[] = $scene_name;
  6699. }
  6700. }
  6701. // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
  6702. usort($role_names, function($a, $b) {
  6703. return mb_strlen($b) - mb_strlen($a);
  6704. });
  6705. usort($scene_names, function($a, $b) {
  6706. return mb_strlen($b) - mb_strlen($a);
  6707. });
  6708. try {
  6709. DB::beginTransaction();
  6710. // 处理每个片段
  6711. foreach ($acts as $act) {
  6712. $act_content = getProp($act, 'act_content');
  6713. if (!$act_content) continue;
  6714. $processed_content = $act_content;
  6715. // 标记已处理的位置,避免重复标记
  6716. $marked_positions = [];
  6717. // 先匹配场景(在"场景:"后面)
  6718. foreach ($scene_names as $scene_name) {
  6719. // 转义特殊字符
  6720. $escaped_scene = preg_quote($scene_name, '/');
  6721. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  6722. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  6723. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  6724. $full_match = $matches[0];
  6725. $prefix = $matches[1];
  6726. $scene_name = $matches[2];
  6727. // 检查是否已经被标记
  6728. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  6729. return $prefix . '{' . $scene_name . '}';
  6730. }
  6731. return $full_match;
  6732. }, $processed_content);
  6733. }
  6734. // 再匹配角色名称(只在"画面:"部分)
  6735. foreach ($role_names as $role_name) {
  6736. // 转义特殊字符
  6737. $escaped_role = preg_quote($role_name, '/');
  6738. // 只匹配"画面:"开始到换行之前的内容
  6739. $pattern = '/(画面:[^\n]*)/u';
  6740. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  6741. $line = $matches[1]; // 整行"画面:xxxxx"
  6742. // 在这一行中匹配所有角色名(避免重复标记)
  6743. $new_line = preg_replace(
  6744. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  6745. '{$1}',
  6746. $line
  6747. );
  6748. return $new_line;
  6749. }, $processed_content);
  6750. }
  6751. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  6752. $shot_counter = 0;
  6753. $processed_content = preg_replace_callback(
  6754. '/【(?:镜头|分镜)(\d+)】/u',
  6755. function($matches) use (&$shot_counter) {
  6756. $shot_counter++;
  6757. return '【镜头' . $shot_counter . '】';
  6758. },
  6759. $processed_content
  6760. );
  6761. // 更新数据库
  6762. $boolen = DB::table('mp_episode_segments')
  6763. ->where('id', $act->id)
  6764. ->update([
  6765. 'act_show_content' => $processed_content,
  6766. 'updated_at' => date('Y-m-d H:i:s')
  6767. ]);
  6768. if (!$boolen) {
  6769. Utils::throwError('20003:片段处理失败');
  6770. }
  6771. }
  6772. }catch (\Exception $e) {
  6773. DB::rollBack();
  6774. Utils::throwError('20003:'.$e->getMessage());
  6775. }
  6776. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6777. 'is_generated' => 1,
  6778. 'updated_at' => date('Y-m-d H:i:s')
  6779. ]);
  6780. if (!$boolen1) {
  6781. DB::rollBack();
  6782. Utils::throwError('20003:分集处理失败!');
  6783. }
  6784. DB::commit();
  6785. // 重新查询更新后的片段数据
  6786. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6787. // 合并角色、场景和extra_products作为products,统一字段名为product_name
  6788. // extra_products优先级更高,会覆盖同名的roles和scenes
  6789. $products = [];
  6790. // 先处理角色数组
  6791. foreach ($roles as $role) {
  6792. $product = $role;
  6793. // 将role字段重命名为product_name
  6794. if (isset($product['role'])) {
  6795. $product['product_name'] = $product['role'];
  6796. unset($product['role']);
  6797. }
  6798. $product['product'] = 1; // 标记类型为角色
  6799. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6800. }
  6801. // 处理场景数组
  6802. foreach ($scenes as $scene) {
  6803. $product = $scene;
  6804. // 将scene字段重命名为product_name
  6805. if (isset($product['scene'])) {
  6806. $product['product_name'] = $product['scene'];
  6807. unset($product['scene']);
  6808. }
  6809. $product['product'] = 2; // 标记类型为场景
  6810. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6811. }
  6812. // extra_products优先级更高,直接覆盖同名的roles和scenes
  6813. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  6814. foreach ($extra_products as $extra_product) {
  6815. $product_name = getProp($extra_product, 'product_name');
  6816. if ($product_name) {
  6817. $products[$product_name] = $extra_product; // 覆盖同名数据
  6818. }
  6819. }
  6820. // 重新索引数组(去除key)
  6821. $products = array_values($products);
  6822. // 构建返回的acts数组
  6823. $return_acts = [];
  6824. foreach ($acts as $act) {
  6825. $return_acts[] = [
  6826. 'act_id' => getProp($act, 'id'),
  6827. 'act_number' => getProp($act, 'act_number'),
  6828. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  6829. 'act_show_content' => getProp($act, 'act_show_content'),
  6830. 'video_url' => getProp($act, 'video_url'),
  6831. 'video_duration' => getProp($act, 'video_duration'),
  6832. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  6833. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  6834. ];
  6835. }
  6836. return [
  6837. 'anime_id' => getProp($episode, 'anime_id'),
  6838. 'episode_id' => $episode_id,
  6839. 'title' => getProp($episode, 'title'),
  6840. 'episode_number' => getProp($episode, 'episode_number'),
  6841. 'is_generated' => getProp($episode, 'is_generated'),
  6842. 'products' => $products,
  6843. 'acts' => $return_acts
  6844. ];
  6845. }
  6846. }