AnimeService.php 430 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044
  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 App\Services\TaskCenterService;
  13. use Dflydev\DotAccessData\Util;
  14. use GuzzleHttp\Client;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. use Illuminate\Support\Facades\Redis;
  18. use OSS\Core\OssException;
  19. use OSS\OssClient;
  20. class AnimeService
  21. {
  22. protected $aiImageGenerationService;
  23. protected $aiVideoGenerationService;
  24. protected $DeepSeekService;
  25. protected $pointsService;
  26. protected $taskCenterService;
  27. private $url;
  28. private $api_key;
  29. private $headers;
  30. public function __construct(
  31. AIImageGenerationService $aiImageGenerationService,
  32. AIVideoGenerationService $aiVideoGenerationService,
  33. DeepSeekService $DeepSeekService,
  34. PointsService $pointsService,
  35. TaskCenterService $taskCenterService
  36. ) {
  37. $this->aiImageGenerationService = $aiImageGenerationService;
  38. $this->aiVideoGenerationService = $aiVideoGenerationService;
  39. $this->DeepSeekService = $DeepSeekService;
  40. $this->pointsService = $pointsService;
  41. $this->taskCenterService = $taskCenterService;
  42. $this->url = 'https://api.deepseek.com/chat/completions';
  43. $this->api_key = env('DEEPSEEK_API_KEY');
  44. $this->headers = [
  45. 'Authorization' => 'Bearer '.$this->api_key,
  46. 'Content-Type' => 'application/json; charset=UTF-8'
  47. ];
  48. }
  49. /**
  50. * 构建统一的分镜数据结构(episodeInfo格式)
  51. * @param array $segments 分镜数据数组
  52. * @return array 返回包含acts和total_duration的数组
  53. */
  54. public function buildEpisodeSegmentsStructure($segments) {
  55. $acts = [];
  56. $totalDuration = 0; // 初始化总时长
  57. foreach($segments as $segment) {
  58. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  59. $videoDuration = getProp($segment, 'video_duration');
  60. $audioDuration = getProp($segment, 'audio_duration');
  61. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  62. $totalDuration += floatval($videoDuration);
  63. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  64. $totalDuration += floatval($audioDuration);
  65. } else {
  66. $totalDuration += 5; // 默认5秒
  67. }
  68. $segment_content = getProp($segment, 'segment_content');
  69. // 判断是否有尾帧描述,如果有则去掉这部分内容
  70. if (strpos($segment_content, '尾帧') !== false) {
  71. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  72. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  73. }
  74. // 构建分镜信息
  75. $segmentInfo = [
  76. 'segment_id' => getProp($segment, 'segment_id'),
  77. 'segment_number' => getProp($segment, 'segment_number'),
  78. 'segment_content' => $segment_content,
  79. 'description' => getProp($segment, 'description'),
  80. 'composition' => getProp($segment, 'composition'),
  81. 'camera_movement' => getProp($segment, 'camera_movement'),
  82. 'voice_actor' => getProp($segment, 'voice_actor'),
  83. 'dialogue' => getProp($segment, 'dialogue'),
  84. 'frame_type' => getProp($segment, 'frame_type'),
  85. 'scene' => getProp($segment, 'scene'),
  86. 'characters' => getProp($segment, 'characters'),
  87. 'tail_frame' => getProp($segment, 'tail_frame'),
  88. 'emotion' => getProp($segment, 'emotion'),
  89. 'emotion_type' => getProp($segment, 'emotion_type'),
  90. 'gender' => getProp($segment, 'gender'),
  91. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  92. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  93. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  94. 'pitch' => getProp($segment, 'pitch'),
  95. 'voice_name' => getProp($segment, 'voice_name'),
  96. 'voice_type' => getProp($segment, 'voice_type'),
  97. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  98. 'img_url' => getProp($segment, 'img_url'),
  99. 'audio_url' => getProp($segment, 'audio_url'),
  100. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  101. 'video_url' => getProp($segment, 'video_url'),
  102. 'video_duration' => getProp($segment, 'video_duration', 0),
  103. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  104. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  105. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  106. 'current_type' => getProp($segment, 'current_type'),
  107. ];
  108. $actNumber = getProp($segment, 'act_number');
  109. if (isset($acts[$actNumber])) {
  110. $acts[$actNumber]['segments'][] = $segmentInfo;
  111. } else {
  112. $acts[$actNumber] = [
  113. 'act_number' => $actNumber,
  114. 'act_title' => getProp($segment, 'act_title'),
  115. 'act_duration' => getProp($segment, 'act_duration'),
  116. 'segments' => [$segmentInfo]
  117. ];
  118. }
  119. }
  120. return [
  121. 'acts' => array_values($acts),
  122. 'total_duration' => intval(round($totalDuration))
  123. ];
  124. }
  125. /**
  126. * 构建统一的分段数据结构(episodeInfoForAce格式)
  127. * @param array $segments 分段数据数组
  128. * @return array 返回包含acts和total_duration的数组
  129. */
  130. public function buildEpisodeActsStructureForAce($segments) {
  131. $acts = [];
  132. $totalDuration = 0; // 初始化总时长
  133. foreach($segments as $segment) {
  134. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  135. $videoDuration = getProp($segment, 'video_duration');
  136. $actDuration = getProp($segment, 'act_duration');
  137. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  138. $totalDuration += floatval($videoDuration);
  139. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  140. $totalDuration += floatval($actDuration);
  141. } else {
  142. $totalDuration += 5; // 默认5秒
  143. }
  144. // 构建分镜信息
  145. $segmentInfo = [
  146. 'act_id' => getProp($segment, 'id'),
  147. 'act_number' => getProp($segment, 'act_number'),
  148. 'act_title' => getProp($segment, 'act_title'),
  149. 'act_duration' => getProp($segment, 'act_duration'),
  150. 'act_content' => getProp($segment, 'act_content'),
  151. 'video_url' => getProp($segment, 'video_url'),
  152. 'video_duration' => getProp($segment, 'video_duration', 0),
  153. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  154. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  155. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  156. 'current_type' => getProp($segment, 'current_type'),
  157. ];
  158. $acts[] = $segmentInfo;
  159. }
  160. return [
  161. 'acts' => array_values($acts),
  162. 'total_duration' => intval(round($totalDuration))
  163. ];
  164. }
  165. /**
  166. * 验证画面比例是否有效
  167. * @param string $ratio 画面比例
  168. * @return bool
  169. */
  170. public function validateRatio($ratio) {
  171. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  172. }
  173. /**
  174. * 获取画面比例对应的宽高
  175. * @param string $ratio 画面比例
  176. * @return array ['width' => int, 'height' => int]
  177. * @throws \Exception
  178. */
  179. private function getRatioDimensions($ratio) {
  180. if ($ratio && !$this->validateRatio($ratio)) {
  181. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  182. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  183. }
  184. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  185. }
  186. public function createAnime($data) {
  187. $uid = Site::getUid();
  188. $cpid = Site::getCpid();
  189. $input_art_style = getProp($data, 'art_style');
  190. $file = getProp($data, 'file');
  191. $content = getProp($data, 'content', '');
  192. $bid = getProp($data, 'bid', 0);
  193. $script_id = getProp($data, 'script_id', 0);
  194. $ace_mode = getProp($data, 'ace_mode', 0);
  195. $extra_products = getProp($data, 'products', []);
  196. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  197. if (!is_array($extra_products)) {
  198. Utils::throwError('20003:传入的资产格式不正确');
  199. }
  200. // 替换美术风格
  201. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  202. // 提取文件内容
  203. if ($file) {
  204. $content = $this->DeepSeekService->extractFileContent($file);
  205. if (!$content) {
  206. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  207. }
  208. } elseif ($script_id) {
  209. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  210. if (!$content) {
  211. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  212. }
  213. } elseif ($bid) {
  214. $content = $this->DeepSeekService->getContentByBid($bid);
  215. if (!$content) {
  216. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  217. }
  218. } elseif ($content) {
  219. $content = filterContent($content);
  220. }else {
  221. $content = '';
  222. }
  223. $anime_data = [
  224. 'user_id' => $uid,
  225. 'cpid' => $cpid,
  226. 'anime_name' => '新剧本策划',
  227. 'is_multi' => getProp($data, 'is_multi', 1),
  228. 'content' => $content,
  229. 'art_style_type' => $input_art_style,
  230. 'ace_mode' => $ace_mode,
  231. 'script_id' => $script_id,
  232. 'extra_products' => json_encode($extra_products, 256),
  233. 'created_at' => date('Y-m-d H:i:s'),
  234. 'updated_at' => date('Y-m-d H:i:s'),
  235. ];
  236. // 处理文本模型
  237. $model = getProp($data, 'model');
  238. if (!$model) {
  239. // 用户没有输入,使用默认值
  240. $model = 'deepseek-v4-pro';
  241. }
  242. // 验证模型是否在可用模型表中
  243. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  244. $model = 'deepseek-v4-pro';
  245. }
  246. $anime_data['model'] = $model;
  247. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  248. return DB::table('mp_animes')->insertGetId($anime_data);
  249. }
  250. public function chatList($data) {
  251. $uid = Site::getUid();
  252. $anime_name = getProp($data, 'anime_name');
  253. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  254. if ($anime_name) {
  255. $query->where('anime_name', 'like', "%$anime_name%");
  256. }
  257. return $query->orderBy('id', 'desc')->paginate();
  258. }
  259. public function chatHistory($data) {
  260. $anime_id = getProp($data, 'anime_id');
  261. $sequence = getProp($data, 'sequence', 0);
  262. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  263. $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)
  264. ->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');
  265. return $query->orderBy('ar.id')->get()->map(function ($value) {
  266. $value = (array)$value;
  267. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  268. $value['created_at'] = transDate($value['created_at']);
  269. $value['episode_created_at'] = transDate($value['episode_created_at']);
  270. return $value;
  271. })->toArray();
  272. }
  273. public function batchSetRoleImg($data) {
  274. $episode_id = getProp($data, 'episode_id');
  275. if (!$episode_id) Utils::throwError('1002:请选择分集');
  276. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  277. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  278. $art_style = getProp($episode, 'art_style');
  279. $anime_id = getProp($episode, 'anime_id');
  280. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  281. $art_style_type = getProp($anime, 'art_style_type');
  282. $character_prefix = '';
  283. $scene_prefix = '';
  284. if ($art_style_type) {
  285. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  286. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  287. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  288. }
  289. foreach ($roles as &$role) {
  290. $role_name = getProp($role, 'role');
  291. if ($role_name == '旁白') continue;
  292. // 优先使用 pic_prompt,如果没有则使用 description
  293. $pic_prompt = getProp($role, 'pic_prompt');
  294. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  295. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  296. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  297. // 参考图地址
  298. $ref_img_url = getProp($role, 'url');
  299. if ($ref_img_url) continue; // 已有图片则跳过
  300. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  301. try {
  302. $params = [
  303. 'prompt' => $description,
  304. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  305. ];
  306. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  307. $task_id = $task->id;
  308. if (!$task_id) {
  309. Utils::throwError("20003:角色({$role_name})生成图片失败");
  310. }
  311. $role['task_id'] = $task_id;
  312. $role['task_status'] = 'processing';
  313. } catch (\Exception $e) {
  314. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  315. Utils::throwError("20003:" . $e->getMessage());
  316. }
  317. }
  318. // 保存角色信息
  319. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  320. 'roles' => json_encode($roles, 256),
  321. 'generate_status' => '执行中',
  322. 'generate_at' => date('Y-m-d H:i:s'),
  323. 'updated_at' => date('Y-m-d H:i:s')
  324. ]);
  325. if (!$boolen) {
  326. Utils::throwError('20003:保存角色信息失败');
  327. }
  328. return $boolen;
  329. }
  330. public function batchSetSceneImg($data) {
  331. $episode_id = getProp($data, 'episode_id');
  332. if (!$episode_id) Utils::throwError('1002:请选择分集');
  333. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  334. $scenes = json_decode(getProp($episode, 'scenes'), true);
  335. $art_style = getProp($episode, 'art_style');
  336. $target_scene = getProp($data, 'target_scene');
  337. $anime_id = getProp($episode, 'anime_id');
  338. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  339. $art_style_type = getProp($anime, 'art_style_type');
  340. $character_prefix = '';
  341. $scene_prefix = '';
  342. if ($art_style_type) {
  343. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  344. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  345. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  346. }
  347. foreach ($scenes as &$scene) {
  348. $scene_name = getProp($scene, 'scene');
  349. if ($scene_name != $target_scene) continue;
  350. // 优先使用 pic_prompt,如果没有则使用 description
  351. $pic_prompt = getProp($scene, 'pic_prompt');
  352. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  353. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  354. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  355. // 参考图地址
  356. $ref_img_url = getProp($scene, 'url');
  357. if ($ref_img_url) continue; // 已有图片则跳过
  358. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  359. try {
  360. $params = [
  361. 'prompt' => $description,
  362. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  363. ];
  364. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  365. $task_id = $task->id;
  366. if (!$task_id) {
  367. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  368. }
  369. $scene['task_id'] = $task_id;
  370. $scene['task_status'] = 'processing';
  371. } catch (\Exception $e) {
  372. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  373. Utils::throwError("20003:" . $e->getMessage());
  374. }
  375. }
  376. // 保存场景信息
  377. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  378. 'scenes' => json_encode($scenes, 256),
  379. 'generate_status' => '执行中',
  380. 'generate_at' => date('Y-m-d H:i:s'),
  381. 'updated_at' => date('Y-m-d H:i:s')
  382. ]);
  383. if (!$boolen) {
  384. Utils::throwError('20003:保存角色信息失败');
  385. }
  386. return $boolen;
  387. }
  388. public function editAnime($data) {
  389. $anime_id = getProp($data, 'anime_id');
  390. $anime_name = trim(getProp($data, 'anime_name'));
  391. // 确认对话名称唯一性
  392. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  393. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  394. }
  395. if (!$anime_id || !$anime_name) {
  396. Utils::throwError('20003:参数异常');
  397. }
  398. return DB::table('mp_animes')->where('id', $anime_id)->update([
  399. 'anime_name' => $anime_name,
  400. 'updated_at' => date('Y-m-d H:i:s')
  401. ]);
  402. // $script_arr =getProp($data, 'script', []);
  403. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  404. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  405. // $anime_id = getProp($data, 'anime_id');
  406. // try {
  407. // DB::beginTransaction();
  408. // $table_data = [
  409. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  410. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  411. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  412. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  413. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  414. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  415. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  416. // 'status' => 3,
  417. // 'start_episode_sequence' => $start_episode_sequence,
  418. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  419. // 'episode_num' => count($script_arr['episodes']),
  420. // 'updated_at' => date('Y-m-d H:i:s')
  421. // ];
  422. // // 保存剧本内容
  423. // if (!empty($anime_id)) {
  424. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  425. // if (!$boolen) {
  426. // dLog('anime')->info('对话保存失败', $table_data);
  427. // Utils::throwError('20003:对话保存失败');
  428. // }
  429. // }else {
  430. // $table['created_at'] = $table_data['updated_at'];
  431. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  432. // if (!$anime_id) {
  433. // dLog('anime')->info('对话保存失败', $table_data);
  434. // Utils::throwError('20003:对话保存失败');
  435. // }
  436. // }
  437. // // 保存分集内容
  438. // // 删除历史分集内容
  439. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  440. // $episodes = [];
  441. // $sequence = 1;
  442. // foreach ($script_arr['episodes'] as $episode) {
  443. // $segment_number = 1;
  444. // foreach($episode['segments'] as $segment) {
  445. // $episodes[] = [
  446. // 'anime_id' => $anime_id,
  447. // 'episode_number' => $episode['episode_number'],
  448. // 'title' => $episode['title'],
  449. // // 'content' => $episode['content'],
  450. // 'content' => '',
  451. // 'segment_number' => $segment_number,
  452. // 'segment_content' => $segment['segment_content'],
  453. // 'sequence' => $sequence,
  454. // 'created_at' => date('Y-m-d H:i:s'),
  455. // 'updated_at' => date('Y-m-d H:i:s')
  456. // ];
  457. // $sequence++;
  458. // $segment_number++;
  459. // }
  460. // }
  461. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  462. // if (!$boolen2) {
  463. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  464. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  465. // Utils::throwError('20003:分集内容保存失败');
  466. // }
  467. // } catch (\Exception $e) {
  468. // DB::rollBack();
  469. // Utils::throwError('20003:'.$e->getMessage());
  470. // }
  471. // DB::commit();
  472. // return true;
  473. }
  474. public function delAnime($data) {
  475. $anime_id = getProp($data, 'anime_id');
  476. if (!$anime_id) {
  477. Utils::throwError('20003:请选择剧本');
  478. }
  479. return DB::table('mp_animes')->where('id', $anime_id)->update([
  480. 'is_deleted' => 1,
  481. 'updated_at' => date('Y-m-d H:i:s')
  482. ]);
  483. }
  484. public function animeDetail($data) {
  485. $uid = Site::getUid();
  486. $anime_id = getProp($data, 'anime_id');
  487. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  488. ->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();
  489. if (!$anime) Utils::throwError('20003:权限不足');
  490. $anime = (array)$anime;
  491. $anime['roles'] = json_decode($anime['roles']);
  492. $anime['scenes'] = json_decode($anime['scenes']);
  493. // 获取分集信息
  494. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  495. ->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"))
  496. ->orderBy('episode_number')->get()->map(function ($value) {
  497. return (array)$value;
  498. })->toArray();
  499. $anime['episodes'] = $episodes;
  500. return $anime;
  501. }
  502. public function episodeInfo($data) {
  503. $uid = Site::getUid();
  504. $anime_id = getProp($data, 'anime_id');
  505. $episode_id = getProp($data, 'episode_id');
  506. if (!$anime_id || !$episode_id) {
  507. Utils::throwError('1002:请选择剧集');
  508. }
  509. // 验证用户权限
  510. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  511. if (!$anime) Utils::throwError('20003:权限不足');
  512. $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();
  513. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  514. $episode = (array)$episode;
  515. $episode['roles'] = json_decode($episode['roles'], true);
  516. // foreach($episode['roles'] as &$item) {
  517. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  518. // }
  519. $episode['scenes'] = json_decode($episode['scenes'], true);
  520. // foreach($episode['scenes'] as &$item) {
  521. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  522. // }
  523. // 获取分镜信息
  524. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  525. ->select('*')->get()->map(function ($value) {
  526. return (array)$value;
  527. })->toArray();
  528. // 使用公共方法构建分镜结构
  529. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  530. $episode['acts'] = $segmentsStructure['acts'];
  531. $episode['total_duration'] = $segmentsStructure['total_duration'];
  532. return $episode;
  533. }
  534. public function episodeInfoForAce($data) {
  535. $anime_id = getProp($data, 'anime_id');
  536. $episode_id = getProp($data, 'episode_id');
  537. if (!$anime_id || !$episode_id) {
  538. Utils::throwError('1002:请选择剧集');
  539. }
  540. $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();
  541. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  542. $episode = (array)$episode;
  543. $episode['roles'] = json_decode($episode['roles'], true);
  544. // foreach($episode['roles'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  546. // }
  547. $episode['scenes'] = json_decode($episode['scenes'], true);
  548. // foreach($episode['scenes'] as &$item) {
  549. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  550. // }
  551. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  552. // 获取分镜信息
  553. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  554. ->select('*')->get()->map(function ($value) {
  555. return (array)$value;
  556. })->toArray();
  557. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  558. $episode['acts'] = $segmentsStructure['acts'];
  559. $episode['total_duration'] = $segmentsStructure['total_duration'];
  560. // 获取mp_animes表中的视频参数
  561. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  562. $episode['video_params'] = [
  563. 'video_model' => getProp($anime, 'video_model'),
  564. 'video_resolution' => getProp($anime, 'video_resolution'),
  565. 'ratio' => getProp($anime, 'video_ratio'),
  566. ];
  567. return $episode;
  568. }
  569. public function segmentInfo($data) {
  570. $uid = Site::getUid();
  571. $segment_id = getProp($data, 'segment_id');
  572. if (!$segment_id) {
  573. Utils::throwError('1002:请选择分镜');
  574. }
  575. // 获取分镜信息
  576. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  577. // 验证用户权限
  578. if ($segment) {
  579. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  580. if (!$anime) Utils::throwError('20003:权限不足');
  581. }
  582. $result = [
  583. 'segment_id' => getProp($segment, 'segment_id'),
  584. 'segment_number' => getProp($segment, 'segment_number'),
  585. 'segment_content' => getProp($segment, 'segment_content'),
  586. 'description' => getProp($segment, 'description'),
  587. 'composition' => getProp($segment, 'composition'),
  588. 'camera_movement' => getProp($segment, 'camera_movement'),
  589. 'voice_actor' => getProp($segment, 'voice_actor'),
  590. 'dialogue' => getProp($segment, 'dialogue'),
  591. 'frame_type' => getProp($segment, 'frame_type'),
  592. 'scene' => getProp($segment, 'scene'),
  593. 'characters' => getProp($segment, 'characters'),
  594. 'tail_frame' => getProp($segment, 'tail_frame'),
  595. 'emotion' => getProp($segment, 'emotion'),
  596. 'emotion_type' => getProp($segment, 'emotion_type'),
  597. 'gender' => getProp($segment, 'gender'),
  598. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  599. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  600. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  601. 'pitch' => getProp($segment, 'pitch'),
  602. 'voice_name' => getProp($segment, 'voice_name'),
  603. 'voice_type' => getProp($segment, 'voice_type'),
  604. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  605. 'img_url' => getProp($segment, 'img_url'),
  606. 'video_url' => getProp($segment, 'video_url'),
  607. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  608. ];
  609. return $result;
  610. }
  611. public function copyEpisodeVersion($data) {
  612. $episode_id = getProp($data, 'episode_id');
  613. $uid = Site::getUid();
  614. $cpid = Site::getCpid();
  615. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  616. if (!$episode) Utils::throwError('20003:该剧集不存在');
  617. $episode = (array)$episode;
  618. $anime_id = $episode['anime_id'];
  619. $episode_number = $episode['episode_number'];
  620. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  621. $sequence = $count + 1;
  622. unset($episode['id']);
  623. $now = date('Y-m-d H:i:s');
  624. $episode['created_at'] = $now;
  625. $episode['updated_at'] = $now;
  626. $episode['is_default'] = 1;
  627. // 获取版本中含有"(副本"字样的个数
  628. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  629. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  630. $episode['sequence'] = $sequence;
  631. $episode['is_generated'] = 0;
  632. $episode['cpid'] = $cpid;
  633. // 获取ace_mode
  634. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  635. try {
  636. DB::beginTransaction();
  637. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  638. // 新增副本
  639. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  640. if (!$new_episode_id) {
  641. Utils::throwError('20003:创建副本失败!');
  642. }
  643. // 获取分镜数据并准备插入
  644. $segments_for_insert = DB::table('mp_episode_segments')
  645. ->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')
  646. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  647. $item = (array)$item;
  648. $item['episode_id'] = $new_episode_id;
  649. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  650. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  651. return $item;
  652. })->toArray();
  653. // 写入分镜数据
  654. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  655. if (!$boolen2) {
  656. Utils::throwError('20003:写入分镜数据失败!');
  657. }
  658. // 写入对话历史
  659. $records = [
  660. [
  661. 'uid' => $uid,
  662. 'anime_id' => $anime_id,
  663. 'role' => 'user',
  664. 'content' => '创建副本',
  665. 'sequence' => $episode_number,
  666. 'episode_id' => $new_episode_id,
  667. 'created_at' => $now,
  668. 'updated_at' => $now
  669. ],
  670. [
  671. 'uid' => $uid,
  672. 'anime_id' => $anime_id,
  673. 'role' => 'assistant',
  674. 'content' => '好的,已为您创建副本',
  675. 'sequence' => $episode_number,
  676. 'episode_id' => $new_episode_id,
  677. 'created_at' => $now,
  678. 'updated_at' => $now
  679. ]
  680. ];
  681. $boolen3 = DB::table('mp_anime_records')->insert($records);
  682. if (!$boolen3) {
  683. Utils::throwError('20003:对话记录保存失败');
  684. }
  685. }catch (\Exception $e) {
  686. DB::rollBack();
  687. Utils::throwError('20003:'.$e->getMessage());
  688. }
  689. DB::commit();
  690. // 构建与 episodeInfo 方法一致的返回数据结构
  691. $result = [
  692. 'episode_id' => $new_episode_id,
  693. 'anime_id' => $anime_id,
  694. 'episode_number' => $episode_number,
  695. 'title' => $episode['title'],
  696. 'intro' => $episode['intro'],
  697. 'art_style' => $episode['art_style'],
  698. 'roles' => json_decode($episode['roles'], true),
  699. 'scenes' => json_decode($episode['scenes'], true),
  700. 'is_generated' => (int)$episode['is_generated']
  701. ];
  702. if ((int)$ace_mode === 1) {
  703. // 获取分镜信息
  704. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  705. ->select('*')->get()->map(function ($value) {
  706. return (array)$value;
  707. })->toArray();
  708. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  709. }else {
  710. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  711. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  712. }
  713. $result['acts'] = $segmentsStructure['acts'];
  714. $result['total_duration'] = $segmentsStructure['total_duration'];
  715. return $result;
  716. }
  717. public function episodeVersions($data) {
  718. $anime_id = getProp($data, 'anime_id');
  719. $episode_id = getProp($data, 'episode_id');
  720. if (!$anime_id || !$episode_id) {
  721. Utils::throwError('1002:请选择剧集');
  722. }
  723. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  724. $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) {
  725. return (array)$value;
  726. })->toArray();
  727. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  728. foreach($episodes as &$episode) {
  729. $episode['version'] = 'V'.$episode['sequence'];
  730. $episode['roles'] = json_decode($episode['roles'], true);
  731. $episode['scenes'] = json_decode($episode['scenes'], true);
  732. // 获取分镜信息
  733. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  734. ->select('*')->get()->map(function ($value) {
  735. return (array)$value;
  736. })->toArray();
  737. // 使用公共方法构建分镜结构
  738. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  739. $episode['acts'] = $segmentsStructure['acts'];
  740. $episode['total_duration'] = $segmentsStructure['total_duration'];
  741. }
  742. return $episodes;
  743. }
  744. public function bindEpisodeVersion($data) {
  745. $episode_id = getProp($data, 'episode_id');
  746. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  747. if (!$episode) Utils::throwError('20003:该剧集不存在');
  748. $episode = (array)$episode;
  749. if ((int)$episode['is_default'] === 1) return true;
  750. try {
  751. DB::beginTransaction();
  752. // 移除is_default标志
  753. $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')]);
  754. if (!$boolen) {
  755. Utils::throwError('20003:更新失败!');
  756. }
  757. // 绑定副本
  758. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  759. if (!$boolen2) {
  760. Utils::throwError('20003:绑定失败!');
  761. }
  762. }catch (\Exception $e) {
  763. DB::rollBack();
  764. Utils::throwError('20003:'.$e->getMessage());
  765. }
  766. DB::commit();
  767. return true;
  768. }
  769. public function chatChangeImg($data) {
  770. $segment_id = getProp($data, 'segment_id');
  771. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  772. $prompt = getProp($data, 'prompt');
  773. if (!$prompt || !$segment_id) {
  774. Utils::throwError('1002:请输入提示词,并且选择分镜');
  775. }
  776. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  777. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  778. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  779. else $ref_img_url = '';
  780. // $ref_img_url = '';
  781. if (empty($prompt)) {
  782. if (empty($ref_img_url)) {
  783. $prompt = getProp($segment, 'segment_content');
  784. }else {
  785. $prompt = '请根据图片生成';
  786. }
  787. }
  788. $anime_id = getProp($segment, 'anime_id');
  789. $episode_id = getProp($segment, 'episode_id');
  790. $episode_number = getProp($segment, 'episode_number');
  791. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  792. $ratio = getProp($data, 'ratio');
  793. if (!$ratio) {
  794. $ratio = getProp($episode, 'ratio');
  795. if (!$ratio) $ratio = '9:16';
  796. }
  797. $art_style = getProp($episode, 'art_style');
  798. if ($art_style) {
  799. $prompt = "美术风格:{$art_style}\n{$prompt}";
  800. }
  801. $dimensions = $this->getRatioDimensions($ratio);
  802. $width = $dimensions['width'];
  803. $height = $dimensions['height'];
  804. try {
  805. $params = [
  806. 'alias_segment_id' => $segment_id,
  807. 'prompt' => $prompt,
  808. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  809. 'width' => $width,
  810. 'height' => $height
  811. ];
  812. // 优化提示词(不要生成字幕)
  813. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  814. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  815. $task_id = $task->id;
  816. if (!$task_id) {
  817. Utils::throwError("20003:生成图片失败");
  818. }
  819. // 更新任务ID
  820. $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')]);
  821. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  822. } catch (\Exception $e) {
  823. Utils::throwError("20003:" . $e->getMessage());
  824. }
  825. // 创建任务之后先暂停10s等待异步任务完成
  826. sleep(10);
  827. $img_url = $this->loopGetPicTaskResult($task_id);
  828. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  829. // 图片生成后新增对话记录
  830. try {
  831. $uid = Site::getUid();
  832. $now = date('Y-m-d H:i:s');
  833. // 使用AI反推图片提示词
  834. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  835. // 保存对话记录
  836. $records = [
  837. [
  838. 'uid' => $uid,
  839. 'anime_id' => $anime_id,
  840. 'sequence' => $episode_number,
  841. 'role' => 'user',
  842. 'content' => $prompt,
  843. 'segment_id' => $segment_id,
  844. 'pic_task_id' => $task_id,
  845. 'image_url' => '',
  846. 'created_at' => $now,
  847. 'updated_at' => $now
  848. ],
  849. [
  850. 'uid' => $uid,
  851. 'anime_id' => $anime_id,
  852. 'sequence' => $episode_number,
  853. 'role' => 'assistant',
  854. 'content' => $pic_prompt,
  855. 'segment_id' => $segment_id,
  856. 'pic_task_id' => $task_id,
  857. 'image_url' => $img_url,
  858. 'created_at' => $now,
  859. 'updated_at' => $now
  860. ]
  861. ];
  862. DB::table('mp_anime_records')->insert($records);
  863. } catch (\Exception $e) {
  864. // 记录日志但不影响主流程
  865. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  866. 'segment_id' => $segment_id,
  867. 'img_url' => $img_url
  868. ]);
  869. logDB('anime', 'error', '保存对话记录失败', [
  870. 'segment_id' => $segment_id,
  871. 'img_url' => $img_url,
  872. 'error' => $e->getMessage()
  873. ]);
  874. }
  875. return $img_url;
  876. }
  877. public function segmentChatHistory($data) {
  878. $segment_id = getProp($data, 'segment_id');
  879. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  880. $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');
  881. $chat = $query->orderBy('id')->get()->map(function ($value) {
  882. $value = (array)$value;
  883. $value['created_at'] = transDate($value['created_at']);
  884. return $value;
  885. })->toArray();
  886. // 获取历史图片
  887. $url = [];
  888. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  889. foreach($pic_history as $task) {
  890. $result_url = getProp($task, 'result_url');
  891. if (is_json($result_url)) {
  892. $url = array_merge($url, json_decode($result_url, true));
  893. }else {
  894. $url[] = $result_url;
  895. }
  896. }
  897. // 获取历史视频
  898. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  899. foreach($video_history as $task) {
  900. $result_url = getProp($task, 'compressed_url');
  901. if (is_json($result_url)) {
  902. $url = array_merge($url, json_decode($result_url, true));
  903. }else {
  904. $url[] = $result_url;
  905. }
  906. }
  907. return compact('chat', 'url');
  908. }
  909. public function changeEpisodeRoles($data) {
  910. $anime_id = getProp($data, 'anime_id');
  911. $episode_id = getProp($data, 'episode_id');
  912. $target_roles = getProp($data, 'roles');
  913. $is_deleted = getProp($data, 'is_deleted', 0);
  914. // 参数验证
  915. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  916. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  917. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  918. // 验证剧集是否存在
  919. $episode = DB::table('mp_anime_episodes')
  920. ->where('anime_id', $anime_id)
  921. ->where('id', $episode_id)
  922. ->first();
  923. if (!$episode) Utils::throwError('20003:该剧集不存在');
  924. $roles = json_decode(getProp($episode, 'roles'), true);
  925. // 获取anime信息,检查是否有关联的script_id
  926. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  927. if (!$anime) Utils::throwError('20003:动漫不存在');
  928. $script_id = getProp($anime, 'script_id');
  929. $episode_number = getProp($episode, 'episode_number', 1);
  930. $uid = Site::getUid();
  931. $cpid = Site::getCpid();
  932. try {
  933. $target_role_name = getProp($target_roles, 'role');
  934. if (empty($target_role_name)) {
  935. Utils::throwError('20003:角色名称不能为空');
  936. }
  937. // 如果是删除操作
  938. if ($is_deleted == 1) {
  939. // 从角色列表中移除该角色
  940. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  941. return getProp($role, 'role') !== $target_role_name;
  942. }));
  943. // 更新角色列表
  944. $result = DB::table('mp_anime_episodes')
  945. ->where('anime_id', $anime_id)
  946. ->where('id', $episode_id)
  947. ->update([
  948. 'roles' => json_encode($roles, 256),
  949. 'updated_at' => date('Y-m-d H:i:s')
  950. ]);
  951. if ($result === false) {
  952. Utils::throwError('20003:删除角色失败');
  953. }
  954. } else {
  955. // 新增或更新操作
  956. $role_found = false;
  957. $is_new_role = false;
  958. // 查找并更新已存在的角色
  959. foreach($roles as &$role) {
  960. if (getProp($role, 'role') === $target_role_name) {
  961. $role = $target_roles;
  962. $role_found = true;
  963. break;
  964. }
  965. }
  966. // 如果角色不存在,则新增
  967. if (!$role_found) {
  968. $roles[] = $target_roles;
  969. $is_new_role = true;
  970. }
  971. // 更新角色列表
  972. $result = DB::table('mp_anime_episodes')
  973. ->where('anime_id', $anime_id)
  974. ->where('id', $episode_id)
  975. ->update([
  976. 'roles' => json_encode($roles, 256),
  977. 'updated_at' => date('Y-m-d H:i:s')
  978. ]);
  979. if ($result === false) {
  980. Utils::throwError('20003:更新角色列表失败');
  981. }
  982. // 同步更新分镜表中对应主体的音色信息
  983. $voice_name = getProp($target_roles, 'voice_name');
  984. $voice_type = getProp($target_roles, 'voice_type');
  985. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  986. DB::table('mp_episode_segments')
  987. ->where('anime_id', $anime_id)
  988. ->where('episode_id', $episode_id)
  989. ->where('voice_actor', $target_role_name)
  990. ->update([
  991. 'voice_name' => $voice_name,
  992. 'voice_type' => $voice_type,
  993. 'voice_audio_url' => $voice_audio_url,
  994. 'updated_at' => date('Y-m-d H:i:s')
  995. ]);
  996. // 如果有关联的script_id,则同步到mp_products表
  997. if ($script_id) {
  998. // 查询剧本信息
  999. $script = DB::table('mp_scripts')
  1000. ->where('id', $script_id)
  1001. ->where('is_deleted', 0)
  1002. ->first();
  1003. if ($script) {
  1004. $script_name = $script->script_name ?? 'script_' . $script_id;
  1005. $product_name = getProp($target_roles, 'role');
  1006. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1007. $url = getProp($target_roles, 'url', '');
  1008. $product_type = 1; // 1=角色
  1009. // 查找或创建以script_name命名的文件夹
  1010. $folder = DB::table('mp_products')
  1011. ->where('cpid', $cpid)
  1012. ->where('type', 2) // 文件夹类型
  1013. ->where('product', $product_type) // 角色类型
  1014. ->where('product_name', $script_name)
  1015. ->where('parent_id', 0)
  1016. ->where('is_deleted', 0)
  1017. ->first();
  1018. if (!$folder) {
  1019. // 创建文件夹
  1020. $folder_id = DB::table('mp_products')->insertGetId([
  1021. 'user_id' => $uid,
  1022. 'cpid' => $cpid,
  1023. 'type' => 2, // 文件夹
  1024. 'product' => $product_type, // 角色类型
  1025. 'parent_id' => 0,
  1026. 'level' => 1,
  1027. 'product_name' => $script_name,
  1028. 'sort_order' => time(),
  1029. 'is_deleted' => 0,
  1030. 'created_at' => date('Y-m-d H:i:s'),
  1031. 'updated_at' => date('Y-m-d H:i:s')
  1032. ]);
  1033. } else {
  1034. $folder_id = $folder->id;
  1035. }
  1036. // 查找该文件夹下是否已存在同名资产
  1037. $existing_product = DB::table('mp_products')
  1038. ->where('cpid', $cpid)
  1039. ->where('type', 1) // 资产类型
  1040. ->where('product', $product_type)
  1041. ->where('parent_id', $folder_id)
  1042. ->where('product_name', $product_name)
  1043. ->where('is_deleted', 0)
  1044. ->first();
  1045. if ($existing_product) {
  1046. // 更新已存在的资产
  1047. $updateData = [
  1048. 'pic_task_status' => '生成成功',
  1049. ];
  1050. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1051. if ($url) $updateData['url'] = $url;
  1052. // 处理versions字段
  1053. $versions = getProp($target_roles, 'versions', []);
  1054. if ($versions && is_array($versions)) {
  1055. $updateData['versions'] = json_encode($versions, 256);
  1056. }
  1057. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1058. DB::table('mp_products')
  1059. ->where('id', $existing_product->id)
  1060. ->update($updateData);
  1061. $product_id = $existing_product->id;
  1062. } else {
  1063. // 创建新资产
  1064. $versions = getProp($target_roles, 'versions', []);
  1065. $product_id = DB::table('mp_products')->insertGetId([
  1066. 'user_id' => $uid,
  1067. 'cpid' => $cpid,
  1068. 'type' => 1, // 资产
  1069. 'product' => $product_type, // 角色
  1070. 'parent_id' => $folder_id,
  1071. 'level' => 2,
  1072. 'product_name' => $product_name,
  1073. 'url' => $url,
  1074. 'pic_prompt' => $pic_prompt,
  1075. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1076. 'sort_order' => time(),
  1077. 'is_deleted' => 0,
  1078. 'pic_task_status' => '生成成功',
  1079. 'created_at' => date('Y-m-d H:i:s'),
  1080. 'updated_at' => date('Y-m-d H:i:s')
  1081. ]);
  1082. }
  1083. // 建立或更新绑定关系
  1084. $existing_mapping = DB::table('mp_script_product_mappings')
  1085. ->where('script_id', $script_id)
  1086. ->where('product_id', $product_id)
  1087. ->where('episode_number', $episode_number)
  1088. ->first();
  1089. if (!$existing_mapping) {
  1090. // 创建绑定关系
  1091. DB::table('mp_script_product_mappings')->insert([
  1092. 'script_id' => $script_id,
  1093. 'product_id' => $product_id,
  1094. 'episode_number' => $episode_number,
  1095. 'created_at' => date('Y-m-d H:i:s'),
  1096. 'updated_at' => date('Y-m-d H:i:s')
  1097. ]);
  1098. }
  1099. }
  1100. }
  1101. }
  1102. } catch (\Exception $e) {
  1103. dLog('anime')->error('更新剧集角色失败', [
  1104. 'anime_id' => $anime_id,
  1105. 'episode_id' => $episode_id,
  1106. 'error' => $e->getMessage()
  1107. ]);
  1108. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1109. }
  1110. return true;
  1111. }
  1112. public function changeEpisodeScenes($data) {
  1113. $anime_id = getProp($data, 'anime_id');
  1114. $episode_id = getProp($data, 'episode_id');
  1115. $target_scenes = getProp($data, 'scenes');
  1116. $is_deleted = getProp($data, 'is_deleted', 0);
  1117. // 参数验证
  1118. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1119. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1120. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1121. // 验证剧集是否存在
  1122. $episode = DB::table('mp_anime_episodes')
  1123. ->where('anime_id', $anime_id)
  1124. ->where('id', $episode_id)
  1125. ->first();
  1126. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1127. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1128. // 获取anime信息,检查是否有关联的script_id
  1129. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1130. if (!$anime) Utils::throwError('20003:动漫不存在');
  1131. $script_id = getProp($anime, 'script_id');
  1132. $episode_number = getProp($episode, 'episode_number', 1);
  1133. $uid = Site::getUid();
  1134. $cpid = Site::getCpid();
  1135. try {
  1136. $target_scene_name = getProp($target_scenes, 'scene');
  1137. if (empty($target_scene_name)) {
  1138. Utils::throwError('20003:场景名称不能为空');
  1139. }
  1140. // 如果是删除操作
  1141. if ($is_deleted == 1) {
  1142. // 从场景列表中移除该场景
  1143. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1144. return getProp($scene, 'scene') !== $target_scene_name;
  1145. }));
  1146. // 更新场景列表
  1147. $result = DB::table('mp_anime_episodes')
  1148. ->where('anime_id', $anime_id)
  1149. ->where('id', $episode_id)
  1150. ->update([
  1151. 'scenes' => json_encode($scenes, 256),
  1152. 'updated_at' => date('Y-m-d H:i:s')
  1153. ]);
  1154. if ($result === false) {
  1155. Utils::throwError('20003:删除场景失败');
  1156. }
  1157. } else {
  1158. // 新增或更新操作
  1159. $scene_found = false;
  1160. $is_new_scene = false;
  1161. // 查找并更新已存在的场景
  1162. foreach($scenes as &$scene) {
  1163. if (getProp($scene, 'scene') === $target_scene_name) {
  1164. $scene = $target_scenes;
  1165. $scene_found = true;
  1166. break;
  1167. }
  1168. }
  1169. // 如果场景不存在,则新增
  1170. if (!$scene_found) {
  1171. $scenes[] = $target_scenes;
  1172. $is_new_scene = true;
  1173. }
  1174. // 更新场景列表
  1175. $result = DB::table('mp_anime_episodes')
  1176. ->where('anime_id', $anime_id)
  1177. ->where('id', $episode_id)
  1178. ->update([
  1179. 'scenes' => json_encode($scenes, 256),
  1180. 'updated_at' => date('Y-m-d H:i:s')
  1181. ]);
  1182. if ($result === false) {
  1183. Utils::throwError('20003:更新场景列表失败');
  1184. }
  1185. // 如果有关联的script_id,则同步到mp_products表
  1186. if ($script_id) {
  1187. // 查询剧本信息
  1188. $script = DB::table('mp_scripts')
  1189. ->where('id', $script_id)
  1190. ->where('is_deleted', 0)
  1191. ->first();
  1192. if ($script) {
  1193. $script_name = $script->script_name ?? 'script_' . $script_id;
  1194. $product_name = getProp($target_scenes, 'scene');
  1195. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1196. $url = getProp($target_scenes, 'url', '');
  1197. $product_type = 2; // 2=场景
  1198. // 查找或创建以script_name命名的文件夹
  1199. $folder = DB::table('mp_products')
  1200. ->where('cpid', $cpid)
  1201. ->where('type', 2) // 文件夹类型
  1202. ->where('product', $product_type) // 场景类型
  1203. ->where('product_name', $script_name)
  1204. ->where('parent_id', 0)
  1205. ->where('is_deleted', 0)
  1206. ->first();
  1207. if (!$folder) {
  1208. // 创建文件夹
  1209. $folder_id = DB::table('mp_products')->insertGetId([
  1210. 'user_id' => $uid,
  1211. 'cpid' => $cpid,
  1212. 'type' => 2, // 文件夹
  1213. 'product' => $product_type, // 场景类型
  1214. 'parent_id' => 0,
  1215. 'level' => 1,
  1216. 'product_name' => $script_name,
  1217. 'sort_order' => time(),
  1218. 'is_deleted' => 0,
  1219. 'created_at' => date('Y-m-d H:i:s'),
  1220. 'updated_at' => date('Y-m-d H:i:s')
  1221. ]);
  1222. } else {
  1223. $folder_id = $folder->id;
  1224. }
  1225. // 查找该文件夹下是否已存在同名资产
  1226. $existing_product = DB::table('mp_products')
  1227. ->where('cpid', $cpid)
  1228. ->where('type', 1) // 资产类型
  1229. ->where('product', $product_type)
  1230. ->where('parent_id', $folder_id)
  1231. ->where('product_name', $product_name)
  1232. ->where('is_deleted', 0)
  1233. ->first();
  1234. if ($existing_product) {
  1235. // 更新已存在的资产
  1236. $updateData = [
  1237. 'pic_task_status' => '生成成功'
  1238. ];
  1239. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1240. if ($url) $updateData['url'] = $url;
  1241. // 处理versions字段
  1242. $versions = getProp($target_scenes, 'versions', []);
  1243. if ($versions && is_array($versions)) {
  1244. $updateData['versions'] = json_encode($versions, 256);
  1245. }
  1246. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1247. DB::table('mp_products')
  1248. ->where('id', $existing_product->id)
  1249. ->update($updateData);
  1250. $product_id = $existing_product->id;
  1251. } else {
  1252. // 创建新资产
  1253. $versions = getProp($target_scenes, 'versions', []);
  1254. $product_id = DB::table('mp_products')->insertGetId([
  1255. 'user_id' => $uid,
  1256. 'cpid' => $cpid,
  1257. 'type' => 1, // 资产
  1258. 'product' => $product_type, // 场景
  1259. 'parent_id' => $folder_id,
  1260. 'level' => 2,
  1261. 'product_name' => $product_name,
  1262. 'url' => $url,
  1263. 'pic_prompt' => $pic_prompt,
  1264. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1265. 'sort_order' => time(),
  1266. 'is_deleted' => 0,
  1267. 'pic_task_status' => '生成成功',
  1268. 'created_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s')
  1270. ]);
  1271. }
  1272. // 建立或更新绑定关系
  1273. $existing_mapping = DB::table('mp_script_product_mappings')
  1274. ->where('script_id', $script_id)
  1275. ->where('product_id', $product_id)
  1276. ->where('episode_number', $episode_number)
  1277. ->first();
  1278. if (!$existing_mapping) {
  1279. // 创建绑定关系
  1280. DB::table('mp_script_product_mappings')->insert([
  1281. 'script_id' => $script_id,
  1282. 'product_id' => $product_id,
  1283. 'episode_number' => $episode_number,
  1284. 'created_at' => date('Y-m-d H:i:s'),
  1285. 'updated_at' => date('Y-m-d H:i:s')
  1286. ]);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. } catch (\Exception $e) {
  1292. dLog('anime')->error('更新剧集场景失败', [
  1293. 'anime_id' => $anime_id,
  1294. 'episode_id' => $episode_id,
  1295. 'error' => $e->getMessage()
  1296. ]);
  1297. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1298. }
  1299. return true;
  1300. }
  1301. public function changeEpisodeProps($data) {
  1302. $anime_id = getProp($data, 'anime_id');
  1303. $episode_id = getProp($data, 'episode_id');
  1304. $target_props = getProp($data, 'props');
  1305. $is_deleted = getProp($data, 'is_deleted', 0);
  1306. // 参数验证
  1307. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1308. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1309. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1310. // 验证剧集是否存在
  1311. $episode = DB::table('mp_anime_episodes')
  1312. ->where('anime_id', $anime_id)
  1313. ->where('id', $episode_id)
  1314. ->first();
  1315. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1316. $props = json_decode(getProp($episode, 'props'), true);
  1317. // 获取anime信息,检查是否有关联的script_id
  1318. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1319. if (!$anime) Utils::throwError('20003:动漫不存在');
  1320. $script_id = getProp($anime, 'script_id');
  1321. $episode_number = getProp($episode, 'episode_number', 1);
  1322. $uid = Site::getUid();
  1323. $cpid = Site::getCpid();
  1324. try {
  1325. $target_prop_name = getProp($target_props, 'prop');
  1326. if (empty($target_prop_name)) {
  1327. Utils::throwError('20003:道具名称不能为空');
  1328. }
  1329. // 如果是删除操作
  1330. if ($is_deleted == 1) {
  1331. // 从道具列表中移除该道具
  1332. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1333. return getProp($prop, 'prop') !== $target_prop_name;
  1334. }));
  1335. // 更新道具列表
  1336. $result = DB::table('mp_anime_episodes')
  1337. ->where('anime_id', $anime_id)
  1338. ->where('id', $episode_id)
  1339. ->update([
  1340. 'props' => json_encode($props, 256),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. if ($result === false) {
  1344. Utils::throwError('20003:删除道具失败');
  1345. }
  1346. } else {
  1347. // 新增或更新操作
  1348. $prop_found = false;
  1349. $is_new_prop = false;
  1350. // 查找并更新已存在的道具
  1351. foreach($props as &$prop) {
  1352. if (getProp($prop, 'prop') === $target_prop_name) {
  1353. $prop = $target_props;
  1354. $prop_found = true;
  1355. break;
  1356. }
  1357. }
  1358. // 如果道具不存在,则新增
  1359. if (!$prop_found) {
  1360. $props[] = $target_props;
  1361. $is_new_prop = true;
  1362. }
  1363. // 更新道具列表
  1364. $result = DB::table('mp_anime_episodes')
  1365. ->where('anime_id', $anime_id)
  1366. ->where('id', $episode_id)
  1367. ->update([
  1368. 'props' => json_encode($props, 256),
  1369. 'updated_at' => date('Y-m-d H:i:s')
  1370. ]);
  1371. if ($result === false) {
  1372. Utils::throwError('20003:更新道具列表失败');
  1373. }
  1374. // 如果有关联的script_id,则同步到mp_products表
  1375. if ($script_id) {
  1376. // 查询剧本信息
  1377. $script = DB::table('mp_scripts')
  1378. ->where('id', $script_id)
  1379. ->where('is_deleted', 0)
  1380. ->first();
  1381. if ($script) {
  1382. $script_name = $script->script_name ?? 'script_' . $script_id;
  1383. $product_name = getProp($target_props, 'prop');
  1384. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1385. $url = getProp($target_props, 'url', '');
  1386. $product_type = 3; // 3=道具
  1387. // 查找或创建以script_name命名的文件夹
  1388. $folder = DB::table('mp_products')
  1389. ->where('cpid', $cpid)
  1390. ->where('type', 2) // 文件夹类型
  1391. ->where('product', $product_type) // 道具类型
  1392. ->where('product_name', $script_name)
  1393. ->where('parent_id', 0)
  1394. ->where('is_deleted', 0)
  1395. ->first();
  1396. if (!$folder) {
  1397. // 创建文件夹
  1398. $folder_id = DB::table('mp_products')->insertGetId([
  1399. 'user_id' => $uid,
  1400. 'cpid' => $cpid,
  1401. 'type' => 2, // 文件夹
  1402. 'product' => $product_type, // 道具类型
  1403. 'parent_id' => 0,
  1404. 'level' => 1,
  1405. 'product_name' => $script_name,
  1406. 'sort_order' => time(),
  1407. 'is_deleted' => 0,
  1408. 'created_at' => date('Y-m-d H:i:s'),
  1409. 'updated_at' => date('Y-m-d H:i:s')
  1410. ]);
  1411. } else {
  1412. $folder_id = $folder->id;
  1413. }
  1414. // 查找该文件夹下是否已存在同名资产
  1415. $existing_product = DB::table('mp_products')
  1416. ->where('cpid', $cpid)
  1417. ->where('type', 1) // 资产类型
  1418. ->where('product', $product_type)
  1419. ->where('parent_id', $folder_id)
  1420. ->where('product_name', $product_name)
  1421. ->where('is_deleted', 0)
  1422. ->first();
  1423. if ($existing_product) {
  1424. // 更新已存在的资产
  1425. $updateData = [
  1426. 'pic_task_status' => '生成成功'
  1427. ];
  1428. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1429. if ($url) $updateData['url'] = $url;
  1430. // 处理versions字段
  1431. $versions = getProp($target_props, 'versions', []);
  1432. if ($versions && is_array($versions)) {
  1433. $updateData['versions'] = json_encode($versions, 256);
  1434. }
  1435. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1436. DB::table('mp_products')
  1437. ->where('id', $existing_product->id)
  1438. ->update($updateData);
  1439. $product_id = $existing_product->id;
  1440. } else {
  1441. // 创建新资产
  1442. $versions = getProp($target_props, 'versions', []);
  1443. $product_id = DB::table('mp_products')->insertGetId([
  1444. 'user_id' => $uid,
  1445. 'cpid' => $cpid,
  1446. 'type' => 1, // 资产
  1447. 'product' => $product_type, // 道具
  1448. 'parent_id' => $folder_id,
  1449. 'level' => 2,
  1450. 'product_name' => $product_name,
  1451. 'url' => $url,
  1452. 'pic_prompt' => $pic_prompt,
  1453. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1454. 'sort_order' => time(),
  1455. 'is_deleted' => 0,
  1456. 'pic_task_status' => '生成成功',
  1457. 'created_at' => date('Y-m-d H:i:s'),
  1458. 'updated_at' => date('Y-m-d H:i:s')
  1459. ]);
  1460. }
  1461. // 建立或更新绑定关系
  1462. $existing_mapping = DB::table('mp_script_product_mappings')
  1463. ->where('script_id', $script_id)
  1464. ->where('product_id', $product_id)
  1465. ->where('episode_number', $episode_number)
  1466. ->first();
  1467. if (!$existing_mapping) {
  1468. // 创建绑定关系
  1469. DB::table('mp_script_product_mappings')->insert([
  1470. 'script_id' => $script_id,
  1471. 'product_id' => $product_id,
  1472. 'episode_number' => $episode_number,
  1473. 'created_at' => date('Y-m-d H:i:s'),
  1474. 'updated_at' => date('Y-m-d H:i:s')
  1475. ]);
  1476. }
  1477. }
  1478. }
  1479. }
  1480. } catch (\Exception $e) {
  1481. dLog('anime')->error('更新剧集道具失败', [
  1482. 'anime_id' => $anime_id,
  1483. 'episode_id' => $episode_id,
  1484. 'error' => $e->getMessage()
  1485. ]);
  1486. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1487. }
  1488. return true;
  1489. }
  1490. public function editSegment($data) {
  1491. $segment_id = getProp($data, 'segment_id');
  1492. $segment_content = getProp($data, 'segment_content');
  1493. $image_url = getProp($data, 'image_url');
  1494. $video_url = getProp($data, 'video_url');
  1495. // 参数验证
  1496. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1497. // 验证分镜是否存在
  1498. $segment = DB::table('mp_episode_segments')
  1499. ->where('segment_id', $segment_id)
  1500. ->first();
  1501. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1502. $dubTaskId = 0;
  1503. try {
  1504. DB::beginTransaction();
  1505. // 准备更新数据
  1506. $update_data = [
  1507. 'updated_at' => date('Y-m-d H:i:s')
  1508. ];
  1509. if ($segment_content) {
  1510. // 先将segment_content赋值到update_data
  1511. $update_data['segment_content'] = $segment_content;
  1512. // 使用现有方法分析segment_content,提取各个字段
  1513. $this->handleSegmentContent($update_data);
  1514. // 如果有对话内容,创建视频配音合成任务
  1515. $dialogue = getProp($update_data, 'dialogue');
  1516. if (!empty($dialogue)) {
  1517. $now = date('Y-m-d H:i:s');
  1518. $generate_json = [
  1519. 'text' => $dialogue,
  1520. 'role' => getProp($update_data, 'voice_actor'),
  1521. 'voice_type' => getProp($update_data, 'voice_type'),
  1522. 'voice_name' => getProp($update_data, 'voice_name'),
  1523. 'emotion' => getProp($update_data, 'emotion'),
  1524. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1525. 'gender' => getProp($update_data, 'gender'),
  1526. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1527. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1528. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1529. 'pitch' => getProp($update_data, 'pitch', 0),
  1530. ];
  1531. // 插入视频配音合成任务
  1532. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1533. 'alias_segment_id' => $segment_id,
  1534. 'generate_status' => '执行中',
  1535. 'audio_url' => '',
  1536. 'generate_json' => json_encode($generate_json, 256),
  1537. 'created_at' => $now,
  1538. 'updated_at' => $now,
  1539. ]);
  1540. if (!$dubTaskId) {
  1541. Utils::throwError('20003:创建配音任务失败!');
  1542. }
  1543. $update_data['audio_url'] = '';
  1544. } else {
  1545. // dialogue为空时,直接写入默认音频信息
  1546. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1547. $update_data['audio_duration'] = 2.0;
  1548. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1549. }
  1550. }
  1551. if ($image_url) {
  1552. $update_data['img_url'] = $image_url;
  1553. // 同时写入一个简单的图片生成任务
  1554. $pic_task = [
  1555. 'alias_segment_id' => $segment_id,
  1556. 'ref_img_url' => json_encode([]),
  1557. 'status' => 'success',
  1558. 'result_url' => json_encode([$image_url], 256),
  1559. 'model' => '',
  1560. 'created_at' => date('Y-m-d H:i:s'),
  1561. 'updated_at' => date('Y-m-d H:i:s'),
  1562. ];
  1563. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1564. }
  1565. if ($video_url) {
  1566. $update_data['origin_video_url'] = $video_url;
  1567. $compressed_video_url = compressVideo($video_url);
  1568. $update_data['current_type'] = 2;
  1569. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1570. // 同时写入一个简单的视频生成任务
  1571. $video_task = [
  1572. 'alias_segment_id' => $segment_id,
  1573. 'status' => 'success',
  1574. 'result_url' => $update_data['origin_video_url'],
  1575. 'compressed_url' => $update_data['video_url'],
  1576. 'created_at' => date('Y-m-d H:i:s'),
  1577. 'updated_at' => date('Y-m-d H:i:s'),
  1578. ];
  1579. DB::table('mp_generate_video_tasks')->insert($video_task);
  1580. }
  1581. // 更新分镜信息
  1582. $result = DB::table('mp_episode_segments')
  1583. ->where('segment_id', $segment_id)
  1584. ->update($update_data);
  1585. if ($result === false) {
  1586. Utils::throwError('20003:更新分镜剧本失败');
  1587. }
  1588. DB::commit();
  1589. // 如果有创建音频生成任务则调用API
  1590. if ($dubTaskId) {
  1591. // 请求远程服务器执行生成
  1592. $client = new Client(['timeout' => 300, 'verify' => false]);
  1593. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1594. $response = $result->getBody()->getContents();
  1595. $response_arr = json_decode($response, true);
  1596. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1597. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1598. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1599. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1600. Utils::throwError('20003:火山生成音频失败');
  1601. }
  1602. }
  1603. return true;
  1604. } catch (\Exception $e) {
  1605. DB::rollBack();
  1606. dLog('anime')->error('更新分镜剧本失败', [
  1607. 'segment_id' => $segment_id,
  1608. 'error' => $e->getMessage()
  1609. ]);
  1610. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1611. }
  1612. }
  1613. public function batchSetSegmentPics($data) {
  1614. $anime_id = getProp($data, 'anime_id');
  1615. $episode_id = getProp($data, 'episode_id');
  1616. $ratio = getProp($data, 'ratio');
  1617. $dimensions = $this->getRatioDimensions($ratio);
  1618. $width = $dimensions['width'];
  1619. $height = $dimensions['height'];
  1620. if (!$anime_id || !$episode_id) {
  1621. Utils::throwError('1002:请选择剧集');
  1622. }
  1623. // 获取剧集信息
  1624. $episode = DB::table('mp_anime_episodes')
  1625. ->where('anime_id', $anime_id)
  1626. ->where('id', $episode_id)
  1627. ->where('is_default', 1)
  1628. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1629. ->first();
  1630. if (!$episode) {
  1631. Utils::throwError('20003:该剧集不存在');
  1632. }
  1633. $model = getProp($data, 'model');
  1634. if (!$model) {
  1635. $model = getProp($episode, 'image_model');
  1636. if (!$model) {
  1637. // episode表也没有,使用默认值
  1638. $model = 'doubao-seedream-5-0-lite-260128';
  1639. }
  1640. }
  1641. // 验证模型是否在可用模型表中
  1642. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1643. $model = 'doubao-seedream-5-0-lite-260128';
  1644. }
  1645. $roles = json_decode(getProp($episode, 'roles'), true);
  1646. if (!$roles) {
  1647. Utils::throwError('20003:角色信息格式错误');
  1648. }
  1649. // 构建角色名称到参考图的映射
  1650. $role_map = [];
  1651. foreach ($roles as $role) {
  1652. $role_name = getProp($role, 'role');
  1653. $role_url = getProp($role, 'url');
  1654. if (!empty($role_name) && !empty($role_url)) {
  1655. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1656. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1657. // $role_map[$base_name] = $role_url;
  1658. // 同时保存完整名称的映射
  1659. $role_map[$role_name] = $role_url;
  1660. }
  1661. }
  1662. $scenes = json_decode(getProp($episode, 'roles'), true);
  1663. if (!$scenes) {
  1664. Utils::throwError('20003:场景信息格式错误');
  1665. }
  1666. // 构建角色名称到参考图的映射
  1667. $scene_map = [];
  1668. foreach ($scenes as $scene) {
  1669. $scene_name = getProp($scene, 'scene');
  1670. $scene_url = getProp($scene, 'url');
  1671. if (!empty($scene_name) && !empty($scene_url)) {
  1672. $scene_map[$scene_name] = $scene_url;
  1673. }
  1674. }
  1675. // 获取所有分镜信息
  1676. $segments = DB::table('mp_episode_segments')
  1677. ->where('anime_id', $anime_id)
  1678. ->where('episode_id', $episode_id)
  1679. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1680. ->orderBy('segment_number')
  1681. ->get()
  1682. ->toArray();
  1683. if (empty($segments)) {
  1684. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1685. }
  1686. // 保存图片比例
  1687. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1688. $updated_segments = [];
  1689. $failed_segments = [];
  1690. // 批量为每个分镜生成图片任务
  1691. foreach ($segments as $segment) {
  1692. $segment_id = $segment->segment_id;
  1693. $segment_content = $segment->segment_content;
  1694. if (empty($segment_content)) {
  1695. $failed_segments[] = [
  1696. 'segment_id' => $segment_id,
  1697. 'error' => '分镜内容为空'
  1698. ];
  1699. continue;
  1700. }
  1701. try {
  1702. $dubTaskId = 0;
  1703. // 解析分镜内容,提取画面描述作为主要提示词
  1704. $prompt = $segment_content;
  1705. $ref_img_urls = [];
  1706. // 分镜场景
  1707. $scene = getProp($segment, 'scene');
  1708. $matched_scene = '';
  1709. if (isset($scene_map[$scene])) {
  1710. $img_index = count($ref_img_urls) + 1;
  1711. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1712. $ref_img_urls[] = $scene_map[$scene];
  1713. $matched_scene = $scene;
  1714. }
  1715. // 分镜角色
  1716. $characters = getProp($segment, 'characters');
  1717. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1718. $roles = explode(',', $characters);
  1719. // 从分镜内容中提取涉及的角色
  1720. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1721. // 获取匹配角色的参考图
  1722. foreach ($segment_characters as $character) {
  1723. if (isset($role_map[$character])) {
  1724. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1725. $img_index = count($ref_img_urls) + 1;
  1726. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1727. $ref_img_urls[] = $role_map[$character];
  1728. }
  1729. }
  1730. // 如果没有找到匹配的角色参考图,不使用参考图
  1731. if (empty($ref_img_urls)) {
  1732. $ref_img_urls = [];
  1733. }
  1734. // 准备生成任务参数
  1735. $params = [
  1736. 'model' => $model,
  1737. 'alias_segment_id' => $segment_id,
  1738. 'prompt' => $prompt,
  1739. 'ref_img_urls' => $ref_img_urls,
  1740. 'width' => $width,
  1741. 'height' => $height,
  1742. ];
  1743. // 优化提示词(不要生成字幕)
  1744. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1745. // $task_id = mt_rand(100000, 999999);
  1746. // 调用AI图片生成服务
  1747. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1748. $task_id = $task->id;
  1749. if (!$task_id) {
  1750. $failed_segments[] = [
  1751. 'segment_id' => $segment_id,
  1752. 'error' => '创建生成任务失败'
  1753. ];
  1754. continue;
  1755. }
  1756. $update_data = [
  1757. 'pic_task_id' => $task_id,
  1758. 'pic_task_status' => '生成中',
  1759. 'audio_url' => '',
  1760. 'updated_at' => date('Y-m-d H:i:s')
  1761. ];
  1762. // 如果有对话内容,创建视频配音合成任务
  1763. $dialogue = getProp($segment, 'dialogue');
  1764. if (!empty($dialogue)) {
  1765. $now = date('Y-m-d H:i:s');
  1766. $generate_json = [
  1767. 'text' => $dialogue,
  1768. 'role' => getProp($segment, 'voice_actor'),
  1769. 'voice_type' => getProp($segment, 'voice_type'),
  1770. 'voice_name' => getProp($segment, 'voice_name'),
  1771. 'emotion' => getProp($segment, 'emotion'),
  1772. 'emotion_type' => getProp($segment, 'emotion_type'),
  1773. 'gender' => getProp($segment, 'gender'),
  1774. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1775. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1776. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1777. 'pitch' => getProp($segment, 'pitch', 0),
  1778. ];
  1779. // 插入视频配音合成任务
  1780. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1781. 'alias_segment_id' => $segment_id,
  1782. 'generate_status' => '执行中',
  1783. 'audio_url' => '',
  1784. 'generate_json' => json_encode($generate_json, 256),
  1785. 'created_at' => $now,
  1786. 'updated_at' => $now,
  1787. ]);
  1788. if (!$dubTaskId) {
  1789. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1790. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1791. // Utils::throwError('20003:创建配音任务失败!');
  1792. }
  1793. } else {
  1794. // dialogue为空时,直接写入默认音频信息到分镜表
  1795. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1796. $update_data['audio_duration'] = 2.0;
  1797. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1798. }
  1799. // 更新分镜的任务信息
  1800. $update_result = DB::table('mp_episode_segments')
  1801. ->where('segment_id', $segment_id)
  1802. ->update($update_data);
  1803. // 如果是第一集的首帧图片,则存入待更新数组
  1804. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1805. Redis::sadd('anime_first_frame_urls', $segment_id);
  1806. }
  1807. if ($update_result) {
  1808. $updated_segments[] = [
  1809. 'segment_id' => $segment_id,
  1810. 'task_id' => $task_id,
  1811. 'status' => '生成中',
  1812. 'matched_scenes' => $matched_scene,
  1813. 'matched_roles' => $segment_characters,
  1814. 'ref_urls_count' => count($ref_img_urls)
  1815. ];
  1816. } else {
  1817. $failed_segments[] = [
  1818. 'segment_id' => $segment_id,
  1819. 'error' => '更新分镜任务状态失败'
  1820. ];
  1821. }
  1822. if ($dubTaskId) {
  1823. sleep(1);
  1824. // 请求远程服务器执行生成
  1825. $client = new Client(['timeout' => 300, 'verify' => false]);
  1826. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1827. $response = $result->getBody()->getContents();
  1828. $response_arr = json_decode($response, true);
  1829. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1830. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1831. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1832. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1833. }
  1834. }
  1835. } catch (\Exception $e) {
  1836. $failed_segments[] = [
  1837. 'segment_id' => $segment_id,
  1838. 'error' => $e->getMessage()
  1839. ];
  1840. }
  1841. }
  1842. // 更新剧集生成状态
  1843. if (!empty($updated_segments)) {
  1844. DB::table('mp_anime_episodes')
  1845. ->where('id', $episode_id)
  1846. ->update([
  1847. 'is_generated' => 1,
  1848. 'updated_at' => date('Y-m-d H:i:s')
  1849. ]);
  1850. }
  1851. return [
  1852. 'success_count' => count($updated_segments),
  1853. 'failed_count' => count($failed_segments),
  1854. 'success_segments' => $updated_segments,
  1855. 'failed_segments' => $failed_segments,
  1856. 'total_segments' => count($segments)
  1857. ];
  1858. }
  1859. public function reGenerateSegment($data) {
  1860. $segment_id = getProp($data, 'segment_id');
  1861. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1862. $anime_id = getProp($segment, 'anime_id');
  1863. $episode_id = getProp($segment, 'episode_id');
  1864. $episode_number = getProp($segment, 'episode_number');
  1865. $segment_content = getProp($data, 'segment_content');
  1866. $ratio = getProp($data, 'ratio');
  1867. if (!$ratio) {
  1868. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1869. if (!$ratio) $ratio = '9:16';
  1870. }
  1871. $dimensions = $this->getRatioDimensions($ratio);
  1872. $width = $dimensions['width'];
  1873. $height = $dimensions['height'];
  1874. if (!$anime_id || !$episode_id) {
  1875. Utils::throwError('1002:请选择分镜');
  1876. }
  1877. // 使用文生文模型重新解析segment_content
  1878. if (!empty($segment_content)) {
  1879. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1880. }
  1881. // 获取动漫的角色信息(包含参考图)
  1882. $anime = DB::table('mp_animes')
  1883. ->where('id', $anime_id)
  1884. ->select('roles', 'scenes')
  1885. ->first();
  1886. if (!$anime || !$anime->roles) {
  1887. Utils::throwError('20003:未找到角色信息');
  1888. }
  1889. $roles = json_decode($anime->roles, true);
  1890. if (!$roles) {
  1891. Utils::throwError('20003:角色信息格式错误');
  1892. }
  1893. // 构建角色名称到参考图的映射
  1894. $role_map = [];
  1895. foreach ($roles as $role) {
  1896. $role_name = getProp($role, 'role');
  1897. $role_url = getProp($role, 'url');
  1898. if (!empty($role_name) && !empty($role_url)) {
  1899. $role_map[$role_name] = $role_url;
  1900. }
  1901. }
  1902. $scenes = json_decode($anime->scenes, true);
  1903. if (!$scenes) {
  1904. Utils::throwError('20003:角色信息格式错误');
  1905. }
  1906. // 构建角色名称到参考图的映射
  1907. $scene_map = [];
  1908. foreach ($scenes as $scene) {
  1909. $scene_name = getProp($scene, 'scene');
  1910. $scene_url = getProp($scene, 'url');
  1911. if (!empty($scene_name) && !empty($scene_url)) {
  1912. $scene_map[$scene_name] = $scene_url;
  1913. }
  1914. }
  1915. $segment_id = $segment->segment_id;
  1916. $original_segment_content = $segment->segment_content;
  1917. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1918. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1919. if (empty($final_segment_content)) {
  1920. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1921. }
  1922. try {
  1923. $dubTaskId = 0;
  1924. // 分镜剧本数组
  1925. $update_data = [
  1926. 'segment_content' => $final_segment_content,
  1927. 'pic_task_status' => '生成中',
  1928. 'updated_at' => date('Y-m-d H:i:s')
  1929. ];
  1930. // 解析分镜内容,提取画面描述作为主要提示词
  1931. $prompt = $final_segment_content;
  1932. $ref_img_urls = [];
  1933. // 分镜场景
  1934. $scene = getProp($data, 'scene');
  1935. if ($scene) {
  1936. $matched_scene = '';
  1937. if (isset($scene_map[$scene])) {
  1938. $img_index = count($ref_img_urls) + 1;
  1939. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1940. $ref_img_urls[] = $scene_map[$scene];
  1941. $matched_scene = $scene;
  1942. }
  1943. $update_data['scene'] = $scene;
  1944. }
  1945. // 分镜角色
  1946. $characters = getProp($data, 'characters');
  1947. if ($characters) {
  1948. $update_data['characters'] = $characters;
  1949. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1950. $characters = explode(',', $characters);
  1951. // 从分镜内容中提取涉及的角色
  1952. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1953. // 获取匹配角色的参考图
  1954. foreach ($segment_characters as $character) {
  1955. if (isset($role_map[$character])) {
  1956. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1957. $img_index = count($ref_img_urls) + 1;
  1958. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1959. $ref_img_urls[] = $role_map[$character];
  1960. }
  1961. }
  1962. }
  1963. // 如果没有找到匹配的角色参考图,不使用参考图
  1964. if (empty($ref_img_urls)) {
  1965. $ref_img_urls = [];
  1966. }
  1967. // 准备生成任务参数
  1968. $params = [
  1969. 'alias_segment_id' => $segment_id,
  1970. 'prompt' => $prompt,
  1971. 'ref_img_urls' => $ref_img_urls,
  1972. 'width' => $width,
  1973. 'height' => $height,
  1974. ];
  1975. // 优化提示词(不要生成字幕)
  1976. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1977. // 调用AI图片生成服务
  1978. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1979. $task_id = $task->id;
  1980. if (!$task_id) {
  1981. Utils::throwError('20003:创建生成任务失败!');
  1982. }
  1983. $update_data['pic_task_id'] = $task_id;
  1984. // 更新分镜剧本信息
  1985. $this->handleSegmentContent($update_data);
  1986. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1987. if ($segment_content) {
  1988. $dialogue = getProp($update_data, 'dialogue');
  1989. if (!empty($dialogue)) {
  1990. $now = date('Y-m-d H:i:s');
  1991. $generate_json = [
  1992. 'text' => $dialogue,
  1993. 'role' => getProp($update_data, 'voice_actor'),
  1994. 'voice_type' => getProp($update_data, 'voice_type'),
  1995. 'voice_name' => getProp($update_data, 'voice_name'),
  1996. 'emotion' => getProp($update_data, 'emotion'),
  1997. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1998. 'gender' => getProp($update_data, 'gender'),
  1999. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2000. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2001. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2002. 'pitch' => getProp($update_data, 'pitch', 0),
  2003. ];
  2004. // 插入视频配音合成任务
  2005. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2006. 'alias_segment_id' => $segment_id,
  2007. 'generate_status' => '执行中',
  2008. 'audio_url' => '',
  2009. 'generate_json' => json_encode($generate_json, 256),
  2010. 'created_at' => date('Y-m-d H:i:s'),
  2011. 'updated_at' => date('Y-m-d H:i:s'),
  2012. ]);
  2013. if (!$dubTaskId) {
  2014. Utils::throwError('20003:创建配音任务失败!');
  2015. }
  2016. $update_data['audio_url'] = '';
  2017. } else {
  2018. // dialogue为空时,直接写入默认音频信息
  2019. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2020. $update_data['audio_duration'] = 2.0;
  2021. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2022. }
  2023. }
  2024. $boolen = DB::table('mp_episode_segments')
  2025. ->where('segment_id', $segment_id)
  2026. ->update($update_data);
  2027. // 如果是第一集的首帧图片,则存入待更新数组
  2028. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2029. Redis::sadd('anime_first_frame_urls', $segment_id);
  2030. }
  2031. if ($dubTaskId) {
  2032. // 请求远程服务器执行生成
  2033. $client = new Client(['timeout' => 300, 'verify' => false]);
  2034. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2035. $response = $result->getBody()->getContents();
  2036. $response_arr = json_decode($response, true);
  2037. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2038. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2039. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2040. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2041. Utils::throwError('20003:火山生成音频失败');
  2042. }
  2043. }
  2044. } catch (\Exception $e) {
  2045. $failed_segments[] = [
  2046. 'segment_id' => $segment_id,
  2047. 'error' => $e->getMessage()
  2048. ];
  2049. }
  2050. // 创建任务之后先暂停10s等待异步任务完成
  2051. sleep(10);
  2052. $img_url = $this->loopGetPicTaskResult($task_id);
  2053. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2054. // 图片生成后新增对话记录
  2055. try {
  2056. $uid = Site::getUid();
  2057. $now = date('Y-m-d H:i:s');
  2058. // 使用AI反推图片提示词
  2059. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2060. // 保存对话记录
  2061. $records = [
  2062. [
  2063. 'uid' => $uid,
  2064. 'anime_id' => $anime_id,
  2065. 'sequence' => $episode_number,
  2066. 'role' => 'user',
  2067. 'content' => '重新生成',
  2068. 'segment_id' => $segment_id,
  2069. 'pic_task_id' => $task_id,
  2070. 'image_url' => '',
  2071. 'created_at' => $now,
  2072. 'updated_at' => $now
  2073. ],
  2074. [
  2075. 'uid' => $uid,
  2076. 'anime_id' => $anime_id,
  2077. 'sequence' => $episode_number,
  2078. 'role' => 'assistant',
  2079. 'content' => $pic_prompt,
  2080. 'segment_id' => $segment_id,
  2081. 'pic_task_id' => $task_id,
  2082. 'image_url' => $img_url,
  2083. 'created_at' => $now,
  2084. 'updated_at' => $now
  2085. ]
  2086. ];
  2087. DB::table('mp_anime_records')->insert($records);
  2088. } catch (\Exception $e) {
  2089. // 记录日志但不影响主流程
  2090. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2091. 'segment_id' => $segment_id,
  2092. 'img_url' => $img_url
  2093. ]);
  2094. }
  2095. return $img_url;
  2096. }
  2097. public function addSegment($data) {
  2098. $prev_segment_id = getProp($data, 'prev_segment_id');
  2099. $img_url = getProp($data, 'img_url');
  2100. $video_url = getProp($data, 'video_url');
  2101. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2102. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2103. $anime_id = getProp($segment, 'anime_id');
  2104. $episode_id = getProp($segment, 'episode_id');
  2105. $episode_number = getProp($segment, 'episode_number');
  2106. $segment_number = getProp($segment, 'segment_number');
  2107. $new_segment_number = $segment_number + 1;
  2108. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2109. // 分镜剧本数组
  2110. $insert_data = [
  2111. 'anime_id' => $anime_id,
  2112. 'episode_id' => $episode_id,
  2113. 'episode_number' => $episode_number,
  2114. 'act_number' => getProp($segment, 'act_number'),
  2115. 'act_title' => getProp($segment, 'act_title'),
  2116. 'segment_id' => $segment_id,
  2117. 'segment_number' => $new_segment_number,
  2118. 'segment_content' => '',
  2119. 'img_url' => '',
  2120. 'video_url' => '',
  2121. 'created_at' => date('Y-m-d H:i:s'),
  2122. 'updated_at' => date('Y-m-d H:i:s')
  2123. ];
  2124. if ($img_url) $insert_data['img_url'] = $img_url;
  2125. if ($video_url) {
  2126. $insert_data['origin_video_url'] = $video_url;
  2127. $insert_data['current_type'] = 2;
  2128. $compressed_video_url = compressVideo($video_url);
  2129. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2130. }
  2131. try {
  2132. DB::beginTransaction();
  2133. // 先更新序号
  2134. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2135. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2136. if (!$id) {
  2137. Utils::throwError('20003:新增分镜失败!');
  2138. }
  2139. }catch (\Exception $e) {
  2140. DB::rollBack();
  2141. Utils::throwError('20003:'.$e->getMessage());
  2142. }
  2143. DB::commit();
  2144. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2145. $segment = $segment ? (array)$segment : [];
  2146. return $segment;
  2147. // 以下代码暂弃用
  2148. $anime_id = getProp($segment, 'anime_id');
  2149. $episode_id = getProp($segment, 'episode_id');
  2150. $episode_number = getProp($segment, 'episode_number');
  2151. $segment_number = getProp($segment, 'segment_number');
  2152. $segment_content = getProp($data, 'segment_content');
  2153. $img_url = getProp($data, 'img_url');
  2154. $video_url = getProp($data, 'video_url');
  2155. $ratio = getProp($data, 'ratio');
  2156. $dimensions = $this->getRatioDimensions($ratio);
  2157. $width = $dimensions['width'];
  2158. $height = $dimensions['height'];
  2159. if (!$anime_id || !$episode_id) {
  2160. Utils::throwError('1002:请选择分镜');
  2161. }
  2162. // 使用文生文模型重新解析segment_content
  2163. if (!empty($segment_content)) {
  2164. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2165. }
  2166. // 获取动漫的角色信息(包含参考图)
  2167. $anime = DB::table('mp_animes')
  2168. ->where('id', $anime_id)
  2169. ->select('roles', 'scenes')
  2170. ->first();
  2171. if (!$anime || !$anime->roles) {
  2172. Utils::throwError('20003:未找到角色信息');
  2173. }
  2174. $roles = json_decode($anime->roles, true);
  2175. if (!$roles) {
  2176. Utils::throwError('20003:角色信息格式错误');
  2177. }
  2178. // 构建角色名称到参考图的映射
  2179. $role_map = [];
  2180. foreach ($roles as $role) {
  2181. $role_name = getProp($role, 'role');
  2182. $role_url = getProp($role, 'url');
  2183. if (!empty($role_name) && !empty($role_url)) {
  2184. $role_map[$role_name] = $role_url;
  2185. }
  2186. }
  2187. $scenes = json_decode($anime->scenes, true);
  2188. if (!$scenes) {
  2189. Utils::throwError('20003:角色信息格式错误');
  2190. }
  2191. // 构建角色名称到参考图的映射
  2192. $scene_map = [];
  2193. foreach ($scenes as $scene) {
  2194. $scene_name = getProp($scene, 'scene');
  2195. $scene_url = getProp($scene, 'url');
  2196. if (!empty($scene_name) && !empty($scene_url)) {
  2197. $scene_map[$scene_name] = $scene_url;
  2198. }
  2199. }
  2200. $segment_id = $segment->segment_id;
  2201. $original_segment_content = $segment->segment_content;
  2202. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2203. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2204. if (empty($final_segment_content)) {
  2205. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2206. }
  2207. try {
  2208. $dubTaskId = 0;
  2209. DB::beginTransaction();
  2210. $new_segment_number = $segment_number + 1;
  2211. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2212. // 分镜剧本数组
  2213. $insert_data = [
  2214. 'anime_id' => $anime_id,
  2215. 'episode_id' => $episode_id,
  2216. 'episode_number' => $episode_number,
  2217. 'act_number' => getProp($segment, 'act_number'),
  2218. 'act_title' => getProp($segment, 'act_title'),
  2219. 'segment_id' => $segment_id,
  2220. 'segment_number' => $new_segment_number,
  2221. 'segment_content' => $final_segment_content,
  2222. 'img_url' => $img_url,
  2223. 'video_url' => $video_url,
  2224. 'created_at' => date('Y-m-d H:i:s'),
  2225. 'updated_at' => date('Y-m-d H:i:s')
  2226. ];
  2227. // 更新分镜剧本信息
  2228. $this->handleSegmentContent($insert_data);
  2229. // 如果有对话内容,创建视频配音合成任务
  2230. $dialogue = getProp($insert_data, 'dialogue');
  2231. if (!empty($dialogue)) {
  2232. $now = date('Y-m-d H:i:s');
  2233. $generate_json = [
  2234. 'text' => $dialogue,
  2235. 'role' => getProp($insert_data, 'voice_actor'),
  2236. 'voice_type' => getProp($insert_data, 'voice_type'),
  2237. 'voice_name' => getProp($insert_data, 'voice_name'),
  2238. 'emotion' => getProp($insert_data, 'emotion'),
  2239. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2240. 'gender' => getProp($insert_data, 'gender'),
  2241. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2242. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2243. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2244. 'pitch' => getProp($insert_data, 'pitch', 0),
  2245. ];
  2246. // 插入视频配音合成任务
  2247. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2248. 'alias_segment_id' => $segment_id,
  2249. 'generate_status' => '执行中',
  2250. 'audio_url' => '',
  2251. 'generate_json' => json_encode($generate_json, 256),
  2252. 'created_at' => $now,
  2253. 'updated_at' => $now,
  2254. ]);
  2255. if (!$dubTaskId) {
  2256. Utils::throwError('20003:创建配音任务失败!');
  2257. }
  2258. $insert_data['audio_url'] = '';
  2259. } else {
  2260. // dialogue为空时,直接写入默认音频信息
  2261. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2262. $insert_data['audio_duration'] = 2.0;
  2263. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2264. }
  2265. // 如果没有上传图片则使用当前描述进行生成
  2266. if (!$img_url) {
  2267. // 解析分镜内容,提取画面描述作为主要提示词
  2268. $prompt = $final_segment_content;
  2269. $ref_img_urls = [];
  2270. // 分镜场景
  2271. $scene = getProp($insert_data, 'scene');
  2272. if ($scene) {
  2273. $matched_scene = '';
  2274. if (isset($scene_map[$scene])) {
  2275. $img_index = count($ref_img_urls) + 1;
  2276. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2277. $ref_img_urls[] = $scene_map[$scene];
  2278. $matched_scene = $scene;
  2279. }
  2280. $update_data['scene'] = $scene;
  2281. }
  2282. // 分镜角色
  2283. $characters = getProp($insert_data, 'characters');
  2284. if ($characters) {
  2285. $update_data['characters'] = $characters;
  2286. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2287. $characters = explode(',', $characters);
  2288. // 从分镜内容中提取涉及的角色
  2289. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2290. // 获取匹配角色的参考图
  2291. foreach ($segment_characters as $character) {
  2292. if (isset($role_map[$character])) {
  2293. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2294. $img_index = count($ref_img_urls) + 1;
  2295. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2296. $ref_img_urls[] = $role_map[$character];
  2297. }
  2298. }
  2299. }
  2300. // 如果没有找到匹配的角色参考图,不使用参考图
  2301. if (empty($ref_img_urls)) {
  2302. $ref_img_urls = [];
  2303. }
  2304. // 准备生成任务参数
  2305. $params = [
  2306. 'alias_segment_id' => $segment_id,
  2307. 'prompt' => $prompt,
  2308. 'ref_img_urls' => $ref_img_urls,
  2309. 'width' => $width,
  2310. 'height' => $height,
  2311. ];
  2312. // 调用AI图片生成服务
  2313. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2314. $task_id = $task->id;
  2315. // $task_id = 'whatever';
  2316. if (!$task_id) {
  2317. Utils::throwError('20003:创建生成任务失败!');
  2318. }
  2319. $insert_data['pic_task_status'] = '生成中';
  2320. $insert_data['pic_task_id'] = $task_id;
  2321. }
  2322. // 先更新序号
  2323. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2324. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2325. if (!$boolen) {
  2326. Utils::throwError('20003:新增分镜失败!');
  2327. }
  2328. // 如果是第一集的首帧图片,则存入待更新数组
  2329. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2330. Redis::sadd('anime_first_frame_urls', $segment_id);
  2331. }
  2332. if ($dubTaskId) {
  2333. // 请求远程服务器执行生成
  2334. $client = new Client(['timeout' => 300, 'verify' => false]);
  2335. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2336. $response = $result->getBody()->getContents();
  2337. $response_arr = json_decode($response, true);
  2338. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2339. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2340. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2341. Utils::throwError('20003:火山生成音频失败');
  2342. }
  2343. }
  2344. } catch (\Exception $e) {
  2345. DB::rollBack();
  2346. Utils::throwError('20003:'.$e->getMessage());
  2347. }
  2348. DB::commit();
  2349. // 创建任务之后先暂停10s等待异步任务完成
  2350. sleep(10);
  2351. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2352. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2353. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2354. $segment = $segment ? (array)$segment : [];
  2355. return $segment;
  2356. }
  2357. public function copySegment($data) {
  2358. $segment_id = getProp($data, 'segment_id');
  2359. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2360. if (!$segment) Utils::throwError('20003:请选择分镜');
  2361. $anime_id = getProp($segment, 'anime_id');
  2362. $episode_id = getProp($segment, 'episode_id');
  2363. $episode_number = getProp($segment, 'episode_number');
  2364. $segment_number = getProp($segment, 'segment_number');
  2365. $new_segment_id = 0;
  2366. try {
  2367. DB::beginTransaction();
  2368. $segment = (array)$segment;
  2369. unset($segment['id']);
  2370. $segment['segment_number'] += 1;
  2371. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2372. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2373. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2374. // 更新其他分镜序号
  2375. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2376. // 复制分镜
  2377. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2378. if (!$id) {
  2379. Utils::throwError('20003:复制分镜失败');
  2380. }
  2381. }catch (\Exception $e) {
  2382. DB::rollBack();
  2383. Utils::throwError('20003:'.$e->getMessage());
  2384. }
  2385. DB::commit();
  2386. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2387. $segment = $segment ? (array)$segment : [];
  2388. return $segment;
  2389. }
  2390. public function moveSegment($data) {
  2391. $segment_id = getProp($data, 'segment_id');
  2392. $target_segment_id = getProp($data, 'target_segment_id');
  2393. // 获取源分镜信息
  2394. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2395. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2396. // 获取目标分镜信息
  2397. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2398. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2399. $anime_id = getProp($source_segment, 'anime_id');
  2400. $episode_id = getProp($source_segment, 'episode_id');
  2401. $episode_number = getProp($source_segment, 'episode_number');
  2402. $source_segment_number = getProp($source_segment, 'segment_number');
  2403. $target_segment_number = getProp($target_segment, 'segment_number');
  2404. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2405. $target_anime_id = getProp($target_segment, 'anime_id');
  2406. $target_episode_number = getProp($target_segment, 'episode_number');
  2407. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2408. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2409. }
  2410. // 如果源分镜和目标分镜相同,无需移动
  2411. if ($source_segment_number == $target_segment_number) {
  2412. return true;
  2413. }
  2414. try {
  2415. DB::beginTransaction();
  2416. if ($source_segment_number < $target_segment_number) {
  2417. // 向后移动:源分镜移动到目标分镜之后
  2418. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2419. DB::table('mp_episode_segments')
  2420. ->where('anime_id', $anime_id)
  2421. ->where('episode_id', $episode_id)
  2422. ->where('segment_number', '>', $source_segment_number)
  2423. ->where('segment_number', '<=', $target_segment_number)
  2424. ->decrement('segment_number');
  2425. // 2. 将源分镜移动到目标分镜之后
  2426. $new_segment_number = $target_segment_number;
  2427. } else {
  2428. // 向前移动:源分镜移动到目标分镜之后
  2429. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2430. DB::table('mp_episode_segments')
  2431. ->where('anime_id', $anime_id)
  2432. ->where('episode_id', $episode_id)
  2433. ->where('segment_number', '>', $target_segment_number)
  2434. ->where('segment_number', '<', $source_segment_number)
  2435. ->increment('segment_number');
  2436. // 2. 将源分镜移动到目标分镜之后
  2437. $new_segment_number = $target_segment_number + 1;
  2438. }
  2439. // 3. 更新源分镜的序号
  2440. $update_result = DB::table('mp_episode_segments')
  2441. ->where('segment_id', $segment_id)
  2442. ->update([
  2443. 'segment_number' => $new_segment_number,
  2444. 'updated_at' => date('Y-m-d H:i:s')
  2445. ]);
  2446. if (!$update_result) {
  2447. Utils::throwError('20003:更新分镜序号失败');
  2448. }
  2449. DB::commit();
  2450. return true;
  2451. } catch (\Exception $e) {
  2452. DB::rollBack();
  2453. Utils::throwError('20003:' . $e->getMessage());
  2454. }
  2455. }
  2456. public function delSegment($data) {
  2457. $segment_id = getProp($data, 'segment_id');
  2458. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2459. if (!$segment) Utils::throwError('20003:请选择分镜');
  2460. $anime_id = getProp($segment, 'anime_id');
  2461. $episode_id = getProp($segment, 'episode_id');
  2462. $episode_number = getProp($segment, 'episode_number');
  2463. $segment_number = getProp($segment, 'segment_number');
  2464. try {
  2465. DB::beginTransaction();
  2466. // 删除分镜
  2467. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2468. if (!$boolen) {
  2469. Utils::throwError('20003:删除分镜失败');
  2470. }
  2471. // 更新其他分镜序号
  2472. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2473. }catch (\Exception $e) {
  2474. DB::rollBack();
  2475. Utils::throwError('20003:'.$e->getMessage());
  2476. }
  2477. DB::commit();
  2478. return true;
  2479. }
  2480. public function applySegment($data) {
  2481. $segment_id = getProp($data, 'segment_id');
  2482. $url = getProp($data, 'url');
  2483. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2484. if (!$url) Utils::throwError('20003:URL不能为空');
  2485. // 获取URL的文件扩展名
  2486. $urlPath = parse_url($url, PHP_URL_PATH);
  2487. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2488. // 定义图片和视频的扩展名
  2489. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2490. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2491. // 判断是图片还是视频
  2492. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2493. if (in_array($extension, $imageExtensions)) {
  2494. // 图片类型
  2495. $updateData['img_url'] = $url;
  2496. $updateData['current_type'] = 1;
  2497. } elseif (in_array($extension, $videoExtensions)) {
  2498. // 视频类型
  2499. $updateData['video_url'] = $url;
  2500. $updateData['current_type'] = 2;
  2501. } else {
  2502. Utils::throwError('20003:不支持的文件类型');
  2503. }
  2504. // 更新分镜表
  2505. $result = DB::table('mp_episode_segments')
  2506. ->where('segment_id', $segment_id)
  2507. ->update($updateData);
  2508. if (!$result) {
  2509. Utils::throwError('20003:更新分镜失败');
  2510. }
  2511. return true;
  2512. }
  2513. public function segmentHistory($data) {
  2514. $segment_id = getProp($data, 'segment_id');
  2515. // 获取历史图片
  2516. $pics = [];
  2517. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2518. foreach($pic_history as $task) {
  2519. $result_url = getProp($task, 'result_url');
  2520. if (is_json($result_url)) {
  2521. $pics = array_merge($pics, json_decode($result_url, true));
  2522. }else {
  2523. $pics[] = $result_url;
  2524. }
  2525. }
  2526. // 获取历史视频
  2527. $videos = [];
  2528. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2529. foreach($video_history as $task) {
  2530. $result_url = getProp($task, 'result_url');
  2531. if (is_json($result_url)) {
  2532. $videos = array_merge($videos, json_decode($result_url, true));
  2533. }else {
  2534. $videos[] = $result_url;
  2535. }
  2536. }
  2537. return compact('pics', 'videos');
  2538. }
  2539. public function addAct($data) {
  2540. $prev_act_id = getProp($data, 'prev_act_id');
  2541. $act_title = getProp($data, 'act_title', '');
  2542. $act_content = getProp($data, 'act_content', '');
  2543. $act_duration = getProp($data, 'act_duration', 5);
  2544. $video_url = getProp($data, 'video_url');
  2545. // 根据prev_act_id获取记录
  2546. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2547. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2548. $anime_id = getProp($prev_segment, 'anime_id');
  2549. $episode_id = getProp($prev_segment, 'episode_id');
  2550. $episode_number = getProp($prev_segment, 'episode_number');
  2551. $prev_act_number = getProp($prev_segment, 'act_number');
  2552. // 获取新的act_number
  2553. $new_act_number = $prev_act_number + 1;
  2554. try {
  2555. DB::beginTransaction();
  2556. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2557. DB::table('mp_episode_segments')
  2558. ->where('anime_id', $anime_id)
  2559. ->where('episode_id', $episode_id)
  2560. ->where('act_number', '>', $prev_act_number)
  2561. ->increment('act_number');
  2562. // 插入新片段记录
  2563. $insert_data = [
  2564. 'anime_id' => $anime_id,
  2565. 'episode_id' => $episode_id,
  2566. 'episode_number' => $episode_number,
  2567. 'act_number' => $new_act_number,
  2568. 'created_at' => date('Y-m-d H:i:s'),
  2569. 'updated_at' => date('Y-m-d H:i:s')
  2570. ];
  2571. if ($act_title) {
  2572. $insert_data['act_title'] = $act_title;
  2573. }
  2574. if ($act_content) {
  2575. $insert_data['act_content'] = $act_content;
  2576. }
  2577. if ($act_duration) {
  2578. $insert_data['act_duration'] = $act_duration;
  2579. }
  2580. if ($video_url) {
  2581. $insert_data['origin_video_url'] = $video_url;
  2582. $insert_data['current_type'] = 2;
  2583. $compressed_video_url = compressVideo($video_url);
  2584. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2585. }
  2586. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2587. if (!$id) {
  2588. Utils::throwError('20003:新增片段失败!');
  2589. }
  2590. DB::commit();
  2591. }catch (\Exception $e) {
  2592. DB::rollBack();
  2593. Utils::throwError('20003:'.$e->getMessage());
  2594. }
  2595. $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();
  2596. $segment = $segment ? (array)$segment : [];
  2597. return $segment;
  2598. }
  2599. public function editAct($data) {
  2600. $act_id = getProp($data, 'act_id');
  2601. $act_content = getProp($data, 'act_content');
  2602. $act_duration = getProp($data, 'act_duration');
  2603. $act_title = getProp($data, 'act_title');
  2604. $image_url = getProp($data, 'image_url');
  2605. $video_url = getProp($data, 'video_url');
  2606. // 参数验证
  2607. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2608. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2609. $segment = DB::table('mp_episode_segments')
  2610. ->where('id', $act_id)
  2611. ->first();
  2612. if (!$segment) Utils::throwError('20003:该片段不存在');
  2613. try {
  2614. DB::beginTransaction();
  2615. // 准备更新数据
  2616. $update_data = [
  2617. 'updated_at' => date('Y-m-d H:i:s')
  2618. ];
  2619. // 更新act相关字段
  2620. if (!empty($act_content)) {
  2621. $update_data['act_show_content'] = $act_content;
  2622. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2623. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2624. $shot_counter = 0;
  2625. $update_data['act_show_content'] = preg_replace_callback(
  2626. '/【(?:镜头|分镜)(\d+)】/u',
  2627. function($matches) use (&$shot_counter) {
  2628. $shot_counter++;
  2629. return '【镜头' . $shot_counter . '】';
  2630. },
  2631. $update_data['act_show_content']
  2632. );
  2633. }
  2634. if (!empty($act_duration)) {
  2635. $update_data['act_duration'] = $act_duration;
  2636. }
  2637. if (!empty($act_title)) {
  2638. $update_data['act_title'] = $act_title;
  2639. }
  2640. // 处理图片上传
  2641. if ($image_url) {
  2642. $update_data['img_url'] = $image_url;
  2643. $update_data['current_type'] = 1;
  2644. // 同时写入一个图片生成任务记录
  2645. if ($act_id) {
  2646. $pic_task = [
  2647. 'alias_act_id' => $act_id,
  2648. 'ref_img_url' => json_encode([]),
  2649. 'status' => 'success',
  2650. 'result_url' => json_encode([$image_url], 256),
  2651. 'model' => '',
  2652. 'created_at' => date('Y-m-d H:i:s'),
  2653. 'updated_at' => date('Y-m-d H:i:s'),
  2654. ];
  2655. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2656. }
  2657. }
  2658. // 处理视频上传
  2659. if ($video_url) {
  2660. $update_data['origin_video_url'] = $video_url;
  2661. $compressed_video_url = compressVideo($video_url);
  2662. $update_data['current_type'] = 2;
  2663. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2664. // 同时写入一个视频生成任务记录
  2665. if ($act_id) {
  2666. $video_task = [
  2667. 'alias_act_id' => $act_id,
  2668. 'status' => 'success',
  2669. 'result_url' => $update_data['origin_video_url'],
  2670. 'compressed_url' => $update_data['video_url'],
  2671. 'created_at' => date('Y-m-d H:i:s'),
  2672. 'updated_at' => date('Y-m-d H:i:s'),
  2673. ];
  2674. DB::table('mp_generate_video_tasks')->insert($video_task);
  2675. }
  2676. }
  2677. // 更新片段信息
  2678. $result = DB::table('mp_episode_segments')
  2679. ->where('id', $act_id)
  2680. ->update($update_data);
  2681. if ($result === false) {
  2682. Utils::throwError('20003:更新片段失败');
  2683. }
  2684. DB::commit();
  2685. // 返回新复制的记录
  2686. $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();
  2687. $new_segment = (array)$new_segment;
  2688. return $new_segment;
  2689. } catch (\Exception $e) {
  2690. DB::rollBack();
  2691. dLog('anime')->error('更新片段失败', [
  2692. 'act_id' => $act_id,
  2693. 'error' => $e->getMessage()
  2694. ]);
  2695. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2696. }
  2697. }
  2698. public function copyAct($data) {
  2699. $act_id = getProp($data, 'act_id');
  2700. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2701. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2702. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2703. $anime_id = getProp($source_segment, 'anime_id');
  2704. $episode_id = getProp($source_segment, 'episode_id');
  2705. $episode_number = getProp($source_segment, 'episode_number');
  2706. $act_number = getProp($source_segment, 'act_number');
  2707. try {
  2708. DB::beginTransaction();
  2709. // 新act的编号
  2710. $new_act_number = $act_number + 1;
  2711. // 更新后续所有act的act_number
  2712. DB::table('mp_episode_segments')
  2713. ->where('anime_id', $anime_id)
  2714. ->where('episode_id', $episode_id)
  2715. ->where('act_number', '>', $act_number)
  2716. ->increment('act_number');
  2717. // 复制该片段记录
  2718. $segment_data = (array)$source_segment;
  2719. unset($segment_data['id']);
  2720. $segment_data['video_url'] = '';
  2721. $segment_data['video_task_id'] = '';
  2722. $segment_data['video_task_status'] = '';
  2723. $segment_data['act_number'] = $new_act_number;
  2724. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2725. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2726. if (!$id) {
  2727. Utils::throwError('20003:复制片段失败');
  2728. }
  2729. DB::commit();
  2730. }catch (\Exception $e) {
  2731. DB::rollBack();
  2732. Utils::throwError('20003:'.$e->getMessage());
  2733. }
  2734. // 返回新复制的记录
  2735. $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();
  2736. $new_segment = $new_segment ? (array)$new_segment : [];
  2737. $new_segment['act_id'] = $id;
  2738. return $new_segment;
  2739. }
  2740. public function moveAct($data) {
  2741. $act_id = getProp($data, 'act_id');
  2742. $target_act_id = getProp($data, 'target_act_id');
  2743. // 获取源片段信息
  2744. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2745. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2746. // 获取目标片段信息
  2747. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2748. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2749. $anime_id = getProp($source_segment, 'anime_id');
  2750. $episode_id = getProp($source_segment, 'episode_id');
  2751. $source_act_number = getProp($source_segment, 'act_number');
  2752. $target_act_number = getProp($target_segment, 'act_number');
  2753. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2754. $target_anime_id = getProp($target_segment, 'anime_id');
  2755. $target_episode_id = getProp($target_segment, 'episode_id');
  2756. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2757. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2758. }
  2759. // 如果源片段和目标片段相同,无需移动
  2760. if ($source_act_number == $target_act_number) {
  2761. return true;
  2762. }
  2763. try {
  2764. DB::beginTransaction();
  2765. if ($source_act_number < $target_act_number) {
  2766. // 向后移动:源片段移动到目标片段之后
  2767. // 1. 将源片段和目标片段之间的所有片段编号减1
  2768. DB::table('mp_episode_segments')
  2769. ->where('anime_id', $anime_id)
  2770. ->where('episode_id', $episode_id)
  2771. ->where('act_number', '>', $source_act_number)
  2772. ->where('act_number', '<=', $target_act_number)
  2773. ->decrement('act_number');
  2774. // 2. 将源片段移动到目标片段之后
  2775. $new_act_number = $target_act_number;
  2776. } else {
  2777. // 向前移动:源片段移动到目标片段之后
  2778. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2779. DB::table('mp_episode_segments')
  2780. ->where('anime_id', $anime_id)
  2781. ->where('episode_id', $episode_id)
  2782. ->where('act_number', '>', $target_act_number)
  2783. ->where('act_number', '<', $source_act_number)
  2784. ->increment('act_number');
  2785. // 2. 将源片段移动到目标片段之后
  2786. $new_act_number = $target_act_number + 1;
  2787. }
  2788. // 3. 更新源片段的编号
  2789. $update_result = DB::table('mp_episode_segments')
  2790. ->where('id', $act_id)
  2791. ->update([
  2792. 'act_number' => $new_act_number,
  2793. 'updated_at' => date('Y-m-d H:i:s')
  2794. ]);
  2795. if (!$update_result) {
  2796. Utils::throwError('20003:更新片段编号失败');
  2797. }
  2798. DB::commit();
  2799. return true;
  2800. } catch (\Exception $e) {
  2801. DB::rollBack();
  2802. Utils::throwError('20003:' . $e->getMessage());
  2803. }
  2804. }
  2805. public function delAct($data) {
  2806. $act_id = getProp($data, 'act_id');
  2807. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2808. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2809. if (!$segment) Utils::throwError('20003:请选择片段');
  2810. $anime_id = getProp($segment, 'anime_id');
  2811. $episode_id = getProp($segment, 'episode_id');
  2812. $act_number = getProp($segment, 'act_number');
  2813. try {
  2814. DB::beginTransaction();
  2815. // 删除该片段记录
  2816. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2817. if (!$deleted) {
  2818. Utils::throwError('20003:删除片段失败');
  2819. }
  2820. // 更新后续act的编号
  2821. DB::table('mp_episode_segments')
  2822. ->where('anime_id', $anime_id)
  2823. ->where('episode_id', $episode_id)
  2824. ->where('act_number', '>', $act_number)
  2825. ->decrement('act_number');
  2826. DB::commit();
  2827. }catch (\Exception $e) {
  2828. DB::rollBack();
  2829. Utils::throwError('20003:'.$e->getMessage());
  2830. }
  2831. return true;
  2832. }
  2833. public function applyAct($data) {
  2834. $act_id = getProp($data, 'act_id');
  2835. $url = getProp($data, 'url');
  2836. if (!$act_id) Utils::throwError('20003:请选择片段');
  2837. if (!$url) Utils::throwError('20003:URL不能为空');
  2838. // 获取URL的文件扩展名
  2839. $urlPath = parse_url($url, PHP_URL_PATH);
  2840. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2841. // 定义图片和视频的扩展名
  2842. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2843. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2844. // 判断是图片还是视频
  2845. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2846. if (in_array($extension, $imageExtensions)) {
  2847. // 图片类型
  2848. $updateData['img_url'] = $url;
  2849. $updateData['current_type'] = 1;
  2850. } elseif (in_array($extension, $videoExtensions)) {
  2851. // 视频类型
  2852. $updateData['video_url'] = $url;
  2853. $updateData['current_type'] = 2;
  2854. } else {
  2855. Utils::throwError('20003:不支持的文件类型');
  2856. }
  2857. // 更新片段记录(全能模式下每个act只有一条记录)
  2858. $result = DB::table('mp_episode_segments')
  2859. ->where('id', $act_id)
  2860. ->update($updateData);
  2861. if (!$result) {
  2862. Utils::throwError('20003:更新片段失败');
  2863. }
  2864. return true;
  2865. }
  2866. public function actChatHistory($data) {
  2867. $act_id = getProp($data, 'act_id');
  2868. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2869. $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');
  2870. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2871. $value = (array)$value;
  2872. $value['created_at'] = transDate($value['created_at']);
  2873. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2874. else $value['reference_images'] = [];
  2875. return $value;
  2876. })->toArray();
  2877. // 获取历史图片
  2878. $url = [];
  2879. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2880. foreach($pic_history as $task) {
  2881. $result_url = getProp($task, 'result_url');
  2882. if (is_json($result_url)) {
  2883. $url = array_merge($url, json_decode($result_url, true));
  2884. }else {
  2885. $url[] = $result_url;
  2886. }
  2887. }
  2888. // 获取历史视频
  2889. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2890. foreach($video_history as $task) {
  2891. $result_url = getProp($task, 'result_url');
  2892. if (is_json($result_url)) {
  2893. $url = array_merge($url, json_decode($result_url, true));
  2894. }else {
  2895. $url[] = $result_url;
  2896. }
  2897. }
  2898. // 获取资产库
  2899. $products = [];
  2900. // 通过act_id查询片段信息获取episode_id
  2901. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2902. if ($segment) {
  2903. $episode_id = getProp($segment, 'episode_id');
  2904. // 查询剧集信息获取roles、scenes和extra_products
  2905. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2906. if ($episode) {
  2907. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2908. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2909. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2910. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2911. // 先合并roles、scenes和props
  2912. // 处理角色数组
  2913. foreach ($roles as $role) {
  2914. $product = $role;
  2915. // 将role字段重命名为product_name
  2916. if (is_array($product) && !empty($product['role'] ?? null)) {
  2917. $product['product_name'] = $product['role'];
  2918. unset($product['role']);
  2919. $product['product'] = 1; // 标记类型为角色
  2920. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2921. }
  2922. }
  2923. // 处理场景数组
  2924. foreach ($scenes as $scene) {
  2925. $product = $scene;
  2926. // 将scene字段重命名为product_name
  2927. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2928. $product['product_name'] = $product['scene'];
  2929. unset($product['scene']);
  2930. $product['product'] = 2; // 标记类型为场景
  2931. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2932. }
  2933. }
  2934. // 处理道具数组
  2935. foreach ($props as $prop) {
  2936. $product = $prop;
  2937. // 将prop字段重命名为product_name
  2938. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2939. $product['product_name'] = $product['prop'];
  2940. unset($product['prop']);
  2941. $product['product'] = 3; // 标记类型为道具
  2942. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2943. }
  2944. }
  2945. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2946. foreach ($extra_products as $extra_product) {
  2947. $product_name = getProp($extra_product, 'product_name');
  2948. if ($product_name) {
  2949. $products[$product_name] = $extra_product; // 覆盖同名数据
  2950. }
  2951. }
  2952. // 重新索引数组(去除key)
  2953. $products = array_values($products);
  2954. }
  2955. }
  2956. // 获取执行中的任务
  2957. $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) {
  2958. $value = (array)$value;
  2959. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2960. else $value['ref_image_url'] = [];
  2961. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2962. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2963. if (!empty($value['prompt'])) {
  2964. $prompt = $value['prompt'];
  2965. // 查找第一个【镜头】的位置
  2966. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2967. // 从【镜头】开始截取
  2968. $prompt = substr($prompt, $matches[0][1]);
  2969. }
  2970. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2971. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2972. $value['prompt'] = $prompt;
  2973. }
  2974. return $value;
  2975. })->toArray();
  2976. return compact('chat', 'url', 'products', 'tasks');
  2977. }
  2978. public function applyAudioData($data) {
  2979. $segment_id = getProp($data, 'segment_id');
  2980. $global_data = getProp($data, 'global_data');
  2981. $segment_data = getProp($data, 'segment_data');
  2982. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2983. $global_data = is_array($global_data) ? $global_data : [];
  2984. $segment_data = is_array($segment_data) ? $segment_data : [];
  2985. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2986. $dialogue_item = null;
  2987. foreach ($global_data as $key => $item) {
  2988. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2989. $dialogue_item = $item;
  2990. unset($global_data[$key]);
  2991. break;
  2992. }
  2993. }
  2994. if ($dialogue_item) {
  2995. $segment_data[] = $dialogue_item;
  2996. }
  2997. // 特殊参数: audio_url,audio_duration,subtitle_info
  2998. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2999. // 如果不是全部存在,则仍需创建音频任务
  3000. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3001. $special_update_data = [];
  3002. $has_all_special_params = false;
  3003. // 从segment_data中提取特殊参数
  3004. $filtered_segment_data = [];
  3005. foreach ($segment_data as $item) {
  3006. $field_name = trim((string)getProp($item, 'name'));
  3007. if (in_array($field_name, $special_fields)) {
  3008. $special_update_data[$field_name] = getProp($item, 'value');
  3009. } else {
  3010. // 非特殊参数保留,继续后续处理
  3011. $filtered_segment_data[] = $item;
  3012. }
  3013. }
  3014. // 检查是否三个特殊参数都存在
  3015. if (count($special_update_data) === 3 &&
  3016. isset($special_update_data['audio_url']) &&
  3017. isset($special_update_data['audio_duration']) &&
  3018. isset($special_update_data['subtitle_info'])) {
  3019. $has_all_special_params = true;
  3020. // 立即更新到当前分镜
  3021. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3022. DB::table('mp_episode_segments')
  3023. ->where('segment_id', $segment_id)
  3024. ->update($special_update_data);
  3025. }
  3026. // 使用过滤后的segment_data继续处理其他参数
  3027. $segment_data = $filtered_segment_data;
  3028. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3029. $global_update_data = [];
  3030. $segment_update_data = [];
  3031. $global_voice_type = '';
  3032. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3033. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3034. $episode_id = getProp($target_segment, 'episode_id');
  3035. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3036. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3037. if (!$episode) Utils::throwError('20003:分集不存在');
  3038. foreach ($global_data as $item) {
  3039. $field_name = trim((string)getProp($item, 'name'));
  3040. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3041. continue;
  3042. }
  3043. $global_update_data[$field_name] = getProp($item, 'value');
  3044. if ($field_name === 'voice_type') {
  3045. $global_voice_type = trim((string)getProp($item, 'value'));
  3046. }
  3047. }
  3048. foreach ($segment_data as $item) {
  3049. $field_name = trim((string)getProp($item, 'name'));
  3050. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3051. continue;
  3052. }
  3053. $segment_update_data[$field_name] = getProp($item, 'value');
  3054. }
  3055. if ($global_voice_type) {
  3056. $timbre_info = DB::table('mp_timbres')
  3057. ->where('timbre_type', $global_voice_type)
  3058. ->select('audio_url', 'timbre_name')
  3059. ->first();
  3060. if ($timbre_info) {
  3061. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3062. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3063. }
  3064. }
  3065. try {
  3066. DB::beginTransaction();
  3067. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3068. $segment_ids_to_create_task = [];
  3069. $segments_data = [];
  3070. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3071. if (!empty($global_update_data)) {
  3072. // 如果角色不存在,则只更新当前分镜
  3073. if (!$target_voice_actor) {
  3074. // 只处理当前分镜
  3075. $affected_segments = DB::table('mp_episode_segments')
  3076. ->where('segment_id', $segment_id)
  3077. ->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')
  3078. ->get();
  3079. } else {
  3080. // 获取该角色的所有分镜
  3081. $affected_segments = DB::table('mp_episode_segments')
  3082. ->where('episode_id', $episode_id)
  3083. ->where('voice_actor', $target_voice_actor)
  3084. ->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')
  3085. ->get();
  3086. }
  3087. foreach ($affected_segments as $seg) {
  3088. $seg = (array)$seg;
  3089. $sid = getProp($seg, 'segment_id');
  3090. // 检查参数是否发生变化
  3091. $has_changed = false;
  3092. foreach ($global_update_data as $field => $new_value) {
  3093. $old_value = getProp($seg, $field);
  3094. if ($old_value != $new_value) {
  3095. $has_changed = true;
  3096. break;
  3097. }
  3098. }
  3099. if ($has_changed) {
  3100. $segment_ids_to_create_task[] = $sid;
  3101. $segments_data[$sid] = $seg;
  3102. }
  3103. }
  3104. // 只有在有变化的分镜时才更新
  3105. if (!empty($segment_ids_to_create_task)) {
  3106. $global_segment_update_data = $global_update_data;
  3107. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3108. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3109. DB::table('mp_episode_segments')
  3110. ->where('episode_id', $episode_id)
  3111. ->where('voice_actor', $target_voice_actor)
  3112. ->whereIn('segment_id', $segment_ids_to_create_task)
  3113. ->update($global_segment_update_data);
  3114. }
  3115. if ($global_voice_type) {
  3116. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3117. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3118. $roles_updated = false;
  3119. foreach ($episode_roles as &$role) {
  3120. // 通过 role 字段匹配角色名,而不是 voice_name
  3121. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3122. continue;
  3123. }
  3124. $role['voice_type'] = $global_voice_type;
  3125. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3126. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3127. $roles_updated = true;
  3128. }
  3129. unset($role);
  3130. if ($roles_updated) {
  3131. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3132. 'roles' => json_encode($episode_roles, 256),
  3133. 'updated_at' => date('Y-m-d H:i:s'),
  3134. ]);
  3135. }
  3136. }
  3137. }
  3138. // 如果有单个分镜更新,检查是否有变化
  3139. if (!empty($segment_update_data)) {
  3140. // 获取当前分镜数据
  3141. $current_segment = DB::table('mp_episode_segments')
  3142. ->where('segment_id', $segment_id)
  3143. ->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')
  3144. ->first();
  3145. if ($current_segment) {
  3146. $current_segment = (array)$current_segment;
  3147. // 检查参数是否发生变化
  3148. $has_changed = false;
  3149. foreach ($segment_update_data as $field => $new_value) {
  3150. $old_value = getProp($current_segment, $field);
  3151. if ($old_value != $new_value) {
  3152. $has_changed = true;
  3153. break;
  3154. }
  3155. }
  3156. if ($has_changed) {
  3157. // 如果该分镜还未在列表中,添加进去
  3158. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3159. $segment_ids_to_create_task[] = $segment_id;
  3160. $segments_data[$segment_id] = $current_segment;
  3161. }
  3162. // 更新分镜数据并清空音频URL
  3163. $segment_update_data['audio_url'] = '';
  3164. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3165. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3166. }
  3167. }
  3168. }
  3169. // 为所有有变化的分镜创建音频合成任务
  3170. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3171. if (!empty($segment_ids_to_create_task)) {
  3172. foreach ($segment_ids_to_create_task as $sid) {
  3173. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3174. if ($sid === $segment_id && $has_all_special_params) {
  3175. continue;
  3176. }
  3177. // 重新获取更新后的分镜数据
  3178. $updated_segment = DB::table('mp_episode_segments')
  3179. ->where('segment_id', $sid)
  3180. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3181. ->first();
  3182. if (!$updated_segment) continue;
  3183. $updated_segment = (array)$updated_segment;
  3184. // 检查dialogue是否为空
  3185. $dialogue = getProp($updated_segment, 'dialogue');
  3186. if (empty($dialogue)) {
  3187. // dialogue为空时,直接写入默认音频信息
  3188. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3189. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3190. 'audio_duration' => 2.0,
  3191. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3192. 'updated_at' => date('Y-m-d H:i:s')
  3193. ]);
  3194. continue;
  3195. }
  3196. $generate_json = [
  3197. 'text' => $dialogue,
  3198. 'role' => getProp($updated_segment, 'voice_actor'),
  3199. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3200. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3201. 'emotion' => getProp($updated_segment, 'emotion'),
  3202. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3203. 'gender' => getProp($updated_segment, 'gender'),
  3204. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3205. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3206. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3207. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3208. ];
  3209. // 插入视频配音合成任务
  3210. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3211. 'alias_segment_id' => $sid,
  3212. 'generate_status' => '执行中',
  3213. 'audio_url' => '',
  3214. 'generate_json' => json_encode($generate_json, 256),
  3215. 'created_at' => date('Y-m-d H:i:s'),
  3216. 'updated_at' => date('Y-m-d H:i:s'),
  3217. ]);
  3218. if (!$dubTaskId) {
  3219. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3220. continue;
  3221. }
  3222. // 将任务ID添加到Redis列表中
  3223. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3224. // 请求远程服务器执行生成
  3225. try {
  3226. sleep(1);
  3227. $client = new Client(['timeout' => 300, 'verify' => false]);
  3228. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3229. $response = $result->getBody()->getContents();
  3230. $response_arr = json_decode($response, true);
  3231. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3232. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3233. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3234. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3235. }
  3236. } catch (\Exception $e) {
  3237. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3238. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3239. }
  3240. }
  3241. }
  3242. DB::commit();
  3243. } catch (\Exception $e) {
  3244. DB::rollBack();
  3245. Utils::throwError('20003:'.$e->getMessage());
  3246. }
  3247. return true;
  3248. }
  3249. public function episodePicsInfo($data) {
  3250. $anime_id = getProp($data, 'anime_id');
  3251. $episode_id = getProp($data, 'episode_id');
  3252. // 参数验证
  3253. if (!$anime_id && !$episode_id) {
  3254. Utils::throwError('20003:请提供动漫ID或分集ID');
  3255. }
  3256. // 根据参数获取数据源
  3257. if ($episode_id) {
  3258. // 从剧集表获取
  3259. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3260. if (!$source) Utils::throwError('20003:该剧集不存在');
  3261. $table_name = 'mp_anime_episodes';
  3262. $id_field = 'id';
  3263. $id_value = $episode_id;
  3264. // 获取剧集的anime_id用于继承全局数据
  3265. $anime_id = getProp($source, 'anime_id');
  3266. } else {
  3267. // 从动漫表获取
  3268. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3269. if (!$source) Utils::throwError('20003:该动漫不存在');
  3270. $table_name = 'mp_animes';
  3271. $id_field = 'id';
  3272. $id_value = $anime_id;
  3273. }
  3274. $source = (array)$source;
  3275. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3276. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3277. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3278. // 如果是分集数据,需要处理继承和任务创建逻辑
  3279. if ($episode_id) {
  3280. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3281. }
  3282. // 返回生成器函数,用于 SSE 流式输出
  3283. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3284. $startTime = time();
  3285. $maxDuration = 600; // 10分钟超时
  3286. $checkInterval = 3; // 每3秒检查一次
  3287. // Redis 缓存键
  3288. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3289. // 生成当前数据的哈希值用于比较
  3290. $generateHash = function($roles, $scenes, $props) {
  3291. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3292. };
  3293. // 发送初始数据
  3294. $currentHash = $generateHash($roles, $scenes, $props);
  3295. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3296. echo "data: " . json_encode([
  3297. 'type' => 'init',
  3298. 'data' => [
  3299. 'roles' => $roles,
  3300. 'scenes' => $scenes,
  3301. 'props' => $props,
  3302. 'start_time' => $startTime
  3303. ]
  3304. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3305. if (ob_get_level() > 0) {
  3306. ob_flush();
  3307. }
  3308. flush();
  3309. // 持续轮询任务状态
  3310. while (time() - $startTime < $maxDuration) {
  3311. $hasProcessing = false;
  3312. $updated = false;
  3313. // 检查角色任务状态
  3314. foreach ($roles as $index => &$role) {
  3315. $task_id = getProp($role, 'task_id');
  3316. $task_status = getProp($role, 'task_status');
  3317. $existing_url = getProp($role, 'url');
  3318. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3319. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3320. $hasProcessing = ($task_status === 'processing');
  3321. // 查询任务状态
  3322. $task = DB::table('mp_generate_pic_tasks')
  3323. ->where('id', $task_id)
  3324. ->select('id', 'status', 'result_url', 'error_message')
  3325. ->first();
  3326. if ($task) {
  3327. $task = (array)$task;
  3328. $status = getProp($task, 'status');
  3329. // 如果任务完成或失败
  3330. if (in_array($status, ['success', 'failed'])) {
  3331. $role['task_status'] = $status;
  3332. if ($status === 'success') {
  3333. $result_url = getProp($task, 'result_url');
  3334. if ($result_url) {
  3335. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3336. if (is_array($result_urls) && !empty($result_urls[0])) {
  3337. $role['url'] = $result_urls[0];
  3338. }
  3339. }
  3340. }
  3341. $updated = true;
  3342. } else if ($status === 'processing') {
  3343. $hasProcessing = true;
  3344. }
  3345. }
  3346. }
  3347. }
  3348. // 检查场景任务状态
  3349. foreach ($scenes as $index => &$scene) {
  3350. $task_id = getProp($scene, 'task_id');
  3351. $task_status = getProp($scene, 'task_status');
  3352. $existing_url = getProp($scene, 'url');
  3353. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3354. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3355. $hasProcessing = ($task_status === 'processing');
  3356. // 查询任务状态
  3357. $task = DB::table('mp_generate_pic_tasks')
  3358. ->where('id', $task_id)
  3359. ->select('id', 'status', 'result_url', 'error_message')
  3360. ->first();
  3361. if ($task) {
  3362. $task = (array)$task;
  3363. $status = getProp($task, 'status');
  3364. // 如果任务完成或失败
  3365. if (in_array($status, ['success', 'failed'])) {
  3366. $scene['task_status'] = $status;
  3367. if ($status === 'success') {
  3368. $result_url = getProp($task, 'result_url');
  3369. if ($result_url) {
  3370. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3371. if (is_array($result_urls) && !empty($result_urls[0])) {
  3372. $scene['url'] = $result_urls[0];
  3373. }
  3374. }
  3375. }
  3376. $updated = true;
  3377. } else if ($status === 'processing') {
  3378. $hasProcessing = true;
  3379. }
  3380. }
  3381. }
  3382. }
  3383. // 检查道具任务状态
  3384. foreach ($props as $index => &$prop) {
  3385. $task_id = getProp($prop, 'task_id');
  3386. $task_status = getProp($prop, 'task_status');
  3387. $existing_url = getProp($prop, 'url');
  3388. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3389. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3390. $hasProcessing = ($task_status === 'processing');
  3391. // 查询任务状态
  3392. $task = DB::table('mp_generate_pic_tasks')
  3393. ->where('id', $task_id)
  3394. ->select('id', 'status', 'result_url', 'error_message')
  3395. ->first();
  3396. if ($task) {
  3397. $task = (array)$task;
  3398. $status = getProp($task, 'status');
  3399. // 如果任务完成或失败
  3400. if (in_array($status, ['success', 'failed'])) {
  3401. $prop['task_status'] = $status;
  3402. if ($status === 'success') {
  3403. $result_url = getProp($task, 'result_url');
  3404. if ($result_url) {
  3405. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3406. if (is_array($result_urls) && !empty($result_urls[0])) {
  3407. $prop['url'] = $result_urls[0];
  3408. }
  3409. }
  3410. }
  3411. $updated = true;
  3412. } else if ($status === 'processing') {
  3413. $hasProcessing = true;
  3414. }
  3415. }
  3416. }
  3417. }
  3418. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3419. if ($updated) {
  3420. $newHash = $generateHash($roles, $scenes, $props);
  3421. $cachedHash = Redis::get($cacheKey);
  3422. // 只有当数据真正变化时才更新数据库和发送事件
  3423. if ($newHash !== $cachedHash) {
  3424. try {
  3425. // 更新数据库
  3426. DB::table($table_name)->where($id_field, $id_value)->update([
  3427. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3428. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3429. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3430. 'updated_at' => date('Y-m-d H:i:s')
  3431. ]);
  3432. // 更新缓存
  3433. Redis::setex($cacheKey, 600, $newHash);
  3434. // 发送更新事件
  3435. echo "data: " . json_encode([
  3436. 'type' => 'update',
  3437. 'data' => [
  3438. 'roles' => $roles,
  3439. 'scenes' => $scenes,
  3440. 'props' => $props,
  3441. 'elapsed_time' => time() - $startTime
  3442. ]
  3443. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3444. if (ob_get_level() > 0) {
  3445. ob_flush();
  3446. }
  3447. flush();
  3448. } catch (\Exception $e) {
  3449. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3450. }
  3451. } else {
  3452. // 即使哈希相同,如果有URL更新也要发送事件
  3453. $hasUrlUpdate = false;
  3454. foreach ($roles as $role) {
  3455. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3456. $hasUrlUpdate = true;
  3457. break;
  3458. }
  3459. }
  3460. if (!$hasUrlUpdate) {
  3461. foreach ($scenes as $scene) {
  3462. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3463. $hasUrlUpdate = true;
  3464. break;
  3465. }
  3466. }
  3467. }
  3468. if (!$hasUrlUpdate) {
  3469. foreach ($props as $prop) {
  3470. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3471. $hasUrlUpdate = true;
  3472. break;
  3473. }
  3474. }
  3475. }
  3476. if ($hasUrlUpdate) {
  3477. // 强制更新数据库和发送事件
  3478. try {
  3479. DB::table($table_name)->where($id_field, $id_value)->update([
  3480. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3481. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3482. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3483. 'updated_at' => date('Y-m-d H:i:s')
  3484. ]);
  3485. // 更新缓存
  3486. Redis::setex($cacheKey, 600, $newHash);
  3487. // 发送更新事件
  3488. echo "data: " . json_encode([
  3489. 'type' => 'update',
  3490. 'data' => [
  3491. 'roles' => $roles,
  3492. 'scenes' => $scenes,
  3493. 'props' => $props,
  3494. 'elapsed_time' => time() - $startTime
  3495. ]
  3496. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3497. if (ob_get_level() > 0) {
  3498. ob_flush();
  3499. }
  3500. flush();
  3501. } catch (\Exception $e) {
  3502. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3503. }
  3504. }
  3505. }
  3506. }
  3507. // 如果所有任务都已完成,发送完成事件并退出
  3508. if (!$hasProcessing) {
  3509. // 查询数据库中的最终数据,确保返回最新的完整数据
  3510. try {
  3511. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3512. if ($finalSource) {
  3513. $finalSource = (array)$finalSource;
  3514. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3515. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3516. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3517. // 使用数据库中的最终数据
  3518. $roles = $finalRoles;
  3519. $scenes = $finalScenes;
  3520. $props = $finalProps;
  3521. }
  3522. } catch (\Exception $e) {
  3523. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3524. // 如果查询失败,继续使用内存中的数据
  3525. }
  3526. // 清理缓存
  3527. Redis::del($cacheKey);
  3528. echo "data: " . json_encode([
  3529. 'type' => 'completed',
  3530. 'data' => [
  3531. 'roles' => $roles,
  3532. 'scenes' => $scenes,
  3533. 'props' => $props,
  3534. 'total_time' => time() - $startTime
  3535. ]
  3536. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3537. if (ob_get_level() > 0) {
  3538. ob_flush();
  3539. }
  3540. flush();
  3541. break;
  3542. }
  3543. // 等待下次检查
  3544. sleep($checkInterval);
  3545. }
  3546. // 超时处理
  3547. if (time() - $startTime >= $maxDuration) {
  3548. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3549. try {
  3550. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3551. if ($finalSource) {
  3552. $finalSource = (array)$finalSource;
  3553. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3554. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3555. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3556. // 使用数据库中的最终数据
  3557. $roles = $finalRoles;
  3558. $scenes = $finalScenes;
  3559. $props = $finalProps;
  3560. }
  3561. } catch (\Exception $e) {
  3562. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3563. // 如果查询失败,继续使用内存中的数据
  3564. }
  3565. // 清理缓存
  3566. Redis::del($cacheKey);
  3567. echo "data: " . json_encode([
  3568. 'type' => 'timeout',
  3569. 'message' => '轮询超时,请刷新页面查看最新状态',
  3570. 'data' => [
  3571. 'roles' => $roles,
  3572. 'scenes' => $scenes,
  3573. 'props' => $props
  3574. ]
  3575. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3576. if (ob_get_level() > 0) {
  3577. ob_flush();
  3578. }
  3579. flush();
  3580. }
  3581. };
  3582. }
  3583. public function clipSegmentVideo($data) {
  3584. $segment_id = getProp($data, 'segment_id');
  3585. $video_time_point_start = getProp($data, 'video_time_point_start');
  3586. $video_time_point_end = getProp($data, 'video_time_point_end');
  3587. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3588. Utils::throwError('20003:参数异常');
  3589. }
  3590. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3591. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3592. }
  3593. $video_duration = $video_time_point_end - $video_time_point_start;
  3594. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3595. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3596. 'video_duration' => $video_duration,
  3597. 'video_time_point_start' => $video_time_point_start,
  3598. 'video_time_point_end' => $video_time_point_end,
  3599. 'updated_at' => date('Y-m-d H:i:s')
  3600. ]);
  3601. }
  3602. // 轮训获取图片任务结果
  3603. private function loopGetPicTaskResult($task_id) {
  3604. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3605. if (!$task) {
  3606. return '';
  3607. }
  3608. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3609. $model = getProp($task, 'model');
  3610. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3611. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3612. $isSyncModel = $isVolcModel || $isGptModel;
  3613. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3614. $start_count = 0;
  3615. $img_url = '';
  3616. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3617. sleep(3);
  3618. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3619. // 如果任务已经完成,直接返回结果
  3620. if ($task->status === 'success' && $task->result_url) {
  3621. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3622. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3623. }
  3624. // 如果任务已失败,返回空
  3625. if ($task->status === 'failed') {
  3626. return '';
  3627. }
  3628. if ($isSyncModel) continue;
  3629. // 查询任务状态
  3630. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3631. if ($statusInfo['status'] === 'success') {
  3632. $task->updateStatus('success', [
  3633. 'result_url' => $statusInfo['result_url'],
  3634. 'result_json' => $statusInfo['result_json'] ?? []
  3635. ]);
  3636. // 同步调整分镜图片状态和结果
  3637. if (getProp($task, 'alias_segment_id')) {
  3638. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3639. 'img_url' => $statusInfo['result_url'][0],
  3640. 'pic_task_status' => '已完成',
  3641. ]);
  3642. }
  3643. $img_url = $statusInfo['result_url'][0];
  3644. break;
  3645. } elseif ($statusInfo['status'] === 'failed') {
  3646. $task->updateStatus('failed', [
  3647. 'error_message' => $statusInfo['error_message'],
  3648. 'result_json' => $statusInfo['result_json'] ?? []
  3649. ]);
  3650. if (getProp($task, 'alias_segment_id')) {
  3651. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3652. 'pic_task_status' => '失败',
  3653. ]);
  3654. }
  3655. break;
  3656. }
  3657. $start_count++;
  3658. }
  3659. return $img_url;
  3660. }
  3661. /**
  3662. * 从分镜内容中提取涉及的角色
  3663. */
  3664. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3665. $found_characters = [];
  3666. foreach ($available_characters as $character) {
  3667. // 检查角色名称是否在分镜内容中出现
  3668. if (strpos($segment_content, $character) !== false) {
  3669. $found_characters[] = $character;
  3670. }
  3671. }
  3672. if (!$found_characters) {
  3673. foreach ($roles as $character) {
  3674. // 检查角色名称是否在分镜内容中出现
  3675. if (strpos($segment_content, $character) !== false) {
  3676. $found_characters[] = $character;
  3677. }
  3678. }
  3679. }
  3680. return array_unique($found_characters);
  3681. }
  3682. // 从分镜剧本中提取关键字段
  3683. private function handleSegmentContent(&$data) {
  3684. $segmentContent = getProp($data, 'segment_content');
  3685. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3686. $segmentData = [
  3687. 'description' => '',
  3688. 'composition' => '',
  3689. 'camera_movement' => '',
  3690. 'voice_actor' => '',
  3691. 'dialogue' => '',
  3692. 'frame_type' => '',
  3693. 'scene' => '', // 场景
  3694. 'characters' => '', // 出镜角色
  3695. 'tail_frame' => '', // 尾帧描述
  3696. 'emotion' => '中性', // 情感
  3697. 'gender' => '0', // 性别(0未知,1男,2女)
  3698. 'speed_ratio' => 0, // 语速
  3699. 'loudness_ratio' => 0, // 音量
  3700. 'emotion_scale' => 4, // 情感强度
  3701. 'pitch' => 0, // 音调
  3702. ];
  3703. // 用于存储需要从 segment_content 中移除的匹配项
  3704. $replaceEmptyArr = [];
  3705. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3706. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3707. $segmentData['description'] = trim($descMatch[1]);
  3708. $data['description'] = trim($descMatch[1]);
  3709. }
  3710. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3711. $segmentData['composition'] = trim($compMatch[1]);
  3712. $data['composition'] = trim($compMatch[1]);
  3713. }
  3714. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3715. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3716. $data['camera_movement'] = trim($cameraMatch[1]);
  3717. }
  3718. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3719. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3720. $data['voice_actor'] = trim($voiceMatch[1]);
  3721. }
  3722. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3723. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3724. $data['dialogue'] = trim($dialogueMatch[1]);
  3725. }
  3726. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3727. $segmentData['frame_type'] = trim($frameMatch[1]);
  3728. $data['frame_type'] = trim($frameMatch[1]);
  3729. }
  3730. // 场景字段
  3731. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3732. $segmentData['scene'] = trim($sceneMatch[1]);
  3733. $data['scene'] = trim($sceneMatch[1]);
  3734. }
  3735. // 出镜角色字段
  3736. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3737. $segmentData['characters'] = trim($charactersMatch[1]);
  3738. $data['characters'] = trim($charactersMatch[1]);
  3739. }
  3740. // 尾帧描述字段
  3741. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3742. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3743. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3744. }
  3745. // 情感字段
  3746. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3747. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3748. $segmentData['emotion'] = trim($emotionMatch[1]);
  3749. $data['emotion'] = trim($emotionMatch[1]);
  3750. }
  3751. // 性别字段
  3752. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3753. $replaceEmptyArr[] = trim($genderMatch[0]);
  3754. $genderStr = trim($genderMatch[1]);
  3755. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3756. $segmentData['gender'] = '1';
  3757. $data['gender'] = '1';
  3758. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3759. $segmentData['gender'] = '2';
  3760. $data['gender'] = '2';
  3761. } else {
  3762. $segmentData['gender'] = '0';
  3763. $data['gender'] = '0';
  3764. }
  3765. }
  3766. // 语速字段
  3767. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3768. $replaceEmptyArr[] = trim($speedMatch[0]);
  3769. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3770. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3771. }
  3772. // 音量字段
  3773. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3774. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3775. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3776. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3777. }
  3778. // 情感强度字段
  3779. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3780. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3781. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3782. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3783. }
  3784. // 音调字段
  3785. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3786. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3787. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3788. $data['pitch'] = (int)trim($pitchMatch[1]);
  3789. }
  3790. // 从 segment_content 中移除已提取的配音参数字段
  3791. if (!empty($replaceEmptyArr)) {
  3792. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3793. }
  3794. // 如果有配音角色,查询音色信息并验证情感
  3795. $voice_actor = $segmentData['voice_actor'];
  3796. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3797. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3798. $anime_id = getProp($data, 'anime_id');
  3799. $episode_id = getProp($data, 'episode_id');
  3800. // 优先从剧集的角色列表中查找
  3801. $roles = [];
  3802. if ($episode_id) {
  3803. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3804. if ($episode && getProp($episode, 'roles')) {
  3805. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3806. }
  3807. }
  3808. // 如果剧集中没有,从动漫的角色列表中查找
  3809. if (empty($roles) && $anime_id) {
  3810. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3811. if ($anime && getProp($anime, 'roles')) {
  3812. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3813. }
  3814. }
  3815. // 查找匹配的角色音色信息
  3816. $timbre_info = null;
  3817. foreach ($roles as $role) {
  3818. if (getProp($role, 'role') === $voice_actor) {
  3819. $timbre_info = $role;
  3820. break;
  3821. }
  3822. }
  3823. // 如果找到音色信息,添加到数据中
  3824. if ($timbre_info) {
  3825. $voice_type = getProp($timbre_info, 'voice_type');
  3826. $voice_name = getProp($timbre_info, 'voice_name');
  3827. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3828. if ($voice_type) {
  3829. $data['voice_type'] = $voice_type;
  3830. $segmentData['voice_type'] = $voice_type;
  3831. }
  3832. if ($voice_name) {
  3833. $data['voice_name'] = $voice_name;
  3834. $segmentData['voice_name'] = $voice_name;
  3835. }
  3836. if ($voice_audio_url) {
  3837. $data['voice_audio_url'] = $voice_audio_url;
  3838. $segmentData['voice_audio_url'] = $voice_audio_url;
  3839. }
  3840. // 验证情感是否在音色支持的情感列表中
  3841. if ($voice_type) {
  3842. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3843. if ($timbre_emotion) {
  3844. $timbre_emotion = explode(',', $timbre_emotion);
  3845. } else {
  3846. $timbre_emotion = [];
  3847. }
  3848. $emotion = getProp($segmentData, 'emotion', '中性');
  3849. if (!in_array($emotion, $timbre_emotion)) {
  3850. $emotion = '中性';
  3851. }
  3852. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3853. $emotion_list = array_flip($emotion_list);
  3854. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3855. $data['emotion_type'] = $emotion_type;
  3856. $segmentData['emotion_type'] = $emotion_type;
  3857. }
  3858. }
  3859. }
  3860. return $segmentData;
  3861. }
  3862. public function createSegmentVideoTask($data) {
  3863. $segment_id = getProp($data, 'segment_id');
  3864. $tail_frame = getProp($data, 'tail_frame');
  3865. $first_frame_url = getProp($data, 'first_frame_url');
  3866. $tail_frame_url = getProp($data, 'tail_frame_url');
  3867. $generate_audio = getProp($data, 'generate_audio', 0);
  3868. if (!$segment_id) {
  3869. Utils::throwError('1002:分镜ID不能为空');
  3870. }
  3871. // 获取分镜信息
  3872. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3873. if (!$segment) {
  3874. Utils::throwError('20003:分镜不存在');
  3875. }
  3876. $segment = (array)$segment;
  3877. $episode_id = getProp($segment, 'episode_id');
  3878. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3879. if (!$ratio) $ratio = '9:16';
  3880. // 获取分镜内容
  3881. $segmentContent = getProp($segment, 'segment_content', '');
  3882. // 检查 $segmentContent 中是否已有尾帧描述
  3883. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3884. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3885. $finalTailFrame = '';
  3886. if ($tail_frame) {
  3887. // 用户输入了尾帧描述,优先使用
  3888. $finalTailFrame = $tail_frame;
  3889. // 如果 segmentContent 中已有尾帧描述,需要替换
  3890. if ($contentHasTailFrame) {
  3891. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3892. }
  3893. } elseif ($contentHasTailFrame) {
  3894. // segmentContent 中有尾帧描述,使用它
  3895. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3896. } else {
  3897. // 两者都没有,使用分镜表中的尾帧描述
  3898. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3899. }
  3900. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3901. $hasDialogue = false;
  3902. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3903. $dialogue = trim($dialogueMatch[1]);
  3904. // 如果台词不为空且不是"无"
  3905. if (!empty($dialogue) && $dialogue !== '无') {
  3906. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3907. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3908. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3909. $hasDialogue = true;
  3910. }
  3911. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3912. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3913. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3914. if (!preg_match('/^[“]/', $dialogue)) {
  3915. $dialogue = '“' . $dialogue;
  3916. }
  3917. if (!preg_match('/[”]$/', $dialogue)) {
  3918. $dialogue .= '”';
  3919. }
  3920. // 将修改后的台词替换回 $segmentContent
  3921. $originalDialogue = $dialogueMatch[1];
  3922. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3923. }
  3924. }
  3925. // 构建完整的提示词
  3926. $fullPrompt = $segmentContent;
  3927. if ($finalTailFrame && !$contentHasTailFrame) {
  3928. // 只有当 segmentContent 中没有尾帧描述时才追加
  3929. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3930. }
  3931. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3932. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3933. $fullPrompt = trim($fullPrompt);
  3934. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3935. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3936. // 智能选择视频时长
  3937. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3938. $videoDuration = -1;
  3939. // 处理视频模型
  3940. $model = getProp($data, 'model');
  3941. if (!$model) {
  3942. // 用户没有输入,从episode表获取
  3943. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3944. $model = getProp($episode, 'video_model');
  3945. if (!$model) {
  3946. // episode表也没有,使用默认值
  3947. $model = 'doubao-seedance-1-5-pro-251215';
  3948. }
  3949. }
  3950. // 验证模型是否在可用模型表中
  3951. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3952. $model = 'doubao-seedance-1-5-pro-251215';
  3953. }
  3954. // 保存到episode表
  3955. $episode_id = getProp($segment, 'episode_id');
  3956. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3957. 'video_model' => $model,
  3958. 'updated_at' => date('Y-m-d H:i:s')
  3959. ]);
  3960. // 构建视频生成参数
  3961. $videoParams = [
  3962. 'model' => $model,
  3963. 'alias_segment_id' => $segment_id,
  3964. 'prompt' => trim($fullPrompt),
  3965. 'video_duration' => $videoDuration,
  3966. 'video_resolution' => '720P',
  3967. 'seed' => -1,
  3968. 'ratio' => $ratio,
  3969. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3970. 'draft' => false,
  3971. 'watermark' => false,
  3972. 'camera_fixed' => false,
  3973. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3974. ];
  3975. // 如果分镜有图片,作为首帧
  3976. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3977. $hasVideo = !empty(getProp($segment, 'video_url'));
  3978. if ($hasImage) {
  3979. if ($first_frame_url) {
  3980. $videoParams['first_frame_url'] = $first_frame_url;
  3981. }else {
  3982. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3983. }
  3984. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3985. }
  3986. // 构建content数组
  3987. $videoParams['content'] = [
  3988. [
  3989. 'type' => 'text',
  3990. 'text' => $videoParams['prompt'],
  3991. ]
  3992. ];
  3993. // 如果有首帧图片,添加到content中
  3994. if ($hasImage) {
  3995. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3996. $videoParams['content'][] = [
  3997. 'type' => 'image_url',
  3998. 'image_url' => [
  3999. 'url' => $videoParams['first_frame_url'],
  4000. ],
  4001. 'role' => 'reference_image',
  4002. ];
  4003. if (isset($videoParams['tail_frame_url'])) {
  4004. $videoParams['content'][] = [
  4005. 'type' => 'image_url',
  4006. 'image_url' => [
  4007. 'url' => $videoParams['tail_frame_url'],
  4008. ],
  4009. 'role' => 'reference_image',
  4010. ];
  4011. }
  4012. }else {
  4013. $videoParams['content'][] = [
  4014. 'type' => 'image_url',
  4015. 'image_url' => [
  4016. 'url' => $videoParams['first_frame_url'],
  4017. ],
  4018. 'role' => 'first_frame',
  4019. ];
  4020. if (isset($videoParams['tail_frame_url'])) {
  4021. $videoParams['content'][] = [
  4022. 'type' => 'image_url',
  4023. 'image_url' => [
  4024. 'url' => $videoParams['tail_frame_url'],
  4025. ],
  4026. 'role' => 'last_frame',
  4027. ];
  4028. }
  4029. }
  4030. }
  4031. // 获取配音音频URL
  4032. $audioUrl = getProp($segment, 'audio_url');
  4033. $audioDuration = getProp($segment, 'audio_duration');
  4034. // 音频传入的前提:必须有至少一张图片或一个视频
  4035. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4036. // 余额预检:按预估时长计算所需积分,不足直接报错
  4037. $chargeDuration = (int)ceil((float)$audioDuration);
  4038. if ($chargeDuration <= 0) {
  4039. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4040. }
  4041. $this->pointsService->checkUserPointsEnough(
  4042. $this->pointsService->getVideoChargePoints([
  4043. 'model' => $model,
  4044. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4045. 'video_duration' => $chargeDuration,
  4046. 'ratio' => $ratio,
  4047. 'generate_audio' => $current_generate_audio,
  4048. ])
  4049. );
  4050. // dd($videoParams);
  4051. // 根据模型选择不同的视频生成方法
  4052. if (strpos($model, 'jimeng') !== false) {
  4053. // 即梦模型参数调整
  4054. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4055. unset($videoParams['content']); // 即梦不使用content格式
  4056. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4057. } elseif (strpos($model, 'kling') !== false) {
  4058. // Keling模型参数调整
  4059. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4060. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4061. unset($videoParams['ratio']);
  4062. unset($videoParams['content']); // Keling不使用content格式
  4063. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4064. } elseif (strpos($model, 'zhizhen') !== false) {
  4065. // 智帧20等新模型使用统一API
  4066. // 构建统一API参数
  4067. $unifiedParams = [
  4068. 'model_code' => $model,
  4069. 'alias_segment_id' => $segment_id,
  4070. 'prompt' => trim($fullPrompt),
  4071. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4072. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4073. 'video_ratio' => $ratio,
  4074. 'seed' => -1,
  4075. ];
  4076. // 构建parameters参数
  4077. $parameters = [
  4078. 'seconds' => $unifiedParams['video_duration'],
  4079. 'resolution' => $unifiedParams['video_resolution'],
  4080. 'ratio' => $ratio,
  4081. // 'video_mode' => 'multi_image',
  4082. // 'mode' => 'multi_image',
  4083. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4084. ];
  4085. $hasImage = false;
  4086. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4087. if ($hasImage) {
  4088. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4089. if (isset($videoParams['tail_frame_url'])) {
  4090. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4091. }
  4092. // 只有在有图片的情况下才能添加参考音频
  4093. if ($audioUrl) {
  4094. // $parameters['reference_audios'] = [$audioUrl];
  4095. }
  4096. } else {
  4097. // 没有图片时,记录错误日志
  4098. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4099. 'segment_id' => $segment_id,
  4100. 'model' => $model
  4101. ]);
  4102. }
  4103. $unifiedParams['parameters'] = $parameters;
  4104. // 调用统一API创建任务
  4105. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4106. } else {
  4107. // Seedance模型(默认)
  4108. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4109. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4110. // 添加配音音频到content中
  4111. $videoParams['content'][] = [
  4112. 'type' => 'audio_url',
  4113. 'audio_url' => [
  4114. 'url' => $audioUrl,
  4115. ],
  4116. 'role' => 'reference_audio',
  4117. ];
  4118. // 优化提示词,增加音频相关描述
  4119. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4120. $videoParams['prompt'] = $audioPrompt;
  4121. $videoParams['content'][0]['text'] = $audioPrompt;
  4122. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4123. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4124. }
  4125. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4126. }
  4127. // 更新分镜表的视频任务信息
  4128. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4129. 'video_task_id' => $task->id,
  4130. 'video_task_status' => '生成中',
  4131. 'generate_audio' => $generate_audio,
  4132. 'updated_at' => date('Y-m-d H:i:s')
  4133. ]);
  4134. return [
  4135. 'task_id' => $task->id,
  4136. 'status' => $task->status,
  4137. 'segment_id' => $segment_id,
  4138. 'video_duration' => $videoDuration
  4139. ];
  4140. }
  4141. public function createActVideoTask($data) {
  4142. $act_id = getProp($data, 'act_id');
  4143. $first_frame_url = getProp($data, 'first_frame_url');
  4144. $tail_frame_url = getProp($data, 'tail_frame_url');
  4145. $generate_audio = getProp($data, 'generate_audio', 1);
  4146. $video_duration = getProp($data, 'video_duration');
  4147. $video_resolution = getProp($data, 'video_resolution');
  4148. $ratio = getProp($data, 'ratio');
  4149. $products = getProp($data, 'products', []);
  4150. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4151. if (!is_array($reference_images) || !is_array($products)) {
  4152. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4153. }
  4154. if (!$act_id) {
  4155. Utils::throwError('1002:片段ID不能为空');
  4156. }
  4157. // 获取片段信息
  4158. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4159. if (!$act) {
  4160. Utils::throwError('20003:片段不存在');
  4161. }
  4162. $act = (array)$act;
  4163. $anime_id = getProp($act, 'anime_id');
  4164. $episode_id = getProp($act, 'episode_id');
  4165. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4166. $ace_mode = getProp($anime, 'ace_mode');
  4167. $art_style_type = getProp($anime, 'art_style_type');
  4168. $art_style = getProp($anime, 'art_style');
  4169. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4170. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4171. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4172. // 将资产中新出现的资产放到extra_products中
  4173. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4174. if (!empty($products) && $episode) {
  4175. // 获取剧集中的角色、场景和道具列表
  4176. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4177. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4178. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4179. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4180. // 构建角色名称列表
  4181. $role_names = array_column($roles, 'role');
  4182. // 构建场景名称列表
  4183. $scene_names = array_column($scenes, 'scene');
  4184. // 构建道具名称列表
  4185. $prop_names = array_column($props, 'prop');
  4186. // 遍历传入的products
  4187. foreach ($products as $product) {
  4188. $product_name = getProp($product, 'product_name');
  4189. // 如果product_name不在roles、scenes和props中
  4190. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4191. // 查找是否在extra_products中存在同名的
  4192. $found = false;
  4193. foreach ($extra_products as $key => $extra_product) {
  4194. if (getProp($extra_product, 'product_name') === $product_name) {
  4195. // 有同名的则覆盖
  4196. $extra_products[$key] = $product;
  4197. $found = true;
  4198. break;
  4199. }
  4200. }
  4201. // 没有则新增
  4202. if (!$found) {
  4203. $extra_products[] = $product;
  4204. }
  4205. }
  4206. }
  4207. if ($extra_products) {
  4208. // 保存到数据库
  4209. DB::table('mp_anime_episodes')
  4210. ->where('id', $episode_id)
  4211. ->update([
  4212. 'extra_products' => json_encode($extra_products, 256),
  4213. 'updated_at' => date('Y-m-d H:i:s')
  4214. ]);
  4215. }
  4216. }
  4217. // 获取分镜内容
  4218. $actContent = getProp($act, 'act_show_content', '');
  4219. // 音效同出(默认使用)
  4220. $current_generate_audio = $generate_audio ? 1 : 0;
  4221. // 构建完整的提示词
  4222. $processResult = $this->processActContentWithProducts($actContent, $products);
  4223. $fullPrompt = $processResult['content'];
  4224. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4225. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4226. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4227. // 处理视频模型
  4228. $model = getProp($data, 'model');
  4229. if (!$model) {
  4230. $model = getProp($episode, 'video_model');
  4231. if (!$model) {
  4232. // episode表也没有,使用默认值
  4233. $model = 'zhizhen-20';
  4234. }
  4235. }
  4236. // 验证模型是否在可用模型表中
  4237. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4238. $model = 'zhizhen-20';
  4239. }
  4240. // 保存到episode表(仅在专用方法中更新模型)
  4241. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4242. // 'video_model' => $model,
  4243. // 'updated_at' => date('Y-m-d H:i:s')
  4244. // ]);
  4245. // 余额预检:按预估时长计算所需积分,不足直接报错
  4246. $chargeDuration = (int)$videoDuration;
  4247. if ($chargeDuration <= 0) {
  4248. $chargeDuration = 5; // 无时长时按默认5秒预估
  4249. }
  4250. $this->pointsService->checkUserPointsEnough(
  4251. $this->pointsService->getVideoChargePoints([
  4252. 'model' => $model,
  4253. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4254. 'video_duration' => $chargeDuration,
  4255. 'ratio' => $ratio,
  4256. 'generate_audio' => $current_generate_audio,
  4257. ])
  4258. );
  4259. // 构建视频生成参数
  4260. $videoParams = [
  4261. 'model' => $model,
  4262. 'alias_act_id' => $act_id,
  4263. 'prompt' => trim($fullPrompt),
  4264. 'video_duration' => $videoDuration,
  4265. 'video_resolution' => $video_resolution,
  4266. 'seed' => -1,
  4267. 'ratio' => $ratio,
  4268. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4269. 'draft' => false,
  4270. 'watermark' => false,
  4271. 'camera_fixed' => false,
  4272. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4273. ];
  4274. // 如果分镜有图片,作为首帧
  4275. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4276. $hasVideo = !empty(getProp($act, 'video_url'));
  4277. if ($hasImage) {
  4278. if ($first_frame_url) {
  4279. $videoParams['first_frame_url'] = $first_frame_url;
  4280. }else {
  4281. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4282. }
  4283. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4284. }
  4285. // 构建content数组
  4286. $videoParams['content'] = [
  4287. [
  4288. 'type' => 'text',
  4289. 'text' => $videoParams['prompt'],
  4290. ]
  4291. ];
  4292. // 如果有首帧图片,添加到content中
  4293. if ($hasImage) {
  4294. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4295. $videoParams['content'][] = [
  4296. 'type' => 'image_url',
  4297. 'image_url' => [
  4298. 'url' => $videoParams['first_frame_url'],
  4299. ],
  4300. 'role' => 'reference_image',
  4301. ];
  4302. if (isset($videoParams['tail_frame_url'])) {
  4303. $videoParams['content'][] = [
  4304. 'type' => 'image_url',
  4305. 'image_url' => [
  4306. 'url' => $videoParams['tail_frame_url'],
  4307. ],
  4308. 'role' => 'reference_image',
  4309. ];
  4310. }
  4311. }else {
  4312. $videoParams['content'][] = [
  4313. 'type' => 'image_url',
  4314. 'image_url' => [
  4315. 'url' => $videoParams['first_frame_url'],
  4316. ],
  4317. 'role' => 'first_frame',
  4318. ];
  4319. if (isset($videoParams['tail_frame_url'])) {
  4320. $videoParams['content'][] = [
  4321. 'type' => 'image_url',
  4322. 'image_url' => [
  4323. 'url' => $videoParams['tail_frame_url'],
  4324. ],
  4325. 'role' => 'last_frame',
  4326. ];
  4327. }
  4328. }
  4329. }
  4330. // dd($videoParams);
  4331. // 根据模型选择不同的视频生成方法
  4332. if (strpos($model, 'jimeng') !== false) {
  4333. // 即梦模型参数调整
  4334. unset($videoParams['content']); // 即梦不使用content格式
  4335. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4336. } elseif (strpos($model, 'kling') !== false) {
  4337. // Keling模型参数调整
  4338. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4339. unset($videoParams['ratio']);
  4340. unset($videoParams['content']); // Keling不使用content格式
  4341. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4342. } elseif (strpos($model, 'zhizhen') !== false) {
  4343. // 智帧20等新模型使用统一API
  4344. // 构建统一API参数
  4345. $unifiedParams = [
  4346. 'model_code' => $model,
  4347. 'alias_act_id' => $act_id,
  4348. 'prompt' => trim($fullPrompt),
  4349. 'video_duration' => $videoDuration,
  4350. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4351. 'video_ratio' => $ratio,
  4352. 'seed' => -1,
  4353. ];
  4354. // 构建parameters参数
  4355. $parameters = [
  4356. 'seconds' => $unifiedParams['video_duration'],
  4357. 'resolution' => $unifiedParams['video_resolution'],
  4358. 'ratio' => $ratio,
  4359. // 'video_mode' => 'multi_image',
  4360. // 'mode' => 'multi_image',
  4361. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4362. ];
  4363. $hasImage = false;
  4364. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4365. if ($hasImage) {
  4366. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4367. if (isset($videoParams['tail_frame_url'])) {
  4368. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4369. }
  4370. } else {
  4371. // 没有图片时,记录错误日志
  4372. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4373. 'act_id' => $act_id,
  4374. 'model' => $model
  4375. ]);
  4376. }
  4377. if ($reference_images) {
  4378. // 限制只传入9张参考图
  4379. $reference_images = array_slice($reference_images, 0, 9);
  4380. // 在处理之前先保存原始reference_images到任务参数中
  4381. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4382. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4383. $parameters['reference_images'] = $reference_images;
  4384. $parameters['video_mode'] = 'multi_image';
  4385. $parameters['mode'] = 'multi_image';
  4386. }
  4387. $unifiedParams['parameters'] = $parameters;
  4388. // 调用统一API创建任务
  4389. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4390. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4391. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4392. // 保存原始参考图用于任务记录
  4393. $videoParams['reference_images'] = $reference_images;
  4394. if ($reference_images) {
  4395. // 限制只传入9张参考图
  4396. $reference_images = array_slice($reference_images, 0, 9);
  4397. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4398. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4399. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4400. $videoParams['prompt'] = trim($fullPrompt);
  4401. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4402. $videoParams['reference_image_assets'] = $reference_image_assets;
  4403. }
  4404. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4405. } else {
  4406. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4407. }
  4408. // 更新分镜表的视频任务信息
  4409. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4410. 'video_task_id' => $task->id,
  4411. 'video_task_status' => '生成中',
  4412. 'generate_audio' => $generate_audio,
  4413. 'updated_at' => date('Y-m-d H:i:s')
  4414. ]);
  4415. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4416. $episode_number = getProp($act, 'episode_number');
  4417. $act_number = getProp($act, 'act_number');
  4418. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4419. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4420. }
  4421. return [
  4422. 'task_id' => $task->id,
  4423. 'status' => $task->status,
  4424. 'act_id' => $act_id,
  4425. 'video_duration' => $videoDuration
  4426. ];
  4427. }
  4428. /**
  4429. * 文生视频通用方法
  4430. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4431. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4432. *
  4433. * @param array $data 请求参数
  4434. * @return array
  4435. */
  4436. public function generateVideo($data) {
  4437. $prompt = getProp($data, 'prompt');
  4438. if (empty($prompt)) {
  4439. Utils::throwError('20003:提示词不能为空');
  4440. }
  4441. $model = getProp($data, 'model');
  4442. if (!$model) {
  4443. $model = 'zhizhen-20';
  4444. }
  4445. // 验证模型是否在可用模型表中
  4446. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4447. Utils::throwError('20003:该模型已不可用,请更换!');
  4448. }
  4449. $video_duration = getProp($data, 'video_duration', 5);
  4450. $video_resolution = getProp($data, 'video_resolution', '480p');
  4451. $ratio = getProp($data, 'ratio', '9:16');
  4452. $generate_audio = getProp($data, 'generate_audio', 1);
  4453. $seed = getProp($data, 'seed', -1);
  4454. $first_frame_url = getProp($data, 'first_frame_url');
  4455. $tail_frame_url = getProp($data, 'tail_frame_url');
  4456. // 参考图(支持数组或JSON字符串,最多9张)
  4457. $reference_images = getProp($data, 'reference_images', []);
  4458. if (is_string($reference_images)) {
  4459. $reference_images = json_decode($reference_images, true) ?: [];
  4460. }
  4461. if (!is_array($reference_images)) {
  4462. Utils::throwError('20003:参考图格式不正确');
  4463. }
  4464. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4465. $reference_images = array_slice($reference_images, 0, 9);
  4466. // 参考视频(支持数组或JSON字符串,最多3个)
  4467. $reference_videos = getProp($data, 'reference_videos', []);
  4468. if (is_string($reference_videos)) {
  4469. $reference_videos = json_decode($reference_videos, true) ?: [];
  4470. }
  4471. if (!is_array($reference_videos)) {
  4472. Utils::throwError('20003:参考视频格式不正确');
  4473. }
  4474. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4475. if (count($reference_videos) > 3) {
  4476. Utils::throwError('20003:参考视频最多选择3个');
  4477. }
  4478. $reference_videos = array_slice($reference_videos, 0, 3);
  4479. // 参考音频(支持数组或JSON字符串,最多3个)
  4480. $reference_audios = getProp($data, 'reference_audios', []);
  4481. if (is_string($reference_audios)) {
  4482. $reference_audios = json_decode($reference_audios, true) ?: [];
  4483. }
  4484. if (!is_array($reference_audios)) {
  4485. Utils::throwError('20003:参考音频格式不正确');
  4486. }
  4487. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4488. if (count($reference_audios) > 3) {
  4489. Utils::throwError('20003:参考音频最多选择3个');
  4490. }
  4491. $reference_audios = array_slice($reference_audios, 0, 3);
  4492. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4493. $videoParams = [
  4494. 'model' => $model,
  4495. 'prompt' => $prompt,
  4496. 'video_duration' => $video_duration,
  4497. 'video_resolution' => $video_resolution,
  4498. 'seed' => $seed,
  4499. 'ratio' => $ratio,
  4500. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4501. 'draft' => getProp($data, 'draft', false),
  4502. 'watermark' => getProp($data, 'watermark', false),
  4503. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4504. ];
  4505. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4506. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4507. // 构建content数组
  4508. $videoParams['content'] = [
  4509. [
  4510. 'type' => 'text',
  4511. 'text' => $prompt,
  4512. ]
  4513. ];
  4514. // 根据模型选择不同的视频生成方法
  4515. if (strpos($model, 'jimeng') !== false) {
  4516. // 即梦模型参数调整
  4517. unset($videoParams['content']); // 即梦不使用content格式
  4518. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4519. } elseif (strpos($model, 'kling') !== false) {
  4520. // 可灵模型参数调整
  4521. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4522. unset($videoParams['ratio']);
  4523. unset($videoParams['content']); // 可灵不使用content格式
  4524. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4525. } elseif (strpos($model, 'zhizhen') !== false) {
  4526. // 智帧等新模型使用统一API
  4527. $unifiedParams = [
  4528. 'model_code' => $model,
  4529. 'prompt' => $prompt,
  4530. 'video_duration' => $video_duration,
  4531. 'video_resolution' => strtolower($video_resolution),
  4532. 'video_ratio' => $ratio,
  4533. 'seed' => $seed,
  4534. ];
  4535. // 构建parameters参数
  4536. $parameters = [
  4537. 'seconds' => $unifiedParams['video_duration'],
  4538. 'resolution' => $unifiedParams['video_resolution'],
  4539. 'ratio' => $ratio,
  4540. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4541. ];
  4542. // 首帧和尾帧
  4543. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4544. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4545. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4546. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4547. if ($refImageUrls) {
  4548. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4549. }
  4550. // 参考图处理
  4551. if ($reference_images) {
  4552. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4553. $parameters['reference_images'] = $reference_images;
  4554. $parameters['video_mode'] = 'multi_image';
  4555. $parameters['mode'] = 'multi_image';
  4556. }
  4557. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4558. if ($reference_videos) {
  4559. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4560. $parameters['reference_videos'] = $reference_videos;
  4561. }
  4562. if ($reference_audios) {
  4563. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4564. $parameters['reference_audios'] = $reference_audios;
  4565. }
  4566. $unifiedParams['parameters'] = $parameters;
  4567. // 调用统一API创建任务
  4568. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4569. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4570. // 豆包Seedance 2.0(百度AI网关):图片/视频/音频需要先上传为素材
  4571. $videoParams['reference_images'] = $reference_images;
  4572. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4573. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4574. if ($refImageUrls) {
  4575. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4576. }
  4577. if ($reference_images) {
  4578. // 参考图上传为百度网关素材
  4579. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4580. $videoParams['reference_image_assets'] = $reference_image_assets;
  4581. }
  4582. // 参考视频上传为百度网关素材
  4583. if ($reference_videos) {
  4584. $reference_video_assets = $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4585. $videoParams['reference_video_assets'] = $reference_video_assets;
  4586. }
  4587. // 参考音频上传为百度网关素材
  4588. if ($reference_audios) {
  4589. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4590. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4591. }
  4592. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4593. if ($reference_images || $reference_videos || $reference_audios) {
  4594. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4595. }
  4596. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4597. } else {
  4598. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4599. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4600. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4601. if ($refImageUrls) {
  4602. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4603. }
  4604. if ($reference_videos) {
  4605. foreach ($reference_videos as $videoUrl) {
  4606. $videoParams['content'][] = [
  4607. 'type' => 'video_url',
  4608. 'video_url' => [
  4609. 'url' => $videoUrl,
  4610. ],
  4611. 'role' => 'reference_video',
  4612. ];
  4613. }
  4614. }
  4615. if ($reference_audios) {
  4616. foreach ($reference_audios as $audioUrl) {
  4617. $videoParams['content'][] = [
  4618. 'type' => 'audio_url',
  4619. 'audio_url' => [
  4620. 'url' => $audioUrl,
  4621. ],
  4622. 'role' => 'reference_audio',
  4623. ];
  4624. }
  4625. }
  4626. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4627. }
  4628. return [
  4629. 'task_id' => $task->id,
  4630. 'status' => $task->status,
  4631. 'model' => $model,
  4632. 'video_duration' => $video_duration,
  4633. 'video_resolution' => $video_resolution,
  4634. 'ratio' => $ratio
  4635. ];
  4636. }
  4637. /**
  4638. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4639. *
  4640. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4641. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4642. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4643. *
  4644. * @param array $data
  4645. * @return array
  4646. */
  4647. public function previewCharge(array $data): array
  4648. {
  4649. $mode = (string)getProp($data, 'mode', '');
  4650. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4651. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4652. }
  4653. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4654. $scene = (string)getProp($data, 'scene', 'video_generation');
  4655. $items = [];
  4656. $model = '';
  4657. $resolution = '';
  4658. if ($mode === 'video') {
  4659. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4660. $model = (string)getProp($data, 'model', '');
  4661. if (!$model) {
  4662. Utils::throwError('1002:model参数不能为空');
  4663. }
  4664. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4665. $duration = (int)getProp($data, 'video_duration', 5);
  4666. if ($duration <= 0) {
  4667. $duration = 5;
  4668. }
  4669. $count = max(1, (int)getProp($data, 'count', 1));
  4670. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4671. 'model' => $model,
  4672. 'video_resolution' => $resolution,
  4673. 'video_duration' => $duration,
  4674. 'mode' => $scene,
  4675. ]);
  4676. $points = $pointsPerVideo * $count;
  4677. $items[] = [
  4678. 'type' => 'video',
  4679. 'model' => $model,
  4680. 'video_resolution' => $resolution,
  4681. 'video_duration' => $duration,
  4682. 'count' => $count,
  4683. 'points' => $points,
  4684. ];
  4685. } elseif ($mode === 'image') {
  4686. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4687. $model = (string)getProp($data, 'model', '');
  4688. if (!$model) {
  4689. Utils::throwError('1002:model参数不能为空');
  4690. }
  4691. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4692. if (!$resolution) {
  4693. $width = (int)getProp($data, 'width', 0);
  4694. $height = (int)getProp($data, 'height', 0);
  4695. if ($width <= 0 || $height <= 0) {
  4696. $width = 1600;
  4697. $height = 2848;
  4698. }
  4699. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4700. }
  4701. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4702. $points = $this->pointsService->getImageChargePoints([
  4703. 'model' => $model,
  4704. 'resolution' => $resolution,
  4705. ]) * $imageNum;
  4706. $items[] = [
  4707. 'type' => 'image',
  4708. 'model' => $model,
  4709. 'resolution' => $resolution,
  4710. 'image_num' => $imageNum,
  4711. 'points' => $points,
  4712. ];
  4713. } else {
  4714. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4715. $count = max(1, (int)getProp($data, 'count', 1));
  4716. $animeId = getProp($data, 'anime_id');
  4717. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4718. if ($animeId && $generateEpisodes > 0) {
  4719. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4720. ->where('anime_id', $animeId)
  4721. ->where('is_default', 1)
  4722. ->max('episode_number');
  4723. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4724. $startEpisodeNumber = $currentMaxEpisode + 1;
  4725. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4726. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4727. ->where('anime_id', $animeId)
  4728. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4729. ->whereIn('status', ['pending', 'processing', 'completed'])
  4730. ->count();
  4731. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4732. if ($count < 0) {
  4733. $count = 0;
  4734. }
  4735. }
  4736. $points = $this->pointsService->getChatChargePoints((string)$model) * $count;
  4737. $items[] = [
  4738. 'type' => 'chat',
  4739. 'count' => $count,
  4740. 'points' => $points,
  4741. ];
  4742. }
  4743. $totalPoints = 0;
  4744. foreach ($items as $item) {
  4745. $totalPoints += $item['points'];
  4746. }
  4747. return [
  4748. 'mode' => $mode,
  4749. 'total_points' => $totalPoints,
  4750. 'items' => $items,
  4751. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4752. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4753. ];
  4754. }
  4755. /**
  4756. * 根据提示词内容智能计算最优视频时长
  4757. *
  4758. * @param string $segmentContent 分镜内容
  4759. * @param string $tailFrame 尾帧描述
  4760. * @return int 视频时长(2-12秒)
  4761. */
  4762. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4763. // 合并所有文本内容
  4764. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4765. // 如果没有内容,返回默认时长
  4766. if (empty($fullText)) {
  4767. return 5;
  4768. }
  4769. // 计算文本长度(中文字符按2个字符计算)
  4770. $textLength = mb_strlen($fullText, 'UTF-8');
  4771. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4772. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4773. // 分析内容复杂度
  4774. $complexityScore = $this->analyzeContentComplexity($fullText);
  4775. // 基础时长计算(根据文本长度)
  4776. $baseDuration = 3; // 默认2秒
  4777. // if ($adjustedLength <= 20) {
  4778. // $baseDuration = 3;
  4779. // } elseif ($adjustedLength <= 40) {
  4780. // $baseDuration = 4;
  4781. // } elseif ($adjustedLength <= 60) {
  4782. // $baseDuration = 5;
  4783. // } elseif ($adjustedLength <= 80) {
  4784. // $baseDuration = 6;
  4785. // } elseif ($adjustedLength <= 100) {
  4786. // $baseDuration = 7;
  4787. // } elseif ($adjustedLength <= 120) {
  4788. // $baseDuration = 8;
  4789. // } else {
  4790. // $baseDuration = 9;
  4791. // }
  4792. // 根据内容复杂度调整时长
  4793. $finalDuration = $baseDuration + $complexityScore;
  4794. // 确保时长在2-12秒范围内
  4795. return max(4, min(12, $finalDuration));
  4796. }
  4797. /**
  4798. * 分析内容复杂度,返回时长调整值
  4799. *
  4800. * @param string $text 文本内容
  4801. * @return int 调整值(-2到+3)
  4802. */
  4803. private function analyzeContentComplexity($text) {
  4804. $score = 0;
  4805. // 动作关键词(需要更长时间展现)
  4806. $actionKeywords = [
  4807. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4808. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4809. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4810. ];
  4811. // 静态关键词(可以用较短时间)
  4812. $staticKeywords = [
  4813. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4814. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4815. ];
  4816. // 复杂场景关键词(需要更长时间)
  4817. $complexSceneKeywords = [
  4818. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4819. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4820. ];
  4821. // 情感关键词(需要适中时间表现)
  4822. $emotionKeywords = [
  4823. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4824. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4825. ];
  4826. // 检查动作关键词
  4827. foreach ($actionKeywords as $keyword) {
  4828. if (strpos($text, $keyword) !== false) {
  4829. $score += 1;
  4830. break; // 避免重复加分
  4831. }
  4832. }
  4833. // 检查静态关键词
  4834. foreach ($staticKeywords as $keyword) {
  4835. if (strpos($text, $keyword) !== false) {
  4836. $score -= 1;
  4837. break;
  4838. }
  4839. }
  4840. // 检查复杂场景关键词
  4841. foreach ($complexSceneKeywords as $keyword) {
  4842. if (strpos($text, $keyword) !== false) {
  4843. $score += 1;
  4844. break;
  4845. }
  4846. }
  4847. // 检查情感关键词
  4848. foreach ($emotionKeywords as $keyword) {
  4849. if (strpos($text, $keyword) !== false) {
  4850. $score += 1;
  4851. break;
  4852. }
  4853. }
  4854. // 检查时间相关词汇
  4855. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4856. $score += 1;
  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. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4871. $score += 1;
  4872. }
  4873. // 限制调整范围
  4874. return max(-1, min(4, $score));
  4875. }
  4876. /**
  4877. * 创建完整视频合成任务
  4878. *
  4879. * @param array $data
  4880. * @return array
  4881. */
  4882. public function createCompleteVideoTask($data)
  4883. {
  4884. $animeId = getProp($data, 'anime_id');
  4885. $episodeId = getProp($data, 'episode_id');
  4886. // 验证参数
  4887. if (!$animeId || !$episodeId) {
  4888. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4889. }
  4890. // 检查是否已存在处理中的任务
  4891. $existingTask = DB::table('mp_complete_video_tasks')
  4892. ->where('anime_id', $animeId)
  4893. ->where('episode_id', $episodeId)
  4894. ->whereIn('generate_status', ['执行中'])
  4895. ->first();
  4896. if ($existingTask) {
  4897. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4898. }
  4899. // 获取全能模式状态
  4900. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4901. if ((int)$ace_mode === 1) {
  4902. // 获取所有片段的配音视频,按 act_number 排序
  4903. $segments = DB::table('mp_episode_segments')
  4904. ->where('anime_id', $animeId)
  4905. ->where('episode_id', $episodeId)
  4906. ->orderBy('segment_number')
  4907. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4908. ->get();
  4909. // 检查是否所有片段都有视频
  4910. $missingVideos = $segments->filter(function($segment) {
  4911. return empty($segment->video_url);
  4912. });
  4913. if ($missingVideos->isNotEmpty()) {
  4914. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4915. }
  4916. }else {
  4917. // 获取所有分镜的配音视频,按 segment_number 排序
  4918. $segments = DB::table('mp_episode_segments')
  4919. ->where('anime_id', $animeId)
  4920. ->where('episode_id', $episodeId)
  4921. ->orderBy('segment_number')
  4922. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4923. ->get();
  4924. // 检查是否所有分镜都有配音和视频
  4925. $missingVideos = $segments->filter(function($segment) {
  4926. return empty($segment->audio_url) || empty($segment->video_url);
  4927. });
  4928. if ($missingVideos->isNotEmpty()) {
  4929. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4930. }
  4931. }
  4932. if ($segments->isEmpty()) {
  4933. Utils::throwError('20003:未找到该剧集的分镜数据');
  4934. }
  4935. // 获取当前完整视频url
  4936. $completeVideoUrl = DB::table('mp_anime_episodes')
  4937. ->where('anime_id', $animeId)
  4938. ->where('id', $episodeId)
  4939. ->value('complete_video_url');
  4940. // 构建 generate_json
  4941. $generateJson = [];
  4942. $sequence = 1;
  4943. foreach ($segments as $segment) {
  4944. if ((int)$ace_mode === 1) {
  4945. $generateJson[] = [
  4946. 'sequence' => $sequence++,
  4947. 'video_url' => $segment->video_url,
  4948. 'video_time_point_start' => $segment->video_time_point_start,
  4949. 'video_time_point_end' => $segment->video_time_point_end
  4950. ];
  4951. }else {
  4952. $generateJson[] = [
  4953. 'sequence' => $sequence++,
  4954. 'video_url' => $segment->video_url,
  4955. 'audio_url' => $segment->audio_url,
  4956. 'video_time_point_start' => $segment->video_time_point_start,
  4957. 'video_time_point_end' => $segment->video_time_point_end
  4958. ];
  4959. }
  4960. }
  4961. // 创建任务
  4962. $now = date('Y-m-d H:i:s');
  4963. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4964. 'anime_id' => $animeId,
  4965. 'episode_id' => $episodeId,
  4966. 'generate_json' => json_encode($generateJson, 256),
  4967. 'generate_status' => '执行中',
  4968. 'complete_video_url' => '',
  4969. 'created_at' => $now,
  4970. 'updated_at' => $now
  4971. ]);
  4972. if (!$taskId) {
  4973. Utils::throwError('20003:创建任务失败');
  4974. }
  4975. // 更新剧集表的任务ID和状态
  4976. $boolen = DB::table('mp_anime_episodes')
  4977. ->where('anime_id', $animeId)
  4978. ->where('id', $episodeId)
  4979. ->update([
  4980. 'complete_video_task_id' => $taskId,
  4981. 'complete_video_task_status' => '执行中',
  4982. 'updated_at' => $now
  4983. ]);
  4984. if (!$boolen) {
  4985. Utils::throwError('20003:更新剧集表失败');
  4986. }
  4987. dLog('anime')->info('创建完整视频合成任务', [
  4988. 'task_id' => $taskId,
  4989. 'anime_id' => $animeId,
  4990. 'episode_id' => $episodeId,
  4991. 'segment_count' => count($generateJson)
  4992. ]);
  4993. // 请求远程服务器执行生成
  4994. $client = new Client(['timeout' => 600, 'verify' => false]);
  4995. try {
  4996. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4997. $response = $result->getBody()->getContents();
  4998. $response_arr = json_decode($response, true);
  4999. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5000. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5001. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5002. // // 更新任务状态为失败
  5003. // DB::table('mp_complete_video_tasks')
  5004. // ->where('id', $taskId)
  5005. // ->update([
  5006. // 'generate_status' => '执行失败',
  5007. // 'error_message' => $error_msg,
  5008. // 'updated_at' => date('Y-m-d H:i:s')
  5009. // ]);
  5010. // // 同步更新剧集表状态
  5011. // DB::table('mp_anime_episodes')
  5012. // ->where('complete_video_task_id', $taskId)
  5013. // ->update([
  5014. // 'complete_video_task_status' => '执行失败',
  5015. // 'updated_at' => date('Y-m-d H:i:s')
  5016. // ]);
  5017. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5018. }
  5019. } catch (\Exception $e) {
  5020. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5021. // 更新任务状态为失败
  5022. DB::table('mp_complete_video_tasks')
  5023. ->where('id', $taskId)
  5024. ->update([
  5025. 'generate_status' => '执行失败',
  5026. 'error_message' => $e->getMessage(),
  5027. 'updated_at' => date('Y-m-d H:i:s')
  5028. ]);
  5029. // 同步更新剧集表状态
  5030. DB::table('mp_anime_episodes')
  5031. ->where('complete_video_task_id', $taskId)
  5032. ->update([
  5033. 'complete_video_task_status' => '执行失败',
  5034. 'updated_at' => date('Y-m-d H:i:s')
  5035. ]);
  5036. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5037. }
  5038. // 开始轮询任务状态
  5039. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5040. $pollInterval = 5; // 每5秒轮询一次
  5041. $attempt = 0;
  5042. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5043. while ($attempt < $maxAttempts) {
  5044. sleep($pollInterval);
  5045. $attempt++;
  5046. // 查询任务状态
  5047. $task = DB::table('mp_complete_video_tasks')
  5048. ->where('id', $taskId)
  5049. ->first();
  5050. if (!$task) {
  5051. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5052. Utils::throwError('20003:任务不存在');
  5053. }
  5054. dLog('anime')->info('轮询任务状态', [
  5055. 'task_id' => $taskId,
  5056. 'attempt' => $attempt,
  5057. 'status' => $task->generate_status
  5058. ]);
  5059. // 检查任务是否完成
  5060. if ($task->generate_status === '执行成功') {
  5061. // 同步更新剧集表状态
  5062. $boolen3 = DB::table('mp_anime_episodes')
  5063. ->where('anime_id', $animeId)
  5064. ->where('id', $episodeId)
  5065. ->update([
  5066. 'complete_video_url' => $task->complete_video_url,
  5067. 'complete_video_task_status' => '执行成功',
  5068. 'updated_at' => date('Y-m-d H:i:s')
  5069. ]);
  5070. dLog('anime')->info('视频合成任务完成', [
  5071. 'task_id' => $taskId,
  5072. 'video_url' => $task->complete_video_url,
  5073. 'attempts' => $attempt
  5074. ]);
  5075. // 如果更新成功则远程删除之前的文件
  5076. if ($boolen3 && $completeVideoUrl) {
  5077. $encode_url = urlencode($completeVideoUrl);
  5078. $client = new Client(['timeout' => 300, 'verify' => false]);
  5079. // 根据ID通过API通知合成音频
  5080. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5081. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5082. $response = $result->getBody()->getContents();
  5083. $response_arr = json_decode($response, true);
  5084. Log::info('火山删除音频返回: '.$response);
  5085. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5086. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5087. Log::info('火山删除音频失败: '.$error_msg);
  5088. // Utils::throwError('20003:火山删除音频失败');
  5089. }
  5090. }
  5091. return [
  5092. 'task_id' => $taskId,
  5093. 'anime_id' => $animeId,
  5094. 'episode_id' => $episodeId,
  5095. 'segment_count' => count($generateJson),
  5096. 'generate_status' => '执行成功',
  5097. 'complete_video_url' => $task->complete_video_url,
  5098. ];
  5099. }
  5100. // 检查任务是否失败
  5101. if ($task->generate_status === '执行失败') {
  5102. // 同步更新剧集表状态
  5103. DB::table('mp_anime_episodes')
  5104. ->where('anime_id', $animeId)
  5105. ->where('id', $episodeId)
  5106. ->update([
  5107. 'complete_video_task_status' => '执行失败',
  5108. 'updated_at' => date('Y-m-d H:i:s')
  5109. ]);
  5110. $errorMessage = $task->error_message ?? '未知错误';
  5111. dLog('anime')->error('视频合成任务失败', [
  5112. 'task_id' => $taskId,
  5113. 'error' => $errorMessage,
  5114. 'attempts' => $attempt
  5115. ]);
  5116. return [
  5117. 'task_id' => $taskId,
  5118. 'anime_id' => $animeId,
  5119. 'episode_id' => $episodeId,
  5120. 'segment_count' => count($generateJson),
  5121. 'generate_status' => '执行失败',
  5122. 'error_message' => $errorMessage
  5123. ];
  5124. }
  5125. }
  5126. // 超时处理
  5127. dLog('anime')->warning('视频合成任务超时', [
  5128. 'task_id' => $taskId,
  5129. 'max_attempts' => $maxAttempts,
  5130. 'timeout_seconds' => $maxAttempts * $pollInterval
  5131. ]);
  5132. // 更新任务状态为超时
  5133. DB::table('mp_complete_video_tasks')
  5134. ->where('id', $taskId)
  5135. ->update([
  5136. 'generate_status' => '超时',
  5137. 'error_message' => '任务执行超时(5分钟)',
  5138. 'updated_at' => date('Y-m-d H:i:s')
  5139. ]);
  5140. return [
  5141. 'task_id' => $taskId,
  5142. 'anime_id' => $animeId,
  5143. 'episode_id' => $episodeId,
  5144. 'segment_count' => count($generateJson),
  5145. 'generate_status' => '超时',
  5146. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5147. ];
  5148. }
  5149. /**
  5150. * 根据 inner_prompt_type 附加内置提示词
  5151. *
  5152. * @param string $prompt 用户提示词
  5153. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5154. * @return string 合并后的提示词
  5155. */
  5156. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5157. {
  5158. $innerPromptMap = [
  5159. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5160. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5161. ];
  5162. if (!isset($innerPromptMap[$innerPromptType])) {
  5163. return $prompt;
  5164. }
  5165. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5166. }
  5167. /**
  5168. * 根据 inner_prompt_type 获取生成图片数量
  5169. *
  5170. * @param int $innerPromptType 内置提示词类型
  5171. * @param int $imageNum 传入的图片张数
  5172. * @return int 图片数量
  5173. */
  5174. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5175. {
  5176. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5177. }
  5178. /**
  5179. * 提取图片生成结果URL
  5180. *
  5181. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5182. * @param int $innerPromptType 内置提示词类型
  5183. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5184. */
  5185. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5186. {
  5187. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5188. if (is_array($resultUrls) && !empty($resultUrls)) {
  5189. $resultUrls = array_values($resultUrls);
  5190. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5191. }
  5192. if (!empty($resultUrl)) {
  5193. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5194. }
  5195. return (int)$innerPromptType === 2 ? [] : '';
  5196. }
  5197. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5198. $prompt = getProp($data, 'prompt');
  5199. $episode_id = getProp($data, 'episode_id');
  5200. $ref_img_urls = getProp($data, 'ref_img_urls');
  5201. $ratio = getProp($data, 'ratio', '9:16');
  5202. $resolution = getProp($data, 'resolution', '2k');
  5203. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5204. $imageNum = (int)getProp($data, 'image_num', 1);
  5205. // 定义分辨率和宽高比对应的尺寸映射表
  5206. $sizeMap = [
  5207. '2k' => [
  5208. '1:1' => ['width' => 2048, 'height' => 2048],
  5209. '4:3' => ['width' => 2304, 'height' => 1728],
  5210. '3:4' => ['width' => 1728, 'height' => 2304],
  5211. '16:9' => ['width' => 2848, 'height' => 1600],
  5212. '9:16' => ['width' => 1600, 'height' => 2848],
  5213. '3:2' => ['width' => 2496, 'height' => 1664],
  5214. '2:3' => ['width' => 1664, 'height' => 2496],
  5215. '21:9' => ['width' => 3136, 'height' => 1344],
  5216. ],
  5217. '3k' => [
  5218. '1:1' => ['width' => 3072, 'height' => 3072],
  5219. '4:3' => ['width' => 3456, 'height' => 2592],
  5220. '3:4' => ['width' => 2592, 'height' => 3456],
  5221. '16:9' => ['width' => 4096, 'height' => 2304],
  5222. '9:16' => ['width' => 2304, 'height' => 4096],
  5223. '2:3' => ['width' => 2496, 'height' => 3744],
  5224. '3:2' => ['width' => 3744, 'height' => 2496],
  5225. '21:9' => ['width' => 4704, 'height' => 2016],
  5226. ],
  5227. '4k' => [
  5228. '1:1' => ['width' => 4096, 'height' => 4096],
  5229. '3:4' => ['width' => 3520, 'height' => 4704],
  5230. '4:3' => ['width' => 4704, 'height' => 3520],
  5231. '16:9' => ['width' => 5504, 'height' => 3040],
  5232. '9:16' => ['width' => 3040, 'height' => 5504],
  5233. '2:3' => ['width' => 3328, 'height' => 4992],
  5234. '3:2' => ['width' => 4992, 'height' => 3328],
  5235. '21:9' => ['width' => 6240, 'height' => 2656],
  5236. ],
  5237. ];
  5238. // 参数验证
  5239. $resolution = strtolower($resolution);
  5240. if (!isset($sizeMap[$resolution])) {
  5241. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5242. }
  5243. if (!isset($sizeMap[$resolution][$ratio])) {
  5244. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5245. }
  5246. // 根据 ratio 和 resolution 确定宽高
  5247. $width = $sizeMap[$resolution][$ratio]['width'];
  5248. $height = $sizeMap[$resolution][$ratio]['height'];
  5249. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5250. if (is_json($ref_img_urls)) {
  5251. $ref_img_urls = json_decode($ref_img_urls, true);
  5252. }else {
  5253. $ref_img_urls = explode(',', $ref_img_urls);
  5254. }
  5255. }
  5256. // 处理图片模型
  5257. $model = getProp($data, 'model');
  5258. if (!$model) {
  5259. // 用户没有输入,从episode表获取
  5260. if ($episode_id) {
  5261. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5262. $model = getProp($episode, 'image_model');
  5263. }
  5264. if (!$model) {
  5265. // episode表也没有,使用默认值
  5266. $model = 'doubao-seedream-5-0-lite-260128';
  5267. }
  5268. }
  5269. // 验证模型是否在可用模型表中
  5270. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5271. // $model = 'doubao-seedream-5-0-lite-260128';
  5272. Utils::throwError('20003:该模型已不可用,请更换!');
  5273. }
  5274. // 保存到episode表
  5275. if ($episode_id) {
  5276. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5277. 'image_model' => $model,
  5278. 'updated_at' => date('Y-m-d H:i:s')
  5279. ]);
  5280. }
  5281. // 参数验证
  5282. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5283. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5284. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5285. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5286. try {
  5287. // 创建图片生成任务
  5288. $params = [
  5289. 'prompt' => $prompt,
  5290. 'model' => $model,
  5291. 'ref_img_urls' => '',
  5292. 'width' => $width,
  5293. 'height' => $height,
  5294. 'image_num' => $imageNum
  5295. ];
  5296. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5297. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5298. $task_id = $task->id;
  5299. if (!$task_id) {
  5300. Utils::throwError('20003:创建图片生成任务失败');
  5301. }
  5302. // 创建任务中心记录并关联图片任务ID
  5303. $taskCenter = $this->taskCenterService->createTask('image', [
  5304. 'title' => '文生图',
  5305. 'ref_task_id' => $task_id,
  5306. // 'prompt' => $prompt,
  5307. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5308. ]);
  5309. $taskCenterId = $taskCenter->id;
  5310. // 组装本次任务信息(用于init消息,类似generateVideo)
  5311. $taskInfo = [
  5312. 'task_id' => $task_id,
  5313. 'status' => getProp($task, 'status', 'processing'),
  5314. 'model' => $model,
  5315. 'ratio' => $ratio,
  5316. 'resolution' => $resolution,
  5317. 'image_num' => $imageNum,
  5318. ];
  5319. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5320. if (is_callable($onTaskCreated)) {
  5321. $onTaskCreated($taskCenterId, $taskInfo);
  5322. }
  5323. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5324. $model = getProp($task, 'model');
  5325. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5326. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5327. $isSyncModel = $isVolcModel || $isGptModel;
  5328. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5329. $start_time = time();
  5330. $timeout = 300; // 5分钟
  5331. $img_url = '';
  5332. $img_urls = [];
  5333. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5334. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5335. while (time() - $start_time < $timeout) {
  5336. sleep(3);
  5337. // 每分钟发送一次队列状态消息(仅流式模式)
  5338. if (is_callable($onPoll)) {
  5339. $currentTime = time();
  5340. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5341. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5342. $lastQueueMessageTime = $currentTime;
  5343. }
  5344. }
  5345. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5346. if ($isSyncModel) {
  5347. // 刷新任务状态
  5348. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5349. if ($task->status === 'success' && $task->result_url) {
  5350. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5351. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5352. if (!empty($resultUrls)) {
  5353. $img_urls = $resultUrls;
  5354. $img_url = $resultUrls[0];
  5355. } else {
  5356. $img_url = (string)$task->result_url;
  5357. }
  5358. break;
  5359. } elseif ($task->status === 'failed') {
  5360. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5361. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5362. }
  5363. // // 如果还在处理中,提示用户稍后查看
  5364. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5365. }else {
  5366. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5367. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5368. if ($statusInfo['status'] === 'success') {
  5369. $task->updateStatus('success', [
  5370. 'result_url' => $statusInfo['result_url'],
  5371. 'result_json' => $statusInfo['result_json'] ?? []
  5372. ]);
  5373. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5374. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5375. if (!empty($resultUrls)) {
  5376. $img_urls = $resultUrls;
  5377. $img_url = $resultUrls[0];
  5378. } else {
  5379. $img_url = (string)$statusInfo['result_url'];
  5380. }
  5381. break;
  5382. } elseif ($statusInfo['status'] === 'failed') {
  5383. $task->updateStatus('failed', [
  5384. 'error_message' => $statusInfo['error_message'],
  5385. 'result_json' => $statusInfo['result_json'] ?? []
  5386. ]);
  5387. dLog('anime')->error('图片生成失败,', [
  5388. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5389. ]);
  5390. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5391. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5392. }
  5393. }
  5394. }
  5395. if (empty($img_url)) {
  5396. Utils::throwError('20003:图片生成超时,请稍后重试');
  5397. }
  5398. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5399. if (count($img_urls) > 1) {
  5400. return [
  5401. 'img_url' => $img_url,
  5402. 'image_urls' => $img_urls,
  5403. 'task_id' => $taskCenterId,
  5404. ];
  5405. }
  5406. return [
  5407. 'img_url' => $img_url,
  5408. 'task_id' => $taskCenterId,
  5409. ];
  5410. } catch (\Exception $e) {
  5411. dLog('anime')->error('更新角色或场景失败', [
  5412. 'error' => $e->getMessage()
  5413. ]);
  5414. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5415. Utils::throwError('20003:' . $e->getMessage());
  5416. }
  5417. }
  5418. /**
  5419. * 使用文生文模型解析分镜内容
  5420. */
  5421. private function parseSegmentContentWithAI($segment_content) {
  5422. try {
  5423. // 使用DeepSeek服务的公开方法解析分镜内容
  5424. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5425. } catch (\Exception $e) {
  5426. // 如果AI解析失败,记录日志并返回原内容
  5427. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5428. return $segment_content;
  5429. }
  5430. }
  5431. /**
  5432. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5433. *
  5434. * @param int $episode_id 分集ID
  5435. * @param int $anime_id 动漫ID
  5436. * @param array $roles 分集角色数组(引用传递)
  5437. * @param array $scenes 分集场景数组(引用传递)
  5438. * @param array $episode 分集数据
  5439. */
  5440. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5441. // 获取全局动漫的角色和场景数据
  5442. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5443. if (!$anime) return;
  5444. $art_style_type = getProp($anime, 'art_style_type');
  5445. $character_prefix = '';
  5446. $scene_prefix = '';
  5447. if ($art_style_type) {
  5448. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5449. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5450. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5451. }
  5452. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5453. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5454. $roles_updated = false;
  5455. $scenes_updated = false;
  5456. // 处理角色
  5457. foreach ($roles as &$role) {
  5458. $role_name = getProp($role, 'role');
  5459. $role_description = getProp($role, 'description');
  5460. $role_pic_prompt = getProp($role, 'pic_prompt');
  5461. $role_url = getProp($role, 'url');
  5462. $role_task_id = getProp($role, 'task_id');
  5463. // 如果已有URL或已有任务ID,跳过
  5464. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5465. continue;
  5466. }
  5467. $url_inherited = false;
  5468. // 尝试从全局数据中继承
  5469. foreach ($global_roles as $global_role) {
  5470. $global_role_name = getProp($global_role, 'role');
  5471. $global_role_description = getProp($global_role, 'description');
  5472. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5473. $global_role_url = getProp($global_role, 'url');
  5474. $global_role_task_id = getProp($global_role, 'task_id');
  5475. $global_role_task_status = getProp($global_role, 'task_status');
  5476. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5477. if ($role_name === $global_role_name
  5478. && $role_description === $global_role_description
  5479. && $role_pic_prompt === $global_role_pic_prompt
  5480. && !empty($global_role_url)) {
  5481. // 继承 task_id、task_status 和 url
  5482. $role['task_id'] = $global_role_task_id;
  5483. $role['task_status'] = $global_role_task_status;
  5484. $role['url'] = $global_role_url;
  5485. $roles_updated = true;
  5486. $url_inherited = true;
  5487. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5488. break;
  5489. }
  5490. }
  5491. // 如果无法继承且没有任务ID,创建新任务
  5492. if (!$url_inherited && empty($role_task_id)) {
  5493. try {
  5494. $art_style = getProp($episode, 'art_style');
  5495. // 优先使用 pic_prompt,如果没有则使用 description
  5496. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5497. // if ($art_style) {
  5498. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5499. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5500. // }
  5501. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5502. $params = [
  5503. 'prompt' => $description,
  5504. 'ref_img_urls' => []
  5505. ];
  5506. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5507. $task_id = $task->id;
  5508. if ($task_id) {
  5509. $role['task_id'] = $task_id;
  5510. $role['task_status'] = 'processing';
  5511. $roles_updated = true;
  5512. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5513. }
  5514. } catch (\Exception $e) {
  5515. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5516. }
  5517. }
  5518. }
  5519. // 处理场景
  5520. foreach ($scenes as &$scene) {
  5521. $scene_name = getProp($scene, 'scene');
  5522. $scene_description = getProp($scene, 'description');
  5523. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5524. $scene_url = getProp($scene, 'url');
  5525. $scene_task_id = getProp($scene, 'task_id');
  5526. // 如果已有URL或已有任务ID,跳过
  5527. if (!empty($scene_url) || !empty($scene_task_id)) {
  5528. continue;
  5529. }
  5530. $url_inherited = false;
  5531. // 尝试从全局数据中继承
  5532. foreach ($global_scenes as $global_scene) {
  5533. $global_scene_name = getProp($global_scene, 'scene');
  5534. $global_scene_description = getProp($global_scene, 'description');
  5535. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5536. $global_scene_url = getProp($global_scene, 'url');
  5537. $global_scene_task_id = getProp($global_scene, 'task_id');
  5538. $global_scene_task_status = getProp($global_scene, 'task_status');
  5539. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5540. if ($scene_name === $global_scene_name
  5541. && $scene_description === $global_scene_description
  5542. && $scene_pic_prompt === $global_scene_pic_prompt
  5543. && !empty($global_scene_url)) {
  5544. // 继承 task_id、task_status 和 url
  5545. $scene['task_id'] = $global_scene_task_id;
  5546. $scene['task_status'] = $global_scene_task_status;
  5547. $scene['url'] = $global_scene_url;
  5548. $scenes_updated = true;
  5549. $url_inherited = true;
  5550. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5551. break;
  5552. }
  5553. }
  5554. // 如果无法继承且没有任务ID,创建新任务
  5555. if (!$url_inherited && empty($scene_task_id)) {
  5556. try {
  5557. $art_style = getProp($episode, 'art_style');
  5558. // 优先使用 pic_prompt,如果没有则使用 description
  5559. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5560. // if ($art_style) {
  5561. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5562. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5563. // }
  5564. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5565. $params = [
  5566. 'prompt' => $description,
  5567. 'ref_img_urls' => []
  5568. ];
  5569. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5570. $task_id = $task->id;
  5571. if ($task_id) {
  5572. $scene['task_id'] = $task_id;
  5573. $scene['task_status'] = 'processing';
  5574. $scenes_updated = true;
  5575. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5576. }
  5577. } catch (\Exception $e) {
  5578. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5579. }
  5580. }
  5581. }
  5582. // 如果有更新,保存到数据库
  5583. if ($roles_updated || $scenes_updated) {
  5584. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5585. if ($roles_updated) {
  5586. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5587. }
  5588. if ($scenes_updated) {
  5589. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5590. }
  5591. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5592. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5593. }
  5594. }
  5595. /**
  5596. * 根据图片URL使用AI反推图片提示词
  5597. *
  5598. * @param string $img_url 图片URL
  5599. * @return string 反推的提示词
  5600. */
  5601. private function generateImagePromptFromUrl($img_url) {
  5602. try {
  5603. // 获取默认模型
  5604. $model = 'doubao-seed-2-0-mini-260215';
  5605. // 构建messages参数
  5606. $messages = [
  5607. [
  5608. 'role' => 'user',
  5609. 'content' => [
  5610. [
  5611. 'type' => 'text',
  5612. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5613. ],
  5614. [
  5615. 'type' => 'image_url',
  5616. 'image_url' => [
  5617. 'url' => $img_url
  5618. ]
  5619. ]
  5620. ]
  5621. ]
  5622. ];
  5623. // 构建请求参数
  5624. $params = [
  5625. 'model' => $model,
  5626. 'messages' => $messages,
  5627. 'stream' => false,
  5628. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5629. ];
  5630. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5631. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5632. // 仅记录 token 使用明细(不扣积分)
  5633. $uid = 0;
  5634. try {
  5635. $uid = (int)Site::getUid();
  5636. } catch (\Throwable $e) {
  5637. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5638. }
  5639. $this->pointsService->recordTokenOnlyDetail(
  5640. $uid,
  5641. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5642. [
  5643. 'model' => $model,
  5644. 'img_url' => $img_url,
  5645. 'source' => 'generateImagePromptFromUrl',
  5646. ],
  5647. 'chat',
  5648. $model,
  5649. ''
  5650. );
  5651. // 返回生成的内容
  5652. return getProp($result, 'fullContent', '图片描述生成失败');
  5653. } catch (\Exception $e) {
  5654. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5655. 'img_url' => $img_url
  5656. ]);
  5657. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5658. 'error' => $e->getMessage(),
  5659. 'img_url' => $img_url
  5660. ]);
  5661. return '图片描述生成失败: ' . $e->getMessage();
  5662. }
  5663. }
  5664. /**
  5665. * 音频试听接口
  5666. * 创建音频任务并轮询获取结果
  5667. *
  5668. * @param array $data 参数数组
  5669. * @return array 返回音频URL或错误信息
  5670. */
  5671. public function previewAudio($data) {
  5672. $dialogue = getProp($data, 'dialogue');
  5673. // 必填参数验证
  5674. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5675. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5676. $voice_type = getProp($data, 'voice_type');
  5677. $voice_name = getProp($data, 'voice_name');
  5678. $voice_actor = getProp($data, 'voice_actor');
  5679. $emotion_type = getProp($data, 'emotion_type');
  5680. $gender = getProp($data, 'gender', 0);
  5681. $emotion = getProp($data, 'emotion');
  5682. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5683. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5684. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5685. $pitch = getProp($data, 'pitch', 0);
  5686. try {
  5687. $now = date('Y-m-d H:i:s');
  5688. // 构建生成参数
  5689. $generate_json = json_encode([
  5690. 'text' => $dialogue,
  5691. 'role' => $voice_actor,
  5692. 'voice_type' => $voice_type,
  5693. 'voice_name' => $voice_name,
  5694. 'emotion' => $emotion,
  5695. 'emotion_type' => $emotion_type,
  5696. 'gender' => $gender,
  5697. 'speed_ratio' => $speed_ratio,
  5698. 'loudness_ratio' => $loudness_ratio,
  5699. 'emotion_scale' => $emotion_scale,
  5700. 'pitch' => $pitch,
  5701. ], 256);
  5702. // 请求远程服务器执行生成
  5703. $client = new Client(['timeout' => 600, 'verify' => false]);
  5704. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5705. $response = $result->getBody()->getContents();
  5706. $response_arr = json_decode($response, true);
  5707. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5708. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5709. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5710. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5711. }
  5712. $arr = $response_arr['data'];
  5713. $subtitle_info = $arr['subtitle_info'];
  5714. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5715. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5716. return [
  5717. 'audio_url' => $arr['url'],
  5718. 'subtitle_info' => $subtitle_info,
  5719. 'audio_duration' => round($audio_duration, 2)
  5720. ];
  5721. } catch (\Exception $e) {
  5722. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5723. Utils::throwError('20003:' . $e->getMessage());
  5724. }
  5725. }
  5726. /**
  5727. * 获取角色库列表(支持文件夹递归查询)
  5728. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5729. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5730. */
  5731. public function globalProducts($data) {
  5732. $uid = Site::getUid();
  5733. $cpid = Site::getCpid();
  5734. $role = Site::getRole();
  5735. $id = getProp($data, 'id', 0);
  5736. $parent_id = getProp($data, 'parent_id', 0);
  5737. $product_name = getProp($data, 'product_name');
  5738. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5739. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5740. if (!$product) {
  5741. Utils::throwError('20003:请选择产品类型');
  5742. }
  5743. // 根据角色和is_public参数确定查询范围
  5744. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5745. // user角色:根据is_public参数筛选
  5746. $query_user_ids = [];
  5747. if ($role === 'admin') {
  5748. // admin获取所有个人库和公共库
  5749. $query_user_ids = [$uid, 0];
  5750. } else {
  5751. // user角色根据is_public参数筛选
  5752. if ($is_public == 2) {
  5753. // 个人库+公共库
  5754. $query_user_ids = [$uid, 0];
  5755. } elseif ($is_public == 0) {
  5756. // 仅个人库
  5757. $query_user_ids = [$uid];
  5758. } elseif ($is_public == 1) {
  5759. // 仅公共库
  5760. $query_user_ids = [0];
  5761. }
  5762. }
  5763. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5764. if ($id || $product_name) {
  5765. $query = DB::table('mp_products')
  5766. ->where('cpid', $cpid)
  5767. ->whereIn('user_id', $query_user_ids)
  5768. ->where('is_deleted', 0);
  5769. // 如果指定了 id,按 id 精确查询
  5770. if ($id) {
  5771. $query->where('id', $id);
  5772. }
  5773. // 如果指定了 product_name,按名称模糊查询
  5774. if ($product_name) {
  5775. $query->where('product_name', 'like', "%{$product_name}%");
  5776. }
  5777. // 如果指定了 product,添加筛选条件
  5778. if ($product) {
  5779. $query->where('product', $product);
  5780. }
  5781. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5782. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5783. ->get()
  5784. ->map(function($value) {
  5785. $value = (array)$value;
  5786. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5787. $value['type'] = (int)$value['type'];
  5788. $value['parent_id'] = (int)$value['parent_id'];
  5789. $value['level'] = (int)$value['level'];
  5790. $value['product'] = (int)($value['product'] ?? 1);
  5791. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5792. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5793. unset($value['user_id']);
  5794. return $value;
  5795. })
  5796. ->toArray();
  5797. return $result;
  5798. }
  5799. // 递归获取所有子目录和角色
  5800. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5801. }
  5802. /**
  5803. * 递归获取指定目录下的所有子目录和角色
  5804. * @param int $cpid 公司ID
  5805. * @param int $parent_id 父目录ID
  5806. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5807. * @param array $query_user_ids 用户ID数组(支持多个)
  5808. * @param int $current_uid 当前用户ID(用于排序)
  5809. * @return array
  5810. */
  5811. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5812. // 查询当前层级的所有项(文件夹和角色)
  5813. $query = DB::table('mp_products')
  5814. ->where('cpid', $cpid)
  5815. ->where('is_deleted', 0)
  5816. ->where('parent_id', $parent_id);
  5817. // 添加用户ID验证(支持多个user_id)
  5818. if (!empty($query_user_ids)) {
  5819. $query->whereIn('user_id', $query_user_ids);
  5820. }
  5821. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5822. if ($product) {
  5823. $query->where('product', $product);
  5824. }
  5825. // 排序规则:
  5826. // 1. 文件夹在前(type DESC)
  5827. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5828. // 3. 其他排序规则
  5829. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5830. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5831. ->get();
  5832. $result = [];
  5833. foreach ($items as $item) {
  5834. $itemArray = [
  5835. 'id' => $item->id,
  5836. 'type' => (int)$item->type,
  5837. 'parent_id' => (int)$item->parent_id,
  5838. 'level' => (int)$item->level,
  5839. 'product_name' => $item->product_name,
  5840. 'url' => $item->url,
  5841. 'pic_prompt' => $item->pic_prompt ?? '',
  5842. 'three_view_image_url' => $item->three_view_image_url,
  5843. 'product' => (int)($item->product ?? 1),
  5844. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5845. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5846. ];
  5847. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5848. // 如果是文件夹,递归获取其子项
  5849. if ($item->type == 2) {
  5850. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5851. if (!empty($children)) {
  5852. $itemArray['children'] = $children;
  5853. }
  5854. }
  5855. $result[] = $itemArray;
  5856. }
  5857. return $result;
  5858. }
  5859. /**
  5860. * 创建文件夹
  5861. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5862. * @return int 返回新建文件夹ID
  5863. */
  5864. public function createFolder($data) {
  5865. $uid = Site::getUid();
  5866. $cpid = Site::getCpid();
  5867. $role = Site::getRole();
  5868. $parent_id = getProp($data, 'parent_id', 0);
  5869. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5870. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5871. // 如果是公共库操作,需要admin权限
  5872. if ($is_public && $role !== 'admin') {
  5873. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5874. }
  5875. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5876. $store_uid = $is_public ? 0 : $uid;
  5877. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5878. $product = getProp($data, 'product');
  5879. if (!in_array($product, [1, 2, 3])) {
  5880. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5881. }
  5882. // 验证父文件夹
  5883. $parent_level = 0;
  5884. if ($parent_id > 0) {
  5885. $parent = DB::table('mp_products')
  5886. ->where('id', $parent_id)
  5887. ->where('cpid', $cpid)
  5888. ->where('user_id', $store_uid)
  5889. ->where('type', 2)
  5890. ->where('is_deleted', 0)
  5891. ->first();
  5892. if (!$parent) {
  5893. Utils::throwError('20003:父文件夹不存在');
  5894. }
  5895. // 检查父文件夹的 product 类型是否一致
  5896. if ($parent->product != $product) {
  5897. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5898. }
  5899. $parent_level = $parent->level;
  5900. // 检查层级限制(最多3层)
  5901. if ($parent_level >= 3) {
  5902. Utils::throwError('20003:文件夹层级不能超过3层');
  5903. }
  5904. }
  5905. // 检查当前目录下是否已存在空白文件夹
  5906. $empty_folder_exists = DB::table('mp_products')
  5907. ->where('parent_id', $parent_id)
  5908. ->where('cpid', $cpid)
  5909. ->where('user_id', $store_uid)
  5910. ->where('type', 2)
  5911. ->where('product', $product)
  5912. ->where('product_name', '新建文件夹')
  5913. ->where('is_deleted', 0)
  5914. ->exists();
  5915. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5916. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5917. }
  5918. // 创建文件夹
  5919. $folder_id = DB::table('mp_products')->insertGetId([
  5920. 'user_id' => $store_uid,
  5921. 'cpid' => $cpid,
  5922. 'type' => 2,
  5923. 'parent_id' => $parent_id,
  5924. 'level' => $parent_level + 1,
  5925. 'product_name' => $folder_name,
  5926. 'product' => $product,
  5927. 'sort_order' => time(), // 使用时间戳作为排序权重
  5928. 'is_deleted' => 0,
  5929. 'created_at' => date('Y-m-d H:i:s'),
  5930. 'updated_at' => date('Y-m-d H:i:s')
  5931. ]);
  5932. return [
  5933. 'id' => $folder_id,
  5934. 'type' => 2,
  5935. 'parent_id' => $parent_id,
  5936. 'level' => $parent_level + 1,
  5937. 'product_name' => $folder_name,
  5938. 'product' => $product,
  5939. ];
  5940. }
  5941. /**
  5942. * 重命名文件夹或角色
  5943. * @param array $data 包含 id、product_name(新名称)
  5944. * @return bool
  5945. */
  5946. public function renameFolder($data) {
  5947. $uid = Site::getUid();
  5948. $cpid = Site::getCpid();
  5949. $role = Site::getRole();
  5950. $id = getProp($data, 'id');
  5951. $new_name = getProp($data, 'product_name');
  5952. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5953. if (!$id || !$new_name) {
  5954. Utils::throwError('20003:参数不完整');
  5955. }
  5956. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5957. $query_uid = $is_public ? 0 : $uid;
  5958. // 如果是公共库操作,需要admin权限
  5959. if ($is_public && $role !== 'admin') {
  5960. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5961. }
  5962. // 检查是否存在
  5963. $item = DB::table('mp_products')
  5964. ->where('id', $id)
  5965. ->where('cpid', $cpid)
  5966. ->where('user_id', $query_uid)
  5967. ->where('is_deleted', 0)
  5968. ->first();
  5969. if (!$item) {
  5970. Utils::throwError('20003:项目不存在');
  5971. }
  5972. return DB::table('mp_products')
  5973. ->where('id', $id)
  5974. ->where('cpid', $cpid)
  5975. ->where('user_id', $query_uid)
  5976. ->update([
  5977. 'product_name' => $new_name,
  5978. 'updated_at' => date('Y-m-d H:i:s')
  5979. ]);
  5980. }
  5981. /**
  5982. * 移动角色或文件夹到指定文件夹
  5983. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5984. * @return bool
  5985. */
  5986. public function moveProductOrFolder($data) {
  5987. $uid = Site::getUid();
  5988. $cpid = Site::getCpid();
  5989. $role = Site::getRole();
  5990. $id = getProp($data, 'id');
  5991. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5992. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5993. if (!$id) {
  5994. Utils::throwError('20003:请选择要移动的项目');
  5995. }
  5996. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5997. $query_uid = $is_public ? 0 : $uid;
  5998. // 如果是公共库操作,需要admin权限
  5999. if ($is_public && $role !== 'admin') {
  6000. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6001. }
  6002. // 检查要移动的项目
  6003. $item = DB::table('mp_products')
  6004. ->where('id', $id)
  6005. ->where('cpid', $cpid)
  6006. ->where('user_id', $query_uid)
  6007. ->where('is_deleted', 0)
  6008. ->first();
  6009. if (!$item) {
  6010. Utils::throwError('20003:项目不存在');
  6011. }
  6012. // 验证目标文件夹
  6013. $target_level = 0;
  6014. $target_product = $item->product; // 默认使用当前项目的 product
  6015. if ($target_parent_id > 0) {
  6016. $target_parent = DB::table('mp_products')
  6017. ->where('id', $target_parent_id)
  6018. ->where('cpid', $cpid)
  6019. ->where('user_id', $query_uid)
  6020. ->where('type', 2)
  6021. ->where('is_deleted', 0)
  6022. ->first();
  6023. if (!$target_parent) {
  6024. Utils::throwError('20003:目标文件夹不存在');
  6025. }
  6026. // 检查 product 类型是否一致
  6027. if ($target_parent->product != $item->product) {
  6028. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6029. }
  6030. $target_level = $target_parent->level;
  6031. $target_product = $target_parent->product;
  6032. // 如果移动的是文件夹,需要检查层级
  6033. if ($item->type == 2) {
  6034. // 计算移动后的最大层级
  6035. $max_child_level = $this->getMaxChildLevel($id);
  6036. $depth = $max_child_level - $item->level;
  6037. if ($target_level + 1 + $depth > 3) {
  6038. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6039. }
  6040. // 不能移动到自己或自己的子文件夹下
  6041. if ($this->isDescendant($target_parent_id, $id)) {
  6042. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6043. }
  6044. }
  6045. }
  6046. // 更新父文件夹和层级
  6047. $new_level = $target_level + 1;
  6048. DB::table('mp_products')
  6049. ->where('id', $id)
  6050. ->update([
  6051. 'parent_id' => $target_parent_id,
  6052. 'level' => $new_level,
  6053. 'updated_at' => date('Y-m-d H:i:s')
  6054. ]);
  6055. // 如果是文件夹,需要递归更新所有子项的层级
  6056. if ($item->type == 2) {
  6057. $this->updateChildrenLevel($id, $new_level);
  6058. }
  6059. return true;
  6060. }
  6061. /**
  6062. * 获取文件夹下最大子层级
  6063. * @param int $folder_id
  6064. * @return int
  6065. */
  6066. private function getMaxChildLevel($folder_id) {
  6067. $max_level = DB::table('mp_products')
  6068. ->where('parent_id', $folder_id)
  6069. ->where('is_deleted', 0)
  6070. ->max('level');
  6071. if (!$max_level) {
  6072. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6073. }
  6074. // 递归查找子文件夹
  6075. $children = DB::table('mp_products')
  6076. ->where('parent_id', $folder_id)
  6077. ->where('type', 2)
  6078. ->where('is_deleted', 0)
  6079. ->pluck('id');
  6080. foreach ($children as $child_id) {
  6081. $child_max = $this->getMaxChildLevel($child_id);
  6082. if ($child_max > $max_level) {
  6083. $max_level = $child_max;
  6084. }
  6085. }
  6086. return $max_level;
  6087. }
  6088. /**
  6089. * 检查 target_id 是否是 folder_id 的后代
  6090. * @param int $target_id
  6091. * @param int $folder_id
  6092. * @return bool
  6093. */
  6094. private function isDescendant($target_id, $folder_id) {
  6095. if ($target_id == $folder_id) {
  6096. return true;
  6097. }
  6098. $parent = DB::table('mp_products')
  6099. ->where('id', $target_id)
  6100. ->where('is_deleted', 0)
  6101. ->first();
  6102. if (!$parent || $parent->parent_id == 0) {
  6103. return false;
  6104. }
  6105. return $this->isDescendant($parent->parent_id, $folder_id);
  6106. }
  6107. /**
  6108. * 递归更新子项层级
  6109. * @param int $parent_id
  6110. * @param int $parent_level
  6111. */
  6112. private function updateChildrenLevel($parent_id, $parent_level) {
  6113. $children = DB::table('mp_products')
  6114. ->where('parent_id', $parent_id)
  6115. ->where('is_deleted', 0)
  6116. ->get();
  6117. foreach ($children as $child) {
  6118. $new_level = $parent_level + 1;
  6119. DB::table('mp_products')
  6120. ->where('id', $child->id)
  6121. ->update([
  6122. 'level' => $new_level,
  6123. 'updated_at' => date('Y-m-d H:i:s')
  6124. ]);
  6125. // 如果是文件夹,继续递归
  6126. if ($child->type == 2) {
  6127. $this->updateChildrenLevel($child->id, $new_level);
  6128. }
  6129. }
  6130. }
  6131. /**
  6132. * 获取文件夹路径(面包屑导航)
  6133. * @param array $data 包含 folder_id
  6134. * @return array 返回路径数组
  6135. */
  6136. public function getFolderPath($data) {
  6137. $uid = Site::getUid();
  6138. $cpid = Site::getCpid();
  6139. $folder_id = getProp($data, 'id', 0);
  6140. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6141. if ($folder_id == 0) {
  6142. return [
  6143. ['id' => 0, 'name' => '根目录']
  6144. ];
  6145. }
  6146. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6147. $query_uid = $is_public ? 0 : $uid;
  6148. $path = [];
  6149. $current_id = $folder_id;
  6150. while ($current_id > 0) {
  6151. $folder = DB::table('mp_products')
  6152. ->where('id', $current_id)
  6153. ->where('cpid', $cpid)
  6154. ->where('user_id', $query_uid)
  6155. ->where('type', 2)
  6156. ->where('is_deleted', 0)
  6157. ->first();
  6158. if (!$folder) {
  6159. break;
  6160. }
  6161. array_unshift($path, [
  6162. 'id' => $folder->id,
  6163. 'name' => $folder->product_name
  6164. ]);
  6165. $current_id = $folder->parent_id;
  6166. }
  6167. // 添加根目录
  6168. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6169. return $path;
  6170. }
  6171. public function createProduct($data) {
  6172. $uid = Site::getUid();
  6173. $cpid = Site::getCpid();
  6174. $role = Site::getRole();
  6175. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6176. // 如果是公共库操作,需要admin权限
  6177. if ($is_public && $role !== 'admin') {
  6178. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6179. }
  6180. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6181. $store_uid = $is_public ? 0 : $uid;
  6182. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6183. $script_id = (int)getProp($data, 'script_id', 0);
  6184. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6185. if ($script_id && empty($episode_numbers)) {
  6186. Utils::throwError('20003:剧集序号不能为空');
  6187. }
  6188. if (!$script_id && !empty($episode_numbers)) {
  6189. Utils::throwError('20003:请提供剧本ID');
  6190. }
  6191. $product_name = trim(getProp($data, 'product_name'));
  6192. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6193. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6194. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6195. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6196. $url = trim(getProp($data, 'url'));
  6197. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6198. $versions = getProp($data, 'versions');
  6199. // 检查是否是正确的图片格式
  6200. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6201. $urlPath = parse_url($url, PHP_URL_PATH);
  6202. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6203. if (!in_array($extension, $allowedExtensions)) {
  6204. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6205. }
  6206. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6207. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6208. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6209. $product = getProp($data, 'product');
  6210. if (!in_array($product, [1, 2, 3])) {
  6211. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6212. }
  6213. // 获取父文件夹ID和层级
  6214. $parent_id = getProp($data, 'parent_id', 0);
  6215. $parent_level = 0;
  6216. if ($parent_id > 0) {
  6217. $parent = DB::table('mp_products')
  6218. ->where('id', $parent_id)
  6219. ->where('cpid', $cpid)
  6220. ->where('user_id', $store_uid)
  6221. ->where('type', 2)
  6222. ->where('is_deleted', 0)
  6223. ->first();
  6224. if (!$parent) {
  6225. Utils::throwError('20003:父文件夹不存在');
  6226. }
  6227. $parent_level = $parent->level;
  6228. }
  6229. // 创建资产并保存剧本资产关联关系(同一事务)
  6230. DB::beginTransaction();
  6231. try {
  6232. $id = DB::table('mp_products')->insertGetId([
  6233. 'user_id' => $store_uid,
  6234. 'cpid' => $cpid,
  6235. 'type' => 1, // 1=角色图片
  6236. 'parent_id' => $parent_id,
  6237. 'level' => $parent_level + 1,
  6238. 'product_name' => $product_name,
  6239. 'url' => $url,
  6240. 'pic_prompt' => $pic_prompt,
  6241. 'product' => $product,
  6242. 'versions' => json_encode($versions, 256),
  6243. 'sort_order' => time(), // 使用时间戳作为排序权重
  6244. 'created_at' => date('Y-m-d H:i:s'),
  6245. 'updated_at' => date('Y-m-d H:i:s')
  6246. ]);
  6247. if (!$id) Utils::throwError('20003:创建失败');
  6248. // 保存剧本资产关联关系
  6249. if ($script_id) {
  6250. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6251. }
  6252. DB::commit();
  6253. } catch (\Exception $e) {
  6254. DB::rollback();
  6255. throw $e;
  6256. }
  6257. return [
  6258. 'id' => $id,
  6259. 'type' => 1,
  6260. 'parent_id' => $parent_id,
  6261. 'level' => $parent_level + 1,
  6262. 'product_name' => $product_name,
  6263. 'url' => $url,
  6264. 'pic_prompt' => $pic_prompt,
  6265. 'product' => $product,
  6266. 'versions' => $versions
  6267. ];
  6268. }
  6269. public function editProduct($data) {
  6270. $uid = Site::getUid();
  6271. $cpid = Site::getCpid();
  6272. $role = Site::getRole();
  6273. $id = getProp($data, 'id');
  6274. if (!$id) Utils::throwError('20003:ID不能为空');
  6275. $versions = getProp($data, 'versions');
  6276. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6277. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6278. $script_id = (int)getProp($data, 'script_id', 0);
  6279. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6280. if ($script_id && empty($episode_numbers)) {
  6281. Utils::throwError('20003:剧集序号不能为空');
  6282. }
  6283. if (!$script_id && !empty($episode_numbers)) {
  6284. Utils::throwError('20003:请提供剧本ID');
  6285. }
  6286. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6287. $query_uid = $is_public ? 0 : $uid;
  6288. // 如果是公共库操作,需要admin权限
  6289. if ($is_public && $role !== 'admin') {
  6290. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6291. }
  6292. // 检查是否存在且属于当前用户或公共库
  6293. $role = DB::table('mp_products')
  6294. ->where('id', $id)
  6295. ->where('cpid', $cpid)
  6296. ->where('user_id', $query_uid)
  6297. ->where('type', 1)->first();
  6298. if (!$role) Utils::throwError('20003:记录不存在');
  6299. $updateData = [];
  6300. // $needVersionRecord = false; // 是否需要记录版本
  6301. // 名称
  6302. $product_name = trim(getProp($data, 'product_name'));
  6303. if ($product_name) {
  6304. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6305. $updateData['product_name'] = $product_name;
  6306. }
  6307. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6308. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6309. // 图片地址
  6310. $url = trim(getProp($data, 'url'));
  6311. if ($url) {
  6312. // 检查是否是正确的图片格式
  6313. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6314. $urlPath = parse_url($url, PHP_URL_PATH);
  6315. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6316. if (!in_array($extension, $allowedExtensions)) {
  6317. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6318. }
  6319. // // 如果 url 有变更,记录版本
  6320. // if ($url !== $role->url) {
  6321. // $needVersionRecord = true;
  6322. // }
  6323. $updateData['url'] = $url;
  6324. }
  6325. // 提示词
  6326. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6327. if ($pic_prompt) {
  6328. // // 如果 pic_prompt 有变更,记录版本
  6329. // if ($pic_prompt !== $role->pic_prompt) {
  6330. // $needVersionRecord = true;
  6331. // }
  6332. $updateData['pic_prompt'] = $pic_prompt;
  6333. }
  6334. if (empty($updateData) && !$script_id) {
  6335. Utils::throwError('20003:没有需要更新的数据');
  6336. }
  6337. // // 如果需要记录版本,将数据添加到 versions 数组
  6338. // if ($needVersionRecord) {
  6339. // // 获取现有的 versions 数据
  6340. // $versions = json_decode($role->versions, true) ?: [];
  6341. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6342. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6343. // if ($isFirstVersion) {
  6344. // $oldVersion = [
  6345. // 'url' => $role->url,
  6346. // 'description' => $role->pic_prompt,
  6347. // ];
  6348. // // 旧版本添加到数组末尾
  6349. // $versions[] = $oldVersion;
  6350. // }
  6351. // // 构建新版本(变更后)
  6352. // $newVersion = [
  6353. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6354. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6355. // ];
  6356. // // 检查新版本是否已存在于历史版本中
  6357. // $existingIndex = -1;
  6358. // foreach ($versions as $index => $version) {
  6359. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6360. // $existingIndex = $index;
  6361. // break;
  6362. // }
  6363. // }
  6364. // if ($existingIndex !== -1) {
  6365. // // 如果已存在,移除旧的位置
  6366. // array_splice($versions, $existingIndex, 1);
  6367. // }
  6368. // // 新版本添加到数组开头(最新的在前)
  6369. // array_unshift($versions, $newVersion);
  6370. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6371. // // if (count($versions) > 10) {
  6372. // // $versions = array_slice($versions, 0, 10);
  6373. // // }
  6374. // $updateData['versions'] = json_encode($versions, 256);
  6375. // }
  6376. if ($versions) {
  6377. $updateData['versions'] = json_encode($versions, 256);
  6378. }
  6379. if (!empty($updateData)) {
  6380. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6381. }
  6382. // 更新资产并保存剧本资产关联关系(同一事务)
  6383. DB::beginTransaction();
  6384. try {
  6385. $updated = true;
  6386. if (!empty($updateData)) {
  6387. $updated = DB::table('mp_products')
  6388. ->where('cpid', $cpid)
  6389. ->where('id', $id)
  6390. ->update($updateData);
  6391. }
  6392. // 保存剧本资产关联关系
  6393. if ($script_id) {
  6394. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6395. }
  6396. DB::commit();
  6397. } catch (\Exception $e) {
  6398. DB::rollback();
  6399. throw $e;
  6400. }
  6401. return $updated;
  6402. }
  6403. /**
  6404. * 保存单一资产与剧本剧集的关联关系
  6405. *
  6406. * @param int $product_id 资产ID
  6407. * @param int $script_id 剧本ID
  6408. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6409. * @return int 新增关联数量
  6410. */
  6411. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6412. $uid = Site::getUid();
  6413. // 验证剧本是否存在
  6414. $script = DB::table('mp_scripts')
  6415. ->where('id', $script_id)
  6416. ->where('is_deleted', 0)
  6417. ->first();
  6418. if (!$script) {
  6419. Utils::throwError('20003:剧本不存在');
  6420. }
  6421. // 验证剧本归属:只能关联自己的剧本
  6422. if ((int)$script->user_id !== (int)$uid) {
  6423. Utils::throwError('20003:只能添加到自己的剧本');
  6424. }
  6425. // 使用 splitContent 拆分剧本内容获取总集数
  6426. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6427. // 解析剧集序号(数组)
  6428. $episodes = [];
  6429. foreach ($episode_numbers as $item) {
  6430. if (is_array($item)) {
  6431. continue;
  6432. }
  6433. $item = trim((string)$item);
  6434. if ($item === '' || !is_numeric($item)) {
  6435. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6436. }
  6437. $episodes[] = (int)$item;
  6438. }
  6439. // 去重并校验序号范围(序号从1开始)
  6440. $episodes = array_values(array_unique($episodes));
  6441. if (empty($episodes)) {
  6442. Utils::throwError('20003:剧集序号不能为空');
  6443. }
  6444. foreach ($episodes as $episode) {
  6445. if ($episode < 1 || $episode > $totalEpisodes) {
  6446. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6447. }
  6448. }
  6449. $now = now();
  6450. // 过滤已存在的关联,避免重复
  6451. $existingEpisodes = DB::table('mp_script_product_mappings')
  6452. ->where('script_id', $script_id)
  6453. ->where('product_id', $product_id)
  6454. ->whereIn('episode_number', $episodes)
  6455. ->pluck('episode_number')
  6456. ->all();
  6457. $mappingRecords = [];
  6458. foreach ($episodes as $episode) {
  6459. if (in_array($episode, $existingEpisodes)) {
  6460. continue;
  6461. }
  6462. $mappingRecords[] = [
  6463. 'script_id' => $script_id,
  6464. 'product_id' => $product_id,
  6465. 'episode_number' => $episode,
  6466. 'created_at' => $now,
  6467. 'updated_at' => $now,
  6468. ];
  6469. }
  6470. $insertedCount = 0;
  6471. if (!empty($mappingRecords)) {
  6472. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6473. }
  6474. return $insertedCount;
  6475. }
  6476. /**
  6477. * 规范化剧集序号参数,统一为数组
  6478. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6479. *
  6480. * @param mixed $episode_number 剧集序号参数
  6481. * @return array
  6482. */
  6483. private function normalizeEpisodeNumbers($episode_number) {
  6484. if (!is_array($episode_number)) {
  6485. $episode_number = explode(',', (string)$episode_number);
  6486. }
  6487. $items = [];
  6488. foreach ($episode_number as $item) {
  6489. if (is_array($item)) {
  6490. continue;
  6491. }
  6492. foreach (explode(',', (string)$item) as $part) {
  6493. $part = trim($part);
  6494. if ($part !== '') {
  6495. $items[] = $part;
  6496. }
  6497. }
  6498. }
  6499. return $items;
  6500. }
  6501. /**
  6502. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6503. *
  6504. * @param object $script 剧本记录
  6505. * @return int 总集数
  6506. */
  6507. private function getScriptTotalEpisodeCount($script) {
  6508. if (empty($script->content)) {
  6509. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6510. }
  6511. $totalEpisodes = count(splitContent($script->content));
  6512. if ($totalEpisodes < 1) {
  6513. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6514. }
  6515. return $totalEpisodes;
  6516. }
  6517. /**
  6518. * 获取剧本总集数
  6519. *
  6520. * @param array $data 包含 script_id(剧本ID)
  6521. * @return array
  6522. */
  6523. public function getScriptTotalEpisodes($data) {
  6524. $script_id = (int)getProp($data, 'script_id', 0);
  6525. if (!$script_id) {
  6526. Utils::throwError('20003:请提供剧本ID');
  6527. }
  6528. // 验证剧本是否存在
  6529. $script = DB::table('mp_scripts')
  6530. ->where('id', $script_id)
  6531. ->where('is_deleted', 0)
  6532. ->first();
  6533. if (!$script) {
  6534. Utils::throwError('20003:剧本不存在');
  6535. }
  6536. return [
  6537. 'script_id' => $script_id,
  6538. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6539. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6540. ];
  6541. }
  6542. /**
  6543. * 获取角色版本历史
  6544. * @param array $data 包含 id(角色ID)
  6545. * @return array 返回版本历史列表
  6546. */
  6547. public function getProductVersions($data) {
  6548. $cpid = Site::getCpid();
  6549. $id = getProp($data, 'id');
  6550. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6551. $role = DB::table('mp_products')
  6552. ->where('id', $id)
  6553. ->where('cpid', $cpid)
  6554. ->where('type', 1)
  6555. ->first();
  6556. if (!$role) Utils::throwError('20003:角色不存在');
  6557. // 获取版本历史
  6558. $versions = json_decode($role->versions, true) ?: [];
  6559. // 添加当前版本作为最新版本
  6560. $currentVersion = [
  6561. 'version' => 0, // 0 表示当前版本
  6562. 'url' => $role->url,
  6563. 'pic_prompt' => $role->pic_prompt,
  6564. 'updated_at' => $role->updated_at,
  6565. 'is_current' => true
  6566. ];
  6567. array_unshift($versions, $currentVersion);
  6568. return $versions;
  6569. }
  6570. /**
  6571. * 恢复到指定版本
  6572. * @param array $data 包含 id(角色ID)、version(版本号)
  6573. * @return bool
  6574. */
  6575. public function restoreProductVersion($data) {
  6576. $uid = Site::getUid();
  6577. $cpid = Site::getCpid();
  6578. $id = getProp($data, 'id');
  6579. $version = getProp($data, 'version');
  6580. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6581. if (!$version) Utils::throwError('20003:版本号不能为空');
  6582. $role = DB::table('mp_products')
  6583. ->where('id', $id)
  6584. ->where('cpid', $cpid)
  6585. ->where('type', 1)
  6586. ->first();
  6587. if (!$role) Utils::throwError('20003:角色不存在');
  6588. // 获取版本历史
  6589. $versions = json_decode($role->versions, true) ?: [];
  6590. // 查找指定版本
  6591. $targetVersion = null;
  6592. foreach ($versions as $v) {
  6593. if ($v['version'] == $version) {
  6594. $targetVersion = $v;
  6595. break;
  6596. }
  6597. }
  6598. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6599. // 先将当前版本保存到历史
  6600. $newVersion = [
  6601. 'version' => count($versions) + 1,
  6602. 'url' => $role->url,
  6603. 'pic_prompt' => $role->pic_prompt,
  6604. 'updated_at' => date('Y-m-d H:i:s'),
  6605. 'updated_by' => $uid
  6606. ];
  6607. array_unshift($versions, $newVersion);
  6608. // 限制版本数量
  6609. if (count($versions) > 10) {
  6610. $versions = array_slice($versions, 0, 10);
  6611. }
  6612. // 恢复到指定版本
  6613. return DB::table('mp_products')
  6614. ->where('id', $id)
  6615. ->where('cpid', $cpid)
  6616. ->update([
  6617. 'url' => $targetVersion['url'],
  6618. 'pic_prompt' => $targetVersion['pic_prompt'],
  6619. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6620. 'updated_at' => date('Y-m-d H:i:s')
  6621. ]);
  6622. }
  6623. public function deleteProduct($data) {
  6624. $uid = Site::getUid();
  6625. $cpid = Site::getCpid();
  6626. $role = Site::getRole();
  6627. $id = getProp($data, 'id');
  6628. if (!$id) Utils::throwError('20003:ID不能为空');
  6629. $ids = explode(',', $id);
  6630. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6631. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6632. $query_uid = $is_public ? 0 : $uid;
  6633. // 如果是公共库操作,需要admin权限
  6634. if ($is_public && $role !== 'admin') {
  6635. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6636. }
  6637. // 检查是否存在且属于当前用户或公共库
  6638. $role = DB::table('mp_products')
  6639. ->whereIn('id', $ids)
  6640. ->where('cpid', $cpid)
  6641. ->where('user_id', $query_uid)
  6642. ->get();
  6643. if (!$role) Utils::throwError('20003:记录不存在');
  6644. return DB::table('mp_products')
  6645. ->where('cpid', $cpid)
  6646. ->where('user_id', $query_uid)
  6647. ->whereIn('id', $ids)
  6648. ->update([
  6649. 'is_deleted' => 1,
  6650. 'updated_at' => date('Y-m-d H:i:s')
  6651. ]);
  6652. }
  6653. public function generateThreeView($data) {
  6654. $uid = Site::getUid();
  6655. $cpid = Site::getCpid();
  6656. $role = Site::getRole();
  6657. $id = getProp($data, 'id');
  6658. if (!$id) Utils::throwError('20003:ID不能为空');
  6659. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6660. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6661. $query_uid = $is_public ? 0 : $uid;
  6662. // 如果是公共库操作,需要admin权限
  6663. if ($is_public && $role !== 'admin') {
  6664. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6665. }
  6666. // 检查是否存在且属于当前用户或公共库
  6667. $product = DB::table('mp_products')
  6668. ->where('id', $id)
  6669. ->where('cpid', $cpid)
  6670. ->where('user_id', $query_uid)
  6671. ->where('type', 1)->first();
  6672. if (!$product) Utils::throwError('20003:资产不存在');
  6673. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6674. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6675. if (!$ref_img_url) {
  6676. // 如果没有传入参考图,使用角色表中的图片
  6677. $ref_img_url = $product->url ?? '';
  6678. if (!$ref_img_url) {
  6679. Utils::throwError('20003:参考图不能为空');
  6680. }
  6681. }
  6682. $pic_prompt = getProp($product, 'pic_prompt');
  6683. if ($pic_prompt) {
  6684. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6685. }
  6686. // 检查参考图是否是正确的图片格式
  6687. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6688. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6689. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6690. if (!in_array($extension, $allowedExtensions)) {
  6691. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6692. }
  6693. // 处理图片模型
  6694. $model = getProp($data, 'model');
  6695. if (!$model) {
  6696. // 使用默认模型
  6697. $model = 'doubao-seedream-5-0-lite-260128';
  6698. }
  6699. // 验证模型是否在可用模型表中
  6700. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6701. Utils::throwError('20003:该模型已不可用,请更换!');
  6702. }
  6703. $ratio = getProp($data, 'ratio', '16:9');
  6704. $resolution = getProp($data, 'resolution', '2k');
  6705. // 定义分辨率和宽高比对应的尺寸映射表
  6706. $sizeMap = [
  6707. '2k' => [
  6708. '1:1' => ['width' => 2048, 'height' => 2048],
  6709. '4:3' => ['width' => 2304, 'height' => 1728],
  6710. '3:4' => ['width' => 1728, 'height' => 2304],
  6711. '16:9' => ['width' => 2848, 'height' => 1600],
  6712. '9:16' => ['width' => 1600, 'height' => 2848],
  6713. '3:2' => ['width' => 2496, 'height' => 1664],
  6714. '2:3' => ['width' => 1664, 'height' => 2496],
  6715. '21:9' => ['width' => 3136, 'height' => 1344],
  6716. ],
  6717. '3k' => [
  6718. '1:1' => ['width' => 3072, 'height' => 3072],
  6719. '4:3' => ['width' => 3456, 'height' => 2592],
  6720. '3:4' => ['width' => 2592, 'height' => 3456],
  6721. '16:9' => ['width' => 4096, 'height' => 2304],
  6722. '9:16' => ['width' => 2304, 'height' => 4096],
  6723. '2:3' => ['width' => 2496, 'height' => 3744],
  6724. '3:2' => ['width' => 3744, 'height' => 2496],
  6725. '21:9' => ['width' => 4704, 'height' => 2016],
  6726. ],
  6727. '4k' => [
  6728. '1:1' => ['width' => 4096, 'height' => 4096],
  6729. '3:4' => ['width' => 3520, 'height' => 4704],
  6730. '4:3' => ['width' => 4704, 'height' => 3520],
  6731. '16:9' => ['width' => 5504, 'height' => 3040],
  6732. '9:16' => ['width' => 3040, 'height' => 5504],
  6733. '2:3' => ['width' => 3328, 'height' => 4992],
  6734. '3:2' => ['width' => 4992, 'height' => 3328],
  6735. '21:9' => ['width' => 6240, 'height' => 2656],
  6736. ],
  6737. ];
  6738. // 参数验证
  6739. $resolution = strtolower($resolution);
  6740. if (!isset($sizeMap[$resolution])) {
  6741. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6742. }
  6743. if (!isset($sizeMap[$resolution][$ratio])) {
  6744. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6745. }
  6746. // 根据 ratio 和 resolution 确定宽高
  6747. $width = $sizeMap[$resolution][$ratio]['width'];
  6748. $height = $sizeMap[$resolution][$ratio]['height'];
  6749. try {
  6750. // 创建图片生成任务
  6751. $params = [
  6752. 'prompt' => $prompt,
  6753. 'model' => $model,
  6754. 'ref_img_urls' => [$ref_img_url],
  6755. 'width' => $width,
  6756. 'height' => $height
  6757. ];
  6758. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6759. $task_id = $task->id;
  6760. if (!$task_id) {
  6761. Utils::throwError('20003:创建图片生成任务失败');
  6762. }
  6763. // 轮询获取结果
  6764. // 只查询数据库,不调用API,不更新任务表
  6765. $start_time = time();
  6766. $timeout = 1800;
  6767. $img_url = '';
  6768. while (time() - $start_time < $timeout) {
  6769. sleep(5);
  6770. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6771. $task = DB::table('mp_generate_pic_tasks')
  6772. ->where('id', $task_id)
  6773. ->first();
  6774. if (!$task) {
  6775. Utils::throwError('20003:任务不存在');
  6776. }
  6777. if ($task->status === 'success' && $task->result_url) {
  6778. $result_urls = is_string($task->result_url)
  6779. ? json_decode($task->result_url, true)
  6780. : $task->result_url;
  6781. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6782. break;
  6783. } elseif ($task->status === 'failed') {
  6784. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6785. }
  6786. // 其他状态继续轮询
  6787. }
  6788. if (empty($img_url)) {
  6789. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6790. }
  6791. // 更新 mp_products 表(不是任务表)
  6792. DB::table('mp_products')
  6793. ->where('id', $id)
  6794. ->where('cpid', $cpid)
  6795. ->update([
  6796. 'three_view_image_url' => $img_url,
  6797. 'updated_at' => date('Y-m-d H:i:s')
  6798. ]);
  6799. return ['three_view_image_url' => $img_url];
  6800. } catch (\Exception $e) {
  6801. dLog('anime')->error('生成三视图失败', [
  6802. 'error' => $e->getMessage()
  6803. ]);
  6804. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6805. Utils::throwError('20003:' . $e->getMessage());
  6806. }
  6807. }
  6808. /**
  6809. * 推送(复制)资产或文件夹到目标位置
  6810. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6811. * @return array 返回推送结果
  6812. */
  6813. public function pushProductOrFolder($data) {
  6814. $uid = Site::getUid();
  6815. $cpid = Site::getCpid();
  6816. $role = Site::getRole();
  6817. $product_id = getProp($data, 'product_id');
  6818. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6819. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6820. if (!$product_id) {
  6821. Utils::throwError('20003:请选择要推送的项目');
  6822. }
  6823. // 查询源项目(只通过cpid查询,不限制user_id)
  6824. $sourceItem = DB::table('mp_products')
  6825. ->where('id', $product_id)
  6826. ->where('cpid', $cpid)
  6827. ->where('is_deleted', 0)
  6828. ->first();
  6829. if (!$sourceItem) {
  6830. Utils::throwError('20003:要推送的项目不存在');
  6831. }
  6832. // 通过user_id判断源是公共库还是个人库
  6833. $source_uid = $sourceItem->user_id;
  6834. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6835. // 验证目标文件夹并确定目标是公共库还是个人库
  6836. $target_level = 0;
  6837. $target_uid = $uid; // 默认推送到个人库
  6838. $target_is_public = 0;
  6839. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6840. if ($target_parent_id > 0) {
  6841. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6842. $targetParent = DB::table('mp_products')
  6843. ->where('id', $target_parent_id)
  6844. ->where('cpid', $cpid)
  6845. ->where('type', 2)
  6846. ->where('is_deleted', 0)
  6847. ->first();
  6848. if (!$targetParent) {
  6849. Utils::throwError('20003:目标文件夹不存在');
  6850. }
  6851. // 通过user_id判断目标是公共库还是个人库
  6852. $target_level = $targetParent->level;
  6853. $target_uid = $targetParent->user_id;
  6854. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6855. // 使用目标文件夹的 product 类型
  6856. $final_product_type = $targetParent->product;
  6857. }
  6858. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6859. else {
  6860. $push_to_public = getProp($data, 'push_to_public');
  6861. if ($push_to_public === '') {
  6862. Utils::throwError('20003:请选择是否推送到公共库');
  6863. }
  6864. if ($push_to_public) {
  6865. $target_uid = 0;
  6866. $target_is_public = 1;
  6867. }
  6868. // 推送到根目录时,必须指定 product 类型
  6869. if ($target_product === null || $target_product === '') {
  6870. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6871. }
  6872. $final_product_type = $target_product;
  6873. }
  6874. // 如果目标是公共库,需要admin权限
  6875. if ($target_is_public && $role !== 'admin') {
  6876. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6877. }
  6878. // 权限验证:验证是否符合允许的推送规则
  6879. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6880. try {
  6881. DB::beginTransaction();
  6882. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6883. if ($sourceItem->type == 1) {
  6884. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6885. DB::commit();
  6886. return [
  6887. 'product_id' => $newId,
  6888. ];
  6889. }
  6890. // 如果是文件夹,递归复制(支持跨类型推送)
  6891. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6892. DB::commit();
  6893. return [
  6894. 'product_id' => $newFolderId,
  6895. ];
  6896. } catch (\Exception $e) {
  6897. DB::rollBack();
  6898. dLog('anime')->error('推送失败', [
  6899. 'error' => $e->getMessage(),
  6900. 'product_id' => $product_id
  6901. ]);
  6902. Utils::throwError('20003:' . $e->getMessage());
  6903. }
  6904. }
  6905. /**
  6906. * 验证推送权限
  6907. * 允许的推送规则:
  6908. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6909. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6910. * 3. 公共库推送给公共库(公共库 → 公共库)
  6911. *
  6912. * @param int $source_uid 源的user_id
  6913. * @param int $target_uid 目标的user_id
  6914. * @param int $current_uid 当前用户ID
  6915. * @throws \Exception
  6916. */
  6917. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6918. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6919. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6920. return; // 允许
  6921. }
  6922. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6923. if ($source_uid == 0 && $target_uid == $current_uid) {
  6924. return; // 允许
  6925. }
  6926. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6927. if ($source_uid == 0 && $target_uid == 0) {
  6928. return; // 允许
  6929. }
  6930. // 其他情况都不允许
  6931. if ($source_uid != 0 && $source_uid != $current_uid) {
  6932. // 源是别人的个人库
  6933. Utils::throwError('20003:无权限访问该资产');
  6934. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6935. // 个人库推送给公共库(不允许)
  6936. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6937. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6938. // 不同用户的个人库之间推送(不允许)
  6939. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6940. } else {
  6941. // 其他未知情况
  6942. Utils::throwError('20003:不允许的推送操作');
  6943. }
  6944. }
  6945. /**
  6946. * 复制单个资产
  6947. * @param object $sourceProduct 源资产对象
  6948. * @param int $targetParentId 目标父文件夹ID
  6949. * @param int $targetLevel 目标层级
  6950. * @param int $cpid 公司ID
  6951. * @param int $targetUid 目标用户ID
  6952. * @return int 返回新资产ID
  6953. */
  6954. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6955. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6956. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6957. $newProductData = [
  6958. 'user_id' => $targetUid,
  6959. 'cpid' => $cpid,
  6960. 'type' => 1,
  6961. 'parent_id' => $targetParentId,
  6962. 'level' => $targetLevel,
  6963. 'product_name' => $sourceProduct->product_name,
  6964. 'url' => $sourceProduct->url,
  6965. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6966. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6967. 'product' => $finalProductType,
  6968. 'versions' => $sourceProduct->versions ?? '',
  6969. 'sort_order' => time(),
  6970. 'is_deleted' => 0,
  6971. 'created_at' => date('Y-m-d H:i:s'),
  6972. 'updated_at' => date('Y-m-d H:i:s')
  6973. ];
  6974. return DB::table('mp_products')->insertGetId($newProductData);
  6975. }
  6976. /**
  6977. * 递归复制文件夹及其子项
  6978. * @param object $sourceFolder 源文件夹对象
  6979. * @param int $targetParentId 目标父文件夹ID
  6980. * @param int $targetLevel 目标层级
  6981. * @param int $cpid 公司ID
  6982. * @param int $targetUid 目标用户ID
  6983. * @param int $sourceUid 源用户ID
  6984. * @return int 返回新文件夹ID
  6985. */
  6986. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6987. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6988. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6989. // 创建新文件夹
  6990. $newFolderData = [
  6991. 'user_id' => $targetUid,
  6992. 'cpid' => $cpid,
  6993. 'type' => 2,
  6994. 'parent_id' => $targetParentId,
  6995. 'level' => $targetLevel,
  6996. 'product_name' => $sourceFolder->product_name,
  6997. 'product' => $finalProductType,
  6998. 'sort_order' => time(),
  6999. 'is_deleted' => 0,
  7000. 'created_at' => date('Y-m-d H:i:s'),
  7001. 'updated_at' => date('Y-m-d H:i:s')
  7002. ];
  7003. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7004. // 获取源文件夹下的所有子项
  7005. $children = DB::table('mp_products')
  7006. ->where('parent_id', $sourceFolder->id)
  7007. ->where('cpid', $cpid)
  7008. ->where('user_id', $sourceUid)
  7009. ->where('is_deleted', 0)
  7010. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7011. ->get();
  7012. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7013. foreach ($children as $child) {
  7014. if ($child->type == 1) {
  7015. // 资产
  7016. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7017. } else {
  7018. // 文件夹
  7019. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7020. }
  7021. }
  7022. return $newFolderId;
  7023. }
  7024. /**
  7025. * 保存剧本资产关联关系
  7026. * @param array $data 请求参数
  7027. * @return bool
  7028. */
  7029. public function saveScriptProducts($data) {
  7030. $uid = Site::getUid();
  7031. $cpid = Site::getCpid();
  7032. $script_id = getProp($data, 'script_id');
  7033. $products = getProp($data, 'products', []);
  7034. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7035. if (!$script_id) {
  7036. Utils::throwError('20003:请提供剧本ID');
  7037. }
  7038. // 验证剧本是否存在
  7039. $script = DB::table('mp_scripts')
  7040. ->where('id', $script_id)
  7041. ->where('is_deleted', 0)
  7042. ->first();
  7043. if (!$script) {
  7044. Utils::throwError('20003:剧本不存在');
  7045. }
  7046. // 处理图片模型
  7047. $model = getProp($data, 'model');
  7048. if (!$model) {
  7049. // 使用默认模型
  7050. $model = 'doubao-seedream-5-0-lite-260128';
  7051. }
  7052. // 验证模型是否在可用模型表中
  7053. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7054. Utils::throwError('20003:该模型已不可用,请更换!');
  7055. }
  7056. $ratio = getProp($data, 'ratio', '9:16');
  7057. $resolution = getProp($data, 'resolution', '2k');
  7058. // 定义分辨率和宽高比对应的尺寸映射表
  7059. $sizeMap = [
  7060. '2k' => [
  7061. '1:1' => ['width' => 2048, 'height' => 2048],
  7062. '4:3' => ['width' => 2304, 'height' => 1728],
  7063. '3:4' => ['width' => 1728, 'height' => 2304],
  7064. '16:9' => ['width' => 2848, 'height' => 1600],
  7065. '9:16' => ['width' => 1600, 'height' => 2848],
  7066. '3:2' => ['width' => 2496, 'height' => 1664],
  7067. '2:3' => ['width' => 1664, 'height' => 2496],
  7068. '21:9' => ['width' => 3136, 'height' => 1344],
  7069. ],
  7070. '3k' => [
  7071. '1:1' => ['width' => 3072, 'height' => 3072],
  7072. '4:3' => ['width' => 3456, 'height' => 2592],
  7073. '3:4' => ['width' => 2592, 'height' => 3456],
  7074. '16:9' => ['width' => 4096, 'height' => 2304],
  7075. '9:16' => ['width' => 2304, 'height' => 4096],
  7076. '2:3' => ['width' => 2496, 'height' => 3744],
  7077. '3:2' => ['width' => 3744, 'height' => 2496],
  7078. '21:9' => ['width' => 4704, 'height' => 2016],
  7079. ],
  7080. '4k' => [
  7081. '1:1' => ['width' => 4096, 'height' => 4096],
  7082. '3:4' => ['width' => 3520, 'height' => 4704],
  7083. '4:3' => ['width' => 4704, 'height' => 3520],
  7084. '16:9' => ['width' => 5504, 'height' => 3040],
  7085. '9:16' => ['width' => 3040, 'height' => 5504],
  7086. '2:3' => ['width' => 3328, 'height' => 4992],
  7087. '3:2' => ['width' => 4992, 'height' => 3328],
  7088. '21:9' => ['width' => 6240, 'height' => 2656],
  7089. ],
  7090. ];
  7091. // 参数验证
  7092. $resolution = strtolower($resolution);
  7093. if (!isset($sizeMap[$resolution])) {
  7094. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7095. }
  7096. if (!isset($sizeMap[$resolution][$ratio])) {
  7097. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7098. }
  7099. // 根据 ratio 和 resolution 确定宽高
  7100. $width = $sizeMap[$resolution][$ratio]['width'];
  7101. $height = $sizeMap[$resolution][$ratio]['height'];
  7102. $script_name = $script->script_name ?? 'script_' . $script_id;
  7103. // 检查是否已经有该剧本的资产数据
  7104. $existingMappings = DB::table('mp_script_product_mappings')
  7105. ->where('script_id', $script_id)
  7106. ->get();
  7107. if ($existingMappings->isNotEmpty()) {
  7108. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7109. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7110. // 查询这些资产的图片生成任务状态
  7111. $productsWithTasks = DB::table('mp_products')
  7112. ->whereIn('id', $productIds)
  7113. ->where('is_deleted', 0)
  7114. ->get();
  7115. $productTaskMap = [];
  7116. $typeFolderIds = [];
  7117. $hasAllTasks = true;
  7118. foreach ($productsWithTasks as $product) {
  7119. // 收集类型文件夹ID
  7120. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7121. $parentFolder = DB::table('mp_products')
  7122. ->where('id', $product->parent_id)
  7123. ->where('type', 2)
  7124. ->first();
  7125. if ($parentFolder) {
  7126. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7127. }
  7128. }
  7129. // 检查是否有图片生成任务
  7130. if (!empty($product->pic_task_id)) {
  7131. $productTaskMap[$product->id] = $product->pic_task_id;
  7132. } else if($product->url && $product->pic_task_status == '生成成功') {
  7133. continue;
  7134. } else {
  7135. // 有资产没有图片任务
  7136. $hasAllTasks = false;
  7137. }
  7138. }
  7139. // 如果所有资产都有任务ID,直接轮询返回结果
  7140. if ($hasAllTasks && !empty($productTaskMap)) {
  7141. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7142. 'script_id' => $script_id,
  7143. 'script_name' => $script_name,
  7144. 'product_count' => count($productTaskMap)
  7145. ]);
  7146. // 直接返回 SSE 流轮询结果
  7147. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7148. }
  7149. // 如果部分资产没有任务ID,只为这些资产创建任务
  7150. if (!$hasAllTasks && $auto_generate_images) {
  7151. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7152. 'script_id' => $script_id,
  7153. 'script_name' => $script_name
  7154. ]);
  7155. // 开启事务
  7156. DB::beginTransaction();
  7157. try {
  7158. foreach ($productsWithTasks as $product) {
  7159. // 跳过已有任务的资产
  7160. if (!empty($product->pic_task_id)) {
  7161. continue;
  7162. }
  7163. // 跳过没有提示词的资产
  7164. if (empty($product->pic_prompt)) {
  7165. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7166. 'product_id' => $product->id,
  7167. 'product_name' => $product->product_name
  7168. ]);
  7169. continue;
  7170. }
  7171. try {
  7172. // 创建图片生成任务
  7173. $params = [
  7174. 'prompt' => $product->pic_prompt,
  7175. 'model' => $model,
  7176. 'ref_img_urls' => [],
  7177. 'width' => $width,
  7178. 'height' => $height
  7179. ];
  7180. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7181. $task_id = $task->id;
  7182. if ($task_id) {
  7183. $productTaskMap[$product->id] = $task_id;
  7184. // 在事务中更新资产表的任务ID和状态
  7185. DB::table('mp_products')
  7186. ->where('id', $product->id)
  7187. ->update([
  7188. 'pic_task_id' => $task_id,
  7189. 'pic_task_status' => '生成中',
  7190. 'updated_at' => now()
  7191. ]);
  7192. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7193. 'product_id' => $product->id,
  7194. 'task_id' => $task_id
  7195. ]);
  7196. }
  7197. } catch (\Exception $e) {
  7198. dLog('anime')->error('创建资产图片生成任务失败', [
  7199. 'product_id' => $product->id,
  7200. 'error' => $e->getMessage()
  7201. ]);
  7202. // 标记为失败(仍在事务中)
  7203. DB::table('mp_products')
  7204. ->where('id', $product->id)
  7205. ->update([
  7206. 'pic_task_status' => '生成失败',
  7207. 'updated_at' => now()
  7208. ]);
  7209. }
  7210. }
  7211. // 提交事务
  7212. DB::commit();
  7213. // 如果有新创建的任务,返回 SSE 流
  7214. if (!empty($productTaskMap)) {
  7215. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7216. }
  7217. } catch (\Exception $e) {
  7218. // 回滚事务
  7219. DB::rollback();
  7220. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7221. 'script_id' => $script_id,
  7222. 'error' => $e->getMessage()
  7223. ]);
  7224. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7225. }
  7226. }
  7227. // 如果不需要生成图片,返回已存在的信息
  7228. return [
  7229. 'success' => true,
  7230. 'message' => '剧本资产已存在',
  7231. 'script_id' => $script_id,
  7232. 'script_name' => $script_name,
  7233. 'type_folder_ids' => $typeFolderIds,
  7234. 'existing_products' => count($productIds),
  7235. 'tasks_count' => count($productTaskMap)
  7236. ];
  7237. }
  7238. // 解析 products(可能是 JSON 字符串或数组)
  7239. if (is_string($products)) {
  7240. $products = json_decode($products, true);
  7241. if (json_last_error() !== JSON_ERROR_NONE) {
  7242. Utils::throwError('20003:产品数据格式错误');
  7243. }
  7244. }
  7245. if (!is_array($products) || empty($products)) {
  7246. Utils::throwError('20003:产品数据不能为空');
  7247. }
  7248. // 以下是原有的创建逻辑...
  7249. // 开启事务
  7250. DB::beginTransaction();
  7251. try {
  7252. $now = now();
  7253. $mappingRecords = [];
  7254. $createdProductIds = []; // 记录所有创建的资产ID
  7255. // 获取剧本名称
  7256. $script_name = $script->script_name ?? 'script_' . $script_id;
  7257. // 存储每个类型的根文件夹ID
  7258. $typeFolderIds = [];
  7259. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7260. foreach ($products as $productGroup) {
  7261. $type = getProp($productGroup, 'type');
  7262. $title = getProp($productGroup, 'title', '');
  7263. $content = getProp($productGroup, 'content', []);
  7264. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7265. continue;
  7266. }
  7267. // 为当前类型创建根文件夹(如果还未创建)
  7268. if (!isset($typeFolderIds[$type])) {
  7269. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7270. 'user_id' => $uid,
  7271. 'cpid' => $cpid,
  7272. 'type' => 2, // 1.资产 2文件夹
  7273. 'product' => $type, // 1.主体 2.场景 3.道具
  7274. 'parent_id' => 0, // 根文件夹,parent_id=0
  7275. 'level' => 1, // 第一层级
  7276. 'product_name' => $script_name,
  7277. 'sort_order' => time() + $type,
  7278. 'is_deleted' => 0,
  7279. 'created_at' => $now,
  7280. 'updated_at' => $now
  7281. ]);
  7282. }
  7283. $folder_id = $typeFolderIds[$type];
  7284. // 获取表头(第一行)并查找关键列的位置
  7285. $headers = $content[0];
  7286. $nameColumnIndex = -1; // 资产名称列索引
  7287. $sequenceColumnIndex = -1; // 使用范围列索引
  7288. $promptColumnIndex = -1; // 参考提示词列索引
  7289. foreach ($headers as $index => $header) {
  7290. // 查找"资产名称"列
  7291. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7292. $nameColumnIndex = $index;
  7293. }
  7294. // 查找"使用范围"列
  7295. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7296. $sequenceColumnIndex = $index;
  7297. }
  7298. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7299. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7300. $promptColumnIndex = $index;
  7301. }
  7302. }
  7303. // 验证必要的列是否都找到了
  7304. if ($nameColumnIndex === -1) {
  7305. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7306. continue;
  7307. }
  7308. if ($sequenceColumnIndex === -1) {
  7309. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7310. continue;
  7311. }
  7312. // 跳过表头,解析每一行数据
  7313. for ($i = 1; $i < count($content); $i++) {
  7314. $row = $content[$i];
  7315. // 确保行数据有效
  7316. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7317. continue;
  7318. }
  7319. // 根据动态查找的列索引提取数据
  7320. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7321. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7322. $pic_prompt = '';
  7323. // 提取参考提示词(如果找到了该列)
  7324. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7325. $pic_prompt = trim($row[$promptColumnIndex]);
  7326. }
  7327. // 解析使用范围(逗号分隔的序号)
  7328. $sequences = [];
  7329. if (!empty($sequence_str)) {
  7330. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7331. foreach ($sequenceParts as $part) {
  7332. if (is_numeric($part)) {
  7333. $sequences[] = (int)$part;
  7334. }
  7335. }
  7336. }
  7337. if (empty($product_name)) {
  7338. continue;
  7339. }
  7340. // 处理product_name两边的符号
  7341. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7342. // 如果名称不存在或仅剩占位符号,则跳过
  7343. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7344. dLog('anime')->warning('资产名称无效,跳过保存', [
  7345. 'script_id' => $script_id,
  7346. 'type' => $type,
  7347. 'product_name' => $product_name
  7348. ]);
  7349. continue;
  7350. }
  7351. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7352. $product_id = DB::table('mp_products')->insertGetId([
  7353. 'product_name' => $product_name,
  7354. 'type' => 1, // 1=资产 2.文件夹
  7355. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7356. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7357. 'level' => 2, // 第二层级
  7358. 'pic_prompt' => $pic_prompt,
  7359. 'user_id' => $uid,
  7360. 'cpid' => $cpid,
  7361. 'sort_order' => time(),
  7362. 'is_deleted' => 0,
  7363. 'created_at' => $now,
  7364. 'updated_at' => $now,
  7365. ]);
  7366. // 记录创建的资产ID
  7367. $createdProductIds[] = $product_id;
  7368. // 为每个序号创建映射记录
  7369. if (!empty($sequences)) {
  7370. foreach ($sequences as $sequence) {
  7371. $mappingRecords[] = [
  7372. 'script_id' => $script_id,
  7373. 'product_id' => $product_id,
  7374. 'episode_number' => $sequence,
  7375. 'created_at' => $now,
  7376. 'updated_at' => $now,
  7377. ];
  7378. }
  7379. } else {
  7380. // 如果没有指定序号,创建一个默认映射(序号为0)
  7381. $mappingRecords[] = [
  7382. 'script_id' => $script_id,
  7383. 'product_id' => $product_id,
  7384. 'episode_number' => 0,
  7385. 'created_at' => $now,
  7386. 'updated_at' => $now,
  7387. ];
  7388. }
  7389. }
  7390. }
  7391. if (empty($mappingRecords)) {
  7392. Utils::throwError('20003:没有有效的产品数据');
  7393. }
  7394. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7395. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7396. // 剧本已有资产,同步更新is_products标记
  7397. DB::table('mp_scripts')->where('id', $script_id)->update([
  7398. 'is_products' => 1,
  7399. 'updated_at' => $now
  7400. ]);
  7401. // 如果需要自动生成图片,在事务中创建图片生成任务
  7402. $productTaskMap = [];
  7403. if ($auto_generate_images && !empty($createdProductIds)) {
  7404. // 查询所有创建的资产
  7405. $productsToGenerate = DB::table('mp_products')
  7406. ->whereIn('id', $createdProductIds)
  7407. ->where('is_deleted', 0)
  7408. ->get();
  7409. foreach ($productsToGenerate as $product) {
  7410. if (empty($product->pic_prompt)) {
  7411. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7412. 'product_id' => $product->id,
  7413. 'product_name' => $product->product_name
  7414. ]);
  7415. continue;
  7416. }
  7417. try {
  7418. // 创建图片生成任务
  7419. $params = [
  7420. 'prompt' => $product->pic_prompt,
  7421. 'model' => $model,
  7422. 'ref_img_urls' => [],
  7423. 'width' => $width,
  7424. 'height' => $height
  7425. ];
  7426. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7427. $task_id = $task->id;
  7428. if ($task_id) {
  7429. $productTaskMap[$product->id] = $task_id;
  7430. // 在事务中更新资产表的任务ID和状态
  7431. DB::table('mp_products')
  7432. ->where('id', $product->id)
  7433. ->update([
  7434. 'pic_task_id' => $task_id,
  7435. 'pic_task_status' => '生成中',
  7436. 'updated_at' => now()
  7437. ]);
  7438. dLog('anime')->info('创建资产图片生成任务', [
  7439. 'product_id' => $product->id,
  7440. 'task_id' => $task_id
  7441. ]);
  7442. }
  7443. } catch (\Exception $e) {
  7444. dLog('anime')->error('创建资产图片生成任务失败', [
  7445. 'product_id' => $product->id,
  7446. 'error' => $e->getMessage()
  7447. ]);
  7448. // 标记为失败(仍在事务中)
  7449. DB::table('mp_products')
  7450. ->where('id', $product->id)
  7451. ->update([
  7452. 'pic_task_status' => '生成失败',
  7453. 'updated_at' => now()
  7454. ]);
  7455. }
  7456. }
  7457. }
  7458. // 提交事务
  7459. DB::commit();
  7460. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7461. if ($auto_generate_images && !empty($productTaskMap)) {
  7462. // 返回 SSE 流(事务外轮询)
  7463. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7464. }
  7465. // 如果不需要生成图片,返回普通结果
  7466. return [
  7467. 'success' => true,
  7468. 'type_folder_ids' => $typeFolderIds,
  7469. 'inserted_count' => $insertedCount,
  7470. 'total_records' => count($mappingRecords),
  7471. 'created_products' => count($createdProductIds),
  7472. 'image_tasks_created' => count($productTaskMap)
  7473. ];
  7474. } catch (\Exception $e) {
  7475. // 回滚事务
  7476. DB::rollback();
  7477. // 记录错误日志
  7478. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7479. 'script_id' => $script_id,
  7480. 'error' => $e->getMessage(),
  7481. 'trace' => $e->getTraceAsString()
  7482. ]);
  7483. // 统一使用 Utils::throwError 抛出错误
  7484. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7485. }
  7486. }
  7487. /**
  7488. * 批量为剧本资产生成图片
  7489. *
  7490. * @param array $data 请求参数
  7491. * @return \Generator 返回 SSE 流
  7492. */
  7493. public function batchGenerateProductImages($data) {
  7494. $script_id = getProp($data, 'script_id');
  7495. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7496. if (!$script_id) {
  7497. Utils::throwError('20003:请提供剧本ID');
  7498. }
  7499. // 验证剧本是否存在
  7500. $script = DB::table('mp_scripts')
  7501. ->where('id', $script_id)
  7502. ->where('is_deleted', 0)
  7503. ->first();
  7504. if (!$script) {
  7505. Utils::throwError('20003:剧本不存在');
  7506. }
  7507. $script_name = $script->script_name ?? 'script_' . $script_id;
  7508. // 获取需要生成图片的所有资产
  7509. $products = DB::table('mp_products')
  7510. ->whereIn('parent_id', array_values($type_folder_ids))
  7511. ->where('is_deleted', 0)
  7512. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7513. ->get();
  7514. if ($products->isEmpty()) {
  7515. Utils::throwError('20003:没有找到需要生成图片的资产');
  7516. }
  7517. // 默认参数
  7518. $model = 'doubao-seedream-5-0-lite-260128';
  7519. $width = 1600;
  7520. $height = 2848;
  7521. // 开始为每个资产创建图片生成任务
  7522. $taskIds = [];
  7523. $productTaskMap = []; // 资产ID到任务ID的映射
  7524. foreach ($products as $product) {
  7525. if (empty($product->pic_prompt)) {
  7526. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7527. continue;
  7528. }
  7529. try {
  7530. // 创建图片生成任务
  7531. $params = [
  7532. 'prompt' => $product->pic_prompt,
  7533. 'model' => $model,
  7534. 'ref_img_urls' => [],
  7535. 'width' => $width,
  7536. 'height' => $height
  7537. ];
  7538. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7539. $task_id = $task->id;
  7540. if ($task_id) {
  7541. $taskIds[] = $task_id;
  7542. $productTaskMap[$product->id] = $task_id;
  7543. // 更新资产表的任务ID和状态
  7544. DB::table('mp_products')
  7545. ->where('id', $product->id)
  7546. ->update([
  7547. 'pic_task_id' => $task_id,
  7548. 'pic_task_status' => '生成中',
  7549. 'updated_at' => now()
  7550. ]);
  7551. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7552. }
  7553. } catch (\Exception $e) {
  7554. dLog('anime')->error('创建资产图片生成任务失败', [
  7555. 'product_id' => $product->id,
  7556. 'error' => $e->getMessage()
  7557. ]);
  7558. // 标记为失败
  7559. DB::table('mp_products')
  7560. ->where('id', $product->id)
  7561. ->update([
  7562. 'pic_task_status' => '生成失败',
  7563. 'updated_at' => now()
  7564. ]);
  7565. }
  7566. }
  7567. if (empty($taskIds)) {
  7568. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7569. }
  7570. // 返回 SSE 流
  7571. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7572. }
  7573. /**
  7574. * 轮询资产图片生成任务状态(SSE流式返回)
  7575. * 只通过查询数据库获取任务状态,不主动调用API
  7576. *
  7577. * @param int $script_id 剧本ID
  7578. * @param string $script_name 剧本名称
  7579. * @param array $productTaskMap 资产ID到任务ID的映射
  7580. * @param array $type_folder_ids 类型文件夹ID映射
  7581. * @return \Generator
  7582. */
  7583. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7584. $startTime = time();
  7585. $timeout = 1800; // 30分钟超时
  7586. $pollInterval = 10; // 10秒轮询一次
  7587. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7588. // 定义类型名称映射
  7589. $typeNames = [
  7590. 1 => 'roles', // 角色
  7591. 2 => 'scenes', // 场景
  7592. 3 => 'props' // 道具
  7593. ];
  7594. while (time() - $startTime < $timeout) {
  7595. sleep($pollInterval);
  7596. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7597. $mappings = DB::table('mp_script_product_mappings')
  7598. ->where('script_id', $script_id)
  7599. ->pluck('product_id')
  7600. ->unique()
  7601. ->toArray();
  7602. if (empty($mappings)) {
  7603. dLog('anime')->warning('该剧本没有关联的资产', [
  7604. 'script_id' => $script_id,
  7605. 'script_name' => $script_name
  7606. ]);
  7607. break;
  7608. }
  7609. // 查询所有资产的当前状态
  7610. $products = DB::table('mp_products')
  7611. ->whereIn('id', $mappings)
  7612. ->where('is_deleted', 0)
  7613. ->get();
  7614. // 统计各类型的状态(使用类型名称作为键名)
  7615. $stats = [
  7616. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7617. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7618. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7619. ];
  7620. $allCompleted = true;
  7621. $hasStatusChange = false;
  7622. foreach ($products as $product) {
  7623. $type = $product->product;
  7624. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7625. // 如果类型名称不在 stats 中,初始化
  7626. if (!isset($stats[$typeName])) {
  7627. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7628. }
  7629. $stats[$typeName]['total']++;
  7630. $task_id = $product->pic_task_id;
  7631. $currentStatus = $product->pic_task_status;
  7632. // 检查状态是否有变化
  7633. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7634. $hasStatusChange = true;
  7635. $lastStatus[$product->id] = $currentStatus;
  7636. }
  7637. // 如果是生成中,查询任务表状态
  7638. if ($currentStatus === '生成中' && $task_id) {
  7639. // 只查询数据库,不调用API
  7640. $task = DB::table('mp_generate_pic_tasks')
  7641. ->where('id', $task_id)
  7642. ->first();
  7643. if ($task) {
  7644. // 检查任务状态
  7645. if ($task->status === 'success' && $task->result_url) {
  7646. // 解析图片URL
  7647. $result_urls = $task->result_url;
  7648. if (is_string($result_urls)) {
  7649. $result_urls = json_decode($result_urls, true);
  7650. }
  7651. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7652. // 更新资产表状态
  7653. DB::table('mp_products')
  7654. ->where('id', $product->id)
  7655. ->update([
  7656. 'pic_task_status' => '生成成功',
  7657. 'url' => $img_url,
  7658. 'updated_at' => now()
  7659. ]);
  7660. $stats[$typeName]['success']++;
  7661. $stats[$typeName]['completed']++;
  7662. $hasStatusChange = true;
  7663. dLog('anime')->info('资产图片生成成功', [
  7664. 'product_id' => $product->id,
  7665. 'task_id' => $task_id,
  7666. 'img_url' => $img_url
  7667. ]);
  7668. } elseif ($task->status === 'failed') {
  7669. // 更新资产表状态
  7670. DB::table('mp_products')
  7671. ->where('id', $product->id)
  7672. ->update([
  7673. 'pic_task_status' => '生成失败',
  7674. 'updated_at' => now()
  7675. ]);
  7676. $stats[$typeName]['completed']++;
  7677. $hasStatusChange = true;
  7678. dLog('anime')->warning('资产图片生成失败', [
  7679. 'product_id' => $product->id,
  7680. 'task_id' => $task_id,
  7681. 'error' => $task->error_message ?? '未知错误'
  7682. ]);
  7683. } else {
  7684. // 任务还在处理中
  7685. $allCompleted = false;
  7686. }
  7687. } else {
  7688. // 任务不存在,标记为失败
  7689. DB::table('mp_products')
  7690. ->where('id', $product->id)
  7691. ->update([
  7692. 'pic_task_status' => '生成失败',
  7693. 'updated_at' => now()
  7694. ]);
  7695. $stats[$type]['completed']++;
  7696. $hasStatusChange = true;
  7697. dLog('anime')->error('图片生成任务不存在', [
  7698. 'product_id' => $product->id,
  7699. 'task_id' => $task_id
  7700. ]);
  7701. }
  7702. } elseif ($currentStatus === '生成成功') {
  7703. $stats[$typeName]['success']++;
  7704. $stats[$typeName]['completed']++;
  7705. } elseif ($currentStatus === '生成失败') {
  7706. $stats[$typeName]['completed']++;
  7707. } else {
  7708. // 其他状态也认为未完成
  7709. $allCompleted = false;
  7710. }
  7711. }
  7712. // 移除没有数据的类型(total=0)
  7713. foreach ($stats as $typeName => $stat) {
  7714. if ($stat['total'] === 0) {
  7715. unset($stats[$typeName]);
  7716. }
  7717. }
  7718. // 如果有状态变化,发送 SSE 更新
  7719. if ($hasStatusChange) {
  7720. $eventType = $allCompleted ? 'complete' : 'update';
  7721. $response = [
  7722. 'type' => $eventType,
  7723. 'script_id' => $script_id,
  7724. 'script_name' => $script_name,
  7725. 'stats' => $stats,
  7726. 'timestamp' => date('Y-m-d H:i:s')
  7727. ];
  7728. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7729. dLog('anime')->info('SSE更新', [
  7730. 'event_type' => $eventType,
  7731. 'script_id' => $script_id,
  7732. 'script_name' => $script_name,
  7733. 'stats' => $stats
  7734. ]);
  7735. if ($allCompleted) {
  7736. dLog('anime')->info('所有资产图片生成任务已完成', [
  7737. 'script_id' => $script_id,
  7738. 'script_name' => $script_name,
  7739. 'stats' => $stats
  7740. ]);
  7741. break;
  7742. }
  7743. }
  7744. }
  7745. // 超时处理
  7746. if (time() - $startTime >= $timeout && !$allCompleted) {
  7747. $response = [
  7748. 'type' => 'timeout',
  7749. 'message' => '部分任务超时,请稍后查看结果',
  7750. 'script_id' => $script_id,
  7751. 'script_name' => $script_name,
  7752. 'timestamp' => date('Y-m-d H:i:s')
  7753. ];
  7754. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7755. dLog('anime')->warning('资产图片生成任务超时', [
  7756. 'script_id' => $script_id,
  7757. 'script_name' => $script_name,
  7758. 'timeout' => $timeout
  7759. ]);
  7760. }
  7761. }
  7762. /**
  7763. * 获取剧本关联的资产列表
  7764. * @param array $data 请求参数
  7765. * @return array
  7766. */
  7767. public function getScriptProducts($data) {
  7768. $uid = Site::getUid();
  7769. $cpid = Site::getCpid();
  7770. $script_id = getProp($data, 'script_id');
  7771. $episode_number = getProp($data, 'episode_number');
  7772. if (!$script_id) {
  7773. Utils::throwError('20003:请提供剧本ID');
  7774. }
  7775. // 验证剧本是否存在
  7776. $script = DB::table('mp_scripts')
  7777. ->where('id', $script_id)
  7778. ->where('is_deleted', 0)
  7779. ->first();
  7780. if (!$script) {
  7781. Utils::throwError('20003:剧本不存在');
  7782. }
  7783. // 联表查询资产信息
  7784. $query = DB::table('mp_script_product_mappings as mapping')
  7785. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7786. ->where('mapping.script_id', $script_id)
  7787. ->where('product.cpid', $cpid)
  7788. ->where('product.is_deleted', 0);
  7789. // 如果提供了 episode_number,则过滤指定集数
  7790. if ($episode_number !== null && $episode_number !== '') {
  7791. $query->where('mapping.episode_number', $episode_number);
  7792. }
  7793. $mappings = $query->select(
  7794. 'mapping.script_id',
  7795. 'mapping.product_id',
  7796. 'mapping.episode_number',
  7797. 'product.product_name',
  7798. 'product.type',
  7799. 'product.product',
  7800. 'product.pic_prompt',
  7801. 'product.url',
  7802. 'product.pic_task_id',
  7803. 'product.pic_task_status',
  7804. 'product.three_view_image_url',
  7805. 'mapping.created_at'
  7806. )
  7807. ->orderBy('mapping.product_id', 'asc')
  7808. ->orderBy('mapping.episode_number', 'asc')
  7809. ->get();
  7810. // 按 product_id 分组,合并 episode_number
  7811. $productMap = [];
  7812. foreach ($mappings as $item) {
  7813. $product_id = $item->product_id;
  7814. if (!isset($productMap[$product_id])) {
  7815. $productMap[$product_id] = [
  7816. 'product_id' => $product_id,
  7817. 'product_name' => $item->product_name,
  7818. 'type' => (int)$item->type,
  7819. 'product' => (int)$item->product,
  7820. 'pic_prompt' => $item->pic_prompt,
  7821. 'url' => $item->url,
  7822. 'pic_task_id' => $item->pic_task_id,
  7823. 'pic_task_status' => $item->pic_task_status,
  7824. 'episode_numbers' => [],
  7825. 'created_at' => $item->created_at,
  7826. ];
  7827. }
  7828. // 添加 episode_number(去重)
  7829. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7830. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7831. }
  7832. }
  7833. // 按类型分组
  7834. $roles = []; // type=1 角色/主体
  7835. $scenes = []; // type=2 场景
  7836. $props = []; // type=3 道具
  7837. foreach ($productMap as $product) {
  7838. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7839. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7840. // 构造返回数据
  7841. $productData = [
  7842. 'product_id' => $product['product_id'],
  7843. 'product_name' => $product['product_name'],
  7844. 'product' => $product['product'],
  7845. 'pic_prompt' => $product['pic_prompt'],
  7846. 'url' => $product['url'],
  7847. 'pic_task_id' => $product['pic_task_id'],
  7848. 'pic_task_status' => $product['pic_task_status'],
  7849. 'episode_numbers' => $episodeNumbersStr,
  7850. 'created_at' => $product['created_at'],
  7851. ];
  7852. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7853. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7854. switch ($product['product']) {
  7855. case 1:
  7856. $roles[] = $productData;
  7857. break;
  7858. case 2:
  7859. $scenes[] = $productData;
  7860. break;
  7861. case 3:
  7862. $props[] = $productData;
  7863. break;
  7864. }
  7865. }
  7866. return [
  7867. 'script_id' => $script_id,
  7868. 'script_name' => $script->script_name ?? '',
  7869. 'roles' => $roles, // 主体
  7870. 'scenes' => $scenes, // 场景
  7871. 'props' => $props, // 道具
  7872. ];
  7873. }
  7874. /**
  7875. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7876. * @param string $actContent 原始内容
  7877. * @param array $products 产品数组(包含product_name和url)
  7878. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7879. */
  7880. public function processActContentWithProducts($actContent, $products) {
  7881. if (empty($actContent) || empty($products)) {
  7882. return [
  7883. 'content' => $actContent,
  7884. 'reference_images' => []
  7885. ];
  7886. }
  7887. // 构建产品名称到产品信息的映射
  7888. $product_dict = [];
  7889. foreach ($products as $product) {
  7890. $product_name = getProp($product, 'product_name');
  7891. if ($product_name) {
  7892. $product_dict[$product_name] = [
  7893. 'url' => getProp($product, 'url'),
  7894. 'voice_prompt' => getProp($product, 'voice_prompt')
  7895. ];
  7896. }
  7897. }
  7898. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7899. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7900. $reference_images = [];
  7901. $product_index_map = []; // 产品名称 => 图片序号的映射
  7902. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7903. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7904. $current_index = 1;
  7905. if (!empty($matches[1])) {
  7906. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7907. $seen_products = []; // 用于去重
  7908. foreach ($matches[1] as $product_name) {
  7909. // 跳过已处理的产品
  7910. if (isset($seen_products[$product_name])) {
  7911. continue;
  7912. }
  7913. $seen_products[$product_name] = true;
  7914. // 检查产品是否在字典中
  7915. if (isset($product_dict[$product_name])) {
  7916. $url = $product_dict[$product_name]['url'];
  7917. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7918. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7919. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7920. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7921. }
  7922. // 只有URL非空才分配序号和添加到参考图片
  7923. if (!empty($url)) {
  7924. // 检查URL是否已经在reference_images中(去重)
  7925. if (!in_array($url, $reference_images)) {
  7926. $reference_images[] = $url;
  7927. $product_index_map[$product_name] = $current_index;
  7928. $current_index++;
  7929. } else {
  7930. // URL重复,找到已有的序号
  7931. $existing_index = array_search($url, $reference_images) + 1;
  7932. $product_index_map[$product_name] = $existing_index;
  7933. }
  7934. } else {
  7935. // URL为空,不分配序号(后续直接去掉{})
  7936. $product_index_map[$product_name] = 0;
  7937. }
  7938. } else {
  7939. // 产品不在字典中,不分配序号
  7940. $product_index_map[$product_name] = 0;
  7941. }
  7942. }
  7943. }
  7944. // 第二步:替换内容中的 {产品名称}
  7945. $processedContent = $actContent;
  7946. foreach ($product_index_map as $product_name => $index) {
  7947. $escaped_name = preg_quote($product_name, '/');
  7948. if ($index > 0) {
  7949. // 有图片,替换为:产品名称(图X)
  7950. $replacement = $product_name . '<图片' . $index . '>';
  7951. } else {
  7952. // 无图片,只保留产品名称
  7953. $replacement = $product_name;
  7954. }
  7955. // 替换所有 {产品名称} 为处理后的格式
  7956. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7957. }
  7958. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7959. foreach ($products as $product) {
  7960. $product_name = getProp($product, 'product_name');
  7961. $voice_prompt = getProp($product, 'voice_prompt');
  7962. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7963. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7964. break; // 找到旁白后退出循环
  7965. }
  7966. }
  7967. // 第四步:将voice_prompt信息添加到内容最前面
  7968. $voice_prompt_prefix = '';
  7969. if (!empty($voice_prompts)) {
  7970. $voice_prompt_prefix .= implode('', $voice_prompts);
  7971. }
  7972. // 旁白的voice_prompt放在最后
  7973. if (!empty($narrator_voice_prompt)) {
  7974. $voice_prompt_prefix .= $narrator_voice_prompt;
  7975. }
  7976. // 如果有voice_prompt信息,添加到内容开头
  7977. if (!empty($voice_prompt_prefix)) {
  7978. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7979. }
  7980. return [
  7981. 'content' => $processedContent,
  7982. 'reference_images' => $reference_images
  7983. ];
  7984. }
  7985. public function saveActVideoGenerateParams($data) {
  7986. $episode_id = getProp($data, 'episode_id');
  7987. $model = getProp($data, 'video_model');
  7988. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7989. Utils::throwError('20003:该模型不可用');
  7990. }
  7991. if (!$model) {
  7992. // 使用默认模型
  7993. $model = 'zhizhen-20';
  7994. }
  7995. // 验证模型是否在可用模型表中
  7996. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7997. Utils::throwError('20003:该模型已不可用,请更换!');
  7998. }
  7999. $video_resolution = getProp($data, 'video_resolution', '720p');
  8000. $ratio = getProp($data, 'ratio');
  8001. if (!$ratio) $ratio = '9:16';
  8002. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8003. if (!$episode) {
  8004. Utils::throwError('20003:分集不存在');
  8005. }
  8006. try {
  8007. DB::beginTransaction();
  8008. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8009. 'video_model' => $model,
  8010. 'video_resolution' => $video_resolution,
  8011. 'ratio' => $ratio,
  8012. 'updated_at' => date('Y-m-d H:i:s')
  8013. ]);
  8014. if ($result === false) {
  8015. Utils::throwError('20003:分集视频参数保存失败');
  8016. }
  8017. // 同步更新mp_animes表
  8018. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8019. 'video_model' => $model,
  8020. 'video_resolution' => $video_resolution,
  8021. 'video_ratio' => $ratio,
  8022. 'updated_at' => date('Y-m-d H:i:s')
  8023. ]);
  8024. if ($anime_result === false) {
  8025. Utils::throwError('20003:动漫视频参数保存失败');
  8026. }
  8027. } catch (\Exception $e) {
  8028. DB::rollBack();
  8029. Utils::throwError('20003:'.$e->getMessage());
  8030. }
  8031. DB::commit();
  8032. return $result;
  8033. }
  8034. public function confirmActs($data) {
  8035. $episode_id = getProp($data, 'episode_id');
  8036. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8037. if (!$episode) {
  8038. Utils::throwError('20003:分集不存在');
  8039. }
  8040. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8041. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8042. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8043. // 获取所有片段数据
  8044. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8045. // 收集所有资产名称(角色、场景、道具)
  8046. $product_names = [];
  8047. // 收集角色名称
  8048. foreach ($roles as $role) {
  8049. $role_name = getProp($role, 'role');
  8050. if ($role_name && $role_name != '旁白') {
  8051. $product_names[] = $role_name;
  8052. }
  8053. }
  8054. // 收集场景名称
  8055. foreach ($scenes as $scene) {
  8056. $scene_name = getProp($scene, 'scene');
  8057. if ($scene_name) {
  8058. $product_names[] = $scene_name;
  8059. }
  8060. }
  8061. // 收集道具名称
  8062. foreach ($props as $prop) {
  8063. $prop_name = getProp($prop, 'prop');
  8064. if ($prop_name) {
  8065. $product_names[] = $prop_name;
  8066. }
  8067. }
  8068. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8069. $product_names = array_unique($product_names);
  8070. usort($product_names, function($a, $b) {
  8071. return mb_strlen($b) - mb_strlen($a);
  8072. });
  8073. try {
  8074. DB::beginTransaction();
  8075. // 处理每个片段
  8076. foreach ($acts as $act) {
  8077. $act_content = getProp($act, 'act_content');
  8078. if (!$act_content) continue;
  8079. $processed_content = $act_content;
  8080. // 统一替换所有资产名称为 {资产名} 格式
  8081. // 使用占位符避免嵌套替换问题
  8082. $placeholder_map = [];
  8083. $placeholder_index = 0;
  8084. foreach ($product_names as $product_name) {
  8085. // 转义特殊字符
  8086. $escaped_product = preg_quote($product_name, '/');
  8087. // 检查是否匹配且未被 {} 包裹
  8088. $processed_content = preg_replace_callback(
  8089. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8090. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8091. // 使用唯一占位符
  8092. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8093. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8094. $placeholder_index++;
  8095. return $placeholder;
  8096. },
  8097. $processed_content
  8098. );
  8099. }
  8100. // 将所有占位符替换回实际内容
  8101. foreach ($placeholder_map as $placeholder => $replacement) {
  8102. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8103. }
  8104. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8105. $shot_counter = 0;
  8106. $processed_content = preg_replace_callback(
  8107. '/【(?:镜头|分镜)(\d+)】/u',
  8108. function($matches) use (&$shot_counter) {
  8109. $shot_counter++;
  8110. return '【镜头' . $shot_counter . '】';
  8111. },
  8112. $processed_content
  8113. );
  8114. // 更新数据库
  8115. $boolen = DB::table('mp_episode_segments')
  8116. ->where('id', $act->id)
  8117. ->update([
  8118. 'act_show_content' => $processed_content,
  8119. 'updated_at' => date('Y-m-d H:i:s')
  8120. ]);
  8121. if (!$boolen) {
  8122. Utils::throwError('20003:片段处理失败');
  8123. }
  8124. }
  8125. }catch (\Exception $e) {
  8126. DB::rollBack();
  8127. Utils::throwError('20003:'.$e->getMessage());
  8128. }
  8129. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8130. 'is_generated' => 1,
  8131. 'updated_at' => date('Y-m-d H:i:s')
  8132. ]);
  8133. if (!$boolen1) {
  8134. DB::rollBack();
  8135. Utils::throwError('20003:分集处理失败!');
  8136. }
  8137. DB::commit();
  8138. // 重新查询更新后的片段数据
  8139. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8140. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8141. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8142. $products = [];
  8143. // 先处理角色数组
  8144. foreach ($roles as $role) {
  8145. $product = $role;
  8146. // 将role字段重命名为product_name
  8147. if (isset($product['role'])) {
  8148. $product['product_name'] = $product['role'];
  8149. unset($product['role']);
  8150. $product['product'] = 1; // 标记类型为角色
  8151. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8152. }
  8153. }
  8154. // 处理场景数组
  8155. foreach ($scenes as $scene) {
  8156. $product = $scene;
  8157. // 将scene字段重命名为product_name
  8158. if (isset($product['scene'])) {
  8159. $product['product_name'] = $product['scene'];
  8160. unset($product['scene']);
  8161. $product['product'] = 2; // 标记类型为场景
  8162. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8163. }
  8164. }
  8165. // 处理道具数组(逻辑与场景一致)
  8166. foreach ($props as $prop) {
  8167. $product = $prop;
  8168. // 将prop字段重命名为product_name
  8169. if (isset($product['prop'])) {
  8170. $product['product_name'] = $product['prop'];
  8171. unset($product['prop']);
  8172. $product['product'] = 3; // 标记类型为道具
  8173. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8174. }
  8175. }
  8176. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8177. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8178. foreach ($extra_products as $extra_product) {
  8179. $product_name = getProp($extra_product, 'product_name');
  8180. if ($product_name) {
  8181. $products[$product_name] = $extra_product; // 覆盖同名数据
  8182. }
  8183. }
  8184. // 重新索引数组(去除key)
  8185. $products = array_values($products);
  8186. // 构建返回的acts数组
  8187. $return_acts = [];
  8188. foreach ($acts as $act) {
  8189. $return_acts[] = [
  8190. 'act_id' => getProp($act, 'id'),
  8191. 'act_number' => getProp($act, 'act_number'),
  8192. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8193. 'act_show_content' => getProp($act, 'act_show_content'),
  8194. 'video_url' => getProp($act, 'video_url'),
  8195. 'video_duration' => getProp($act, 'video_duration'),
  8196. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8197. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8198. ];
  8199. }
  8200. return [
  8201. 'anime_id' => getProp($episode, 'anime_id'),
  8202. 'episode_id' => $episode_id,
  8203. 'title' => getProp($episode, 'title'),
  8204. 'episode_number' => getProp($episode, 'episode_number'),
  8205. 'is_generated' => getProp($episode, 'is_generated'),
  8206. 'video_params' => [
  8207. 'video_model' => getProp($episode, 'video_model'),
  8208. 'video_resolution' => getProp($episode, 'video_resolution'),
  8209. 'ratio' => getProp($episode, 'ratio'),
  8210. ],
  8211. 'products' => $products,
  8212. 'acts' => $return_acts
  8213. ];
  8214. }
  8215. /**
  8216. * 导出动漫剧本为PDF(参照示例PDF版式)
  8217. * @param int $animeId 动漫ID
  8218. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8219. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8220. * @return string|null
  8221. */
  8222. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8223. // 图片下载与转换可能占用较多内存
  8224. ini_set('memory_limit', '512M');
  8225. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8226. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8227. $anime = (array)$anime;
  8228. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8229. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8230. // 获取分集(默认展示版本,按集数升序)
  8231. $episodeQuery = DB::table('mp_anime_episodes')
  8232. ->where('anime_id', $animeId)
  8233. ->where('is_default', 1)
  8234. ->orderBy('episode_number')
  8235. ->orderBy('id');
  8236. if ($episodeCount > 0) {
  8237. $episodeQuery->limit($episodeCount);
  8238. }
  8239. $episodes = $episodeQuery->get()->map(function ($value) {
  8240. return (array)$value;
  8241. })->toArray();
  8242. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8243. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8244. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8245. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8246. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8247. // 组装分集剧本数据
  8248. $episodeScripts = [];
  8249. foreach ($episodes as $episode) {
  8250. $segments = DB::table('mp_episode_segments')
  8251. ->where('anime_id', $animeId)
  8252. ->where('episode_id', $episode['id'])
  8253. ->get();
  8254. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8255. $acts = [];
  8256. foreach ($segments as $segment) {
  8257. $segment = (array)$segment;
  8258. $actNumber = (int)getProp($segment, 'act_number', 0);
  8259. if ($actNumber <= 0) continue;
  8260. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8261. $acts[$actNumber] = [
  8262. 'id' => (int)$segment['id'],
  8263. 'act_number' => $actNumber,
  8264. 'duration' => getProp($segment, 'act_duration', ''),
  8265. 'content' => getProp($segment, 'act_content', ''),
  8266. ];
  8267. }
  8268. }
  8269. ksort($acts);
  8270. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8271. $segmentCounter = 0;
  8272. foreach ($acts as &$act) {
  8273. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8274. }
  8275. unset($act);
  8276. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8277. $narratorVoice = '';
  8278. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8279. foreach ($episodeRoles as $role) {
  8280. if (getProp($role, 'role') === '旁白') {
  8281. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8282. break;
  8283. }
  8284. }
  8285. if ($narratorVoice === '') {
  8286. foreach ($acts as $act) {
  8287. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8288. $narratorVoice = trim($match[1]);
  8289. break;
  8290. }
  8291. }
  8292. }
  8293. $episodeScripts[] = [
  8294. 'episode_number' => getProp($episode, 'episode_number'),
  8295. 'title' => getProp($episode, 'title', ''),
  8296. 'act_count' => count($acts),
  8297. 'narrator_voice' => $narratorVoice,
  8298. 'acts' => array_values($acts),
  8299. ];
  8300. }
  8301. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8302. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8303. // 构建PDF
  8304. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8305. // 图片已嵌入PDF,清理临时文件
  8306. foreach ($imageCache as $imgFile) {
  8307. @unlink($imgFile);
  8308. }
  8309. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8310. if ($savePath) {
  8311. $pdf->Output($savePath, 'F');
  8312. return $savePath;
  8313. }
  8314. // 直接下载输出
  8315. header('Content-Type: application/pdf');
  8316. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8317. $pdf->Output($filename . '.pdf', 'D');
  8318. exit();
  8319. }
  8320. /**
  8321. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8322. * @param array $episodes 分集数据
  8323. * @param string $nameKey role|scene|prop
  8324. * @return array
  8325. */
  8326. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8327. $fieldMap = [
  8328. 'role' => 'roles',
  8329. 'scene' => 'scenes',
  8330. 'prop' => 'props',
  8331. ];
  8332. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8333. $items = [];
  8334. foreach ($episodes as $episode) {
  8335. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8336. foreach ($list as $item) {
  8337. if (!is_array($item)) continue;
  8338. $name = trim((string)getProp($item, $nameKey, ''));
  8339. if ($name === '') continue;
  8340. // 旁白不进入主体列表(仅作为旁白音色来源)
  8341. if ($nameKey === 'role' && $name === '旁白') continue;
  8342. if (!isset($items[$name])) {
  8343. $items[$name] = $item;
  8344. }
  8345. }
  8346. }
  8347. return array_values($items);
  8348. }
  8349. /**
  8350. * 构建动漫剧本PDF
  8351. * @param array $anime 动漫信息
  8352. * @param array $roles 主体列表
  8353. * @param array $scenes 场景列表
  8354. * @param array $props 道具列表
  8355. * @param array $episodeScripts 分集剧本数据
  8356. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8357. * @return \TCPDF
  8358. */
  8359. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8360. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8361. $pdf->SetCreator('动漫剧本导出系统');
  8362. $pdf->SetAuthor('系统');
  8363. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8364. $pdf->SetSubject('动漫剧本导出');
  8365. $pdf->SetMargins(15, 15, 15);
  8366. $pdf->SetAutoPageBreak(true, 15);
  8367. // 剧本名
  8368. $pdf->AddPage();
  8369. $pdf->SetFont('simsun', 'B', 20);
  8370. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8371. $pdf->Ln(5);
  8372. // 故事梗概
  8373. $intro = trim((string)getProp($anime, 'intro', ''));
  8374. if ($intro !== '') {
  8375. $this->pdfSectionTitle($pdf, '故事梗概');
  8376. $this->pdfBody($pdf, $intro);
  8377. }
  8378. // 美术风格
  8379. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  8380. if ($artStyle !== '') {
  8381. $this->pdfSectionTitle($pdf, '美术风格');
  8382. $this->pdfBody($pdf, $artStyle);
  8383. }
  8384. // 主体列表(文字+图片)
  8385. $this->pdfSectionTitle($pdf, '主体列表');
  8386. foreach ($roles as $index => $role) {
  8387. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  8388. }
  8389. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  8390. // 场景列表(文字+图片)
  8391. $this->pdfSectionTitle($pdf, '场景列表');
  8392. foreach ($scenes as $index => $scene) {
  8393. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  8394. }
  8395. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  8396. // 道具列表(文字+图片)
  8397. $this->pdfSectionTitle($pdf, '道具列表');
  8398. foreach ($props as $index => $prop) {
  8399. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  8400. }
  8401. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  8402. // 分镜剧本
  8403. $this->pdfSectionTitle($pdf, '分镜剧本');
  8404. foreach ($episodeScripts as $episodeScript) {
  8405. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  8406. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  8407. if ($episodeTitleRaw !== '') {
  8408. // title 字段可能已带"第N集"前缀,避免重复
  8409. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  8410. $episodeTitle = $episodeTitleRaw;
  8411. } else {
  8412. $episodeTitle .= ':' . $episodeTitleRaw;
  8413. }
  8414. }
  8415. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  8416. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  8417. if (getProp($episodeScript, 'narrator_voice') !== '') {
  8418. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  8419. }
  8420. foreach (getProp($episodeScript, 'acts', []) as $act) {
  8421. $actTitle = '片段' . getProp($act, 'act_number');
  8422. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  8423. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  8424. }
  8425. $this->pdfSubTitle($pdf, $actTitle, 12);
  8426. if (getProp($act, 'content') !== '') {
  8427. $this->pdfBody($pdf, getProp($act, 'content'));
  8428. }
  8429. }
  8430. }
  8431. return $pdf;
  8432. }
  8433. /**
  8434. * PDF章节标题(带分隔线)
  8435. */
  8436. private function pdfSectionTitle($pdf, $title) {
  8437. if ($pdf->GetY() > 230) {
  8438. $pdf->AddPage();
  8439. }
  8440. $pdf->SetFont('simsun', 'B', 15);
  8441. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  8442. $y = $pdf->GetY();
  8443. $pdf->SetLineWidth(0.4);
  8444. $pdf->Line(15, $y, 195, $y);
  8445. $pdf->Ln(4);
  8446. }
  8447. /**
  8448. * PDF子标题(集数/片段标题)
  8449. */
  8450. private function pdfSubTitle($pdf, $title, $size = 13) {
  8451. if ($pdf->GetY() > 240) {
  8452. $pdf->AddPage();
  8453. }
  8454. $pdf->SetFont('simsun', 'B', $size);
  8455. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  8456. $pdf->Ln(1);
  8457. }
  8458. /**
  8459. * PDF正文段落
  8460. */
  8461. private function pdfBody($pdf, $text) {
  8462. $pdf->SetFont('simsun', '', 11);
  8463. $pdf->MultiCell(0, 6, $text, 0, 'L');
  8464. $pdf->Ln(2);
  8465. }
  8466. /**
  8467. * 输出列表项图片(每张图单独一页,图下标注名称)
  8468. * @param \TCPDF $pdf
  8469. * @param array $items 列表项
  8470. * @param string $nameKey role|scene|prop
  8471. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8472. */
  8473. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  8474. foreach ($items as $item) {
  8475. $url = trim((string)getProp($item, 'url', ''));
  8476. $name = trim((string)getProp($item, $nameKey, ''));
  8477. if ($url === '' || !isset($imageCache[$url])) continue;
  8478. $imgPath = $imageCache[$url];
  8479. $size = @getimagesize($imgPath);
  8480. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  8481. continue;
  8482. }
  8483. $pdf->AddPage();
  8484. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  8485. $maxW = 160;
  8486. $maxH = 170;
  8487. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  8488. $drawW = $size[0] * $ratio;
  8489. $drawH = $size[1] * $ratio;
  8490. $x = (210 - $drawW) / 2;
  8491. $y = max(15, (297 - $drawH) / 2 - 10);
  8492. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  8493. // 图下标注名称
  8494. $pdf->SetFont('simsun', 'B', 13);
  8495. $pdf->SetY(297 - 28);
  8496. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  8497. }
  8498. }
  8499. /**
  8500. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  8501. * @param array $items 包含url字段的列表项
  8502. * @return array url => 临时文件路径
  8503. */
  8504. private function downloadImagesConcurrently(array $items) {
  8505. // 收集唯一的图片URL
  8506. $urls = [];
  8507. foreach ($items as $item) {
  8508. $url = trim((string)getProp($item, 'url', ''));
  8509. if ($url !== '') $urls[$url] = true;
  8510. }
  8511. if (!$urls) return [];
  8512. $urls = array_keys($urls);
  8513. $tmpDir = sys_get_temp_dir();
  8514. $rawFiles = [];
  8515. foreach ($urls as $url) {
  8516. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  8517. $rawFiles[$url] = $rawFile;
  8518. }
  8519. $client = new Client(['timeout' => 180, 'verify' => false]);
  8520. // 低并发下载,sink写入文件避免大图占用内存
  8521. $generator = (function () use ($urls, $client, $rawFiles) {
  8522. foreach ($urls as $url) {
  8523. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  8524. }
  8525. })();
  8526. $errors = [];
  8527. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  8528. 'concurrency' => 4,
  8529. 'rejected' => function ($reason, $url) use (&$errors) {
  8530. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  8531. },
  8532. ]);
  8533. $each->promise()->wait();
  8534. // 失败的图片串行重试一次(独占带宽,提高成功率)
  8535. foreach ($urls as $url) {
  8536. if (!isset($errors[$url])) continue;
  8537. try {
  8538. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  8539. unset($errors[$url]);
  8540. } catch (\Throwable $e) {
  8541. // 重试仍失败
  8542. }
  8543. }
  8544. $cache = [];
  8545. foreach ($urls as $url) {
  8546. $rawFile = $rawFiles[$url];
  8547. if (isset($errors[$url])) {
  8548. dLog('anime')->error('导出PDF图片下载失败', [
  8549. 'url' => $url,
  8550. 'error' => $errors[$url],
  8551. ]);
  8552. @unlink($rawFile);
  8553. continue;
  8554. }
  8555. $converted = $this->convertImageFile($rawFile, $url);
  8556. if ($converted !== null) {
  8557. $cache[$url] = $converted;
  8558. } else {
  8559. @unlink($rawFile);
  8560. }
  8561. }
  8562. return $cache;
  8563. }
  8564. /**
  8565. * 将已下载的图片文件缩放并转为JPEG
  8566. * @param string $rawFile 原始图片临时文件
  8567. * @param string $url 图片地址(用于命名)
  8568. * @return string|null 转换后的文件路径,转换失败返回null
  8569. */
  8570. private function convertImageFile($rawFile, $url) {
  8571. $content = @file_get_contents($rawFile);
  8572. if ($content === false || $content === '') return null;
  8573. if (!function_exists('imagecreatefromstring')) return null;
  8574. $image = @imagecreatefromstring($content);
  8575. if ($image === false) return null;
  8576. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  8577. imagedestroy($image);
  8578. if ($jpeg !== null) {
  8579. @unlink($rawFile);
  8580. }
  8581. return $jpeg;
  8582. }
  8583. /**
  8584. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  8585. * @param resource $srcImage GD图片资源
  8586. * @param string $rawFile 原始图片临时文件
  8587. * @param string $url 图片地址(用于命名)
  8588. * @return string|null 压缩后的JPEG文件路径
  8589. */
  8590. private function compressImageForPdf($srcImage, $rawFile, $url) {
  8591. $maxBytes = 2 * 1024 * 1024; // 2MB
  8592. $sizes = [2048, 1600, 1280, 1024, 800];
  8593. $qualities = [85, 70, 55, 40];
  8594. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  8595. foreach ($sizes as $size) {
  8596. $resized = $this->copyAndResize($srcImage, $size);
  8597. $flat = $this->flattenToWhite($resized);
  8598. imagedestroy($resized);
  8599. foreach ($qualities as $quality) {
  8600. ob_start();
  8601. $saved = imagejpeg($flat, null, $quality);
  8602. $data = ob_get_clean();
  8603. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  8604. file_put_contents($jpeg, $data);
  8605. imagedestroy($flat);
  8606. dLog('anime')->info('导出PDF图片压缩完成', [
  8607. 'url' => $url,
  8608. 'size' => filesize($jpeg),
  8609. 'edge' => $size,
  8610. 'quality' => $quality,
  8611. ]);
  8612. return $jpeg;
  8613. }
  8614. }
  8615. imagedestroy($flat);
  8616. }
  8617. // 兜底:最小尺寸、最低质量强制输出
  8618. $resized = $this->copyAndResize($srcImage, 800);
  8619. $flat = $this->flattenToWhite($resized);
  8620. imagedestroy($resized);
  8621. $saved = imagejpeg($flat, $jpeg, 30);
  8622. imagedestroy($flat);
  8623. if (!$saved) return null;
  8624. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  8625. 'url' => $url,
  8626. 'size' => filesize($jpeg),
  8627. ]);
  8628. return $jpeg;
  8629. }
  8630. /**
  8631. * 等比缩放图片副本(不销毁原图)
  8632. * @param resource $srcImage GD图片资源
  8633. * @param int $maxEdge 最大边长
  8634. * @return resource
  8635. */
  8636. private function copyAndResize($srcImage, $maxEdge) {
  8637. $width = imagesx($srcImage);
  8638. $height = imagesy($srcImage);
  8639. $max = max($width, $height);
  8640. if ($max <= $maxEdge) {
  8641. $copy = imagecreatetruecolor($width, $height);
  8642. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  8643. return $copy;
  8644. }
  8645. $ratio = $maxEdge / $max;
  8646. $newWidth = max(1, (int)round($width * $ratio));
  8647. $newHeight = max(1, (int)round($height * $ratio));
  8648. $resized = imagecreatetruecolor($newWidth, $newHeight);
  8649. imagealphablending($resized, false);
  8650. imagesavealpha($resized, true);
  8651. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  8652. return $resized;
  8653. }
  8654. /**
  8655. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  8656. * @param resource $image GD图片资源
  8657. * @return resource
  8658. */
  8659. private function flattenToWhite($image) {
  8660. $width = imagesx($image);
  8661. $height = imagesy($image);
  8662. $flat = imagecreatetruecolor($width, $height);
  8663. $white = imagecolorallocate($flat, 255, 255, 255);
  8664. imagefill($flat, 0, 0, $white);
  8665. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  8666. return $flat;
  8667. }
  8668. /**
  8669. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  8670. * @param string $content 片段内容
  8671. * @param int $counter 当前已编号数量(引用传递,整集累计)
  8672. * @return string
  8673. */
  8674. private function renumberSegmentBlocks($content, &$counter) {
  8675. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  8676. $counter++;
  8677. return '【' . $match[1] . $counter . '】';
  8678. }, $content);
  8679. }
  8680. }