AnimeService.php 428 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use App\Services\PointsService;
  12. use Dflydev\DotAccessData\Util;
  13. use GuzzleHttp\Client;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. class AnimeService
  20. {
  21. protected $aiImageGenerationService;
  22. protected $aiVideoGenerationService;
  23. protected $DeepSeekService;
  24. protected $pointsService;
  25. private $url;
  26. private $api_key;
  27. private $headers;
  28. public function __construct(
  29. AIImageGenerationService $aiImageGenerationService,
  30. AIVideoGenerationService $aiVideoGenerationService,
  31. DeepSeekService $DeepSeekService,
  32. PointsService $pointsService
  33. ) {
  34. $this->aiImageGenerationService = $aiImageGenerationService;
  35. $this->aiVideoGenerationService = $aiVideoGenerationService;
  36. $this->DeepSeekService = $DeepSeekService;
  37. $this->pointsService = $pointsService;
  38. $this->url = 'https://api.deepseek.com/chat/completions';
  39. $this->api_key = env('DEEPSEEK_API_KEY');
  40. $this->headers = [
  41. 'Authorization' => 'Bearer '.$this->api_key,
  42. 'Content-Type' => 'application/json; charset=UTF-8'
  43. ];
  44. }
  45. /**
  46. * 构建统一的分镜数据结构(episodeInfo格式)
  47. * @param array $segments 分镜数据数组
  48. * @return array 返回包含acts和total_duration的数组
  49. */
  50. public function buildEpisodeSegmentsStructure($segments) {
  51. $acts = [];
  52. $totalDuration = 0; // 初始化总时长
  53. foreach($segments as $segment) {
  54. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  55. $videoDuration = getProp($segment, 'video_duration');
  56. $audioDuration = getProp($segment, 'audio_duration');
  57. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  58. $totalDuration += floatval($videoDuration);
  59. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  60. $totalDuration += floatval($audioDuration);
  61. } else {
  62. $totalDuration += 5; // 默认5秒
  63. }
  64. $segment_content = getProp($segment, 'segment_content');
  65. // 判断是否有尾帧描述,如果有则去掉这部分内容
  66. if (strpos($segment_content, '尾帧') !== false) {
  67. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  68. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  69. }
  70. // 构建分镜信息
  71. $segmentInfo = [
  72. 'segment_id' => getProp($segment, 'segment_id'),
  73. 'segment_number' => getProp($segment, 'segment_number'),
  74. 'segment_content' => $segment_content,
  75. 'description' => getProp($segment, 'description'),
  76. 'composition' => getProp($segment, 'composition'),
  77. 'camera_movement' => getProp($segment, 'camera_movement'),
  78. 'voice_actor' => getProp($segment, 'voice_actor'),
  79. 'dialogue' => getProp($segment, 'dialogue'),
  80. 'frame_type' => getProp($segment, 'frame_type'),
  81. 'scene' => getProp($segment, 'scene'),
  82. 'characters' => getProp($segment, 'characters'),
  83. 'tail_frame' => getProp($segment, 'tail_frame'),
  84. 'emotion' => getProp($segment, 'emotion'),
  85. 'emotion_type' => getProp($segment, 'emotion_type'),
  86. 'gender' => getProp($segment, 'gender'),
  87. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  88. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  89. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  90. 'pitch' => getProp($segment, 'pitch'),
  91. 'voice_name' => getProp($segment, 'voice_name'),
  92. 'voice_type' => getProp($segment, 'voice_type'),
  93. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  94. 'img_url' => getProp($segment, 'img_url'),
  95. 'audio_url' => getProp($segment, 'audio_url'),
  96. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  97. 'video_url' => getProp($segment, 'video_url'),
  98. 'video_duration' => getProp($segment, 'video_duration', 0),
  99. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  100. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  101. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  102. 'current_type' => getProp($segment, 'current_type'),
  103. ];
  104. $actNumber = getProp($segment, 'act_number');
  105. if (isset($acts[$actNumber])) {
  106. $acts[$actNumber]['segments'][] = $segmentInfo;
  107. } else {
  108. $acts[$actNumber] = [
  109. 'act_number' => $actNumber,
  110. 'act_title' => getProp($segment, 'act_title'),
  111. 'act_duration' => getProp($segment, 'act_duration'),
  112. 'segments' => [$segmentInfo]
  113. ];
  114. }
  115. }
  116. return [
  117. 'acts' => array_values($acts),
  118. 'total_duration' => intval(round($totalDuration))
  119. ];
  120. }
  121. /**
  122. * 构建统一的分段数据结构(episodeInfoForAce格式)
  123. * @param array $segments 分段数据数组
  124. * @return array 返回包含acts和total_duration的数组
  125. */
  126. public function buildEpisodeActsStructureForAce($segments) {
  127. $acts = [];
  128. $totalDuration = 0; // 初始化总时长
  129. foreach($segments as $segment) {
  130. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  131. $videoDuration = getProp($segment, 'video_duration');
  132. $actDuration = getProp($segment, 'act_duration');
  133. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  134. $totalDuration += floatval($videoDuration);
  135. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  136. $totalDuration += floatval($actDuration);
  137. } else {
  138. $totalDuration += 5; // 默认5秒
  139. }
  140. // 构建分镜信息
  141. $segmentInfo = [
  142. 'act_id' => getProp($segment, 'id'),
  143. 'act_number' => getProp($segment, 'act_number'),
  144. 'act_title' => getProp($segment, 'act_title'),
  145. 'act_duration' => getProp($segment, 'act_duration'),
  146. 'act_content' => getProp($segment, 'act_content'),
  147. 'video_url' => getProp($segment, 'video_url'),
  148. 'video_duration' => getProp($segment, 'video_duration', 0),
  149. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  150. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  151. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  152. 'current_type' => getProp($segment, 'current_type'),
  153. ];
  154. $acts[] = $segmentInfo;
  155. }
  156. return [
  157. 'acts' => array_values($acts),
  158. 'total_duration' => intval(round($totalDuration))
  159. ];
  160. }
  161. /**
  162. * 验证画面比例是否有效
  163. * @param string $ratio 画面比例
  164. * @return bool
  165. */
  166. public function validateRatio($ratio) {
  167. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  168. }
  169. /**
  170. * 获取画面比例对应的宽高
  171. * @param string $ratio 画面比例
  172. * @return array ['width' => int, 'height' => int]
  173. * @throws \Exception
  174. */
  175. private function getRatioDimensions($ratio) {
  176. if ($ratio && !$this->validateRatio($ratio)) {
  177. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  178. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  179. }
  180. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  181. }
  182. public function createAnime($data) {
  183. $uid = Site::getUid();
  184. $cpid = Site::getCpid();
  185. $input_art_style = getProp($data, 'art_style');
  186. $file = getProp($data, 'file');
  187. $content = getProp($data, 'content', '');
  188. $bid = getProp($data, 'bid', 0);
  189. $script_id = getProp($data, 'script_id', 0);
  190. $ace_mode = getProp($data, 'ace_mode', 0);
  191. $extra_products = getProp($data, 'products', []);
  192. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  193. if (!is_array($extra_products)) {
  194. Utils::throwError('20003:传入的资产格式不正确');
  195. }
  196. // 替换美术风格
  197. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  198. // 提取文件内容
  199. if ($file) {
  200. $content = $this->DeepSeekService->extractFileContent($file);
  201. if (!$content) {
  202. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  203. }
  204. } elseif ($script_id) {
  205. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  208. }
  209. } elseif ($bid) {
  210. $content = $this->DeepSeekService->getContentByBid($bid);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  213. }
  214. } elseif ($content) {
  215. $content = filterContent($content);
  216. }else {
  217. $content = '';
  218. }
  219. $anime_data = [
  220. 'user_id' => $uid,
  221. 'cpid' => $cpid,
  222. 'anime_name' => '新剧本策划',
  223. 'is_multi' => getProp($data, 'is_multi', 1),
  224. 'content' => $content,
  225. 'art_style_type' => $input_art_style,
  226. 'ace_mode' => $ace_mode,
  227. 'script_id' => $script_id,
  228. 'extra_products' => json_encode($extra_products, 256),
  229. 'created_at' => date('Y-m-d H:i:s'),
  230. 'updated_at' => date('Y-m-d H:i:s'),
  231. ];
  232. // 处理文本模型
  233. $model = getProp($data, 'model');
  234. if (!$model) {
  235. // 用户没有输入,使用默认值
  236. $model = 'deepseek-v4-pro';
  237. }
  238. // 验证模型是否在可用模型表中
  239. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  240. $model = 'deepseek-v4-pro';
  241. }
  242. $anime_data['model'] = $model;
  243. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  244. return DB::table('mp_animes')->insertGetId($anime_data);
  245. }
  246. public function chatList($data) {
  247. $uid = Site::getUid();
  248. $anime_name = getProp($data, 'anime_name');
  249. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  250. if ($anime_name) {
  251. $query->where('anime_name', 'like', "%$anime_name%");
  252. }
  253. return $query->orderBy('id', 'desc')->paginate();
  254. }
  255. public function chatHistory($data) {
  256. $anime_id = getProp($data, 'anime_id');
  257. $sequence = getProp($data, 'sequence', 0);
  258. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  259. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  260. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  261. return $query->orderBy('ar.id')->get()->map(function ($value) {
  262. $value = (array)$value;
  263. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  264. $value['created_at'] = transDate($value['created_at']);
  265. $value['episode_created_at'] = transDate($value['episode_created_at']);
  266. return $value;
  267. })->toArray();
  268. }
  269. public function batchSetRoleImg($data) {
  270. $episode_id = getProp($data, 'episode_id');
  271. if (!$episode_id) Utils::throwError('1002:请选择分集');
  272. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  273. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  274. $art_style = getProp($episode, 'art_style');
  275. $anime_id = getProp($episode, 'anime_id');
  276. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  277. $art_style_type = getProp($anime, 'art_style_type');
  278. $character_prefix = '';
  279. $scene_prefix = '';
  280. if ($art_style_type) {
  281. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  282. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  283. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  284. }
  285. foreach ($roles as &$role) {
  286. $role_name = getProp($role, 'role');
  287. if ($role_name == '旁白') continue;
  288. // 优先使用 pic_prompt,如果没有则使用 description
  289. $pic_prompt = getProp($role, 'pic_prompt');
  290. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  291. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  292. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  293. // 参考图地址
  294. $ref_img_url = getProp($role, 'url');
  295. if ($ref_img_url) continue; // 已有图片则跳过
  296. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  297. try {
  298. $params = [
  299. 'prompt' => $description,
  300. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  301. ];
  302. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  303. $task_id = $task->id;
  304. if (!$task_id) {
  305. Utils::throwError("20003:角色({$role_name})生成图片失败");
  306. }
  307. $role['task_id'] = $task_id;
  308. $role['task_status'] = 'processing';
  309. } catch (\Exception $e) {
  310. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  311. Utils::throwError("20003:" . $e->getMessage());
  312. }
  313. }
  314. // 保存角色信息
  315. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  316. 'roles' => json_encode($roles, 256),
  317. 'generate_status' => '执行中',
  318. 'generate_at' => date('Y-m-d H:i:s'),
  319. 'updated_at' => date('Y-m-d H:i:s')
  320. ]);
  321. if (!$boolen) {
  322. Utils::throwError('20003:保存角色信息失败');
  323. }
  324. return $boolen;
  325. }
  326. public function batchSetSceneImg($data) {
  327. $episode_id = getProp($data, 'episode_id');
  328. if (!$episode_id) Utils::throwError('1002:请选择分集');
  329. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  330. $scenes = json_decode(getProp($episode, 'scenes'), true);
  331. $art_style = getProp($episode, 'art_style');
  332. $target_scene = getProp($data, 'target_scene');
  333. $anime_id = getProp($episode, 'anime_id');
  334. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  335. $art_style_type = getProp($anime, 'art_style_type');
  336. $character_prefix = '';
  337. $scene_prefix = '';
  338. if ($art_style_type) {
  339. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  340. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  341. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  342. }
  343. foreach ($scenes as &$scene) {
  344. $scene_name = getProp($scene, 'scene');
  345. if ($scene_name != $target_scene) continue;
  346. // 优先使用 pic_prompt,如果没有则使用 description
  347. $pic_prompt = getProp($scene, 'pic_prompt');
  348. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  349. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  350. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  351. // 参考图地址
  352. $ref_img_url = getProp($scene, 'url');
  353. if ($ref_img_url) continue; // 已有图片则跳过
  354. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  355. try {
  356. $params = [
  357. 'prompt' => $description,
  358. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  359. ];
  360. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  361. $task_id = $task->id;
  362. if (!$task_id) {
  363. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  364. }
  365. $scene['task_id'] = $task_id;
  366. $scene['task_status'] = 'processing';
  367. } catch (\Exception $e) {
  368. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  369. Utils::throwError("20003:" . $e->getMessage());
  370. }
  371. }
  372. // 保存场景信息
  373. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  374. 'scenes' => json_encode($scenes, 256),
  375. 'generate_status' => '执行中',
  376. 'generate_at' => date('Y-m-d H:i:s'),
  377. 'updated_at' => date('Y-m-d H:i:s')
  378. ]);
  379. if (!$boolen) {
  380. Utils::throwError('20003:保存角色信息失败');
  381. }
  382. return $boolen;
  383. }
  384. public function editAnime($data) {
  385. $anime_id = getProp($data, 'anime_id');
  386. $anime_name = trim(getProp($data, 'anime_name'));
  387. // 确认对话名称唯一性
  388. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  389. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  390. }
  391. if (!$anime_id || !$anime_name) {
  392. Utils::throwError('20003:参数异常');
  393. }
  394. return DB::table('mp_animes')->where('id', $anime_id)->update([
  395. 'anime_name' => $anime_name,
  396. 'updated_at' => date('Y-m-d H:i:s')
  397. ]);
  398. // $script_arr =getProp($data, 'script', []);
  399. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  400. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  401. // $anime_id = getProp($data, 'anime_id');
  402. // try {
  403. // DB::beginTransaction();
  404. // $table_data = [
  405. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  406. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  407. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  408. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  409. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  410. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  411. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  412. // 'status' => 3,
  413. // 'start_episode_sequence' => $start_episode_sequence,
  414. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  415. // 'episode_num' => count($script_arr['episodes']),
  416. // 'updated_at' => date('Y-m-d H:i:s')
  417. // ];
  418. // // 保存剧本内容
  419. // if (!empty($anime_id)) {
  420. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  421. // if (!$boolen) {
  422. // dLog('anime')->info('对话保存失败', $table_data);
  423. // Utils::throwError('20003:对话保存失败');
  424. // }
  425. // }else {
  426. // $table['created_at'] = $table_data['updated_at'];
  427. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  428. // if (!$anime_id) {
  429. // dLog('anime')->info('对话保存失败', $table_data);
  430. // Utils::throwError('20003:对话保存失败');
  431. // }
  432. // }
  433. // // 保存分集内容
  434. // // 删除历史分集内容
  435. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  436. // $episodes = [];
  437. // $sequence = 1;
  438. // foreach ($script_arr['episodes'] as $episode) {
  439. // $segment_number = 1;
  440. // foreach($episode['segments'] as $segment) {
  441. // $episodes[] = [
  442. // 'anime_id' => $anime_id,
  443. // 'episode_number' => $episode['episode_number'],
  444. // 'title' => $episode['title'],
  445. // // 'content' => $episode['content'],
  446. // 'content' => '',
  447. // 'segment_number' => $segment_number,
  448. // 'segment_content' => $segment['segment_content'],
  449. // 'sequence' => $sequence,
  450. // 'created_at' => date('Y-m-d H:i:s'),
  451. // 'updated_at' => date('Y-m-d H:i:s')
  452. // ];
  453. // $sequence++;
  454. // $segment_number++;
  455. // }
  456. // }
  457. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  458. // if (!$boolen2) {
  459. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  460. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  461. // Utils::throwError('20003:分集内容保存失败');
  462. // }
  463. // } catch (\Exception $e) {
  464. // DB::rollBack();
  465. // Utils::throwError('20003:'.$e->getMessage());
  466. // }
  467. // DB::commit();
  468. // return true;
  469. }
  470. public function delAnime($data) {
  471. $anime_id = getProp($data, 'anime_id');
  472. if (!$anime_id) {
  473. Utils::throwError('20003:请选择剧本');
  474. }
  475. return DB::table('mp_animes')->where('id', $anime_id)->update([
  476. 'is_deleted' => 1,
  477. 'updated_at' => date('Y-m-d H:i:s')
  478. ]);
  479. }
  480. public function animeDetail($data) {
  481. $uid = Site::getUid();
  482. $anime_id = getProp($data, 'anime_id');
  483. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  484. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  485. if (!$anime) Utils::throwError('20003:权限不足');
  486. $anime = (array)$anime;
  487. $anime['roles'] = json_decode($anime['roles']);
  488. $anime['scenes'] = json_decode($anime['scenes']);
  489. // 获取分集信息
  490. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  491. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  492. ->orderBy('episode_number')->get()->map(function ($value) {
  493. return (array)$value;
  494. })->toArray();
  495. $anime['episodes'] = $episodes;
  496. return $anime;
  497. }
  498. public function episodeInfo($data) {
  499. $uid = Site::getUid();
  500. $anime_id = getProp($data, 'anime_id');
  501. $episode_id = getProp($data, 'episode_id');
  502. if (!$anime_id || !$episode_id) {
  503. Utils::throwError('1002:请选择剧集');
  504. }
  505. // 验证用户权限
  506. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  507. if (!$anime) Utils::throwError('20003:权限不足');
  508. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  509. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  510. $episode = (array)$episode;
  511. $episode['roles'] = json_decode($episode['roles'], true);
  512. // foreach($episode['roles'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  514. // }
  515. $episode['scenes'] = json_decode($episode['scenes'], true);
  516. // foreach($episode['scenes'] as &$item) {
  517. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  518. // }
  519. // 获取分镜信息
  520. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  521. ->select('*')->get()->map(function ($value) {
  522. return (array)$value;
  523. })->toArray();
  524. // 使用公共方法构建分镜结构
  525. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  526. $episode['acts'] = $segmentsStructure['acts'];
  527. $episode['total_duration'] = $segmentsStructure['total_duration'];
  528. return $episode;
  529. }
  530. public function episodeInfoForAce($data) {
  531. $anime_id = getProp($data, 'anime_id');
  532. $episode_id = getProp($data, 'episode_id');
  533. if (!$anime_id || !$episode_id) {
  534. Utils::throwError('1002:请选择剧集');
  535. }
  536. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  537. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  538. $episode = (array)$episode;
  539. $episode['roles'] = json_decode($episode['roles'], true);
  540. // foreach($episode['roles'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  542. // }
  543. $episode['scenes'] = json_decode($episode['scenes'], true);
  544. // foreach($episode['scenes'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  546. // }
  547. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  548. // 获取分镜信息
  549. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  550. ->select('*')->get()->map(function ($value) {
  551. return (array)$value;
  552. })->toArray();
  553. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  554. $episode['acts'] = $segmentsStructure['acts'];
  555. $episode['total_duration'] = $segmentsStructure['total_duration'];
  556. // 获取mp_animes表中的视频参数
  557. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  558. $episode['video_params'] = [
  559. 'video_model' => getProp($anime, 'video_model'),
  560. 'video_resolution' => getProp($anime, 'video_resolution'),
  561. 'ratio' => getProp($anime, 'video_ratio'),
  562. ];
  563. return $episode;
  564. }
  565. public function segmentInfo($data) {
  566. $uid = Site::getUid();
  567. $segment_id = getProp($data, 'segment_id');
  568. if (!$segment_id) {
  569. Utils::throwError('1002:请选择分镜');
  570. }
  571. // 获取分镜信息
  572. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  573. // 验证用户权限
  574. if ($segment) {
  575. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  576. if (!$anime) Utils::throwError('20003:权限不足');
  577. }
  578. $result = [
  579. 'segment_id' => getProp($segment, 'segment_id'),
  580. 'segment_number' => getProp($segment, 'segment_number'),
  581. 'segment_content' => getProp($segment, 'segment_content'),
  582. 'description' => getProp($segment, 'description'),
  583. 'composition' => getProp($segment, 'composition'),
  584. 'camera_movement' => getProp($segment, 'camera_movement'),
  585. 'voice_actor' => getProp($segment, 'voice_actor'),
  586. 'dialogue' => getProp($segment, 'dialogue'),
  587. 'frame_type' => getProp($segment, 'frame_type'),
  588. 'scene' => getProp($segment, 'scene'),
  589. 'characters' => getProp($segment, 'characters'),
  590. 'tail_frame' => getProp($segment, 'tail_frame'),
  591. 'emotion' => getProp($segment, 'emotion'),
  592. 'emotion_type' => getProp($segment, 'emotion_type'),
  593. 'gender' => getProp($segment, 'gender'),
  594. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  595. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  596. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  597. 'pitch' => getProp($segment, 'pitch'),
  598. 'voice_name' => getProp($segment, 'voice_name'),
  599. 'voice_type' => getProp($segment, 'voice_type'),
  600. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  601. 'img_url' => getProp($segment, 'img_url'),
  602. 'video_url' => getProp($segment, 'video_url'),
  603. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  604. ];
  605. return $result;
  606. }
  607. public function copyEpisodeVersion($data) {
  608. $episode_id = getProp($data, 'episode_id');
  609. $uid = Site::getUid();
  610. $cpid = Site::getCpid();
  611. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  612. if (!$episode) Utils::throwError('20003:该剧集不存在');
  613. $episode = (array)$episode;
  614. $anime_id = $episode['anime_id'];
  615. $episode_number = $episode['episode_number'];
  616. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  617. $sequence = $count + 1;
  618. unset($episode['id']);
  619. $now = date('Y-m-d H:i:s');
  620. $episode['created_at'] = $now;
  621. $episode['updated_at'] = $now;
  622. $episode['is_default'] = 1;
  623. // 获取版本中含有"(副本"字样的个数
  624. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  625. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  626. $episode['sequence'] = $sequence;
  627. $episode['is_generated'] = 0;
  628. $episode['cpid'] = $cpid;
  629. // 获取ace_mode
  630. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  631. try {
  632. DB::beginTransaction();
  633. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  634. // 新增副本
  635. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  636. if (!$new_episode_id) {
  637. Utils::throwError('20003:创建副本失败!');
  638. }
  639. // 获取分镜数据并准备插入
  640. $segments_for_insert = DB::table('mp_episode_segments')
  641. ->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')
  642. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  643. $item = (array)$item;
  644. $item['episode_id'] = $new_episode_id;
  645. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  646. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  647. return $item;
  648. })->toArray();
  649. // 写入分镜数据
  650. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  651. if (!$boolen2) {
  652. Utils::throwError('20003:写入分镜数据失败!');
  653. }
  654. // 写入对话历史
  655. $records = [
  656. [
  657. 'uid' => $uid,
  658. 'anime_id' => $anime_id,
  659. 'role' => 'user',
  660. 'content' => '创建副本',
  661. 'sequence' => $episode_number,
  662. 'episode_id' => $new_episode_id,
  663. 'created_at' => $now,
  664. 'updated_at' => $now
  665. ],
  666. [
  667. 'uid' => $uid,
  668. 'anime_id' => $anime_id,
  669. 'role' => 'assistant',
  670. 'content' => '好的,已为您创建副本',
  671. 'sequence' => $episode_number,
  672. 'episode_id' => $new_episode_id,
  673. 'created_at' => $now,
  674. 'updated_at' => $now
  675. ]
  676. ];
  677. $boolen3 = DB::table('mp_anime_records')->insert($records);
  678. if (!$boolen3) {
  679. Utils::throwError('20003:对话记录保存失败');
  680. }
  681. }catch (\Exception $e) {
  682. DB::rollBack();
  683. Utils::throwError('20003:'.$e->getMessage());
  684. }
  685. DB::commit();
  686. // 构建与 episodeInfo 方法一致的返回数据结构
  687. $result = [
  688. 'episode_id' => $new_episode_id,
  689. 'anime_id' => $anime_id,
  690. 'episode_number' => $episode_number,
  691. 'title' => $episode['title'],
  692. 'intro' => $episode['intro'],
  693. 'art_style' => $episode['art_style'],
  694. 'roles' => json_decode($episode['roles'], true),
  695. 'scenes' => json_decode($episode['scenes'], true),
  696. 'is_generated' => (int)$episode['is_generated']
  697. ];
  698. if ((int)$ace_mode === 1) {
  699. // 获取分镜信息
  700. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  701. ->select('*')->get()->map(function ($value) {
  702. return (array)$value;
  703. })->toArray();
  704. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  705. }else {
  706. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  707. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  708. }
  709. $result['acts'] = $segmentsStructure['acts'];
  710. $result['total_duration'] = $segmentsStructure['total_duration'];
  711. return $result;
  712. }
  713. public function episodeVersions($data) {
  714. $anime_id = getProp($data, 'anime_id');
  715. $episode_id = getProp($data, 'episode_id');
  716. if (!$anime_id || !$episode_id) {
  717. Utils::throwError('1002:请选择剧集');
  718. }
  719. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  720. $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) {
  721. return (array)$value;
  722. })->toArray();
  723. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  724. foreach($episodes as &$episode) {
  725. $episode['version'] = 'V'.$episode['sequence'];
  726. $episode['roles'] = json_decode($episode['roles'], true);
  727. $episode['scenes'] = json_decode($episode['scenes'], true);
  728. // 获取分镜信息
  729. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  730. ->select('*')->get()->map(function ($value) {
  731. return (array)$value;
  732. })->toArray();
  733. // 使用公共方法构建分镜结构
  734. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  735. $episode['acts'] = $segmentsStructure['acts'];
  736. $episode['total_duration'] = $segmentsStructure['total_duration'];
  737. }
  738. return $episodes;
  739. }
  740. public function bindEpisodeVersion($data) {
  741. $episode_id = getProp($data, 'episode_id');
  742. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  743. if (!$episode) Utils::throwError('20003:该剧集不存在');
  744. $episode = (array)$episode;
  745. if ((int)$episode['is_default'] === 1) return true;
  746. try {
  747. DB::beginTransaction();
  748. // 移除is_default标志
  749. $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')]);
  750. if (!$boolen) {
  751. Utils::throwError('20003:更新失败!');
  752. }
  753. // 绑定副本
  754. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  755. if (!$boolen2) {
  756. Utils::throwError('20003:绑定失败!');
  757. }
  758. }catch (\Exception $e) {
  759. DB::rollBack();
  760. Utils::throwError('20003:'.$e->getMessage());
  761. }
  762. DB::commit();
  763. return true;
  764. }
  765. public function chatChangeImg($data) {
  766. $segment_id = getProp($data, 'segment_id');
  767. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  768. $prompt = getProp($data, 'prompt');
  769. if (!$prompt || !$segment_id) {
  770. Utils::throwError('1002:请输入提示词,并且选择分镜');
  771. }
  772. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  773. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  774. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  775. else $ref_img_url = '';
  776. // $ref_img_url = '';
  777. if (empty($prompt)) {
  778. if (empty($ref_img_url)) {
  779. $prompt = getProp($segment, 'segment_content');
  780. }else {
  781. $prompt = '请根据图片生成';
  782. }
  783. }
  784. $anime_id = getProp($segment, 'anime_id');
  785. $episode_id = getProp($segment, 'episode_id');
  786. $episode_number = getProp($segment, 'episode_number');
  787. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  788. $ratio = getProp($data, 'ratio');
  789. if (!$ratio) {
  790. $ratio = getProp($episode, 'ratio');
  791. if (!$ratio) $ratio = '9:16';
  792. }
  793. $art_style = getProp($episode, 'art_style');
  794. if ($art_style) {
  795. $prompt = "美术风格:{$art_style}\n{$prompt}";
  796. }
  797. $dimensions = $this->getRatioDimensions($ratio);
  798. $width = $dimensions['width'];
  799. $height = $dimensions['height'];
  800. try {
  801. $params = [
  802. 'alias_segment_id' => $segment_id,
  803. 'prompt' => $prompt,
  804. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  805. 'width' => $width,
  806. 'height' => $height
  807. ];
  808. // 优化提示词(不要生成字幕)
  809. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  810. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  811. $task_id = $task->id;
  812. if (!$task_id) {
  813. Utils::throwError("20003:生成图片失败");
  814. }
  815. // 更新任务ID
  816. $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')]);
  817. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  818. } catch (\Exception $e) {
  819. Utils::throwError("20003:" . $e->getMessage());
  820. }
  821. // 创建任务之后先暂停10s等待异步任务完成
  822. sleep(10);
  823. $img_url = $this->loopGetPicTaskResult($task_id);
  824. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  825. // 图片生成后新增对话记录
  826. try {
  827. $uid = Site::getUid();
  828. $now = date('Y-m-d H:i:s');
  829. // 使用AI反推图片提示词
  830. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  831. // 保存对话记录
  832. $records = [
  833. [
  834. 'uid' => $uid,
  835. 'anime_id' => $anime_id,
  836. 'sequence' => $episode_number,
  837. 'role' => 'user',
  838. 'content' => $prompt,
  839. 'segment_id' => $segment_id,
  840. 'pic_task_id' => $task_id,
  841. 'image_url' => '',
  842. 'created_at' => $now,
  843. 'updated_at' => $now
  844. ],
  845. [
  846. 'uid' => $uid,
  847. 'anime_id' => $anime_id,
  848. 'sequence' => $episode_number,
  849. 'role' => 'assistant',
  850. 'content' => $pic_prompt,
  851. 'segment_id' => $segment_id,
  852. 'pic_task_id' => $task_id,
  853. 'image_url' => $img_url,
  854. 'created_at' => $now,
  855. 'updated_at' => $now
  856. ]
  857. ];
  858. DB::table('mp_anime_records')->insert($records);
  859. } catch (\Exception $e) {
  860. // 记录日志但不影响主流程
  861. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  862. 'segment_id' => $segment_id,
  863. 'img_url' => $img_url
  864. ]);
  865. logDB('anime', 'error', '保存对话记录失败', [
  866. 'segment_id' => $segment_id,
  867. 'img_url' => $img_url,
  868. 'error' => $e->getMessage()
  869. ]);
  870. }
  871. return $img_url;
  872. }
  873. public function segmentChatHistory($data) {
  874. $segment_id = getProp($data, 'segment_id');
  875. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  876. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'created_at');
  877. $chat = $query->orderBy('id')->get()->map(function ($value) {
  878. $value = (array)$value;
  879. $value['created_at'] = transDate($value['created_at']);
  880. return $value;
  881. })->toArray();
  882. // 获取历史图片
  883. $url = [];
  884. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  885. foreach($pic_history as $task) {
  886. $result_url = getProp($task, 'result_url');
  887. if (is_json($result_url)) {
  888. $url = array_merge($url, json_decode($result_url, true));
  889. }else {
  890. $url[] = $result_url;
  891. }
  892. }
  893. // 获取历史视频
  894. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  895. foreach($video_history as $task) {
  896. $result_url = getProp($task, 'compressed_url');
  897. if (is_json($result_url)) {
  898. $url = array_merge($url, json_decode($result_url, true));
  899. }else {
  900. $url[] = $result_url;
  901. }
  902. }
  903. return compact('chat', 'url');
  904. }
  905. public function changeEpisodeRoles($data) {
  906. $anime_id = getProp($data, 'anime_id');
  907. $episode_id = getProp($data, 'episode_id');
  908. $target_roles = getProp($data, 'roles');
  909. $is_deleted = getProp($data, 'is_deleted', 0);
  910. // 参数验证
  911. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  912. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  913. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  914. // 验证剧集是否存在
  915. $episode = DB::table('mp_anime_episodes')
  916. ->where('anime_id', $anime_id)
  917. ->where('id', $episode_id)
  918. ->first();
  919. if (!$episode) Utils::throwError('20003:该剧集不存在');
  920. $roles = json_decode(getProp($episode, 'roles'), true);
  921. // 获取anime信息,检查是否有关联的script_id
  922. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  923. if (!$anime) Utils::throwError('20003:动漫不存在');
  924. $script_id = getProp($anime, 'script_id');
  925. $episode_number = getProp($episode, 'episode_number', 1);
  926. $uid = Site::getUid();
  927. $cpid = Site::getCpid();
  928. try {
  929. $target_role_name = getProp($target_roles, 'role');
  930. if (empty($target_role_name)) {
  931. Utils::throwError('20003:角色名称不能为空');
  932. }
  933. // 如果是删除操作
  934. if ($is_deleted == 1) {
  935. // 从角色列表中移除该角色
  936. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  937. return getProp($role, 'role') !== $target_role_name;
  938. }));
  939. // 更新角色列表
  940. $result = DB::table('mp_anime_episodes')
  941. ->where('anime_id', $anime_id)
  942. ->where('id', $episode_id)
  943. ->update([
  944. 'roles' => json_encode($roles, 256),
  945. 'updated_at' => date('Y-m-d H:i:s')
  946. ]);
  947. if ($result === false) {
  948. Utils::throwError('20003:删除角色失败');
  949. }
  950. } else {
  951. // 新增或更新操作
  952. $role_found = false;
  953. $is_new_role = false;
  954. // 查找并更新已存在的角色
  955. foreach($roles as &$role) {
  956. if (getProp($role, 'role') === $target_role_name) {
  957. $role = $target_roles;
  958. $role_found = true;
  959. break;
  960. }
  961. }
  962. // 如果角色不存在,则新增
  963. if (!$role_found) {
  964. $roles[] = $target_roles;
  965. $is_new_role = true;
  966. }
  967. // 更新角色列表
  968. $result = DB::table('mp_anime_episodes')
  969. ->where('anime_id', $anime_id)
  970. ->where('id', $episode_id)
  971. ->update([
  972. 'roles' => json_encode($roles, 256),
  973. 'updated_at' => date('Y-m-d H:i:s')
  974. ]);
  975. if ($result === false) {
  976. Utils::throwError('20003:更新角色列表失败');
  977. }
  978. // 同步更新分镜表中对应主体的音色信息
  979. $voice_name = getProp($target_roles, 'voice_name');
  980. $voice_type = getProp($target_roles, 'voice_type');
  981. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  982. DB::table('mp_episode_segments')
  983. ->where('anime_id', $anime_id)
  984. ->where('episode_id', $episode_id)
  985. ->where('voice_actor', $target_role_name)
  986. ->update([
  987. 'voice_name' => $voice_name,
  988. 'voice_type' => $voice_type,
  989. 'voice_audio_url' => $voice_audio_url,
  990. 'updated_at' => date('Y-m-d H:i:s')
  991. ]);
  992. // 如果有关联的script_id,则同步到mp_products表
  993. if ($script_id) {
  994. // 查询剧本信息
  995. $script = DB::table('mp_scripts')
  996. ->where('id', $script_id)
  997. ->where('is_deleted', 0)
  998. ->first();
  999. if ($script) {
  1000. $script_name = $script->script_name ?? 'script_' . $script_id;
  1001. $product_name = getProp($target_roles, 'role');
  1002. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1003. $url = getProp($target_roles, 'url', '');
  1004. $product_type = 1; // 1=角色
  1005. // 查找或创建以script_name命名的文件夹
  1006. $folder = DB::table('mp_products')
  1007. ->where('cpid', $cpid)
  1008. ->where('type', 2) // 文件夹类型
  1009. ->where('product', $product_type) // 角色类型
  1010. ->where('product_name', $script_name)
  1011. ->where('parent_id', 0)
  1012. ->where('is_deleted', 0)
  1013. ->first();
  1014. if (!$folder) {
  1015. // 创建文件夹
  1016. $folder_id = DB::table('mp_products')->insertGetId([
  1017. 'user_id' => $uid,
  1018. 'cpid' => $cpid,
  1019. 'type' => 2, // 文件夹
  1020. 'product' => $product_type, // 角色类型
  1021. 'parent_id' => 0,
  1022. 'level' => 1,
  1023. 'product_name' => $script_name,
  1024. 'sort_order' => time(),
  1025. 'is_deleted' => 0,
  1026. 'created_at' => date('Y-m-d H:i:s'),
  1027. 'updated_at' => date('Y-m-d H:i:s')
  1028. ]);
  1029. } else {
  1030. $folder_id = $folder->id;
  1031. }
  1032. // 查找该文件夹下是否已存在同名资产
  1033. $existing_product = DB::table('mp_products')
  1034. ->where('cpid', $cpid)
  1035. ->where('type', 1) // 资产类型
  1036. ->where('product', $product_type)
  1037. ->where('parent_id', $folder_id)
  1038. ->where('product_name', $product_name)
  1039. ->where('is_deleted', 0)
  1040. ->first();
  1041. if ($existing_product) {
  1042. // 更新已存在的资产
  1043. $updateData = [
  1044. 'pic_task_status' => '生成成功',
  1045. ];
  1046. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1047. if ($url) $updateData['url'] = $url;
  1048. // 处理versions字段
  1049. $versions = getProp($target_roles, 'versions', []);
  1050. if ($versions && is_array($versions)) {
  1051. $updateData['versions'] = json_encode($versions, 256);
  1052. }
  1053. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1054. DB::table('mp_products')
  1055. ->where('id', $existing_product->id)
  1056. ->update($updateData);
  1057. $product_id = $existing_product->id;
  1058. } else {
  1059. // 创建新资产
  1060. $versions = getProp($target_roles, 'versions', []);
  1061. $product_id = DB::table('mp_products')->insertGetId([
  1062. 'user_id' => $uid,
  1063. 'cpid' => $cpid,
  1064. 'type' => 1, // 资产
  1065. 'product' => $product_type, // 角色
  1066. 'parent_id' => $folder_id,
  1067. 'level' => 2,
  1068. 'product_name' => $product_name,
  1069. 'url' => $url,
  1070. 'pic_prompt' => $pic_prompt,
  1071. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1072. 'sort_order' => time(),
  1073. 'is_deleted' => 0,
  1074. 'pic_task_status' => '生成成功',
  1075. 'created_at' => date('Y-m-d H:i:s'),
  1076. 'updated_at' => date('Y-m-d H:i:s')
  1077. ]);
  1078. }
  1079. // 建立或更新绑定关系
  1080. $existing_mapping = DB::table('mp_script_product_mappings')
  1081. ->where('script_id', $script_id)
  1082. ->where('product_id', $product_id)
  1083. ->where('episode_number', $episode_number)
  1084. ->first();
  1085. if (!$existing_mapping) {
  1086. // 创建绑定关系
  1087. DB::table('mp_script_product_mappings')->insert([
  1088. 'script_id' => $script_id,
  1089. 'product_id' => $product_id,
  1090. 'episode_number' => $episode_number,
  1091. 'created_at' => date('Y-m-d H:i:s'),
  1092. 'updated_at' => date('Y-m-d H:i:s')
  1093. ]);
  1094. }
  1095. }
  1096. }
  1097. }
  1098. } catch (\Exception $e) {
  1099. dLog('anime')->error('更新剧集角色失败', [
  1100. 'anime_id' => $anime_id,
  1101. 'episode_id' => $episode_id,
  1102. 'error' => $e->getMessage()
  1103. ]);
  1104. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1105. }
  1106. return true;
  1107. }
  1108. public function changeEpisodeScenes($data) {
  1109. $anime_id = getProp($data, 'anime_id');
  1110. $episode_id = getProp($data, 'episode_id');
  1111. $target_scenes = getProp($data, 'scenes');
  1112. $is_deleted = getProp($data, 'is_deleted', 0);
  1113. // 参数验证
  1114. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1115. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1116. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1117. // 验证剧集是否存在
  1118. $episode = DB::table('mp_anime_episodes')
  1119. ->where('anime_id', $anime_id)
  1120. ->where('id', $episode_id)
  1121. ->first();
  1122. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1123. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1124. // 获取anime信息,检查是否有关联的script_id
  1125. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1126. if (!$anime) Utils::throwError('20003:动漫不存在');
  1127. $script_id = getProp($anime, 'script_id');
  1128. $episode_number = getProp($episode, 'episode_number', 1);
  1129. $uid = Site::getUid();
  1130. $cpid = Site::getCpid();
  1131. try {
  1132. $target_scene_name = getProp($target_scenes, 'scene');
  1133. if (empty($target_scene_name)) {
  1134. Utils::throwError('20003:场景名称不能为空');
  1135. }
  1136. // 如果是删除操作
  1137. if ($is_deleted == 1) {
  1138. // 从场景列表中移除该场景
  1139. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1140. return getProp($scene, 'scene') !== $target_scene_name;
  1141. }));
  1142. // 更新场景列表
  1143. $result = DB::table('mp_anime_episodes')
  1144. ->where('anime_id', $anime_id)
  1145. ->where('id', $episode_id)
  1146. ->update([
  1147. 'scenes' => json_encode($scenes, 256),
  1148. 'updated_at' => date('Y-m-d H:i:s')
  1149. ]);
  1150. if ($result === false) {
  1151. Utils::throwError('20003:删除场景失败');
  1152. }
  1153. } else {
  1154. // 新增或更新操作
  1155. $scene_found = false;
  1156. $is_new_scene = false;
  1157. // 查找并更新已存在的场景
  1158. foreach($scenes as &$scene) {
  1159. if (getProp($scene, 'scene') === $target_scene_name) {
  1160. $scene = $target_scenes;
  1161. $scene_found = true;
  1162. break;
  1163. }
  1164. }
  1165. // 如果场景不存在,则新增
  1166. if (!$scene_found) {
  1167. $scenes[] = $target_scenes;
  1168. $is_new_scene = true;
  1169. }
  1170. // 更新场景列表
  1171. $result = DB::table('mp_anime_episodes')
  1172. ->where('anime_id', $anime_id)
  1173. ->where('id', $episode_id)
  1174. ->update([
  1175. 'scenes' => json_encode($scenes, 256),
  1176. 'updated_at' => date('Y-m-d H:i:s')
  1177. ]);
  1178. if ($result === false) {
  1179. Utils::throwError('20003:更新场景列表失败');
  1180. }
  1181. // 如果有关联的script_id,则同步到mp_products表
  1182. if ($script_id) {
  1183. // 查询剧本信息
  1184. $script = DB::table('mp_scripts')
  1185. ->where('id', $script_id)
  1186. ->where('is_deleted', 0)
  1187. ->first();
  1188. if ($script) {
  1189. $script_name = $script->script_name ?? 'script_' . $script_id;
  1190. $product_name = getProp($target_scenes, 'scene');
  1191. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1192. $url = getProp($target_scenes, 'url', '');
  1193. $product_type = 2; // 2=场景
  1194. // 查找或创建以script_name命名的文件夹
  1195. $folder = DB::table('mp_products')
  1196. ->where('cpid', $cpid)
  1197. ->where('type', 2) // 文件夹类型
  1198. ->where('product', $product_type) // 场景类型
  1199. ->where('product_name', $script_name)
  1200. ->where('parent_id', 0)
  1201. ->where('is_deleted', 0)
  1202. ->first();
  1203. if (!$folder) {
  1204. // 创建文件夹
  1205. $folder_id = DB::table('mp_products')->insertGetId([
  1206. 'user_id' => $uid,
  1207. 'cpid' => $cpid,
  1208. 'type' => 2, // 文件夹
  1209. 'product' => $product_type, // 场景类型
  1210. 'parent_id' => 0,
  1211. 'level' => 1,
  1212. 'product_name' => $script_name,
  1213. 'sort_order' => time(),
  1214. 'is_deleted' => 0,
  1215. 'created_at' => date('Y-m-d H:i:s'),
  1216. 'updated_at' => date('Y-m-d H:i:s')
  1217. ]);
  1218. } else {
  1219. $folder_id = $folder->id;
  1220. }
  1221. // 查找该文件夹下是否已存在同名资产
  1222. $existing_product = DB::table('mp_products')
  1223. ->where('cpid', $cpid)
  1224. ->where('type', 1) // 资产类型
  1225. ->where('product', $product_type)
  1226. ->where('parent_id', $folder_id)
  1227. ->where('product_name', $product_name)
  1228. ->where('is_deleted', 0)
  1229. ->first();
  1230. if ($existing_product) {
  1231. // 更新已存在的资产
  1232. $updateData = [
  1233. 'pic_task_status' => '生成成功'
  1234. ];
  1235. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1236. if ($url) $updateData['url'] = $url;
  1237. // 处理versions字段
  1238. $versions = getProp($target_scenes, 'versions', []);
  1239. if ($versions && is_array($versions)) {
  1240. $updateData['versions'] = json_encode($versions, 256);
  1241. }
  1242. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1243. DB::table('mp_products')
  1244. ->where('id', $existing_product->id)
  1245. ->update($updateData);
  1246. $product_id = $existing_product->id;
  1247. } else {
  1248. // 创建新资产
  1249. $versions = getProp($target_scenes, 'versions', []);
  1250. $product_id = DB::table('mp_products')->insertGetId([
  1251. 'user_id' => $uid,
  1252. 'cpid' => $cpid,
  1253. 'type' => 1, // 资产
  1254. 'product' => $product_type, // 场景
  1255. 'parent_id' => $folder_id,
  1256. 'level' => 2,
  1257. 'product_name' => $product_name,
  1258. 'url' => $url,
  1259. 'pic_prompt' => $pic_prompt,
  1260. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1261. 'sort_order' => time(),
  1262. 'is_deleted' => 0,
  1263. 'pic_task_status' => '生成成功',
  1264. 'created_at' => date('Y-m-d H:i:s'),
  1265. 'updated_at' => date('Y-m-d H:i:s')
  1266. ]);
  1267. }
  1268. // 建立或更新绑定关系
  1269. $existing_mapping = DB::table('mp_script_product_mappings')
  1270. ->where('script_id', $script_id)
  1271. ->where('product_id', $product_id)
  1272. ->where('episode_number', $episode_number)
  1273. ->first();
  1274. if (!$existing_mapping) {
  1275. // 创建绑定关系
  1276. DB::table('mp_script_product_mappings')->insert([
  1277. 'script_id' => $script_id,
  1278. 'product_id' => $product_id,
  1279. 'episode_number' => $episode_number,
  1280. 'created_at' => date('Y-m-d H:i:s'),
  1281. 'updated_at' => date('Y-m-d H:i:s')
  1282. ]);
  1283. }
  1284. }
  1285. }
  1286. }
  1287. } catch (\Exception $e) {
  1288. dLog('anime')->error('更新剧集场景失败', [
  1289. 'anime_id' => $anime_id,
  1290. 'episode_id' => $episode_id,
  1291. 'error' => $e->getMessage()
  1292. ]);
  1293. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1294. }
  1295. return true;
  1296. }
  1297. public function changeEpisodeProps($data) {
  1298. $anime_id = getProp($data, 'anime_id');
  1299. $episode_id = getProp($data, 'episode_id');
  1300. $target_props = getProp($data, 'props');
  1301. $is_deleted = getProp($data, 'is_deleted', 0);
  1302. // 参数验证
  1303. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1304. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1305. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1306. // 验证剧集是否存在
  1307. $episode = DB::table('mp_anime_episodes')
  1308. ->where('anime_id', $anime_id)
  1309. ->where('id', $episode_id)
  1310. ->first();
  1311. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1312. $props = json_decode(getProp($episode, 'props'), true);
  1313. // 获取anime信息,检查是否有关联的script_id
  1314. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1315. if (!$anime) Utils::throwError('20003:动漫不存在');
  1316. $script_id = getProp($anime, 'script_id');
  1317. $episode_number = getProp($episode, 'episode_number', 1);
  1318. $uid = Site::getUid();
  1319. $cpid = Site::getCpid();
  1320. try {
  1321. $target_prop_name = getProp($target_props, 'prop');
  1322. if (empty($target_prop_name)) {
  1323. Utils::throwError('20003:道具名称不能为空');
  1324. }
  1325. // 如果是删除操作
  1326. if ($is_deleted == 1) {
  1327. // 从道具列表中移除该道具
  1328. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1329. return getProp($prop, 'prop') !== $target_prop_name;
  1330. }));
  1331. // 更新道具列表
  1332. $result = DB::table('mp_anime_episodes')
  1333. ->where('anime_id', $anime_id)
  1334. ->where('id', $episode_id)
  1335. ->update([
  1336. 'props' => json_encode($props, 256),
  1337. 'updated_at' => date('Y-m-d H:i:s')
  1338. ]);
  1339. if ($result === false) {
  1340. Utils::throwError('20003:删除道具失败');
  1341. }
  1342. } else {
  1343. // 新增或更新操作
  1344. $prop_found = false;
  1345. $is_new_prop = false;
  1346. // 查找并更新已存在的道具
  1347. foreach($props as &$prop) {
  1348. if (getProp($prop, 'prop') === $target_prop_name) {
  1349. $prop = $target_props;
  1350. $prop_found = true;
  1351. break;
  1352. }
  1353. }
  1354. // 如果道具不存在,则新增
  1355. if (!$prop_found) {
  1356. $props[] = $target_props;
  1357. $is_new_prop = true;
  1358. }
  1359. // 更新道具列表
  1360. $result = DB::table('mp_anime_episodes')
  1361. ->where('anime_id', $anime_id)
  1362. ->where('id', $episode_id)
  1363. ->update([
  1364. 'props' => json_encode($props, 256),
  1365. 'updated_at' => date('Y-m-d H:i:s')
  1366. ]);
  1367. if ($result === false) {
  1368. Utils::throwError('20003:更新道具列表失败');
  1369. }
  1370. // 如果有关联的script_id,则同步到mp_products表
  1371. if ($script_id) {
  1372. // 查询剧本信息
  1373. $script = DB::table('mp_scripts')
  1374. ->where('id', $script_id)
  1375. ->where('is_deleted', 0)
  1376. ->first();
  1377. if ($script) {
  1378. $script_name = $script->script_name ?? 'script_' . $script_id;
  1379. $product_name = getProp($target_props, 'prop');
  1380. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1381. $url = getProp($target_props, 'url', '');
  1382. $product_type = 3; // 3=道具
  1383. // 查找或创建以script_name命名的文件夹
  1384. $folder = DB::table('mp_products')
  1385. ->where('cpid', $cpid)
  1386. ->where('type', 2) // 文件夹类型
  1387. ->where('product', $product_type) // 道具类型
  1388. ->where('product_name', $script_name)
  1389. ->where('parent_id', 0)
  1390. ->where('is_deleted', 0)
  1391. ->first();
  1392. if (!$folder) {
  1393. // 创建文件夹
  1394. $folder_id = DB::table('mp_products')->insertGetId([
  1395. 'user_id' => $uid,
  1396. 'cpid' => $cpid,
  1397. 'type' => 2, // 文件夹
  1398. 'product' => $product_type, // 道具类型
  1399. 'parent_id' => 0,
  1400. 'level' => 1,
  1401. 'product_name' => $script_name,
  1402. 'sort_order' => time(),
  1403. 'is_deleted' => 0,
  1404. 'created_at' => date('Y-m-d H:i:s'),
  1405. 'updated_at' => date('Y-m-d H:i:s')
  1406. ]);
  1407. } else {
  1408. $folder_id = $folder->id;
  1409. }
  1410. // 查找该文件夹下是否已存在同名资产
  1411. $existing_product = DB::table('mp_products')
  1412. ->where('cpid', $cpid)
  1413. ->where('type', 1) // 资产类型
  1414. ->where('product', $product_type)
  1415. ->where('parent_id', $folder_id)
  1416. ->where('product_name', $product_name)
  1417. ->where('is_deleted', 0)
  1418. ->first();
  1419. if ($existing_product) {
  1420. // 更新已存在的资产
  1421. $updateData = [
  1422. 'pic_task_status' => '生成成功'
  1423. ];
  1424. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1425. if ($url) $updateData['url'] = $url;
  1426. // 处理versions字段
  1427. $versions = getProp($target_props, 'versions', []);
  1428. if ($versions && is_array($versions)) {
  1429. $updateData['versions'] = json_encode($versions, 256);
  1430. }
  1431. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1432. DB::table('mp_products')
  1433. ->where('id', $existing_product->id)
  1434. ->update($updateData);
  1435. $product_id = $existing_product->id;
  1436. } else {
  1437. // 创建新资产
  1438. $versions = getProp($target_props, 'versions', []);
  1439. $product_id = DB::table('mp_products')->insertGetId([
  1440. 'user_id' => $uid,
  1441. 'cpid' => $cpid,
  1442. 'type' => 1, // 资产
  1443. 'product' => $product_type, // 道具
  1444. 'parent_id' => $folder_id,
  1445. 'level' => 2,
  1446. 'product_name' => $product_name,
  1447. 'url' => $url,
  1448. 'pic_prompt' => $pic_prompt,
  1449. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1450. 'sort_order' => time(),
  1451. 'is_deleted' => 0,
  1452. 'pic_task_status' => '生成成功',
  1453. 'created_at' => date('Y-m-d H:i:s'),
  1454. 'updated_at' => date('Y-m-d H:i:s')
  1455. ]);
  1456. }
  1457. // 建立或更新绑定关系
  1458. $existing_mapping = DB::table('mp_script_product_mappings')
  1459. ->where('script_id', $script_id)
  1460. ->where('product_id', $product_id)
  1461. ->where('episode_number', $episode_number)
  1462. ->first();
  1463. if (!$existing_mapping) {
  1464. // 创建绑定关系
  1465. DB::table('mp_script_product_mappings')->insert([
  1466. 'script_id' => $script_id,
  1467. 'product_id' => $product_id,
  1468. 'episode_number' => $episode_number,
  1469. 'created_at' => date('Y-m-d H:i:s'),
  1470. 'updated_at' => date('Y-m-d H:i:s')
  1471. ]);
  1472. }
  1473. }
  1474. }
  1475. }
  1476. } catch (\Exception $e) {
  1477. dLog('anime')->error('更新剧集道具失败', [
  1478. 'anime_id' => $anime_id,
  1479. 'episode_id' => $episode_id,
  1480. 'error' => $e->getMessage()
  1481. ]);
  1482. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1483. }
  1484. return true;
  1485. }
  1486. public function editSegment($data) {
  1487. $segment_id = getProp($data, 'segment_id');
  1488. $segment_content = getProp($data, 'segment_content');
  1489. $image_url = getProp($data, 'image_url');
  1490. $video_url = getProp($data, 'video_url');
  1491. // 参数验证
  1492. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1493. // 验证分镜是否存在
  1494. $segment = DB::table('mp_episode_segments')
  1495. ->where('segment_id', $segment_id)
  1496. ->first();
  1497. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1498. $dubTaskId = 0;
  1499. try {
  1500. DB::beginTransaction();
  1501. // 准备更新数据
  1502. $update_data = [
  1503. 'updated_at' => date('Y-m-d H:i:s')
  1504. ];
  1505. if ($segment_content) {
  1506. // 先将segment_content赋值到update_data
  1507. $update_data['segment_content'] = $segment_content;
  1508. // 使用现有方法分析segment_content,提取各个字段
  1509. $this->handleSegmentContent($update_data);
  1510. // 如果有对话内容,创建视频配音合成任务
  1511. $dialogue = getProp($update_data, 'dialogue');
  1512. if (!empty($dialogue)) {
  1513. $now = date('Y-m-d H:i:s');
  1514. $generate_json = [
  1515. 'text' => $dialogue,
  1516. 'role' => getProp($update_data, 'voice_actor'),
  1517. 'voice_type' => getProp($update_data, 'voice_type'),
  1518. 'voice_name' => getProp($update_data, 'voice_name'),
  1519. 'emotion' => getProp($update_data, 'emotion'),
  1520. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1521. 'gender' => getProp($update_data, 'gender'),
  1522. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1523. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1524. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1525. 'pitch' => getProp($update_data, 'pitch', 0),
  1526. ];
  1527. // 插入视频配音合成任务
  1528. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1529. 'alias_segment_id' => $segment_id,
  1530. 'generate_status' => '执行中',
  1531. 'audio_url' => '',
  1532. 'generate_json' => json_encode($generate_json, 256),
  1533. 'created_at' => $now,
  1534. 'updated_at' => $now,
  1535. ]);
  1536. if (!$dubTaskId) {
  1537. Utils::throwError('20003:创建配音任务失败!');
  1538. }
  1539. $update_data['audio_url'] = '';
  1540. } else {
  1541. // dialogue为空时,直接写入默认音频信息
  1542. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1543. $update_data['audio_duration'] = 2.0;
  1544. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1545. }
  1546. }
  1547. if ($image_url) {
  1548. $update_data['img_url'] = $image_url;
  1549. // 同时写入一个简单的图片生成任务
  1550. $pic_task = [
  1551. 'alias_segment_id' => $segment_id,
  1552. 'ref_img_url' => json_encode([]),
  1553. 'status' => 'success',
  1554. 'result_url' => json_encode([$image_url], 256),
  1555. 'model' => '',
  1556. 'created_at' => date('Y-m-d H:i:s'),
  1557. 'updated_at' => date('Y-m-d H:i:s'),
  1558. ];
  1559. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1560. }
  1561. if ($video_url) {
  1562. $update_data['origin_video_url'] = $video_url;
  1563. $compressed_video_url = compressVideo($video_url);
  1564. $update_data['current_type'] = 2;
  1565. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1566. // 同时写入一个简单的视频生成任务
  1567. $video_task = [
  1568. 'alias_segment_id' => $segment_id,
  1569. 'status' => 'success',
  1570. 'result_url' => $update_data['origin_video_url'],
  1571. 'compressed_url' => $update_data['video_url'],
  1572. 'created_at' => date('Y-m-d H:i:s'),
  1573. 'updated_at' => date('Y-m-d H:i:s'),
  1574. ];
  1575. DB::table('mp_generate_video_tasks')->insert($video_task);
  1576. }
  1577. // 更新分镜信息
  1578. $result = DB::table('mp_episode_segments')
  1579. ->where('segment_id', $segment_id)
  1580. ->update($update_data);
  1581. if ($result === false) {
  1582. Utils::throwError('20003:更新分镜剧本失败');
  1583. }
  1584. DB::commit();
  1585. // 如果有创建音频生成任务则调用API
  1586. if ($dubTaskId) {
  1587. // 请求远程服务器执行生成
  1588. $client = new Client(['timeout' => 300, 'verify' => false]);
  1589. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1590. $response = $result->getBody()->getContents();
  1591. $response_arr = json_decode($response, true);
  1592. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1593. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1594. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1595. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1596. Utils::throwError('20003:火山生成音频失败');
  1597. }
  1598. }
  1599. return true;
  1600. } catch (\Exception $e) {
  1601. DB::rollBack();
  1602. dLog('anime')->error('更新分镜剧本失败', [
  1603. 'segment_id' => $segment_id,
  1604. 'error' => $e->getMessage()
  1605. ]);
  1606. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1607. }
  1608. }
  1609. public function batchSetSegmentPics($data) {
  1610. $anime_id = getProp($data, 'anime_id');
  1611. $episode_id = getProp($data, 'episode_id');
  1612. $ratio = getProp($data, 'ratio');
  1613. $dimensions = $this->getRatioDimensions($ratio);
  1614. $width = $dimensions['width'];
  1615. $height = $dimensions['height'];
  1616. if (!$anime_id || !$episode_id) {
  1617. Utils::throwError('1002:请选择剧集');
  1618. }
  1619. // 获取剧集信息
  1620. $episode = DB::table('mp_anime_episodes')
  1621. ->where('anime_id', $anime_id)
  1622. ->where('id', $episode_id)
  1623. ->where('is_default', 1)
  1624. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1625. ->first();
  1626. if (!$episode) {
  1627. Utils::throwError('20003:该剧集不存在');
  1628. }
  1629. $model = getProp($data, 'model');
  1630. if (!$model) {
  1631. $model = getProp($episode, 'image_model');
  1632. if (!$model) {
  1633. // episode表也没有,使用默认值
  1634. $model = 'doubao-seedream-5-0-lite-260128';
  1635. }
  1636. }
  1637. // 验证模型是否在可用模型表中
  1638. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1639. $model = 'doubao-seedream-5-0-lite-260128';
  1640. }
  1641. $roles = json_decode(getProp($episode, 'roles'), true);
  1642. if (!$roles) {
  1643. Utils::throwError('20003:角色信息格式错误');
  1644. }
  1645. // 构建角色名称到参考图的映射
  1646. $role_map = [];
  1647. foreach ($roles as $role) {
  1648. $role_name = getProp($role, 'role');
  1649. $role_url = getProp($role, 'url');
  1650. if (!empty($role_name) && !empty($role_url)) {
  1651. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1652. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1653. // $role_map[$base_name] = $role_url;
  1654. // 同时保存完整名称的映射
  1655. $role_map[$role_name] = $role_url;
  1656. }
  1657. }
  1658. $scenes = json_decode(getProp($episode, 'roles'), true);
  1659. if (!$scenes) {
  1660. Utils::throwError('20003:场景信息格式错误');
  1661. }
  1662. // 构建角色名称到参考图的映射
  1663. $scene_map = [];
  1664. foreach ($scenes as $scene) {
  1665. $scene_name = getProp($scene, 'scene');
  1666. $scene_url = getProp($scene, 'url');
  1667. if (!empty($scene_name) && !empty($scene_url)) {
  1668. $scene_map[$scene_name] = $scene_url;
  1669. }
  1670. }
  1671. // 获取所有分镜信息
  1672. $segments = DB::table('mp_episode_segments')
  1673. ->where('anime_id', $anime_id)
  1674. ->where('episode_id', $episode_id)
  1675. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1676. ->orderBy('segment_number')
  1677. ->get()
  1678. ->toArray();
  1679. if (empty($segments)) {
  1680. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1681. }
  1682. // 保存图片比例
  1683. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1684. $updated_segments = [];
  1685. $failed_segments = [];
  1686. // 批量为每个分镜生成图片任务
  1687. foreach ($segments as $segment) {
  1688. $segment_id = $segment->segment_id;
  1689. $segment_content = $segment->segment_content;
  1690. if (empty($segment_content)) {
  1691. $failed_segments[] = [
  1692. 'segment_id' => $segment_id,
  1693. 'error' => '分镜内容为空'
  1694. ];
  1695. continue;
  1696. }
  1697. try {
  1698. $dubTaskId = 0;
  1699. // 解析分镜内容,提取画面描述作为主要提示词
  1700. $prompt = $segment_content;
  1701. $ref_img_urls = [];
  1702. // 分镜场景
  1703. $scene = getProp($segment, 'scene');
  1704. $matched_scene = '';
  1705. if (isset($scene_map[$scene])) {
  1706. $img_index = count($ref_img_urls) + 1;
  1707. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1708. $ref_img_urls[] = $scene_map[$scene];
  1709. $matched_scene = $scene;
  1710. }
  1711. // 分镜角色
  1712. $characters = getProp($segment, 'characters');
  1713. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1714. $roles = explode(',', $characters);
  1715. // 从分镜内容中提取涉及的角色
  1716. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1717. // 获取匹配角色的参考图
  1718. foreach ($segment_characters as $character) {
  1719. if (isset($role_map[$character])) {
  1720. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1721. $img_index = count($ref_img_urls) + 1;
  1722. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1723. $ref_img_urls[] = $role_map[$character];
  1724. }
  1725. }
  1726. // 如果没有找到匹配的角色参考图,不使用参考图
  1727. if (empty($ref_img_urls)) {
  1728. $ref_img_urls = [];
  1729. }
  1730. // 准备生成任务参数
  1731. $params = [
  1732. 'model' => $model,
  1733. 'alias_segment_id' => $segment_id,
  1734. 'prompt' => $prompt,
  1735. 'ref_img_urls' => $ref_img_urls,
  1736. 'width' => $width,
  1737. 'height' => $height,
  1738. ];
  1739. // 优化提示词(不要生成字幕)
  1740. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1741. // $task_id = mt_rand(100000, 999999);
  1742. // 调用AI图片生成服务
  1743. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1744. $task_id = $task->id;
  1745. if (!$task_id) {
  1746. $failed_segments[] = [
  1747. 'segment_id' => $segment_id,
  1748. 'error' => '创建生成任务失败'
  1749. ];
  1750. continue;
  1751. }
  1752. $update_data = [
  1753. 'pic_task_id' => $task_id,
  1754. 'pic_task_status' => '生成中',
  1755. 'audio_url' => '',
  1756. 'updated_at' => date('Y-m-d H:i:s')
  1757. ];
  1758. // 如果有对话内容,创建视频配音合成任务
  1759. $dialogue = getProp($segment, 'dialogue');
  1760. if (!empty($dialogue)) {
  1761. $now = date('Y-m-d H:i:s');
  1762. $generate_json = [
  1763. 'text' => $dialogue,
  1764. 'role' => getProp($segment, 'voice_actor'),
  1765. 'voice_type' => getProp($segment, 'voice_type'),
  1766. 'voice_name' => getProp($segment, 'voice_name'),
  1767. 'emotion' => getProp($segment, 'emotion'),
  1768. 'emotion_type' => getProp($segment, 'emotion_type'),
  1769. 'gender' => getProp($segment, 'gender'),
  1770. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1771. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1772. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1773. 'pitch' => getProp($segment, 'pitch', 0),
  1774. ];
  1775. // 插入视频配音合成任务
  1776. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1777. 'alias_segment_id' => $segment_id,
  1778. 'generate_status' => '执行中',
  1779. 'audio_url' => '',
  1780. 'generate_json' => json_encode($generate_json, 256),
  1781. 'created_at' => $now,
  1782. 'updated_at' => $now,
  1783. ]);
  1784. if (!$dubTaskId) {
  1785. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1786. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1787. // Utils::throwError('20003:创建配音任务失败!');
  1788. }
  1789. } else {
  1790. // dialogue为空时,直接写入默认音频信息到分镜表
  1791. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1792. $update_data['audio_duration'] = 2.0;
  1793. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1794. }
  1795. // 更新分镜的任务信息
  1796. $update_result = DB::table('mp_episode_segments')
  1797. ->where('segment_id', $segment_id)
  1798. ->update($update_data);
  1799. // 如果是第一集的首帧图片,则存入待更新数组
  1800. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1801. Redis::sadd('anime_first_frame_urls', $segment_id);
  1802. }
  1803. if ($update_result) {
  1804. $updated_segments[] = [
  1805. 'segment_id' => $segment_id,
  1806. 'task_id' => $task_id,
  1807. 'status' => '生成中',
  1808. 'matched_scenes' => $matched_scene,
  1809. 'matched_roles' => $segment_characters,
  1810. 'ref_urls_count' => count($ref_img_urls)
  1811. ];
  1812. } else {
  1813. $failed_segments[] = [
  1814. 'segment_id' => $segment_id,
  1815. 'error' => '更新分镜任务状态失败'
  1816. ];
  1817. }
  1818. if ($dubTaskId) {
  1819. sleep(1);
  1820. // 请求远程服务器执行生成
  1821. $client = new Client(['timeout' => 300, 'verify' => false]);
  1822. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1823. $response = $result->getBody()->getContents();
  1824. $response_arr = json_decode($response, true);
  1825. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1826. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1827. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1828. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1829. }
  1830. }
  1831. } catch (\Exception $e) {
  1832. $failed_segments[] = [
  1833. 'segment_id' => $segment_id,
  1834. 'error' => $e->getMessage()
  1835. ];
  1836. }
  1837. }
  1838. // 更新剧集生成状态
  1839. if (!empty($updated_segments)) {
  1840. DB::table('mp_anime_episodes')
  1841. ->where('id', $episode_id)
  1842. ->update([
  1843. 'is_generated' => 1,
  1844. 'updated_at' => date('Y-m-d H:i:s')
  1845. ]);
  1846. }
  1847. return [
  1848. 'success_count' => count($updated_segments),
  1849. 'failed_count' => count($failed_segments),
  1850. 'success_segments' => $updated_segments,
  1851. 'failed_segments' => $failed_segments,
  1852. 'total_segments' => count($segments)
  1853. ];
  1854. }
  1855. public function reGenerateSegment($data) {
  1856. $segment_id = getProp($data, 'segment_id');
  1857. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1858. $anime_id = getProp($segment, 'anime_id');
  1859. $episode_id = getProp($segment, 'episode_id');
  1860. $episode_number = getProp($segment, 'episode_number');
  1861. $segment_content = getProp($data, 'segment_content');
  1862. $ratio = getProp($data, 'ratio');
  1863. if (!$ratio) {
  1864. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1865. if (!$ratio) $ratio = '9:16';
  1866. }
  1867. $dimensions = $this->getRatioDimensions($ratio);
  1868. $width = $dimensions['width'];
  1869. $height = $dimensions['height'];
  1870. if (!$anime_id || !$episode_id) {
  1871. Utils::throwError('1002:请选择分镜');
  1872. }
  1873. // 使用文生文模型重新解析segment_content
  1874. if (!empty($segment_content)) {
  1875. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1876. }
  1877. // 获取动漫的角色信息(包含参考图)
  1878. $anime = DB::table('mp_animes')
  1879. ->where('id', $anime_id)
  1880. ->select('roles', 'scenes')
  1881. ->first();
  1882. if (!$anime || !$anime->roles) {
  1883. Utils::throwError('20003:未找到角色信息');
  1884. }
  1885. $roles = json_decode($anime->roles, true);
  1886. if (!$roles) {
  1887. Utils::throwError('20003:角色信息格式错误');
  1888. }
  1889. // 构建角色名称到参考图的映射
  1890. $role_map = [];
  1891. foreach ($roles as $role) {
  1892. $role_name = getProp($role, 'role');
  1893. $role_url = getProp($role, 'url');
  1894. if (!empty($role_name) && !empty($role_url)) {
  1895. $role_map[$role_name] = $role_url;
  1896. }
  1897. }
  1898. $scenes = json_decode($anime->scenes, true);
  1899. if (!$scenes) {
  1900. Utils::throwError('20003:角色信息格式错误');
  1901. }
  1902. // 构建角色名称到参考图的映射
  1903. $scene_map = [];
  1904. foreach ($scenes as $scene) {
  1905. $scene_name = getProp($scene, 'scene');
  1906. $scene_url = getProp($scene, 'url');
  1907. if (!empty($scene_name) && !empty($scene_url)) {
  1908. $scene_map[$scene_name] = $scene_url;
  1909. }
  1910. }
  1911. $segment_id = $segment->segment_id;
  1912. $original_segment_content = $segment->segment_content;
  1913. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1914. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1915. if (empty($final_segment_content)) {
  1916. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1917. }
  1918. try {
  1919. $dubTaskId = 0;
  1920. // 分镜剧本数组
  1921. $update_data = [
  1922. 'segment_content' => $final_segment_content,
  1923. 'pic_task_status' => '生成中',
  1924. 'updated_at' => date('Y-m-d H:i:s')
  1925. ];
  1926. // 解析分镜内容,提取画面描述作为主要提示词
  1927. $prompt = $final_segment_content;
  1928. $ref_img_urls = [];
  1929. // 分镜场景
  1930. $scene = getProp($data, 'scene');
  1931. if ($scene) {
  1932. $matched_scene = '';
  1933. if (isset($scene_map[$scene])) {
  1934. $img_index = count($ref_img_urls) + 1;
  1935. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1936. $ref_img_urls[] = $scene_map[$scene];
  1937. $matched_scene = $scene;
  1938. }
  1939. $update_data['scene'] = $scene;
  1940. }
  1941. // 分镜角色
  1942. $characters = getProp($data, 'characters');
  1943. if ($characters) {
  1944. $update_data['characters'] = $characters;
  1945. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1946. $characters = explode(',', $characters);
  1947. // 从分镜内容中提取涉及的角色
  1948. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1949. // 获取匹配角色的参考图
  1950. foreach ($segment_characters as $character) {
  1951. if (isset($role_map[$character])) {
  1952. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1953. $img_index = count($ref_img_urls) + 1;
  1954. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1955. $ref_img_urls[] = $role_map[$character];
  1956. }
  1957. }
  1958. }
  1959. // 如果没有找到匹配的角色参考图,不使用参考图
  1960. if (empty($ref_img_urls)) {
  1961. $ref_img_urls = [];
  1962. }
  1963. // 准备生成任务参数
  1964. $params = [
  1965. 'alias_segment_id' => $segment_id,
  1966. 'prompt' => $prompt,
  1967. 'ref_img_urls' => $ref_img_urls,
  1968. 'width' => $width,
  1969. 'height' => $height,
  1970. ];
  1971. // 优化提示词(不要生成字幕)
  1972. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1973. // 调用AI图片生成服务
  1974. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1975. $task_id = $task->id;
  1976. if (!$task_id) {
  1977. Utils::throwError('20003:创建生成任务失败!');
  1978. }
  1979. $update_data['pic_task_id'] = $task_id;
  1980. // 更新分镜剧本信息
  1981. $this->handleSegmentContent($update_data);
  1982. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1983. if ($segment_content) {
  1984. $dialogue = getProp($update_data, 'dialogue');
  1985. if (!empty($dialogue)) {
  1986. $now = date('Y-m-d H:i:s');
  1987. $generate_json = [
  1988. 'text' => $dialogue,
  1989. 'role' => getProp($update_data, 'voice_actor'),
  1990. 'voice_type' => getProp($update_data, 'voice_type'),
  1991. 'voice_name' => getProp($update_data, 'voice_name'),
  1992. 'emotion' => getProp($update_data, 'emotion'),
  1993. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1994. 'gender' => getProp($update_data, 'gender'),
  1995. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1996. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1997. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1998. 'pitch' => getProp($update_data, 'pitch', 0),
  1999. ];
  2000. // 插入视频配音合成任务
  2001. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2002. 'alias_segment_id' => $segment_id,
  2003. 'generate_status' => '执行中',
  2004. 'audio_url' => '',
  2005. 'generate_json' => json_encode($generate_json, 256),
  2006. 'created_at' => date('Y-m-d H:i:s'),
  2007. 'updated_at' => date('Y-m-d H:i:s'),
  2008. ]);
  2009. if (!$dubTaskId) {
  2010. Utils::throwError('20003:创建配音任务失败!');
  2011. }
  2012. $update_data['audio_url'] = '';
  2013. } else {
  2014. // dialogue为空时,直接写入默认音频信息
  2015. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2016. $update_data['audio_duration'] = 2.0;
  2017. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2018. }
  2019. }
  2020. $boolen = DB::table('mp_episode_segments')
  2021. ->where('segment_id', $segment_id)
  2022. ->update($update_data);
  2023. // 如果是第一集的首帧图片,则存入待更新数组
  2024. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2025. Redis::sadd('anime_first_frame_urls', $segment_id);
  2026. }
  2027. if ($dubTaskId) {
  2028. // 请求远程服务器执行生成
  2029. $client = new Client(['timeout' => 300, 'verify' => false]);
  2030. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2031. $response = $result->getBody()->getContents();
  2032. $response_arr = json_decode($response, true);
  2033. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2034. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2035. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2036. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2037. Utils::throwError('20003:火山生成音频失败');
  2038. }
  2039. }
  2040. } catch (\Exception $e) {
  2041. $failed_segments[] = [
  2042. 'segment_id' => $segment_id,
  2043. 'error' => $e->getMessage()
  2044. ];
  2045. }
  2046. // 创建任务之后先暂停10s等待异步任务完成
  2047. sleep(10);
  2048. $img_url = $this->loopGetPicTaskResult($task_id);
  2049. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2050. // 图片生成后新增对话记录
  2051. try {
  2052. $uid = Site::getUid();
  2053. $now = date('Y-m-d H:i:s');
  2054. // 使用AI反推图片提示词
  2055. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2056. // 保存对话记录
  2057. $records = [
  2058. [
  2059. 'uid' => $uid,
  2060. 'anime_id' => $anime_id,
  2061. 'sequence' => $episode_number,
  2062. 'role' => 'user',
  2063. 'content' => '重新生成',
  2064. 'segment_id' => $segment_id,
  2065. 'pic_task_id' => $task_id,
  2066. 'image_url' => '',
  2067. 'created_at' => $now,
  2068. 'updated_at' => $now
  2069. ],
  2070. [
  2071. 'uid' => $uid,
  2072. 'anime_id' => $anime_id,
  2073. 'sequence' => $episode_number,
  2074. 'role' => 'assistant',
  2075. 'content' => $pic_prompt,
  2076. 'segment_id' => $segment_id,
  2077. 'pic_task_id' => $task_id,
  2078. 'image_url' => $img_url,
  2079. 'created_at' => $now,
  2080. 'updated_at' => $now
  2081. ]
  2082. ];
  2083. DB::table('mp_anime_records')->insert($records);
  2084. } catch (\Exception $e) {
  2085. // 记录日志但不影响主流程
  2086. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2087. 'segment_id' => $segment_id,
  2088. 'img_url' => $img_url
  2089. ]);
  2090. }
  2091. return $img_url;
  2092. }
  2093. public function addSegment($data) {
  2094. $prev_segment_id = getProp($data, 'prev_segment_id');
  2095. $img_url = getProp($data, 'img_url');
  2096. $video_url = getProp($data, 'video_url');
  2097. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2098. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2099. $anime_id = getProp($segment, 'anime_id');
  2100. $episode_id = getProp($segment, 'episode_id');
  2101. $episode_number = getProp($segment, 'episode_number');
  2102. $segment_number = getProp($segment, 'segment_number');
  2103. $new_segment_number = $segment_number + 1;
  2104. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2105. // 分镜剧本数组
  2106. $insert_data = [
  2107. 'anime_id' => $anime_id,
  2108. 'episode_id' => $episode_id,
  2109. 'episode_number' => $episode_number,
  2110. 'act_number' => getProp($segment, 'act_number'),
  2111. 'act_title' => getProp($segment, 'act_title'),
  2112. 'segment_id' => $segment_id,
  2113. 'segment_number' => $new_segment_number,
  2114. 'segment_content' => '',
  2115. 'img_url' => '',
  2116. 'video_url' => '',
  2117. 'created_at' => date('Y-m-d H:i:s'),
  2118. 'updated_at' => date('Y-m-d H:i:s')
  2119. ];
  2120. if ($img_url) $insert_data['img_url'] = $img_url;
  2121. if ($video_url) {
  2122. $insert_data['origin_video_url'] = $video_url;
  2123. $insert_data['current_type'] = 2;
  2124. $compressed_video_url = compressVideo($video_url);
  2125. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2126. }
  2127. try {
  2128. DB::beginTransaction();
  2129. // 先更新序号
  2130. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2131. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2132. if (!$id) {
  2133. Utils::throwError('20003:新增分镜失败!');
  2134. }
  2135. }catch (\Exception $e) {
  2136. DB::rollBack();
  2137. Utils::throwError('20003:'.$e->getMessage());
  2138. }
  2139. DB::commit();
  2140. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2141. $segment = $segment ? (array)$segment : [];
  2142. return $segment;
  2143. // 以下代码暂弃用
  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. $segment_content = getProp($data, 'segment_content');
  2149. $img_url = getProp($data, 'img_url');
  2150. $video_url = getProp($data, 'video_url');
  2151. $ratio = getProp($data, 'ratio');
  2152. $dimensions = $this->getRatioDimensions($ratio);
  2153. $width = $dimensions['width'];
  2154. $height = $dimensions['height'];
  2155. if (!$anime_id || !$episode_id) {
  2156. Utils::throwError('1002:请选择分镜');
  2157. }
  2158. // 使用文生文模型重新解析segment_content
  2159. if (!empty($segment_content)) {
  2160. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2161. }
  2162. // 获取动漫的角色信息(包含参考图)
  2163. $anime = DB::table('mp_animes')
  2164. ->where('id', $anime_id)
  2165. ->select('roles', 'scenes')
  2166. ->first();
  2167. if (!$anime || !$anime->roles) {
  2168. Utils::throwError('20003:未找到角色信息');
  2169. }
  2170. $roles = json_decode($anime->roles, true);
  2171. if (!$roles) {
  2172. Utils::throwError('20003:角色信息格式错误');
  2173. }
  2174. // 构建角色名称到参考图的映射
  2175. $role_map = [];
  2176. foreach ($roles as $role) {
  2177. $role_name = getProp($role, 'role');
  2178. $role_url = getProp($role, 'url');
  2179. if (!empty($role_name) && !empty($role_url)) {
  2180. $role_map[$role_name] = $role_url;
  2181. }
  2182. }
  2183. $scenes = json_decode($anime->scenes, true);
  2184. if (!$scenes) {
  2185. Utils::throwError('20003:角色信息格式错误');
  2186. }
  2187. // 构建角色名称到参考图的映射
  2188. $scene_map = [];
  2189. foreach ($scenes as $scene) {
  2190. $scene_name = getProp($scene, 'scene');
  2191. $scene_url = getProp($scene, 'url');
  2192. if (!empty($scene_name) && !empty($scene_url)) {
  2193. $scene_map[$scene_name] = $scene_url;
  2194. }
  2195. }
  2196. $segment_id = $segment->segment_id;
  2197. $original_segment_content = $segment->segment_content;
  2198. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2199. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2200. if (empty($final_segment_content)) {
  2201. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2202. }
  2203. try {
  2204. $dubTaskId = 0;
  2205. DB::beginTransaction();
  2206. $new_segment_number = $segment_number + 1;
  2207. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2208. // 分镜剧本数组
  2209. $insert_data = [
  2210. 'anime_id' => $anime_id,
  2211. 'episode_id' => $episode_id,
  2212. 'episode_number' => $episode_number,
  2213. 'act_number' => getProp($segment, 'act_number'),
  2214. 'act_title' => getProp($segment, 'act_title'),
  2215. 'segment_id' => $segment_id,
  2216. 'segment_number' => $new_segment_number,
  2217. 'segment_content' => $final_segment_content,
  2218. 'img_url' => $img_url,
  2219. 'video_url' => $video_url,
  2220. 'created_at' => date('Y-m-d H:i:s'),
  2221. 'updated_at' => date('Y-m-d H:i:s')
  2222. ];
  2223. // 更新分镜剧本信息
  2224. $this->handleSegmentContent($insert_data);
  2225. // 如果有对话内容,创建视频配音合成任务
  2226. $dialogue = getProp($insert_data, 'dialogue');
  2227. if (!empty($dialogue)) {
  2228. $now = date('Y-m-d H:i:s');
  2229. $generate_json = [
  2230. 'text' => $dialogue,
  2231. 'role' => getProp($insert_data, 'voice_actor'),
  2232. 'voice_type' => getProp($insert_data, 'voice_type'),
  2233. 'voice_name' => getProp($insert_data, 'voice_name'),
  2234. 'emotion' => getProp($insert_data, 'emotion'),
  2235. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2236. 'gender' => getProp($insert_data, 'gender'),
  2237. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2238. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2239. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2240. 'pitch' => getProp($insert_data, 'pitch', 0),
  2241. ];
  2242. // 插入视频配音合成任务
  2243. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2244. 'alias_segment_id' => $segment_id,
  2245. 'generate_status' => '执行中',
  2246. 'audio_url' => '',
  2247. 'generate_json' => json_encode($generate_json, 256),
  2248. 'created_at' => $now,
  2249. 'updated_at' => $now,
  2250. ]);
  2251. if (!$dubTaskId) {
  2252. Utils::throwError('20003:创建配音任务失败!');
  2253. }
  2254. $insert_data['audio_url'] = '';
  2255. } else {
  2256. // dialogue为空时,直接写入默认音频信息
  2257. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2258. $insert_data['audio_duration'] = 2.0;
  2259. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2260. }
  2261. // 如果没有上传图片则使用当前描述进行生成
  2262. if (!$img_url) {
  2263. // 解析分镜内容,提取画面描述作为主要提示词
  2264. $prompt = $final_segment_content;
  2265. $ref_img_urls = [];
  2266. // 分镜场景
  2267. $scene = getProp($insert_data, 'scene');
  2268. if ($scene) {
  2269. $matched_scene = '';
  2270. if (isset($scene_map[$scene])) {
  2271. $img_index = count($ref_img_urls) + 1;
  2272. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2273. $ref_img_urls[] = $scene_map[$scene];
  2274. $matched_scene = $scene;
  2275. }
  2276. $update_data['scene'] = $scene;
  2277. }
  2278. // 分镜角色
  2279. $characters = getProp($insert_data, 'characters');
  2280. if ($characters) {
  2281. $update_data['characters'] = $characters;
  2282. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2283. $characters = explode(',', $characters);
  2284. // 从分镜内容中提取涉及的角色
  2285. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2286. // 获取匹配角色的参考图
  2287. foreach ($segment_characters as $character) {
  2288. if (isset($role_map[$character])) {
  2289. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2290. $img_index = count($ref_img_urls) + 1;
  2291. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2292. $ref_img_urls[] = $role_map[$character];
  2293. }
  2294. }
  2295. }
  2296. // 如果没有找到匹配的角色参考图,不使用参考图
  2297. if (empty($ref_img_urls)) {
  2298. $ref_img_urls = [];
  2299. }
  2300. // 准备生成任务参数
  2301. $params = [
  2302. 'alias_segment_id' => $segment_id,
  2303. 'prompt' => $prompt,
  2304. 'ref_img_urls' => $ref_img_urls,
  2305. 'width' => $width,
  2306. 'height' => $height,
  2307. ];
  2308. // 调用AI图片生成服务
  2309. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2310. $task_id = $task->id;
  2311. // $task_id = 'whatever';
  2312. if (!$task_id) {
  2313. Utils::throwError('20003:创建生成任务失败!');
  2314. }
  2315. $insert_data['pic_task_status'] = '生成中';
  2316. $insert_data['pic_task_id'] = $task_id;
  2317. }
  2318. // 先更新序号
  2319. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2320. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2321. if (!$boolen) {
  2322. Utils::throwError('20003:新增分镜失败!');
  2323. }
  2324. // 如果是第一集的首帧图片,则存入待更新数组
  2325. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2326. Redis::sadd('anime_first_frame_urls', $segment_id);
  2327. }
  2328. if ($dubTaskId) {
  2329. // 请求远程服务器执行生成
  2330. $client = new Client(['timeout' => 300, 'verify' => false]);
  2331. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2332. $response = $result->getBody()->getContents();
  2333. $response_arr = json_decode($response, true);
  2334. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2335. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2336. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2337. Utils::throwError('20003:火山生成音频失败');
  2338. }
  2339. }
  2340. } catch (\Exception $e) {
  2341. DB::rollBack();
  2342. Utils::throwError('20003:'.$e->getMessage());
  2343. }
  2344. DB::commit();
  2345. // 创建任务之后先暂停10s等待异步任务完成
  2346. sleep(10);
  2347. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2348. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2349. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2350. $segment = $segment ? (array)$segment : [];
  2351. return $segment;
  2352. }
  2353. public function copySegment($data) {
  2354. $segment_id = getProp($data, 'segment_id');
  2355. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2356. if (!$segment) Utils::throwError('20003:请选择分镜');
  2357. $anime_id = getProp($segment, 'anime_id');
  2358. $episode_id = getProp($segment, 'episode_id');
  2359. $episode_number = getProp($segment, 'episode_number');
  2360. $segment_number = getProp($segment, 'segment_number');
  2361. $new_segment_id = 0;
  2362. try {
  2363. DB::beginTransaction();
  2364. $segment = (array)$segment;
  2365. unset($segment['id']);
  2366. $segment['segment_number'] += 1;
  2367. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2368. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2369. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2370. // 更新其他分镜序号
  2371. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2372. // 复制分镜
  2373. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2374. if (!$id) {
  2375. Utils::throwError('20003:复制分镜失败');
  2376. }
  2377. }catch (\Exception $e) {
  2378. DB::rollBack();
  2379. Utils::throwError('20003:'.$e->getMessage());
  2380. }
  2381. DB::commit();
  2382. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2383. $segment = $segment ? (array)$segment : [];
  2384. return $segment;
  2385. }
  2386. public function moveSegment($data) {
  2387. $segment_id = getProp($data, 'segment_id');
  2388. $target_segment_id = getProp($data, 'target_segment_id');
  2389. // 获取源分镜信息
  2390. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2391. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2392. // 获取目标分镜信息
  2393. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2394. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2395. $anime_id = getProp($source_segment, 'anime_id');
  2396. $episode_id = getProp($source_segment, 'episode_id');
  2397. $episode_number = getProp($source_segment, 'episode_number');
  2398. $source_segment_number = getProp($source_segment, 'segment_number');
  2399. $target_segment_number = getProp($target_segment, 'segment_number');
  2400. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2401. $target_anime_id = getProp($target_segment, 'anime_id');
  2402. $target_episode_number = getProp($target_segment, 'episode_number');
  2403. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2404. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2405. }
  2406. // 如果源分镜和目标分镜相同,无需移动
  2407. if ($source_segment_number == $target_segment_number) {
  2408. return true;
  2409. }
  2410. try {
  2411. DB::beginTransaction();
  2412. if ($source_segment_number < $target_segment_number) {
  2413. // 向后移动:源分镜移动到目标分镜之后
  2414. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2415. DB::table('mp_episode_segments')
  2416. ->where('anime_id', $anime_id)
  2417. ->where('episode_id', $episode_id)
  2418. ->where('segment_number', '>', $source_segment_number)
  2419. ->where('segment_number', '<=', $target_segment_number)
  2420. ->decrement('segment_number');
  2421. // 2. 将源分镜移动到目标分镜之后
  2422. $new_segment_number = $target_segment_number;
  2423. } else {
  2424. // 向前移动:源分镜移动到目标分镜之后
  2425. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2426. DB::table('mp_episode_segments')
  2427. ->where('anime_id', $anime_id)
  2428. ->where('episode_id', $episode_id)
  2429. ->where('segment_number', '>', $target_segment_number)
  2430. ->where('segment_number', '<', $source_segment_number)
  2431. ->increment('segment_number');
  2432. // 2. 将源分镜移动到目标分镜之后
  2433. $new_segment_number = $target_segment_number + 1;
  2434. }
  2435. // 3. 更新源分镜的序号
  2436. $update_result = DB::table('mp_episode_segments')
  2437. ->where('segment_id', $segment_id)
  2438. ->update([
  2439. 'segment_number' => $new_segment_number,
  2440. 'updated_at' => date('Y-m-d H:i:s')
  2441. ]);
  2442. if (!$update_result) {
  2443. Utils::throwError('20003:更新分镜序号失败');
  2444. }
  2445. DB::commit();
  2446. return true;
  2447. } catch (\Exception $e) {
  2448. DB::rollBack();
  2449. Utils::throwError('20003:' . $e->getMessage());
  2450. }
  2451. }
  2452. public function delSegment($data) {
  2453. $segment_id = getProp($data, 'segment_id');
  2454. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2455. if (!$segment) Utils::throwError('20003:请选择分镜');
  2456. $anime_id = getProp($segment, 'anime_id');
  2457. $episode_id = getProp($segment, 'episode_id');
  2458. $episode_number = getProp($segment, 'episode_number');
  2459. $segment_number = getProp($segment, 'segment_number');
  2460. try {
  2461. DB::beginTransaction();
  2462. // 删除分镜
  2463. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2464. if (!$boolen) {
  2465. Utils::throwError('20003:删除分镜失败');
  2466. }
  2467. // 更新其他分镜序号
  2468. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2469. }catch (\Exception $e) {
  2470. DB::rollBack();
  2471. Utils::throwError('20003:'.$e->getMessage());
  2472. }
  2473. DB::commit();
  2474. return true;
  2475. }
  2476. public function applySegment($data) {
  2477. $segment_id = getProp($data, 'segment_id');
  2478. $url = getProp($data, 'url');
  2479. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2480. if (!$url) Utils::throwError('20003:URL不能为空');
  2481. // 获取URL的文件扩展名
  2482. $urlPath = parse_url($url, PHP_URL_PATH);
  2483. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2484. // 定义图片和视频的扩展名
  2485. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2486. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2487. // 判断是图片还是视频
  2488. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2489. if (in_array($extension, $imageExtensions)) {
  2490. // 图片类型
  2491. $updateData['img_url'] = $url;
  2492. $updateData['current_type'] = 1;
  2493. } elseif (in_array($extension, $videoExtensions)) {
  2494. // 视频类型
  2495. $updateData['video_url'] = $url;
  2496. $updateData['current_type'] = 2;
  2497. } else {
  2498. Utils::throwError('20003:不支持的文件类型');
  2499. }
  2500. // 更新分镜表
  2501. $result = DB::table('mp_episode_segments')
  2502. ->where('segment_id', $segment_id)
  2503. ->update($updateData);
  2504. if (!$result) {
  2505. Utils::throwError('20003:更新分镜失败');
  2506. }
  2507. return true;
  2508. }
  2509. public function segmentHistory($data) {
  2510. $segment_id = getProp($data, 'segment_id');
  2511. // 获取历史图片
  2512. $pics = [];
  2513. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2514. foreach($pic_history as $task) {
  2515. $result_url = getProp($task, 'result_url');
  2516. if (is_json($result_url)) {
  2517. $pics = array_merge($pics, json_decode($result_url, true));
  2518. }else {
  2519. $pics[] = $result_url;
  2520. }
  2521. }
  2522. // 获取历史视频
  2523. $videos = [];
  2524. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2525. foreach($video_history as $task) {
  2526. $result_url = getProp($task, 'result_url');
  2527. if (is_json($result_url)) {
  2528. $videos = array_merge($videos, json_decode($result_url, true));
  2529. }else {
  2530. $videos[] = $result_url;
  2531. }
  2532. }
  2533. return compact('pics', 'videos');
  2534. }
  2535. public function addAct($data) {
  2536. $prev_act_id = getProp($data, 'prev_act_id');
  2537. $act_title = getProp($data, 'act_title', '');
  2538. $act_content = getProp($data, 'act_content', '');
  2539. $act_duration = getProp($data, 'act_duration', 5);
  2540. $video_url = getProp($data, 'video_url');
  2541. // 根据prev_act_id获取记录
  2542. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2543. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2544. $anime_id = getProp($prev_segment, 'anime_id');
  2545. $episode_id = getProp($prev_segment, 'episode_id');
  2546. $episode_number = getProp($prev_segment, 'episode_number');
  2547. $prev_act_number = getProp($prev_segment, 'act_number');
  2548. // 获取新的act_number
  2549. $new_act_number = $prev_act_number + 1;
  2550. try {
  2551. DB::beginTransaction();
  2552. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2553. DB::table('mp_episode_segments')
  2554. ->where('anime_id', $anime_id)
  2555. ->where('episode_id', $episode_id)
  2556. ->where('act_number', '>', $prev_act_number)
  2557. ->increment('act_number');
  2558. // 插入新片段记录
  2559. $insert_data = [
  2560. 'anime_id' => $anime_id,
  2561. 'episode_id' => $episode_id,
  2562. 'episode_number' => $episode_number,
  2563. 'act_number' => $new_act_number,
  2564. 'created_at' => date('Y-m-d H:i:s'),
  2565. 'updated_at' => date('Y-m-d H:i:s')
  2566. ];
  2567. if ($act_title) {
  2568. $insert_data['act_title'] = $act_title;
  2569. }
  2570. if ($act_content) {
  2571. $insert_data['act_content'] = $act_content;
  2572. }
  2573. if ($act_duration) {
  2574. $insert_data['act_duration'] = $act_duration;
  2575. }
  2576. if ($video_url) {
  2577. $insert_data['origin_video_url'] = $video_url;
  2578. $insert_data['current_type'] = 2;
  2579. $compressed_video_url = compressVideo($video_url);
  2580. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2581. }
  2582. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2583. if (!$id) {
  2584. Utils::throwError('20003:新增片段失败!');
  2585. }
  2586. DB::commit();
  2587. }catch (\Exception $e) {
  2588. DB::rollBack();
  2589. Utils::throwError('20003:'.$e->getMessage());
  2590. }
  2591. $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();
  2592. $segment = $segment ? (array)$segment : [];
  2593. return $segment;
  2594. }
  2595. public function editAct($data) {
  2596. $act_id = getProp($data, 'act_id');
  2597. $act_content = getProp($data, 'act_content');
  2598. $act_duration = getProp($data, 'act_duration');
  2599. $act_title = getProp($data, 'act_title');
  2600. $image_url = getProp($data, 'image_url');
  2601. $video_url = getProp($data, 'video_url');
  2602. // 参数验证
  2603. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2604. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2605. $segment = DB::table('mp_episode_segments')
  2606. ->where('id', $act_id)
  2607. ->first();
  2608. if (!$segment) Utils::throwError('20003:该片段不存在');
  2609. try {
  2610. DB::beginTransaction();
  2611. // 准备更新数据
  2612. $update_data = [
  2613. 'updated_at' => date('Y-m-d H:i:s')
  2614. ];
  2615. // 更新act相关字段
  2616. if (!empty($act_content)) {
  2617. $update_data['act_show_content'] = $act_content;
  2618. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2619. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2620. $shot_counter = 0;
  2621. $update_data['act_show_content'] = preg_replace_callback(
  2622. '/【(?:镜头|分镜)(\d+)】/u',
  2623. function($matches) use (&$shot_counter) {
  2624. $shot_counter++;
  2625. return '【镜头' . $shot_counter . '】';
  2626. },
  2627. $update_data['act_show_content']
  2628. );
  2629. }
  2630. if (!empty($act_duration)) {
  2631. $update_data['act_duration'] = $act_duration;
  2632. }
  2633. if (!empty($act_title)) {
  2634. $update_data['act_title'] = $act_title;
  2635. }
  2636. // 处理图片上传
  2637. if ($image_url) {
  2638. $update_data['img_url'] = $image_url;
  2639. $update_data['current_type'] = 1;
  2640. // 同时写入一个图片生成任务记录
  2641. if ($act_id) {
  2642. $pic_task = [
  2643. 'alias_act_id' => $act_id,
  2644. 'ref_img_url' => json_encode([]),
  2645. 'status' => 'success',
  2646. 'result_url' => json_encode([$image_url], 256),
  2647. 'model' => '',
  2648. 'created_at' => date('Y-m-d H:i:s'),
  2649. 'updated_at' => date('Y-m-d H:i:s'),
  2650. ];
  2651. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2652. }
  2653. }
  2654. // 处理视频上传
  2655. if ($video_url) {
  2656. $update_data['origin_video_url'] = $video_url;
  2657. $compressed_video_url = compressVideo($video_url);
  2658. $update_data['current_type'] = 2;
  2659. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2660. // 同时写入一个视频生成任务记录
  2661. if ($act_id) {
  2662. $video_task = [
  2663. 'alias_act_id' => $act_id,
  2664. 'status' => 'success',
  2665. 'result_url' => $update_data['origin_video_url'],
  2666. 'compressed_url' => $update_data['video_url'],
  2667. 'created_at' => date('Y-m-d H:i:s'),
  2668. 'updated_at' => date('Y-m-d H:i:s'),
  2669. ];
  2670. DB::table('mp_generate_video_tasks')->insert($video_task);
  2671. }
  2672. }
  2673. // 更新片段信息
  2674. $result = DB::table('mp_episode_segments')
  2675. ->where('id', $act_id)
  2676. ->update($update_data);
  2677. if ($result === false) {
  2678. Utils::throwError('20003:更新片段失败');
  2679. }
  2680. DB::commit();
  2681. // 返回新复制的记录
  2682. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
  2683. $new_segment = (array)$new_segment;
  2684. return $new_segment;
  2685. } catch (\Exception $e) {
  2686. DB::rollBack();
  2687. dLog('anime')->error('更新片段失败', [
  2688. 'act_id' => $act_id,
  2689. 'error' => $e->getMessage()
  2690. ]);
  2691. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2692. }
  2693. }
  2694. public function copyAct($data) {
  2695. $act_id = getProp($data, 'act_id');
  2696. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2697. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2698. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2699. $anime_id = getProp($source_segment, 'anime_id');
  2700. $episode_id = getProp($source_segment, 'episode_id');
  2701. $episode_number = getProp($source_segment, 'episode_number');
  2702. $act_number = getProp($source_segment, 'act_number');
  2703. try {
  2704. DB::beginTransaction();
  2705. // 新act的编号
  2706. $new_act_number = $act_number + 1;
  2707. // 更新后续所有act的act_number
  2708. DB::table('mp_episode_segments')
  2709. ->where('anime_id', $anime_id)
  2710. ->where('episode_id', $episode_id)
  2711. ->where('act_number', '>', $act_number)
  2712. ->increment('act_number');
  2713. // 复制该片段记录
  2714. $segment_data = (array)$source_segment;
  2715. unset($segment_data['id']);
  2716. $segment_data['video_url'] = '';
  2717. $segment_data['video_task_id'] = '';
  2718. $segment_data['video_task_status'] = '';
  2719. $segment_data['act_number'] = $new_act_number;
  2720. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2721. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2722. if (!$id) {
  2723. Utils::throwError('20003:复制片段失败');
  2724. }
  2725. DB::commit();
  2726. }catch (\Exception $e) {
  2727. DB::rollBack();
  2728. Utils::throwError('20003:'.$e->getMessage());
  2729. }
  2730. // 返回新复制的记录
  2731. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2732. $new_segment = $new_segment ? (array)$new_segment : [];
  2733. $new_segment['act_id'] = $id;
  2734. return $new_segment;
  2735. }
  2736. public function moveAct($data) {
  2737. $act_id = getProp($data, 'act_id');
  2738. $target_act_id = getProp($data, 'target_act_id');
  2739. // 获取源片段信息
  2740. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2741. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2742. // 获取目标片段信息
  2743. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2744. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2745. $anime_id = getProp($source_segment, 'anime_id');
  2746. $episode_id = getProp($source_segment, 'episode_id');
  2747. $source_act_number = getProp($source_segment, 'act_number');
  2748. $target_act_number = getProp($target_segment, 'act_number');
  2749. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2750. $target_anime_id = getProp($target_segment, 'anime_id');
  2751. $target_episode_id = getProp($target_segment, 'episode_id');
  2752. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2753. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2754. }
  2755. // 如果源片段和目标片段相同,无需移动
  2756. if ($source_act_number == $target_act_number) {
  2757. return true;
  2758. }
  2759. try {
  2760. DB::beginTransaction();
  2761. if ($source_act_number < $target_act_number) {
  2762. // 向后移动:源片段移动到目标片段之后
  2763. // 1. 将源片段和目标片段之间的所有片段编号减1
  2764. DB::table('mp_episode_segments')
  2765. ->where('anime_id', $anime_id)
  2766. ->where('episode_id', $episode_id)
  2767. ->where('act_number', '>', $source_act_number)
  2768. ->where('act_number', '<=', $target_act_number)
  2769. ->decrement('act_number');
  2770. // 2. 将源片段移动到目标片段之后
  2771. $new_act_number = $target_act_number;
  2772. } else {
  2773. // 向前移动:源片段移动到目标片段之后
  2774. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2775. DB::table('mp_episode_segments')
  2776. ->where('anime_id', $anime_id)
  2777. ->where('episode_id', $episode_id)
  2778. ->where('act_number', '>', $target_act_number)
  2779. ->where('act_number', '<', $source_act_number)
  2780. ->increment('act_number');
  2781. // 2. 将源片段移动到目标片段之后
  2782. $new_act_number = $target_act_number + 1;
  2783. }
  2784. // 3. 更新源片段的编号
  2785. $update_result = DB::table('mp_episode_segments')
  2786. ->where('id', $act_id)
  2787. ->update([
  2788. 'act_number' => $new_act_number,
  2789. 'updated_at' => date('Y-m-d H:i:s')
  2790. ]);
  2791. if (!$update_result) {
  2792. Utils::throwError('20003:更新片段编号失败');
  2793. }
  2794. DB::commit();
  2795. return true;
  2796. } catch (\Exception $e) {
  2797. DB::rollBack();
  2798. Utils::throwError('20003:' . $e->getMessage());
  2799. }
  2800. }
  2801. public function delAct($data) {
  2802. $act_id = getProp($data, 'act_id');
  2803. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2804. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2805. if (!$segment) Utils::throwError('20003:请选择片段');
  2806. $anime_id = getProp($segment, 'anime_id');
  2807. $episode_id = getProp($segment, 'episode_id');
  2808. $act_number = getProp($segment, 'act_number');
  2809. try {
  2810. DB::beginTransaction();
  2811. // 删除该片段记录
  2812. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2813. if (!$deleted) {
  2814. Utils::throwError('20003:删除片段失败');
  2815. }
  2816. // 更新后续act的编号
  2817. DB::table('mp_episode_segments')
  2818. ->where('anime_id', $anime_id)
  2819. ->where('episode_id', $episode_id)
  2820. ->where('act_number', '>', $act_number)
  2821. ->decrement('act_number');
  2822. DB::commit();
  2823. }catch (\Exception $e) {
  2824. DB::rollBack();
  2825. Utils::throwError('20003:'.$e->getMessage());
  2826. }
  2827. return true;
  2828. }
  2829. public function applyAct($data) {
  2830. $act_id = getProp($data, 'act_id');
  2831. $url = getProp($data, 'url');
  2832. if (!$act_id) Utils::throwError('20003:请选择片段');
  2833. if (!$url) Utils::throwError('20003:URL不能为空');
  2834. // 获取URL的文件扩展名
  2835. $urlPath = parse_url($url, PHP_URL_PATH);
  2836. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2837. // 定义图片和视频的扩展名
  2838. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2839. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2840. // 判断是图片还是视频
  2841. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2842. if (in_array($extension, $imageExtensions)) {
  2843. // 图片类型
  2844. $updateData['img_url'] = $url;
  2845. $updateData['current_type'] = 1;
  2846. } elseif (in_array($extension, $videoExtensions)) {
  2847. // 视频类型
  2848. $updateData['video_url'] = $url;
  2849. $updateData['current_type'] = 2;
  2850. } else {
  2851. Utils::throwError('20003:不支持的文件类型');
  2852. }
  2853. // 更新片段记录(全能模式下每个act只有一条记录)
  2854. $result = DB::table('mp_episode_segments')
  2855. ->where('id', $act_id)
  2856. ->update($updateData);
  2857. if (!$result) {
  2858. Utils::throwError('20003:更新片段失败');
  2859. }
  2860. return true;
  2861. }
  2862. public function actChatHistory($data) {
  2863. $act_id = getProp($data, 'act_id');
  2864. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2865. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'reference_images', 'created_at');
  2866. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2867. $value = (array)$value;
  2868. $value['created_at'] = transDate($value['created_at']);
  2869. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2870. else $value['reference_images'] = [];
  2871. return $value;
  2872. })->toArray();
  2873. // 获取历史图片
  2874. $url = [];
  2875. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2876. foreach($pic_history as $task) {
  2877. $result_url = getProp($task, 'result_url');
  2878. if (is_json($result_url)) {
  2879. $url = array_merge($url, json_decode($result_url, true));
  2880. }else {
  2881. $url[] = $result_url;
  2882. }
  2883. }
  2884. // 获取历史视频
  2885. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2886. foreach($video_history as $task) {
  2887. $result_url = getProp($task, 'result_url');
  2888. if (is_json($result_url)) {
  2889. $url = array_merge($url, json_decode($result_url, true));
  2890. }else {
  2891. $url[] = $result_url;
  2892. }
  2893. }
  2894. // 获取资产库
  2895. $products = [];
  2896. // 通过act_id查询片段信息获取episode_id
  2897. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2898. if ($segment) {
  2899. $episode_id = getProp($segment, 'episode_id');
  2900. // 查询剧集信息获取roles、scenes和extra_products
  2901. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2902. if ($episode) {
  2903. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2904. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2905. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2906. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2907. // 先合并roles、scenes和props
  2908. // 处理角色数组
  2909. foreach ($roles as $role) {
  2910. $product = $role;
  2911. // 将role字段重命名为product_name
  2912. if (is_array($product) && !empty($product['role'] ?? null)) {
  2913. $product['product_name'] = $product['role'];
  2914. unset($product['role']);
  2915. $product['product'] = 1; // 标记类型为角色
  2916. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2917. }
  2918. }
  2919. // 处理场景数组
  2920. foreach ($scenes as $scene) {
  2921. $product = $scene;
  2922. // 将scene字段重命名为product_name
  2923. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2924. $product['product_name'] = $product['scene'];
  2925. unset($product['scene']);
  2926. $product['product'] = 2; // 标记类型为场景
  2927. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2928. }
  2929. }
  2930. // 处理道具数组
  2931. foreach ($props as $prop) {
  2932. $product = $prop;
  2933. // 将prop字段重命名为product_name
  2934. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2935. $product['product_name'] = $product['prop'];
  2936. unset($product['prop']);
  2937. $product['product'] = 3; // 标记类型为道具
  2938. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2939. }
  2940. }
  2941. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2942. foreach ($extra_products as $extra_product) {
  2943. $product_name = getProp($extra_product, 'product_name');
  2944. if ($product_name) {
  2945. $products[$product_name] = $extra_product; // 覆盖同名数据
  2946. }
  2947. }
  2948. // 重新索引数组(去除key)
  2949. $products = array_values($products);
  2950. }
  2951. }
  2952. // 获取执行中的任务
  2953. $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) {
  2954. $value = (array)$value;
  2955. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2956. else $value['ref_image_url'] = [];
  2957. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2958. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2959. if (!empty($value['prompt'])) {
  2960. $prompt = $value['prompt'];
  2961. // 查找第一个【镜头】的位置
  2962. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2963. // 从【镜头】开始截取
  2964. $prompt = substr($prompt, $matches[0][1]);
  2965. }
  2966. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2967. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2968. $value['prompt'] = $prompt;
  2969. }
  2970. return $value;
  2971. })->toArray();
  2972. return compact('chat', 'url', 'products', 'tasks');
  2973. }
  2974. public function applyAudioData($data) {
  2975. $segment_id = getProp($data, 'segment_id');
  2976. $global_data = getProp($data, 'global_data');
  2977. $segment_data = getProp($data, 'segment_data');
  2978. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2979. $global_data = is_array($global_data) ? $global_data : [];
  2980. $segment_data = is_array($segment_data) ? $segment_data : [];
  2981. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2982. $dialogue_item = null;
  2983. foreach ($global_data as $key => $item) {
  2984. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2985. $dialogue_item = $item;
  2986. unset($global_data[$key]);
  2987. break;
  2988. }
  2989. }
  2990. if ($dialogue_item) {
  2991. $segment_data[] = $dialogue_item;
  2992. }
  2993. // 特殊参数: audio_url,audio_duration,subtitle_info
  2994. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2995. // 如果不是全部存在,则仍需创建音频任务
  2996. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2997. $special_update_data = [];
  2998. $has_all_special_params = false;
  2999. // 从segment_data中提取特殊参数
  3000. $filtered_segment_data = [];
  3001. foreach ($segment_data as $item) {
  3002. $field_name = trim((string)getProp($item, 'name'));
  3003. if (in_array($field_name, $special_fields)) {
  3004. $special_update_data[$field_name] = getProp($item, 'value');
  3005. } else {
  3006. // 非特殊参数保留,继续后续处理
  3007. $filtered_segment_data[] = $item;
  3008. }
  3009. }
  3010. // 检查是否三个特殊参数都存在
  3011. if (count($special_update_data) === 3 &&
  3012. isset($special_update_data['audio_url']) &&
  3013. isset($special_update_data['audio_duration']) &&
  3014. isset($special_update_data['subtitle_info'])) {
  3015. $has_all_special_params = true;
  3016. // 立即更新到当前分镜
  3017. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3018. DB::table('mp_episode_segments')
  3019. ->where('segment_id', $segment_id)
  3020. ->update($special_update_data);
  3021. }
  3022. // 使用过滤后的segment_data继续处理其他参数
  3023. $segment_data = $filtered_segment_data;
  3024. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3025. $global_update_data = [];
  3026. $segment_update_data = [];
  3027. $global_voice_type = '';
  3028. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3029. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3030. $episode_id = getProp($target_segment, 'episode_id');
  3031. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3032. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3033. if (!$episode) Utils::throwError('20003:分集不存在');
  3034. foreach ($global_data as $item) {
  3035. $field_name = trim((string)getProp($item, 'name'));
  3036. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3037. continue;
  3038. }
  3039. $global_update_data[$field_name] = getProp($item, 'value');
  3040. if ($field_name === 'voice_type') {
  3041. $global_voice_type = trim((string)getProp($item, 'value'));
  3042. }
  3043. }
  3044. foreach ($segment_data as $item) {
  3045. $field_name = trim((string)getProp($item, 'name'));
  3046. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3047. continue;
  3048. }
  3049. $segment_update_data[$field_name] = getProp($item, 'value');
  3050. }
  3051. if ($global_voice_type) {
  3052. $timbre_info = DB::table('mp_timbres')
  3053. ->where('timbre_type', $global_voice_type)
  3054. ->select('audio_url', 'timbre_name')
  3055. ->first();
  3056. if ($timbre_info) {
  3057. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3058. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3059. }
  3060. }
  3061. try {
  3062. DB::beginTransaction();
  3063. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3064. $segment_ids_to_create_task = [];
  3065. $segments_data = [];
  3066. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3067. if (!empty($global_update_data)) {
  3068. // 如果角色不存在,则只更新当前分镜
  3069. if (!$target_voice_actor) {
  3070. // 只处理当前分镜
  3071. $affected_segments = DB::table('mp_episode_segments')
  3072. ->where('segment_id', $segment_id)
  3073. ->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')
  3074. ->get();
  3075. } else {
  3076. // 获取该角色的所有分镜
  3077. $affected_segments = DB::table('mp_episode_segments')
  3078. ->where('episode_id', $episode_id)
  3079. ->where('voice_actor', $target_voice_actor)
  3080. ->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')
  3081. ->get();
  3082. }
  3083. foreach ($affected_segments as $seg) {
  3084. $seg = (array)$seg;
  3085. $sid = getProp($seg, 'segment_id');
  3086. // 检查参数是否发生变化
  3087. $has_changed = false;
  3088. foreach ($global_update_data as $field => $new_value) {
  3089. $old_value = getProp($seg, $field);
  3090. if ($old_value != $new_value) {
  3091. $has_changed = true;
  3092. break;
  3093. }
  3094. }
  3095. if ($has_changed) {
  3096. $segment_ids_to_create_task[] = $sid;
  3097. $segments_data[$sid] = $seg;
  3098. }
  3099. }
  3100. // 只有在有变化的分镜时才更新
  3101. if (!empty($segment_ids_to_create_task)) {
  3102. $global_segment_update_data = $global_update_data;
  3103. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3104. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3105. DB::table('mp_episode_segments')
  3106. ->where('episode_id', $episode_id)
  3107. ->where('voice_actor', $target_voice_actor)
  3108. ->whereIn('segment_id', $segment_ids_to_create_task)
  3109. ->update($global_segment_update_data);
  3110. }
  3111. if ($global_voice_type) {
  3112. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3113. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3114. $roles_updated = false;
  3115. foreach ($episode_roles as &$role) {
  3116. // 通过 role 字段匹配角色名,而不是 voice_name
  3117. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3118. continue;
  3119. }
  3120. $role['voice_type'] = $global_voice_type;
  3121. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3122. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3123. $roles_updated = true;
  3124. }
  3125. unset($role);
  3126. if ($roles_updated) {
  3127. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3128. 'roles' => json_encode($episode_roles, 256),
  3129. 'updated_at' => date('Y-m-d H:i:s'),
  3130. ]);
  3131. }
  3132. }
  3133. }
  3134. // 如果有单个分镜更新,检查是否有变化
  3135. if (!empty($segment_update_data)) {
  3136. // 获取当前分镜数据
  3137. $current_segment = DB::table('mp_episode_segments')
  3138. ->where('segment_id', $segment_id)
  3139. ->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')
  3140. ->first();
  3141. if ($current_segment) {
  3142. $current_segment = (array)$current_segment;
  3143. // 检查参数是否发生变化
  3144. $has_changed = false;
  3145. foreach ($segment_update_data as $field => $new_value) {
  3146. $old_value = getProp($current_segment, $field);
  3147. if ($old_value != $new_value) {
  3148. $has_changed = true;
  3149. break;
  3150. }
  3151. }
  3152. if ($has_changed) {
  3153. // 如果该分镜还未在列表中,添加进去
  3154. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3155. $segment_ids_to_create_task[] = $segment_id;
  3156. $segments_data[$segment_id] = $current_segment;
  3157. }
  3158. // 更新分镜数据并清空音频URL
  3159. $segment_update_data['audio_url'] = '';
  3160. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3161. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3162. }
  3163. }
  3164. }
  3165. // 为所有有变化的分镜创建音频合成任务
  3166. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3167. if (!empty($segment_ids_to_create_task)) {
  3168. foreach ($segment_ids_to_create_task as $sid) {
  3169. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3170. if ($sid === $segment_id && $has_all_special_params) {
  3171. continue;
  3172. }
  3173. // 重新获取更新后的分镜数据
  3174. $updated_segment = DB::table('mp_episode_segments')
  3175. ->where('segment_id', $sid)
  3176. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3177. ->first();
  3178. if (!$updated_segment) continue;
  3179. $updated_segment = (array)$updated_segment;
  3180. // 检查dialogue是否为空
  3181. $dialogue = getProp($updated_segment, 'dialogue');
  3182. if (empty($dialogue)) {
  3183. // dialogue为空时,直接写入默认音频信息
  3184. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3185. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3186. 'audio_duration' => 2.0,
  3187. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3188. 'updated_at' => date('Y-m-d H:i:s')
  3189. ]);
  3190. continue;
  3191. }
  3192. $generate_json = [
  3193. 'text' => $dialogue,
  3194. 'role' => getProp($updated_segment, 'voice_actor'),
  3195. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3196. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3197. 'emotion' => getProp($updated_segment, 'emotion'),
  3198. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3199. 'gender' => getProp($updated_segment, 'gender'),
  3200. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3201. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3202. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3203. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3204. ];
  3205. // 插入视频配音合成任务
  3206. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3207. 'alias_segment_id' => $sid,
  3208. 'generate_status' => '执行中',
  3209. 'audio_url' => '',
  3210. 'generate_json' => json_encode($generate_json, 256),
  3211. 'created_at' => date('Y-m-d H:i:s'),
  3212. 'updated_at' => date('Y-m-d H:i:s'),
  3213. ]);
  3214. if (!$dubTaskId) {
  3215. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3216. continue;
  3217. }
  3218. // 将任务ID添加到Redis列表中
  3219. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3220. // 请求远程服务器执行生成
  3221. try {
  3222. sleep(1);
  3223. $client = new Client(['timeout' => 300, 'verify' => false]);
  3224. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3225. $response = $result->getBody()->getContents();
  3226. $response_arr = json_decode($response, true);
  3227. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3228. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3229. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3230. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3231. }
  3232. } catch (\Exception $e) {
  3233. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3234. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3235. }
  3236. }
  3237. }
  3238. DB::commit();
  3239. } catch (\Exception $e) {
  3240. DB::rollBack();
  3241. Utils::throwError('20003:'.$e->getMessage());
  3242. }
  3243. return true;
  3244. }
  3245. public function episodePicsInfo($data) {
  3246. $anime_id = getProp($data, 'anime_id');
  3247. $episode_id = getProp($data, 'episode_id');
  3248. // 参数验证
  3249. if (!$anime_id && !$episode_id) {
  3250. Utils::throwError('20003:请提供动漫ID或分集ID');
  3251. }
  3252. // 根据参数获取数据源
  3253. if ($episode_id) {
  3254. // 从剧集表获取
  3255. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3256. if (!$source) Utils::throwError('20003:该剧集不存在');
  3257. $table_name = 'mp_anime_episodes';
  3258. $id_field = 'id';
  3259. $id_value = $episode_id;
  3260. // 获取剧集的anime_id用于继承全局数据
  3261. $anime_id = getProp($source, 'anime_id');
  3262. } else {
  3263. // 从动漫表获取
  3264. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3265. if (!$source) Utils::throwError('20003:该动漫不存在');
  3266. $table_name = 'mp_animes';
  3267. $id_field = 'id';
  3268. $id_value = $anime_id;
  3269. }
  3270. $source = (array)$source;
  3271. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3272. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3273. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3274. // 如果是分集数据,需要处理继承和任务创建逻辑
  3275. if ($episode_id) {
  3276. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3277. }
  3278. // 返回生成器函数,用于 SSE 流式输出
  3279. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3280. $startTime = time();
  3281. $maxDuration = 600; // 10分钟超时
  3282. $checkInterval = 3; // 每3秒检查一次
  3283. // Redis 缓存键
  3284. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3285. // 生成当前数据的哈希值用于比较
  3286. $generateHash = function($roles, $scenes, $props) {
  3287. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3288. };
  3289. // 发送初始数据
  3290. $currentHash = $generateHash($roles, $scenes, $props);
  3291. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3292. echo "data: " . json_encode([
  3293. 'type' => 'init',
  3294. 'data' => [
  3295. 'roles' => $roles,
  3296. 'scenes' => $scenes,
  3297. 'props' => $props,
  3298. 'start_time' => $startTime
  3299. ]
  3300. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3301. if (ob_get_level() > 0) {
  3302. ob_flush();
  3303. }
  3304. flush();
  3305. // 持续轮询任务状态
  3306. while (time() - $startTime < $maxDuration) {
  3307. $hasProcessing = false;
  3308. $updated = false;
  3309. // 检查角色任务状态
  3310. foreach ($roles as $index => &$role) {
  3311. $task_id = getProp($role, 'task_id');
  3312. $task_status = getProp($role, 'task_status');
  3313. $existing_url = getProp($role, 'url');
  3314. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3315. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3316. $hasProcessing = ($task_status === 'processing');
  3317. // 查询任务状态
  3318. $task = DB::table('mp_generate_pic_tasks')
  3319. ->where('id', $task_id)
  3320. ->select('id', 'status', 'result_url', 'error_message')
  3321. ->first();
  3322. if ($task) {
  3323. $task = (array)$task;
  3324. $status = getProp($task, 'status');
  3325. // 如果任务完成或失败
  3326. if (in_array($status, ['success', 'failed'])) {
  3327. $role['task_status'] = $status;
  3328. if ($status === 'success') {
  3329. $result_url = getProp($task, 'result_url');
  3330. if ($result_url) {
  3331. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3332. if (is_array($result_urls) && !empty($result_urls[0])) {
  3333. $role['url'] = $result_urls[0];
  3334. }
  3335. }
  3336. }
  3337. $updated = true;
  3338. } else if ($status === 'processing') {
  3339. $hasProcessing = true;
  3340. }
  3341. }
  3342. }
  3343. }
  3344. // 检查场景任务状态
  3345. foreach ($scenes as $index => &$scene) {
  3346. $task_id = getProp($scene, 'task_id');
  3347. $task_status = getProp($scene, 'task_status');
  3348. $existing_url = getProp($scene, 'url');
  3349. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3350. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3351. $hasProcessing = ($task_status === 'processing');
  3352. // 查询任务状态
  3353. $task = DB::table('mp_generate_pic_tasks')
  3354. ->where('id', $task_id)
  3355. ->select('id', 'status', 'result_url', 'error_message')
  3356. ->first();
  3357. if ($task) {
  3358. $task = (array)$task;
  3359. $status = getProp($task, 'status');
  3360. // 如果任务完成或失败
  3361. if (in_array($status, ['success', 'failed'])) {
  3362. $scene['task_status'] = $status;
  3363. if ($status === 'success') {
  3364. $result_url = getProp($task, 'result_url');
  3365. if ($result_url) {
  3366. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3367. if (is_array($result_urls) && !empty($result_urls[0])) {
  3368. $scene['url'] = $result_urls[0];
  3369. }
  3370. }
  3371. }
  3372. $updated = true;
  3373. } else if ($status === 'processing') {
  3374. $hasProcessing = true;
  3375. }
  3376. }
  3377. }
  3378. }
  3379. // 检查道具任务状态
  3380. foreach ($props as $index => &$prop) {
  3381. $task_id = getProp($prop, 'task_id');
  3382. $task_status = getProp($prop, 'task_status');
  3383. $existing_url = getProp($prop, 'url');
  3384. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3385. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3386. $hasProcessing = ($task_status === 'processing');
  3387. // 查询任务状态
  3388. $task = DB::table('mp_generate_pic_tasks')
  3389. ->where('id', $task_id)
  3390. ->select('id', 'status', 'result_url', 'error_message')
  3391. ->first();
  3392. if ($task) {
  3393. $task = (array)$task;
  3394. $status = getProp($task, 'status');
  3395. // 如果任务完成或失败
  3396. if (in_array($status, ['success', 'failed'])) {
  3397. $prop['task_status'] = $status;
  3398. if ($status === 'success') {
  3399. $result_url = getProp($task, 'result_url');
  3400. if ($result_url) {
  3401. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3402. if (is_array($result_urls) && !empty($result_urls[0])) {
  3403. $prop['url'] = $result_urls[0];
  3404. }
  3405. }
  3406. }
  3407. $updated = true;
  3408. } else if ($status === 'processing') {
  3409. $hasProcessing = true;
  3410. }
  3411. }
  3412. }
  3413. }
  3414. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3415. if ($updated) {
  3416. $newHash = $generateHash($roles, $scenes, $props);
  3417. $cachedHash = Redis::get($cacheKey);
  3418. // 只有当数据真正变化时才更新数据库和发送事件
  3419. if ($newHash !== $cachedHash) {
  3420. try {
  3421. // 更新数据库
  3422. DB::table($table_name)->where($id_field, $id_value)->update([
  3423. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3424. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3425. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3426. 'updated_at' => date('Y-m-d H:i:s')
  3427. ]);
  3428. // 更新缓存
  3429. Redis::setex($cacheKey, 600, $newHash);
  3430. // 发送更新事件
  3431. echo "data: " . json_encode([
  3432. 'type' => 'update',
  3433. 'data' => [
  3434. 'roles' => $roles,
  3435. 'scenes' => $scenes,
  3436. 'props' => $props,
  3437. 'elapsed_time' => time() - $startTime
  3438. ]
  3439. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3440. if (ob_get_level() > 0) {
  3441. ob_flush();
  3442. }
  3443. flush();
  3444. } catch (\Exception $e) {
  3445. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3446. }
  3447. } else {
  3448. // 即使哈希相同,如果有URL更新也要发送事件
  3449. $hasUrlUpdate = false;
  3450. foreach ($roles as $role) {
  3451. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3452. $hasUrlUpdate = true;
  3453. break;
  3454. }
  3455. }
  3456. if (!$hasUrlUpdate) {
  3457. foreach ($scenes as $scene) {
  3458. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3459. $hasUrlUpdate = true;
  3460. break;
  3461. }
  3462. }
  3463. }
  3464. if (!$hasUrlUpdate) {
  3465. foreach ($props as $prop) {
  3466. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3467. $hasUrlUpdate = true;
  3468. break;
  3469. }
  3470. }
  3471. }
  3472. if ($hasUrlUpdate) {
  3473. // 强制更新数据库和发送事件
  3474. try {
  3475. DB::table($table_name)->where($id_field, $id_value)->update([
  3476. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3477. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3478. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3479. 'updated_at' => date('Y-m-d H:i:s')
  3480. ]);
  3481. // 更新缓存
  3482. Redis::setex($cacheKey, 600, $newHash);
  3483. // 发送更新事件
  3484. echo "data: " . json_encode([
  3485. 'type' => 'update',
  3486. 'data' => [
  3487. 'roles' => $roles,
  3488. 'scenes' => $scenes,
  3489. 'props' => $props,
  3490. 'elapsed_time' => time() - $startTime
  3491. ]
  3492. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3493. if (ob_get_level() > 0) {
  3494. ob_flush();
  3495. }
  3496. flush();
  3497. } catch (\Exception $e) {
  3498. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3499. }
  3500. }
  3501. }
  3502. }
  3503. // 如果所有任务都已完成,发送完成事件并退出
  3504. if (!$hasProcessing) {
  3505. // 查询数据库中的最终数据,确保返回最新的完整数据
  3506. try {
  3507. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3508. if ($finalSource) {
  3509. $finalSource = (array)$finalSource;
  3510. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3511. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3512. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3513. // 使用数据库中的最终数据
  3514. $roles = $finalRoles;
  3515. $scenes = $finalScenes;
  3516. $props = $finalProps;
  3517. }
  3518. } catch (\Exception $e) {
  3519. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3520. // 如果查询失败,继续使用内存中的数据
  3521. }
  3522. // 清理缓存
  3523. Redis::del($cacheKey);
  3524. echo "data: " . json_encode([
  3525. 'type' => 'completed',
  3526. 'data' => [
  3527. 'roles' => $roles,
  3528. 'scenes' => $scenes,
  3529. 'props' => $props,
  3530. 'total_time' => time() - $startTime
  3531. ]
  3532. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3533. if (ob_get_level() > 0) {
  3534. ob_flush();
  3535. }
  3536. flush();
  3537. break;
  3538. }
  3539. // 等待下次检查
  3540. sleep($checkInterval);
  3541. }
  3542. // 超时处理
  3543. if (time() - $startTime >= $maxDuration) {
  3544. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3545. try {
  3546. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3547. if ($finalSource) {
  3548. $finalSource = (array)$finalSource;
  3549. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3550. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3551. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3552. // 使用数据库中的最终数据
  3553. $roles = $finalRoles;
  3554. $scenes = $finalScenes;
  3555. $props = $finalProps;
  3556. }
  3557. } catch (\Exception $e) {
  3558. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3559. // 如果查询失败,继续使用内存中的数据
  3560. }
  3561. // 清理缓存
  3562. Redis::del($cacheKey);
  3563. echo "data: " . json_encode([
  3564. 'type' => 'timeout',
  3565. 'message' => '轮询超时,请刷新页面查看最新状态',
  3566. 'data' => [
  3567. 'roles' => $roles,
  3568. 'scenes' => $scenes,
  3569. 'props' => $props
  3570. ]
  3571. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3572. if (ob_get_level() > 0) {
  3573. ob_flush();
  3574. }
  3575. flush();
  3576. }
  3577. };
  3578. }
  3579. public function clipSegmentVideo($data) {
  3580. $segment_id = getProp($data, 'segment_id');
  3581. $video_time_point_start = getProp($data, 'video_time_point_start');
  3582. $video_time_point_end = getProp($data, 'video_time_point_end');
  3583. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3584. Utils::throwError('20003:参数异常');
  3585. }
  3586. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3587. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3588. }
  3589. $video_duration = $video_time_point_end - $video_time_point_start;
  3590. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3591. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3592. 'video_duration' => $video_duration,
  3593. 'video_time_point_start' => $video_time_point_start,
  3594. 'video_time_point_end' => $video_time_point_end,
  3595. 'updated_at' => date('Y-m-d H:i:s')
  3596. ]);
  3597. }
  3598. // 轮训获取图片任务结果
  3599. private function loopGetPicTaskResult($task_id) {
  3600. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3601. if (!$task) {
  3602. return '';
  3603. }
  3604. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3605. $model = getProp($task, 'model');
  3606. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3607. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3608. $isSyncModel = $isVolcModel || $isGptModel;
  3609. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3610. $start_count = 0;
  3611. $img_url = '';
  3612. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3613. sleep(3);
  3614. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3615. // 如果任务已经完成,直接返回结果
  3616. if ($task->status === 'success' && $task->result_url) {
  3617. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3618. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3619. }
  3620. // 如果任务已失败,返回空
  3621. if ($task->status === 'failed') {
  3622. return '';
  3623. }
  3624. if ($isSyncModel) continue;
  3625. // 查询任务状态
  3626. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3627. if ($statusInfo['status'] === 'success') {
  3628. $task->updateStatus('success', [
  3629. 'result_url' => $statusInfo['result_url'],
  3630. 'result_json' => $statusInfo['result_json'] ?? []
  3631. ]);
  3632. // 同步调整分镜图片状态和结果
  3633. if (getProp($task, 'alias_segment_id')) {
  3634. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3635. 'img_url' => $statusInfo['result_url'][0],
  3636. 'pic_task_status' => '已完成',
  3637. ]);
  3638. }
  3639. $img_url = $statusInfo['result_url'][0];
  3640. break;
  3641. } elseif ($statusInfo['status'] === 'failed') {
  3642. $task->updateStatus('failed', [
  3643. 'error_message' => $statusInfo['error_message'],
  3644. 'result_json' => $statusInfo['result_json'] ?? []
  3645. ]);
  3646. if (getProp($task, 'alias_segment_id')) {
  3647. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3648. 'pic_task_status' => '失败',
  3649. ]);
  3650. }
  3651. break;
  3652. }
  3653. $start_count++;
  3654. }
  3655. return $img_url;
  3656. }
  3657. /**
  3658. * 从分镜内容中提取涉及的角色
  3659. */
  3660. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3661. $found_characters = [];
  3662. foreach ($available_characters as $character) {
  3663. // 检查角色名称是否在分镜内容中出现
  3664. if (strpos($segment_content, $character) !== false) {
  3665. $found_characters[] = $character;
  3666. }
  3667. }
  3668. if (!$found_characters) {
  3669. foreach ($roles as $character) {
  3670. // 检查角色名称是否在分镜内容中出现
  3671. if (strpos($segment_content, $character) !== false) {
  3672. $found_characters[] = $character;
  3673. }
  3674. }
  3675. }
  3676. return array_unique($found_characters);
  3677. }
  3678. // 从分镜剧本中提取关键字段
  3679. private function handleSegmentContent(&$data) {
  3680. $segmentContent = getProp($data, 'segment_content');
  3681. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3682. $segmentData = [
  3683. 'description' => '',
  3684. 'composition' => '',
  3685. 'camera_movement' => '',
  3686. 'voice_actor' => '',
  3687. 'dialogue' => '',
  3688. 'frame_type' => '',
  3689. 'scene' => '', // 场景
  3690. 'characters' => '', // 出镜角色
  3691. 'tail_frame' => '', // 尾帧描述
  3692. 'emotion' => '中性', // 情感
  3693. 'gender' => '0', // 性别(0未知,1男,2女)
  3694. 'speed_ratio' => 0, // 语速
  3695. 'loudness_ratio' => 0, // 音量
  3696. 'emotion_scale' => 4, // 情感强度
  3697. 'pitch' => 0, // 音调
  3698. ];
  3699. // 用于存储需要从 segment_content 中移除的匹配项
  3700. $replaceEmptyArr = [];
  3701. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3702. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3703. $segmentData['description'] = trim($descMatch[1]);
  3704. $data['description'] = trim($descMatch[1]);
  3705. }
  3706. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3707. $segmentData['composition'] = trim($compMatch[1]);
  3708. $data['composition'] = trim($compMatch[1]);
  3709. }
  3710. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3711. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3712. $data['camera_movement'] = trim($cameraMatch[1]);
  3713. }
  3714. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3715. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3716. $data['voice_actor'] = trim($voiceMatch[1]);
  3717. }
  3718. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3719. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3720. $data['dialogue'] = trim($dialogueMatch[1]);
  3721. }
  3722. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3723. $segmentData['frame_type'] = trim($frameMatch[1]);
  3724. $data['frame_type'] = trim($frameMatch[1]);
  3725. }
  3726. // 场景字段
  3727. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3728. $segmentData['scene'] = trim($sceneMatch[1]);
  3729. $data['scene'] = trim($sceneMatch[1]);
  3730. }
  3731. // 出镜角色字段
  3732. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3733. $segmentData['characters'] = trim($charactersMatch[1]);
  3734. $data['characters'] = trim($charactersMatch[1]);
  3735. }
  3736. // 尾帧描述字段
  3737. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3738. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3739. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3740. }
  3741. // 情感字段
  3742. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3743. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3744. $segmentData['emotion'] = trim($emotionMatch[1]);
  3745. $data['emotion'] = trim($emotionMatch[1]);
  3746. }
  3747. // 性别字段
  3748. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3749. $replaceEmptyArr[] = trim($genderMatch[0]);
  3750. $genderStr = trim($genderMatch[1]);
  3751. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3752. $segmentData['gender'] = '1';
  3753. $data['gender'] = '1';
  3754. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3755. $segmentData['gender'] = '2';
  3756. $data['gender'] = '2';
  3757. } else {
  3758. $segmentData['gender'] = '0';
  3759. $data['gender'] = '0';
  3760. }
  3761. }
  3762. // 语速字段
  3763. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3764. $replaceEmptyArr[] = trim($speedMatch[0]);
  3765. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3766. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3767. }
  3768. // 音量字段
  3769. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3770. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3771. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3772. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3773. }
  3774. // 情感强度字段
  3775. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3776. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3777. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3778. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3779. }
  3780. // 音调字段
  3781. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3782. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3783. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3784. $data['pitch'] = (int)trim($pitchMatch[1]);
  3785. }
  3786. // 从 segment_content 中移除已提取的配音参数字段
  3787. if (!empty($replaceEmptyArr)) {
  3788. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3789. }
  3790. // 如果有配音角色,查询音色信息并验证情感
  3791. $voice_actor = $segmentData['voice_actor'];
  3792. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3793. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3794. $anime_id = getProp($data, 'anime_id');
  3795. $episode_id = getProp($data, 'episode_id');
  3796. // 优先从剧集的角色列表中查找
  3797. $roles = [];
  3798. if ($episode_id) {
  3799. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3800. if ($episode && getProp($episode, 'roles')) {
  3801. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3802. }
  3803. }
  3804. // 如果剧集中没有,从动漫的角色列表中查找
  3805. if (empty($roles) && $anime_id) {
  3806. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3807. if ($anime && getProp($anime, 'roles')) {
  3808. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3809. }
  3810. }
  3811. // 查找匹配的角色音色信息
  3812. $timbre_info = null;
  3813. foreach ($roles as $role) {
  3814. if (getProp($role, 'role') === $voice_actor) {
  3815. $timbre_info = $role;
  3816. break;
  3817. }
  3818. }
  3819. // 如果找到音色信息,添加到数据中
  3820. if ($timbre_info) {
  3821. $voice_type = getProp($timbre_info, 'voice_type');
  3822. $voice_name = getProp($timbre_info, 'voice_name');
  3823. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3824. if ($voice_type) {
  3825. $data['voice_type'] = $voice_type;
  3826. $segmentData['voice_type'] = $voice_type;
  3827. }
  3828. if ($voice_name) {
  3829. $data['voice_name'] = $voice_name;
  3830. $segmentData['voice_name'] = $voice_name;
  3831. }
  3832. if ($voice_audio_url) {
  3833. $data['voice_audio_url'] = $voice_audio_url;
  3834. $segmentData['voice_audio_url'] = $voice_audio_url;
  3835. }
  3836. // 验证情感是否在音色支持的情感列表中
  3837. if ($voice_type) {
  3838. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3839. if ($timbre_emotion) {
  3840. $timbre_emotion = explode(',', $timbre_emotion);
  3841. } else {
  3842. $timbre_emotion = [];
  3843. }
  3844. $emotion = getProp($segmentData, 'emotion', '中性');
  3845. if (!in_array($emotion, $timbre_emotion)) {
  3846. $emotion = '中性';
  3847. }
  3848. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3849. $emotion_list = array_flip($emotion_list);
  3850. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3851. $data['emotion_type'] = $emotion_type;
  3852. $segmentData['emotion_type'] = $emotion_type;
  3853. }
  3854. }
  3855. }
  3856. return $segmentData;
  3857. }
  3858. public function createSegmentVideoTask($data) {
  3859. $segment_id = getProp($data, 'segment_id');
  3860. $tail_frame = getProp($data, 'tail_frame');
  3861. $first_frame_url = getProp($data, 'first_frame_url');
  3862. $tail_frame_url = getProp($data, 'tail_frame_url');
  3863. $generate_audio = getProp($data, 'generate_audio', 0);
  3864. if (!$segment_id) {
  3865. Utils::throwError('1002:分镜ID不能为空');
  3866. }
  3867. // 获取分镜信息
  3868. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3869. if (!$segment) {
  3870. Utils::throwError('20003:分镜不存在');
  3871. }
  3872. $segment = (array)$segment;
  3873. $episode_id = getProp($segment, 'episode_id');
  3874. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3875. if (!$ratio) $ratio = '9:16';
  3876. // 获取分镜内容
  3877. $segmentContent = getProp($segment, 'segment_content', '');
  3878. // 检查 $segmentContent 中是否已有尾帧描述
  3879. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3880. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3881. $finalTailFrame = '';
  3882. if ($tail_frame) {
  3883. // 用户输入了尾帧描述,优先使用
  3884. $finalTailFrame = $tail_frame;
  3885. // 如果 segmentContent 中已有尾帧描述,需要替换
  3886. if ($contentHasTailFrame) {
  3887. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3888. }
  3889. } elseif ($contentHasTailFrame) {
  3890. // segmentContent 中有尾帧描述,使用它
  3891. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3892. } else {
  3893. // 两者都没有,使用分镜表中的尾帧描述
  3894. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3895. }
  3896. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3897. $hasDialogue = false;
  3898. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3899. $dialogue = trim($dialogueMatch[1]);
  3900. // 如果台词不为空且不是"无"
  3901. if (!empty($dialogue) && $dialogue !== '无') {
  3902. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3903. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3904. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3905. $hasDialogue = true;
  3906. }
  3907. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3908. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3909. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3910. if (!preg_match('/^[“]/', $dialogue)) {
  3911. $dialogue = '“' . $dialogue;
  3912. }
  3913. if (!preg_match('/[”]$/', $dialogue)) {
  3914. $dialogue .= '”';
  3915. }
  3916. // 将修改后的台词替换回 $segmentContent
  3917. $originalDialogue = $dialogueMatch[1];
  3918. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3919. }
  3920. }
  3921. // 构建完整的提示词
  3922. $fullPrompt = $segmentContent;
  3923. if ($finalTailFrame && !$contentHasTailFrame) {
  3924. // 只有当 segmentContent 中没有尾帧描述时才追加
  3925. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3926. }
  3927. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3928. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3929. $fullPrompt = trim($fullPrompt);
  3930. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3931. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3932. // 智能选择视频时长
  3933. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3934. $videoDuration = -1;
  3935. // 处理视频模型
  3936. $model = getProp($data, 'model');
  3937. if (!$model) {
  3938. // 用户没有输入,从episode表获取
  3939. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3940. $model = getProp($episode, 'video_model');
  3941. if (!$model) {
  3942. // episode表也没有,使用默认值
  3943. $model = 'doubao-seedance-1-5-pro-251215';
  3944. }
  3945. }
  3946. // 验证模型是否在可用模型表中
  3947. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3948. $model = 'doubao-seedance-1-5-pro-251215';
  3949. }
  3950. // 保存到episode表
  3951. $episode_id = getProp($segment, 'episode_id');
  3952. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3953. 'video_model' => $model,
  3954. 'updated_at' => date('Y-m-d H:i:s')
  3955. ]);
  3956. // 构建视频生成参数
  3957. $videoParams = [
  3958. 'model' => $model,
  3959. 'alias_segment_id' => $segment_id,
  3960. 'prompt' => trim($fullPrompt),
  3961. 'video_duration' => $videoDuration,
  3962. 'video_resolution' => '720P',
  3963. 'seed' => -1,
  3964. 'ratio' => $ratio,
  3965. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3966. 'draft' => false,
  3967. 'watermark' => false,
  3968. 'camera_fixed' => false,
  3969. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3970. ];
  3971. // 如果分镜有图片,作为首帧
  3972. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3973. $hasVideo = !empty(getProp($segment, 'video_url'));
  3974. if ($hasImage) {
  3975. if ($first_frame_url) {
  3976. $videoParams['first_frame_url'] = $first_frame_url;
  3977. }else {
  3978. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3979. }
  3980. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3981. }
  3982. // 构建content数组
  3983. $videoParams['content'] = [
  3984. [
  3985. 'type' => 'text',
  3986. 'text' => $videoParams['prompt'],
  3987. ]
  3988. ];
  3989. // 如果有首帧图片,添加到content中
  3990. if ($hasImage) {
  3991. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3992. $videoParams['content'][] = [
  3993. 'type' => 'image_url',
  3994. 'image_url' => [
  3995. 'url' => $videoParams['first_frame_url'],
  3996. ],
  3997. 'role' => 'reference_image',
  3998. ];
  3999. if (isset($videoParams['tail_frame_url'])) {
  4000. $videoParams['content'][] = [
  4001. 'type' => 'image_url',
  4002. 'image_url' => [
  4003. 'url' => $videoParams['tail_frame_url'],
  4004. ],
  4005. 'role' => 'reference_image',
  4006. ];
  4007. }
  4008. }else {
  4009. $videoParams['content'][] = [
  4010. 'type' => 'image_url',
  4011. 'image_url' => [
  4012. 'url' => $videoParams['first_frame_url'],
  4013. ],
  4014. 'role' => 'first_frame',
  4015. ];
  4016. if (isset($videoParams['tail_frame_url'])) {
  4017. $videoParams['content'][] = [
  4018. 'type' => 'image_url',
  4019. 'image_url' => [
  4020. 'url' => $videoParams['tail_frame_url'],
  4021. ],
  4022. 'role' => 'last_frame',
  4023. ];
  4024. }
  4025. }
  4026. }
  4027. // 获取配音音频URL
  4028. $audioUrl = getProp($segment, 'audio_url');
  4029. $audioDuration = getProp($segment, 'audio_duration');
  4030. // 音频传入的前提:必须有至少一张图片或一个视频
  4031. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4032. // 余额预检:按预估时长计算所需积分,不足直接报错
  4033. $chargeDuration = (int)ceil((float)$audioDuration);
  4034. if ($chargeDuration <= 0) {
  4035. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4036. }
  4037. $this->pointsService->checkUserPointsEnough(
  4038. $this->pointsService->getVideoChargePoints([
  4039. 'model' => $model,
  4040. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4041. 'video_duration' => $chargeDuration,
  4042. 'ratio' => $ratio,
  4043. 'generate_audio' => $current_generate_audio,
  4044. ])
  4045. );
  4046. // dd($videoParams);
  4047. // 根据模型选择不同的视频生成方法
  4048. if (strpos($model, 'jimeng') !== false) {
  4049. // 即梦模型参数调整
  4050. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4051. unset($videoParams['content']); // 即梦不使用content格式
  4052. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4053. } elseif (strpos($model, 'kling') !== false) {
  4054. // Keling模型参数调整
  4055. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4056. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4057. unset($videoParams['ratio']);
  4058. unset($videoParams['content']); // Keling不使用content格式
  4059. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4060. } elseif (strpos($model, 'zhizhen') !== false) {
  4061. // 智帧20等新模型使用统一API
  4062. // 构建统一API参数
  4063. $unifiedParams = [
  4064. 'model_code' => $model,
  4065. 'alias_segment_id' => $segment_id,
  4066. 'prompt' => trim($fullPrompt),
  4067. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4068. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4069. 'video_ratio' => $ratio,
  4070. 'seed' => -1,
  4071. ];
  4072. // 构建parameters参数
  4073. $parameters = [
  4074. 'seconds' => $unifiedParams['video_duration'],
  4075. 'resolution' => $unifiedParams['video_resolution'],
  4076. 'ratio' => $ratio,
  4077. // 'video_mode' => 'multi_image',
  4078. // 'mode' => 'multi_image',
  4079. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4080. ];
  4081. $hasImage = false;
  4082. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4083. if ($hasImage) {
  4084. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4085. if (isset($videoParams['tail_frame_url'])) {
  4086. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4087. }
  4088. // 只有在有图片的情况下才能添加参考音频
  4089. if ($audioUrl) {
  4090. // $parameters['reference_audios'] = [$audioUrl];
  4091. }
  4092. } else {
  4093. // 没有图片时,记录错误日志
  4094. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4095. 'segment_id' => $segment_id,
  4096. 'model' => $model
  4097. ]);
  4098. }
  4099. $unifiedParams['parameters'] = $parameters;
  4100. // 调用统一API创建任务
  4101. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4102. } else {
  4103. // Seedance模型(默认)
  4104. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4105. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4106. // 添加配音音频到content中
  4107. $videoParams['content'][] = [
  4108. 'type' => 'audio_url',
  4109. 'audio_url' => [
  4110. 'url' => $audioUrl,
  4111. ],
  4112. 'role' => 'reference_audio',
  4113. ];
  4114. // 优化提示词,增加音频相关描述
  4115. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4116. $videoParams['prompt'] = $audioPrompt;
  4117. $videoParams['content'][0]['text'] = $audioPrompt;
  4118. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4119. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4120. }
  4121. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4122. }
  4123. // 更新分镜表的视频任务信息
  4124. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4125. 'video_task_id' => $task->id,
  4126. 'video_task_status' => '生成中',
  4127. 'generate_audio' => $generate_audio,
  4128. 'updated_at' => date('Y-m-d H:i:s')
  4129. ]);
  4130. return [
  4131. 'task_id' => $task->id,
  4132. 'status' => $task->status,
  4133. 'segment_id' => $segment_id,
  4134. 'video_duration' => $videoDuration
  4135. ];
  4136. }
  4137. public function createActVideoTask($data) {
  4138. $act_id = getProp($data, 'act_id');
  4139. $first_frame_url = getProp($data, 'first_frame_url');
  4140. $tail_frame_url = getProp($data, 'tail_frame_url');
  4141. $generate_audio = getProp($data, 'generate_audio', 1);
  4142. $video_duration = getProp($data, 'video_duration');
  4143. $video_resolution = getProp($data, 'video_resolution');
  4144. $ratio = getProp($data, 'ratio');
  4145. $products = getProp($data, 'products', []);
  4146. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4147. if (!is_array($reference_images) || !is_array($products)) {
  4148. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4149. }
  4150. if (!$act_id) {
  4151. Utils::throwError('1002:片段ID不能为空');
  4152. }
  4153. // 获取片段信息
  4154. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4155. if (!$act) {
  4156. Utils::throwError('20003:片段不存在');
  4157. }
  4158. $act = (array)$act;
  4159. $anime_id = getProp($act, 'anime_id');
  4160. $episode_id = getProp($act, 'episode_id');
  4161. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4162. $ace_mode = getProp($anime, 'ace_mode');
  4163. $art_style_type = getProp($anime, 'art_style_type');
  4164. $art_style = getProp($anime, 'art_style');
  4165. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4166. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4167. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4168. // 将资产中新出现的资产放到extra_products中
  4169. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4170. if (!empty($products) && $episode) {
  4171. // 获取剧集中的角色、场景和道具列表
  4172. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4173. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4174. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4175. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4176. // 构建角色名称列表
  4177. $role_names = array_column($roles, 'role');
  4178. // 构建场景名称列表
  4179. $scene_names = array_column($scenes, 'scene');
  4180. // 构建道具名称列表
  4181. $prop_names = array_column($props, 'prop');
  4182. // 遍历传入的products
  4183. foreach ($products as $product) {
  4184. $product_name = getProp($product, 'product_name');
  4185. // 如果product_name不在roles、scenes和props中
  4186. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4187. // 查找是否在extra_products中存在同名的
  4188. $found = false;
  4189. foreach ($extra_products as $key => $extra_product) {
  4190. if (getProp($extra_product, 'product_name') === $product_name) {
  4191. // 有同名的则覆盖
  4192. $extra_products[$key] = $product;
  4193. $found = true;
  4194. break;
  4195. }
  4196. }
  4197. // 没有则新增
  4198. if (!$found) {
  4199. $extra_products[] = $product;
  4200. }
  4201. }
  4202. }
  4203. if ($extra_products) {
  4204. // 保存到数据库
  4205. DB::table('mp_anime_episodes')
  4206. ->where('id', $episode_id)
  4207. ->update([
  4208. 'extra_products' => json_encode($extra_products, 256),
  4209. 'updated_at' => date('Y-m-d H:i:s')
  4210. ]);
  4211. }
  4212. }
  4213. // 获取分镜内容
  4214. $actContent = getProp($act, 'act_show_content', '');
  4215. // 音效同出(默认使用)
  4216. $current_generate_audio = $generate_audio ? 1 : 0;
  4217. // 构建完整的提示词
  4218. $processResult = $this->processActContentWithProducts($actContent, $products);
  4219. $fullPrompt = $processResult['content'];
  4220. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4221. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4222. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4223. // 处理视频模型
  4224. $model = getProp($data, 'model');
  4225. if (!$model) {
  4226. $model = getProp($episode, 'video_model');
  4227. if (!$model) {
  4228. // episode表也没有,使用默认值
  4229. $model = 'zhizhen-20';
  4230. }
  4231. }
  4232. // 验证模型是否在可用模型表中
  4233. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4234. $model = 'zhizhen-20';
  4235. }
  4236. // 保存到episode表(仅在专用方法中更新模型)
  4237. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4238. // 'video_model' => $model,
  4239. // 'updated_at' => date('Y-m-d H:i:s')
  4240. // ]);
  4241. // 余额预检:按预估时长计算所需积分,不足直接报错
  4242. $chargeDuration = (int)$videoDuration;
  4243. if ($chargeDuration <= 0) {
  4244. $chargeDuration = 5; // 无时长时按默认5秒预估
  4245. }
  4246. $this->pointsService->checkUserPointsEnough(
  4247. $this->pointsService->getVideoChargePoints([
  4248. 'model' => $model,
  4249. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4250. 'video_duration' => $chargeDuration,
  4251. 'ratio' => $ratio,
  4252. 'generate_audio' => $current_generate_audio,
  4253. ])
  4254. );
  4255. // 构建视频生成参数
  4256. $videoParams = [
  4257. 'model' => $model,
  4258. 'alias_act_id' => $act_id,
  4259. 'prompt' => trim($fullPrompt),
  4260. 'video_duration' => $videoDuration,
  4261. 'video_resolution' => $video_resolution,
  4262. 'seed' => -1,
  4263. 'ratio' => $ratio,
  4264. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4265. 'draft' => false,
  4266. 'watermark' => false,
  4267. 'camera_fixed' => false,
  4268. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4269. ];
  4270. // 如果分镜有图片,作为首帧
  4271. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4272. $hasVideo = !empty(getProp($act, 'video_url'));
  4273. if ($hasImage) {
  4274. if ($first_frame_url) {
  4275. $videoParams['first_frame_url'] = $first_frame_url;
  4276. }else {
  4277. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4278. }
  4279. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4280. }
  4281. // 构建content数组
  4282. $videoParams['content'] = [
  4283. [
  4284. 'type' => 'text',
  4285. 'text' => $videoParams['prompt'],
  4286. ]
  4287. ];
  4288. // 如果有首帧图片,添加到content中
  4289. if ($hasImage) {
  4290. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4291. $videoParams['content'][] = [
  4292. 'type' => 'image_url',
  4293. 'image_url' => [
  4294. 'url' => $videoParams['first_frame_url'],
  4295. ],
  4296. 'role' => 'reference_image',
  4297. ];
  4298. if (isset($videoParams['tail_frame_url'])) {
  4299. $videoParams['content'][] = [
  4300. 'type' => 'image_url',
  4301. 'image_url' => [
  4302. 'url' => $videoParams['tail_frame_url'],
  4303. ],
  4304. 'role' => 'reference_image',
  4305. ];
  4306. }
  4307. }else {
  4308. $videoParams['content'][] = [
  4309. 'type' => 'image_url',
  4310. 'image_url' => [
  4311. 'url' => $videoParams['first_frame_url'],
  4312. ],
  4313. 'role' => 'first_frame',
  4314. ];
  4315. if (isset($videoParams['tail_frame_url'])) {
  4316. $videoParams['content'][] = [
  4317. 'type' => 'image_url',
  4318. 'image_url' => [
  4319. 'url' => $videoParams['tail_frame_url'],
  4320. ],
  4321. 'role' => 'last_frame',
  4322. ];
  4323. }
  4324. }
  4325. }
  4326. // dd($videoParams);
  4327. // 根据模型选择不同的视频生成方法
  4328. if (strpos($model, 'jimeng') !== false) {
  4329. // 即梦模型参数调整
  4330. unset($videoParams['content']); // 即梦不使用content格式
  4331. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4332. } elseif (strpos($model, 'kling') !== false) {
  4333. // Keling模型参数调整
  4334. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4335. unset($videoParams['ratio']);
  4336. unset($videoParams['content']); // Keling不使用content格式
  4337. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4338. } elseif (strpos($model, 'zhizhen') !== false) {
  4339. // 智帧20等新模型使用统一API
  4340. // 构建统一API参数
  4341. $unifiedParams = [
  4342. 'model_code' => $model,
  4343. 'alias_act_id' => $act_id,
  4344. 'prompt' => trim($fullPrompt),
  4345. 'video_duration' => $videoDuration,
  4346. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4347. 'video_ratio' => $ratio,
  4348. 'seed' => -1,
  4349. ];
  4350. // 构建parameters参数
  4351. $parameters = [
  4352. 'seconds' => $unifiedParams['video_duration'],
  4353. 'resolution' => $unifiedParams['video_resolution'],
  4354. 'ratio' => $ratio,
  4355. // 'video_mode' => 'multi_image',
  4356. // 'mode' => 'multi_image',
  4357. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4358. ];
  4359. $hasImage = false;
  4360. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4361. if ($hasImage) {
  4362. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4363. if (isset($videoParams['tail_frame_url'])) {
  4364. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4365. }
  4366. } else {
  4367. // 没有图片时,记录错误日志
  4368. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4369. 'act_id' => $act_id,
  4370. 'model' => $model
  4371. ]);
  4372. }
  4373. if ($reference_images) {
  4374. // 限制只传入9张参考图
  4375. $reference_images = array_slice($reference_images, 0, 9);
  4376. // 在处理之前先保存原始reference_images到任务参数中
  4377. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4378. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4379. $parameters['reference_images'] = $reference_images;
  4380. $parameters['video_mode'] = 'multi_image';
  4381. $parameters['mode'] = 'multi_image';
  4382. }
  4383. $unifiedParams['parameters'] = $parameters;
  4384. // 调用统一API创建任务
  4385. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4386. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4387. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4388. // 保存原始参考图用于任务记录
  4389. $videoParams['reference_images'] = $reference_images;
  4390. if ($reference_images) {
  4391. // 限制只传入9张参考图
  4392. $reference_images = array_slice($reference_images, 0, 9);
  4393. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4394. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4395. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4396. $videoParams['prompt'] = trim($fullPrompt);
  4397. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4398. $videoParams['reference_image_assets'] = $reference_image_assets;
  4399. }
  4400. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4401. } else {
  4402. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4403. }
  4404. // 更新分镜表的视频任务信息
  4405. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4406. 'video_task_id' => $task->id,
  4407. 'video_task_status' => '生成中',
  4408. 'generate_audio' => $generate_audio,
  4409. 'updated_at' => date('Y-m-d H:i:s')
  4410. ]);
  4411. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4412. $episode_number = getProp($act, 'episode_number');
  4413. $act_number = getProp($act, 'act_number');
  4414. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4415. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4416. }
  4417. return [
  4418. 'task_id' => $task->id,
  4419. 'status' => $task->status,
  4420. 'act_id' => $act_id,
  4421. 'video_duration' => $videoDuration
  4422. ];
  4423. }
  4424. /**
  4425. * 文生视频通用方法
  4426. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4427. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4428. *
  4429. * @param array $data 请求参数
  4430. * @return array
  4431. */
  4432. public function generateVideo($data) {
  4433. $prompt = getProp($data, 'prompt');
  4434. if (empty($prompt)) {
  4435. Utils::throwError('20003:提示词不能为空');
  4436. }
  4437. $model = getProp($data, 'model');
  4438. if (!$model) {
  4439. $model = 'zhizhen-20';
  4440. }
  4441. // 验证模型是否在可用模型表中
  4442. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4443. Utils::throwError('20003:该模型已不可用,请更换!');
  4444. }
  4445. $video_duration = getProp($data, 'video_duration', 5);
  4446. $video_resolution = getProp($data, 'video_resolution', '480p');
  4447. $ratio = getProp($data, 'ratio', '9:16');
  4448. $generate_audio = getProp($data, 'generate_audio', 1);
  4449. $seed = getProp($data, 'seed', -1);
  4450. $first_frame_url = getProp($data, 'first_frame_url');
  4451. $tail_frame_url = getProp($data, 'tail_frame_url');
  4452. // 参考图(支持数组或JSON字符串,最多9张)
  4453. $reference_images = getProp($data, 'reference_images', []);
  4454. if (is_string($reference_images)) {
  4455. $reference_images = json_decode($reference_images, true) ?: [];
  4456. }
  4457. if (!is_array($reference_images)) {
  4458. Utils::throwError('20003:参考图格式不正确');
  4459. }
  4460. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4461. $reference_images = array_slice($reference_images, 0, 9);
  4462. // 参考视频(支持数组或JSON字符串,最多3个)
  4463. $reference_videos = getProp($data, 'reference_videos', []);
  4464. if (is_string($reference_videos)) {
  4465. $reference_videos = json_decode($reference_videos, true) ?: [];
  4466. }
  4467. if (!is_array($reference_videos)) {
  4468. Utils::throwError('20003:参考视频格式不正确');
  4469. }
  4470. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4471. if (count($reference_videos) > 3) {
  4472. Utils::throwError('20003:参考视频最多选择3个');
  4473. }
  4474. $reference_videos = array_slice($reference_videos, 0, 3);
  4475. // 参考音频(支持数组或JSON字符串,最多3个)
  4476. $reference_audios = getProp($data, 'reference_audios', []);
  4477. if (is_string($reference_audios)) {
  4478. $reference_audios = json_decode($reference_audios, true) ?: [];
  4479. }
  4480. if (!is_array($reference_audios)) {
  4481. Utils::throwError('20003:参考音频格式不正确');
  4482. }
  4483. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4484. if (count($reference_audios) > 3) {
  4485. Utils::throwError('20003:参考音频最多选择3个');
  4486. }
  4487. $reference_audios = array_slice($reference_audios, 0, 3);
  4488. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4489. $videoParams = [
  4490. 'model' => $model,
  4491. 'prompt' => $prompt,
  4492. 'video_duration' => $video_duration,
  4493. 'video_resolution' => $video_resolution,
  4494. 'seed' => $seed,
  4495. 'ratio' => $ratio,
  4496. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4497. 'draft' => getProp($data, 'draft', false),
  4498. 'watermark' => getProp($data, 'watermark', false),
  4499. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4500. ];
  4501. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4502. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4503. // 构建content数组
  4504. $videoParams['content'] = [
  4505. [
  4506. 'type' => 'text',
  4507. 'text' => $prompt,
  4508. ]
  4509. ];
  4510. // 根据模型选择不同的视频生成方法
  4511. if (strpos($model, 'jimeng') !== false) {
  4512. // 即梦模型参数调整
  4513. unset($videoParams['content']); // 即梦不使用content格式
  4514. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4515. } elseif (strpos($model, 'kling') !== false) {
  4516. // 可灵模型参数调整
  4517. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4518. unset($videoParams['ratio']);
  4519. unset($videoParams['content']); // 可灵不使用content格式
  4520. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4521. } elseif (strpos($model, 'zhizhen') !== false) {
  4522. // 智帧等新模型使用统一API
  4523. $unifiedParams = [
  4524. 'model_code' => $model,
  4525. 'prompt' => $prompt,
  4526. 'video_duration' => $video_duration,
  4527. 'video_resolution' => strtolower($video_resolution),
  4528. 'video_ratio' => $ratio,
  4529. 'seed' => $seed,
  4530. ];
  4531. // 构建parameters参数
  4532. $parameters = [
  4533. 'seconds' => $unifiedParams['video_duration'],
  4534. 'resolution' => $unifiedParams['video_resolution'],
  4535. 'ratio' => $ratio,
  4536. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4537. ];
  4538. // 首帧和尾帧
  4539. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4540. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4541. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4542. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4543. if ($refImageUrls) {
  4544. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4545. }
  4546. // 参考图处理
  4547. if ($reference_images) {
  4548. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4549. $parameters['reference_images'] = $reference_images;
  4550. $parameters['video_mode'] = 'multi_image';
  4551. $parameters['mode'] = 'multi_image';
  4552. }
  4553. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4554. if ($reference_videos) {
  4555. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4556. $parameters['reference_videos'] = $reference_videos;
  4557. }
  4558. if ($reference_audios) {
  4559. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4560. $parameters['reference_audios'] = $reference_audios;
  4561. }
  4562. $unifiedParams['parameters'] = $parameters;
  4563. // 调用统一API创建任务
  4564. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4565. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4566. // 豆包Seedance 2.0(百度AI网关):图片/视频/音频需要先上传为素材
  4567. $videoParams['reference_images'] = $reference_images;
  4568. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4569. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4570. if ($refImageUrls) {
  4571. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4572. }
  4573. if ($reference_images) {
  4574. // 参考图上传为百度网关素材
  4575. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4576. $videoParams['reference_image_assets'] = $reference_image_assets;
  4577. }
  4578. // 参考视频上传为百度网关素材
  4579. if ($reference_videos) {
  4580. $reference_video_assets = $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4581. $videoParams['reference_video_assets'] = $reference_video_assets;
  4582. }
  4583. // 参考音频上传为百度网关素材
  4584. if ($reference_audios) {
  4585. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4586. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4587. }
  4588. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4589. if ($reference_images || $reference_videos || $reference_audios) {
  4590. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4591. }
  4592. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4593. } else {
  4594. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4595. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4596. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4597. if ($refImageUrls) {
  4598. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4599. }
  4600. if ($reference_videos) {
  4601. foreach ($reference_videos as $videoUrl) {
  4602. $videoParams['content'][] = [
  4603. 'type' => 'video_url',
  4604. 'video_url' => [
  4605. 'url' => $videoUrl,
  4606. ],
  4607. 'role' => 'reference_video',
  4608. ];
  4609. }
  4610. }
  4611. if ($reference_audios) {
  4612. foreach ($reference_audios as $audioUrl) {
  4613. $videoParams['content'][] = [
  4614. 'type' => 'audio_url',
  4615. 'audio_url' => [
  4616. 'url' => $audioUrl,
  4617. ],
  4618. 'role' => 'reference_audio',
  4619. ];
  4620. }
  4621. }
  4622. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4623. }
  4624. return [
  4625. 'task_id' => $task->id,
  4626. 'status' => $task->status,
  4627. 'model' => $model,
  4628. 'video_duration' => $video_duration,
  4629. 'video_resolution' => $video_resolution,
  4630. 'ratio' => $ratio
  4631. ];
  4632. }
  4633. /**
  4634. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4635. *
  4636. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4637. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4638. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4639. *
  4640. * @param array $data
  4641. * @return array
  4642. */
  4643. public function previewCharge(array $data): array
  4644. {
  4645. $mode = (string)getProp($data, 'mode', '');
  4646. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4647. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4648. }
  4649. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4650. $scene = (string)getProp($data, 'scene', 'video_generation');
  4651. $items = [];
  4652. $model = '';
  4653. $resolution = '';
  4654. if ($mode === 'video') {
  4655. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4656. $model = (string)getProp($data, 'model', '');
  4657. if (!$model) {
  4658. Utils::throwError('1002:model参数不能为空');
  4659. }
  4660. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4661. $duration = (int)getProp($data, 'video_duration', 5);
  4662. if ($duration <= 0) {
  4663. $duration = 5;
  4664. }
  4665. $count = max(1, (int)getProp($data, 'count', 1));
  4666. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4667. 'model' => $model,
  4668. 'video_resolution' => $resolution,
  4669. 'video_duration' => $duration,
  4670. 'mode' => $scene,
  4671. ]);
  4672. $points = $pointsPerVideo * $count;
  4673. $items[] = [
  4674. 'type' => 'video',
  4675. 'model' => $model,
  4676. 'video_resolution' => $resolution,
  4677. 'video_duration' => $duration,
  4678. 'count' => $count,
  4679. 'points' => $points,
  4680. ];
  4681. } elseif ($mode === 'image') {
  4682. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4683. $model = (string)getProp($data, 'model', '');
  4684. if (!$model) {
  4685. Utils::throwError('1002:model参数不能为空');
  4686. }
  4687. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4688. if (!$resolution) {
  4689. $width = (int)getProp($data, 'width', 0);
  4690. $height = (int)getProp($data, 'height', 0);
  4691. if ($width <= 0 || $height <= 0) {
  4692. $width = 1600;
  4693. $height = 2848;
  4694. }
  4695. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4696. }
  4697. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4698. $points = $this->pointsService->getImageChargePoints([
  4699. 'model' => $model,
  4700. 'resolution' => $resolution,
  4701. ]) * $imageNum;
  4702. $items[] = [
  4703. 'type' => 'image',
  4704. 'model' => $model,
  4705. 'resolution' => $resolution,
  4706. 'image_num' => $imageNum,
  4707. 'points' => $points,
  4708. ];
  4709. } else {
  4710. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4711. $count = max(1, (int)getProp($data, 'count', 1));
  4712. $animeId = getProp($data, 'anime_id');
  4713. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4714. if ($animeId && $generateEpisodes > 0) {
  4715. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4716. ->where('anime_id', $animeId)
  4717. ->where('is_default', 1)
  4718. ->max('episode_number');
  4719. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4720. $startEpisodeNumber = $currentMaxEpisode + 1;
  4721. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4722. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4723. ->where('anime_id', $animeId)
  4724. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4725. ->whereIn('status', ['pending', 'processing', 'completed'])
  4726. ->count();
  4727. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4728. if ($count < 0) {
  4729. $count = 0;
  4730. }
  4731. }
  4732. $points = PointsService::CHAT_CHARGE_POINTS * $count;
  4733. $items[] = [
  4734. 'type' => 'chat',
  4735. 'count' => $count,
  4736. 'points' => $points,
  4737. ];
  4738. }
  4739. $totalPoints = 0;
  4740. foreach ($items as $item) {
  4741. $totalPoints += $item['points'];
  4742. }
  4743. return [
  4744. 'mode' => $mode,
  4745. 'total_points' => $totalPoints,
  4746. 'items' => $items,
  4747. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4748. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4749. ];
  4750. }
  4751. /**
  4752. * 根据提示词内容智能计算最优视频时长
  4753. *
  4754. * @param string $segmentContent 分镜内容
  4755. * @param string $tailFrame 尾帧描述
  4756. * @return int 视频时长(2-12秒)
  4757. */
  4758. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4759. // 合并所有文本内容
  4760. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4761. // 如果没有内容,返回默认时长
  4762. if (empty($fullText)) {
  4763. return 5;
  4764. }
  4765. // 计算文本长度(中文字符按2个字符计算)
  4766. $textLength = mb_strlen($fullText, 'UTF-8');
  4767. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4768. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4769. // 分析内容复杂度
  4770. $complexityScore = $this->analyzeContentComplexity($fullText);
  4771. // 基础时长计算(根据文本长度)
  4772. $baseDuration = 3; // 默认2秒
  4773. // if ($adjustedLength <= 20) {
  4774. // $baseDuration = 3;
  4775. // } elseif ($adjustedLength <= 40) {
  4776. // $baseDuration = 4;
  4777. // } elseif ($adjustedLength <= 60) {
  4778. // $baseDuration = 5;
  4779. // } elseif ($adjustedLength <= 80) {
  4780. // $baseDuration = 6;
  4781. // } elseif ($adjustedLength <= 100) {
  4782. // $baseDuration = 7;
  4783. // } elseif ($adjustedLength <= 120) {
  4784. // $baseDuration = 8;
  4785. // } else {
  4786. // $baseDuration = 9;
  4787. // }
  4788. // 根据内容复杂度调整时长
  4789. $finalDuration = $baseDuration + $complexityScore;
  4790. // 确保时长在2-12秒范围内
  4791. return max(4, min(12, $finalDuration));
  4792. }
  4793. /**
  4794. * 分析内容复杂度,返回时长调整值
  4795. *
  4796. * @param string $text 文本内容
  4797. * @return int 调整值(-2到+3)
  4798. */
  4799. private function analyzeContentComplexity($text) {
  4800. $score = 0;
  4801. // 动作关键词(需要更长时间展现)
  4802. $actionKeywords = [
  4803. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4804. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4805. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4806. ];
  4807. // 静态关键词(可以用较短时间)
  4808. $staticKeywords = [
  4809. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4810. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4811. ];
  4812. // 复杂场景关键词(需要更长时间)
  4813. $complexSceneKeywords = [
  4814. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4815. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4816. ];
  4817. // 情感关键词(需要适中时间表现)
  4818. $emotionKeywords = [
  4819. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4820. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4821. ];
  4822. // 检查动作关键词
  4823. foreach ($actionKeywords as $keyword) {
  4824. if (strpos($text, $keyword) !== false) {
  4825. $score += 1;
  4826. break; // 避免重复加分
  4827. }
  4828. }
  4829. // 检查静态关键词
  4830. foreach ($staticKeywords as $keyword) {
  4831. if (strpos($text, $keyword) !== false) {
  4832. $score -= 1;
  4833. break;
  4834. }
  4835. }
  4836. // 检查复杂场景关键词
  4837. foreach ($complexSceneKeywords as $keyword) {
  4838. if (strpos($text, $keyword) !== false) {
  4839. $score += 1;
  4840. break;
  4841. }
  4842. }
  4843. // 检查情感关键词
  4844. foreach ($emotionKeywords as $keyword) {
  4845. if (strpos($text, $keyword) !== false) {
  4846. $score += 1;
  4847. break;
  4848. }
  4849. }
  4850. // 检查时间相关词汇
  4851. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4852. $score += 1;
  4853. }
  4854. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4855. $score -= 1;
  4856. }
  4857. // 检查转场词汇
  4858. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4859. $score += 1;
  4860. }
  4861. // 检查环境描述(复杂环境需要更多时间)
  4862. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4863. $score += 1;
  4864. }
  4865. // 检查对话内容(对话需要更多时间)
  4866. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4867. $score += 1;
  4868. }
  4869. // 限制调整范围
  4870. return max(-1, min(4, $score));
  4871. }
  4872. /**
  4873. * 创建完整视频合成任务
  4874. *
  4875. * @param array $data
  4876. * @return array
  4877. */
  4878. public function createCompleteVideoTask($data)
  4879. {
  4880. $animeId = getProp($data, 'anime_id');
  4881. $episodeId = getProp($data, 'episode_id');
  4882. // 验证参数
  4883. if (!$animeId || !$episodeId) {
  4884. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4885. }
  4886. // 检查是否已存在处理中的任务
  4887. $existingTask = DB::table('mp_complete_video_tasks')
  4888. ->where('anime_id', $animeId)
  4889. ->where('episode_id', $episodeId)
  4890. ->whereIn('generate_status', ['执行中'])
  4891. ->first();
  4892. if ($existingTask) {
  4893. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4894. }
  4895. // 获取全能模式状态
  4896. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4897. if ((int)$ace_mode === 1) {
  4898. // 获取所有片段的配音视频,按 act_number 排序
  4899. $segments = DB::table('mp_episode_segments')
  4900. ->where('anime_id', $animeId)
  4901. ->where('episode_id', $episodeId)
  4902. ->orderBy('segment_number')
  4903. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4904. ->get();
  4905. // 检查是否所有片段都有视频
  4906. $missingVideos = $segments->filter(function($segment) {
  4907. return empty($segment->video_url);
  4908. });
  4909. if ($missingVideos->isNotEmpty()) {
  4910. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4911. }
  4912. }else {
  4913. // 获取所有分镜的配音视频,按 segment_number 排序
  4914. $segments = DB::table('mp_episode_segments')
  4915. ->where('anime_id', $animeId)
  4916. ->where('episode_id', $episodeId)
  4917. ->orderBy('segment_number')
  4918. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4919. ->get();
  4920. // 检查是否所有分镜都有配音和视频
  4921. $missingVideos = $segments->filter(function($segment) {
  4922. return empty($segment->audio_url) || empty($segment->video_url);
  4923. });
  4924. if ($missingVideos->isNotEmpty()) {
  4925. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4926. }
  4927. }
  4928. if ($segments->isEmpty()) {
  4929. Utils::throwError('20003:未找到该剧集的分镜数据');
  4930. }
  4931. // 获取当前完整视频url
  4932. $completeVideoUrl = DB::table('mp_anime_episodes')
  4933. ->where('anime_id', $animeId)
  4934. ->where('id', $episodeId)
  4935. ->value('complete_video_url');
  4936. // 构建 generate_json
  4937. $generateJson = [];
  4938. $sequence = 1;
  4939. foreach ($segments as $segment) {
  4940. if ((int)$ace_mode === 1) {
  4941. $generateJson[] = [
  4942. 'sequence' => $sequence++,
  4943. 'video_url' => $segment->video_url,
  4944. 'video_time_point_start' => $segment->video_time_point_start,
  4945. 'video_time_point_end' => $segment->video_time_point_end
  4946. ];
  4947. }else {
  4948. $generateJson[] = [
  4949. 'sequence' => $sequence++,
  4950. 'video_url' => $segment->video_url,
  4951. 'audio_url' => $segment->audio_url,
  4952. 'video_time_point_start' => $segment->video_time_point_start,
  4953. 'video_time_point_end' => $segment->video_time_point_end
  4954. ];
  4955. }
  4956. }
  4957. // 创建任务
  4958. $now = date('Y-m-d H:i:s');
  4959. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4960. 'anime_id' => $animeId,
  4961. 'episode_id' => $episodeId,
  4962. 'generate_json' => json_encode($generateJson, 256),
  4963. 'generate_status' => '执行中',
  4964. 'complete_video_url' => '',
  4965. 'created_at' => $now,
  4966. 'updated_at' => $now
  4967. ]);
  4968. if (!$taskId) {
  4969. Utils::throwError('20003:创建任务失败');
  4970. }
  4971. // 更新剧集表的任务ID和状态
  4972. $boolen = DB::table('mp_anime_episodes')
  4973. ->where('anime_id', $animeId)
  4974. ->where('id', $episodeId)
  4975. ->update([
  4976. 'complete_video_task_id' => $taskId,
  4977. 'complete_video_task_status' => '执行中',
  4978. 'updated_at' => $now
  4979. ]);
  4980. if (!$boolen) {
  4981. Utils::throwError('20003:更新剧集表失败');
  4982. }
  4983. dLog('anime')->info('创建完整视频合成任务', [
  4984. 'task_id' => $taskId,
  4985. 'anime_id' => $animeId,
  4986. 'episode_id' => $episodeId,
  4987. 'segment_count' => count($generateJson)
  4988. ]);
  4989. // 请求远程服务器执行生成
  4990. $client = new Client(['timeout' => 600, 'verify' => false]);
  4991. try {
  4992. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4993. $response = $result->getBody()->getContents();
  4994. $response_arr = json_decode($response, true);
  4995. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4996. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4997. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4998. // // 更新任务状态为失败
  4999. // DB::table('mp_complete_video_tasks')
  5000. // ->where('id', $taskId)
  5001. // ->update([
  5002. // 'generate_status' => '执行失败',
  5003. // 'error_message' => $error_msg,
  5004. // 'updated_at' => date('Y-m-d H:i:s')
  5005. // ]);
  5006. // // 同步更新剧集表状态
  5007. // DB::table('mp_anime_episodes')
  5008. // ->where('complete_video_task_id', $taskId)
  5009. // ->update([
  5010. // 'complete_video_task_status' => '执行失败',
  5011. // 'updated_at' => date('Y-m-d H:i:s')
  5012. // ]);
  5013. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5014. }
  5015. } catch (\Exception $e) {
  5016. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5017. // 更新任务状态为失败
  5018. DB::table('mp_complete_video_tasks')
  5019. ->where('id', $taskId)
  5020. ->update([
  5021. 'generate_status' => '执行失败',
  5022. 'error_message' => $e->getMessage(),
  5023. 'updated_at' => date('Y-m-d H:i:s')
  5024. ]);
  5025. // 同步更新剧集表状态
  5026. DB::table('mp_anime_episodes')
  5027. ->where('complete_video_task_id', $taskId)
  5028. ->update([
  5029. 'complete_video_task_status' => '执行失败',
  5030. 'updated_at' => date('Y-m-d H:i:s')
  5031. ]);
  5032. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5033. }
  5034. // 开始轮询任务状态
  5035. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5036. $pollInterval = 5; // 每5秒轮询一次
  5037. $attempt = 0;
  5038. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5039. while ($attempt < $maxAttempts) {
  5040. sleep($pollInterval);
  5041. $attempt++;
  5042. // 查询任务状态
  5043. $task = DB::table('mp_complete_video_tasks')
  5044. ->where('id', $taskId)
  5045. ->first();
  5046. if (!$task) {
  5047. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5048. Utils::throwError('20003:任务不存在');
  5049. }
  5050. dLog('anime')->info('轮询任务状态', [
  5051. 'task_id' => $taskId,
  5052. 'attempt' => $attempt,
  5053. 'status' => $task->generate_status
  5054. ]);
  5055. // 检查任务是否完成
  5056. if ($task->generate_status === '执行成功') {
  5057. // 同步更新剧集表状态
  5058. $boolen3 = DB::table('mp_anime_episodes')
  5059. ->where('anime_id', $animeId)
  5060. ->where('id', $episodeId)
  5061. ->update([
  5062. 'complete_video_url' => $task->complete_video_url,
  5063. 'complete_video_task_status' => '执行成功',
  5064. 'updated_at' => date('Y-m-d H:i:s')
  5065. ]);
  5066. dLog('anime')->info('视频合成任务完成', [
  5067. 'task_id' => $taskId,
  5068. 'video_url' => $task->complete_video_url,
  5069. 'attempts' => $attempt
  5070. ]);
  5071. // 如果更新成功则远程删除之前的文件
  5072. if ($boolen3 && $completeVideoUrl) {
  5073. $encode_url = urlencode($completeVideoUrl);
  5074. $client = new Client(['timeout' => 300, 'verify' => false]);
  5075. // 根据ID通过API通知合成音频
  5076. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5077. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5078. $response = $result->getBody()->getContents();
  5079. $response_arr = json_decode($response, true);
  5080. Log::info('火山删除音频返回: '.$response);
  5081. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5082. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5083. Log::info('火山删除音频失败: '.$error_msg);
  5084. // Utils::throwError('20003:火山删除音频失败');
  5085. }
  5086. }
  5087. return [
  5088. 'task_id' => $taskId,
  5089. 'anime_id' => $animeId,
  5090. 'episode_id' => $episodeId,
  5091. 'segment_count' => count($generateJson),
  5092. 'generate_status' => '执行成功',
  5093. 'complete_video_url' => $task->complete_video_url,
  5094. ];
  5095. }
  5096. // 检查任务是否失败
  5097. if ($task->generate_status === '执行失败') {
  5098. // 同步更新剧集表状态
  5099. DB::table('mp_anime_episodes')
  5100. ->where('anime_id', $animeId)
  5101. ->where('id', $episodeId)
  5102. ->update([
  5103. 'complete_video_task_status' => '执行失败',
  5104. 'updated_at' => date('Y-m-d H:i:s')
  5105. ]);
  5106. $errorMessage = $task->error_message ?? '未知错误';
  5107. dLog('anime')->error('视频合成任务失败', [
  5108. 'task_id' => $taskId,
  5109. 'error' => $errorMessage,
  5110. 'attempts' => $attempt
  5111. ]);
  5112. return [
  5113. 'task_id' => $taskId,
  5114. 'anime_id' => $animeId,
  5115. 'episode_id' => $episodeId,
  5116. 'segment_count' => count($generateJson),
  5117. 'generate_status' => '执行失败',
  5118. 'error_message' => $errorMessage
  5119. ];
  5120. }
  5121. }
  5122. // 超时处理
  5123. dLog('anime')->warning('视频合成任务超时', [
  5124. 'task_id' => $taskId,
  5125. 'max_attempts' => $maxAttempts,
  5126. 'timeout_seconds' => $maxAttempts * $pollInterval
  5127. ]);
  5128. // 更新任务状态为超时
  5129. DB::table('mp_complete_video_tasks')
  5130. ->where('id', $taskId)
  5131. ->update([
  5132. 'generate_status' => '超时',
  5133. 'error_message' => '任务执行超时(5分钟)',
  5134. 'updated_at' => date('Y-m-d H:i:s')
  5135. ]);
  5136. return [
  5137. 'task_id' => $taskId,
  5138. 'anime_id' => $animeId,
  5139. 'episode_id' => $episodeId,
  5140. 'segment_count' => count($generateJson),
  5141. 'generate_status' => '超时',
  5142. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5143. ];
  5144. }
  5145. /**
  5146. * 根据 inner_prompt_type 附加内置提示词
  5147. *
  5148. * @param string $prompt 用户提示词
  5149. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5150. * @return string 合并后的提示词
  5151. */
  5152. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5153. {
  5154. $innerPromptMap = [
  5155. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5156. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5157. ];
  5158. if (!isset($innerPromptMap[$innerPromptType])) {
  5159. return $prompt;
  5160. }
  5161. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5162. }
  5163. /**
  5164. * 根据 inner_prompt_type 获取生成图片数量
  5165. *
  5166. * @param int $innerPromptType 内置提示词类型
  5167. * @param int $imageNum 传入的图片张数
  5168. * @return int 图片数量
  5169. */
  5170. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5171. {
  5172. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5173. }
  5174. /**
  5175. * 提取图片生成结果URL
  5176. *
  5177. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5178. * @param int $innerPromptType 内置提示词类型
  5179. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5180. */
  5181. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5182. {
  5183. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5184. if (is_array($resultUrls) && !empty($resultUrls)) {
  5185. $resultUrls = array_values($resultUrls);
  5186. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5187. }
  5188. if (!empty($resultUrl)) {
  5189. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5190. }
  5191. return (int)$innerPromptType === 2 ? [] : '';
  5192. }
  5193. public function generateImg($data) {
  5194. $prompt = getProp($data, 'prompt');
  5195. $episode_id = getProp($data, 'episode_id');
  5196. $ref_img_urls = getProp($data, 'ref_img_urls');
  5197. $ratio = getProp($data, 'ratio', '9:16');
  5198. $resolution = getProp($data, 'resolution', '2k');
  5199. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5200. $imageNum = (int)getProp($data, 'image_num', 1);
  5201. // 定义分辨率和宽高比对应的尺寸映射表
  5202. $sizeMap = [
  5203. '2k' => [
  5204. '1:1' => ['width' => 2048, 'height' => 2048],
  5205. '4:3' => ['width' => 2304, 'height' => 1728],
  5206. '3:4' => ['width' => 1728, 'height' => 2304],
  5207. '16:9' => ['width' => 2848, 'height' => 1600],
  5208. '9:16' => ['width' => 1600, 'height' => 2848],
  5209. '3:2' => ['width' => 2496, 'height' => 1664],
  5210. '2:3' => ['width' => 1664, 'height' => 2496],
  5211. '21:9' => ['width' => 3136, 'height' => 1344],
  5212. ],
  5213. '3k' => [
  5214. '1:1' => ['width' => 3072, 'height' => 3072],
  5215. '4:3' => ['width' => 3456, 'height' => 2592],
  5216. '3:4' => ['width' => 2592, 'height' => 3456],
  5217. '16:9' => ['width' => 4096, 'height' => 2304],
  5218. '9:16' => ['width' => 2304, 'height' => 4096],
  5219. '2:3' => ['width' => 2496, 'height' => 3744],
  5220. '3:2' => ['width' => 3744, 'height' => 2496],
  5221. '21:9' => ['width' => 4704, 'height' => 2016],
  5222. ],
  5223. '4k' => [
  5224. '1:1' => ['width' => 4096, 'height' => 4096],
  5225. '3:4' => ['width' => 3520, 'height' => 4704],
  5226. '4:3' => ['width' => 4704, 'height' => 3520],
  5227. '16:9' => ['width' => 5504, 'height' => 3040],
  5228. '9:16' => ['width' => 3040, 'height' => 5504],
  5229. '2:3' => ['width' => 3328, 'height' => 4992],
  5230. '3:2' => ['width' => 4992, 'height' => 3328],
  5231. '21:9' => ['width' => 6240, 'height' => 2656],
  5232. ],
  5233. ];
  5234. // 参数验证
  5235. $resolution = strtolower($resolution);
  5236. if (!isset($sizeMap[$resolution])) {
  5237. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5238. }
  5239. if (!isset($sizeMap[$resolution][$ratio])) {
  5240. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5241. }
  5242. // 根据 ratio 和 resolution 确定宽高
  5243. $width = $sizeMap[$resolution][$ratio]['width'];
  5244. $height = $sizeMap[$resolution][$ratio]['height'];
  5245. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5246. if (is_json($ref_img_urls)) {
  5247. $ref_img_urls = json_decode($ref_img_urls, true);
  5248. }else {
  5249. $ref_img_urls = explode(',', $ref_img_urls);
  5250. }
  5251. }
  5252. // 处理图片模型
  5253. $model = getProp($data, 'model');
  5254. if (!$model) {
  5255. // 用户没有输入,从episode表获取
  5256. if ($episode_id) {
  5257. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5258. $model = getProp($episode, 'image_model');
  5259. }
  5260. if (!$model) {
  5261. // episode表也没有,使用默认值
  5262. $model = 'doubao-seedream-5-0-lite-260128';
  5263. }
  5264. }
  5265. // 验证模型是否在可用模型表中
  5266. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5267. // $model = 'doubao-seedream-5-0-lite-260128';
  5268. Utils::throwError('20003:该模型已不可用,请更换!');
  5269. }
  5270. // 保存到episode表
  5271. if ($episode_id) {
  5272. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5273. 'image_model' => $model,
  5274. 'updated_at' => date('Y-m-d H:i:s')
  5275. ]);
  5276. }
  5277. // 参数验证
  5278. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5279. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5280. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5281. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5282. try {
  5283. // 创建图片生成任务
  5284. $params = [
  5285. 'prompt' => $prompt,
  5286. 'model' => $model,
  5287. 'ref_img_urls' => '',
  5288. 'width' => $width,
  5289. 'height' => $height,
  5290. 'image_num' => $imageNum
  5291. ];
  5292. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5293. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5294. $task_id = $task->id;
  5295. if (!$task_id) {
  5296. Utils::throwError('20003:创建图片生成任务失败');
  5297. }
  5298. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5299. $model = getProp($task, 'model');
  5300. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5301. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5302. $isSyncModel = $isVolcModel || $isGptModel;
  5303. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5304. $start_time = time();
  5305. $timeout = 300; // 5分钟
  5306. $img_url = '';
  5307. $img_urls = [];
  5308. while (time() - $start_time < $timeout) {
  5309. sleep(3);
  5310. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5311. if ($isSyncModel) {
  5312. // 刷新任务状态
  5313. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5314. if ($task->status === 'success' && $task->result_url) {
  5315. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5316. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5317. if (!empty($resultUrls)) {
  5318. $img_urls = $resultUrls;
  5319. $img_url = $resultUrls[0];
  5320. } else {
  5321. $img_url = (string)$task->result_url;
  5322. }
  5323. break;
  5324. } elseif ($task->status === 'failed') {
  5325. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5326. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5327. }
  5328. // // 如果还在处理中,提示用户稍后查看
  5329. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5330. }else {
  5331. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5332. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5333. if ($statusInfo['status'] === 'success') {
  5334. $task->updateStatus('success', [
  5335. 'result_url' => $statusInfo['result_url'],
  5336. 'result_json' => $statusInfo['result_json'] ?? []
  5337. ]);
  5338. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5339. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5340. if (!empty($resultUrls)) {
  5341. $img_urls = $resultUrls;
  5342. $img_url = $resultUrls[0];
  5343. } else {
  5344. $img_url = (string)$statusInfo['result_url'];
  5345. }
  5346. break;
  5347. } elseif ($statusInfo['status'] === 'failed') {
  5348. $task->updateStatus('failed', [
  5349. 'error_message' => $statusInfo['error_message'],
  5350. 'result_json' => $statusInfo['result_json'] ?? []
  5351. ]);
  5352. dLog('anime')->error('图片生成失败,', [
  5353. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5354. ]);
  5355. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5356. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5357. }
  5358. }
  5359. }
  5360. if (empty($img_url)) {
  5361. Utils::throwError('20003:图片生成超时,请稍后重试');
  5362. }
  5363. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5364. if (count($img_urls) > 1) {
  5365. return [
  5366. 'img_url' => $img_url,
  5367. 'image_urls' => $img_urls
  5368. ];
  5369. }
  5370. return $img_url;
  5371. } catch (\Exception $e) {
  5372. dLog('anime')->error('更新角色或场景失败', [
  5373. 'error' => $e->getMessage()
  5374. ]);
  5375. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5376. Utils::throwError('20003:' . $e->getMessage());
  5377. }
  5378. }
  5379. /**
  5380. * 使用文生文模型解析分镜内容
  5381. */
  5382. private function parseSegmentContentWithAI($segment_content) {
  5383. try {
  5384. // 使用DeepSeek服务的公开方法解析分镜内容
  5385. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5386. } catch (\Exception $e) {
  5387. // 如果AI解析失败,记录日志并返回原内容
  5388. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5389. return $segment_content;
  5390. }
  5391. }
  5392. /**
  5393. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5394. *
  5395. * @param int $episode_id 分集ID
  5396. * @param int $anime_id 动漫ID
  5397. * @param array $roles 分集角色数组(引用传递)
  5398. * @param array $scenes 分集场景数组(引用传递)
  5399. * @param array $episode 分集数据
  5400. */
  5401. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5402. // 获取全局动漫的角色和场景数据
  5403. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5404. if (!$anime) return;
  5405. $art_style_type = getProp($anime, 'art_style_type');
  5406. $character_prefix = '';
  5407. $scene_prefix = '';
  5408. if ($art_style_type) {
  5409. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5410. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5411. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5412. }
  5413. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5414. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5415. $roles_updated = false;
  5416. $scenes_updated = false;
  5417. // 处理角色
  5418. foreach ($roles as &$role) {
  5419. $role_name = getProp($role, 'role');
  5420. $role_description = getProp($role, 'description');
  5421. $role_pic_prompt = getProp($role, 'pic_prompt');
  5422. $role_url = getProp($role, 'url');
  5423. $role_task_id = getProp($role, 'task_id');
  5424. // 如果已有URL或已有任务ID,跳过
  5425. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5426. continue;
  5427. }
  5428. $url_inherited = false;
  5429. // 尝试从全局数据中继承
  5430. foreach ($global_roles as $global_role) {
  5431. $global_role_name = getProp($global_role, 'role');
  5432. $global_role_description = getProp($global_role, 'description');
  5433. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5434. $global_role_url = getProp($global_role, 'url');
  5435. $global_role_task_id = getProp($global_role, 'task_id');
  5436. $global_role_task_status = getProp($global_role, 'task_status');
  5437. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5438. if ($role_name === $global_role_name
  5439. && $role_description === $global_role_description
  5440. && $role_pic_prompt === $global_role_pic_prompt
  5441. && !empty($global_role_url)) {
  5442. // 继承 task_id、task_status 和 url
  5443. $role['task_id'] = $global_role_task_id;
  5444. $role['task_status'] = $global_role_task_status;
  5445. $role['url'] = $global_role_url;
  5446. $roles_updated = true;
  5447. $url_inherited = true;
  5448. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5449. break;
  5450. }
  5451. }
  5452. // 如果无法继承且没有任务ID,创建新任务
  5453. if (!$url_inherited && empty($role_task_id)) {
  5454. try {
  5455. $art_style = getProp($episode, 'art_style');
  5456. // 优先使用 pic_prompt,如果没有则使用 description
  5457. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5458. // if ($art_style) {
  5459. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5460. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5461. // }
  5462. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5463. $params = [
  5464. 'prompt' => $description,
  5465. 'ref_img_urls' => []
  5466. ];
  5467. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5468. $task_id = $task->id;
  5469. if ($task_id) {
  5470. $role['task_id'] = $task_id;
  5471. $role['task_status'] = 'processing';
  5472. $roles_updated = true;
  5473. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5474. }
  5475. } catch (\Exception $e) {
  5476. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5477. }
  5478. }
  5479. }
  5480. // 处理场景
  5481. foreach ($scenes as &$scene) {
  5482. $scene_name = getProp($scene, 'scene');
  5483. $scene_description = getProp($scene, 'description');
  5484. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5485. $scene_url = getProp($scene, 'url');
  5486. $scene_task_id = getProp($scene, 'task_id');
  5487. // 如果已有URL或已有任务ID,跳过
  5488. if (!empty($scene_url) || !empty($scene_task_id)) {
  5489. continue;
  5490. }
  5491. $url_inherited = false;
  5492. // 尝试从全局数据中继承
  5493. foreach ($global_scenes as $global_scene) {
  5494. $global_scene_name = getProp($global_scene, 'scene');
  5495. $global_scene_description = getProp($global_scene, 'description');
  5496. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5497. $global_scene_url = getProp($global_scene, 'url');
  5498. $global_scene_task_id = getProp($global_scene, 'task_id');
  5499. $global_scene_task_status = getProp($global_scene, 'task_status');
  5500. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5501. if ($scene_name === $global_scene_name
  5502. && $scene_description === $global_scene_description
  5503. && $scene_pic_prompt === $global_scene_pic_prompt
  5504. && !empty($global_scene_url)) {
  5505. // 继承 task_id、task_status 和 url
  5506. $scene['task_id'] = $global_scene_task_id;
  5507. $scene['task_status'] = $global_scene_task_status;
  5508. $scene['url'] = $global_scene_url;
  5509. $scenes_updated = true;
  5510. $url_inherited = true;
  5511. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5512. break;
  5513. }
  5514. }
  5515. // 如果无法继承且没有任务ID,创建新任务
  5516. if (!$url_inherited && empty($scene_task_id)) {
  5517. try {
  5518. $art_style = getProp($episode, 'art_style');
  5519. // 优先使用 pic_prompt,如果没有则使用 description
  5520. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5521. // if ($art_style) {
  5522. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5523. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5524. // }
  5525. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5526. $params = [
  5527. 'prompt' => $description,
  5528. 'ref_img_urls' => []
  5529. ];
  5530. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5531. $task_id = $task->id;
  5532. if ($task_id) {
  5533. $scene['task_id'] = $task_id;
  5534. $scene['task_status'] = 'processing';
  5535. $scenes_updated = true;
  5536. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5537. }
  5538. } catch (\Exception $e) {
  5539. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5540. }
  5541. }
  5542. }
  5543. // 如果有更新,保存到数据库
  5544. if ($roles_updated || $scenes_updated) {
  5545. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5546. if ($roles_updated) {
  5547. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5548. }
  5549. if ($scenes_updated) {
  5550. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5551. }
  5552. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5553. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5554. }
  5555. }
  5556. /**
  5557. * 根据图片URL使用AI反推图片提示词
  5558. *
  5559. * @param string $img_url 图片URL
  5560. * @return string 反推的提示词
  5561. */
  5562. private function generateImagePromptFromUrl($img_url) {
  5563. try {
  5564. // 获取默认模型
  5565. $model = 'doubao-seed-2-0-mini-260215';
  5566. // 构建messages参数
  5567. $messages = [
  5568. [
  5569. 'role' => 'user',
  5570. 'content' => [
  5571. [
  5572. 'type' => 'text',
  5573. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5574. ],
  5575. [
  5576. 'type' => 'image_url',
  5577. 'image_url' => [
  5578. 'url' => $img_url
  5579. ]
  5580. ]
  5581. ]
  5582. ]
  5583. ];
  5584. // 构建请求参数
  5585. $params = [
  5586. 'model' => $model,
  5587. 'messages' => $messages,
  5588. 'stream' => false,
  5589. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5590. ];
  5591. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5592. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5593. // 返回生成的内容
  5594. return getProp($result, 'fullContent', '图片描述生成失败');
  5595. } catch (\Exception $e) {
  5596. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5597. 'img_url' => $img_url
  5598. ]);
  5599. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5600. 'error' => $e->getMessage(),
  5601. 'img_url' => $img_url
  5602. ]);
  5603. return '图片描述生成失败: ' . $e->getMessage();
  5604. }
  5605. }
  5606. /**
  5607. * 音频试听接口
  5608. * 创建音频任务并轮询获取结果
  5609. *
  5610. * @param array $data 参数数组
  5611. * @return array 返回音频URL或错误信息
  5612. */
  5613. public function previewAudio($data) {
  5614. $dialogue = getProp($data, 'dialogue');
  5615. // 必填参数验证
  5616. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5617. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5618. $voice_type = getProp($data, 'voice_type');
  5619. $voice_name = getProp($data, 'voice_name');
  5620. $voice_actor = getProp($data, 'voice_actor');
  5621. $emotion_type = getProp($data, 'emotion_type');
  5622. $gender = getProp($data, 'gender', 0);
  5623. $emotion = getProp($data, 'emotion');
  5624. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5625. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5626. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5627. $pitch = getProp($data, 'pitch', 0);
  5628. try {
  5629. $now = date('Y-m-d H:i:s');
  5630. // 构建生成参数
  5631. $generate_json = json_encode([
  5632. 'text' => $dialogue,
  5633. 'role' => $voice_actor,
  5634. 'voice_type' => $voice_type,
  5635. 'voice_name' => $voice_name,
  5636. 'emotion' => $emotion,
  5637. 'emotion_type' => $emotion_type,
  5638. 'gender' => $gender,
  5639. 'speed_ratio' => $speed_ratio,
  5640. 'loudness_ratio' => $loudness_ratio,
  5641. 'emotion_scale' => $emotion_scale,
  5642. 'pitch' => $pitch,
  5643. ], 256);
  5644. // 请求远程服务器执行生成
  5645. $client = new Client(['timeout' => 600, 'verify' => false]);
  5646. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5647. $response = $result->getBody()->getContents();
  5648. $response_arr = json_decode($response, true);
  5649. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5650. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5651. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5652. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5653. }
  5654. $arr = $response_arr['data'];
  5655. $subtitle_info = $arr['subtitle_info'];
  5656. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5657. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5658. return [
  5659. 'audio_url' => $arr['url'],
  5660. 'subtitle_info' => $subtitle_info,
  5661. 'audio_duration' => round($audio_duration, 2)
  5662. ];
  5663. } catch (\Exception $e) {
  5664. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5665. Utils::throwError('20003:' . $e->getMessage());
  5666. }
  5667. }
  5668. /**
  5669. * 获取角色库列表(支持文件夹递归查询)
  5670. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5671. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5672. */
  5673. public function globalProducts($data) {
  5674. $uid = Site::getUid();
  5675. $cpid = Site::getCpid();
  5676. $role = Site::getRole();
  5677. $id = getProp($data, 'id', 0);
  5678. $parent_id = getProp($data, 'parent_id', 0);
  5679. $product_name = getProp($data, 'product_name');
  5680. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5681. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5682. if (!$product) {
  5683. Utils::throwError('20003:请选择产品类型');
  5684. }
  5685. // 根据角色和is_public参数确定查询范围
  5686. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5687. // user角色:根据is_public参数筛选
  5688. $query_user_ids = [];
  5689. if ($role === 'admin') {
  5690. // admin获取所有个人库和公共库
  5691. $query_user_ids = [$uid, 0];
  5692. } else {
  5693. // user角色根据is_public参数筛选
  5694. if ($is_public == 2) {
  5695. // 个人库+公共库
  5696. $query_user_ids = [$uid, 0];
  5697. } elseif ($is_public == 0) {
  5698. // 仅个人库
  5699. $query_user_ids = [$uid];
  5700. } elseif ($is_public == 1) {
  5701. // 仅公共库
  5702. $query_user_ids = [0];
  5703. }
  5704. }
  5705. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5706. if ($id || $product_name) {
  5707. $query = DB::table('mp_products')
  5708. ->where('cpid', $cpid)
  5709. ->whereIn('user_id', $query_user_ids)
  5710. ->where('is_deleted', 0);
  5711. // 如果指定了 id,按 id 精确查询
  5712. if ($id) {
  5713. $query->where('id', $id);
  5714. }
  5715. // 如果指定了 product_name,按名称模糊查询
  5716. if ($product_name) {
  5717. $query->where('product_name', 'like', "%{$product_name}%");
  5718. }
  5719. // 如果指定了 product,添加筛选条件
  5720. if ($product) {
  5721. $query->where('product', $product);
  5722. }
  5723. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5724. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5725. ->get()
  5726. ->map(function($value) {
  5727. $value = (array)$value;
  5728. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5729. $value['type'] = (int)$value['type'];
  5730. $value['parent_id'] = (int)$value['parent_id'];
  5731. $value['level'] = (int)$value['level'];
  5732. $value['product'] = (int)($value['product'] ?? 1);
  5733. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5734. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5735. unset($value['user_id']);
  5736. return $value;
  5737. })
  5738. ->toArray();
  5739. return $result;
  5740. }
  5741. // 递归获取所有子目录和角色
  5742. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5743. }
  5744. /**
  5745. * 递归获取指定目录下的所有子目录和角色
  5746. * @param int $cpid 公司ID
  5747. * @param int $parent_id 父目录ID
  5748. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5749. * @param array $query_user_ids 用户ID数组(支持多个)
  5750. * @param int $current_uid 当前用户ID(用于排序)
  5751. * @return array
  5752. */
  5753. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5754. // 查询当前层级的所有项(文件夹和角色)
  5755. $query = DB::table('mp_products')
  5756. ->where('cpid', $cpid)
  5757. ->where('is_deleted', 0)
  5758. ->where('parent_id', $parent_id);
  5759. // 添加用户ID验证(支持多个user_id)
  5760. if (!empty($query_user_ids)) {
  5761. $query->whereIn('user_id', $query_user_ids);
  5762. }
  5763. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5764. if ($product) {
  5765. $query->where('product', $product);
  5766. }
  5767. // 排序规则:
  5768. // 1. 文件夹在前(type DESC)
  5769. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5770. // 3. 其他排序规则
  5771. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5772. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5773. ->get();
  5774. $result = [];
  5775. foreach ($items as $item) {
  5776. $itemArray = [
  5777. 'id' => $item->id,
  5778. 'type' => (int)$item->type,
  5779. 'parent_id' => (int)$item->parent_id,
  5780. 'level' => (int)$item->level,
  5781. 'product_name' => $item->product_name,
  5782. 'url' => $item->url,
  5783. 'pic_prompt' => $item->pic_prompt ?? '',
  5784. 'three_view_image_url' => $item->three_view_image_url,
  5785. 'product' => (int)($item->product ?? 1),
  5786. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5787. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5788. ];
  5789. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5790. // 如果是文件夹,递归获取其子项
  5791. if ($item->type == 2) {
  5792. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5793. if (!empty($children)) {
  5794. $itemArray['children'] = $children;
  5795. }
  5796. }
  5797. $result[] = $itemArray;
  5798. }
  5799. return $result;
  5800. }
  5801. /**
  5802. * 创建文件夹
  5803. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5804. * @return int 返回新建文件夹ID
  5805. */
  5806. public function createFolder($data) {
  5807. $uid = Site::getUid();
  5808. $cpid = Site::getCpid();
  5809. $role = Site::getRole();
  5810. $parent_id = getProp($data, 'parent_id', 0);
  5811. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5812. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5813. // 如果是公共库操作,需要admin权限
  5814. if ($is_public && $role !== 'admin') {
  5815. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5816. }
  5817. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5818. $store_uid = $is_public ? 0 : $uid;
  5819. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5820. $product = getProp($data, 'product');
  5821. if (!in_array($product, [1, 2, 3])) {
  5822. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5823. }
  5824. // 验证父文件夹
  5825. $parent_level = 0;
  5826. if ($parent_id > 0) {
  5827. $parent = DB::table('mp_products')
  5828. ->where('id', $parent_id)
  5829. ->where('cpid', $cpid)
  5830. ->where('user_id', $store_uid)
  5831. ->where('type', 2)
  5832. ->where('is_deleted', 0)
  5833. ->first();
  5834. if (!$parent) {
  5835. Utils::throwError('20003:父文件夹不存在');
  5836. }
  5837. // 检查父文件夹的 product 类型是否一致
  5838. if ($parent->product != $product) {
  5839. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5840. }
  5841. $parent_level = $parent->level;
  5842. // 检查层级限制(最多3层)
  5843. if ($parent_level >= 3) {
  5844. Utils::throwError('20003:文件夹层级不能超过3层');
  5845. }
  5846. }
  5847. // 检查当前目录下是否已存在空白文件夹
  5848. $empty_folder_exists = DB::table('mp_products')
  5849. ->where('parent_id', $parent_id)
  5850. ->where('cpid', $cpid)
  5851. ->where('user_id', $store_uid)
  5852. ->where('type', 2)
  5853. ->where('product', $product)
  5854. ->where('product_name', '新建文件夹')
  5855. ->where('is_deleted', 0)
  5856. ->exists();
  5857. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5858. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5859. }
  5860. // 创建文件夹
  5861. $folder_id = DB::table('mp_products')->insertGetId([
  5862. 'user_id' => $store_uid,
  5863. 'cpid' => $cpid,
  5864. 'type' => 2,
  5865. 'parent_id' => $parent_id,
  5866. 'level' => $parent_level + 1,
  5867. 'product_name' => $folder_name,
  5868. 'product' => $product,
  5869. 'sort_order' => time(), // 使用时间戳作为排序权重
  5870. 'is_deleted' => 0,
  5871. 'created_at' => date('Y-m-d H:i:s'),
  5872. 'updated_at' => date('Y-m-d H:i:s')
  5873. ]);
  5874. return [
  5875. 'id' => $folder_id,
  5876. 'type' => 2,
  5877. 'parent_id' => $parent_id,
  5878. 'level' => $parent_level + 1,
  5879. 'product_name' => $folder_name,
  5880. 'product' => $product,
  5881. ];
  5882. }
  5883. /**
  5884. * 重命名文件夹或角色
  5885. * @param array $data 包含 id、product_name(新名称)
  5886. * @return bool
  5887. */
  5888. public function renameFolder($data) {
  5889. $uid = Site::getUid();
  5890. $cpid = Site::getCpid();
  5891. $role = Site::getRole();
  5892. $id = getProp($data, 'id');
  5893. $new_name = getProp($data, 'product_name');
  5894. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5895. if (!$id || !$new_name) {
  5896. Utils::throwError('20003:参数不完整');
  5897. }
  5898. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5899. $query_uid = $is_public ? 0 : $uid;
  5900. // 如果是公共库操作,需要admin权限
  5901. if ($is_public && $role !== 'admin') {
  5902. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5903. }
  5904. // 检查是否存在
  5905. $item = DB::table('mp_products')
  5906. ->where('id', $id)
  5907. ->where('cpid', $cpid)
  5908. ->where('user_id', $query_uid)
  5909. ->where('is_deleted', 0)
  5910. ->first();
  5911. if (!$item) {
  5912. Utils::throwError('20003:项目不存在');
  5913. }
  5914. return DB::table('mp_products')
  5915. ->where('id', $id)
  5916. ->where('cpid', $cpid)
  5917. ->where('user_id', $query_uid)
  5918. ->update([
  5919. 'product_name' => $new_name,
  5920. 'updated_at' => date('Y-m-d H:i:s')
  5921. ]);
  5922. }
  5923. /**
  5924. * 移动角色或文件夹到指定文件夹
  5925. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5926. * @return bool
  5927. */
  5928. public function moveProductOrFolder($data) {
  5929. $uid = Site::getUid();
  5930. $cpid = Site::getCpid();
  5931. $role = Site::getRole();
  5932. $id = getProp($data, 'id');
  5933. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5934. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5935. if (!$id) {
  5936. Utils::throwError('20003:请选择要移动的项目');
  5937. }
  5938. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5939. $query_uid = $is_public ? 0 : $uid;
  5940. // 如果是公共库操作,需要admin权限
  5941. if ($is_public && $role !== 'admin') {
  5942. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5943. }
  5944. // 检查要移动的项目
  5945. $item = DB::table('mp_products')
  5946. ->where('id', $id)
  5947. ->where('cpid', $cpid)
  5948. ->where('user_id', $query_uid)
  5949. ->where('is_deleted', 0)
  5950. ->first();
  5951. if (!$item) {
  5952. Utils::throwError('20003:项目不存在');
  5953. }
  5954. // 验证目标文件夹
  5955. $target_level = 0;
  5956. $target_product = $item->product; // 默认使用当前项目的 product
  5957. if ($target_parent_id > 0) {
  5958. $target_parent = DB::table('mp_products')
  5959. ->where('id', $target_parent_id)
  5960. ->where('cpid', $cpid)
  5961. ->where('user_id', $query_uid)
  5962. ->where('type', 2)
  5963. ->where('is_deleted', 0)
  5964. ->first();
  5965. if (!$target_parent) {
  5966. Utils::throwError('20003:目标文件夹不存在');
  5967. }
  5968. // 检查 product 类型是否一致
  5969. if ($target_parent->product != $item->product) {
  5970. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5971. }
  5972. $target_level = $target_parent->level;
  5973. $target_product = $target_parent->product;
  5974. // 如果移动的是文件夹,需要检查层级
  5975. if ($item->type == 2) {
  5976. // 计算移动后的最大层级
  5977. $max_child_level = $this->getMaxChildLevel($id);
  5978. $depth = $max_child_level - $item->level;
  5979. if ($target_level + 1 + $depth > 3) {
  5980. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5981. }
  5982. // 不能移动到自己或自己的子文件夹下
  5983. if ($this->isDescendant($target_parent_id, $id)) {
  5984. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5985. }
  5986. }
  5987. }
  5988. // 更新父文件夹和层级
  5989. $new_level = $target_level + 1;
  5990. DB::table('mp_products')
  5991. ->where('id', $id)
  5992. ->update([
  5993. 'parent_id' => $target_parent_id,
  5994. 'level' => $new_level,
  5995. 'updated_at' => date('Y-m-d H:i:s')
  5996. ]);
  5997. // 如果是文件夹,需要递归更新所有子项的层级
  5998. if ($item->type == 2) {
  5999. $this->updateChildrenLevel($id, $new_level);
  6000. }
  6001. return true;
  6002. }
  6003. /**
  6004. * 获取文件夹下最大子层级
  6005. * @param int $folder_id
  6006. * @return int
  6007. */
  6008. private function getMaxChildLevel($folder_id) {
  6009. $max_level = DB::table('mp_products')
  6010. ->where('parent_id', $folder_id)
  6011. ->where('is_deleted', 0)
  6012. ->max('level');
  6013. if (!$max_level) {
  6014. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6015. }
  6016. // 递归查找子文件夹
  6017. $children = DB::table('mp_products')
  6018. ->where('parent_id', $folder_id)
  6019. ->where('type', 2)
  6020. ->where('is_deleted', 0)
  6021. ->pluck('id');
  6022. foreach ($children as $child_id) {
  6023. $child_max = $this->getMaxChildLevel($child_id);
  6024. if ($child_max > $max_level) {
  6025. $max_level = $child_max;
  6026. }
  6027. }
  6028. return $max_level;
  6029. }
  6030. /**
  6031. * 检查 target_id 是否是 folder_id 的后代
  6032. * @param int $target_id
  6033. * @param int $folder_id
  6034. * @return bool
  6035. */
  6036. private function isDescendant($target_id, $folder_id) {
  6037. if ($target_id == $folder_id) {
  6038. return true;
  6039. }
  6040. $parent = DB::table('mp_products')
  6041. ->where('id', $target_id)
  6042. ->where('is_deleted', 0)
  6043. ->first();
  6044. if (!$parent || $parent->parent_id == 0) {
  6045. return false;
  6046. }
  6047. return $this->isDescendant($parent->parent_id, $folder_id);
  6048. }
  6049. /**
  6050. * 递归更新子项层级
  6051. * @param int $parent_id
  6052. * @param int $parent_level
  6053. */
  6054. private function updateChildrenLevel($parent_id, $parent_level) {
  6055. $children = DB::table('mp_products')
  6056. ->where('parent_id', $parent_id)
  6057. ->where('is_deleted', 0)
  6058. ->get();
  6059. foreach ($children as $child) {
  6060. $new_level = $parent_level + 1;
  6061. DB::table('mp_products')
  6062. ->where('id', $child->id)
  6063. ->update([
  6064. 'level' => $new_level,
  6065. 'updated_at' => date('Y-m-d H:i:s')
  6066. ]);
  6067. // 如果是文件夹,继续递归
  6068. if ($child->type == 2) {
  6069. $this->updateChildrenLevel($child->id, $new_level);
  6070. }
  6071. }
  6072. }
  6073. /**
  6074. * 获取文件夹路径(面包屑导航)
  6075. * @param array $data 包含 folder_id
  6076. * @return array 返回路径数组
  6077. */
  6078. public function getFolderPath($data) {
  6079. $uid = Site::getUid();
  6080. $cpid = Site::getCpid();
  6081. $folder_id = getProp($data, 'id', 0);
  6082. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6083. if ($folder_id == 0) {
  6084. return [
  6085. ['id' => 0, 'name' => '根目录']
  6086. ];
  6087. }
  6088. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6089. $query_uid = $is_public ? 0 : $uid;
  6090. $path = [];
  6091. $current_id = $folder_id;
  6092. while ($current_id > 0) {
  6093. $folder = DB::table('mp_products')
  6094. ->where('id', $current_id)
  6095. ->where('cpid', $cpid)
  6096. ->where('user_id', $query_uid)
  6097. ->where('type', 2)
  6098. ->where('is_deleted', 0)
  6099. ->first();
  6100. if (!$folder) {
  6101. break;
  6102. }
  6103. array_unshift($path, [
  6104. 'id' => $folder->id,
  6105. 'name' => $folder->product_name
  6106. ]);
  6107. $current_id = $folder->parent_id;
  6108. }
  6109. // 添加根目录
  6110. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6111. return $path;
  6112. }
  6113. public function createProduct($data) {
  6114. $uid = Site::getUid();
  6115. $cpid = Site::getCpid();
  6116. $role = Site::getRole();
  6117. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6118. // 如果是公共库操作,需要admin权限
  6119. if ($is_public && $role !== 'admin') {
  6120. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6121. }
  6122. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6123. $store_uid = $is_public ? 0 : $uid;
  6124. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6125. $script_id = (int)getProp($data, 'script_id', 0);
  6126. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6127. if ($script_id && empty($episode_numbers)) {
  6128. Utils::throwError('20003:剧集序号不能为空');
  6129. }
  6130. if (!$script_id && !empty($episode_numbers)) {
  6131. Utils::throwError('20003:请提供剧本ID');
  6132. }
  6133. $product_name = trim(getProp($data, 'product_name'));
  6134. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6135. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6136. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6137. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6138. $url = trim(getProp($data, 'url'));
  6139. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6140. $versions = getProp($data, 'versions');
  6141. // 检查是否是正确的图片格式
  6142. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6143. $urlPath = parse_url($url, PHP_URL_PATH);
  6144. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6145. if (!in_array($extension, $allowedExtensions)) {
  6146. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6147. }
  6148. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6149. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6150. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6151. $product = getProp($data, 'product');
  6152. if (!in_array($product, [1, 2, 3])) {
  6153. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6154. }
  6155. // 获取父文件夹ID和层级
  6156. $parent_id = getProp($data, 'parent_id', 0);
  6157. $parent_level = 0;
  6158. if ($parent_id > 0) {
  6159. $parent = DB::table('mp_products')
  6160. ->where('id', $parent_id)
  6161. ->where('cpid', $cpid)
  6162. ->where('user_id', $store_uid)
  6163. ->where('type', 2)
  6164. ->where('is_deleted', 0)
  6165. ->first();
  6166. if (!$parent) {
  6167. Utils::throwError('20003:父文件夹不存在');
  6168. }
  6169. $parent_level = $parent->level;
  6170. }
  6171. // 创建资产并保存剧本资产关联关系(同一事务)
  6172. DB::beginTransaction();
  6173. try {
  6174. $id = DB::table('mp_products')->insertGetId([
  6175. 'user_id' => $store_uid,
  6176. 'cpid' => $cpid,
  6177. 'type' => 1, // 1=角色图片
  6178. 'parent_id' => $parent_id,
  6179. 'level' => $parent_level + 1,
  6180. 'product_name' => $product_name,
  6181. 'url' => $url,
  6182. 'pic_prompt' => $pic_prompt,
  6183. 'product' => $product,
  6184. 'versions' => json_encode($versions, 256),
  6185. 'sort_order' => time(), // 使用时间戳作为排序权重
  6186. 'created_at' => date('Y-m-d H:i:s'),
  6187. 'updated_at' => date('Y-m-d H:i:s')
  6188. ]);
  6189. if (!$id) Utils::throwError('20003:创建失败');
  6190. // 保存剧本资产关联关系
  6191. if ($script_id) {
  6192. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6193. }
  6194. DB::commit();
  6195. } catch (\Exception $e) {
  6196. DB::rollback();
  6197. throw $e;
  6198. }
  6199. return [
  6200. 'id' => $id,
  6201. 'type' => 1,
  6202. 'parent_id' => $parent_id,
  6203. 'level' => $parent_level + 1,
  6204. 'product_name' => $product_name,
  6205. 'url' => $url,
  6206. 'pic_prompt' => $pic_prompt,
  6207. 'product' => $product,
  6208. 'versions' => $versions
  6209. ];
  6210. }
  6211. public function editProduct($data) {
  6212. $uid = Site::getUid();
  6213. $cpid = Site::getCpid();
  6214. $role = Site::getRole();
  6215. $id = getProp($data, 'id');
  6216. if (!$id) Utils::throwError('20003:ID不能为空');
  6217. $versions = getProp($data, 'versions');
  6218. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6219. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6220. $script_id = (int)getProp($data, 'script_id', 0);
  6221. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6222. if ($script_id && empty($episode_numbers)) {
  6223. Utils::throwError('20003:剧集序号不能为空');
  6224. }
  6225. if (!$script_id && !empty($episode_numbers)) {
  6226. Utils::throwError('20003:请提供剧本ID');
  6227. }
  6228. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6229. $query_uid = $is_public ? 0 : $uid;
  6230. // 如果是公共库操作,需要admin权限
  6231. if ($is_public && $role !== 'admin') {
  6232. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6233. }
  6234. // 检查是否存在且属于当前用户或公共库
  6235. $role = DB::table('mp_products')
  6236. ->where('id', $id)
  6237. ->where('cpid', $cpid)
  6238. ->where('user_id', $query_uid)
  6239. ->where('type', 1)->first();
  6240. if (!$role) Utils::throwError('20003:记录不存在');
  6241. $updateData = [];
  6242. // $needVersionRecord = false; // 是否需要记录版本
  6243. // 名称
  6244. $product_name = trim(getProp($data, 'product_name'));
  6245. if ($product_name) {
  6246. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6247. $updateData['product_name'] = $product_name;
  6248. }
  6249. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6250. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6251. // 图片地址
  6252. $url = trim(getProp($data, 'url'));
  6253. if ($url) {
  6254. // 检查是否是正确的图片格式
  6255. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6256. $urlPath = parse_url($url, PHP_URL_PATH);
  6257. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6258. if (!in_array($extension, $allowedExtensions)) {
  6259. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6260. }
  6261. // // 如果 url 有变更,记录版本
  6262. // if ($url !== $role->url) {
  6263. // $needVersionRecord = true;
  6264. // }
  6265. $updateData['url'] = $url;
  6266. }
  6267. // 提示词
  6268. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6269. if ($pic_prompt) {
  6270. // // 如果 pic_prompt 有变更,记录版本
  6271. // if ($pic_prompt !== $role->pic_prompt) {
  6272. // $needVersionRecord = true;
  6273. // }
  6274. $updateData['pic_prompt'] = $pic_prompt;
  6275. }
  6276. if (empty($updateData) && !$script_id) {
  6277. Utils::throwError('20003:没有需要更新的数据');
  6278. }
  6279. // // 如果需要记录版本,将数据添加到 versions 数组
  6280. // if ($needVersionRecord) {
  6281. // // 获取现有的 versions 数据
  6282. // $versions = json_decode($role->versions, true) ?: [];
  6283. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6284. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6285. // if ($isFirstVersion) {
  6286. // $oldVersion = [
  6287. // 'url' => $role->url,
  6288. // 'description' => $role->pic_prompt,
  6289. // ];
  6290. // // 旧版本添加到数组末尾
  6291. // $versions[] = $oldVersion;
  6292. // }
  6293. // // 构建新版本(变更后)
  6294. // $newVersion = [
  6295. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6296. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6297. // ];
  6298. // // 检查新版本是否已存在于历史版本中
  6299. // $existingIndex = -1;
  6300. // foreach ($versions as $index => $version) {
  6301. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6302. // $existingIndex = $index;
  6303. // break;
  6304. // }
  6305. // }
  6306. // if ($existingIndex !== -1) {
  6307. // // 如果已存在,移除旧的位置
  6308. // array_splice($versions, $existingIndex, 1);
  6309. // }
  6310. // // 新版本添加到数组开头(最新的在前)
  6311. // array_unshift($versions, $newVersion);
  6312. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6313. // // if (count($versions) > 10) {
  6314. // // $versions = array_slice($versions, 0, 10);
  6315. // // }
  6316. // $updateData['versions'] = json_encode($versions, 256);
  6317. // }
  6318. if ($versions) {
  6319. $updateData['versions'] = json_encode($versions, 256);
  6320. }
  6321. if (!empty($updateData)) {
  6322. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6323. }
  6324. // 更新资产并保存剧本资产关联关系(同一事务)
  6325. DB::beginTransaction();
  6326. try {
  6327. $updated = true;
  6328. if (!empty($updateData)) {
  6329. $updated = DB::table('mp_products')
  6330. ->where('cpid', $cpid)
  6331. ->where('id', $id)
  6332. ->update($updateData);
  6333. }
  6334. // 保存剧本资产关联关系
  6335. if ($script_id) {
  6336. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6337. }
  6338. DB::commit();
  6339. } catch (\Exception $e) {
  6340. DB::rollback();
  6341. throw $e;
  6342. }
  6343. return $updated;
  6344. }
  6345. /**
  6346. * 保存单一资产与剧本剧集的关联关系
  6347. *
  6348. * @param int $product_id 资产ID
  6349. * @param int $script_id 剧本ID
  6350. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6351. * @return int 新增关联数量
  6352. */
  6353. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6354. $uid = Site::getUid();
  6355. // 验证剧本是否存在
  6356. $script = DB::table('mp_scripts')
  6357. ->where('id', $script_id)
  6358. ->where('is_deleted', 0)
  6359. ->first();
  6360. if (!$script) {
  6361. Utils::throwError('20003:剧本不存在');
  6362. }
  6363. // 验证剧本归属:只能关联自己的剧本
  6364. if ((int)$script->user_id !== (int)$uid) {
  6365. Utils::throwError('20003:只能添加到自己的剧本');
  6366. }
  6367. // 使用 splitContent 拆分剧本内容获取总集数
  6368. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6369. // 解析剧集序号(数组)
  6370. $episodes = [];
  6371. foreach ($episode_numbers as $item) {
  6372. if (is_array($item)) {
  6373. continue;
  6374. }
  6375. $item = trim((string)$item);
  6376. if ($item === '' || !is_numeric($item)) {
  6377. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6378. }
  6379. $episodes[] = (int)$item;
  6380. }
  6381. // 去重并校验序号范围(序号从1开始)
  6382. $episodes = array_values(array_unique($episodes));
  6383. if (empty($episodes)) {
  6384. Utils::throwError('20003:剧集序号不能为空');
  6385. }
  6386. foreach ($episodes as $episode) {
  6387. if ($episode < 1 || $episode > $totalEpisodes) {
  6388. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6389. }
  6390. }
  6391. $now = now();
  6392. // 过滤已存在的关联,避免重复
  6393. $existingEpisodes = DB::table('mp_script_product_mappings')
  6394. ->where('script_id', $script_id)
  6395. ->where('product_id', $product_id)
  6396. ->whereIn('episode_number', $episodes)
  6397. ->pluck('episode_number')
  6398. ->all();
  6399. $mappingRecords = [];
  6400. foreach ($episodes as $episode) {
  6401. if (in_array($episode, $existingEpisodes)) {
  6402. continue;
  6403. }
  6404. $mappingRecords[] = [
  6405. 'script_id' => $script_id,
  6406. 'product_id' => $product_id,
  6407. 'episode_number' => $episode,
  6408. 'created_at' => $now,
  6409. 'updated_at' => $now,
  6410. ];
  6411. }
  6412. $insertedCount = 0;
  6413. if (!empty($mappingRecords)) {
  6414. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6415. }
  6416. return $insertedCount;
  6417. }
  6418. /**
  6419. * 规范化剧集序号参数,统一为数组
  6420. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6421. *
  6422. * @param mixed $episode_number 剧集序号参数
  6423. * @return array
  6424. */
  6425. private function normalizeEpisodeNumbers($episode_number) {
  6426. if (!is_array($episode_number)) {
  6427. $episode_number = explode(',', (string)$episode_number);
  6428. }
  6429. $items = [];
  6430. foreach ($episode_number as $item) {
  6431. if (is_array($item)) {
  6432. continue;
  6433. }
  6434. foreach (explode(',', (string)$item) as $part) {
  6435. $part = trim($part);
  6436. if ($part !== '') {
  6437. $items[] = $part;
  6438. }
  6439. }
  6440. }
  6441. return $items;
  6442. }
  6443. /**
  6444. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6445. *
  6446. * @param object $script 剧本记录
  6447. * @return int 总集数
  6448. */
  6449. private function getScriptTotalEpisodeCount($script) {
  6450. if (empty($script->content)) {
  6451. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6452. }
  6453. $totalEpisodes = count(splitContent($script->content));
  6454. if ($totalEpisodes < 1) {
  6455. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6456. }
  6457. return $totalEpisodes;
  6458. }
  6459. /**
  6460. * 获取剧本总集数
  6461. *
  6462. * @param array $data 包含 script_id(剧本ID)
  6463. * @return array
  6464. */
  6465. public function getScriptTotalEpisodes($data) {
  6466. $script_id = (int)getProp($data, 'script_id', 0);
  6467. if (!$script_id) {
  6468. Utils::throwError('20003:请提供剧本ID');
  6469. }
  6470. // 验证剧本是否存在
  6471. $script = DB::table('mp_scripts')
  6472. ->where('id', $script_id)
  6473. ->where('is_deleted', 0)
  6474. ->first();
  6475. if (!$script) {
  6476. Utils::throwError('20003:剧本不存在');
  6477. }
  6478. return [
  6479. 'script_id' => $script_id,
  6480. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6481. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6482. ];
  6483. }
  6484. /**
  6485. * 获取角色版本历史
  6486. * @param array $data 包含 id(角色ID)
  6487. * @return array 返回版本历史列表
  6488. */
  6489. public function getProductVersions($data) {
  6490. $cpid = Site::getCpid();
  6491. $id = getProp($data, 'id');
  6492. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6493. $role = DB::table('mp_products')
  6494. ->where('id', $id)
  6495. ->where('cpid', $cpid)
  6496. ->where('type', 1)
  6497. ->first();
  6498. if (!$role) Utils::throwError('20003:角色不存在');
  6499. // 获取版本历史
  6500. $versions = json_decode($role->versions, true) ?: [];
  6501. // 添加当前版本作为最新版本
  6502. $currentVersion = [
  6503. 'version' => 0, // 0 表示当前版本
  6504. 'url' => $role->url,
  6505. 'pic_prompt' => $role->pic_prompt,
  6506. 'updated_at' => $role->updated_at,
  6507. 'is_current' => true
  6508. ];
  6509. array_unshift($versions, $currentVersion);
  6510. return $versions;
  6511. }
  6512. /**
  6513. * 恢复到指定版本
  6514. * @param array $data 包含 id(角色ID)、version(版本号)
  6515. * @return bool
  6516. */
  6517. public function restoreProductVersion($data) {
  6518. $uid = Site::getUid();
  6519. $cpid = Site::getCpid();
  6520. $id = getProp($data, 'id');
  6521. $version = getProp($data, 'version');
  6522. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6523. if (!$version) Utils::throwError('20003:版本号不能为空');
  6524. $role = DB::table('mp_products')
  6525. ->where('id', $id)
  6526. ->where('cpid', $cpid)
  6527. ->where('type', 1)
  6528. ->first();
  6529. if (!$role) Utils::throwError('20003:角色不存在');
  6530. // 获取版本历史
  6531. $versions = json_decode($role->versions, true) ?: [];
  6532. // 查找指定版本
  6533. $targetVersion = null;
  6534. foreach ($versions as $v) {
  6535. if ($v['version'] == $version) {
  6536. $targetVersion = $v;
  6537. break;
  6538. }
  6539. }
  6540. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6541. // 先将当前版本保存到历史
  6542. $newVersion = [
  6543. 'version' => count($versions) + 1,
  6544. 'url' => $role->url,
  6545. 'pic_prompt' => $role->pic_prompt,
  6546. 'updated_at' => date('Y-m-d H:i:s'),
  6547. 'updated_by' => $uid
  6548. ];
  6549. array_unshift($versions, $newVersion);
  6550. // 限制版本数量
  6551. if (count($versions) > 10) {
  6552. $versions = array_slice($versions, 0, 10);
  6553. }
  6554. // 恢复到指定版本
  6555. return DB::table('mp_products')
  6556. ->where('id', $id)
  6557. ->where('cpid', $cpid)
  6558. ->update([
  6559. 'url' => $targetVersion['url'],
  6560. 'pic_prompt' => $targetVersion['pic_prompt'],
  6561. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6562. 'updated_at' => date('Y-m-d H:i:s')
  6563. ]);
  6564. }
  6565. public function deleteProduct($data) {
  6566. $uid = Site::getUid();
  6567. $cpid = Site::getCpid();
  6568. $role = Site::getRole();
  6569. $id = getProp($data, 'id');
  6570. if (!$id) Utils::throwError('20003:ID不能为空');
  6571. $ids = explode(',', $id);
  6572. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6573. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6574. $query_uid = $is_public ? 0 : $uid;
  6575. // 如果是公共库操作,需要admin权限
  6576. if ($is_public && $role !== 'admin') {
  6577. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6578. }
  6579. // 检查是否存在且属于当前用户或公共库
  6580. $role = DB::table('mp_products')
  6581. ->whereIn('id', $ids)
  6582. ->where('cpid', $cpid)
  6583. ->where('user_id', $query_uid)
  6584. ->get();
  6585. if (!$role) Utils::throwError('20003:记录不存在');
  6586. return DB::table('mp_products')
  6587. ->where('cpid', $cpid)
  6588. ->where('user_id', $query_uid)
  6589. ->whereIn('id', $ids)
  6590. ->update([
  6591. 'is_deleted' => 1,
  6592. 'updated_at' => date('Y-m-d H:i:s')
  6593. ]);
  6594. }
  6595. public function generateThreeView($data) {
  6596. $uid = Site::getUid();
  6597. $cpid = Site::getCpid();
  6598. $role = Site::getRole();
  6599. $id = getProp($data, 'id');
  6600. if (!$id) Utils::throwError('20003:ID不能为空');
  6601. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6602. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6603. $query_uid = $is_public ? 0 : $uid;
  6604. // 如果是公共库操作,需要admin权限
  6605. if ($is_public && $role !== 'admin') {
  6606. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6607. }
  6608. // 检查是否存在且属于当前用户或公共库
  6609. $product = DB::table('mp_products')
  6610. ->where('id', $id)
  6611. ->where('cpid', $cpid)
  6612. ->where('user_id', $query_uid)
  6613. ->where('type', 1)->first();
  6614. if (!$product) Utils::throwError('20003:资产不存在');
  6615. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6616. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6617. if (!$ref_img_url) {
  6618. // 如果没有传入参考图,使用角色表中的图片
  6619. $ref_img_url = $product->url ?? '';
  6620. if (!$ref_img_url) {
  6621. Utils::throwError('20003:参考图不能为空');
  6622. }
  6623. }
  6624. $pic_prompt = getProp($product, 'pic_prompt');
  6625. if ($pic_prompt) {
  6626. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6627. }
  6628. // 检查参考图是否是正确的图片格式
  6629. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6630. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6631. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6632. if (!in_array($extension, $allowedExtensions)) {
  6633. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6634. }
  6635. // 处理图片模型
  6636. $model = getProp($data, 'model');
  6637. if (!$model) {
  6638. // 使用默认模型
  6639. $model = 'doubao-seedream-5-0-lite-260128';
  6640. }
  6641. // 验证模型是否在可用模型表中
  6642. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6643. Utils::throwError('20003:该模型已不可用,请更换!');
  6644. }
  6645. $ratio = getProp($data, 'ratio', '16:9');
  6646. $resolution = getProp($data, 'resolution', '2k');
  6647. // 定义分辨率和宽高比对应的尺寸映射表
  6648. $sizeMap = [
  6649. '2k' => [
  6650. '1:1' => ['width' => 2048, 'height' => 2048],
  6651. '4:3' => ['width' => 2304, 'height' => 1728],
  6652. '3:4' => ['width' => 1728, 'height' => 2304],
  6653. '16:9' => ['width' => 2848, 'height' => 1600],
  6654. '9:16' => ['width' => 1600, 'height' => 2848],
  6655. '3:2' => ['width' => 2496, 'height' => 1664],
  6656. '2:3' => ['width' => 1664, 'height' => 2496],
  6657. '21:9' => ['width' => 3136, 'height' => 1344],
  6658. ],
  6659. '3k' => [
  6660. '1:1' => ['width' => 3072, 'height' => 3072],
  6661. '4:3' => ['width' => 3456, 'height' => 2592],
  6662. '3:4' => ['width' => 2592, 'height' => 3456],
  6663. '16:9' => ['width' => 4096, 'height' => 2304],
  6664. '9:16' => ['width' => 2304, 'height' => 4096],
  6665. '2:3' => ['width' => 2496, 'height' => 3744],
  6666. '3:2' => ['width' => 3744, 'height' => 2496],
  6667. '21:9' => ['width' => 4704, 'height' => 2016],
  6668. ],
  6669. '4k' => [
  6670. '1:1' => ['width' => 4096, 'height' => 4096],
  6671. '3:4' => ['width' => 3520, 'height' => 4704],
  6672. '4:3' => ['width' => 4704, 'height' => 3520],
  6673. '16:9' => ['width' => 5504, 'height' => 3040],
  6674. '9:16' => ['width' => 3040, 'height' => 5504],
  6675. '2:3' => ['width' => 3328, 'height' => 4992],
  6676. '3:2' => ['width' => 4992, 'height' => 3328],
  6677. '21:9' => ['width' => 6240, 'height' => 2656],
  6678. ],
  6679. ];
  6680. // 参数验证
  6681. $resolution = strtolower($resolution);
  6682. if (!isset($sizeMap[$resolution])) {
  6683. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6684. }
  6685. if (!isset($sizeMap[$resolution][$ratio])) {
  6686. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6687. }
  6688. // 根据 ratio 和 resolution 确定宽高
  6689. $width = $sizeMap[$resolution][$ratio]['width'];
  6690. $height = $sizeMap[$resolution][$ratio]['height'];
  6691. try {
  6692. // 创建图片生成任务
  6693. $params = [
  6694. 'prompt' => $prompt,
  6695. 'model' => $model,
  6696. 'ref_img_urls' => [$ref_img_url],
  6697. 'width' => $width,
  6698. 'height' => $height
  6699. ];
  6700. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6701. $task_id = $task->id;
  6702. if (!$task_id) {
  6703. Utils::throwError('20003:创建图片生成任务失败');
  6704. }
  6705. // 轮询获取结果
  6706. // 只查询数据库,不调用API,不更新任务表
  6707. $start_time = time();
  6708. $timeout = 1800;
  6709. $img_url = '';
  6710. while (time() - $start_time < $timeout) {
  6711. sleep(5);
  6712. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6713. $task = DB::table('mp_generate_pic_tasks')
  6714. ->where('id', $task_id)
  6715. ->first();
  6716. if (!$task) {
  6717. Utils::throwError('20003:任务不存在');
  6718. }
  6719. if ($task->status === 'success' && $task->result_url) {
  6720. $result_urls = is_string($task->result_url)
  6721. ? json_decode($task->result_url, true)
  6722. : $task->result_url;
  6723. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6724. break;
  6725. } elseif ($task->status === 'failed') {
  6726. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6727. }
  6728. // 其他状态继续轮询
  6729. }
  6730. if (empty($img_url)) {
  6731. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6732. }
  6733. // 更新 mp_products 表(不是任务表)
  6734. DB::table('mp_products')
  6735. ->where('id', $id)
  6736. ->where('cpid', $cpid)
  6737. ->update([
  6738. 'three_view_image_url' => $img_url,
  6739. 'updated_at' => date('Y-m-d H:i:s')
  6740. ]);
  6741. return ['three_view_image_url' => $img_url];
  6742. } catch (\Exception $e) {
  6743. dLog('anime')->error('生成三视图失败', [
  6744. 'error' => $e->getMessage()
  6745. ]);
  6746. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6747. Utils::throwError('20003:' . $e->getMessage());
  6748. }
  6749. }
  6750. /**
  6751. * 推送(复制)资产或文件夹到目标位置
  6752. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6753. * @return array 返回推送结果
  6754. */
  6755. public function pushProductOrFolder($data) {
  6756. $uid = Site::getUid();
  6757. $cpid = Site::getCpid();
  6758. $role = Site::getRole();
  6759. $product_id = getProp($data, 'product_id');
  6760. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6761. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6762. if (!$product_id) {
  6763. Utils::throwError('20003:请选择要推送的项目');
  6764. }
  6765. // 查询源项目(只通过cpid查询,不限制user_id)
  6766. $sourceItem = DB::table('mp_products')
  6767. ->where('id', $product_id)
  6768. ->where('cpid', $cpid)
  6769. ->where('is_deleted', 0)
  6770. ->first();
  6771. if (!$sourceItem) {
  6772. Utils::throwError('20003:要推送的项目不存在');
  6773. }
  6774. // 通过user_id判断源是公共库还是个人库
  6775. $source_uid = $sourceItem->user_id;
  6776. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6777. // 验证目标文件夹并确定目标是公共库还是个人库
  6778. $target_level = 0;
  6779. $target_uid = $uid; // 默认推送到个人库
  6780. $target_is_public = 0;
  6781. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6782. if ($target_parent_id > 0) {
  6783. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6784. $targetParent = DB::table('mp_products')
  6785. ->where('id', $target_parent_id)
  6786. ->where('cpid', $cpid)
  6787. ->where('type', 2)
  6788. ->where('is_deleted', 0)
  6789. ->first();
  6790. if (!$targetParent) {
  6791. Utils::throwError('20003:目标文件夹不存在');
  6792. }
  6793. // 通过user_id判断目标是公共库还是个人库
  6794. $target_level = $targetParent->level;
  6795. $target_uid = $targetParent->user_id;
  6796. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6797. // 使用目标文件夹的 product 类型
  6798. $final_product_type = $targetParent->product;
  6799. }
  6800. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6801. else {
  6802. $push_to_public = getProp($data, 'push_to_public');
  6803. if ($push_to_public === '') {
  6804. Utils::throwError('20003:请选择是否推送到公共库');
  6805. }
  6806. if ($push_to_public) {
  6807. $target_uid = 0;
  6808. $target_is_public = 1;
  6809. }
  6810. // 推送到根目录时,必须指定 product 类型
  6811. if ($target_product === null || $target_product === '') {
  6812. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6813. }
  6814. $final_product_type = $target_product;
  6815. }
  6816. // 如果目标是公共库,需要admin权限
  6817. if ($target_is_public && $role !== 'admin') {
  6818. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6819. }
  6820. // 权限验证:验证是否符合允许的推送规则
  6821. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6822. try {
  6823. DB::beginTransaction();
  6824. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6825. if ($sourceItem->type == 1) {
  6826. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6827. DB::commit();
  6828. return [
  6829. 'product_id' => $newId,
  6830. ];
  6831. }
  6832. // 如果是文件夹,递归复制(支持跨类型推送)
  6833. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6834. DB::commit();
  6835. return [
  6836. 'product_id' => $newFolderId,
  6837. ];
  6838. } catch (\Exception $e) {
  6839. DB::rollBack();
  6840. dLog('anime')->error('推送失败', [
  6841. 'error' => $e->getMessage(),
  6842. 'product_id' => $product_id
  6843. ]);
  6844. Utils::throwError('20003:' . $e->getMessage());
  6845. }
  6846. }
  6847. /**
  6848. * 验证推送权限
  6849. * 允许的推送规则:
  6850. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6851. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6852. * 3. 公共库推送给公共库(公共库 → 公共库)
  6853. *
  6854. * @param int $source_uid 源的user_id
  6855. * @param int $target_uid 目标的user_id
  6856. * @param int $current_uid 当前用户ID
  6857. * @throws \Exception
  6858. */
  6859. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6860. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6861. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6862. return; // 允许
  6863. }
  6864. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6865. if ($source_uid == 0 && $target_uid == $current_uid) {
  6866. return; // 允许
  6867. }
  6868. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6869. if ($source_uid == 0 && $target_uid == 0) {
  6870. return; // 允许
  6871. }
  6872. // 其他情况都不允许
  6873. if ($source_uid != 0 && $source_uid != $current_uid) {
  6874. // 源是别人的个人库
  6875. Utils::throwError('20003:无权限访问该资产');
  6876. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6877. // 个人库推送给公共库(不允许)
  6878. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6879. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6880. // 不同用户的个人库之间推送(不允许)
  6881. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6882. } else {
  6883. // 其他未知情况
  6884. Utils::throwError('20003:不允许的推送操作');
  6885. }
  6886. }
  6887. /**
  6888. * 复制单个资产
  6889. * @param object $sourceProduct 源资产对象
  6890. * @param int $targetParentId 目标父文件夹ID
  6891. * @param int $targetLevel 目标层级
  6892. * @param int $cpid 公司ID
  6893. * @param int $targetUid 目标用户ID
  6894. * @return int 返回新资产ID
  6895. */
  6896. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6897. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6898. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6899. $newProductData = [
  6900. 'user_id' => $targetUid,
  6901. 'cpid' => $cpid,
  6902. 'type' => 1,
  6903. 'parent_id' => $targetParentId,
  6904. 'level' => $targetLevel,
  6905. 'product_name' => $sourceProduct->product_name,
  6906. 'url' => $sourceProduct->url,
  6907. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6908. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6909. 'product' => $finalProductType,
  6910. 'versions' => $sourceProduct->versions ?? '',
  6911. 'sort_order' => time(),
  6912. 'is_deleted' => 0,
  6913. 'created_at' => date('Y-m-d H:i:s'),
  6914. 'updated_at' => date('Y-m-d H:i:s')
  6915. ];
  6916. return DB::table('mp_products')->insertGetId($newProductData);
  6917. }
  6918. /**
  6919. * 递归复制文件夹及其子项
  6920. * @param object $sourceFolder 源文件夹对象
  6921. * @param int $targetParentId 目标父文件夹ID
  6922. * @param int $targetLevel 目标层级
  6923. * @param int $cpid 公司ID
  6924. * @param int $targetUid 目标用户ID
  6925. * @param int $sourceUid 源用户ID
  6926. * @return int 返回新文件夹ID
  6927. */
  6928. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6929. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6930. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6931. // 创建新文件夹
  6932. $newFolderData = [
  6933. 'user_id' => $targetUid,
  6934. 'cpid' => $cpid,
  6935. 'type' => 2,
  6936. 'parent_id' => $targetParentId,
  6937. 'level' => $targetLevel,
  6938. 'product_name' => $sourceFolder->product_name,
  6939. 'product' => $finalProductType,
  6940. 'sort_order' => time(),
  6941. 'is_deleted' => 0,
  6942. 'created_at' => date('Y-m-d H:i:s'),
  6943. 'updated_at' => date('Y-m-d H:i:s')
  6944. ];
  6945. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6946. // 获取源文件夹下的所有子项
  6947. $children = DB::table('mp_products')
  6948. ->where('parent_id', $sourceFolder->id)
  6949. ->where('cpid', $cpid)
  6950. ->where('user_id', $sourceUid)
  6951. ->where('is_deleted', 0)
  6952. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6953. ->get();
  6954. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6955. foreach ($children as $child) {
  6956. if ($child->type == 1) {
  6957. // 资产
  6958. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6959. } else {
  6960. // 文件夹
  6961. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6962. }
  6963. }
  6964. return $newFolderId;
  6965. }
  6966. /**
  6967. * 保存剧本资产关联关系
  6968. * @param array $data 请求参数
  6969. * @return bool
  6970. */
  6971. public function saveScriptProducts($data) {
  6972. $uid = Site::getUid();
  6973. $cpid = Site::getCpid();
  6974. $script_id = getProp($data, 'script_id');
  6975. $products = getProp($data, 'products', []);
  6976. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6977. if (!$script_id) {
  6978. Utils::throwError('20003:请提供剧本ID');
  6979. }
  6980. // 验证剧本是否存在
  6981. $script = DB::table('mp_scripts')
  6982. ->where('id', $script_id)
  6983. ->where('is_deleted', 0)
  6984. ->first();
  6985. if (!$script) {
  6986. Utils::throwError('20003:剧本不存在');
  6987. }
  6988. // 处理图片模型
  6989. $model = getProp($data, 'model');
  6990. if (!$model) {
  6991. // 使用默认模型
  6992. $model = 'doubao-seedream-5-0-lite-260128';
  6993. }
  6994. // 验证模型是否在可用模型表中
  6995. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6996. Utils::throwError('20003:该模型已不可用,请更换!');
  6997. }
  6998. $ratio = getProp($data, 'ratio', '9:16');
  6999. $resolution = getProp($data, 'resolution', '2k');
  7000. // 定义分辨率和宽高比对应的尺寸映射表
  7001. $sizeMap = [
  7002. '2k' => [
  7003. '1:1' => ['width' => 2048, 'height' => 2048],
  7004. '4:3' => ['width' => 2304, 'height' => 1728],
  7005. '3:4' => ['width' => 1728, 'height' => 2304],
  7006. '16:9' => ['width' => 2848, 'height' => 1600],
  7007. '9:16' => ['width' => 1600, 'height' => 2848],
  7008. '3:2' => ['width' => 2496, 'height' => 1664],
  7009. '2:3' => ['width' => 1664, 'height' => 2496],
  7010. '21:9' => ['width' => 3136, 'height' => 1344],
  7011. ],
  7012. '3k' => [
  7013. '1:1' => ['width' => 3072, 'height' => 3072],
  7014. '4:3' => ['width' => 3456, 'height' => 2592],
  7015. '3:4' => ['width' => 2592, 'height' => 3456],
  7016. '16:9' => ['width' => 4096, 'height' => 2304],
  7017. '9:16' => ['width' => 2304, 'height' => 4096],
  7018. '2:3' => ['width' => 2496, 'height' => 3744],
  7019. '3:2' => ['width' => 3744, 'height' => 2496],
  7020. '21:9' => ['width' => 4704, 'height' => 2016],
  7021. ],
  7022. '4k' => [
  7023. '1:1' => ['width' => 4096, 'height' => 4096],
  7024. '3:4' => ['width' => 3520, 'height' => 4704],
  7025. '4:3' => ['width' => 4704, 'height' => 3520],
  7026. '16:9' => ['width' => 5504, 'height' => 3040],
  7027. '9:16' => ['width' => 3040, 'height' => 5504],
  7028. '2:3' => ['width' => 3328, 'height' => 4992],
  7029. '3:2' => ['width' => 4992, 'height' => 3328],
  7030. '21:9' => ['width' => 6240, 'height' => 2656],
  7031. ],
  7032. ];
  7033. // 参数验证
  7034. $resolution = strtolower($resolution);
  7035. if (!isset($sizeMap[$resolution])) {
  7036. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7037. }
  7038. if (!isset($sizeMap[$resolution][$ratio])) {
  7039. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7040. }
  7041. // 根据 ratio 和 resolution 确定宽高
  7042. $width = $sizeMap[$resolution][$ratio]['width'];
  7043. $height = $sizeMap[$resolution][$ratio]['height'];
  7044. $script_name = $script->script_name ?? 'script_' . $script_id;
  7045. // 检查是否已经有该剧本的资产数据
  7046. $existingMappings = DB::table('mp_script_product_mappings')
  7047. ->where('script_id', $script_id)
  7048. ->get();
  7049. if ($existingMappings->isNotEmpty()) {
  7050. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7051. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7052. // 查询这些资产的图片生成任务状态
  7053. $productsWithTasks = DB::table('mp_products')
  7054. ->whereIn('id', $productIds)
  7055. ->where('is_deleted', 0)
  7056. ->get();
  7057. $productTaskMap = [];
  7058. $typeFolderIds = [];
  7059. $hasAllTasks = true;
  7060. foreach ($productsWithTasks as $product) {
  7061. // 收集类型文件夹ID
  7062. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7063. $parentFolder = DB::table('mp_products')
  7064. ->where('id', $product->parent_id)
  7065. ->where('type', 2)
  7066. ->first();
  7067. if ($parentFolder) {
  7068. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7069. }
  7070. }
  7071. // 检查是否有图片生成任务
  7072. if (!empty($product->pic_task_id)) {
  7073. $productTaskMap[$product->id] = $product->pic_task_id;
  7074. } else if($product->url && $product->pic_task_status == '生成成功') {
  7075. continue;
  7076. } else {
  7077. // 有资产没有图片任务
  7078. $hasAllTasks = false;
  7079. }
  7080. }
  7081. // 如果所有资产都有任务ID,直接轮询返回结果
  7082. if ($hasAllTasks && !empty($productTaskMap)) {
  7083. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7084. 'script_id' => $script_id,
  7085. 'script_name' => $script_name,
  7086. 'product_count' => count($productTaskMap)
  7087. ]);
  7088. // 直接返回 SSE 流轮询结果
  7089. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7090. }
  7091. // 如果部分资产没有任务ID,只为这些资产创建任务
  7092. if (!$hasAllTasks && $auto_generate_images) {
  7093. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7094. 'script_id' => $script_id,
  7095. 'script_name' => $script_name
  7096. ]);
  7097. // 开启事务
  7098. DB::beginTransaction();
  7099. try {
  7100. foreach ($productsWithTasks as $product) {
  7101. // 跳过已有任务的资产
  7102. if (!empty($product->pic_task_id)) {
  7103. continue;
  7104. }
  7105. // 跳过没有提示词的资产
  7106. if (empty($product->pic_prompt)) {
  7107. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7108. 'product_id' => $product->id,
  7109. 'product_name' => $product->product_name
  7110. ]);
  7111. continue;
  7112. }
  7113. try {
  7114. // 创建图片生成任务
  7115. $params = [
  7116. 'prompt' => $product->pic_prompt,
  7117. 'model' => $model,
  7118. 'ref_img_urls' => [],
  7119. 'width' => $width,
  7120. 'height' => $height
  7121. ];
  7122. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7123. $task_id = $task->id;
  7124. if ($task_id) {
  7125. $productTaskMap[$product->id] = $task_id;
  7126. // 在事务中更新资产表的任务ID和状态
  7127. DB::table('mp_products')
  7128. ->where('id', $product->id)
  7129. ->update([
  7130. 'pic_task_id' => $task_id,
  7131. 'pic_task_status' => '生成中',
  7132. 'updated_at' => now()
  7133. ]);
  7134. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7135. 'product_id' => $product->id,
  7136. 'task_id' => $task_id
  7137. ]);
  7138. }
  7139. } catch (\Exception $e) {
  7140. dLog('anime')->error('创建资产图片生成任务失败', [
  7141. 'product_id' => $product->id,
  7142. 'error' => $e->getMessage()
  7143. ]);
  7144. // 标记为失败(仍在事务中)
  7145. DB::table('mp_products')
  7146. ->where('id', $product->id)
  7147. ->update([
  7148. 'pic_task_status' => '生成失败',
  7149. 'updated_at' => now()
  7150. ]);
  7151. }
  7152. }
  7153. // 提交事务
  7154. DB::commit();
  7155. // 如果有新创建的任务,返回 SSE 流
  7156. if (!empty($productTaskMap)) {
  7157. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7158. }
  7159. } catch (\Exception $e) {
  7160. // 回滚事务
  7161. DB::rollback();
  7162. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7163. 'script_id' => $script_id,
  7164. 'error' => $e->getMessage()
  7165. ]);
  7166. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7167. }
  7168. }
  7169. // 如果不需要生成图片,返回已存在的信息
  7170. return [
  7171. 'success' => true,
  7172. 'message' => '剧本资产已存在',
  7173. 'script_id' => $script_id,
  7174. 'script_name' => $script_name,
  7175. 'type_folder_ids' => $typeFolderIds,
  7176. 'existing_products' => count($productIds),
  7177. 'tasks_count' => count($productTaskMap)
  7178. ];
  7179. }
  7180. // 解析 products(可能是 JSON 字符串或数组)
  7181. if (is_string($products)) {
  7182. $products = json_decode($products, true);
  7183. if (json_last_error() !== JSON_ERROR_NONE) {
  7184. Utils::throwError('20003:产品数据格式错误');
  7185. }
  7186. }
  7187. if (!is_array($products) || empty($products)) {
  7188. Utils::throwError('20003:产品数据不能为空');
  7189. }
  7190. // 以下是原有的创建逻辑...
  7191. // 开启事务
  7192. DB::beginTransaction();
  7193. try {
  7194. $now = now();
  7195. $mappingRecords = [];
  7196. $createdProductIds = []; // 记录所有创建的资产ID
  7197. // 获取剧本名称
  7198. $script_name = $script->script_name ?? 'script_' . $script_id;
  7199. // 存储每个类型的根文件夹ID
  7200. $typeFolderIds = [];
  7201. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7202. foreach ($products as $productGroup) {
  7203. $type = getProp($productGroup, 'type');
  7204. $title = getProp($productGroup, 'title', '');
  7205. $content = getProp($productGroup, 'content', []);
  7206. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7207. continue;
  7208. }
  7209. // 为当前类型创建根文件夹(如果还未创建)
  7210. if (!isset($typeFolderIds[$type])) {
  7211. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7212. 'user_id' => $uid,
  7213. 'cpid' => $cpid,
  7214. 'type' => 2, // 1.资产 2文件夹
  7215. 'product' => $type, // 1.主体 2.场景 3.道具
  7216. 'parent_id' => 0, // 根文件夹,parent_id=0
  7217. 'level' => 1, // 第一层级
  7218. 'product_name' => $script_name,
  7219. 'sort_order' => time() + $type,
  7220. 'is_deleted' => 0,
  7221. 'created_at' => $now,
  7222. 'updated_at' => $now
  7223. ]);
  7224. }
  7225. $folder_id = $typeFolderIds[$type];
  7226. // 获取表头(第一行)并查找关键列的位置
  7227. $headers = $content[0];
  7228. $nameColumnIndex = -1; // 资产名称列索引
  7229. $sequenceColumnIndex = -1; // 使用范围列索引
  7230. $promptColumnIndex = -1; // 参考提示词列索引
  7231. foreach ($headers as $index => $header) {
  7232. // 查找"资产名称"列
  7233. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7234. $nameColumnIndex = $index;
  7235. }
  7236. // 查找"使用范围"列
  7237. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7238. $sequenceColumnIndex = $index;
  7239. }
  7240. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7241. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7242. $promptColumnIndex = $index;
  7243. }
  7244. }
  7245. // 验证必要的列是否都找到了
  7246. if ($nameColumnIndex === -1) {
  7247. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7248. continue;
  7249. }
  7250. if ($sequenceColumnIndex === -1) {
  7251. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7252. continue;
  7253. }
  7254. // 跳过表头,解析每一行数据
  7255. for ($i = 1; $i < count($content); $i++) {
  7256. $row = $content[$i];
  7257. // 确保行数据有效
  7258. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7259. continue;
  7260. }
  7261. // 根据动态查找的列索引提取数据
  7262. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7263. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7264. $pic_prompt = '';
  7265. // 提取参考提示词(如果找到了该列)
  7266. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7267. $pic_prompt = trim($row[$promptColumnIndex]);
  7268. }
  7269. // 解析使用范围(逗号分隔的序号)
  7270. $sequences = [];
  7271. if (!empty($sequence_str)) {
  7272. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7273. foreach ($sequenceParts as $part) {
  7274. if (is_numeric($part)) {
  7275. $sequences[] = (int)$part;
  7276. }
  7277. }
  7278. }
  7279. if (empty($product_name)) {
  7280. continue;
  7281. }
  7282. // 处理product_name两边的符号
  7283. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7284. // 如果名称不存在或仅剩占位符号,则跳过
  7285. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7286. dLog('anime')->warning('资产名称无效,跳过保存', [
  7287. 'script_id' => $script_id,
  7288. 'type' => $type,
  7289. 'product_name' => $product_name
  7290. ]);
  7291. continue;
  7292. }
  7293. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7294. $product_id = DB::table('mp_products')->insertGetId([
  7295. 'product_name' => $product_name,
  7296. 'type' => 1, // 1=资产 2.文件夹
  7297. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7298. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7299. 'level' => 2, // 第二层级
  7300. 'pic_prompt' => $pic_prompt,
  7301. 'user_id' => $uid,
  7302. 'cpid' => $cpid,
  7303. 'sort_order' => time(),
  7304. 'is_deleted' => 0,
  7305. 'created_at' => $now,
  7306. 'updated_at' => $now,
  7307. ]);
  7308. // 记录创建的资产ID
  7309. $createdProductIds[] = $product_id;
  7310. // 为每个序号创建映射记录
  7311. if (!empty($sequences)) {
  7312. foreach ($sequences as $sequence) {
  7313. $mappingRecords[] = [
  7314. 'script_id' => $script_id,
  7315. 'product_id' => $product_id,
  7316. 'episode_number' => $sequence,
  7317. 'created_at' => $now,
  7318. 'updated_at' => $now,
  7319. ];
  7320. }
  7321. } else {
  7322. // 如果没有指定序号,创建一个默认映射(序号为0)
  7323. $mappingRecords[] = [
  7324. 'script_id' => $script_id,
  7325. 'product_id' => $product_id,
  7326. 'episode_number' => 0,
  7327. 'created_at' => $now,
  7328. 'updated_at' => $now,
  7329. ];
  7330. }
  7331. }
  7332. }
  7333. if (empty($mappingRecords)) {
  7334. Utils::throwError('20003:没有有效的产品数据');
  7335. }
  7336. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7337. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7338. // 剧本已有资产,同步更新is_products标记
  7339. DB::table('mp_scripts')->where('id', $script_id)->update([
  7340. 'is_products' => 1,
  7341. 'updated_at' => $now
  7342. ]);
  7343. // 如果需要自动生成图片,在事务中创建图片生成任务
  7344. $productTaskMap = [];
  7345. if ($auto_generate_images && !empty($createdProductIds)) {
  7346. // 查询所有创建的资产
  7347. $productsToGenerate = DB::table('mp_products')
  7348. ->whereIn('id', $createdProductIds)
  7349. ->where('is_deleted', 0)
  7350. ->get();
  7351. foreach ($productsToGenerate as $product) {
  7352. if (empty($product->pic_prompt)) {
  7353. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7354. 'product_id' => $product->id,
  7355. 'product_name' => $product->product_name
  7356. ]);
  7357. continue;
  7358. }
  7359. try {
  7360. // 创建图片生成任务
  7361. $params = [
  7362. 'prompt' => $product->pic_prompt,
  7363. 'model' => $model,
  7364. 'ref_img_urls' => [],
  7365. 'width' => $width,
  7366. 'height' => $height
  7367. ];
  7368. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7369. $task_id = $task->id;
  7370. if ($task_id) {
  7371. $productTaskMap[$product->id] = $task_id;
  7372. // 在事务中更新资产表的任务ID和状态
  7373. DB::table('mp_products')
  7374. ->where('id', $product->id)
  7375. ->update([
  7376. 'pic_task_id' => $task_id,
  7377. 'pic_task_status' => '生成中',
  7378. 'updated_at' => now()
  7379. ]);
  7380. dLog('anime')->info('创建资产图片生成任务', [
  7381. 'product_id' => $product->id,
  7382. 'task_id' => $task_id
  7383. ]);
  7384. }
  7385. } catch (\Exception $e) {
  7386. dLog('anime')->error('创建资产图片生成任务失败', [
  7387. 'product_id' => $product->id,
  7388. 'error' => $e->getMessage()
  7389. ]);
  7390. // 标记为失败(仍在事务中)
  7391. DB::table('mp_products')
  7392. ->where('id', $product->id)
  7393. ->update([
  7394. 'pic_task_status' => '生成失败',
  7395. 'updated_at' => now()
  7396. ]);
  7397. }
  7398. }
  7399. }
  7400. // 提交事务
  7401. DB::commit();
  7402. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7403. if ($auto_generate_images && !empty($productTaskMap)) {
  7404. // 返回 SSE 流(事务外轮询)
  7405. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7406. }
  7407. // 如果不需要生成图片,返回普通结果
  7408. return [
  7409. 'success' => true,
  7410. 'type_folder_ids' => $typeFolderIds,
  7411. 'inserted_count' => $insertedCount,
  7412. 'total_records' => count($mappingRecords),
  7413. 'created_products' => count($createdProductIds),
  7414. 'image_tasks_created' => count($productTaskMap)
  7415. ];
  7416. } catch (\Exception $e) {
  7417. // 回滚事务
  7418. DB::rollback();
  7419. // 记录错误日志
  7420. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7421. 'script_id' => $script_id,
  7422. 'error' => $e->getMessage(),
  7423. 'trace' => $e->getTraceAsString()
  7424. ]);
  7425. // 统一使用 Utils::throwError 抛出错误
  7426. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7427. }
  7428. }
  7429. /**
  7430. * 批量为剧本资产生成图片
  7431. *
  7432. * @param array $data 请求参数
  7433. * @return \Generator 返回 SSE 流
  7434. */
  7435. public function batchGenerateProductImages($data) {
  7436. $script_id = getProp($data, 'script_id');
  7437. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7438. if (!$script_id) {
  7439. Utils::throwError('20003:请提供剧本ID');
  7440. }
  7441. // 验证剧本是否存在
  7442. $script = DB::table('mp_scripts')
  7443. ->where('id', $script_id)
  7444. ->where('is_deleted', 0)
  7445. ->first();
  7446. if (!$script) {
  7447. Utils::throwError('20003:剧本不存在');
  7448. }
  7449. $script_name = $script->script_name ?? 'script_' . $script_id;
  7450. // 获取需要生成图片的所有资产
  7451. $products = DB::table('mp_products')
  7452. ->whereIn('parent_id', array_values($type_folder_ids))
  7453. ->where('is_deleted', 0)
  7454. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7455. ->get();
  7456. if ($products->isEmpty()) {
  7457. Utils::throwError('20003:没有找到需要生成图片的资产');
  7458. }
  7459. // 默认参数
  7460. $model = 'doubao-seedream-5-0-lite-260128';
  7461. $width = 1600;
  7462. $height = 2848;
  7463. // 开始为每个资产创建图片生成任务
  7464. $taskIds = [];
  7465. $productTaskMap = []; // 资产ID到任务ID的映射
  7466. foreach ($products as $product) {
  7467. if (empty($product->pic_prompt)) {
  7468. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7469. continue;
  7470. }
  7471. try {
  7472. // 创建图片生成任务
  7473. $params = [
  7474. 'prompt' => $product->pic_prompt,
  7475. 'model' => $model,
  7476. 'ref_img_urls' => [],
  7477. 'width' => $width,
  7478. 'height' => $height
  7479. ];
  7480. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7481. $task_id = $task->id;
  7482. if ($task_id) {
  7483. $taskIds[] = $task_id;
  7484. $productTaskMap[$product->id] = $task_id;
  7485. // 更新资产表的任务ID和状态
  7486. DB::table('mp_products')
  7487. ->where('id', $product->id)
  7488. ->update([
  7489. 'pic_task_id' => $task_id,
  7490. 'pic_task_status' => '生成中',
  7491. 'updated_at' => now()
  7492. ]);
  7493. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7494. }
  7495. } catch (\Exception $e) {
  7496. dLog('anime')->error('创建资产图片生成任务失败', [
  7497. 'product_id' => $product->id,
  7498. 'error' => $e->getMessage()
  7499. ]);
  7500. // 标记为失败
  7501. DB::table('mp_products')
  7502. ->where('id', $product->id)
  7503. ->update([
  7504. 'pic_task_status' => '生成失败',
  7505. 'updated_at' => now()
  7506. ]);
  7507. }
  7508. }
  7509. if (empty($taskIds)) {
  7510. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7511. }
  7512. // 返回 SSE 流
  7513. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7514. }
  7515. /**
  7516. * 轮询资产图片生成任务状态(SSE流式返回)
  7517. * 只通过查询数据库获取任务状态,不主动调用API
  7518. *
  7519. * @param int $script_id 剧本ID
  7520. * @param string $script_name 剧本名称
  7521. * @param array $productTaskMap 资产ID到任务ID的映射
  7522. * @param array $type_folder_ids 类型文件夹ID映射
  7523. * @return \Generator
  7524. */
  7525. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7526. $startTime = time();
  7527. $timeout = 1800; // 30分钟超时
  7528. $pollInterval = 10; // 10秒轮询一次
  7529. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7530. // 定义类型名称映射
  7531. $typeNames = [
  7532. 1 => 'roles', // 角色
  7533. 2 => 'scenes', // 场景
  7534. 3 => 'props' // 道具
  7535. ];
  7536. while (time() - $startTime < $timeout) {
  7537. sleep($pollInterval);
  7538. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7539. $mappings = DB::table('mp_script_product_mappings')
  7540. ->where('script_id', $script_id)
  7541. ->pluck('product_id')
  7542. ->unique()
  7543. ->toArray();
  7544. if (empty($mappings)) {
  7545. dLog('anime')->warning('该剧本没有关联的资产', [
  7546. 'script_id' => $script_id,
  7547. 'script_name' => $script_name
  7548. ]);
  7549. break;
  7550. }
  7551. // 查询所有资产的当前状态
  7552. $products = DB::table('mp_products')
  7553. ->whereIn('id', $mappings)
  7554. ->where('is_deleted', 0)
  7555. ->get();
  7556. // 统计各类型的状态(使用类型名称作为键名)
  7557. $stats = [
  7558. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7559. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7560. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7561. ];
  7562. $allCompleted = true;
  7563. $hasStatusChange = false;
  7564. foreach ($products as $product) {
  7565. $type = $product->product;
  7566. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7567. // 如果类型名称不在 stats 中,初始化
  7568. if (!isset($stats[$typeName])) {
  7569. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7570. }
  7571. $stats[$typeName]['total']++;
  7572. $task_id = $product->pic_task_id;
  7573. $currentStatus = $product->pic_task_status;
  7574. // 检查状态是否有变化
  7575. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7576. $hasStatusChange = true;
  7577. $lastStatus[$product->id] = $currentStatus;
  7578. }
  7579. // 如果是生成中,查询任务表状态
  7580. if ($currentStatus === '生成中' && $task_id) {
  7581. // 只查询数据库,不调用API
  7582. $task = DB::table('mp_generate_pic_tasks')
  7583. ->where('id', $task_id)
  7584. ->first();
  7585. if ($task) {
  7586. // 检查任务状态
  7587. if ($task->status === 'success' && $task->result_url) {
  7588. // 解析图片URL
  7589. $result_urls = $task->result_url;
  7590. if (is_string($result_urls)) {
  7591. $result_urls = json_decode($result_urls, true);
  7592. }
  7593. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7594. // 更新资产表状态
  7595. DB::table('mp_products')
  7596. ->where('id', $product->id)
  7597. ->update([
  7598. 'pic_task_status' => '生成成功',
  7599. 'url' => $img_url,
  7600. 'updated_at' => now()
  7601. ]);
  7602. $stats[$typeName]['success']++;
  7603. $stats[$typeName]['completed']++;
  7604. $hasStatusChange = true;
  7605. dLog('anime')->info('资产图片生成成功', [
  7606. 'product_id' => $product->id,
  7607. 'task_id' => $task_id,
  7608. 'img_url' => $img_url
  7609. ]);
  7610. } elseif ($task->status === 'failed') {
  7611. // 更新资产表状态
  7612. DB::table('mp_products')
  7613. ->where('id', $product->id)
  7614. ->update([
  7615. 'pic_task_status' => '生成失败',
  7616. 'updated_at' => now()
  7617. ]);
  7618. $stats[$typeName]['completed']++;
  7619. $hasStatusChange = true;
  7620. dLog('anime')->warning('资产图片生成失败', [
  7621. 'product_id' => $product->id,
  7622. 'task_id' => $task_id,
  7623. 'error' => $task->error_message ?? '未知错误'
  7624. ]);
  7625. } else {
  7626. // 任务还在处理中
  7627. $allCompleted = false;
  7628. }
  7629. } else {
  7630. // 任务不存在,标记为失败
  7631. DB::table('mp_products')
  7632. ->where('id', $product->id)
  7633. ->update([
  7634. 'pic_task_status' => '生成失败',
  7635. 'updated_at' => now()
  7636. ]);
  7637. $stats[$type]['completed']++;
  7638. $hasStatusChange = true;
  7639. dLog('anime')->error('图片生成任务不存在', [
  7640. 'product_id' => $product->id,
  7641. 'task_id' => $task_id
  7642. ]);
  7643. }
  7644. } elseif ($currentStatus === '生成成功') {
  7645. $stats[$typeName]['success']++;
  7646. $stats[$typeName]['completed']++;
  7647. } elseif ($currentStatus === '生成失败') {
  7648. $stats[$typeName]['completed']++;
  7649. } else {
  7650. // 其他状态也认为未完成
  7651. $allCompleted = false;
  7652. }
  7653. }
  7654. // 移除没有数据的类型(total=0)
  7655. foreach ($stats as $typeName => $stat) {
  7656. if ($stat['total'] === 0) {
  7657. unset($stats[$typeName]);
  7658. }
  7659. }
  7660. // 如果有状态变化,发送 SSE 更新
  7661. if ($hasStatusChange) {
  7662. $eventType = $allCompleted ? 'complete' : 'update';
  7663. $response = [
  7664. 'type' => $eventType,
  7665. 'script_id' => $script_id,
  7666. 'script_name' => $script_name,
  7667. 'stats' => $stats,
  7668. 'timestamp' => date('Y-m-d H:i:s')
  7669. ];
  7670. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7671. dLog('anime')->info('SSE更新', [
  7672. 'event_type' => $eventType,
  7673. 'script_id' => $script_id,
  7674. 'script_name' => $script_name,
  7675. 'stats' => $stats
  7676. ]);
  7677. if ($allCompleted) {
  7678. dLog('anime')->info('所有资产图片生成任务已完成', [
  7679. 'script_id' => $script_id,
  7680. 'script_name' => $script_name,
  7681. 'stats' => $stats
  7682. ]);
  7683. break;
  7684. }
  7685. }
  7686. }
  7687. // 超时处理
  7688. if (time() - $startTime >= $timeout && !$allCompleted) {
  7689. $response = [
  7690. 'type' => 'timeout',
  7691. 'message' => '部分任务超时,请稍后查看结果',
  7692. 'script_id' => $script_id,
  7693. 'script_name' => $script_name,
  7694. 'timestamp' => date('Y-m-d H:i:s')
  7695. ];
  7696. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7697. dLog('anime')->warning('资产图片生成任务超时', [
  7698. 'script_id' => $script_id,
  7699. 'script_name' => $script_name,
  7700. 'timeout' => $timeout
  7701. ]);
  7702. }
  7703. }
  7704. /**
  7705. * 获取剧本关联的资产列表
  7706. * @param array $data 请求参数
  7707. * @return array
  7708. */
  7709. public function getScriptProducts($data) {
  7710. $uid = Site::getUid();
  7711. $cpid = Site::getCpid();
  7712. $script_id = getProp($data, 'script_id');
  7713. $episode_number = getProp($data, 'episode_number');
  7714. if (!$script_id) {
  7715. Utils::throwError('20003:请提供剧本ID');
  7716. }
  7717. // 验证剧本是否存在
  7718. $script = DB::table('mp_scripts')
  7719. ->where('id', $script_id)
  7720. ->where('is_deleted', 0)
  7721. ->first();
  7722. if (!$script) {
  7723. Utils::throwError('20003:剧本不存在');
  7724. }
  7725. // 联表查询资产信息
  7726. $query = DB::table('mp_script_product_mappings as mapping')
  7727. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7728. ->where('mapping.script_id', $script_id)
  7729. ->where('product.cpid', $cpid)
  7730. ->where('product.is_deleted', 0);
  7731. // 如果提供了 episode_number,则过滤指定集数
  7732. if ($episode_number !== null && $episode_number !== '') {
  7733. $query->where('mapping.episode_number', $episode_number);
  7734. }
  7735. $mappings = $query->select(
  7736. 'mapping.script_id',
  7737. 'mapping.product_id',
  7738. 'mapping.episode_number',
  7739. 'product.product_name',
  7740. 'product.type',
  7741. 'product.product',
  7742. 'product.pic_prompt',
  7743. 'product.url',
  7744. 'product.pic_task_id',
  7745. 'product.pic_task_status',
  7746. 'product.three_view_image_url',
  7747. 'mapping.created_at'
  7748. )
  7749. ->orderBy('mapping.product_id', 'asc')
  7750. ->orderBy('mapping.episode_number', 'asc')
  7751. ->get();
  7752. // 按 product_id 分组,合并 episode_number
  7753. $productMap = [];
  7754. foreach ($mappings as $item) {
  7755. $product_id = $item->product_id;
  7756. if (!isset($productMap[$product_id])) {
  7757. $productMap[$product_id] = [
  7758. 'product_id' => $product_id,
  7759. 'product_name' => $item->product_name,
  7760. 'type' => (int)$item->type,
  7761. 'product' => (int)$item->product,
  7762. 'pic_prompt' => $item->pic_prompt,
  7763. 'url' => $item->url,
  7764. 'pic_task_id' => $item->pic_task_id,
  7765. 'pic_task_status' => $item->pic_task_status,
  7766. 'episode_numbers' => [],
  7767. 'created_at' => $item->created_at,
  7768. ];
  7769. }
  7770. // 添加 episode_number(去重)
  7771. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7772. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7773. }
  7774. }
  7775. // 按类型分组
  7776. $roles = []; // type=1 角色/主体
  7777. $scenes = []; // type=2 场景
  7778. $props = []; // type=3 道具
  7779. foreach ($productMap as $product) {
  7780. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7781. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7782. // 构造返回数据
  7783. $productData = [
  7784. 'product_id' => $product['product_id'],
  7785. 'product_name' => $product['product_name'],
  7786. 'product' => $product['product'],
  7787. 'pic_prompt' => $product['pic_prompt'],
  7788. 'url' => $product['url'],
  7789. 'pic_task_id' => $product['pic_task_id'],
  7790. 'pic_task_status' => $product['pic_task_status'],
  7791. 'episode_numbers' => $episodeNumbersStr,
  7792. 'created_at' => $product['created_at'],
  7793. ];
  7794. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7795. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7796. switch ($product['product']) {
  7797. case 1:
  7798. $roles[] = $productData;
  7799. break;
  7800. case 2:
  7801. $scenes[] = $productData;
  7802. break;
  7803. case 3:
  7804. $props[] = $productData;
  7805. break;
  7806. }
  7807. }
  7808. return [
  7809. 'script_id' => $script_id,
  7810. 'script_name' => $script->script_name ?? '',
  7811. 'roles' => $roles, // 主体
  7812. 'scenes' => $scenes, // 场景
  7813. 'props' => $props, // 道具
  7814. ];
  7815. }
  7816. /**
  7817. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7818. * @param string $actContent 原始内容
  7819. * @param array $products 产品数组(包含product_name和url)
  7820. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7821. */
  7822. public function processActContentWithProducts($actContent, $products) {
  7823. if (empty($actContent) || empty($products)) {
  7824. return [
  7825. 'content' => $actContent,
  7826. 'reference_images' => []
  7827. ];
  7828. }
  7829. // 构建产品名称到产品信息的映射
  7830. $product_dict = [];
  7831. foreach ($products as $product) {
  7832. $product_name = getProp($product, 'product_name');
  7833. if ($product_name) {
  7834. $product_dict[$product_name] = [
  7835. 'url' => getProp($product, 'url'),
  7836. 'voice_prompt' => getProp($product, 'voice_prompt')
  7837. ];
  7838. }
  7839. }
  7840. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7841. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7842. $reference_images = [];
  7843. $product_index_map = []; // 产品名称 => 图片序号的映射
  7844. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7845. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7846. $current_index = 1;
  7847. if (!empty($matches[1])) {
  7848. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7849. $seen_products = []; // 用于去重
  7850. foreach ($matches[1] as $product_name) {
  7851. // 跳过已处理的产品
  7852. if (isset($seen_products[$product_name])) {
  7853. continue;
  7854. }
  7855. $seen_products[$product_name] = true;
  7856. // 检查产品是否在字典中
  7857. if (isset($product_dict[$product_name])) {
  7858. $url = $product_dict[$product_name]['url'];
  7859. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7860. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7861. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7862. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7863. }
  7864. // 只有URL非空才分配序号和添加到参考图片
  7865. if (!empty($url)) {
  7866. // 检查URL是否已经在reference_images中(去重)
  7867. if (!in_array($url, $reference_images)) {
  7868. $reference_images[] = $url;
  7869. $product_index_map[$product_name] = $current_index;
  7870. $current_index++;
  7871. } else {
  7872. // URL重复,找到已有的序号
  7873. $existing_index = array_search($url, $reference_images) + 1;
  7874. $product_index_map[$product_name] = $existing_index;
  7875. }
  7876. } else {
  7877. // URL为空,不分配序号(后续直接去掉{})
  7878. $product_index_map[$product_name] = 0;
  7879. }
  7880. } else {
  7881. // 产品不在字典中,不分配序号
  7882. $product_index_map[$product_name] = 0;
  7883. }
  7884. }
  7885. }
  7886. // 第二步:替换内容中的 {产品名称}
  7887. $processedContent = $actContent;
  7888. foreach ($product_index_map as $product_name => $index) {
  7889. $escaped_name = preg_quote($product_name, '/');
  7890. if ($index > 0) {
  7891. // 有图片,替换为:产品名称(图X)
  7892. $replacement = $product_name . '<图片' . $index . '>';
  7893. } else {
  7894. // 无图片,只保留产品名称
  7895. $replacement = $product_name;
  7896. }
  7897. // 替换所有 {产品名称} 为处理后的格式
  7898. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7899. }
  7900. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7901. foreach ($products as $product) {
  7902. $product_name = getProp($product, 'product_name');
  7903. $voice_prompt = getProp($product, 'voice_prompt');
  7904. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7905. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7906. break; // 找到旁白后退出循环
  7907. }
  7908. }
  7909. // 第四步:将voice_prompt信息添加到内容最前面
  7910. $voice_prompt_prefix = '';
  7911. if (!empty($voice_prompts)) {
  7912. $voice_prompt_prefix .= implode('', $voice_prompts);
  7913. }
  7914. // 旁白的voice_prompt放在最后
  7915. if (!empty($narrator_voice_prompt)) {
  7916. $voice_prompt_prefix .= $narrator_voice_prompt;
  7917. }
  7918. // 如果有voice_prompt信息,添加到内容开头
  7919. if (!empty($voice_prompt_prefix)) {
  7920. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7921. }
  7922. return [
  7923. 'content' => $processedContent,
  7924. 'reference_images' => $reference_images
  7925. ];
  7926. }
  7927. public function saveActVideoGenerateParams($data) {
  7928. $episode_id = getProp($data, 'episode_id');
  7929. $model = getProp($data, 'video_model');
  7930. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7931. Utils::throwError('20003:该模型不可用');
  7932. }
  7933. if (!$model) {
  7934. // 使用默认模型
  7935. $model = 'zhizhen-20';
  7936. }
  7937. // 验证模型是否在可用模型表中
  7938. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7939. Utils::throwError('20003:该模型已不可用,请更换!');
  7940. }
  7941. $video_resolution = getProp($data, 'video_resolution', '720p');
  7942. $ratio = getProp($data, 'ratio');
  7943. if (!$ratio) $ratio = '9:16';
  7944. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  7945. if (!$episode) {
  7946. Utils::throwError('20003:分集不存在');
  7947. }
  7948. try {
  7949. DB::beginTransaction();
  7950. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7951. 'video_model' => $model,
  7952. 'video_resolution' => $video_resolution,
  7953. 'ratio' => $ratio,
  7954. 'updated_at' => date('Y-m-d H:i:s')
  7955. ]);
  7956. if ($result === false) {
  7957. Utils::throwError('20003:分集视频参数保存失败');
  7958. }
  7959. // 同步更新mp_animes表
  7960. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  7961. 'video_model' => $model,
  7962. 'video_resolution' => $video_resolution,
  7963. 'video_ratio' => $ratio,
  7964. 'updated_at' => date('Y-m-d H:i:s')
  7965. ]);
  7966. if ($anime_result === false) {
  7967. Utils::throwError('20003:动漫视频参数保存失败');
  7968. }
  7969. } catch (\Exception $e) {
  7970. DB::rollBack();
  7971. Utils::throwError('20003:'.$e->getMessage());
  7972. }
  7973. DB::commit();
  7974. return $result;
  7975. }
  7976. public function confirmActs($data) {
  7977. $episode_id = getProp($data, 'episode_id');
  7978. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7979. if (!$episode) {
  7980. Utils::throwError('20003:分集不存在');
  7981. }
  7982. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7983. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7984. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7985. // 获取所有片段数据
  7986. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7987. // 收集所有资产名称(角色、场景、道具)
  7988. $product_names = [];
  7989. // 收集角色名称
  7990. foreach ($roles as $role) {
  7991. $role_name = getProp($role, 'role');
  7992. if ($role_name && $role_name != '旁白') {
  7993. $product_names[] = $role_name;
  7994. }
  7995. }
  7996. // 收集场景名称
  7997. foreach ($scenes as $scene) {
  7998. $scene_name = getProp($scene, 'scene');
  7999. if ($scene_name) {
  8000. $product_names[] = $scene_name;
  8001. }
  8002. }
  8003. // 收集道具名称
  8004. foreach ($props as $prop) {
  8005. $prop_name = getProp($prop, 'prop');
  8006. if ($prop_name) {
  8007. $product_names[] = $prop_name;
  8008. }
  8009. }
  8010. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8011. $product_names = array_unique($product_names);
  8012. usort($product_names, function($a, $b) {
  8013. return mb_strlen($b) - mb_strlen($a);
  8014. });
  8015. try {
  8016. DB::beginTransaction();
  8017. // 处理每个片段
  8018. foreach ($acts as $act) {
  8019. $act_content = getProp($act, 'act_content');
  8020. if (!$act_content) continue;
  8021. $processed_content = $act_content;
  8022. // 统一替换所有资产名称为 {资产名} 格式
  8023. // 使用占位符避免嵌套替换问题
  8024. $placeholder_map = [];
  8025. $placeholder_index = 0;
  8026. foreach ($product_names as $product_name) {
  8027. // 转义特殊字符
  8028. $escaped_product = preg_quote($product_name, '/');
  8029. // 检查是否匹配且未被 {} 包裹
  8030. $processed_content = preg_replace_callback(
  8031. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8032. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8033. // 使用唯一占位符
  8034. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8035. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8036. $placeholder_index++;
  8037. return $placeholder;
  8038. },
  8039. $processed_content
  8040. );
  8041. }
  8042. // 将所有占位符替换回实际内容
  8043. foreach ($placeholder_map as $placeholder => $replacement) {
  8044. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8045. }
  8046. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8047. $shot_counter = 0;
  8048. $processed_content = preg_replace_callback(
  8049. '/【(?:镜头|分镜)(\d+)】/u',
  8050. function($matches) use (&$shot_counter) {
  8051. $shot_counter++;
  8052. return '【镜头' . $shot_counter . '】';
  8053. },
  8054. $processed_content
  8055. );
  8056. // 更新数据库
  8057. $boolen = DB::table('mp_episode_segments')
  8058. ->where('id', $act->id)
  8059. ->update([
  8060. 'act_show_content' => $processed_content,
  8061. 'updated_at' => date('Y-m-d H:i:s')
  8062. ]);
  8063. if (!$boolen) {
  8064. Utils::throwError('20003:片段处理失败');
  8065. }
  8066. }
  8067. }catch (\Exception $e) {
  8068. DB::rollBack();
  8069. Utils::throwError('20003:'.$e->getMessage());
  8070. }
  8071. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8072. 'is_generated' => 1,
  8073. 'updated_at' => date('Y-m-d H:i:s')
  8074. ]);
  8075. if (!$boolen1) {
  8076. DB::rollBack();
  8077. Utils::throwError('20003:分集处理失败!');
  8078. }
  8079. DB::commit();
  8080. // 重新查询更新后的片段数据
  8081. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8082. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8083. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8084. $products = [];
  8085. // 先处理角色数组
  8086. foreach ($roles as $role) {
  8087. $product = $role;
  8088. // 将role字段重命名为product_name
  8089. if (isset($product['role'])) {
  8090. $product['product_name'] = $product['role'];
  8091. unset($product['role']);
  8092. $product['product'] = 1; // 标记类型为角色
  8093. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8094. }
  8095. }
  8096. // 处理场景数组
  8097. foreach ($scenes as $scene) {
  8098. $product = $scene;
  8099. // 将scene字段重命名为product_name
  8100. if (isset($product['scene'])) {
  8101. $product['product_name'] = $product['scene'];
  8102. unset($product['scene']);
  8103. $product['product'] = 2; // 标记类型为场景
  8104. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8105. }
  8106. }
  8107. // 处理道具数组(逻辑与场景一致)
  8108. foreach ($props as $prop) {
  8109. $product = $prop;
  8110. // 将prop字段重命名为product_name
  8111. if (isset($product['prop'])) {
  8112. $product['product_name'] = $product['prop'];
  8113. unset($product['prop']);
  8114. $product['product'] = 3; // 标记类型为道具
  8115. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8116. }
  8117. }
  8118. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8119. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8120. foreach ($extra_products as $extra_product) {
  8121. $product_name = getProp($extra_product, 'product_name');
  8122. if ($product_name) {
  8123. $products[$product_name] = $extra_product; // 覆盖同名数据
  8124. }
  8125. }
  8126. // 重新索引数组(去除key)
  8127. $products = array_values($products);
  8128. // 构建返回的acts数组
  8129. $return_acts = [];
  8130. foreach ($acts as $act) {
  8131. $return_acts[] = [
  8132. 'act_id' => getProp($act, 'id'),
  8133. 'act_number' => getProp($act, 'act_number'),
  8134. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8135. 'act_show_content' => getProp($act, 'act_show_content'),
  8136. 'video_url' => getProp($act, 'video_url'),
  8137. 'video_duration' => getProp($act, 'video_duration'),
  8138. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8139. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8140. ];
  8141. }
  8142. return [
  8143. 'anime_id' => getProp($episode, 'anime_id'),
  8144. 'episode_id' => $episode_id,
  8145. 'title' => getProp($episode, 'title'),
  8146. 'episode_number' => getProp($episode, 'episode_number'),
  8147. 'is_generated' => getProp($episode, 'is_generated'),
  8148. 'video_params' => [
  8149. 'video_model' => getProp($episode, 'video_model'),
  8150. 'video_resolution' => getProp($episode, 'video_resolution'),
  8151. 'ratio' => getProp($episode, 'ratio'),
  8152. ],
  8153. 'products' => $products,
  8154. 'acts' => $return_acts
  8155. ];
  8156. }
  8157. /**
  8158. * 导出动漫剧本为PDF(参照示例PDF版式)
  8159. * @param int $animeId 动漫ID
  8160. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8161. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8162. * @return string|null
  8163. */
  8164. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8165. // 图片下载与转换可能占用较多内存
  8166. ini_set('memory_limit', '512M');
  8167. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8168. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8169. $anime = (array)$anime;
  8170. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8171. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8172. // 获取分集(默认展示版本,按集数升序)
  8173. $episodeQuery = DB::table('mp_anime_episodes')
  8174. ->where('anime_id', $animeId)
  8175. ->where('is_default', 1)
  8176. ->orderBy('episode_number')
  8177. ->orderBy('id');
  8178. if ($episodeCount > 0) {
  8179. $episodeQuery->limit($episodeCount);
  8180. }
  8181. $episodes = $episodeQuery->get()->map(function ($value) {
  8182. return (array)$value;
  8183. })->toArray();
  8184. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8185. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8186. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8187. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8188. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8189. // 组装分集剧本数据
  8190. $episodeScripts = [];
  8191. foreach ($episodes as $episode) {
  8192. $segments = DB::table('mp_episode_segments')
  8193. ->where('anime_id', $animeId)
  8194. ->where('episode_id', $episode['id'])
  8195. ->get();
  8196. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8197. $acts = [];
  8198. foreach ($segments as $segment) {
  8199. $segment = (array)$segment;
  8200. $actNumber = (int)getProp($segment, 'act_number', 0);
  8201. if ($actNumber <= 0) continue;
  8202. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8203. $acts[$actNumber] = [
  8204. 'id' => (int)$segment['id'],
  8205. 'act_number' => $actNumber,
  8206. 'duration' => getProp($segment, 'act_duration', ''),
  8207. 'content' => getProp($segment, 'act_content', ''),
  8208. ];
  8209. }
  8210. }
  8211. ksort($acts);
  8212. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8213. $segmentCounter = 0;
  8214. foreach ($acts as &$act) {
  8215. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8216. }
  8217. unset($act);
  8218. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8219. $narratorVoice = '';
  8220. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8221. foreach ($episodeRoles as $role) {
  8222. if (getProp($role, 'role') === '旁白') {
  8223. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8224. break;
  8225. }
  8226. }
  8227. if ($narratorVoice === '') {
  8228. foreach ($acts as $act) {
  8229. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8230. $narratorVoice = trim($match[1]);
  8231. break;
  8232. }
  8233. }
  8234. }
  8235. $episodeScripts[] = [
  8236. 'episode_number' => getProp($episode, 'episode_number'),
  8237. 'title' => getProp($episode, 'title', ''),
  8238. 'act_count' => count($acts),
  8239. 'narrator_voice' => $narratorVoice,
  8240. 'acts' => array_values($acts),
  8241. ];
  8242. }
  8243. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8244. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8245. // 构建PDF
  8246. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8247. // 图片已嵌入PDF,清理临时文件
  8248. foreach ($imageCache as $imgFile) {
  8249. @unlink($imgFile);
  8250. }
  8251. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8252. if ($savePath) {
  8253. $pdf->Output($savePath, 'F');
  8254. return $savePath;
  8255. }
  8256. // 直接下载输出
  8257. header('Content-Type: application/pdf');
  8258. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8259. $pdf->Output($filename . '.pdf', 'D');
  8260. exit();
  8261. }
  8262. /**
  8263. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8264. * @param array $episodes 分集数据
  8265. * @param string $nameKey role|scene|prop
  8266. * @return array
  8267. */
  8268. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8269. $fieldMap = [
  8270. 'role' => 'roles',
  8271. 'scene' => 'scenes',
  8272. 'prop' => 'props',
  8273. ];
  8274. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8275. $items = [];
  8276. foreach ($episodes as $episode) {
  8277. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8278. foreach ($list as $item) {
  8279. if (!is_array($item)) continue;
  8280. $name = trim((string)getProp($item, $nameKey, ''));
  8281. if ($name === '') continue;
  8282. // 旁白不进入主体列表(仅作为旁白音色来源)
  8283. if ($nameKey === 'role' && $name === '旁白') continue;
  8284. if (!isset($items[$name])) {
  8285. $items[$name] = $item;
  8286. }
  8287. }
  8288. }
  8289. return array_values($items);
  8290. }
  8291. /**
  8292. * 构建动漫剧本PDF
  8293. * @param array $anime 动漫信息
  8294. * @param array $roles 主体列表
  8295. * @param array $scenes 场景列表
  8296. * @param array $props 道具列表
  8297. * @param array $episodeScripts 分集剧本数据
  8298. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8299. * @return \TCPDF
  8300. */
  8301. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8302. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8303. $pdf->SetCreator('动漫剧本导出系统');
  8304. $pdf->SetAuthor('系统');
  8305. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8306. $pdf->SetSubject('动漫剧本导出');
  8307. $pdf->SetMargins(15, 15, 15);
  8308. $pdf->SetAutoPageBreak(true, 15);
  8309. // 剧本名
  8310. $pdf->AddPage();
  8311. $pdf->SetFont('simsun', 'B', 20);
  8312. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8313. $pdf->Ln(5);
  8314. // 故事梗概
  8315. $intro = trim((string)getProp($anime, 'intro', ''));
  8316. if ($intro !== '') {
  8317. $this->pdfSectionTitle($pdf, '故事梗概');
  8318. $this->pdfBody($pdf, $intro);
  8319. }
  8320. // 美术风格
  8321. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  8322. if ($artStyle !== '') {
  8323. $this->pdfSectionTitle($pdf, '美术风格');
  8324. $this->pdfBody($pdf, $artStyle);
  8325. }
  8326. // 主体列表(文字+图片)
  8327. $this->pdfSectionTitle($pdf, '主体列表');
  8328. foreach ($roles as $index => $role) {
  8329. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  8330. }
  8331. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  8332. // 场景列表(文字+图片)
  8333. $this->pdfSectionTitle($pdf, '场景列表');
  8334. foreach ($scenes as $index => $scene) {
  8335. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  8336. }
  8337. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  8338. // 道具列表(文字+图片)
  8339. $this->pdfSectionTitle($pdf, '道具列表');
  8340. foreach ($props as $index => $prop) {
  8341. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  8342. }
  8343. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  8344. // 分镜剧本
  8345. $this->pdfSectionTitle($pdf, '分镜剧本');
  8346. foreach ($episodeScripts as $episodeScript) {
  8347. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  8348. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  8349. if ($episodeTitleRaw !== '') {
  8350. // title 字段可能已带"第N集"前缀,避免重复
  8351. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  8352. $episodeTitle = $episodeTitleRaw;
  8353. } else {
  8354. $episodeTitle .= ':' . $episodeTitleRaw;
  8355. }
  8356. }
  8357. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  8358. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  8359. if (getProp($episodeScript, 'narrator_voice') !== '') {
  8360. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  8361. }
  8362. foreach (getProp($episodeScript, 'acts', []) as $act) {
  8363. $actTitle = '片段' . getProp($act, 'act_number');
  8364. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  8365. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  8366. }
  8367. $this->pdfSubTitle($pdf, $actTitle, 12);
  8368. if (getProp($act, 'content') !== '') {
  8369. $this->pdfBody($pdf, getProp($act, 'content'));
  8370. }
  8371. }
  8372. }
  8373. return $pdf;
  8374. }
  8375. /**
  8376. * PDF章节标题(带分隔线)
  8377. */
  8378. private function pdfSectionTitle($pdf, $title) {
  8379. if ($pdf->GetY() > 230) {
  8380. $pdf->AddPage();
  8381. }
  8382. $pdf->SetFont('simsun', 'B', 15);
  8383. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  8384. $y = $pdf->GetY();
  8385. $pdf->SetLineWidth(0.4);
  8386. $pdf->Line(15, $y, 195, $y);
  8387. $pdf->Ln(4);
  8388. }
  8389. /**
  8390. * PDF子标题(集数/片段标题)
  8391. */
  8392. private function pdfSubTitle($pdf, $title, $size = 13) {
  8393. if ($pdf->GetY() > 240) {
  8394. $pdf->AddPage();
  8395. }
  8396. $pdf->SetFont('simsun', 'B', $size);
  8397. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  8398. $pdf->Ln(1);
  8399. }
  8400. /**
  8401. * PDF正文段落
  8402. */
  8403. private function pdfBody($pdf, $text) {
  8404. $pdf->SetFont('simsun', '', 11);
  8405. $pdf->MultiCell(0, 6, $text, 0, 'L');
  8406. $pdf->Ln(2);
  8407. }
  8408. /**
  8409. * 输出列表项图片(每张图单独一页,图下标注名称)
  8410. * @param \TCPDF $pdf
  8411. * @param array $items 列表项
  8412. * @param string $nameKey role|scene|prop
  8413. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8414. */
  8415. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  8416. foreach ($items as $item) {
  8417. $url = trim((string)getProp($item, 'url', ''));
  8418. $name = trim((string)getProp($item, $nameKey, ''));
  8419. if ($url === '' || !isset($imageCache[$url])) continue;
  8420. $imgPath = $imageCache[$url];
  8421. $size = @getimagesize($imgPath);
  8422. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  8423. continue;
  8424. }
  8425. $pdf->AddPage();
  8426. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  8427. $maxW = 160;
  8428. $maxH = 170;
  8429. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  8430. $drawW = $size[0] * $ratio;
  8431. $drawH = $size[1] * $ratio;
  8432. $x = (210 - $drawW) / 2;
  8433. $y = max(15, (297 - $drawH) / 2 - 10);
  8434. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  8435. // 图下标注名称
  8436. $pdf->SetFont('simsun', 'B', 13);
  8437. $pdf->SetY(297 - 28);
  8438. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  8439. }
  8440. }
  8441. /**
  8442. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  8443. * @param array $items 包含url字段的列表项
  8444. * @return array url => 临时文件路径
  8445. */
  8446. private function downloadImagesConcurrently(array $items) {
  8447. // 收集唯一的图片URL
  8448. $urls = [];
  8449. foreach ($items as $item) {
  8450. $url = trim((string)getProp($item, 'url', ''));
  8451. if ($url !== '') $urls[$url] = true;
  8452. }
  8453. if (!$urls) return [];
  8454. $urls = array_keys($urls);
  8455. $tmpDir = sys_get_temp_dir();
  8456. $rawFiles = [];
  8457. foreach ($urls as $url) {
  8458. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  8459. $rawFiles[$url] = $rawFile;
  8460. }
  8461. $client = new Client(['timeout' => 180, 'verify' => false]);
  8462. // 低并发下载,sink写入文件避免大图占用内存
  8463. $generator = (function () use ($urls, $client, $rawFiles) {
  8464. foreach ($urls as $url) {
  8465. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  8466. }
  8467. })();
  8468. $errors = [];
  8469. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  8470. 'concurrency' => 4,
  8471. 'rejected' => function ($reason, $url) use (&$errors) {
  8472. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  8473. },
  8474. ]);
  8475. $each->promise()->wait();
  8476. // 失败的图片串行重试一次(独占带宽,提高成功率)
  8477. foreach ($urls as $url) {
  8478. if (!isset($errors[$url])) continue;
  8479. try {
  8480. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  8481. unset($errors[$url]);
  8482. } catch (\Throwable $e) {
  8483. // 重试仍失败
  8484. }
  8485. }
  8486. $cache = [];
  8487. foreach ($urls as $url) {
  8488. $rawFile = $rawFiles[$url];
  8489. if (isset($errors[$url])) {
  8490. dLog('anime')->error('导出PDF图片下载失败', [
  8491. 'url' => $url,
  8492. 'error' => $errors[$url],
  8493. ]);
  8494. @unlink($rawFile);
  8495. continue;
  8496. }
  8497. $converted = $this->convertImageFile($rawFile, $url);
  8498. if ($converted !== null) {
  8499. $cache[$url] = $converted;
  8500. } else {
  8501. @unlink($rawFile);
  8502. }
  8503. }
  8504. return $cache;
  8505. }
  8506. /**
  8507. * 将已下载的图片文件缩放并转为JPEG
  8508. * @param string $rawFile 原始图片临时文件
  8509. * @param string $url 图片地址(用于命名)
  8510. * @return string|null 转换后的文件路径,转换失败返回null
  8511. */
  8512. private function convertImageFile($rawFile, $url) {
  8513. $content = @file_get_contents($rawFile);
  8514. if ($content === false || $content === '') return null;
  8515. if (!function_exists('imagecreatefromstring')) return null;
  8516. $image = @imagecreatefromstring($content);
  8517. if ($image === false) return null;
  8518. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  8519. imagedestroy($image);
  8520. if ($jpeg !== null) {
  8521. @unlink($rawFile);
  8522. }
  8523. return $jpeg;
  8524. }
  8525. /**
  8526. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  8527. * @param resource $srcImage GD图片资源
  8528. * @param string $rawFile 原始图片临时文件
  8529. * @param string $url 图片地址(用于命名)
  8530. * @return string|null 压缩后的JPEG文件路径
  8531. */
  8532. private function compressImageForPdf($srcImage, $rawFile, $url) {
  8533. $maxBytes = 2 * 1024 * 1024; // 2MB
  8534. $sizes = [2048, 1600, 1280, 1024, 800];
  8535. $qualities = [85, 70, 55, 40];
  8536. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  8537. foreach ($sizes as $size) {
  8538. $resized = $this->copyAndResize($srcImage, $size);
  8539. $flat = $this->flattenToWhite($resized);
  8540. imagedestroy($resized);
  8541. foreach ($qualities as $quality) {
  8542. ob_start();
  8543. $saved = imagejpeg($flat, null, $quality);
  8544. $data = ob_get_clean();
  8545. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  8546. file_put_contents($jpeg, $data);
  8547. imagedestroy($flat);
  8548. dLog('anime')->info('导出PDF图片压缩完成', [
  8549. 'url' => $url,
  8550. 'size' => filesize($jpeg),
  8551. 'edge' => $size,
  8552. 'quality' => $quality,
  8553. ]);
  8554. return $jpeg;
  8555. }
  8556. }
  8557. imagedestroy($flat);
  8558. }
  8559. // 兜底:最小尺寸、最低质量强制输出
  8560. $resized = $this->copyAndResize($srcImage, 800);
  8561. $flat = $this->flattenToWhite($resized);
  8562. imagedestroy($resized);
  8563. $saved = imagejpeg($flat, $jpeg, 30);
  8564. imagedestroy($flat);
  8565. if (!$saved) return null;
  8566. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  8567. 'url' => $url,
  8568. 'size' => filesize($jpeg),
  8569. ]);
  8570. return $jpeg;
  8571. }
  8572. /**
  8573. * 等比缩放图片副本(不销毁原图)
  8574. * @param resource $srcImage GD图片资源
  8575. * @param int $maxEdge 最大边长
  8576. * @return resource
  8577. */
  8578. private function copyAndResize($srcImage, $maxEdge) {
  8579. $width = imagesx($srcImage);
  8580. $height = imagesy($srcImage);
  8581. $max = max($width, $height);
  8582. if ($max <= $maxEdge) {
  8583. $copy = imagecreatetruecolor($width, $height);
  8584. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  8585. return $copy;
  8586. }
  8587. $ratio = $maxEdge / $max;
  8588. $newWidth = max(1, (int)round($width * $ratio));
  8589. $newHeight = max(1, (int)round($height * $ratio));
  8590. $resized = imagecreatetruecolor($newWidth, $newHeight);
  8591. imagealphablending($resized, false);
  8592. imagesavealpha($resized, true);
  8593. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  8594. return $resized;
  8595. }
  8596. /**
  8597. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  8598. * @param resource $image GD图片资源
  8599. * @return resource
  8600. */
  8601. private function flattenToWhite($image) {
  8602. $width = imagesx($image);
  8603. $height = imagesy($image);
  8604. $flat = imagecreatetruecolor($width, $height);
  8605. $white = imagecolorallocate($flat, 255, 255, 255);
  8606. imagefill($flat, 0, 0, $white);
  8607. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  8608. return $flat;
  8609. }
  8610. /**
  8611. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  8612. * @param string $content 片段内容
  8613. * @param int $counter 当前已编号数量(引用传递,整集累计)
  8614. * @return string
  8615. */
  8616. private function renumberSegmentBlocks($content, &$counter) {
  8617. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  8618. $counter++;
  8619. return '【' . $match[1] . $counter . '】';
  8620. }, $content);
  8621. }
  8622. }