AnimeService.php 447 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452
  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\Models\MpTaskCenter;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use App\Services\AIGeneration\AIVideoGenerationService;
  11. use App\Services\DeepSeek\DeepSeekService;
  12. use App\Services\PointsService;
  13. use App\Services\TaskCenterService;
  14. use Dflydev\DotAccessData\Util;
  15. use GuzzleHttp\Client;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Redis;
  19. use OSS\Core\OssException;
  20. use OSS\OssClient;
  21. class AnimeService
  22. {
  23. protected $aiImageGenerationService;
  24. protected $aiVideoGenerationService;
  25. protected $DeepSeekService;
  26. protected $pointsService;
  27. protected $taskCenterService;
  28. private $url;
  29. private $api_key;
  30. private $headers;
  31. public function __construct(
  32. AIImageGenerationService $aiImageGenerationService,
  33. AIVideoGenerationService $aiVideoGenerationService,
  34. DeepSeekService $DeepSeekService,
  35. PointsService $pointsService,
  36. TaskCenterService $taskCenterService
  37. ) {
  38. $this->aiImageGenerationService = $aiImageGenerationService;
  39. $this->aiVideoGenerationService = $aiVideoGenerationService;
  40. $this->DeepSeekService = $DeepSeekService;
  41. $this->pointsService = $pointsService;
  42. $this->taskCenterService = $taskCenterService;
  43. $this->url = 'https://api.deepseek.com/chat/completions';
  44. $this->api_key = env('DEEPSEEK_API_KEY');
  45. $this->headers = [
  46. 'Authorization' => 'Bearer '.$this->api_key,
  47. 'Content-Type' => 'application/json; charset=UTF-8'
  48. ];
  49. }
  50. /**
  51. * 构建统一的分镜数据结构(episodeInfo格式)
  52. * @param array $segments 分镜数据数组
  53. * @return array 返回包含acts和total_duration的数组
  54. */
  55. public function buildEpisodeSegmentsStructure($segments) {
  56. $acts = [];
  57. $totalDuration = 0; // 初始化总时长
  58. foreach($segments as $segment) {
  59. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  60. $videoDuration = getProp($segment, 'video_duration');
  61. $audioDuration = getProp($segment, 'audio_duration');
  62. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  63. $totalDuration += floatval($videoDuration);
  64. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  65. $totalDuration += floatval($audioDuration);
  66. } else {
  67. $totalDuration += 5; // 默认5秒
  68. }
  69. $segment_content = getProp($segment, 'segment_content');
  70. // 判断是否有尾帧描述,如果有则去掉这部分内容
  71. if (strpos($segment_content, '尾帧') !== false) {
  72. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  73. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  74. }
  75. // 构建分镜信息
  76. $segmentInfo = [
  77. 'segment_id' => getProp($segment, 'segment_id'),
  78. 'segment_number' => getProp($segment, 'segment_number'),
  79. 'segment_content' => $segment_content,
  80. 'description' => getProp($segment, 'description'),
  81. 'composition' => getProp($segment, 'composition'),
  82. 'camera_movement' => getProp($segment, 'camera_movement'),
  83. 'voice_actor' => getProp($segment, 'voice_actor'),
  84. 'dialogue' => getProp($segment, 'dialogue'),
  85. 'frame_type' => getProp($segment, 'frame_type'),
  86. 'scene' => getProp($segment, 'scene'),
  87. 'characters' => getProp($segment, 'characters'),
  88. 'tail_frame' => getProp($segment, 'tail_frame'),
  89. 'emotion' => getProp($segment, 'emotion'),
  90. 'emotion_type' => getProp($segment, 'emotion_type'),
  91. 'gender' => getProp($segment, 'gender'),
  92. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  93. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  94. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  95. 'pitch' => getProp($segment, 'pitch'),
  96. 'voice_name' => getProp($segment, 'voice_name'),
  97. 'voice_type' => getProp($segment, 'voice_type'),
  98. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  99. 'img_url' => getProp($segment, 'img_url'),
  100. 'audio_url' => getProp($segment, 'audio_url'),
  101. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  102. 'video_url' => getProp($segment, 'video_url'),
  103. 'video_duration' => getProp($segment, 'video_duration', 0),
  104. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  105. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  106. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  107. 'current_type' => getProp($segment, 'current_type'),
  108. ];
  109. $actNumber = getProp($segment, 'act_number');
  110. if (isset($acts[$actNumber])) {
  111. $acts[$actNumber]['segments'][] = $segmentInfo;
  112. } else {
  113. $acts[$actNumber] = [
  114. 'act_number' => $actNumber,
  115. 'act_title' => getProp($segment, 'act_title'),
  116. 'act_duration' => getProp($segment, 'act_duration'),
  117. 'segments' => [$segmentInfo]
  118. ];
  119. }
  120. }
  121. return [
  122. 'acts' => array_values($acts),
  123. 'total_duration' => intval(round($totalDuration))
  124. ];
  125. }
  126. /**
  127. * 构建统一的分段数据结构(episodeInfoForAce格式)
  128. * @param array $segments 分段数据数组
  129. * @return array 返回包含acts和total_duration的数组
  130. */
  131. public function buildEpisodeActsStructureForAce($segments) {
  132. $acts = [];
  133. $totalDuration = 0; // 初始化总时长
  134. foreach($segments as $segment) {
  135. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  136. $videoDuration = getProp($segment, 'video_duration');
  137. $actDuration = getProp($segment, 'act_duration');
  138. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  139. $totalDuration += floatval($videoDuration);
  140. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  141. $totalDuration += floatval($actDuration);
  142. } else {
  143. $totalDuration += 5; // 默认5秒
  144. }
  145. // 构建分镜信息
  146. $segmentInfo = [
  147. 'act_id' => getProp($segment, 'id'),
  148. 'act_number' => getProp($segment, 'act_number'),
  149. 'act_title' => getProp($segment, 'act_title'),
  150. 'act_duration' => getProp($segment, 'act_duration'),
  151. 'act_content' => getProp($segment, 'act_content'),
  152. 'video_url' => getProp($segment, 'video_url'),
  153. 'video_duration' => getProp($segment, 'video_duration', 0),
  154. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  155. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  156. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  157. 'current_type' => getProp($segment, 'current_type'),
  158. ];
  159. $acts[] = $segmentInfo;
  160. }
  161. return [
  162. 'acts' => array_values($acts),
  163. 'total_duration' => intval(round($totalDuration))
  164. ];
  165. }
  166. /**
  167. * 验证画面比例是否有效
  168. * @param string $ratio 画面比例
  169. * @return bool
  170. */
  171. public function validateRatio($ratio) {
  172. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  173. }
  174. /**
  175. * 获取画面比例对应的宽高
  176. * @param string $ratio 画面比例
  177. * @return array ['width' => int, 'height' => int]
  178. * @throws \Exception
  179. */
  180. private function getRatioDimensions($ratio) {
  181. if ($ratio && !$this->validateRatio($ratio)) {
  182. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  183. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  184. }
  185. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  186. }
  187. public function createAnime($data) {
  188. $uid = Site::getUid();
  189. $cpid = Site::getCpid();
  190. $input_art_style = getProp($data, 'art_style');
  191. $file = getProp($data, 'file');
  192. $content = getProp($data, 'content', '');
  193. $bid = getProp($data, 'bid', 0);
  194. $script_id = getProp($data, 'script_id', 0);
  195. $ace_mode = getProp($data, 'ace_mode', 0);
  196. $extra_products = getProp($data, 'products', []);
  197. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  198. if (!is_array($extra_products)) {
  199. Utils::throwError('20003:传入的资产格式不正确');
  200. }
  201. // 替换美术风格
  202. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  203. // 提取文件内容
  204. if ($file) {
  205. $content = $this->DeepSeekService->extractFileContent($file);
  206. if (!$content) {
  207. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  208. }
  209. } elseif ($script_id) {
  210. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  213. }
  214. } elseif ($bid) {
  215. $content = $this->DeepSeekService->getContentByBid($bid);
  216. if (!$content) {
  217. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  218. }
  219. } elseif ($content) {
  220. $content = filterContent($content);
  221. }else {
  222. $content = '';
  223. }
  224. $anime_data = [
  225. 'user_id' => $uid,
  226. 'cpid' => $cpid,
  227. 'anime_name' => '新剧本策划',
  228. 'is_multi' => getProp($data, 'is_multi', 1),
  229. 'content' => $content,
  230. 'art_style_type' => $input_art_style,
  231. 'ace_mode' => $ace_mode,
  232. 'script_id' => $script_id,
  233. 'extra_products' => json_encode($extra_products, 256),
  234. 'created_at' => date('Y-m-d H:i:s'),
  235. 'updated_at' => date('Y-m-d H:i:s'),
  236. ];
  237. // 处理文本模型
  238. $model = getProp($data, 'model');
  239. if (!$model) {
  240. // 用户没有输入,使用默认值
  241. $model = 'deepseek-v4-pro';
  242. }
  243. // 验证模型是否在可用模型表中
  244. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  245. $model = 'deepseek-v4-pro';
  246. }
  247. $anime_data['model'] = $model;
  248. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  249. return DB::table('mp_animes')->insertGetId($anime_data);
  250. }
  251. public function chatList($data) {
  252. $uid = Site::getUid();
  253. $anime_name = getProp($data, 'anime_name');
  254. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  255. if ($anime_name) {
  256. $query->where('anime_name', 'like', "%$anime_name%");
  257. }
  258. return $query->orderBy('id', 'desc')->paginate();
  259. }
  260. public function chatHistory($data) {
  261. $anime_id = getProp($data, 'anime_id');
  262. $sequence = getProp($data, 'sequence', 0);
  263. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  264. $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)
  265. ->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');
  266. return $query->orderBy('ar.id')->get()->map(function ($value) {
  267. $value = (array)$value;
  268. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  269. $value['created_at'] = transDate($value['created_at']);
  270. $value['episode_created_at'] = transDate($value['episode_created_at']);
  271. return $value;
  272. })->toArray();
  273. }
  274. public function batchSetRoleImg($data) {
  275. $episode_id = getProp($data, 'episode_id');
  276. if (!$episode_id) Utils::throwError('1002:请选择分集');
  277. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  278. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  279. $art_style = getProp($episode, 'art_style');
  280. $anime_id = getProp($episode, 'anime_id');
  281. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  282. $art_style_type = getProp($anime, 'art_style_type');
  283. $character_prefix = '';
  284. $scene_prefix = '';
  285. if ($art_style_type) {
  286. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  287. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  288. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  289. }
  290. foreach ($roles as &$role) {
  291. $role_name = getProp($role, 'role');
  292. if ($role_name == '旁白') continue;
  293. // 优先使用 pic_prompt,如果没有则使用 description
  294. $pic_prompt = getProp($role, 'pic_prompt');
  295. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  296. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  297. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  298. // 参考图地址
  299. $ref_img_url = getProp($role, 'url');
  300. if ($ref_img_url) continue; // 已有图片则跳过
  301. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  302. try {
  303. $params = [
  304. 'prompt' => $description,
  305. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  306. ];
  307. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  308. $task_id = $task->id;
  309. if (!$task_id) {
  310. Utils::throwError("20003:角色({$role_name})生成图片失败");
  311. }
  312. $role['task_id'] = $task_id;
  313. $role['task_status'] = 'processing';
  314. } catch (\Exception $e) {
  315. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  316. Utils::throwError("20003:" . $e->getMessage());
  317. }
  318. }
  319. // 保存角色信息
  320. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  321. 'roles' => json_encode($roles, 256),
  322. 'generate_status' => '执行中',
  323. 'generate_at' => date('Y-m-d H:i:s'),
  324. 'updated_at' => date('Y-m-d H:i:s')
  325. ]);
  326. if (!$boolen) {
  327. Utils::throwError('20003:保存角色信息失败');
  328. }
  329. return $boolen;
  330. }
  331. public function batchSetSceneImg($data) {
  332. $episode_id = getProp($data, 'episode_id');
  333. if (!$episode_id) Utils::throwError('1002:请选择分集');
  334. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  335. $scenes = json_decode(getProp($episode, 'scenes'), true);
  336. $art_style = getProp($episode, 'art_style');
  337. $target_scene = getProp($data, 'target_scene');
  338. $anime_id = getProp($episode, 'anime_id');
  339. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  340. $art_style_type = getProp($anime, 'art_style_type');
  341. $character_prefix = '';
  342. $scene_prefix = '';
  343. if ($art_style_type) {
  344. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  345. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  346. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  347. }
  348. foreach ($scenes as &$scene) {
  349. $scene_name = getProp($scene, 'scene');
  350. if ($scene_name != $target_scene) continue;
  351. // 优先使用 pic_prompt,如果没有则使用 description
  352. $pic_prompt = getProp($scene, 'pic_prompt');
  353. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  354. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  355. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  356. // 参考图地址
  357. $ref_img_url = getProp($scene, 'url');
  358. if ($ref_img_url) continue; // 已有图片则跳过
  359. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  360. try {
  361. $params = [
  362. 'prompt' => $description,
  363. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  364. ];
  365. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  366. $task_id = $task->id;
  367. if (!$task_id) {
  368. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  369. }
  370. $scene['task_id'] = $task_id;
  371. $scene['task_status'] = 'processing';
  372. } catch (\Exception $e) {
  373. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  374. Utils::throwError("20003:" . $e->getMessage());
  375. }
  376. }
  377. // 保存场景信息
  378. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  379. 'scenes' => json_encode($scenes, 256),
  380. 'generate_status' => '执行中',
  381. 'generate_at' => date('Y-m-d H:i:s'),
  382. 'updated_at' => date('Y-m-d H:i:s')
  383. ]);
  384. if (!$boolen) {
  385. Utils::throwError('20003:保存角色信息失败');
  386. }
  387. return $boolen;
  388. }
  389. public function editAnime($data) {
  390. $anime_id = getProp($data, 'anime_id');
  391. $anime_name = trim(getProp($data, 'anime_name'));
  392. // 确认对话名称唯一性
  393. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  394. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  395. }
  396. if (!$anime_id || !$anime_name) {
  397. Utils::throwError('20003:参数异常');
  398. }
  399. return DB::table('mp_animes')->where('id', $anime_id)->update([
  400. 'anime_name' => $anime_name,
  401. 'updated_at' => date('Y-m-d H:i:s')
  402. ]);
  403. // $script_arr =getProp($data, 'script', []);
  404. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  405. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  406. // $anime_id = getProp($data, 'anime_id');
  407. // try {
  408. // DB::beginTransaction();
  409. // $table_data = [
  410. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  411. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  412. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  413. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  414. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  415. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  416. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  417. // 'status' => 3,
  418. // 'start_episode_sequence' => $start_episode_sequence,
  419. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  420. // 'episode_num' => count($script_arr['episodes']),
  421. // 'updated_at' => date('Y-m-d H:i:s')
  422. // ];
  423. // // 保存剧本内容
  424. // if (!empty($anime_id)) {
  425. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  426. // if (!$boolen) {
  427. // dLog('anime')->info('对话保存失败', $table_data);
  428. // Utils::throwError('20003:对话保存失败');
  429. // }
  430. // }else {
  431. // $table['created_at'] = $table_data['updated_at'];
  432. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  433. // if (!$anime_id) {
  434. // dLog('anime')->info('对话保存失败', $table_data);
  435. // Utils::throwError('20003:对话保存失败');
  436. // }
  437. // }
  438. // // 保存分集内容
  439. // // 删除历史分集内容
  440. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  441. // $episodes = [];
  442. // $sequence = 1;
  443. // foreach ($script_arr['episodes'] as $episode) {
  444. // $segment_number = 1;
  445. // foreach($episode['segments'] as $segment) {
  446. // $episodes[] = [
  447. // 'anime_id' => $anime_id,
  448. // 'episode_number' => $episode['episode_number'],
  449. // 'title' => $episode['title'],
  450. // // 'content' => $episode['content'],
  451. // 'content' => '',
  452. // 'segment_number' => $segment_number,
  453. // 'segment_content' => $segment['segment_content'],
  454. // 'sequence' => $sequence,
  455. // 'created_at' => date('Y-m-d H:i:s'),
  456. // 'updated_at' => date('Y-m-d H:i:s')
  457. // ];
  458. // $sequence++;
  459. // $segment_number++;
  460. // }
  461. // }
  462. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  463. // if (!$boolen2) {
  464. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  465. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  466. // Utils::throwError('20003:分集内容保存失败');
  467. // }
  468. // } catch (\Exception $e) {
  469. // DB::rollBack();
  470. // Utils::throwError('20003:'.$e->getMessage());
  471. // }
  472. // DB::commit();
  473. // return true;
  474. }
  475. public function delAnime($data) {
  476. $anime_id = getProp($data, 'anime_id');
  477. if (!$anime_id) {
  478. Utils::throwError('20003:请选择剧本');
  479. }
  480. return DB::table('mp_animes')->where('id', $anime_id)->update([
  481. 'is_deleted' => 1,
  482. 'updated_at' => date('Y-m-d H:i:s')
  483. ]);
  484. }
  485. public function animeDetail($data) {
  486. $uid = Site::getUid();
  487. $anime_id = getProp($data, 'anime_id');
  488. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  489. ->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();
  490. if (!$anime) Utils::throwError('20003:权限不足');
  491. $anime = (array)$anime;
  492. $anime['roles'] = json_decode($anime['roles']);
  493. $anime['scenes'] = json_decode($anime['scenes']);
  494. // 获取分集信息
  495. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  496. ->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"))
  497. ->orderBy('episode_number')->get()->map(function ($value) {
  498. return (array)$value;
  499. })->toArray();
  500. $anime['episodes'] = $episodes;
  501. return $anime;
  502. }
  503. public function episodeInfo($data) {
  504. $uid = Site::getUid();
  505. $anime_id = getProp($data, 'anime_id');
  506. $episode_id = getProp($data, 'episode_id');
  507. if (!$anime_id || !$episode_id) {
  508. Utils::throwError('1002:请选择剧集');
  509. }
  510. // 验证用户权限
  511. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  512. if (!$anime) Utils::throwError('20003:权限不足');
  513. $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();
  514. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  515. $episode = (array)$episode;
  516. $episode['roles'] = json_decode($episode['roles'], true);
  517. // foreach($episode['roles'] as &$item) {
  518. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  519. // }
  520. $episode['scenes'] = json_decode($episode['scenes'], true);
  521. // foreach($episode['scenes'] as &$item) {
  522. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  523. // }
  524. // 获取分镜信息
  525. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  526. ->select('*')->get()->map(function ($value) {
  527. return (array)$value;
  528. })->toArray();
  529. // 使用公共方法构建分镜结构
  530. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  531. $episode['acts'] = $segmentsStructure['acts'];
  532. $episode['total_duration'] = $segmentsStructure['total_duration'];
  533. return $episode;
  534. }
  535. public function episodeInfoForAce($data) {
  536. $anime_id = getProp($data, 'anime_id');
  537. $episode_id = getProp($data, 'episode_id');
  538. if (!$anime_id || !$episode_id) {
  539. Utils::throwError('1002:请选择剧集');
  540. }
  541. $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();
  542. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  543. $episode = (array)$episode;
  544. $episode['roles'] = json_decode($episode['roles'], true);
  545. // foreach($episode['roles'] as &$item) {
  546. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  547. // }
  548. $episode['scenes'] = json_decode($episode['scenes'], true);
  549. // foreach($episode['scenes'] as &$item) {
  550. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  551. // }
  552. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  553. // 获取分镜信息
  554. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  555. ->select('*')->get()->map(function ($value) {
  556. return (array)$value;
  557. })->toArray();
  558. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  559. $episode['acts'] = $segmentsStructure['acts'];
  560. $episode['total_duration'] = $segmentsStructure['total_duration'];
  561. // 获取mp_animes表中的视频参数
  562. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  563. $episode['video_params'] = [
  564. 'video_model' => getProp($anime, 'video_model'),
  565. 'video_resolution' => getProp($anime, 'video_resolution'),
  566. 'ratio' => getProp($anime, 'video_ratio'),
  567. ];
  568. return $episode;
  569. }
  570. public function segmentInfo($data) {
  571. $uid = Site::getUid();
  572. $segment_id = getProp($data, 'segment_id');
  573. if (!$segment_id) {
  574. Utils::throwError('1002:请选择分镜');
  575. }
  576. // 获取分镜信息
  577. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  578. // 验证用户权限
  579. if ($segment) {
  580. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  581. if (!$anime) Utils::throwError('20003:权限不足');
  582. }
  583. $result = [
  584. 'segment_id' => getProp($segment, 'segment_id'),
  585. 'segment_number' => getProp($segment, 'segment_number'),
  586. 'segment_content' => getProp($segment, 'segment_content'),
  587. 'description' => getProp($segment, 'description'),
  588. 'composition' => getProp($segment, 'composition'),
  589. 'camera_movement' => getProp($segment, 'camera_movement'),
  590. 'voice_actor' => getProp($segment, 'voice_actor'),
  591. 'dialogue' => getProp($segment, 'dialogue'),
  592. 'frame_type' => getProp($segment, 'frame_type'),
  593. 'scene' => getProp($segment, 'scene'),
  594. 'characters' => getProp($segment, 'characters'),
  595. 'tail_frame' => getProp($segment, 'tail_frame'),
  596. 'emotion' => getProp($segment, 'emotion'),
  597. 'emotion_type' => getProp($segment, 'emotion_type'),
  598. 'gender' => getProp($segment, 'gender'),
  599. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  600. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  601. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  602. 'pitch' => getProp($segment, 'pitch'),
  603. 'voice_name' => getProp($segment, 'voice_name'),
  604. 'voice_type' => getProp($segment, 'voice_type'),
  605. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  606. 'img_url' => getProp($segment, 'img_url'),
  607. 'video_url' => getProp($segment, 'video_url'),
  608. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  609. ];
  610. return $result;
  611. }
  612. public function copyEpisodeVersion($data) {
  613. $episode_id = getProp($data, 'episode_id');
  614. $uid = Site::getUid();
  615. $cpid = Site::getCpid();
  616. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  617. if (!$episode) Utils::throwError('20003:该剧集不存在');
  618. $episode = (array)$episode;
  619. $anime_id = $episode['anime_id'];
  620. $episode_number = $episode['episode_number'];
  621. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  622. $sequence = $count + 1;
  623. unset($episode['id']);
  624. $now = date('Y-m-d H:i:s');
  625. $episode['created_at'] = $now;
  626. $episode['updated_at'] = $now;
  627. $episode['is_default'] = 1;
  628. // 获取版本中含有"(副本"字样的个数
  629. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  630. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  631. $episode['sequence'] = $sequence;
  632. $episode['is_generated'] = 0;
  633. $episode['cpid'] = $cpid;
  634. // 获取ace_mode
  635. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  636. try {
  637. DB::beginTransaction();
  638. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  639. // 新增副本
  640. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  641. if (!$new_episode_id) {
  642. Utils::throwError('20003:创建副本失败!');
  643. }
  644. // 获取分镜数据并准备插入
  645. $segments_for_insert = DB::table('mp_episode_segments')
  646. ->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')
  647. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  648. $item = (array)$item;
  649. $item['episode_id'] = $new_episode_id;
  650. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  651. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  652. return $item;
  653. })->toArray();
  654. // 写入分镜数据
  655. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  656. if (!$boolen2) {
  657. Utils::throwError('20003:写入分镜数据失败!');
  658. }
  659. // 写入对话历史
  660. $records = [
  661. [
  662. 'uid' => $uid,
  663. 'anime_id' => $anime_id,
  664. 'role' => 'user',
  665. 'content' => '创建副本',
  666. 'sequence' => $episode_number,
  667. 'episode_id' => $new_episode_id,
  668. 'created_at' => $now,
  669. 'updated_at' => $now
  670. ],
  671. [
  672. 'uid' => $uid,
  673. 'anime_id' => $anime_id,
  674. 'role' => 'assistant',
  675. 'content' => '好的,已为您创建副本',
  676. 'sequence' => $episode_number,
  677. 'episode_id' => $new_episode_id,
  678. 'created_at' => $now,
  679. 'updated_at' => $now
  680. ]
  681. ];
  682. $boolen3 = DB::table('mp_anime_records')->insert($records);
  683. if (!$boolen3) {
  684. Utils::throwError('20003:对话记录保存失败');
  685. }
  686. }catch (\Exception $e) {
  687. DB::rollBack();
  688. Utils::throwError('20003:'.$e->getMessage());
  689. }
  690. DB::commit();
  691. // 构建与 episodeInfo 方法一致的返回数据结构
  692. $result = [
  693. 'episode_id' => $new_episode_id,
  694. 'anime_id' => $anime_id,
  695. 'episode_number' => $episode_number,
  696. 'title' => $episode['title'],
  697. 'intro' => $episode['intro'],
  698. 'art_style' => $episode['art_style'],
  699. 'roles' => json_decode($episode['roles'], true),
  700. 'scenes' => json_decode($episode['scenes'], true),
  701. 'is_generated' => (int)$episode['is_generated']
  702. ];
  703. if ((int)$ace_mode === 1) {
  704. // 获取分镜信息
  705. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  706. ->select('*')->get()->map(function ($value) {
  707. return (array)$value;
  708. })->toArray();
  709. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  710. }else {
  711. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  712. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  713. }
  714. $result['acts'] = $segmentsStructure['acts'];
  715. $result['total_duration'] = $segmentsStructure['total_duration'];
  716. return $result;
  717. }
  718. public function episodeVersions($data) {
  719. $anime_id = getProp($data, 'anime_id');
  720. $episode_id = getProp($data, 'episode_id');
  721. if (!$anime_id || !$episode_id) {
  722. Utils::throwError('1002:请选择剧集');
  723. }
  724. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  725. $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) {
  726. return (array)$value;
  727. })->toArray();
  728. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  729. foreach($episodes as &$episode) {
  730. $episode['version'] = 'V'.$episode['sequence'];
  731. $episode['roles'] = json_decode($episode['roles'], true);
  732. $episode['scenes'] = json_decode($episode['scenes'], true);
  733. // 获取分镜信息
  734. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  735. ->select('*')->get()->map(function ($value) {
  736. return (array)$value;
  737. })->toArray();
  738. // 使用公共方法构建分镜结构
  739. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  740. $episode['acts'] = $segmentsStructure['acts'];
  741. $episode['total_duration'] = $segmentsStructure['total_duration'];
  742. }
  743. return $episodes;
  744. }
  745. public function bindEpisodeVersion($data) {
  746. $episode_id = getProp($data, 'episode_id');
  747. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  748. if (!$episode) Utils::throwError('20003:该剧集不存在');
  749. $episode = (array)$episode;
  750. if ((int)$episode['is_default'] === 1) return true;
  751. try {
  752. DB::beginTransaction();
  753. // 移除is_default标志
  754. $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')]);
  755. if (!$boolen) {
  756. Utils::throwError('20003:更新失败!');
  757. }
  758. // 绑定副本
  759. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  760. if (!$boolen2) {
  761. Utils::throwError('20003:绑定失败!');
  762. }
  763. }catch (\Exception $e) {
  764. DB::rollBack();
  765. Utils::throwError('20003:'.$e->getMessage());
  766. }
  767. DB::commit();
  768. return true;
  769. }
  770. public function chatChangeImg($data) {
  771. $segment_id = getProp($data, 'segment_id');
  772. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  773. $prompt = getProp($data, 'prompt');
  774. if (!$prompt || !$segment_id) {
  775. Utils::throwError('1002:请输入提示词,并且选择分镜');
  776. }
  777. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  778. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  779. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  780. else $ref_img_url = '';
  781. // $ref_img_url = '';
  782. if (empty($prompt)) {
  783. if (empty($ref_img_url)) {
  784. $prompt = getProp($segment, 'segment_content');
  785. }else {
  786. $prompt = '请根据图片生成';
  787. }
  788. }
  789. $anime_id = getProp($segment, 'anime_id');
  790. $episode_id = getProp($segment, 'episode_id');
  791. $episode_number = getProp($segment, 'episode_number');
  792. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  793. $ratio = getProp($data, 'ratio');
  794. if (!$ratio) {
  795. $ratio = getProp($episode, 'ratio');
  796. if (!$ratio) $ratio = '9:16';
  797. }
  798. $art_style = getProp($episode, 'art_style');
  799. if ($art_style) {
  800. $prompt = "美术风格:{$art_style}\n{$prompt}";
  801. }
  802. $dimensions = $this->getRatioDimensions($ratio);
  803. $width = $dimensions['width'];
  804. $height = $dimensions['height'];
  805. try {
  806. $params = [
  807. 'alias_segment_id' => $segment_id,
  808. 'prompt' => $prompt,
  809. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  810. 'width' => $width,
  811. 'height' => $height
  812. ];
  813. // 优化提示词(不要生成字幕)
  814. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  815. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  816. $task_id = $task->id;
  817. if (!$task_id) {
  818. Utils::throwError("20003:生成图片失败");
  819. }
  820. // 更新任务ID
  821. $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')]);
  822. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  823. } catch (\Exception $e) {
  824. Utils::throwError("20003:" . $e->getMessage());
  825. }
  826. // 创建任务之后先暂停10s等待异步任务完成
  827. sleep(10);
  828. $img_url = $this->loopGetPicTaskResult($task_id);
  829. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  830. // 图片生成后新增对话记录
  831. try {
  832. $uid = Site::getUid();
  833. $now = date('Y-m-d H:i:s');
  834. // 使用AI反推图片提示词
  835. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  836. // 保存对话记录
  837. $records = [
  838. [
  839. 'uid' => $uid,
  840. 'anime_id' => $anime_id,
  841. 'sequence' => $episode_number,
  842. 'role' => 'user',
  843. 'content' => $prompt,
  844. 'segment_id' => $segment_id,
  845. 'pic_task_id' => $task_id,
  846. 'image_url' => '',
  847. 'created_at' => $now,
  848. 'updated_at' => $now
  849. ],
  850. [
  851. 'uid' => $uid,
  852. 'anime_id' => $anime_id,
  853. 'sequence' => $episode_number,
  854. 'role' => 'assistant',
  855. 'content' => $pic_prompt,
  856. 'segment_id' => $segment_id,
  857. 'pic_task_id' => $task_id,
  858. 'image_url' => $img_url,
  859. 'created_at' => $now,
  860. 'updated_at' => $now
  861. ]
  862. ];
  863. DB::table('mp_anime_records')->insert($records);
  864. } catch (\Exception $e) {
  865. // 记录日志但不影响主流程
  866. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  867. 'segment_id' => $segment_id,
  868. 'img_url' => $img_url
  869. ]);
  870. logDB('anime', 'error', '保存对话记录失败', [
  871. 'segment_id' => $segment_id,
  872. 'img_url' => $img_url,
  873. 'error' => $e->getMessage()
  874. ]);
  875. }
  876. return $img_url;
  877. }
  878. public function segmentChatHistory($data) {
  879. $segment_id = getProp($data, 'segment_id');
  880. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  881. $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');
  882. $chat = $query->orderBy('id')->get()->map(function ($value) {
  883. $value = (array)$value;
  884. $value['created_at'] = transDate($value['created_at']);
  885. return $value;
  886. })->toArray();
  887. // 获取历史图片
  888. $url = [];
  889. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  890. foreach($pic_history as $task) {
  891. $result_url = getProp($task, 'result_url');
  892. if (is_json($result_url)) {
  893. $url = array_merge($url, json_decode($result_url, true));
  894. }else {
  895. $url[] = $result_url;
  896. }
  897. }
  898. // 获取历史视频
  899. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  900. foreach($video_history as $task) {
  901. $result_url = getProp($task, 'compressed_url');
  902. if (is_json($result_url)) {
  903. $url = array_merge($url, json_decode($result_url, true));
  904. }else {
  905. $url[] = $result_url;
  906. }
  907. }
  908. return compact('chat', 'url');
  909. }
  910. public function changeEpisodeRoles($data) {
  911. $anime_id = getProp($data, 'anime_id');
  912. $episode_id = getProp($data, 'episode_id');
  913. $target_roles = getProp($data, 'roles');
  914. $is_deleted = getProp($data, 'is_deleted', 0);
  915. // 参数验证
  916. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  917. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  918. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  919. // 验证剧集是否存在
  920. $episode = DB::table('mp_anime_episodes')
  921. ->where('anime_id', $anime_id)
  922. ->where('id', $episode_id)
  923. ->first();
  924. if (!$episode) Utils::throwError('20003:该剧集不存在');
  925. $roles = json_decode(getProp($episode, 'roles'), true);
  926. // 获取anime信息,检查是否有关联的script_id
  927. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  928. if (!$anime) Utils::throwError('20003:动漫不存在');
  929. $script_id = getProp($anime, 'script_id');
  930. $episode_number = getProp($episode, 'episode_number', 1);
  931. $uid = Site::getUid();
  932. $cpid = Site::getCpid();
  933. try {
  934. $target_role_name = getProp($target_roles, 'role');
  935. if (empty($target_role_name)) {
  936. Utils::throwError('20003:角色名称不能为空');
  937. }
  938. // 如果是删除操作
  939. if ($is_deleted == 1) {
  940. // 从角色列表中移除该角色
  941. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  942. return getProp($role, 'role') !== $target_role_name;
  943. }));
  944. // 更新角色列表
  945. $result = DB::table('mp_anime_episodes')
  946. ->where('anime_id', $anime_id)
  947. ->where('id', $episode_id)
  948. ->update([
  949. 'roles' => json_encode($roles, 256),
  950. 'updated_at' => date('Y-m-d H:i:s')
  951. ]);
  952. if ($result === false) {
  953. Utils::throwError('20003:删除角色失败');
  954. }
  955. } else {
  956. // 新增或更新操作
  957. $role_found = false;
  958. $is_new_role = false;
  959. // 查找并更新已存在的角色
  960. foreach($roles as &$role) {
  961. if (getProp($role, 'role') === $target_role_name) {
  962. $role = $target_roles;
  963. $role_found = true;
  964. break;
  965. }
  966. }
  967. // 如果角色不存在,则新增
  968. if (!$role_found) {
  969. $roles[] = $target_roles;
  970. $is_new_role = true;
  971. }
  972. // 更新角色列表
  973. $result = DB::table('mp_anime_episodes')
  974. ->where('anime_id', $anime_id)
  975. ->where('id', $episode_id)
  976. ->update([
  977. 'roles' => json_encode($roles, 256),
  978. 'updated_at' => date('Y-m-d H:i:s')
  979. ]);
  980. if ($result === false) {
  981. Utils::throwError('20003:更新角色列表失败');
  982. }
  983. // 同步更新分镜表中对应主体的音色信息
  984. $voice_name = getProp($target_roles, 'voice_name');
  985. $voice_type = getProp($target_roles, 'voice_type');
  986. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  987. DB::table('mp_episode_segments')
  988. ->where('anime_id', $anime_id)
  989. ->where('episode_id', $episode_id)
  990. ->where('voice_actor', $target_role_name)
  991. ->update([
  992. 'voice_name' => $voice_name,
  993. 'voice_type' => $voice_type,
  994. 'voice_audio_url' => $voice_audio_url,
  995. 'updated_at' => date('Y-m-d H:i:s')
  996. ]);
  997. // 如果有关联的script_id,则同步到mp_products表
  998. if ($script_id) {
  999. // 查询剧本信息
  1000. $script = DB::table('mp_scripts')
  1001. ->where('id', $script_id)
  1002. ->where('is_deleted', 0)
  1003. ->first();
  1004. if ($script) {
  1005. $script_name = $script->script_name ?? 'script_' . $script_id;
  1006. $product_name = getProp($target_roles, 'role');
  1007. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1008. $url = getProp($target_roles, 'url', '');
  1009. $product_type = 1; // 1=角色
  1010. // 查找或创建以script_name命名的文件夹
  1011. $folder = DB::table('mp_products')
  1012. ->where('cpid', $cpid)
  1013. ->where('type', 2) // 文件夹类型
  1014. ->where('product', $product_type) // 角色类型
  1015. ->where('product_name', $script_name)
  1016. ->where('parent_id', 0)
  1017. ->where('is_deleted', 0)
  1018. ->first();
  1019. if (!$folder) {
  1020. // 创建文件夹
  1021. $folder_id = DB::table('mp_products')->insertGetId([
  1022. 'user_id' => $uid,
  1023. 'cpid' => $cpid,
  1024. 'type' => 2, // 文件夹
  1025. 'product' => $product_type, // 角色类型
  1026. 'parent_id' => 0,
  1027. 'level' => 1,
  1028. 'product_name' => $script_name,
  1029. 'sort_order' => time(),
  1030. 'is_deleted' => 0,
  1031. 'created_at' => date('Y-m-d H:i:s'),
  1032. 'updated_at' => date('Y-m-d H:i:s')
  1033. ]);
  1034. } else {
  1035. $folder_id = $folder->id;
  1036. }
  1037. // 查找该文件夹下是否已存在同名资产
  1038. $existing_product = DB::table('mp_products')
  1039. ->where('cpid', $cpid)
  1040. ->where('type', 1) // 资产类型
  1041. ->where('product', $product_type)
  1042. ->where('parent_id', $folder_id)
  1043. ->where('product_name', $product_name)
  1044. ->where('is_deleted', 0)
  1045. ->first();
  1046. if ($existing_product) {
  1047. // 更新已存在的资产
  1048. $updateData = [
  1049. 'pic_task_status' => '生成成功',
  1050. ];
  1051. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1052. if ($url) $updateData['url'] = $url;
  1053. // 处理versions字段
  1054. $versions = getProp($target_roles, 'versions', []);
  1055. if ($versions && is_array($versions)) {
  1056. $updateData['versions'] = json_encode($versions, 256);
  1057. }
  1058. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1059. DB::table('mp_products')
  1060. ->where('id', $existing_product->id)
  1061. ->update($updateData);
  1062. $product_id = $existing_product->id;
  1063. } else {
  1064. // 创建新资产
  1065. $versions = getProp($target_roles, 'versions', []);
  1066. $product_id = DB::table('mp_products')->insertGetId([
  1067. 'user_id' => $uid,
  1068. 'cpid' => $cpid,
  1069. 'type' => 1, // 资产
  1070. 'product' => $product_type, // 角色
  1071. 'parent_id' => $folder_id,
  1072. 'level' => 2,
  1073. 'product_name' => $product_name,
  1074. 'url' => $url,
  1075. 'pic_prompt' => $pic_prompt,
  1076. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1077. 'sort_order' => time(),
  1078. 'is_deleted' => 0,
  1079. 'pic_task_status' => '生成成功',
  1080. 'created_at' => date('Y-m-d H:i:s'),
  1081. 'updated_at' => date('Y-m-d H:i:s')
  1082. ]);
  1083. }
  1084. // 建立或更新绑定关系
  1085. $existing_mapping = DB::table('mp_script_product_mappings')
  1086. ->where('script_id', $script_id)
  1087. ->where('product_id', $product_id)
  1088. ->where('episode_number', $episode_number)
  1089. ->first();
  1090. if (!$existing_mapping) {
  1091. // 创建绑定关系
  1092. DB::table('mp_script_product_mappings')->insert([
  1093. 'script_id' => $script_id,
  1094. 'product_id' => $product_id,
  1095. 'episode_number' => $episode_number,
  1096. 'created_at' => date('Y-m-d H:i:s'),
  1097. 'updated_at' => date('Y-m-d H:i:s')
  1098. ]);
  1099. }
  1100. }
  1101. }
  1102. }
  1103. } catch (\Exception $e) {
  1104. dLog('anime')->error('更新剧集角色失败', [
  1105. 'anime_id' => $anime_id,
  1106. 'episode_id' => $episode_id,
  1107. 'error' => $e->getMessage()
  1108. ]);
  1109. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1110. }
  1111. return true;
  1112. }
  1113. public function changeEpisodeScenes($data) {
  1114. $anime_id = getProp($data, 'anime_id');
  1115. $episode_id = getProp($data, 'episode_id');
  1116. $target_scenes = getProp($data, 'scenes');
  1117. $is_deleted = getProp($data, 'is_deleted', 0);
  1118. // 参数验证
  1119. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1120. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1121. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1122. // 验证剧集是否存在
  1123. $episode = DB::table('mp_anime_episodes')
  1124. ->where('anime_id', $anime_id)
  1125. ->where('id', $episode_id)
  1126. ->first();
  1127. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1128. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1129. // 获取anime信息,检查是否有关联的script_id
  1130. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1131. if (!$anime) Utils::throwError('20003:动漫不存在');
  1132. $script_id = getProp($anime, 'script_id');
  1133. $episode_number = getProp($episode, 'episode_number', 1);
  1134. $uid = Site::getUid();
  1135. $cpid = Site::getCpid();
  1136. try {
  1137. $target_scene_name = getProp($target_scenes, 'scene');
  1138. if (empty($target_scene_name)) {
  1139. Utils::throwError('20003:场景名称不能为空');
  1140. }
  1141. // 如果是删除操作
  1142. if ($is_deleted == 1) {
  1143. // 从场景列表中移除该场景
  1144. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1145. return getProp($scene, 'scene') !== $target_scene_name;
  1146. }));
  1147. // 更新场景列表
  1148. $result = DB::table('mp_anime_episodes')
  1149. ->where('anime_id', $anime_id)
  1150. ->where('id', $episode_id)
  1151. ->update([
  1152. 'scenes' => json_encode($scenes, 256),
  1153. 'updated_at' => date('Y-m-d H:i:s')
  1154. ]);
  1155. if ($result === false) {
  1156. Utils::throwError('20003:删除场景失败');
  1157. }
  1158. } else {
  1159. // 新增或更新操作
  1160. $scene_found = false;
  1161. $is_new_scene = false;
  1162. // 查找并更新已存在的场景
  1163. foreach($scenes as &$scene) {
  1164. if (getProp($scene, 'scene') === $target_scene_name) {
  1165. $scene = $target_scenes;
  1166. $scene_found = true;
  1167. break;
  1168. }
  1169. }
  1170. // 如果场景不存在,则新增
  1171. if (!$scene_found) {
  1172. $scenes[] = $target_scenes;
  1173. $is_new_scene = true;
  1174. }
  1175. // 更新场景列表
  1176. $result = DB::table('mp_anime_episodes')
  1177. ->where('anime_id', $anime_id)
  1178. ->where('id', $episode_id)
  1179. ->update([
  1180. 'scenes' => json_encode($scenes, 256),
  1181. 'updated_at' => date('Y-m-d H:i:s')
  1182. ]);
  1183. if ($result === false) {
  1184. Utils::throwError('20003:更新场景列表失败');
  1185. }
  1186. // 如果有关联的script_id,则同步到mp_products表
  1187. if ($script_id) {
  1188. // 查询剧本信息
  1189. $script = DB::table('mp_scripts')
  1190. ->where('id', $script_id)
  1191. ->where('is_deleted', 0)
  1192. ->first();
  1193. if ($script) {
  1194. $script_name = $script->script_name ?? 'script_' . $script_id;
  1195. $product_name = getProp($target_scenes, 'scene');
  1196. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1197. $url = getProp($target_scenes, 'url', '');
  1198. $product_type = 2; // 2=场景
  1199. // 查找或创建以script_name命名的文件夹
  1200. $folder = DB::table('mp_products')
  1201. ->where('cpid', $cpid)
  1202. ->where('type', 2) // 文件夹类型
  1203. ->where('product', $product_type) // 场景类型
  1204. ->where('product_name', $script_name)
  1205. ->where('parent_id', 0)
  1206. ->where('is_deleted', 0)
  1207. ->first();
  1208. if (!$folder) {
  1209. // 创建文件夹
  1210. $folder_id = DB::table('mp_products')->insertGetId([
  1211. 'user_id' => $uid,
  1212. 'cpid' => $cpid,
  1213. 'type' => 2, // 文件夹
  1214. 'product' => $product_type, // 场景类型
  1215. 'parent_id' => 0,
  1216. 'level' => 1,
  1217. 'product_name' => $script_name,
  1218. 'sort_order' => time(),
  1219. 'is_deleted' => 0,
  1220. 'created_at' => date('Y-m-d H:i:s'),
  1221. 'updated_at' => date('Y-m-d H:i:s')
  1222. ]);
  1223. } else {
  1224. $folder_id = $folder->id;
  1225. }
  1226. // 查找该文件夹下是否已存在同名资产
  1227. $existing_product = DB::table('mp_products')
  1228. ->where('cpid', $cpid)
  1229. ->where('type', 1) // 资产类型
  1230. ->where('product', $product_type)
  1231. ->where('parent_id', $folder_id)
  1232. ->where('product_name', $product_name)
  1233. ->where('is_deleted', 0)
  1234. ->first();
  1235. if ($existing_product) {
  1236. // 更新已存在的资产
  1237. $updateData = [
  1238. 'pic_task_status' => '生成成功'
  1239. ];
  1240. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1241. if ($url) $updateData['url'] = $url;
  1242. // 处理versions字段
  1243. $versions = getProp($target_scenes, 'versions', []);
  1244. if ($versions && is_array($versions)) {
  1245. $updateData['versions'] = json_encode($versions, 256);
  1246. }
  1247. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1248. DB::table('mp_products')
  1249. ->where('id', $existing_product->id)
  1250. ->update($updateData);
  1251. $product_id = $existing_product->id;
  1252. } else {
  1253. // 创建新资产
  1254. $versions = getProp($target_scenes, 'versions', []);
  1255. $product_id = DB::table('mp_products')->insertGetId([
  1256. 'user_id' => $uid,
  1257. 'cpid' => $cpid,
  1258. 'type' => 1, // 资产
  1259. 'product' => $product_type, // 场景
  1260. 'parent_id' => $folder_id,
  1261. 'level' => 2,
  1262. 'product_name' => $product_name,
  1263. 'url' => $url,
  1264. 'pic_prompt' => $pic_prompt,
  1265. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1266. 'sort_order' => time(),
  1267. 'is_deleted' => 0,
  1268. 'pic_task_status' => '生成成功',
  1269. 'created_at' => date('Y-m-d H:i:s'),
  1270. 'updated_at' => date('Y-m-d H:i:s')
  1271. ]);
  1272. }
  1273. // 建立或更新绑定关系
  1274. $existing_mapping = DB::table('mp_script_product_mappings')
  1275. ->where('script_id', $script_id)
  1276. ->where('product_id', $product_id)
  1277. ->where('episode_number', $episode_number)
  1278. ->first();
  1279. if (!$existing_mapping) {
  1280. // 创建绑定关系
  1281. DB::table('mp_script_product_mappings')->insert([
  1282. 'script_id' => $script_id,
  1283. 'product_id' => $product_id,
  1284. 'episode_number' => $episode_number,
  1285. 'created_at' => date('Y-m-d H:i:s'),
  1286. 'updated_at' => date('Y-m-d H:i:s')
  1287. ]);
  1288. }
  1289. }
  1290. }
  1291. }
  1292. } catch (\Exception $e) {
  1293. dLog('anime')->error('更新剧集场景失败', [
  1294. 'anime_id' => $anime_id,
  1295. 'episode_id' => $episode_id,
  1296. 'error' => $e->getMessage()
  1297. ]);
  1298. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1299. }
  1300. return true;
  1301. }
  1302. public function changeEpisodeProps($data) {
  1303. $anime_id = getProp($data, 'anime_id');
  1304. $episode_id = getProp($data, 'episode_id');
  1305. $target_props = getProp($data, 'props');
  1306. $is_deleted = getProp($data, 'is_deleted', 0);
  1307. // 参数验证
  1308. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1309. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1310. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1311. // 验证剧集是否存在
  1312. $episode = DB::table('mp_anime_episodes')
  1313. ->where('anime_id', $anime_id)
  1314. ->where('id', $episode_id)
  1315. ->first();
  1316. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1317. $props = json_decode(getProp($episode, 'props'), true);
  1318. // 获取anime信息,检查是否有关联的script_id
  1319. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1320. if (!$anime) Utils::throwError('20003:动漫不存在');
  1321. $script_id = getProp($anime, 'script_id');
  1322. $episode_number = getProp($episode, 'episode_number', 1);
  1323. $uid = Site::getUid();
  1324. $cpid = Site::getCpid();
  1325. try {
  1326. $target_prop_name = getProp($target_props, 'prop');
  1327. if (empty($target_prop_name)) {
  1328. Utils::throwError('20003:道具名称不能为空');
  1329. }
  1330. // 如果是删除操作
  1331. if ($is_deleted == 1) {
  1332. // 从道具列表中移除该道具
  1333. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1334. return getProp($prop, 'prop') !== $target_prop_name;
  1335. }));
  1336. // 更新道具列表
  1337. $result = DB::table('mp_anime_episodes')
  1338. ->where('anime_id', $anime_id)
  1339. ->where('id', $episode_id)
  1340. ->update([
  1341. 'props' => json_encode($props, 256),
  1342. 'updated_at' => date('Y-m-d H:i:s')
  1343. ]);
  1344. if ($result === false) {
  1345. Utils::throwError('20003:删除道具失败');
  1346. }
  1347. } else {
  1348. // 新增或更新操作
  1349. $prop_found = false;
  1350. $is_new_prop = false;
  1351. // 查找并更新已存在的道具
  1352. foreach($props as &$prop) {
  1353. if (getProp($prop, 'prop') === $target_prop_name) {
  1354. $prop = $target_props;
  1355. $prop_found = true;
  1356. break;
  1357. }
  1358. }
  1359. // 如果道具不存在,则新增
  1360. if (!$prop_found) {
  1361. $props[] = $target_props;
  1362. $is_new_prop = true;
  1363. }
  1364. // 更新道具列表
  1365. $result = DB::table('mp_anime_episodes')
  1366. ->where('anime_id', $anime_id)
  1367. ->where('id', $episode_id)
  1368. ->update([
  1369. 'props' => json_encode($props, 256),
  1370. 'updated_at' => date('Y-m-d H:i:s')
  1371. ]);
  1372. if ($result === false) {
  1373. Utils::throwError('20003:更新道具列表失败');
  1374. }
  1375. // 如果有关联的script_id,则同步到mp_products表
  1376. if ($script_id) {
  1377. // 查询剧本信息
  1378. $script = DB::table('mp_scripts')
  1379. ->where('id', $script_id)
  1380. ->where('is_deleted', 0)
  1381. ->first();
  1382. if ($script) {
  1383. $script_name = $script->script_name ?? 'script_' . $script_id;
  1384. $product_name = getProp($target_props, 'prop');
  1385. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1386. $url = getProp($target_props, 'url', '');
  1387. $product_type = 3; // 3=道具
  1388. // 查找或创建以script_name命名的文件夹
  1389. $folder = DB::table('mp_products')
  1390. ->where('cpid', $cpid)
  1391. ->where('type', 2) // 文件夹类型
  1392. ->where('product', $product_type) // 道具类型
  1393. ->where('product_name', $script_name)
  1394. ->where('parent_id', 0)
  1395. ->where('is_deleted', 0)
  1396. ->first();
  1397. if (!$folder) {
  1398. // 创建文件夹
  1399. $folder_id = DB::table('mp_products')->insertGetId([
  1400. 'user_id' => $uid,
  1401. 'cpid' => $cpid,
  1402. 'type' => 2, // 文件夹
  1403. 'product' => $product_type, // 道具类型
  1404. 'parent_id' => 0,
  1405. 'level' => 1,
  1406. 'product_name' => $script_name,
  1407. 'sort_order' => time(),
  1408. 'is_deleted' => 0,
  1409. 'created_at' => date('Y-m-d H:i:s'),
  1410. 'updated_at' => date('Y-m-d H:i:s')
  1411. ]);
  1412. } else {
  1413. $folder_id = $folder->id;
  1414. }
  1415. // 查找该文件夹下是否已存在同名资产
  1416. $existing_product = DB::table('mp_products')
  1417. ->where('cpid', $cpid)
  1418. ->where('type', 1) // 资产类型
  1419. ->where('product', $product_type)
  1420. ->where('parent_id', $folder_id)
  1421. ->where('product_name', $product_name)
  1422. ->where('is_deleted', 0)
  1423. ->first();
  1424. if ($existing_product) {
  1425. // 更新已存在的资产
  1426. $updateData = [
  1427. 'pic_task_status' => '生成成功'
  1428. ];
  1429. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1430. if ($url) $updateData['url'] = $url;
  1431. // 处理versions字段
  1432. $versions = getProp($target_props, 'versions', []);
  1433. if ($versions && is_array($versions)) {
  1434. $updateData['versions'] = json_encode($versions, 256);
  1435. }
  1436. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1437. DB::table('mp_products')
  1438. ->where('id', $existing_product->id)
  1439. ->update($updateData);
  1440. $product_id = $existing_product->id;
  1441. } else {
  1442. // 创建新资产
  1443. $versions = getProp($target_props, 'versions', []);
  1444. $product_id = DB::table('mp_products')->insertGetId([
  1445. 'user_id' => $uid,
  1446. 'cpid' => $cpid,
  1447. 'type' => 1, // 资产
  1448. 'product' => $product_type, // 道具
  1449. 'parent_id' => $folder_id,
  1450. 'level' => 2,
  1451. 'product_name' => $product_name,
  1452. 'url' => $url,
  1453. 'pic_prompt' => $pic_prompt,
  1454. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1455. 'sort_order' => time(),
  1456. 'is_deleted' => 0,
  1457. 'pic_task_status' => '生成成功',
  1458. 'created_at' => date('Y-m-d H:i:s'),
  1459. 'updated_at' => date('Y-m-d H:i:s')
  1460. ]);
  1461. }
  1462. // 建立或更新绑定关系
  1463. $existing_mapping = DB::table('mp_script_product_mappings')
  1464. ->where('script_id', $script_id)
  1465. ->where('product_id', $product_id)
  1466. ->where('episode_number', $episode_number)
  1467. ->first();
  1468. if (!$existing_mapping) {
  1469. // 创建绑定关系
  1470. DB::table('mp_script_product_mappings')->insert([
  1471. 'script_id' => $script_id,
  1472. 'product_id' => $product_id,
  1473. 'episode_number' => $episode_number,
  1474. 'created_at' => date('Y-m-d H:i:s'),
  1475. 'updated_at' => date('Y-m-d H:i:s')
  1476. ]);
  1477. }
  1478. }
  1479. }
  1480. }
  1481. } catch (\Exception $e) {
  1482. dLog('anime')->error('更新剧集道具失败', [
  1483. 'anime_id' => $anime_id,
  1484. 'episode_id' => $episode_id,
  1485. 'error' => $e->getMessage()
  1486. ]);
  1487. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1488. }
  1489. return true;
  1490. }
  1491. public function editSegment($data) {
  1492. $segment_id = getProp($data, 'segment_id');
  1493. $segment_content = getProp($data, 'segment_content');
  1494. $image_url = getProp($data, 'image_url');
  1495. $video_url = getProp($data, 'video_url');
  1496. // 参数验证
  1497. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1498. // 验证分镜是否存在
  1499. $segment = DB::table('mp_episode_segments')
  1500. ->where('segment_id', $segment_id)
  1501. ->first();
  1502. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1503. $dubTaskId = 0;
  1504. try {
  1505. DB::beginTransaction();
  1506. // 准备更新数据
  1507. $update_data = [
  1508. 'updated_at' => date('Y-m-d H:i:s')
  1509. ];
  1510. if ($segment_content) {
  1511. // 先将segment_content赋值到update_data
  1512. $update_data['segment_content'] = $segment_content;
  1513. // 使用现有方法分析segment_content,提取各个字段
  1514. $this->handleSegmentContent($update_data);
  1515. // 如果有对话内容,创建视频配音合成任务
  1516. $dialogue = getProp($update_data, 'dialogue');
  1517. if (!empty($dialogue)) {
  1518. $now = date('Y-m-d H:i:s');
  1519. $generate_json = [
  1520. 'text' => $dialogue,
  1521. 'role' => getProp($update_data, 'voice_actor'),
  1522. 'voice_type' => getProp($update_data, 'voice_type'),
  1523. 'voice_name' => getProp($update_data, 'voice_name'),
  1524. 'emotion' => getProp($update_data, 'emotion'),
  1525. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1526. 'gender' => getProp($update_data, 'gender'),
  1527. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1528. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1529. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1530. 'pitch' => getProp($update_data, 'pitch', 0),
  1531. ];
  1532. // 插入视频配音合成任务
  1533. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1534. 'alias_segment_id' => $segment_id,
  1535. 'generate_status' => '执行中',
  1536. 'audio_url' => '',
  1537. 'generate_json' => json_encode($generate_json, 256),
  1538. 'created_at' => $now,
  1539. 'updated_at' => $now,
  1540. ]);
  1541. if (!$dubTaskId) {
  1542. Utils::throwError('20003:创建配音任务失败!');
  1543. }
  1544. $update_data['audio_url'] = '';
  1545. } else {
  1546. // dialogue为空时,直接写入默认音频信息
  1547. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1548. $update_data['audio_duration'] = 2.0;
  1549. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1550. }
  1551. }
  1552. if ($image_url) {
  1553. $update_data['img_url'] = $image_url;
  1554. // 同时写入一个简单的图片生成任务
  1555. $pic_task = [
  1556. 'alias_segment_id' => $segment_id,
  1557. 'ref_img_url' => json_encode([]),
  1558. 'status' => 'success',
  1559. 'result_url' => json_encode([$image_url], 256),
  1560. 'model' => '',
  1561. 'created_at' => date('Y-m-d H:i:s'),
  1562. 'updated_at' => date('Y-m-d H:i:s'),
  1563. ];
  1564. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1565. }
  1566. if ($video_url) {
  1567. $update_data['origin_video_url'] = $video_url;
  1568. $compressed_video_url = compressVideo($video_url);
  1569. $update_data['current_type'] = 2;
  1570. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1571. // 同时写入一个简单的视频生成任务
  1572. $video_task = [
  1573. 'alias_segment_id' => $segment_id,
  1574. 'status' => 'success',
  1575. 'result_url' => $update_data['origin_video_url'],
  1576. 'compressed_url' => $update_data['video_url'],
  1577. 'created_at' => date('Y-m-d H:i:s'),
  1578. 'updated_at' => date('Y-m-d H:i:s'),
  1579. ];
  1580. DB::table('mp_generate_video_tasks')->insert($video_task);
  1581. }
  1582. // 更新分镜信息
  1583. $result = DB::table('mp_episode_segments')
  1584. ->where('segment_id', $segment_id)
  1585. ->update($update_data);
  1586. if ($result === false) {
  1587. Utils::throwError('20003:更新分镜剧本失败');
  1588. }
  1589. DB::commit();
  1590. // 如果有创建音频生成任务则调用API
  1591. if ($dubTaskId) {
  1592. // 请求远程服务器执行生成
  1593. $client = new Client(['timeout' => 300, 'verify' => false]);
  1594. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1595. $response = $result->getBody()->getContents();
  1596. $response_arr = json_decode($response, true);
  1597. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1598. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1599. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1600. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1601. Utils::throwError('20003:火山生成音频失败');
  1602. }
  1603. }
  1604. return true;
  1605. } catch (\Exception $e) {
  1606. DB::rollBack();
  1607. dLog('anime')->error('更新分镜剧本失败', [
  1608. 'segment_id' => $segment_id,
  1609. 'error' => $e->getMessage()
  1610. ]);
  1611. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1612. }
  1613. }
  1614. public function batchSetSegmentPics($data) {
  1615. $anime_id = getProp($data, 'anime_id');
  1616. $episode_id = getProp($data, 'episode_id');
  1617. $ratio = getProp($data, 'ratio');
  1618. $dimensions = $this->getRatioDimensions($ratio);
  1619. $width = $dimensions['width'];
  1620. $height = $dimensions['height'];
  1621. if (!$anime_id || !$episode_id) {
  1622. Utils::throwError('1002:请选择剧集');
  1623. }
  1624. // 获取剧集信息
  1625. $episode = DB::table('mp_anime_episodes')
  1626. ->where('anime_id', $anime_id)
  1627. ->where('id', $episode_id)
  1628. ->where('is_default', 1)
  1629. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1630. ->first();
  1631. if (!$episode) {
  1632. Utils::throwError('20003:该剧集不存在');
  1633. }
  1634. $model = getProp($data, 'model');
  1635. if (!$model) {
  1636. $model = getProp($episode, 'image_model');
  1637. if (!$model) {
  1638. // episode表也没有,使用默认值
  1639. $model = 'doubao-seedream-5-0-lite-260128';
  1640. }
  1641. }
  1642. // 验证模型是否在可用模型表中
  1643. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1644. $model = 'doubao-seedream-5-0-lite-260128';
  1645. }
  1646. $roles = json_decode(getProp($episode, 'roles'), true);
  1647. if (!$roles) {
  1648. Utils::throwError('20003:角色信息格式错误');
  1649. }
  1650. // 构建角色名称到参考图的映射
  1651. $role_map = [];
  1652. foreach ($roles as $role) {
  1653. $role_name = getProp($role, 'role');
  1654. $role_url = getProp($role, 'url');
  1655. if (!empty($role_name) && !empty($role_url)) {
  1656. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1657. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1658. // $role_map[$base_name] = $role_url;
  1659. // 同时保存完整名称的映射
  1660. $role_map[$role_name] = $role_url;
  1661. }
  1662. }
  1663. $scenes = json_decode(getProp($episode, 'roles'), true);
  1664. if (!$scenes) {
  1665. Utils::throwError('20003:场景信息格式错误');
  1666. }
  1667. // 构建角色名称到参考图的映射
  1668. $scene_map = [];
  1669. foreach ($scenes as $scene) {
  1670. $scene_name = getProp($scene, 'scene');
  1671. $scene_url = getProp($scene, 'url');
  1672. if (!empty($scene_name) && !empty($scene_url)) {
  1673. $scene_map[$scene_name] = $scene_url;
  1674. }
  1675. }
  1676. // 获取所有分镜信息
  1677. $segments = DB::table('mp_episode_segments')
  1678. ->where('anime_id', $anime_id)
  1679. ->where('episode_id', $episode_id)
  1680. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1681. ->orderBy('segment_number')
  1682. ->get()
  1683. ->toArray();
  1684. if (empty($segments)) {
  1685. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1686. }
  1687. // 保存图片比例
  1688. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1689. $updated_segments = [];
  1690. $failed_segments = [];
  1691. // 批量为每个分镜生成图片任务
  1692. foreach ($segments as $segment) {
  1693. $segment_id = $segment->segment_id;
  1694. $segment_content = $segment->segment_content;
  1695. if (empty($segment_content)) {
  1696. $failed_segments[] = [
  1697. 'segment_id' => $segment_id,
  1698. 'error' => '分镜内容为空'
  1699. ];
  1700. continue;
  1701. }
  1702. try {
  1703. $dubTaskId = 0;
  1704. // 解析分镜内容,提取画面描述作为主要提示词
  1705. $prompt = $segment_content;
  1706. $ref_img_urls = [];
  1707. // 分镜场景
  1708. $scene = getProp($segment, 'scene');
  1709. $matched_scene = '';
  1710. if (isset($scene_map[$scene])) {
  1711. $img_index = count($ref_img_urls) + 1;
  1712. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1713. $ref_img_urls[] = $scene_map[$scene];
  1714. $matched_scene = $scene;
  1715. }
  1716. // 分镜角色
  1717. $characters = getProp($segment, 'characters');
  1718. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1719. $roles = explode(',', $characters);
  1720. // 从分镜内容中提取涉及的角色
  1721. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1722. // 获取匹配角色的参考图
  1723. foreach ($segment_characters as $character) {
  1724. if (isset($role_map[$character])) {
  1725. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1726. $img_index = count($ref_img_urls) + 1;
  1727. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1728. $ref_img_urls[] = $role_map[$character];
  1729. }
  1730. }
  1731. // 如果没有找到匹配的角色参考图,不使用参考图
  1732. if (empty($ref_img_urls)) {
  1733. $ref_img_urls = [];
  1734. }
  1735. // 准备生成任务参数
  1736. $params = [
  1737. 'model' => $model,
  1738. 'alias_segment_id' => $segment_id,
  1739. 'prompt' => $prompt,
  1740. 'ref_img_urls' => $ref_img_urls,
  1741. 'width' => $width,
  1742. 'height' => $height,
  1743. ];
  1744. // 优化提示词(不要生成字幕)
  1745. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1746. // $task_id = mt_rand(100000, 999999);
  1747. // 调用AI图片生成服务
  1748. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1749. $task_id = $task->id;
  1750. if (!$task_id) {
  1751. $failed_segments[] = [
  1752. 'segment_id' => $segment_id,
  1753. 'error' => '创建生成任务失败'
  1754. ];
  1755. continue;
  1756. }
  1757. $update_data = [
  1758. 'pic_task_id' => $task_id,
  1759. 'pic_task_status' => '生成中',
  1760. 'audio_url' => '',
  1761. 'updated_at' => date('Y-m-d H:i:s')
  1762. ];
  1763. // 如果有对话内容,创建视频配音合成任务
  1764. $dialogue = getProp($segment, 'dialogue');
  1765. if (!empty($dialogue)) {
  1766. $now = date('Y-m-d H:i:s');
  1767. $generate_json = [
  1768. 'text' => $dialogue,
  1769. 'role' => getProp($segment, 'voice_actor'),
  1770. 'voice_type' => getProp($segment, 'voice_type'),
  1771. 'voice_name' => getProp($segment, 'voice_name'),
  1772. 'emotion' => getProp($segment, 'emotion'),
  1773. 'emotion_type' => getProp($segment, 'emotion_type'),
  1774. 'gender' => getProp($segment, 'gender'),
  1775. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1776. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1777. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1778. 'pitch' => getProp($segment, 'pitch', 0),
  1779. ];
  1780. // 插入视频配音合成任务
  1781. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1782. 'alias_segment_id' => $segment_id,
  1783. 'generate_status' => '执行中',
  1784. 'audio_url' => '',
  1785. 'generate_json' => json_encode($generate_json, 256),
  1786. 'created_at' => $now,
  1787. 'updated_at' => $now,
  1788. ]);
  1789. if (!$dubTaskId) {
  1790. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1791. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1792. // Utils::throwError('20003:创建配音任务失败!');
  1793. }
  1794. } else {
  1795. // dialogue为空时,直接写入默认音频信息到分镜表
  1796. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1797. $update_data['audio_duration'] = 2.0;
  1798. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1799. }
  1800. // 更新分镜的任务信息
  1801. $update_result = DB::table('mp_episode_segments')
  1802. ->where('segment_id', $segment_id)
  1803. ->update($update_data);
  1804. // 如果是第一集的首帧图片,则存入待更新数组
  1805. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1806. Redis::sadd('anime_first_frame_urls', $segment_id);
  1807. }
  1808. if ($update_result) {
  1809. $updated_segments[] = [
  1810. 'segment_id' => $segment_id,
  1811. 'task_id' => $task_id,
  1812. 'status' => '生成中',
  1813. 'matched_scenes' => $matched_scene,
  1814. 'matched_roles' => $segment_characters,
  1815. 'ref_urls_count' => count($ref_img_urls)
  1816. ];
  1817. } else {
  1818. $failed_segments[] = [
  1819. 'segment_id' => $segment_id,
  1820. 'error' => '更新分镜任务状态失败'
  1821. ];
  1822. }
  1823. if ($dubTaskId) {
  1824. sleep(1);
  1825. // 请求远程服务器执行生成
  1826. $client = new Client(['timeout' => 300, 'verify' => false]);
  1827. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1828. $response = $result->getBody()->getContents();
  1829. $response_arr = json_decode($response, true);
  1830. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1831. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1832. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1833. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1834. }
  1835. }
  1836. } catch (\Exception $e) {
  1837. $failed_segments[] = [
  1838. 'segment_id' => $segment_id,
  1839. 'error' => $e->getMessage()
  1840. ];
  1841. }
  1842. }
  1843. // 更新剧集生成状态
  1844. if (!empty($updated_segments)) {
  1845. DB::table('mp_anime_episodes')
  1846. ->where('id', $episode_id)
  1847. ->update([
  1848. 'is_generated' => 1,
  1849. 'updated_at' => date('Y-m-d H:i:s')
  1850. ]);
  1851. }
  1852. return [
  1853. 'success_count' => count($updated_segments),
  1854. 'failed_count' => count($failed_segments),
  1855. 'success_segments' => $updated_segments,
  1856. 'failed_segments' => $failed_segments,
  1857. 'total_segments' => count($segments)
  1858. ];
  1859. }
  1860. public function reGenerateSegment($data) {
  1861. $segment_id = getProp($data, 'segment_id');
  1862. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1863. $anime_id = getProp($segment, 'anime_id');
  1864. $episode_id = getProp($segment, 'episode_id');
  1865. $episode_number = getProp($segment, 'episode_number');
  1866. $segment_content = getProp($data, 'segment_content');
  1867. $ratio = getProp($data, 'ratio');
  1868. if (!$ratio) {
  1869. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1870. if (!$ratio) $ratio = '9:16';
  1871. }
  1872. $dimensions = $this->getRatioDimensions($ratio);
  1873. $width = $dimensions['width'];
  1874. $height = $dimensions['height'];
  1875. if (!$anime_id || !$episode_id) {
  1876. Utils::throwError('1002:请选择分镜');
  1877. }
  1878. // 使用文生文模型重新解析segment_content
  1879. if (!empty($segment_content)) {
  1880. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1881. }
  1882. // 获取动漫的角色信息(包含参考图)
  1883. $anime = DB::table('mp_animes')
  1884. ->where('id', $anime_id)
  1885. ->select('roles', 'scenes')
  1886. ->first();
  1887. if (!$anime || !$anime->roles) {
  1888. Utils::throwError('20003:未找到角色信息');
  1889. }
  1890. $roles = json_decode($anime->roles, true);
  1891. if (!$roles) {
  1892. Utils::throwError('20003:角色信息格式错误');
  1893. }
  1894. // 构建角色名称到参考图的映射
  1895. $role_map = [];
  1896. foreach ($roles as $role) {
  1897. $role_name = getProp($role, 'role');
  1898. $role_url = getProp($role, 'url');
  1899. if (!empty($role_name) && !empty($role_url)) {
  1900. $role_map[$role_name] = $role_url;
  1901. }
  1902. }
  1903. $scenes = json_decode($anime->scenes, true);
  1904. if (!$scenes) {
  1905. Utils::throwError('20003:角色信息格式错误');
  1906. }
  1907. // 构建角色名称到参考图的映射
  1908. $scene_map = [];
  1909. foreach ($scenes as $scene) {
  1910. $scene_name = getProp($scene, 'scene');
  1911. $scene_url = getProp($scene, 'url');
  1912. if (!empty($scene_name) && !empty($scene_url)) {
  1913. $scene_map[$scene_name] = $scene_url;
  1914. }
  1915. }
  1916. $segment_id = $segment->segment_id;
  1917. $original_segment_content = $segment->segment_content;
  1918. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1919. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1920. if (empty($final_segment_content)) {
  1921. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1922. }
  1923. try {
  1924. $dubTaskId = 0;
  1925. // 分镜剧本数组
  1926. $update_data = [
  1927. 'segment_content' => $final_segment_content,
  1928. 'pic_task_status' => '生成中',
  1929. 'updated_at' => date('Y-m-d H:i:s')
  1930. ];
  1931. // 解析分镜内容,提取画面描述作为主要提示词
  1932. $prompt = $final_segment_content;
  1933. $ref_img_urls = [];
  1934. // 分镜场景
  1935. $scene = getProp($data, 'scene');
  1936. if ($scene) {
  1937. $matched_scene = '';
  1938. if (isset($scene_map[$scene])) {
  1939. $img_index = count($ref_img_urls) + 1;
  1940. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1941. $ref_img_urls[] = $scene_map[$scene];
  1942. $matched_scene = $scene;
  1943. }
  1944. $update_data['scene'] = $scene;
  1945. }
  1946. // 分镜角色
  1947. $characters = getProp($data, 'characters');
  1948. if ($characters) {
  1949. $update_data['characters'] = $characters;
  1950. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1951. $characters = explode(',', $characters);
  1952. // 从分镜内容中提取涉及的角色
  1953. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1954. // 获取匹配角色的参考图
  1955. foreach ($segment_characters as $character) {
  1956. if (isset($role_map[$character])) {
  1957. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1958. $img_index = count($ref_img_urls) + 1;
  1959. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1960. $ref_img_urls[] = $role_map[$character];
  1961. }
  1962. }
  1963. }
  1964. // 如果没有找到匹配的角色参考图,不使用参考图
  1965. if (empty($ref_img_urls)) {
  1966. $ref_img_urls = [];
  1967. }
  1968. // 准备生成任务参数
  1969. $params = [
  1970. 'alias_segment_id' => $segment_id,
  1971. 'prompt' => $prompt,
  1972. 'ref_img_urls' => $ref_img_urls,
  1973. 'width' => $width,
  1974. 'height' => $height,
  1975. ];
  1976. // 优化提示词(不要生成字幕)
  1977. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1978. // 调用AI图片生成服务
  1979. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1980. $task_id = $task->id;
  1981. if (!$task_id) {
  1982. Utils::throwError('20003:创建生成任务失败!');
  1983. }
  1984. $update_data['pic_task_id'] = $task_id;
  1985. // 更新分镜剧本信息
  1986. $this->handleSegmentContent($update_data);
  1987. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1988. if ($segment_content) {
  1989. $dialogue = getProp($update_data, 'dialogue');
  1990. if (!empty($dialogue)) {
  1991. $now = date('Y-m-d H:i:s');
  1992. $generate_json = [
  1993. 'text' => $dialogue,
  1994. 'role' => getProp($update_data, 'voice_actor'),
  1995. 'voice_type' => getProp($update_data, 'voice_type'),
  1996. 'voice_name' => getProp($update_data, 'voice_name'),
  1997. 'emotion' => getProp($update_data, 'emotion'),
  1998. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1999. 'gender' => getProp($update_data, 'gender'),
  2000. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2001. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2002. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2003. 'pitch' => getProp($update_data, 'pitch', 0),
  2004. ];
  2005. // 插入视频配音合成任务
  2006. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2007. 'alias_segment_id' => $segment_id,
  2008. 'generate_status' => '执行中',
  2009. 'audio_url' => '',
  2010. 'generate_json' => json_encode($generate_json, 256),
  2011. 'created_at' => date('Y-m-d H:i:s'),
  2012. 'updated_at' => date('Y-m-d H:i:s'),
  2013. ]);
  2014. if (!$dubTaskId) {
  2015. Utils::throwError('20003:创建配音任务失败!');
  2016. }
  2017. $update_data['audio_url'] = '';
  2018. } else {
  2019. // dialogue为空时,直接写入默认音频信息
  2020. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2021. $update_data['audio_duration'] = 2.0;
  2022. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2023. }
  2024. }
  2025. $boolen = DB::table('mp_episode_segments')
  2026. ->where('segment_id', $segment_id)
  2027. ->update($update_data);
  2028. // 如果是第一集的首帧图片,则存入待更新数组
  2029. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2030. Redis::sadd('anime_first_frame_urls', $segment_id);
  2031. }
  2032. if ($dubTaskId) {
  2033. // 请求远程服务器执行生成
  2034. $client = new Client(['timeout' => 300, 'verify' => false]);
  2035. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2036. $response = $result->getBody()->getContents();
  2037. $response_arr = json_decode($response, true);
  2038. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2039. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2040. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2041. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2042. Utils::throwError('20003:火山生成音频失败');
  2043. }
  2044. }
  2045. } catch (\Exception $e) {
  2046. $failed_segments[] = [
  2047. 'segment_id' => $segment_id,
  2048. 'error' => $e->getMessage()
  2049. ];
  2050. }
  2051. // 创建任务之后先暂停10s等待异步任务完成
  2052. sleep(10);
  2053. $img_url = $this->loopGetPicTaskResult($task_id);
  2054. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2055. // 图片生成后新增对话记录
  2056. try {
  2057. $uid = Site::getUid();
  2058. $now = date('Y-m-d H:i:s');
  2059. // 使用AI反推图片提示词
  2060. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2061. // 保存对话记录
  2062. $records = [
  2063. [
  2064. 'uid' => $uid,
  2065. 'anime_id' => $anime_id,
  2066. 'sequence' => $episode_number,
  2067. 'role' => 'user',
  2068. 'content' => '重新生成',
  2069. 'segment_id' => $segment_id,
  2070. 'pic_task_id' => $task_id,
  2071. 'image_url' => '',
  2072. 'created_at' => $now,
  2073. 'updated_at' => $now
  2074. ],
  2075. [
  2076. 'uid' => $uid,
  2077. 'anime_id' => $anime_id,
  2078. 'sequence' => $episode_number,
  2079. 'role' => 'assistant',
  2080. 'content' => $pic_prompt,
  2081. 'segment_id' => $segment_id,
  2082. 'pic_task_id' => $task_id,
  2083. 'image_url' => $img_url,
  2084. 'created_at' => $now,
  2085. 'updated_at' => $now
  2086. ]
  2087. ];
  2088. DB::table('mp_anime_records')->insert($records);
  2089. } catch (\Exception $e) {
  2090. // 记录日志但不影响主流程
  2091. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2092. 'segment_id' => $segment_id,
  2093. 'img_url' => $img_url
  2094. ]);
  2095. }
  2096. return $img_url;
  2097. }
  2098. public function addSegment($data) {
  2099. $prev_segment_id = getProp($data, 'prev_segment_id');
  2100. $img_url = getProp($data, 'img_url');
  2101. $video_url = getProp($data, 'video_url');
  2102. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2103. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2104. $anime_id = getProp($segment, 'anime_id');
  2105. $episode_id = getProp($segment, 'episode_id');
  2106. $episode_number = getProp($segment, 'episode_number');
  2107. $segment_number = getProp($segment, 'segment_number');
  2108. $new_segment_number = $segment_number + 1;
  2109. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2110. // 分镜剧本数组
  2111. $insert_data = [
  2112. 'anime_id' => $anime_id,
  2113. 'episode_id' => $episode_id,
  2114. 'episode_number' => $episode_number,
  2115. 'act_number' => getProp($segment, 'act_number'),
  2116. 'act_title' => getProp($segment, 'act_title'),
  2117. 'segment_id' => $segment_id,
  2118. 'segment_number' => $new_segment_number,
  2119. 'segment_content' => '',
  2120. 'img_url' => '',
  2121. 'video_url' => '',
  2122. 'created_at' => date('Y-m-d H:i:s'),
  2123. 'updated_at' => date('Y-m-d H:i:s')
  2124. ];
  2125. if ($img_url) $insert_data['img_url'] = $img_url;
  2126. if ($video_url) {
  2127. $insert_data['origin_video_url'] = $video_url;
  2128. $insert_data['current_type'] = 2;
  2129. $compressed_video_url = compressVideo($video_url);
  2130. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2131. }
  2132. try {
  2133. DB::beginTransaction();
  2134. // 先更新序号
  2135. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2136. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2137. if (!$id) {
  2138. Utils::throwError('20003:新增分镜失败!');
  2139. }
  2140. }catch (\Exception $e) {
  2141. DB::rollBack();
  2142. Utils::throwError('20003:'.$e->getMessage());
  2143. }
  2144. DB::commit();
  2145. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2146. $segment = $segment ? (array)$segment : [];
  2147. return $segment;
  2148. // 以下代码暂弃用
  2149. $anime_id = getProp($segment, 'anime_id');
  2150. $episode_id = getProp($segment, 'episode_id');
  2151. $episode_number = getProp($segment, 'episode_number');
  2152. $segment_number = getProp($segment, 'segment_number');
  2153. $segment_content = getProp($data, 'segment_content');
  2154. $img_url = getProp($data, 'img_url');
  2155. $video_url = getProp($data, 'video_url');
  2156. $ratio = getProp($data, 'ratio');
  2157. $dimensions = $this->getRatioDimensions($ratio);
  2158. $width = $dimensions['width'];
  2159. $height = $dimensions['height'];
  2160. if (!$anime_id || !$episode_id) {
  2161. Utils::throwError('1002:请选择分镜');
  2162. }
  2163. // 使用文生文模型重新解析segment_content
  2164. if (!empty($segment_content)) {
  2165. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2166. }
  2167. // 获取动漫的角色信息(包含参考图)
  2168. $anime = DB::table('mp_animes')
  2169. ->where('id', $anime_id)
  2170. ->select('roles', 'scenes')
  2171. ->first();
  2172. if (!$anime || !$anime->roles) {
  2173. Utils::throwError('20003:未找到角色信息');
  2174. }
  2175. $roles = json_decode($anime->roles, true);
  2176. if (!$roles) {
  2177. Utils::throwError('20003:角色信息格式错误');
  2178. }
  2179. // 构建角色名称到参考图的映射
  2180. $role_map = [];
  2181. foreach ($roles as $role) {
  2182. $role_name = getProp($role, 'role');
  2183. $role_url = getProp($role, 'url');
  2184. if (!empty($role_name) && !empty($role_url)) {
  2185. $role_map[$role_name] = $role_url;
  2186. }
  2187. }
  2188. $scenes = json_decode($anime->scenes, true);
  2189. if (!$scenes) {
  2190. Utils::throwError('20003:角色信息格式错误');
  2191. }
  2192. // 构建角色名称到参考图的映射
  2193. $scene_map = [];
  2194. foreach ($scenes as $scene) {
  2195. $scene_name = getProp($scene, 'scene');
  2196. $scene_url = getProp($scene, 'url');
  2197. if (!empty($scene_name) && !empty($scene_url)) {
  2198. $scene_map[$scene_name] = $scene_url;
  2199. }
  2200. }
  2201. $segment_id = $segment->segment_id;
  2202. $original_segment_content = $segment->segment_content;
  2203. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2204. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2205. if (empty($final_segment_content)) {
  2206. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2207. }
  2208. try {
  2209. $dubTaskId = 0;
  2210. DB::beginTransaction();
  2211. $new_segment_number = $segment_number + 1;
  2212. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2213. // 分镜剧本数组
  2214. $insert_data = [
  2215. 'anime_id' => $anime_id,
  2216. 'episode_id' => $episode_id,
  2217. 'episode_number' => $episode_number,
  2218. 'act_number' => getProp($segment, 'act_number'),
  2219. 'act_title' => getProp($segment, 'act_title'),
  2220. 'segment_id' => $segment_id,
  2221. 'segment_number' => $new_segment_number,
  2222. 'segment_content' => $final_segment_content,
  2223. 'img_url' => $img_url,
  2224. 'video_url' => $video_url,
  2225. 'created_at' => date('Y-m-d H:i:s'),
  2226. 'updated_at' => date('Y-m-d H:i:s')
  2227. ];
  2228. // 更新分镜剧本信息
  2229. $this->handleSegmentContent($insert_data);
  2230. // 如果有对话内容,创建视频配音合成任务
  2231. $dialogue = getProp($insert_data, 'dialogue');
  2232. if (!empty($dialogue)) {
  2233. $now = date('Y-m-d H:i:s');
  2234. $generate_json = [
  2235. 'text' => $dialogue,
  2236. 'role' => getProp($insert_data, 'voice_actor'),
  2237. 'voice_type' => getProp($insert_data, 'voice_type'),
  2238. 'voice_name' => getProp($insert_data, 'voice_name'),
  2239. 'emotion' => getProp($insert_data, 'emotion'),
  2240. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2241. 'gender' => getProp($insert_data, 'gender'),
  2242. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2243. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2244. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2245. 'pitch' => getProp($insert_data, 'pitch', 0),
  2246. ];
  2247. // 插入视频配音合成任务
  2248. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2249. 'alias_segment_id' => $segment_id,
  2250. 'generate_status' => '执行中',
  2251. 'audio_url' => '',
  2252. 'generate_json' => json_encode($generate_json, 256),
  2253. 'created_at' => $now,
  2254. 'updated_at' => $now,
  2255. ]);
  2256. if (!$dubTaskId) {
  2257. Utils::throwError('20003:创建配音任务失败!');
  2258. }
  2259. $insert_data['audio_url'] = '';
  2260. } else {
  2261. // dialogue为空时,直接写入默认音频信息
  2262. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2263. $insert_data['audio_duration'] = 2.0;
  2264. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2265. }
  2266. // 如果没有上传图片则使用当前描述进行生成
  2267. if (!$img_url) {
  2268. // 解析分镜内容,提取画面描述作为主要提示词
  2269. $prompt = $final_segment_content;
  2270. $ref_img_urls = [];
  2271. // 分镜场景
  2272. $scene = getProp($insert_data, 'scene');
  2273. if ($scene) {
  2274. $matched_scene = '';
  2275. if (isset($scene_map[$scene])) {
  2276. $img_index = count($ref_img_urls) + 1;
  2277. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2278. $ref_img_urls[] = $scene_map[$scene];
  2279. $matched_scene = $scene;
  2280. }
  2281. $update_data['scene'] = $scene;
  2282. }
  2283. // 分镜角色
  2284. $characters = getProp($insert_data, 'characters');
  2285. if ($characters) {
  2286. $update_data['characters'] = $characters;
  2287. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2288. $characters = explode(',', $characters);
  2289. // 从分镜内容中提取涉及的角色
  2290. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2291. // 获取匹配角色的参考图
  2292. foreach ($segment_characters as $character) {
  2293. if (isset($role_map[$character])) {
  2294. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2295. $img_index = count($ref_img_urls) + 1;
  2296. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2297. $ref_img_urls[] = $role_map[$character];
  2298. }
  2299. }
  2300. }
  2301. // 如果没有找到匹配的角色参考图,不使用参考图
  2302. if (empty($ref_img_urls)) {
  2303. $ref_img_urls = [];
  2304. }
  2305. // 准备生成任务参数
  2306. $params = [
  2307. 'alias_segment_id' => $segment_id,
  2308. 'prompt' => $prompt,
  2309. 'ref_img_urls' => $ref_img_urls,
  2310. 'width' => $width,
  2311. 'height' => $height,
  2312. ];
  2313. // 调用AI图片生成服务
  2314. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2315. $task_id = $task->id;
  2316. // $task_id = 'whatever';
  2317. if (!$task_id) {
  2318. Utils::throwError('20003:创建生成任务失败!');
  2319. }
  2320. $insert_data['pic_task_status'] = '生成中';
  2321. $insert_data['pic_task_id'] = $task_id;
  2322. }
  2323. // 先更新序号
  2324. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2325. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2326. if (!$boolen) {
  2327. Utils::throwError('20003:新增分镜失败!');
  2328. }
  2329. // 如果是第一集的首帧图片,则存入待更新数组
  2330. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2331. Redis::sadd('anime_first_frame_urls', $segment_id);
  2332. }
  2333. if ($dubTaskId) {
  2334. // 请求远程服务器执行生成
  2335. $client = new Client(['timeout' => 300, 'verify' => false]);
  2336. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2337. $response = $result->getBody()->getContents();
  2338. $response_arr = json_decode($response, true);
  2339. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2340. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2341. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2342. Utils::throwError('20003:火山生成音频失败');
  2343. }
  2344. }
  2345. } catch (\Exception $e) {
  2346. DB::rollBack();
  2347. Utils::throwError('20003:'.$e->getMessage());
  2348. }
  2349. DB::commit();
  2350. // 创建任务之后先暂停10s等待异步任务完成
  2351. sleep(10);
  2352. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2353. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2354. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2355. $segment = $segment ? (array)$segment : [];
  2356. return $segment;
  2357. }
  2358. public function copySegment($data) {
  2359. $segment_id = getProp($data, 'segment_id');
  2360. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2361. if (!$segment) Utils::throwError('20003:请选择分镜');
  2362. $anime_id = getProp($segment, 'anime_id');
  2363. $episode_id = getProp($segment, 'episode_id');
  2364. $episode_number = getProp($segment, 'episode_number');
  2365. $segment_number = getProp($segment, 'segment_number');
  2366. $new_segment_id = 0;
  2367. try {
  2368. DB::beginTransaction();
  2369. $segment = (array)$segment;
  2370. unset($segment['id']);
  2371. $segment['segment_number'] += 1;
  2372. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2373. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2374. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2375. // 更新其他分镜序号
  2376. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2377. // 复制分镜
  2378. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2379. if (!$id) {
  2380. Utils::throwError('20003:复制分镜失败');
  2381. }
  2382. }catch (\Exception $e) {
  2383. DB::rollBack();
  2384. Utils::throwError('20003:'.$e->getMessage());
  2385. }
  2386. DB::commit();
  2387. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2388. $segment = $segment ? (array)$segment : [];
  2389. return $segment;
  2390. }
  2391. public function moveSegment($data) {
  2392. $segment_id = getProp($data, 'segment_id');
  2393. $target_segment_id = getProp($data, 'target_segment_id');
  2394. // 获取源分镜信息
  2395. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2396. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2397. // 获取目标分镜信息
  2398. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2399. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2400. $anime_id = getProp($source_segment, 'anime_id');
  2401. $episode_id = getProp($source_segment, 'episode_id');
  2402. $episode_number = getProp($source_segment, 'episode_number');
  2403. $source_segment_number = getProp($source_segment, 'segment_number');
  2404. $target_segment_number = getProp($target_segment, 'segment_number');
  2405. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2406. $target_anime_id = getProp($target_segment, 'anime_id');
  2407. $target_episode_number = getProp($target_segment, 'episode_number');
  2408. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2409. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2410. }
  2411. // 如果源分镜和目标分镜相同,无需移动
  2412. if ($source_segment_number == $target_segment_number) {
  2413. return true;
  2414. }
  2415. try {
  2416. DB::beginTransaction();
  2417. if ($source_segment_number < $target_segment_number) {
  2418. // 向后移动:源分镜移动到目标分镜之后
  2419. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2420. DB::table('mp_episode_segments')
  2421. ->where('anime_id', $anime_id)
  2422. ->where('episode_id', $episode_id)
  2423. ->where('segment_number', '>', $source_segment_number)
  2424. ->where('segment_number', '<=', $target_segment_number)
  2425. ->decrement('segment_number');
  2426. // 2. 将源分镜移动到目标分镜之后
  2427. $new_segment_number = $target_segment_number;
  2428. } else {
  2429. // 向前移动:源分镜移动到目标分镜之后
  2430. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2431. DB::table('mp_episode_segments')
  2432. ->where('anime_id', $anime_id)
  2433. ->where('episode_id', $episode_id)
  2434. ->where('segment_number', '>', $target_segment_number)
  2435. ->where('segment_number', '<', $source_segment_number)
  2436. ->increment('segment_number');
  2437. // 2. 将源分镜移动到目标分镜之后
  2438. $new_segment_number = $target_segment_number + 1;
  2439. }
  2440. // 3. 更新源分镜的序号
  2441. $update_result = DB::table('mp_episode_segments')
  2442. ->where('segment_id', $segment_id)
  2443. ->update([
  2444. 'segment_number' => $new_segment_number,
  2445. 'updated_at' => date('Y-m-d H:i:s')
  2446. ]);
  2447. if (!$update_result) {
  2448. Utils::throwError('20003:更新分镜序号失败');
  2449. }
  2450. DB::commit();
  2451. return true;
  2452. } catch (\Exception $e) {
  2453. DB::rollBack();
  2454. Utils::throwError('20003:' . $e->getMessage());
  2455. }
  2456. }
  2457. public function delSegment($data) {
  2458. $segment_id = getProp($data, 'segment_id');
  2459. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2460. if (!$segment) Utils::throwError('20003:请选择分镜');
  2461. $anime_id = getProp($segment, 'anime_id');
  2462. $episode_id = getProp($segment, 'episode_id');
  2463. $episode_number = getProp($segment, 'episode_number');
  2464. $segment_number = getProp($segment, 'segment_number');
  2465. try {
  2466. DB::beginTransaction();
  2467. // 删除分镜
  2468. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2469. if (!$boolen) {
  2470. Utils::throwError('20003:删除分镜失败');
  2471. }
  2472. // 更新其他分镜序号
  2473. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2474. }catch (\Exception $e) {
  2475. DB::rollBack();
  2476. Utils::throwError('20003:'.$e->getMessage());
  2477. }
  2478. DB::commit();
  2479. return true;
  2480. }
  2481. public function applySegment($data) {
  2482. $segment_id = getProp($data, 'segment_id');
  2483. $url = getProp($data, 'url');
  2484. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2485. if (!$url) Utils::throwError('20003:URL不能为空');
  2486. // 获取URL的文件扩展名
  2487. $urlPath = parse_url($url, PHP_URL_PATH);
  2488. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2489. // 定义图片和视频的扩展名
  2490. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2491. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2492. // 判断是图片还是视频
  2493. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2494. if (in_array($extension, $imageExtensions)) {
  2495. // 图片类型
  2496. $updateData['img_url'] = $url;
  2497. $updateData['current_type'] = 1;
  2498. } elseif (in_array($extension, $videoExtensions)) {
  2499. // 视频类型
  2500. $updateData['video_url'] = $url;
  2501. $updateData['current_type'] = 2;
  2502. } else {
  2503. Utils::throwError('20003:不支持的文件类型');
  2504. }
  2505. // 更新分镜表
  2506. $result = DB::table('mp_episode_segments')
  2507. ->where('segment_id', $segment_id)
  2508. ->update($updateData);
  2509. if (!$result) {
  2510. Utils::throwError('20003:更新分镜失败');
  2511. }
  2512. return true;
  2513. }
  2514. public function segmentHistory($data) {
  2515. $segment_id = getProp($data, 'segment_id');
  2516. // 获取历史图片
  2517. $pics = [];
  2518. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2519. foreach($pic_history as $task) {
  2520. $result_url = getProp($task, 'result_url');
  2521. if (is_json($result_url)) {
  2522. $pics = array_merge($pics, json_decode($result_url, true));
  2523. }else {
  2524. $pics[] = $result_url;
  2525. }
  2526. }
  2527. // 获取历史视频
  2528. $videos = [];
  2529. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2530. foreach($video_history as $task) {
  2531. $result_url = getProp($task, 'result_url');
  2532. if (is_json($result_url)) {
  2533. $videos = array_merge($videos, json_decode($result_url, true));
  2534. }else {
  2535. $videos[] = $result_url;
  2536. }
  2537. }
  2538. return compact('pics', 'videos');
  2539. }
  2540. public function addAct($data) {
  2541. $prev_act_id = getProp($data, 'prev_act_id');
  2542. $act_title = getProp($data, 'act_title', '');
  2543. $act_content = getProp($data, 'act_content', '');
  2544. $act_duration = getProp($data, 'act_duration', 5);
  2545. $video_url = getProp($data, 'video_url');
  2546. // 根据prev_act_id获取记录
  2547. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2548. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2549. $anime_id = getProp($prev_segment, 'anime_id');
  2550. $episode_id = getProp($prev_segment, 'episode_id');
  2551. $episode_number = getProp($prev_segment, 'episode_number');
  2552. $prev_act_number = getProp($prev_segment, 'act_number');
  2553. // 获取新的act_number
  2554. $new_act_number = $prev_act_number + 1;
  2555. try {
  2556. DB::beginTransaction();
  2557. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2558. DB::table('mp_episode_segments')
  2559. ->where('anime_id', $anime_id)
  2560. ->where('episode_id', $episode_id)
  2561. ->where('act_number', '>', $prev_act_number)
  2562. ->increment('act_number');
  2563. // 插入新片段记录
  2564. $insert_data = [
  2565. 'anime_id' => $anime_id,
  2566. 'episode_id' => $episode_id,
  2567. 'episode_number' => $episode_number,
  2568. 'act_number' => $new_act_number,
  2569. 'created_at' => date('Y-m-d H:i:s'),
  2570. 'updated_at' => date('Y-m-d H:i:s')
  2571. ];
  2572. if ($act_title) {
  2573. $insert_data['act_title'] = $act_title;
  2574. }
  2575. if ($act_content) {
  2576. $insert_data['act_content'] = $act_content;
  2577. }
  2578. if ($act_duration) {
  2579. $insert_data['act_duration'] = $act_duration;
  2580. }
  2581. if ($video_url) {
  2582. $insert_data['origin_video_url'] = $video_url;
  2583. $insert_data['current_type'] = 2;
  2584. $compressed_video_url = compressVideo($video_url);
  2585. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2586. }
  2587. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2588. if (!$id) {
  2589. Utils::throwError('20003:新增片段失败!');
  2590. }
  2591. DB::commit();
  2592. }catch (\Exception $e) {
  2593. DB::rollBack();
  2594. Utils::throwError('20003:'.$e->getMessage());
  2595. }
  2596. $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();
  2597. $segment = $segment ? (array)$segment : [];
  2598. return $segment;
  2599. }
  2600. public function editAct($data) {
  2601. $act_id = getProp($data, 'act_id');
  2602. $act_content = getProp($data, 'act_content');
  2603. $act_duration = getProp($data, 'act_duration');
  2604. $act_title = getProp($data, 'act_title');
  2605. $image_url = getProp($data, 'image_url');
  2606. $video_url = getProp($data, 'video_url');
  2607. // 参数验证
  2608. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2609. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2610. $segment = DB::table('mp_episode_segments')
  2611. ->where('id', $act_id)
  2612. ->first();
  2613. if (!$segment) Utils::throwError('20003:该片段不存在');
  2614. try {
  2615. DB::beginTransaction();
  2616. // 准备更新数据
  2617. $update_data = [
  2618. 'updated_at' => date('Y-m-d H:i:s')
  2619. ];
  2620. // 更新act相关字段
  2621. if (!empty($act_content)) {
  2622. $update_data['act_show_content'] = $act_content;
  2623. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2624. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2625. $shot_counter = 0;
  2626. $update_data['act_show_content'] = preg_replace_callback(
  2627. '/【(?:镜头|分镜)(\d+)】/u',
  2628. function($matches) use (&$shot_counter) {
  2629. $shot_counter++;
  2630. return '【镜头' . $shot_counter . '】';
  2631. },
  2632. $update_data['act_show_content']
  2633. );
  2634. }
  2635. if (!empty($act_duration)) {
  2636. $update_data['act_duration'] = $act_duration;
  2637. }
  2638. if (!empty($act_title)) {
  2639. $update_data['act_title'] = $act_title;
  2640. }
  2641. // 处理图片上传
  2642. if ($image_url) {
  2643. $update_data['img_url'] = $image_url;
  2644. $update_data['current_type'] = 1;
  2645. // 同时写入一个图片生成任务记录
  2646. if ($act_id) {
  2647. $pic_task = [
  2648. 'alias_act_id' => $act_id,
  2649. 'ref_img_url' => json_encode([]),
  2650. 'status' => 'success',
  2651. 'result_url' => json_encode([$image_url], 256),
  2652. 'model' => '',
  2653. 'created_at' => date('Y-m-d H:i:s'),
  2654. 'updated_at' => date('Y-m-d H:i:s'),
  2655. ];
  2656. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2657. }
  2658. }
  2659. // 处理视频上传
  2660. if ($video_url) {
  2661. $update_data['origin_video_url'] = $video_url;
  2662. $compressed_video_url = compressVideo($video_url);
  2663. $update_data['current_type'] = 2;
  2664. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2665. // 同时写入一个视频生成任务记录
  2666. if ($act_id) {
  2667. $video_task = [
  2668. 'alias_act_id' => $act_id,
  2669. 'status' => 'success',
  2670. 'result_url' => $update_data['origin_video_url'],
  2671. 'compressed_url' => $update_data['video_url'],
  2672. 'created_at' => date('Y-m-d H:i:s'),
  2673. 'updated_at' => date('Y-m-d H:i:s'),
  2674. ];
  2675. DB::table('mp_generate_video_tasks')->insert($video_task);
  2676. }
  2677. }
  2678. // 更新片段信息
  2679. $result = DB::table('mp_episode_segments')
  2680. ->where('id', $act_id)
  2681. ->update($update_data);
  2682. if ($result === false) {
  2683. Utils::throwError('20003:更新片段失败');
  2684. }
  2685. DB::commit();
  2686. // 返回新复制的记录
  2687. $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();
  2688. $new_segment = (array)$new_segment;
  2689. return $new_segment;
  2690. } catch (\Exception $e) {
  2691. DB::rollBack();
  2692. dLog('anime')->error('更新片段失败', [
  2693. 'act_id' => $act_id,
  2694. 'error' => $e->getMessage()
  2695. ]);
  2696. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2697. }
  2698. }
  2699. public function copyAct($data) {
  2700. $act_id = getProp($data, 'act_id');
  2701. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2702. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2703. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2704. $anime_id = getProp($source_segment, 'anime_id');
  2705. $episode_id = getProp($source_segment, 'episode_id');
  2706. $episode_number = getProp($source_segment, 'episode_number');
  2707. $act_number = getProp($source_segment, 'act_number');
  2708. try {
  2709. DB::beginTransaction();
  2710. // 新act的编号
  2711. $new_act_number = $act_number + 1;
  2712. // 更新后续所有act的act_number
  2713. DB::table('mp_episode_segments')
  2714. ->where('anime_id', $anime_id)
  2715. ->where('episode_id', $episode_id)
  2716. ->where('act_number', '>', $act_number)
  2717. ->increment('act_number');
  2718. // 复制该片段记录
  2719. $segment_data = (array)$source_segment;
  2720. unset($segment_data['id']);
  2721. $segment_data['video_url'] = '';
  2722. $segment_data['video_task_id'] = '';
  2723. $segment_data['video_task_status'] = '';
  2724. $segment_data['act_number'] = $new_act_number;
  2725. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2726. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2727. if (!$id) {
  2728. Utils::throwError('20003:复制片段失败');
  2729. }
  2730. DB::commit();
  2731. }catch (\Exception $e) {
  2732. DB::rollBack();
  2733. Utils::throwError('20003:'.$e->getMessage());
  2734. }
  2735. // 返回新复制的记录
  2736. $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();
  2737. $new_segment = $new_segment ? (array)$new_segment : [];
  2738. $new_segment['act_id'] = $id;
  2739. return $new_segment;
  2740. }
  2741. public function moveAct($data) {
  2742. $act_id = getProp($data, 'act_id');
  2743. $target_act_id = getProp($data, 'target_act_id');
  2744. // 获取源片段信息
  2745. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2746. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2747. // 获取目标片段信息
  2748. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2749. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2750. $anime_id = getProp($source_segment, 'anime_id');
  2751. $episode_id = getProp($source_segment, 'episode_id');
  2752. $source_act_number = getProp($source_segment, 'act_number');
  2753. $target_act_number = getProp($target_segment, 'act_number');
  2754. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2755. $target_anime_id = getProp($target_segment, 'anime_id');
  2756. $target_episode_id = getProp($target_segment, 'episode_id');
  2757. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2758. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2759. }
  2760. // 如果源片段和目标片段相同,无需移动
  2761. if ($source_act_number == $target_act_number) {
  2762. return true;
  2763. }
  2764. try {
  2765. DB::beginTransaction();
  2766. if ($source_act_number < $target_act_number) {
  2767. // 向后移动:源片段移动到目标片段之后
  2768. // 1. 将源片段和目标片段之间的所有片段编号减1
  2769. DB::table('mp_episode_segments')
  2770. ->where('anime_id', $anime_id)
  2771. ->where('episode_id', $episode_id)
  2772. ->where('act_number', '>', $source_act_number)
  2773. ->where('act_number', '<=', $target_act_number)
  2774. ->decrement('act_number');
  2775. // 2. 将源片段移动到目标片段之后
  2776. $new_act_number = $target_act_number;
  2777. } else {
  2778. // 向前移动:源片段移动到目标片段之后
  2779. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2780. DB::table('mp_episode_segments')
  2781. ->where('anime_id', $anime_id)
  2782. ->where('episode_id', $episode_id)
  2783. ->where('act_number', '>', $target_act_number)
  2784. ->where('act_number', '<', $source_act_number)
  2785. ->increment('act_number');
  2786. // 2. 将源片段移动到目标片段之后
  2787. $new_act_number = $target_act_number + 1;
  2788. }
  2789. // 3. 更新源片段的编号
  2790. $update_result = DB::table('mp_episode_segments')
  2791. ->where('id', $act_id)
  2792. ->update([
  2793. 'act_number' => $new_act_number,
  2794. 'updated_at' => date('Y-m-d H:i:s')
  2795. ]);
  2796. if (!$update_result) {
  2797. Utils::throwError('20003:更新片段编号失败');
  2798. }
  2799. DB::commit();
  2800. return true;
  2801. } catch (\Exception $e) {
  2802. DB::rollBack();
  2803. Utils::throwError('20003:' . $e->getMessage());
  2804. }
  2805. }
  2806. public function delAct($data) {
  2807. $act_id = getProp($data, 'act_id');
  2808. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2809. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2810. if (!$segment) Utils::throwError('20003:请选择片段');
  2811. $anime_id = getProp($segment, 'anime_id');
  2812. $episode_id = getProp($segment, 'episode_id');
  2813. $act_number = getProp($segment, 'act_number');
  2814. try {
  2815. DB::beginTransaction();
  2816. // 删除该片段记录
  2817. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2818. if (!$deleted) {
  2819. Utils::throwError('20003:删除片段失败');
  2820. }
  2821. // 更新后续act的编号
  2822. DB::table('mp_episode_segments')
  2823. ->where('anime_id', $anime_id)
  2824. ->where('episode_id', $episode_id)
  2825. ->where('act_number', '>', $act_number)
  2826. ->decrement('act_number');
  2827. DB::commit();
  2828. }catch (\Exception $e) {
  2829. DB::rollBack();
  2830. Utils::throwError('20003:'.$e->getMessage());
  2831. }
  2832. return true;
  2833. }
  2834. public function applyAct($data) {
  2835. $act_id = getProp($data, 'act_id');
  2836. $url = getProp($data, 'url');
  2837. if (!$act_id) Utils::throwError('20003:请选择片段');
  2838. if (!$url) Utils::throwError('20003:URL不能为空');
  2839. // 获取URL的文件扩展名
  2840. $urlPath = parse_url($url, PHP_URL_PATH);
  2841. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2842. // 定义图片和视频的扩展名
  2843. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2844. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2845. // 判断是图片还是视频
  2846. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2847. if (in_array($extension, $imageExtensions)) {
  2848. // 图片类型
  2849. $updateData['img_url'] = $url;
  2850. $updateData['current_type'] = 1;
  2851. } elseif (in_array($extension, $videoExtensions)) {
  2852. // 视频类型
  2853. $updateData['video_url'] = $url;
  2854. $updateData['current_type'] = 2;
  2855. } else {
  2856. Utils::throwError('20003:不支持的文件类型');
  2857. }
  2858. // 更新片段记录(全能模式下每个act只有一条记录)
  2859. $result = DB::table('mp_episode_segments')
  2860. ->where('id', $act_id)
  2861. ->update($updateData);
  2862. if (!$result) {
  2863. Utils::throwError('20003:更新片段失败');
  2864. }
  2865. return true;
  2866. }
  2867. public function actChatHistory($data) {
  2868. $act_id = getProp($data, 'act_id');
  2869. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2870. $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');
  2871. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2872. $value = (array)$value;
  2873. $value['created_at'] = transDate($value['created_at']);
  2874. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2875. else $value['reference_images'] = [];
  2876. return $value;
  2877. })->toArray();
  2878. // 获取历史图片
  2879. $url = [];
  2880. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2881. foreach($pic_history as $task) {
  2882. $result_url = getProp($task, 'result_url');
  2883. if (is_json($result_url)) {
  2884. $url = array_merge($url, json_decode($result_url, true));
  2885. }else {
  2886. $url[] = $result_url;
  2887. }
  2888. }
  2889. // 获取历史视频
  2890. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2891. foreach($video_history as $task) {
  2892. $result_url = getProp($task, 'result_url');
  2893. if (is_json($result_url)) {
  2894. $url = array_merge($url, json_decode($result_url, true));
  2895. }else {
  2896. $url[] = $result_url;
  2897. }
  2898. }
  2899. // 获取资产库
  2900. $products = [];
  2901. // 通过act_id查询片段信息获取episode_id
  2902. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2903. if ($segment) {
  2904. $episode_id = getProp($segment, 'episode_id');
  2905. // 查询剧集信息获取roles、scenes和extra_products
  2906. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2907. if ($episode) {
  2908. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2909. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2910. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2911. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2912. // 先合并roles、scenes和props
  2913. // 处理角色数组
  2914. foreach ($roles as $role) {
  2915. $product = $role;
  2916. // 将role字段重命名为product_name
  2917. if (is_array($product) && !empty($product['role'] ?? null)) {
  2918. $product['product_name'] = $product['role'];
  2919. unset($product['role']);
  2920. $product['product'] = 1; // 标记类型为角色
  2921. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2922. }
  2923. }
  2924. // 处理场景数组
  2925. foreach ($scenes as $scene) {
  2926. $product = $scene;
  2927. // 将scene字段重命名为product_name
  2928. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2929. $product['product_name'] = $product['scene'];
  2930. unset($product['scene']);
  2931. $product['product'] = 2; // 标记类型为场景
  2932. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2933. }
  2934. }
  2935. // 处理道具数组
  2936. foreach ($props as $prop) {
  2937. $product = $prop;
  2938. // 将prop字段重命名为product_name
  2939. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2940. $product['product_name'] = $product['prop'];
  2941. unset($product['prop']);
  2942. $product['product'] = 3; // 标记类型为道具
  2943. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2944. }
  2945. }
  2946. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2947. foreach ($extra_products as $extra_product) {
  2948. $product_name = getProp($extra_product, 'product_name');
  2949. if ($product_name) {
  2950. $products[$product_name] = $extra_product; // 覆盖同名数据
  2951. }
  2952. }
  2953. // 重新索引数组(去除key)
  2954. $products = array_values($products);
  2955. }
  2956. }
  2957. // 获取执行中的任务
  2958. $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) {
  2959. $value = (array)$value;
  2960. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2961. else $value['ref_image_url'] = [];
  2962. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2963. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2964. if (!empty($value['prompt'])) {
  2965. $prompt = $value['prompt'];
  2966. // 查找第一个【镜头】的位置
  2967. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2968. // 从【镜头】开始截取
  2969. $prompt = substr($prompt, $matches[0][1]);
  2970. }
  2971. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2972. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2973. $value['prompt'] = $prompt;
  2974. }
  2975. return $value;
  2976. })->toArray();
  2977. return compact('chat', 'url', 'products', 'tasks');
  2978. }
  2979. public function applyAudioData($data) {
  2980. $segment_id = getProp($data, 'segment_id');
  2981. $global_data = getProp($data, 'global_data');
  2982. $segment_data = getProp($data, 'segment_data');
  2983. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2984. $global_data = is_array($global_data) ? $global_data : [];
  2985. $segment_data = is_array($segment_data) ? $segment_data : [];
  2986. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2987. $dialogue_item = null;
  2988. foreach ($global_data as $key => $item) {
  2989. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2990. $dialogue_item = $item;
  2991. unset($global_data[$key]);
  2992. break;
  2993. }
  2994. }
  2995. if ($dialogue_item) {
  2996. $segment_data[] = $dialogue_item;
  2997. }
  2998. // 特殊参数: audio_url,audio_duration,subtitle_info
  2999. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3000. // 如果不是全部存在,则仍需创建音频任务
  3001. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3002. $special_update_data = [];
  3003. $has_all_special_params = false;
  3004. // 从segment_data中提取特殊参数
  3005. $filtered_segment_data = [];
  3006. foreach ($segment_data as $item) {
  3007. $field_name = trim((string)getProp($item, 'name'));
  3008. if (in_array($field_name, $special_fields)) {
  3009. $special_update_data[$field_name] = getProp($item, 'value');
  3010. } else {
  3011. // 非特殊参数保留,继续后续处理
  3012. $filtered_segment_data[] = $item;
  3013. }
  3014. }
  3015. // 检查是否三个特殊参数都存在
  3016. if (count($special_update_data) === 3 &&
  3017. isset($special_update_data['audio_url']) &&
  3018. isset($special_update_data['audio_duration']) &&
  3019. isset($special_update_data['subtitle_info'])) {
  3020. $has_all_special_params = true;
  3021. // 立即更新到当前分镜
  3022. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3023. DB::table('mp_episode_segments')
  3024. ->where('segment_id', $segment_id)
  3025. ->update($special_update_data);
  3026. }
  3027. // 使用过滤后的segment_data继续处理其他参数
  3028. $segment_data = $filtered_segment_data;
  3029. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3030. $global_update_data = [];
  3031. $segment_update_data = [];
  3032. $global_voice_type = '';
  3033. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3034. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3035. $episode_id = getProp($target_segment, 'episode_id');
  3036. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3037. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3038. if (!$episode) Utils::throwError('20003:分集不存在');
  3039. foreach ($global_data as $item) {
  3040. $field_name = trim((string)getProp($item, 'name'));
  3041. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3042. continue;
  3043. }
  3044. $global_update_data[$field_name] = getProp($item, 'value');
  3045. if ($field_name === 'voice_type') {
  3046. $global_voice_type = trim((string)getProp($item, 'value'));
  3047. }
  3048. }
  3049. foreach ($segment_data as $item) {
  3050. $field_name = trim((string)getProp($item, 'name'));
  3051. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3052. continue;
  3053. }
  3054. $segment_update_data[$field_name] = getProp($item, 'value');
  3055. }
  3056. if ($global_voice_type) {
  3057. $timbre_info = DB::table('mp_timbres')
  3058. ->where('timbre_type', $global_voice_type)
  3059. ->select('audio_url', 'timbre_name')
  3060. ->first();
  3061. if ($timbre_info) {
  3062. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3063. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3064. }
  3065. }
  3066. try {
  3067. DB::beginTransaction();
  3068. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3069. $segment_ids_to_create_task = [];
  3070. $segments_data = [];
  3071. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3072. if (!empty($global_update_data)) {
  3073. // 如果角色不存在,则只更新当前分镜
  3074. if (!$target_voice_actor) {
  3075. // 只处理当前分镜
  3076. $affected_segments = DB::table('mp_episode_segments')
  3077. ->where('segment_id', $segment_id)
  3078. ->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')
  3079. ->get();
  3080. } else {
  3081. // 获取该角色的所有分镜
  3082. $affected_segments = DB::table('mp_episode_segments')
  3083. ->where('episode_id', $episode_id)
  3084. ->where('voice_actor', $target_voice_actor)
  3085. ->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')
  3086. ->get();
  3087. }
  3088. foreach ($affected_segments as $seg) {
  3089. $seg = (array)$seg;
  3090. $sid = getProp($seg, 'segment_id');
  3091. // 检查参数是否发生变化
  3092. $has_changed = false;
  3093. foreach ($global_update_data as $field => $new_value) {
  3094. $old_value = getProp($seg, $field);
  3095. if ($old_value != $new_value) {
  3096. $has_changed = true;
  3097. break;
  3098. }
  3099. }
  3100. if ($has_changed) {
  3101. $segment_ids_to_create_task[] = $sid;
  3102. $segments_data[$sid] = $seg;
  3103. }
  3104. }
  3105. // 只有在有变化的分镜时才更新
  3106. if (!empty($segment_ids_to_create_task)) {
  3107. $global_segment_update_data = $global_update_data;
  3108. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3109. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3110. DB::table('mp_episode_segments')
  3111. ->where('episode_id', $episode_id)
  3112. ->where('voice_actor', $target_voice_actor)
  3113. ->whereIn('segment_id', $segment_ids_to_create_task)
  3114. ->update($global_segment_update_data);
  3115. }
  3116. if ($global_voice_type) {
  3117. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3118. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3119. $roles_updated = false;
  3120. foreach ($episode_roles as &$role) {
  3121. // 通过 role 字段匹配角色名,而不是 voice_name
  3122. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3123. continue;
  3124. }
  3125. $role['voice_type'] = $global_voice_type;
  3126. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3127. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3128. $roles_updated = true;
  3129. }
  3130. unset($role);
  3131. if ($roles_updated) {
  3132. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3133. 'roles' => json_encode($episode_roles, 256),
  3134. 'updated_at' => date('Y-m-d H:i:s'),
  3135. ]);
  3136. }
  3137. }
  3138. }
  3139. // 如果有单个分镜更新,检查是否有变化
  3140. if (!empty($segment_update_data)) {
  3141. // 获取当前分镜数据
  3142. $current_segment = DB::table('mp_episode_segments')
  3143. ->where('segment_id', $segment_id)
  3144. ->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')
  3145. ->first();
  3146. if ($current_segment) {
  3147. $current_segment = (array)$current_segment;
  3148. // 检查参数是否发生变化
  3149. $has_changed = false;
  3150. foreach ($segment_update_data as $field => $new_value) {
  3151. $old_value = getProp($current_segment, $field);
  3152. if ($old_value != $new_value) {
  3153. $has_changed = true;
  3154. break;
  3155. }
  3156. }
  3157. if ($has_changed) {
  3158. // 如果该分镜还未在列表中,添加进去
  3159. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3160. $segment_ids_to_create_task[] = $segment_id;
  3161. $segments_data[$segment_id] = $current_segment;
  3162. }
  3163. // 更新分镜数据并清空音频URL
  3164. $segment_update_data['audio_url'] = '';
  3165. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3166. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3167. }
  3168. }
  3169. }
  3170. // 为所有有变化的分镜创建音频合成任务
  3171. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3172. if (!empty($segment_ids_to_create_task)) {
  3173. foreach ($segment_ids_to_create_task as $sid) {
  3174. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3175. if ($sid === $segment_id && $has_all_special_params) {
  3176. continue;
  3177. }
  3178. // 重新获取更新后的分镜数据
  3179. $updated_segment = DB::table('mp_episode_segments')
  3180. ->where('segment_id', $sid)
  3181. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3182. ->first();
  3183. if (!$updated_segment) continue;
  3184. $updated_segment = (array)$updated_segment;
  3185. // 检查dialogue是否为空
  3186. $dialogue = getProp($updated_segment, 'dialogue');
  3187. if (empty($dialogue)) {
  3188. // dialogue为空时,直接写入默认音频信息
  3189. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3190. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3191. 'audio_duration' => 2.0,
  3192. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3193. 'updated_at' => date('Y-m-d H:i:s')
  3194. ]);
  3195. continue;
  3196. }
  3197. $generate_json = [
  3198. 'text' => $dialogue,
  3199. 'role' => getProp($updated_segment, 'voice_actor'),
  3200. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3201. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3202. 'emotion' => getProp($updated_segment, 'emotion'),
  3203. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3204. 'gender' => getProp($updated_segment, 'gender'),
  3205. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3206. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3207. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3208. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3209. ];
  3210. // 插入视频配音合成任务
  3211. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3212. 'alias_segment_id' => $sid,
  3213. 'generate_status' => '执行中',
  3214. 'audio_url' => '',
  3215. 'generate_json' => json_encode($generate_json, 256),
  3216. 'created_at' => date('Y-m-d H:i:s'),
  3217. 'updated_at' => date('Y-m-d H:i:s'),
  3218. ]);
  3219. if (!$dubTaskId) {
  3220. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3221. continue;
  3222. }
  3223. // 将任务ID添加到Redis列表中
  3224. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3225. // 请求远程服务器执行生成
  3226. try {
  3227. sleep(1);
  3228. $client = new Client(['timeout' => 300, 'verify' => false]);
  3229. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3230. $response = $result->getBody()->getContents();
  3231. $response_arr = json_decode($response, true);
  3232. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3233. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3234. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3235. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3236. }
  3237. } catch (\Exception $e) {
  3238. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3239. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3240. }
  3241. }
  3242. }
  3243. DB::commit();
  3244. } catch (\Exception $e) {
  3245. DB::rollBack();
  3246. Utils::throwError('20003:'.$e->getMessage());
  3247. }
  3248. return true;
  3249. }
  3250. public function episodePicsInfo($data) {
  3251. $anime_id = getProp($data, 'anime_id');
  3252. $episode_id = getProp($data, 'episode_id');
  3253. // 参数验证
  3254. if (!$anime_id && !$episode_id) {
  3255. Utils::throwError('20003:请提供动漫ID或分集ID');
  3256. }
  3257. // 根据参数获取数据源
  3258. if ($episode_id) {
  3259. // 从剧集表获取
  3260. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3261. if (!$source) Utils::throwError('20003:该剧集不存在');
  3262. $table_name = 'mp_anime_episodes';
  3263. $id_field = 'id';
  3264. $id_value = $episode_id;
  3265. // 获取剧集的anime_id用于继承全局数据
  3266. $anime_id = getProp($source, 'anime_id');
  3267. } else {
  3268. // 从动漫表获取
  3269. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3270. if (!$source) Utils::throwError('20003:该动漫不存在');
  3271. $table_name = 'mp_animes';
  3272. $id_field = 'id';
  3273. $id_value = $anime_id;
  3274. }
  3275. $source = (array)$source;
  3276. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3277. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3278. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3279. // 如果是分集数据,需要处理继承和任务创建逻辑
  3280. if ($episode_id) {
  3281. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3282. }
  3283. // 返回生成器函数,用于 SSE 流式输出
  3284. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3285. $startTime = time();
  3286. $maxDuration = 600; // 10分钟超时
  3287. $checkInterval = 3; // 每3秒检查一次
  3288. // Redis 缓存键
  3289. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3290. // 生成当前数据的哈希值用于比较
  3291. $generateHash = function($roles, $scenes, $props) {
  3292. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3293. };
  3294. // 发送初始数据
  3295. $currentHash = $generateHash($roles, $scenes, $props);
  3296. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3297. echo "data: " . json_encode([
  3298. 'type' => 'init',
  3299. 'data' => [
  3300. 'roles' => $roles,
  3301. 'scenes' => $scenes,
  3302. 'props' => $props,
  3303. 'start_time' => $startTime
  3304. ]
  3305. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3306. if (ob_get_level() > 0) {
  3307. ob_flush();
  3308. }
  3309. flush();
  3310. // 持续轮询任务状态
  3311. while (time() - $startTime < $maxDuration) {
  3312. $hasProcessing = false;
  3313. $updated = false;
  3314. // 检查角色任务状态
  3315. foreach ($roles as $index => &$role) {
  3316. $task_id = getProp($role, 'task_id');
  3317. $task_status = getProp($role, 'task_status');
  3318. $existing_url = getProp($role, 'url');
  3319. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3320. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3321. $hasProcessing = ($task_status === 'processing');
  3322. // 查询任务状态
  3323. $task = DB::table('mp_generate_pic_tasks')
  3324. ->where('id', $task_id)
  3325. ->select('id', 'status', 'result_url', 'error_message')
  3326. ->first();
  3327. if ($task) {
  3328. $task = (array)$task;
  3329. $status = getProp($task, 'status');
  3330. // 如果任务完成或失败
  3331. if (in_array($status, ['success', 'failed'])) {
  3332. $role['task_status'] = $status;
  3333. if ($status === 'success') {
  3334. $result_url = getProp($task, 'result_url');
  3335. if ($result_url) {
  3336. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3337. if (is_array($result_urls) && !empty($result_urls[0])) {
  3338. $role['url'] = $result_urls[0];
  3339. }
  3340. }
  3341. }
  3342. $updated = true;
  3343. } else if ($status === 'processing') {
  3344. $hasProcessing = true;
  3345. }
  3346. }
  3347. }
  3348. }
  3349. // 检查场景任务状态
  3350. foreach ($scenes as $index => &$scene) {
  3351. $task_id = getProp($scene, 'task_id');
  3352. $task_status = getProp($scene, 'task_status');
  3353. $existing_url = getProp($scene, 'url');
  3354. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3355. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3356. $hasProcessing = ($task_status === 'processing');
  3357. // 查询任务状态
  3358. $task = DB::table('mp_generate_pic_tasks')
  3359. ->where('id', $task_id)
  3360. ->select('id', 'status', 'result_url', 'error_message')
  3361. ->first();
  3362. if ($task) {
  3363. $task = (array)$task;
  3364. $status = getProp($task, 'status');
  3365. // 如果任务完成或失败
  3366. if (in_array($status, ['success', 'failed'])) {
  3367. $scene['task_status'] = $status;
  3368. if ($status === 'success') {
  3369. $result_url = getProp($task, 'result_url');
  3370. if ($result_url) {
  3371. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3372. if (is_array($result_urls) && !empty($result_urls[0])) {
  3373. $scene['url'] = $result_urls[0];
  3374. }
  3375. }
  3376. }
  3377. $updated = true;
  3378. } else if ($status === 'processing') {
  3379. $hasProcessing = true;
  3380. }
  3381. }
  3382. }
  3383. }
  3384. // 检查道具任务状态
  3385. foreach ($props as $index => &$prop) {
  3386. $task_id = getProp($prop, 'task_id');
  3387. $task_status = getProp($prop, 'task_status');
  3388. $existing_url = getProp($prop, 'url');
  3389. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3390. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3391. $hasProcessing = ($task_status === 'processing');
  3392. // 查询任务状态
  3393. $task = DB::table('mp_generate_pic_tasks')
  3394. ->where('id', $task_id)
  3395. ->select('id', 'status', 'result_url', 'error_message')
  3396. ->first();
  3397. if ($task) {
  3398. $task = (array)$task;
  3399. $status = getProp($task, 'status');
  3400. // 如果任务完成或失败
  3401. if (in_array($status, ['success', 'failed'])) {
  3402. $prop['task_status'] = $status;
  3403. if ($status === 'success') {
  3404. $result_url = getProp($task, 'result_url');
  3405. if ($result_url) {
  3406. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3407. if (is_array($result_urls) && !empty($result_urls[0])) {
  3408. $prop['url'] = $result_urls[0];
  3409. }
  3410. }
  3411. }
  3412. $updated = true;
  3413. } else if ($status === 'processing') {
  3414. $hasProcessing = true;
  3415. }
  3416. }
  3417. }
  3418. }
  3419. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3420. if ($updated) {
  3421. $newHash = $generateHash($roles, $scenes, $props);
  3422. $cachedHash = Redis::get($cacheKey);
  3423. // 只有当数据真正变化时才更新数据库和发送事件
  3424. if ($newHash !== $cachedHash) {
  3425. try {
  3426. // 更新数据库
  3427. DB::table($table_name)->where($id_field, $id_value)->update([
  3428. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3429. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3430. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3431. 'updated_at' => date('Y-m-d H:i:s')
  3432. ]);
  3433. // 更新缓存
  3434. Redis::setex($cacheKey, 600, $newHash);
  3435. // 发送更新事件
  3436. echo "data: " . json_encode([
  3437. 'type' => 'update',
  3438. 'data' => [
  3439. 'roles' => $roles,
  3440. 'scenes' => $scenes,
  3441. 'props' => $props,
  3442. 'elapsed_time' => time() - $startTime
  3443. ]
  3444. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3445. if (ob_get_level() > 0) {
  3446. ob_flush();
  3447. }
  3448. flush();
  3449. } catch (\Exception $e) {
  3450. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3451. }
  3452. } else {
  3453. // 即使哈希相同,如果有URL更新也要发送事件
  3454. $hasUrlUpdate = false;
  3455. foreach ($roles as $role) {
  3456. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3457. $hasUrlUpdate = true;
  3458. break;
  3459. }
  3460. }
  3461. if (!$hasUrlUpdate) {
  3462. foreach ($scenes as $scene) {
  3463. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3464. $hasUrlUpdate = true;
  3465. break;
  3466. }
  3467. }
  3468. }
  3469. if (!$hasUrlUpdate) {
  3470. foreach ($props as $prop) {
  3471. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3472. $hasUrlUpdate = true;
  3473. break;
  3474. }
  3475. }
  3476. }
  3477. if ($hasUrlUpdate) {
  3478. // 强制更新数据库和发送事件
  3479. try {
  3480. DB::table($table_name)->where($id_field, $id_value)->update([
  3481. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3482. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3483. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3484. 'updated_at' => date('Y-m-d H:i:s')
  3485. ]);
  3486. // 更新缓存
  3487. Redis::setex($cacheKey, 600, $newHash);
  3488. // 发送更新事件
  3489. echo "data: " . json_encode([
  3490. 'type' => 'update',
  3491. 'data' => [
  3492. 'roles' => $roles,
  3493. 'scenes' => $scenes,
  3494. 'props' => $props,
  3495. 'elapsed_time' => time() - $startTime
  3496. ]
  3497. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3498. if (ob_get_level() > 0) {
  3499. ob_flush();
  3500. }
  3501. flush();
  3502. } catch (\Exception $e) {
  3503. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3504. }
  3505. }
  3506. }
  3507. }
  3508. // 如果所有任务都已完成,发送完成事件并退出
  3509. if (!$hasProcessing) {
  3510. // 查询数据库中的最终数据,确保返回最新的完整数据
  3511. try {
  3512. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3513. if ($finalSource) {
  3514. $finalSource = (array)$finalSource;
  3515. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3516. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3517. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3518. // 使用数据库中的最终数据
  3519. $roles = $finalRoles;
  3520. $scenes = $finalScenes;
  3521. $props = $finalProps;
  3522. }
  3523. } catch (\Exception $e) {
  3524. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3525. // 如果查询失败,继续使用内存中的数据
  3526. }
  3527. // 清理缓存
  3528. Redis::del($cacheKey);
  3529. echo "data: " . json_encode([
  3530. 'type' => 'completed',
  3531. 'data' => [
  3532. 'roles' => $roles,
  3533. 'scenes' => $scenes,
  3534. 'props' => $props,
  3535. 'total_time' => time() - $startTime
  3536. ]
  3537. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3538. if (ob_get_level() > 0) {
  3539. ob_flush();
  3540. }
  3541. flush();
  3542. break;
  3543. }
  3544. // 等待下次检查
  3545. sleep($checkInterval);
  3546. }
  3547. // 超时处理
  3548. if (time() - $startTime >= $maxDuration) {
  3549. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3550. try {
  3551. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3552. if ($finalSource) {
  3553. $finalSource = (array)$finalSource;
  3554. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3555. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3556. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3557. // 使用数据库中的最终数据
  3558. $roles = $finalRoles;
  3559. $scenes = $finalScenes;
  3560. $props = $finalProps;
  3561. }
  3562. } catch (\Exception $e) {
  3563. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3564. // 如果查询失败,继续使用内存中的数据
  3565. }
  3566. // 清理缓存
  3567. Redis::del($cacheKey);
  3568. echo "data: " . json_encode([
  3569. 'type' => 'timeout',
  3570. 'message' => '轮询超时,请刷新页面查看最新状态',
  3571. 'data' => [
  3572. 'roles' => $roles,
  3573. 'scenes' => $scenes,
  3574. 'props' => $props
  3575. ]
  3576. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3577. if (ob_get_level() > 0) {
  3578. ob_flush();
  3579. }
  3580. flush();
  3581. }
  3582. };
  3583. }
  3584. public function clipSegmentVideo($data) {
  3585. $segment_id = getProp($data, 'segment_id');
  3586. $video_time_point_start = getProp($data, 'video_time_point_start');
  3587. $video_time_point_end = getProp($data, 'video_time_point_end');
  3588. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3589. Utils::throwError('20003:参数异常');
  3590. }
  3591. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3592. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3593. }
  3594. $video_duration = $video_time_point_end - $video_time_point_start;
  3595. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3596. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3597. 'video_duration' => $video_duration,
  3598. 'video_time_point_start' => $video_time_point_start,
  3599. 'video_time_point_end' => $video_time_point_end,
  3600. 'updated_at' => date('Y-m-d H:i:s')
  3601. ]);
  3602. }
  3603. // 轮训获取图片任务结果
  3604. private function loopGetPicTaskResult($task_id) {
  3605. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3606. if (!$task) {
  3607. return '';
  3608. }
  3609. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3610. $model = getProp($task, 'model');
  3611. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3612. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3613. $isSyncModel = $isVolcModel || $isGptModel;
  3614. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3615. $start_count = 0;
  3616. $img_url = '';
  3617. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3618. sleep(3);
  3619. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3620. // 如果任务已经完成,直接返回结果
  3621. if ($task->status === 'success' && $task->result_url) {
  3622. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3623. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3624. }
  3625. // 如果任务已失败,返回空
  3626. if ($task->status === 'failed') {
  3627. return '';
  3628. }
  3629. if ($isSyncModel) continue;
  3630. // 查询任务状态
  3631. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3632. if ($statusInfo['status'] === 'success') {
  3633. $task->updateStatus('success', [
  3634. 'result_url' => $statusInfo['result_url'],
  3635. 'result_json' => $statusInfo['result_json'] ?? []
  3636. ]);
  3637. // 同步调整分镜图片状态和结果
  3638. if (getProp($task, 'alias_segment_id')) {
  3639. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3640. 'img_url' => $statusInfo['result_url'][0],
  3641. 'pic_task_status' => '已完成',
  3642. ]);
  3643. }
  3644. $img_url = $statusInfo['result_url'][0];
  3645. break;
  3646. } elseif ($statusInfo['status'] === 'failed') {
  3647. $task->updateStatus('failed', [
  3648. 'error_message' => $statusInfo['error_message'],
  3649. 'result_json' => $statusInfo['result_json'] ?? []
  3650. ]);
  3651. if (getProp($task, 'alias_segment_id')) {
  3652. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3653. 'pic_task_status' => '失败',
  3654. ]);
  3655. }
  3656. break;
  3657. }
  3658. $start_count++;
  3659. }
  3660. return $img_url;
  3661. }
  3662. /**
  3663. * 从分镜内容中提取涉及的角色
  3664. */
  3665. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3666. $found_characters = [];
  3667. foreach ($available_characters as $character) {
  3668. // 检查角色名称是否在分镜内容中出现
  3669. if (strpos($segment_content, $character) !== false) {
  3670. $found_characters[] = $character;
  3671. }
  3672. }
  3673. if (!$found_characters) {
  3674. foreach ($roles as $character) {
  3675. // 检查角色名称是否在分镜内容中出现
  3676. if (strpos($segment_content, $character) !== false) {
  3677. $found_characters[] = $character;
  3678. }
  3679. }
  3680. }
  3681. return array_unique($found_characters);
  3682. }
  3683. // 从分镜剧本中提取关键字段
  3684. private function handleSegmentContent(&$data) {
  3685. $segmentContent = getProp($data, 'segment_content');
  3686. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3687. $segmentData = [
  3688. 'description' => '',
  3689. 'composition' => '',
  3690. 'camera_movement' => '',
  3691. 'voice_actor' => '',
  3692. 'dialogue' => '',
  3693. 'frame_type' => '',
  3694. 'scene' => '', // 场景
  3695. 'characters' => '', // 出镜角色
  3696. 'tail_frame' => '', // 尾帧描述
  3697. 'emotion' => '中性', // 情感
  3698. 'gender' => '0', // 性别(0未知,1男,2女)
  3699. 'speed_ratio' => 0, // 语速
  3700. 'loudness_ratio' => 0, // 音量
  3701. 'emotion_scale' => 4, // 情感强度
  3702. 'pitch' => 0, // 音调
  3703. ];
  3704. // 用于存储需要从 segment_content 中移除的匹配项
  3705. $replaceEmptyArr = [];
  3706. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3707. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3708. $segmentData['description'] = trim($descMatch[1]);
  3709. $data['description'] = trim($descMatch[1]);
  3710. }
  3711. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3712. $segmentData['composition'] = trim($compMatch[1]);
  3713. $data['composition'] = trim($compMatch[1]);
  3714. }
  3715. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3716. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3717. $data['camera_movement'] = trim($cameraMatch[1]);
  3718. }
  3719. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3720. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3721. $data['voice_actor'] = trim($voiceMatch[1]);
  3722. }
  3723. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3724. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3725. $data['dialogue'] = trim($dialogueMatch[1]);
  3726. }
  3727. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3728. $segmentData['frame_type'] = trim($frameMatch[1]);
  3729. $data['frame_type'] = trim($frameMatch[1]);
  3730. }
  3731. // 场景字段
  3732. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3733. $segmentData['scene'] = trim($sceneMatch[1]);
  3734. $data['scene'] = trim($sceneMatch[1]);
  3735. }
  3736. // 出镜角色字段
  3737. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3738. $segmentData['characters'] = trim($charactersMatch[1]);
  3739. $data['characters'] = trim($charactersMatch[1]);
  3740. }
  3741. // 尾帧描述字段
  3742. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3743. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3744. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3745. }
  3746. // 情感字段
  3747. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3748. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3749. $segmentData['emotion'] = trim($emotionMatch[1]);
  3750. $data['emotion'] = trim($emotionMatch[1]);
  3751. }
  3752. // 性别字段
  3753. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3754. $replaceEmptyArr[] = trim($genderMatch[0]);
  3755. $genderStr = trim($genderMatch[1]);
  3756. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3757. $segmentData['gender'] = '1';
  3758. $data['gender'] = '1';
  3759. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3760. $segmentData['gender'] = '2';
  3761. $data['gender'] = '2';
  3762. } else {
  3763. $segmentData['gender'] = '0';
  3764. $data['gender'] = '0';
  3765. }
  3766. }
  3767. // 语速字段
  3768. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3769. $replaceEmptyArr[] = trim($speedMatch[0]);
  3770. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3771. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3772. }
  3773. // 音量字段
  3774. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3775. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3776. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3777. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3778. }
  3779. // 情感强度字段
  3780. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3781. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3782. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3783. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3784. }
  3785. // 音调字段
  3786. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3787. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3788. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3789. $data['pitch'] = (int)trim($pitchMatch[1]);
  3790. }
  3791. // 从 segment_content 中移除已提取的配音参数字段
  3792. if (!empty($replaceEmptyArr)) {
  3793. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3794. }
  3795. // 如果有配音角色,查询音色信息并验证情感
  3796. $voice_actor = $segmentData['voice_actor'];
  3797. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3798. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3799. $anime_id = getProp($data, 'anime_id');
  3800. $episode_id = getProp($data, 'episode_id');
  3801. // 优先从剧集的角色列表中查找
  3802. $roles = [];
  3803. if ($episode_id) {
  3804. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3805. if ($episode && getProp($episode, 'roles')) {
  3806. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3807. }
  3808. }
  3809. // 如果剧集中没有,从动漫的角色列表中查找
  3810. if (empty($roles) && $anime_id) {
  3811. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3812. if ($anime && getProp($anime, 'roles')) {
  3813. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3814. }
  3815. }
  3816. // 查找匹配的角色音色信息
  3817. $timbre_info = null;
  3818. foreach ($roles as $role) {
  3819. if (getProp($role, 'role') === $voice_actor) {
  3820. $timbre_info = $role;
  3821. break;
  3822. }
  3823. }
  3824. // 如果找到音色信息,添加到数据中
  3825. if ($timbre_info) {
  3826. $voice_type = getProp($timbre_info, 'voice_type');
  3827. $voice_name = getProp($timbre_info, 'voice_name');
  3828. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3829. if ($voice_type) {
  3830. $data['voice_type'] = $voice_type;
  3831. $segmentData['voice_type'] = $voice_type;
  3832. }
  3833. if ($voice_name) {
  3834. $data['voice_name'] = $voice_name;
  3835. $segmentData['voice_name'] = $voice_name;
  3836. }
  3837. if ($voice_audio_url) {
  3838. $data['voice_audio_url'] = $voice_audio_url;
  3839. $segmentData['voice_audio_url'] = $voice_audio_url;
  3840. }
  3841. // 验证情感是否在音色支持的情感列表中
  3842. if ($voice_type) {
  3843. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3844. if ($timbre_emotion) {
  3845. $timbre_emotion = explode(',', $timbre_emotion);
  3846. } else {
  3847. $timbre_emotion = [];
  3848. }
  3849. $emotion = getProp($segmentData, 'emotion', '中性');
  3850. if (!in_array($emotion, $timbre_emotion)) {
  3851. $emotion = '中性';
  3852. }
  3853. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3854. $emotion_list = array_flip($emotion_list);
  3855. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3856. $data['emotion_type'] = $emotion_type;
  3857. $segmentData['emotion_type'] = $emotion_type;
  3858. }
  3859. }
  3860. }
  3861. return $segmentData;
  3862. }
  3863. public function createSegmentVideoTask($data) {
  3864. $segment_id = getProp($data, 'segment_id');
  3865. $tail_frame = getProp($data, 'tail_frame');
  3866. $first_frame_url = getProp($data, 'first_frame_url');
  3867. $tail_frame_url = getProp($data, 'tail_frame_url');
  3868. $generate_audio = getProp($data, 'generate_audio', 0);
  3869. if (!$segment_id) {
  3870. Utils::throwError('1002:分镜ID不能为空');
  3871. }
  3872. // 获取分镜信息
  3873. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3874. if (!$segment) {
  3875. Utils::throwError('20003:分镜不存在');
  3876. }
  3877. $segment = (array)$segment;
  3878. $episode_id = getProp($segment, 'episode_id');
  3879. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3880. if (!$ratio) $ratio = '9:16';
  3881. // 获取分镜内容
  3882. $segmentContent = getProp($segment, 'segment_content', '');
  3883. // 检查 $segmentContent 中是否已有尾帧描述
  3884. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3885. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3886. $finalTailFrame = '';
  3887. if ($tail_frame) {
  3888. // 用户输入了尾帧描述,优先使用
  3889. $finalTailFrame = $tail_frame;
  3890. // 如果 segmentContent 中已有尾帧描述,需要替换
  3891. if ($contentHasTailFrame) {
  3892. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3893. }
  3894. } elseif ($contentHasTailFrame) {
  3895. // segmentContent 中有尾帧描述,使用它
  3896. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3897. } else {
  3898. // 两者都没有,使用分镜表中的尾帧描述
  3899. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3900. }
  3901. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3902. $hasDialogue = false;
  3903. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3904. $dialogue = trim($dialogueMatch[1]);
  3905. // 如果台词不为空且不是"无"
  3906. if (!empty($dialogue) && $dialogue !== '无') {
  3907. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3908. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3909. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3910. $hasDialogue = true;
  3911. }
  3912. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3913. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3914. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3915. if (!preg_match('/^[“]/', $dialogue)) {
  3916. $dialogue = '“' . $dialogue;
  3917. }
  3918. if (!preg_match('/[”]$/', $dialogue)) {
  3919. $dialogue .= '”';
  3920. }
  3921. // 将修改后的台词替换回 $segmentContent
  3922. $originalDialogue = $dialogueMatch[1];
  3923. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3924. }
  3925. }
  3926. // 构建完整的提示词
  3927. $fullPrompt = $segmentContent;
  3928. if ($finalTailFrame && !$contentHasTailFrame) {
  3929. // 只有当 segmentContent 中没有尾帧描述时才追加
  3930. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3931. }
  3932. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3933. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3934. $fullPrompt = trim($fullPrompt);
  3935. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3936. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3937. // 智能选择视频时长
  3938. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3939. $videoDuration = -1;
  3940. // 处理视频模型
  3941. $model = getProp($data, 'model');
  3942. if (!$model) {
  3943. // 用户没有输入,从episode表获取
  3944. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3945. $model = getProp($episode, 'video_model');
  3946. if (!$model) {
  3947. // episode表也没有,使用默认值
  3948. $model = 'doubao-seedance-1-5-pro-251215';
  3949. }
  3950. }
  3951. // 验证模型是否在可用模型表中
  3952. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3953. $model = 'doubao-seedance-1-5-pro-251215';
  3954. }
  3955. // 保存到episode表
  3956. $episode_id = getProp($segment, 'episode_id');
  3957. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3958. 'video_model' => $model,
  3959. 'updated_at' => date('Y-m-d H:i:s')
  3960. ]);
  3961. // 构建视频生成参数
  3962. $videoParams = [
  3963. 'model' => $model,
  3964. 'alias_segment_id' => $segment_id,
  3965. 'prompt' => trim($fullPrompt),
  3966. 'video_duration' => $videoDuration,
  3967. 'video_resolution' => '720P',
  3968. 'seed' => -1,
  3969. 'ratio' => $ratio,
  3970. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3971. 'draft' => false,
  3972. 'watermark' => false,
  3973. 'camera_fixed' => false,
  3974. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3975. ];
  3976. // 如果分镜有图片,作为首帧
  3977. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3978. $hasVideo = !empty(getProp($segment, 'video_url'));
  3979. if ($hasImage) {
  3980. if ($first_frame_url) {
  3981. $videoParams['first_frame_url'] = $first_frame_url;
  3982. }else {
  3983. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3984. }
  3985. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3986. }
  3987. // 构建content数组
  3988. $videoParams['content'] = [
  3989. [
  3990. 'type' => 'text',
  3991. 'text' => $videoParams['prompt'],
  3992. ]
  3993. ];
  3994. // 如果有首帧图片,添加到content中
  3995. if ($hasImage) {
  3996. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3997. $videoParams['content'][] = [
  3998. 'type' => 'image_url',
  3999. 'image_url' => [
  4000. 'url' => $videoParams['first_frame_url'],
  4001. ],
  4002. 'role' => 'reference_image',
  4003. ];
  4004. if (isset($videoParams['tail_frame_url'])) {
  4005. $videoParams['content'][] = [
  4006. 'type' => 'image_url',
  4007. 'image_url' => [
  4008. 'url' => $videoParams['tail_frame_url'],
  4009. ],
  4010. 'role' => 'reference_image',
  4011. ];
  4012. }
  4013. }else {
  4014. $videoParams['content'][] = [
  4015. 'type' => 'image_url',
  4016. 'image_url' => [
  4017. 'url' => $videoParams['first_frame_url'],
  4018. ],
  4019. 'role' => 'first_frame',
  4020. ];
  4021. if (isset($videoParams['tail_frame_url'])) {
  4022. $videoParams['content'][] = [
  4023. 'type' => 'image_url',
  4024. 'image_url' => [
  4025. 'url' => $videoParams['tail_frame_url'],
  4026. ],
  4027. 'role' => 'last_frame',
  4028. ];
  4029. }
  4030. }
  4031. }
  4032. // 获取配音音频URL
  4033. $audioUrl = getProp($segment, 'audio_url');
  4034. $audioDuration = getProp($segment, 'audio_duration');
  4035. // 音频传入的前提:必须有至少一张图片或一个视频
  4036. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4037. // 余额预检:按预估时长计算所需积分,不足直接报错
  4038. $chargeDuration = (int)ceil((float)$audioDuration);
  4039. if ($chargeDuration <= 0) {
  4040. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4041. }
  4042. $this->pointsService->checkUserPointsEnough(
  4043. $this->pointsService->getVideoChargePoints([
  4044. 'model' => $model,
  4045. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4046. 'video_duration' => $chargeDuration,
  4047. 'ratio' => $ratio,
  4048. 'generate_audio' => $current_generate_audio,
  4049. ])
  4050. );
  4051. // dd($videoParams);
  4052. // 根据模型选择不同的视频生成方法
  4053. if (strpos($model, 'jimeng') !== false) {
  4054. // 即梦模型参数调整
  4055. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4056. unset($videoParams['content']); // 即梦不使用content格式
  4057. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4058. } elseif (strpos($model, 'kling') !== false) {
  4059. // Keling模型参数调整
  4060. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4061. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4062. unset($videoParams['ratio']);
  4063. unset($videoParams['content']); // Keling不使用content格式
  4064. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4065. } elseif (strpos($model, 'zhizhen') !== false) {
  4066. // 智帧20等新模型使用统一API
  4067. // 构建统一API参数
  4068. $unifiedParams = [
  4069. 'model_code' => $model,
  4070. 'alias_segment_id' => $segment_id,
  4071. 'prompt' => trim($fullPrompt),
  4072. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4073. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4074. 'video_ratio' => $ratio,
  4075. 'seed' => -1,
  4076. ];
  4077. // 构建parameters参数
  4078. $parameters = [
  4079. 'seconds' => $unifiedParams['video_duration'],
  4080. 'resolution' => $unifiedParams['video_resolution'],
  4081. 'ratio' => $ratio,
  4082. // 'video_mode' => 'multi_image',
  4083. // 'mode' => 'multi_image',
  4084. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4085. ];
  4086. $hasImage = false;
  4087. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4088. if ($hasImage) {
  4089. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4090. if (isset($videoParams['tail_frame_url'])) {
  4091. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4092. }
  4093. // 只有在有图片的情况下才能添加参考音频
  4094. if ($audioUrl) {
  4095. // $parameters['reference_audios'] = [$audioUrl];
  4096. }
  4097. } else {
  4098. // 没有图片时,记录错误日志
  4099. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4100. 'segment_id' => $segment_id,
  4101. 'model' => $model
  4102. ]);
  4103. }
  4104. $unifiedParams['parameters'] = $parameters;
  4105. // 调用统一API创建任务
  4106. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4107. } else {
  4108. // Seedance模型(默认)
  4109. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4110. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4111. // 添加配音音频到content中
  4112. $videoParams['content'][] = [
  4113. 'type' => 'audio_url',
  4114. 'audio_url' => [
  4115. 'url' => $audioUrl,
  4116. ],
  4117. 'role' => 'reference_audio',
  4118. ];
  4119. // 优化提示词,增加音频相关描述
  4120. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4121. $videoParams['prompt'] = $audioPrompt;
  4122. $videoParams['content'][0]['text'] = $audioPrompt;
  4123. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4124. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4125. }
  4126. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4127. }
  4128. // 更新分镜表的视频任务信息
  4129. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4130. 'video_task_id' => $task->id,
  4131. 'video_task_status' => '生成中',
  4132. 'generate_audio' => $generate_audio,
  4133. 'updated_at' => date('Y-m-d H:i:s')
  4134. ]);
  4135. return [
  4136. 'task_id' => $task->id,
  4137. 'status' => $task->status,
  4138. 'segment_id' => $segment_id,
  4139. 'video_duration' => $videoDuration
  4140. ];
  4141. }
  4142. public function createActVideoTask($data) {
  4143. $act_id = getProp($data, 'act_id');
  4144. $first_frame_url = getProp($data, 'first_frame_url');
  4145. $tail_frame_url = getProp($data, 'tail_frame_url');
  4146. $generate_audio = getProp($data, 'generate_audio', 1);
  4147. $video_duration = getProp($data, 'video_duration');
  4148. $video_resolution = getProp($data, 'video_resolution');
  4149. $ratio = getProp($data, 'ratio');
  4150. $products = getProp($data, 'products', []);
  4151. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4152. if (!is_array($reference_images) || !is_array($products)) {
  4153. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4154. }
  4155. if (!$act_id) {
  4156. Utils::throwError('1002:片段ID不能为空');
  4157. }
  4158. // 获取片段信息
  4159. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4160. if (!$act) {
  4161. Utils::throwError('20003:片段不存在');
  4162. }
  4163. $act = (array)$act;
  4164. $anime_id = getProp($act, 'anime_id');
  4165. $episode_id = getProp($act, 'episode_id');
  4166. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4167. $ace_mode = getProp($anime, 'ace_mode');
  4168. $art_style_type = getProp($anime, 'art_style_type');
  4169. $art_style = getProp($anime, 'art_style');
  4170. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4171. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4172. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4173. // 将资产中新出现的资产放到extra_products中
  4174. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4175. if (!empty($products) && $episode) {
  4176. // 获取剧集中的角色、场景和道具列表
  4177. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4178. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4179. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4180. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4181. // 构建角色名称列表
  4182. $role_names = array_column($roles, 'role');
  4183. // 构建场景名称列表
  4184. $scene_names = array_column($scenes, 'scene');
  4185. // 构建道具名称列表
  4186. $prop_names = array_column($props, 'prop');
  4187. // 遍历传入的products
  4188. foreach ($products as $product) {
  4189. $product_name = getProp($product, 'product_name');
  4190. // 如果product_name不在roles、scenes和props中
  4191. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4192. // 查找是否在extra_products中存在同名的
  4193. $found = false;
  4194. foreach ($extra_products as $key => $extra_product) {
  4195. if (getProp($extra_product, 'product_name') === $product_name) {
  4196. // 有同名的则覆盖
  4197. $extra_products[$key] = $product;
  4198. $found = true;
  4199. break;
  4200. }
  4201. }
  4202. // 没有则新增
  4203. if (!$found) {
  4204. $extra_products[] = $product;
  4205. }
  4206. }
  4207. }
  4208. if ($extra_products) {
  4209. // 保存到数据库
  4210. DB::table('mp_anime_episodes')
  4211. ->where('id', $episode_id)
  4212. ->update([
  4213. 'extra_products' => json_encode($extra_products, 256),
  4214. 'updated_at' => date('Y-m-d H:i:s')
  4215. ]);
  4216. }
  4217. }
  4218. // 获取分镜内容
  4219. $actContent = getProp($act, 'act_show_content', '');
  4220. // 音效同出(默认使用)
  4221. $current_generate_audio = $generate_audio ? 1 : 0;
  4222. // 构建完整的提示词
  4223. $processResult = $this->processActContentWithProducts($actContent, $products);
  4224. $fullPrompt = $processResult['content'];
  4225. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4226. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4227. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4228. // 处理视频模型
  4229. $model = getProp($data, 'model');
  4230. if (!$model) {
  4231. $model = getProp($episode, 'video_model');
  4232. if (!$model) {
  4233. // episode表也没有,使用默认值
  4234. $model = 'zhizhen-20';
  4235. }
  4236. }
  4237. // 验证模型是否在可用模型表中
  4238. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4239. $model = 'zhizhen-20';
  4240. }
  4241. // 保存到episode表(仅在专用方法中更新模型)
  4242. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4243. // 'video_model' => $model,
  4244. // 'updated_at' => date('Y-m-d H:i:s')
  4245. // ]);
  4246. // 余额预检:按预估时长计算所需积分,不足直接报错
  4247. $chargeDuration = (int)$videoDuration;
  4248. if ($chargeDuration <= 0) {
  4249. $chargeDuration = 5; // 无时长时按默认5秒预估
  4250. }
  4251. $this->pointsService->checkUserPointsEnough(
  4252. $this->pointsService->getVideoChargePoints([
  4253. 'model' => $model,
  4254. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4255. 'video_duration' => $chargeDuration,
  4256. 'ratio' => $ratio,
  4257. 'generate_audio' => $current_generate_audio,
  4258. ])
  4259. );
  4260. // 构建视频生成参数
  4261. $videoParams = [
  4262. 'model' => $model,
  4263. 'alias_act_id' => $act_id,
  4264. 'prompt' => trim($fullPrompt),
  4265. 'video_duration' => $videoDuration,
  4266. 'video_resolution' => $video_resolution,
  4267. 'seed' => -1,
  4268. 'ratio' => $ratio,
  4269. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4270. 'draft' => false,
  4271. 'watermark' => false,
  4272. 'camera_fixed' => false,
  4273. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4274. ];
  4275. // 如果分镜有图片,作为首帧
  4276. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4277. $hasVideo = !empty(getProp($act, 'video_url'));
  4278. if ($hasImage) {
  4279. if ($first_frame_url) {
  4280. $videoParams['first_frame_url'] = $first_frame_url;
  4281. }else {
  4282. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4283. }
  4284. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4285. }
  4286. // 构建content数组
  4287. $videoParams['content'] = [
  4288. [
  4289. 'type' => 'text',
  4290. 'text' => $videoParams['prompt'],
  4291. ]
  4292. ];
  4293. // 如果有首帧图片,添加到content中
  4294. if ($hasImage) {
  4295. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4296. $videoParams['content'][] = [
  4297. 'type' => 'image_url',
  4298. 'image_url' => [
  4299. 'url' => $videoParams['first_frame_url'],
  4300. ],
  4301. 'role' => 'reference_image',
  4302. ];
  4303. if (isset($videoParams['tail_frame_url'])) {
  4304. $videoParams['content'][] = [
  4305. 'type' => 'image_url',
  4306. 'image_url' => [
  4307. 'url' => $videoParams['tail_frame_url'],
  4308. ],
  4309. 'role' => 'reference_image',
  4310. ];
  4311. }
  4312. }else {
  4313. $videoParams['content'][] = [
  4314. 'type' => 'image_url',
  4315. 'image_url' => [
  4316. 'url' => $videoParams['first_frame_url'],
  4317. ],
  4318. 'role' => 'first_frame',
  4319. ];
  4320. if (isset($videoParams['tail_frame_url'])) {
  4321. $videoParams['content'][] = [
  4322. 'type' => 'image_url',
  4323. 'image_url' => [
  4324. 'url' => $videoParams['tail_frame_url'],
  4325. ],
  4326. 'role' => 'last_frame',
  4327. ];
  4328. }
  4329. }
  4330. }
  4331. // dd($videoParams);
  4332. // 根据模型选择不同的视频生成方法
  4333. if (strpos($model, 'jimeng') !== false) {
  4334. // 即梦模型参数调整
  4335. unset($videoParams['content']); // 即梦不使用content格式
  4336. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4337. } elseif (strpos($model, 'kling') !== false) {
  4338. // Keling模型参数调整
  4339. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4340. unset($videoParams['ratio']);
  4341. unset($videoParams['content']); // Keling不使用content格式
  4342. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4343. } elseif (strpos($model, 'zhizhen') !== false) {
  4344. // 智帧20等新模型使用统一API
  4345. // 构建统一API参数
  4346. $unifiedParams = [
  4347. 'model_code' => $model,
  4348. 'alias_act_id' => $act_id,
  4349. 'prompt' => trim($fullPrompt),
  4350. 'video_duration' => $videoDuration,
  4351. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4352. 'video_ratio' => $ratio,
  4353. 'seed' => -1,
  4354. ];
  4355. // 构建parameters参数
  4356. $parameters = [
  4357. 'seconds' => $unifiedParams['video_duration'],
  4358. 'resolution' => $unifiedParams['video_resolution'],
  4359. 'ratio' => $ratio,
  4360. // 'video_mode' => 'multi_image',
  4361. // 'mode' => 'multi_image',
  4362. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4363. ];
  4364. $hasImage = false;
  4365. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4366. if ($hasImage) {
  4367. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4368. if (isset($videoParams['tail_frame_url'])) {
  4369. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4370. }
  4371. } else {
  4372. // 没有图片时,记录错误日志
  4373. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4374. 'act_id' => $act_id,
  4375. 'model' => $model
  4376. ]);
  4377. }
  4378. if ($reference_images) {
  4379. // 限制只传入9张参考图
  4380. $reference_images = array_slice($reference_images, 0, 9);
  4381. // 在处理之前先保存原始reference_images到任务参数中
  4382. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4383. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4384. $parameters['reference_images'] = $reference_images;
  4385. $parameters['video_mode'] = 'multi_image';
  4386. $parameters['mode'] = 'multi_image';
  4387. }
  4388. $unifiedParams['parameters'] = $parameters;
  4389. // 调用统一API创建任务
  4390. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4391. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4392. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4393. // 保存原始参考图用于任务记录
  4394. $videoParams['reference_images'] = $reference_images;
  4395. if ($reference_images) {
  4396. // 限制只传入9张参考图
  4397. $reference_images = array_slice($reference_images, 0, 9);
  4398. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4399. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4400. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4401. $videoParams['prompt'] = trim($fullPrompt);
  4402. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4403. $videoParams['reference_image_assets'] = $reference_image_assets;
  4404. }
  4405. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4406. } else {
  4407. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4408. }
  4409. // 更新分镜表的视频任务信息
  4410. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4411. 'video_task_id' => $task->id,
  4412. 'video_task_status' => '生成中',
  4413. 'generate_audio' => $generate_audio,
  4414. 'updated_at' => date('Y-m-d H:i:s')
  4415. ]);
  4416. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4417. $episode_number = getProp($act, 'episode_number');
  4418. $act_number = getProp($act, 'act_number');
  4419. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4420. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4421. }
  4422. return [
  4423. 'task_id' => $task->id,
  4424. 'status' => $task->status,
  4425. 'act_id' => $act_id,
  4426. 'video_duration' => $videoDuration
  4427. ];
  4428. }
  4429. /**
  4430. * 文生视频通用方法
  4431. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4432. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4433. *
  4434. * @param array $data 请求参数
  4435. * @return array
  4436. */
  4437. public function generateVideo($data) {
  4438. $prompt = getProp($data, 'prompt');
  4439. if (empty($prompt)) {
  4440. Utils::throwError('20003:提示词不能为空');
  4441. }
  4442. $model = getProp($data, 'model');
  4443. if (!$model) {
  4444. $model = 'zhizhen-20';
  4445. }
  4446. // 验证模型是否在可用模型表中
  4447. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4448. Utils::throwError('20003:该模型已不可用,请更换!');
  4449. }
  4450. $video_duration = getProp($data, 'video_duration', 5);
  4451. $video_resolution = getProp($data, 'video_resolution', '480p');
  4452. $ratio = getProp($data, 'ratio', '9:16');
  4453. $generate_audio = getProp($data, 'generate_audio', 1);
  4454. $seed = getProp($data, 'seed', -1);
  4455. $first_frame_url = getProp($data, 'first_frame_url');
  4456. $tail_frame_url = getProp($data, 'tail_frame_url');
  4457. // 参考图(支持数组或JSON字符串,最多9张)
  4458. $reference_images = getProp($data, 'reference_images', []);
  4459. if (is_string($reference_images)) {
  4460. $reference_images = json_decode($reference_images, true) ?: [];
  4461. }
  4462. if (!is_array($reference_images)) {
  4463. Utils::throwError('20003:参考图格式不正确');
  4464. }
  4465. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4466. $reference_images = array_slice($reference_images, 0, 9);
  4467. // 参考视频(支持数组或JSON字符串,最多3个)
  4468. $reference_videos = getProp($data, 'reference_videos', []);
  4469. if (is_string($reference_videos)) {
  4470. $reference_videos = json_decode($reference_videos, true) ?: [];
  4471. }
  4472. if (!is_array($reference_videos)) {
  4473. Utils::throwError('20003:参考视频格式不正确');
  4474. }
  4475. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4476. if (count($reference_videos) > 3) {
  4477. Utils::throwError('20003:参考视频最多选择3个');
  4478. }
  4479. $reference_videos = array_slice($reference_videos, 0, 3);
  4480. // 参考音频(支持数组或JSON字符串,最多3个)
  4481. $reference_audios = getProp($data, 'reference_audios', []);
  4482. if (is_string($reference_audios)) {
  4483. $reference_audios = json_decode($reference_audios, true) ?: [];
  4484. }
  4485. if (!is_array($reference_audios)) {
  4486. Utils::throwError('20003:参考音频格式不正确');
  4487. }
  4488. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4489. if (count($reference_audios) > 3) {
  4490. Utils::throwError('20003:参考音频最多选择3个');
  4491. }
  4492. $reference_audios = array_slice($reference_audios, 0, 3);
  4493. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4494. $videoParams = [
  4495. 'model' => $model,
  4496. 'prompt' => $prompt,
  4497. 'video_duration' => $video_duration,
  4498. 'video_resolution' => $video_resolution,
  4499. 'seed' => $seed,
  4500. 'ratio' => $ratio,
  4501. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4502. 'draft' => getProp($data, 'draft', false),
  4503. 'watermark' => getProp($data, 'watermark', false),
  4504. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4505. ];
  4506. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4507. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4508. // 构建content数组
  4509. $videoParams['content'] = [
  4510. [
  4511. 'type' => 'text',
  4512. 'text' => $prompt,
  4513. ]
  4514. ];
  4515. // 根据模型选择不同的视频生成方法
  4516. if (strpos($model, 'jimeng') !== false) {
  4517. // 即梦模型参数调整
  4518. unset($videoParams['content']); // 即梦不使用content格式
  4519. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4520. } elseif (strpos($model, 'kling') !== false) {
  4521. // 可灵模型参数调整
  4522. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4523. unset($videoParams['ratio']);
  4524. unset($videoParams['content']); // 可灵不使用content格式
  4525. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4526. } elseif (strpos($model, 'zhizhen') !== false) {
  4527. // 智帧等新模型使用统一API
  4528. $unifiedParams = [
  4529. 'model_code' => $model,
  4530. 'prompt' => $prompt,
  4531. 'video_duration' => $video_duration,
  4532. 'video_resolution' => strtolower($video_resolution),
  4533. 'video_ratio' => $ratio,
  4534. 'seed' => $seed,
  4535. ];
  4536. // 构建parameters参数
  4537. $parameters = [
  4538. 'seconds' => $unifiedParams['video_duration'],
  4539. 'resolution' => $unifiedParams['video_resolution'],
  4540. 'ratio' => $ratio,
  4541. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4542. ];
  4543. // 首帧和尾帧
  4544. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4545. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4546. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4547. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4548. if ($refImageUrls) {
  4549. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4550. }
  4551. // 参考图处理
  4552. if ($reference_images) {
  4553. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4554. $parameters['reference_images'] = $reference_images;
  4555. $parameters['video_mode'] = 'multi_image';
  4556. $parameters['mode'] = 'multi_image';
  4557. }
  4558. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4559. if ($reference_videos) {
  4560. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4561. $parameters['reference_videos'] = $reference_videos;
  4562. }
  4563. if ($reference_audios) {
  4564. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4565. $parameters['reference_audios'] = $reference_audios;
  4566. }
  4567. $unifiedParams['parameters'] = $parameters;
  4568. // 调用统一API创建任务
  4569. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4570. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4571. // 豆包Seedance 2.0(百度AI网关):图片/视频/音频需要先上传为素材
  4572. $videoParams['reference_images'] = $reference_images;
  4573. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4574. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4575. if ($refImageUrls) {
  4576. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4577. }
  4578. if ($reference_images) {
  4579. // 参考图上传为百度网关素材
  4580. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4581. $videoParams['reference_image_assets'] = $reference_image_assets;
  4582. }
  4583. // 参考视频上传为百度网关素材
  4584. if ($reference_videos) {
  4585. $reference_video_assets = $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4586. $videoParams['reference_video_assets'] = $reference_video_assets;
  4587. }
  4588. // 参考音频上传为百度网关素材
  4589. if ($reference_audios) {
  4590. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4591. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4592. }
  4593. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4594. if ($reference_images || $reference_videos || $reference_audios) {
  4595. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4596. }
  4597. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4598. } else {
  4599. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4600. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4601. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4602. if ($refImageUrls) {
  4603. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4604. }
  4605. if ($reference_videos) {
  4606. foreach ($reference_videos as $videoUrl) {
  4607. $videoParams['content'][] = [
  4608. 'type' => 'video_url',
  4609. 'video_url' => [
  4610. 'url' => $videoUrl,
  4611. ],
  4612. 'role' => 'reference_video',
  4613. ];
  4614. }
  4615. }
  4616. if ($reference_audios) {
  4617. foreach ($reference_audios as $audioUrl) {
  4618. $videoParams['content'][] = [
  4619. 'type' => 'audio_url',
  4620. 'audio_url' => [
  4621. 'url' => $audioUrl,
  4622. ],
  4623. 'role' => 'reference_audio',
  4624. ];
  4625. }
  4626. }
  4627. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4628. }
  4629. return [
  4630. 'task_id' => $task->id,
  4631. 'status' => $task->status,
  4632. 'model' => $model,
  4633. 'video_duration' => $video_duration,
  4634. 'video_resolution' => $video_resolution,
  4635. 'ratio' => $ratio
  4636. ];
  4637. }
  4638. /**
  4639. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4640. *
  4641. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4642. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4643. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4644. *
  4645. * @param array $data
  4646. * @return array
  4647. */
  4648. public function previewCharge(array $data): array
  4649. {
  4650. $mode = (string)getProp($data, 'mode', '');
  4651. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4652. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4653. }
  4654. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4655. $scene = (string)getProp($data, 'scene', 'video_generation');
  4656. $items = [];
  4657. $model = '';
  4658. $resolution = '';
  4659. if ($mode === 'video') {
  4660. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4661. $model = (string)getProp($data, 'model', '');
  4662. if (!$model) {
  4663. Utils::throwError('1002:model参数不能为空');
  4664. }
  4665. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4666. $duration = (int)getProp($data, 'video_duration', 5);
  4667. if ($duration <= 0) {
  4668. $duration = 5;
  4669. }
  4670. $count = max(1, (int)getProp($data, 'count', 1));
  4671. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4672. 'model' => $model,
  4673. 'video_resolution' => $resolution,
  4674. 'video_duration' => $duration,
  4675. 'mode' => $scene,
  4676. ]);
  4677. $points = $pointsPerVideo * $count;
  4678. $items[] = [
  4679. 'type' => 'video',
  4680. 'model' => $model,
  4681. 'video_resolution' => $resolution,
  4682. 'video_duration' => $duration,
  4683. 'count' => $count,
  4684. 'points' => $points,
  4685. ];
  4686. } elseif ($mode === 'image') {
  4687. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4688. $model = (string)getProp($data, 'model', '');
  4689. if (!$model) {
  4690. Utils::throwError('1002:model参数不能为空');
  4691. }
  4692. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4693. if (!$resolution) {
  4694. $width = (int)getProp($data, 'width', 0);
  4695. $height = (int)getProp($data, 'height', 0);
  4696. if ($width <= 0 || $height <= 0) {
  4697. $width = 1600;
  4698. $height = 2848;
  4699. }
  4700. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4701. }
  4702. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4703. $points = $this->pointsService->getImageChargePoints([
  4704. 'model' => $model,
  4705. 'resolution' => $resolution,
  4706. ]) * $imageNum;
  4707. $items[] = [
  4708. 'type' => 'image',
  4709. 'model' => $model,
  4710. 'resolution' => $resolution,
  4711. 'image_num' => $imageNum,
  4712. 'points' => $points,
  4713. ];
  4714. } else {
  4715. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4716. $count = max(1, (int)getProp($data, 'count', 1));
  4717. $animeId = getProp($data, 'anime_id');
  4718. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4719. if ($animeId && $generateEpisodes > 0) {
  4720. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4721. ->where('anime_id', $animeId)
  4722. ->where('is_default', 1)
  4723. ->max('episode_number');
  4724. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4725. $startEpisodeNumber = $currentMaxEpisode + 1;
  4726. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4727. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4728. ->where('anime_id', $animeId)
  4729. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4730. ->whereIn('status', ['pending', 'processing', 'completed'])
  4731. ->count();
  4732. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4733. if ($count < 0) {
  4734. $count = 0;
  4735. }
  4736. }
  4737. $points = $this->pointsService->getChatChargePoints((string)$model) * $count;
  4738. $items[] = [
  4739. 'type' => 'chat',
  4740. 'count' => $count,
  4741. 'points' => $points,
  4742. ];
  4743. }
  4744. $totalPoints = 0;
  4745. foreach ($items as $item) {
  4746. $totalPoints += $item['points'];
  4747. }
  4748. return [
  4749. 'mode' => $mode,
  4750. 'total_points' => $totalPoints,
  4751. 'items' => $items,
  4752. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4753. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4754. ];
  4755. }
  4756. /**
  4757. * 根据提示词内容智能计算最优视频时长
  4758. *
  4759. * @param string $segmentContent 分镜内容
  4760. * @param string $tailFrame 尾帧描述
  4761. * @return int 视频时长(2-12秒)
  4762. */
  4763. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4764. // 合并所有文本内容
  4765. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4766. // 如果没有内容,返回默认时长
  4767. if (empty($fullText)) {
  4768. return 5;
  4769. }
  4770. // 计算文本长度(中文字符按2个字符计算)
  4771. $textLength = mb_strlen($fullText, 'UTF-8');
  4772. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4773. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4774. // 分析内容复杂度
  4775. $complexityScore = $this->analyzeContentComplexity($fullText);
  4776. // 基础时长计算(根据文本长度)
  4777. $baseDuration = 3; // 默认2秒
  4778. // if ($adjustedLength <= 20) {
  4779. // $baseDuration = 3;
  4780. // } elseif ($adjustedLength <= 40) {
  4781. // $baseDuration = 4;
  4782. // } elseif ($adjustedLength <= 60) {
  4783. // $baseDuration = 5;
  4784. // } elseif ($adjustedLength <= 80) {
  4785. // $baseDuration = 6;
  4786. // } elseif ($adjustedLength <= 100) {
  4787. // $baseDuration = 7;
  4788. // } elseif ($adjustedLength <= 120) {
  4789. // $baseDuration = 8;
  4790. // } else {
  4791. // $baseDuration = 9;
  4792. // }
  4793. // 根据内容复杂度调整时长
  4794. $finalDuration = $baseDuration + $complexityScore;
  4795. // 确保时长在2-12秒范围内
  4796. return max(4, min(12, $finalDuration));
  4797. }
  4798. /**
  4799. * 分析内容复杂度,返回时长调整值
  4800. *
  4801. * @param string $text 文本内容
  4802. * @return int 调整值(-2到+3)
  4803. */
  4804. private function analyzeContentComplexity($text) {
  4805. $score = 0;
  4806. // 动作关键词(需要更长时间展现)
  4807. $actionKeywords = [
  4808. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4809. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4810. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4811. ];
  4812. // 静态关键词(可以用较短时间)
  4813. $staticKeywords = [
  4814. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4815. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4816. ];
  4817. // 复杂场景关键词(需要更长时间)
  4818. $complexSceneKeywords = [
  4819. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4820. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4821. ];
  4822. // 情感关键词(需要适中时间表现)
  4823. $emotionKeywords = [
  4824. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4825. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4826. ];
  4827. // 检查动作关键词
  4828. foreach ($actionKeywords as $keyword) {
  4829. if (strpos($text, $keyword) !== false) {
  4830. $score += 1;
  4831. break; // 避免重复加分
  4832. }
  4833. }
  4834. // 检查静态关键词
  4835. foreach ($staticKeywords as $keyword) {
  4836. if (strpos($text, $keyword) !== false) {
  4837. $score -= 1;
  4838. break;
  4839. }
  4840. }
  4841. // 检查复杂场景关键词
  4842. foreach ($complexSceneKeywords as $keyword) {
  4843. if (strpos($text, $keyword) !== false) {
  4844. $score += 1;
  4845. break;
  4846. }
  4847. }
  4848. // 检查情感关键词
  4849. foreach ($emotionKeywords as $keyword) {
  4850. if (strpos($text, $keyword) !== false) {
  4851. $score += 1;
  4852. break;
  4853. }
  4854. }
  4855. // 检查时间相关词汇
  4856. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4857. $score += 1;
  4858. }
  4859. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4860. $score -= 1;
  4861. }
  4862. // 检查转场词汇
  4863. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4864. $score += 1;
  4865. }
  4866. // 检查环境描述(复杂环境需要更多时间)
  4867. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4868. $score += 1;
  4869. }
  4870. // 检查对话内容(对话需要更多时间)
  4871. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4872. $score += 1;
  4873. }
  4874. // 限制调整范围
  4875. return max(-1, min(4, $score));
  4876. }
  4877. /**
  4878. * 创建完整视频合成任务
  4879. *
  4880. * @param array $data
  4881. * @return array
  4882. */
  4883. public function createCompleteVideoTask($data)
  4884. {
  4885. $animeId = getProp($data, 'anime_id');
  4886. $episodeId = getProp($data, 'episode_id');
  4887. // 验证参数
  4888. if (!$animeId || !$episodeId) {
  4889. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4890. }
  4891. // 检查是否已存在处理中的任务
  4892. $existingTask = DB::table('mp_complete_video_tasks')
  4893. ->where('anime_id', $animeId)
  4894. ->where('episode_id', $episodeId)
  4895. ->whereIn('generate_status', ['执行中'])
  4896. ->first();
  4897. if ($existingTask) {
  4898. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4899. }
  4900. // 获取全能模式状态
  4901. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4902. if ((int)$ace_mode === 1) {
  4903. // 获取所有片段的配音视频,按 act_number 排序
  4904. $segments = DB::table('mp_episode_segments')
  4905. ->where('anime_id', $animeId)
  4906. ->where('episode_id', $episodeId)
  4907. ->orderBy('segment_number')
  4908. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4909. ->get();
  4910. // 检查是否所有片段都有视频
  4911. $missingVideos = $segments->filter(function($segment) {
  4912. return empty($segment->video_url);
  4913. });
  4914. if ($missingVideos->isNotEmpty()) {
  4915. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4916. }
  4917. }else {
  4918. // 获取所有分镜的配音视频,按 segment_number 排序
  4919. $segments = DB::table('mp_episode_segments')
  4920. ->where('anime_id', $animeId)
  4921. ->where('episode_id', $episodeId)
  4922. ->orderBy('segment_number')
  4923. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4924. ->get();
  4925. // 检查是否所有分镜都有配音和视频
  4926. $missingVideos = $segments->filter(function($segment) {
  4927. return empty($segment->audio_url) || empty($segment->video_url);
  4928. });
  4929. if ($missingVideos->isNotEmpty()) {
  4930. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4931. }
  4932. }
  4933. if ($segments->isEmpty()) {
  4934. Utils::throwError('20003:未找到该剧集的分镜数据');
  4935. }
  4936. // 获取当前完整视频url
  4937. $completeVideoUrl = DB::table('mp_anime_episodes')
  4938. ->where('anime_id', $animeId)
  4939. ->where('id', $episodeId)
  4940. ->value('complete_video_url');
  4941. // 构建 generate_json
  4942. $generateJson = [];
  4943. $sequence = 1;
  4944. foreach ($segments as $segment) {
  4945. if ((int)$ace_mode === 1) {
  4946. $generateJson[] = [
  4947. 'sequence' => $sequence++,
  4948. 'video_url' => $segment->video_url,
  4949. 'video_time_point_start' => $segment->video_time_point_start,
  4950. 'video_time_point_end' => $segment->video_time_point_end
  4951. ];
  4952. }else {
  4953. $generateJson[] = [
  4954. 'sequence' => $sequence++,
  4955. 'video_url' => $segment->video_url,
  4956. 'audio_url' => $segment->audio_url,
  4957. 'video_time_point_start' => $segment->video_time_point_start,
  4958. 'video_time_point_end' => $segment->video_time_point_end
  4959. ];
  4960. }
  4961. }
  4962. // 创建任务
  4963. $now = date('Y-m-d H:i:s');
  4964. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4965. 'anime_id' => $animeId,
  4966. 'episode_id' => $episodeId,
  4967. 'generate_json' => json_encode($generateJson, 256),
  4968. 'generate_status' => '执行中',
  4969. 'complete_video_url' => '',
  4970. 'created_at' => $now,
  4971. 'updated_at' => $now
  4972. ]);
  4973. if (!$taskId) {
  4974. Utils::throwError('20003:创建任务失败');
  4975. }
  4976. // 更新剧集表的任务ID和状态
  4977. $boolen = DB::table('mp_anime_episodes')
  4978. ->where('anime_id', $animeId)
  4979. ->where('id', $episodeId)
  4980. ->update([
  4981. 'complete_video_task_id' => $taskId,
  4982. 'complete_video_task_status' => '执行中',
  4983. 'updated_at' => $now
  4984. ]);
  4985. if (!$boolen) {
  4986. Utils::throwError('20003:更新剧集表失败');
  4987. }
  4988. dLog('anime')->info('创建完整视频合成任务', [
  4989. 'task_id' => $taskId,
  4990. 'anime_id' => $animeId,
  4991. 'episode_id' => $episodeId,
  4992. 'segment_count' => count($generateJson)
  4993. ]);
  4994. // 请求远程服务器执行生成
  4995. $client = new Client(['timeout' => 600, 'verify' => false]);
  4996. try {
  4997. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4998. $response = $result->getBody()->getContents();
  4999. $response_arr = json_decode($response, true);
  5000. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5001. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5002. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5003. // // 更新任务状态为失败
  5004. // DB::table('mp_complete_video_tasks')
  5005. // ->where('id', $taskId)
  5006. // ->update([
  5007. // 'generate_status' => '执行失败',
  5008. // 'error_message' => $error_msg,
  5009. // 'updated_at' => date('Y-m-d H:i:s')
  5010. // ]);
  5011. // // 同步更新剧集表状态
  5012. // DB::table('mp_anime_episodes')
  5013. // ->where('complete_video_task_id', $taskId)
  5014. // ->update([
  5015. // 'complete_video_task_status' => '执行失败',
  5016. // 'updated_at' => date('Y-m-d H:i:s')
  5017. // ]);
  5018. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5019. }
  5020. } catch (\Exception $e) {
  5021. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5022. // 更新任务状态为失败
  5023. DB::table('mp_complete_video_tasks')
  5024. ->where('id', $taskId)
  5025. ->update([
  5026. 'generate_status' => '执行失败',
  5027. 'error_message' => $e->getMessage(),
  5028. 'updated_at' => date('Y-m-d H:i:s')
  5029. ]);
  5030. // 同步更新剧集表状态
  5031. DB::table('mp_anime_episodes')
  5032. ->where('complete_video_task_id', $taskId)
  5033. ->update([
  5034. 'complete_video_task_status' => '执行失败',
  5035. 'updated_at' => date('Y-m-d H:i:s')
  5036. ]);
  5037. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5038. }
  5039. // 开始轮询任务状态
  5040. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5041. $pollInterval = 5; // 每5秒轮询一次
  5042. $attempt = 0;
  5043. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5044. while ($attempt < $maxAttempts) {
  5045. sleep($pollInterval);
  5046. $attempt++;
  5047. // 查询任务状态
  5048. $task = DB::table('mp_complete_video_tasks')
  5049. ->where('id', $taskId)
  5050. ->first();
  5051. if (!$task) {
  5052. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5053. Utils::throwError('20003:任务不存在');
  5054. }
  5055. dLog('anime')->info('轮询任务状态', [
  5056. 'task_id' => $taskId,
  5057. 'attempt' => $attempt,
  5058. 'status' => $task->generate_status
  5059. ]);
  5060. // 检查任务是否完成
  5061. if ($task->generate_status === '执行成功') {
  5062. // 同步更新剧集表状态
  5063. $boolen3 = DB::table('mp_anime_episodes')
  5064. ->where('anime_id', $animeId)
  5065. ->where('id', $episodeId)
  5066. ->update([
  5067. 'complete_video_url' => $task->complete_video_url,
  5068. 'complete_video_task_status' => '执行成功',
  5069. 'updated_at' => date('Y-m-d H:i:s')
  5070. ]);
  5071. dLog('anime')->info('视频合成任务完成', [
  5072. 'task_id' => $taskId,
  5073. 'video_url' => $task->complete_video_url,
  5074. 'attempts' => $attempt
  5075. ]);
  5076. // 如果更新成功则远程删除之前的文件
  5077. if ($boolen3 && $completeVideoUrl) {
  5078. $encode_url = urlencode($completeVideoUrl);
  5079. $client = new Client(['timeout' => 300, 'verify' => false]);
  5080. // 根据ID通过API通知合成音频
  5081. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5082. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5083. $response = $result->getBody()->getContents();
  5084. $response_arr = json_decode($response, true);
  5085. Log::info('火山删除音频返回: '.$response);
  5086. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5087. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5088. Log::info('火山删除音频失败: '.$error_msg);
  5089. // Utils::throwError('20003:火山删除音频失败');
  5090. }
  5091. }
  5092. return [
  5093. 'task_id' => $taskId,
  5094. 'anime_id' => $animeId,
  5095. 'episode_id' => $episodeId,
  5096. 'segment_count' => count($generateJson),
  5097. 'generate_status' => '执行成功',
  5098. 'complete_video_url' => $task->complete_video_url,
  5099. ];
  5100. }
  5101. // 检查任务是否失败
  5102. if ($task->generate_status === '执行失败') {
  5103. // 同步更新剧集表状态
  5104. DB::table('mp_anime_episodes')
  5105. ->where('anime_id', $animeId)
  5106. ->where('id', $episodeId)
  5107. ->update([
  5108. 'complete_video_task_status' => '执行失败',
  5109. 'updated_at' => date('Y-m-d H:i:s')
  5110. ]);
  5111. $errorMessage = $task->error_message ?? '未知错误';
  5112. dLog('anime')->error('视频合成任务失败', [
  5113. 'task_id' => $taskId,
  5114. 'error' => $errorMessage,
  5115. 'attempts' => $attempt
  5116. ]);
  5117. return [
  5118. 'task_id' => $taskId,
  5119. 'anime_id' => $animeId,
  5120. 'episode_id' => $episodeId,
  5121. 'segment_count' => count($generateJson),
  5122. 'generate_status' => '执行失败',
  5123. 'error_message' => $errorMessage
  5124. ];
  5125. }
  5126. }
  5127. // 超时处理
  5128. dLog('anime')->warning('视频合成任务超时', [
  5129. 'task_id' => $taskId,
  5130. 'max_attempts' => $maxAttempts,
  5131. 'timeout_seconds' => $maxAttempts * $pollInterval
  5132. ]);
  5133. // 更新任务状态为超时
  5134. DB::table('mp_complete_video_tasks')
  5135. ->where('id', $taskId)
  5136. ->update([
  5137. 'generate_status' => '超时',
  5138. 'error_message' => '任务执行超时(5分钟)',
  5139. 'updated_at' => date('Y-m-d H:i:s')
  5140. ]);
  5141. return [
  5142. 'task_id' => $taskId,
  5143. 'anime_id' => $animeId,
  5144. 'episode_id' => $episodeId,
  5145. 'segment_count' => count($generateJson),
  5146. 'generate_status' => '超时',
  5147. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5148. ];
  5149. }
  5150. /**
  5151. * 根据 inner_prompt_type 附加内置提示词
  5152. *
  5153. * @param string $prompt 用户提示词
  5154. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5155. * @return string 合并后的提示词
  5156. */
  5157. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5158. {
  5159. $innerPromptMap = [
  5160. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5161. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5162. ];
  5163. if (!isset($innerPromptMap[$innerPromptType])) {
  5164. return $prompt;
  5165. }
  5166. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5167. }
  5168. /**
  5169. * 根据 inner_prompt_type 获取生成图片数量
  5170. *
  5171. * @param int $innerPromptType 内置提示词类型
  5172. * @param int $imageNum 传入的图片张数
  5173. * @return int 图片数量
  5174. */
  5175. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5176. {
  5177. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5178. }
  5179. /**
  5180. * 提取图片生成结果URL
  5181. *
  5182. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5183. * @param int $innerPromptType 内置提示词类型
  5184. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5185. */
  5186. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5187. {
  5188. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5189. if (is_array($resultUrls) && !empty($resultUrls)) {
  5190. $resultUrls = array_values($resultUrls);
  5191. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5192. }
  5193. if (!empty($resultUrl)) {
  5194. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5195. }
  5196. return (int)$innerPromptType === 2 ? [] : '';
  5197. }
  5198. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5199. $prompt = getProp($data, 'prompt');
  5200. $episode_id = getProp($data, 'episode_id');
  5201. $ref_img_urls = getProp($data, 'ref_img_urls');
  5202. $ratio = getProp($data, 'ratio', '9:16');
  5203. $resolution = getProp($data, 'resolution', '2k');
  5204. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5205. $imageNum = (int)getProp($data, 'image_num', 1);
  5206. // 定义分辨率和宽高比对应的尺寸映射表
  5207. $sizeMap = [
  5208. '2k' => [
  5209. '1:1' => ['width' => 2048, 'height' => 2048],
  5210. '4:3' => ['width' => 2304, 'height' => 1728],
  5211. '3:4' => ['width' => 1728, 'height' => 2304],
  5212. '16:9' => ['width' => 2848, 'height' => 1600],
  5213. '9:16' => ['width' => 1600, 'height' => 2848],
  5214. '3:2' => ['width' => 2496, 'height' => 1664],
  5215. '2:3' => ['width' => 1664, 'height' => 2496],
  5216. '21:9' => ['width' => 3136, 'height' => 1344],
  5217. ],
  5218. '3k' => [
  5219. '1:1' => ['width' => 3072, 'height' => 3072],
  5220. '4:3' => ['width' => 3456, 'height' => 2592],
  5221. '3:4' => ['width' => 2592, 'height' => 3456],
  5222. '16:9' => ['width' => 4096, 'height' => 2304],
  5223. '9:16' => ['width' => 2304, 'height' => 4096],
  5224. '2:3' => ['width' => 2496, 'height' => 3744],
  5225. '3:2' => ['width' => 3744, 'height' => 2496],
  5226. '21:9' => ['width' => 4704, 'height' => 2016],
  5227. ],
  5228. '4k' => [
  5229. '1:1' => ['width' => 4096, 'height' => 4096],
  5230. '3:4' => ['width' => 3520, 'height' => 4704],
  5231. '4:3' => ['width' => 4704, 'height' => 3520],
  5232. '16:9' => ['width' => 5504, 'height' => 3040],
  5233. '9:16' => ['width' => 3040, 'height' => 5504],
  5234. '2:3' => ['width' => 3328, 'height' => 4992],
  5235. '3:2' => ['width' => 4992, 'height' => 3328],
  5236. '21:9' => ['width' => 6240, 'height' => 2656],
  5237. ],
  5238. ];
  5239. // 参数验证
  5240. $resolution = strtolower($resolution);
  5241. if (!isset($sizeMap[$resolution])) {
  5242. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5243. }
  5244. if (!isset($sizeMap[$resolution][$ratio])) {
  5245. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5246. }
  5247. // 根据 ratio 和 resolution 确定宽高
  5248. $width = $sizeMap[$resolution][$ratio]['width'];
  5249. $height = $sizeMap[$resolution][$ratio]['height'];
  5250. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5251. if (is_json($ref_img_urls)) {
  5252. $ref_img_urls = json_decode($ref_img_urls, true);
  5253. }else {
  5254. $ref_img_urls = explode(',', $ref_img_urls);
  5255. }
  5256. }
  5257. // 处理图片模型
  5258. $model = getProp($data, 'model');
  5259. if (!$model) {
  5260. // 用户没有输入,从episode表获取
  5261. if ($episode_id) {
  5262. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5263. $model = getProp($episode, 'image_model');
  5264. }
  5265. if (!$model) {
  5266. // episode表也没有,使用默认值
  5267. $model = 'doubao-seedream-5-0-lite-260128';
  5268. }
  5269. }
  5270. // 验证模型是否在可用模型表中
  5271. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5272. // $model = 'doubao-seedream-5-0-lite-260128';
  5273. Utils::throwError('20003:该模型已不可用,请更换!');
  5274. }
  5275. // 保存到episode表
  5276. if ($episode_id) {
  5277. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5278. 'image_model' => $model,
  5279. 'updated_at' => date('Y-m-d H:i:s')
  5280. ]);
  5281. }
  5282. // 参数验证
  5283. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5284. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5285. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5286. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5287. try {
  5288. // 创建图片生成任务
  5289. $params = [
  5290. 'prompt' => $prompt,
  5291. 'model' => $model,
  5292. 'ref_img_urls' => '',
  5293. 'width' => $width,
  5294. 'height' => $height,
  5295. 'image_num' => $imageNum
  5296. ];
  5297. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5298. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5299. $task_id = $task->id;
  5300. if (!$task_id) {
  5301. Utils::throwError('20003:创建图片生成任务失败');
  5302. }
  5303. // 创建任务中心记录并关联图片任务ID
  5304. $taskCenter = $this->taskCenterService->createTask('image', [
  5305. 'title' => '文生图',
  5306. 'ref_task_id' => $task_id,
  5307. // 'prompt' => $prompt,
  5308. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5309. ]);
  5310. $taskCenterId = $taskCenter->id;
  5311. // 组装本次任务信息(用于init消息,类似generateVideo)
  5312. $taskInfo = [
  5313. 'task_id' => $task_id,
  5314. 'status' => getProp($task, 'status', 'processing'),
  5315. 'model' => $model,
  5316. 'ratio' => $ratio,
  5317. 'resolution' => $resolution,
  5318. 'image_num' => $imageNum,
  5319. ];
  5320. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5321. if (is_callable($onTaskCreated)) {
  5322. $onTaskCreated($taskCenterId, $taskInfo);
  5323. }
  5324. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5325. $model = getProp($task, 'model');
  5326. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5327. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5328. $isSyncModel = $isVolcModel || $isGptModel;
  5329. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5330. $start_time = time();
  5331. $timeout = 300; // 5分钟
  5332. $img_url = '';
  5333. $img_urls = [];
  5334. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5335. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5336. while (time() - $start_time < $timeout) {
  5337. sleep(3);
  5338. // 每分钟发送一次队列状态消息(仅流式模式)
  5339. if (is_callable($onPoll)) {
  5340. $currentTime = time();
  5341. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5342. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5343. $lastQueueMessageTime = $currentTime;
  5344. }
  5345. }
  5346. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5347. if ($isSyncModel) {
  5348. // 刷新任务状态
  5349. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5350. if ($task->status === 'success' && $task->result_url) {
  5351. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5352. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5353. if (!empty($resultUrls)) {
  5354. $img_urls = $resultUrls;
  5355. $img_url = $resultUrls[0];
  5356. } else {
  5357. $img_url = (string)$task->result_url;
  5358. }
  5359. break;
  5360. } elseif ($task->status === 'failed') {
  5361. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5362. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5363. }
  5364. // // 如果还在处理中,提示用户稍后查看
  5365. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5366. }else {
  5367. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5368. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5369. if ($statusInfo['status'] === 'success') {
  5370. $task->updateStatus('success', [
  5371. 'result_url' => $statusInfo['result_url'],
  5372. 'result_json' => $statusInfo['result_json'] ?? []
  5373. ]);
  5374. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5375. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5376. if (!empty($resultUrls)) {
  5377. $img_urls = $resultUrls;
  5378. $img_url = $resultUrls[0];
  5379. } else {
  5380. $img_url = (string)$statusInfo['result_url'];
  5381. }
  5382. break;
  5383. } elseif ($statusInfo['status'] === 'failed') {
  5384. $task->updateStatus('failed', [
  5385. 'error_message' => $statusInfo['error_message'],
  5386. 'result_json' => $statusInfo['result_json'] ?? []
  5387. ]);
  5388. dLog('anime')->error('图片生成失败,', [
  5389. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5390. ]);
  5391. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5392. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5393. }
  5394. }
  5395. }
  5396. if (empty($img_url)) {
  5397. Utils::throwError('20003:图片生成超时,请稍后重试');
  5398. }
  5399. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5400. if (count($img_urls) > 1) {
  5401. return [
  5402. 'img_url' => $img_url,
  5403. 'image_urls' => $img_urls,
  5404. 'task_id' => $taskCenterId,
  5405. ];
  5406. }
  5407. return [
  5408. 'img_url' => $img_url,
  5409. 'task_id' => $taskCenterId,
  5410. ];
  5411. } catch (\Exception $e) {
  5412. dLog('anime')->error('更新角色或场景失败', [
  5413. 'error' => $e->getMessage()
  5414. ]);
  5415. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5416. Utils::throwError('20003:' . $e->getMessage());
  5417. }
  5418. }
  5419. /**
  5420. * 使用文生文模型解析分镜内容
  5421. */
  5422. private function parseSegmentContentWithAI($segment_content) {
  5423. try {
  5424. // 使用DeepSeek服务的公开方法解析分镜内容
  5425. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5426. } catch (\Exception $e) {
  5427. // 如果AI解析失败,记录日志并返回原内容
  5428. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5429. return $segment_content;
  5430. }
  5431. }
  5432. /**
  5433. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5434. *
  5435. * @param int $episode_id 分集ID
  5436. * @param int $anime_id 动漫ID
  5437. * @param array $roles 分集角色数组(引用传递)
  5438. * @param array $scenes 分集场景数组(引用传递)
  5439. * @param array $episode 分集数据
  5440. */
  5441. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5442. // 获取全局动漫的角色和场景数据
  5443. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5444. if (!$anime) return;
  5445. $art_style_type = getProp($anime, 'art_style_type');
  5446. $character_prefix = '';
  5447. $scene_prefix = '';
  5448. if ($art_style_type) {
  5449. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5450. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5451. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5452. }
  5453. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5454. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5455. $roles_updated = false;
  5456. $scenes_updated = false;
  5457. // 处理角色
  5458. foreach ($roles as &$role) {
  5459. $role_name = getProp($role, 'role');
  5460. $role_description = getProp($role, 'description');
  5461. $role_pic_prompt = getProp($role, 'pic_prompt');
  5462. $role_url = getProp($role, 'url');
  5463. $role_task_id = getProp($role, 'task_id');
  5464. // 如果已有URL或已有任务ID,跳过
  5465. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5466. continue;
  5467. }
  5468. $url_inherited = false;
  5469. // 尝试从全局数据中继承
  5470. foreach ($global_roles as $global_role) {
  5471. $global_role_name = getProp($global_role, 'role');
  5472. $global_role_description = getProp($global_role, 'description');
  5473. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5474. $global_role_url = getProp($global_role, 'url');
  5475. $global_role_task_id = getProp($global_role, 'task_id');
  5476. $global_role_task_status = getProp($global_role, 'task_status');
  5477. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5478. if ($role_name === $global_role_name
  5479. && $role_description === $global_role_description
  5480. && $role_pic_prompt === $global_role_pic_prompt
  5481. && !empty($global_role_url)) {
  5482. // 继承 task_id、task_status 和 url
  5483. $role['task_id'] = $global_role_task_id;
  5484. $role['task_status'] = $global_role_task_status;
  5485. $role['url'] = $global_role_url;
  5486. $roles_updated = true;
  5487. $url_inherited = true;
  5488. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5489. break;
  5490. }
  5491. }
  5492. // 如果无法继承且没有任务ID,创建新任务
  5493. if (!$url_inherited && empty($role_task_id)) {
  5494. try {
  5495. $art_style = getProp($episode, 'art_style');
  5496. // 优先使用 pic_prompt,如果没有则使用 description
  5497. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5498. // if ($art_style) {
  5499. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5500. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5501. // }
  5502. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5503. $params = [
  5504. 'prompt' => $description,
  5505. 'ref_img_urls' => []
  5506. ];
  5507. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5508. $task_id = $task->id;
  5509. if ($task_id) {
  5510. $role['task_id'] = $task_id;
  5511. $role['task_status'] = 'processing';
  5512. $roles_updated = true;
  5513. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5514. }
  5515. } catch (\Exception $e) {
  5516. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5517. }
  5518. }
  5519. }
  5520. // 处理场景
  5521. foreach ($scenes as &$scene) {
  5522. $scene_name = getProp($scene, 'scene');
  5523. $scene_description = getProp($scene, 'description');
  5524. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5525. $scene_url = getProp($scene, 'url');
  5526. $scene_task_id = getProp($scene, 'task_id');
  5527. // 如果已有URL或已有任务ID,跳过
  5528. if (!empty($scene_url) || !empty($scene_task_id)) {
  5529. continue;
  5530. }
  5531. $url_inherited = false;
  5532. // 尝试从全局数据中继承
  5533. foreach ($global_scenes as $global_scene) {
  5534. $global_scene_name = getProp($global_scene, 'scene');
  5535. $global_scene_description = getProp($global_scene, 'description');
  5536. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5537. $global_scene_url = getProp($global_scene, 'url');
  5538. $global_scene_task_id = getProp($global_scene, 'task_id');
  5539. $global_scene_task_status = getProp($global_scene, 'task_status');
  5540. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5541. if ($scene_name === $global_scene_name
  5542. && $scene_description === $global_scene_description
  5543. && $scene_pic_prompt === $global_scene_pic_prompt
  5544. && !empty($global_scene_url)) {
  5545. // 继承 task_id、task_status 和 url
  5546. $scene['task_id'] = $global_scene_task_id;
  5547. $scene['task_status'] = $global_scene_task_status;
  5548. $scene['url'] = $global_scene_url;
  5549. $scenes_updated = true;
  5550. $url_inherited = true;
  5551. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5552. break;
  5553. }
  5554. }
  5555. // 如果无法继承且没有任务ID,创建新任务
  5556. if (!$url_inherited && empty($scene_task_id)) {
  5557. try {
  5558. $art_style = getProp($episode, 'art_style');
  5559. // 优先使用 pic_prompt,如果没有则使用 description
  5560. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5561. // if ($art_style) {
  5562. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5563. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5564. // }
  5565. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5566. $params = [
  5567. 'prompt' => $description,
  5568. 'ref_img_urls' => []
  5569. ];
  5570. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5571. $task_id = $task->id;
  5572. if ($task_id) {
  5573. $scene['task_id'] = $task_id;
  5574. $scene['task_status'] = 'processing';
  5575. $scenes_updated = true;
  5576. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5577. }
  5578. } catch (\Exception $e) {
  5579. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5580. }
  5581. }
  5582. }
  5583. // 如果有更新,保存到数据库
  5584. if ($roles_updated || $scenes_updated) {
  5585. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5586. if ($roles_updated) {
  5587. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5588. }
  5589. if ($scenes_updated) {
  5590. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5591. }
  5592. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5593. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5594. }
  5595. }
  5596. /**
  5597. * 根据图片URL使用AI反推图片提示词
  5598. *
  5599. * @param string $img_url 图片URL
  5600. * @return string 反推的提示词
  5601. */
  5602. private function generateImagePromptFromUrl($img_url) {
  5603. try {
  5604. // 获取默认模型
  5605. $model = 'doubao-seed-2-0-mini-260215';
  5606. // 构建messages参数
  5607. $messages = [
  5608. [
  5609. 'role' => 'user',
  5610. 'content' => [
  5611. [
  5612. 'type' => 'text',
  5613. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5614. ],
  5615. [
  5616. 'type' => 'image_url',
  5617. 'image_url' => [
  5618. 'url' => $img_url
  5619. ]
  5620. ]
  5621. ]
  5622. ]
  5623. ];
  5624. // 构建请求参数
  5625. $params = [
  5626. 'model' => $model,
  5627. 'messages' => $messages,
  5628. 'stream' => false,
  5629. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5630. ];
  5631. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5632. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5633. // 仅记录 token 使用明细(不扣积分)
  5634. $uid = 0;
  5635. try {
  5636. $uid = (int)Site::getUid();
  5637. } catch (\Throwable $e) {
  5638. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5639. }
  5640. $this->pointsService->recordTokenOnlyDetail(
  5641. $uid,
  5642. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5643. [
  5644. 'model' => $model,
  5645. 'img_url' => $img_url,
  5646. 'source' => 'generateImagePromptFromUrl',
  5647. ],
  5648. 'chat',
  5649. $model,
  5650. ''
  5651. );
  5652. // 返回生成的内容
  5653. return getProp($result, 'fullContent', '图片描述生成失败');
  5654. } catch (\Exception $e) {
  5655. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5656. 'img_url' => $img_url
  5657. ]);
  5658. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5659. 'error' => $e->getMessage(),
  5660. 'img_url' => $img_url
  5661. ]);
  5662. return '图片描述生成失败: ' . $e->getMessage();
  5663. }
  5664. }
  5665. /**
  5666. * 音频试听接口
  5667. * 创建音频任务并轮询获取结果
  5668. *
  5669. * @param array $data 参数数组
  5670. * @return array 返回音频URL或错误信息
  5671. */
  5672. public function previewAudio($data) {
  5673. $dialogue = getProp($data, 'dialogue');
  5674. // 必填参数验证
  5675. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5676. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5677. $voice_type = getProp($data, 'voice_type');
  5678. $voice_name = getProp($data, 'voice_name');
  5679. $voice_actor = getProp($data, 'voice_actor');
  5680. $emotion_type = getProp($data, 'emotion_type');
  5681. $gender = getProp($data, 'gender', 0);
  5682. $emotion = getProp($data, 'emotion');
  5683. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5684. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5685. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5686. $pitch = getProp($data, 'pitch', 0);
  5687. try {
  5688. $now = date('Y-m-d H:i:s');
  5689. // 构建生成参数
  5690. $generate_json = json_encode([
  5691. 'text' => $dialogue,
  5692. 'role' => $voice_actor,
  5693. 'voice_type' => $voice_type,
  5694. 'voice_name' => $voice_name,
  5695. 'emotion' => $emotion,
  5696. 'emotion_type' => $emotion_type,
  5697. 'gender' => $gender,
  5698. 'speed_ratio' => $speed_ratio,
  5699. 'loudness_ratio' => $loudness_ratio,
  5700. 'emotion_scale' => $emotion_scale,
  5701. 'pitch' => $pitch,
  5702. ], 256);
  5703. // 请求远程服务器执行生成
  5704. $client = new Client(['timeout' => 600, 'verify' => false]);
  5705. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5706. $response = $result->getBody()->getContents();
  5707. $response_arr = json_decode($response, true);
  5708. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5709. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5710. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5711. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5712. }
  5713. $arr = $response_arr['data'];
  5714. $subtitle_info = $arr['subtitle_info'];
  5715. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5716. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5717. return [
  5718. 'audio_url' => $arr['url'],
  5719. 'subtitle_info' => $subtitle_info,
  5720. 'audio_duration' => round($audio_duration, 2)
  5721. ];
  5722. } catch (\Exception $e) {
  5723. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5724. Utils::throwError('20003:' . $e->getMessage());
  5725. }
  5726. }
  5727. /**
  5728. * 获取角色库列表(支持文件夹递归查询)
  5729. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5730. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5731. */
  5732. public function globalProducts($data) {
  5733. $uid = Site::getUid();
  5734. $cpid = Site::getCpid();
  5735. $role = Site::getRole();
  5736. $id = getProp($data, 'id', 0);
  5737. $parent_id = getProp($data, 'parent_id', 0);
  5738. $product_name = getProp($data, 'product_name');
  5739. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5740. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5741. if (!$product) {
  5742. Utils::throwError('20003:请选择产品类型');
  5743. }
  5744. // 根据角色和is_public参数确定查询范围
  5745. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5746. // user角色:根据is_public参数筛选
  5747. $query_user_ids = [];
  5748. if ($role === 'admin') {
  5749. // admin获取所有个人库和公共库
  5750. $query_user_ids = [$uid, 0];
  5751. } else {
  5752. // user角色根据is_public参数筛选
  5753. if ($is_public == 2) {
  5754. // 个人库+公共库
  5755. $query_user_ids = [$uid, 0];
  5756. } elseif ($is_public == 0) {
  5757. // 仅个人库
  5758. $query_user_ids = [$uid];
  5759. } elseif ($is_public == 1) {
  5760. // 仅公共库
  5761. $query_user_ids = [0];
  5762. }
  5763. }
  5764. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5765. if ($id || $product_name) {
  5766. $query = DB::table('mp_products')
  5767. ->where('cpid', $cpid)
  5768. ->whereIn('user_id', $query_user_ids)
  5769. ->where('is_deleted', 0);
  5770. // 如果指定了 id,按 id 精确查询
  5771. if ($id) {
  5772. $query->where('id', $id);
  5773. }
  5774. // 如果指定了 product_name,按名称模糊查询
  5775. if ($product_name) {
  5776. $query->where('product_name', 'like', "%{$product_name}%");
  5777. }
  5778. // 如果指定了 product,添加筛选条件
  5779. if ($product) {
  5780. $query->where('product', $product);
  5781. }
  5782. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5783. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5784. ->get()
  5785. ->map(function($value) {
  5786. $value = (array)$value;
  5787. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5788. $value['type'] = (int)$value['type'];
  5789. $value['parent_id'] = (int)$value['parent_id'];
  5790. $value['level'] = (int)$value['level'];
  5791. $value['product'] = (int)($value['product'] ?? 1);
  5792. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5793. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5794. unset($value['user_id']);
  5795. return $value;
  5796. })
  5797. ->toArray();
  5798. return $result;
  5799. }
  5800. // 递归获取所有子目录和角色
  5801. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5802. }
  5803. /**
  5804. * 递归获取指定目录下的所有子目录和角色
  5805. * @param int $cpid 公司ID
  5806. * @param int $parent_id 父目录ID
  5807. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5808. * @param array $query_user_ids 用户ID数组(支持多个)
  5809. * @param int $current_uid 当前用户ID(用于排序)
  5810. * @return array
  5811. */
  5812. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5813. // 查询当前层级的所有项(文件夹和角色)
  5814. $query = DB::table('mp_products')
  5815. ->where('cpid', $cpid)
  5816. ->where('is_deleted', 0)
  5817. ->where('parent_id', $parent_id);
  5818. // 添加用户ID验证(支持多个user_id)
  5819. if (!empty($query_user_ids)) {
  5820. $query->whereIn('user_id', $query_user_ids);
  5821. }
  5822. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5823. if ($product) {
  5824. $query->where('product', $product);
  5825. }
  5826. // 排序规则:
  5827. // 1. 文件夹在前(type DESC)
  5828. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5829. // 3. 其他排序规则
  5830. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5831. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5832. ->get();
  5833. $result = [];
  5834. foreach ($items as $item) {
  5835. $itemArray = [
  5836. 'id' => $item->id,
  5837. 'type' => (int)$item->type,
  5838. 'parent_id' => (int)$item->parent_id,
  5839. 'level' => (int)$item->level,
  5840. 'product_name' => $item->product_name,
  5841. 'url' => $item->url,
  5842. 'pic_prompt' => $item->pic_prompt ?? '',
  5843. 'three_view_image_url' => $item->three_view_image_url,
  5844. 'product' => (int)($item->product ?? 1),
  5845. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5846. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5847. ];
  5848. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5849. // 如果是文件夹,递归获取其子项
  5850. if ($item->type == 2) {
  5851. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5852. if (!empty($children)) {
  5853. $itemArray['children'] = $children;
  5854. }
  5855. }
  5856. $result[] = $itemArray;
  5857. }
  5858. return $result;
  5859. }
  5860. /**
  5861. * 创建文件夹
  5862. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5863. * @return int 返回新建文件夹ID
  5864. */
  5865. public function createFolder($data) {
  5866. $uid = Site::getUid();
  5867. $cpid = Site::getCpid();
  5868. $role = Site::getRole();
  5869. $parent_id = getProp($data, 'parent_id', 0);
  5870. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5871. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5872. // 如果是公共库操作,需要admin权限
  5873. if ($is_public && $role !== 'admin') {
  5874. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5875. }
  5876. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5877. $store_uid = $is_public ? 0 : $uid;
  5878. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5879. $product = getProp($data, 'product');
  5880. if (!in_array($product, [1, 2, 3])) {
  5881. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5882. }
  5883. // 验证父文件夹
  5884. $parent_level = 0;
  5885. if ($parent_id > 0) {
  5886. $parent = DB::table('mp_products')
  5887. ->where('id', $parent_id)
  5888. ->where('cpid', $cpid)
  5889. ->where('user_id', $store_uid)
  5890. ->where('type', 2)
  5891. ->where('is_deleted', 0)
  5892. ->first();
  5893. if (!$parent) {
  5894. Utils::throwError('20003:父文件夹不存在');
  5895. }
  5896. // 检查父文件夹的 product 类型是否一致
  5897. if ($parent->product != $product) {
  5898. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5899. }
  5900. $parent_level = $parent->level;
  5901. // 检查层级限制(最多3层)
  5902. if ($parent_level >= 3) {
  5903. Utils::throwError('20003:文件夹层级不能超过3层');
  5904. }
  5905. }
  5906. // 检查当前目录下是否已存在空白文件夹
  5907. $empty_folder_exists = DB::table('mp_products')
  5908. ->where('parent_id', $parent_id)
  5909. ->where('cpid', $cpid)
  5910. ->where('user_id', $store_uid)
  5911. ->where('type', 2)
  5912. ->where('product', $product)
  5913. ->where('product_name', '新建文件夹')
  5914. ->where('is_deleted', 0)
  5915. ->exists();
  5916. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5917. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5918. }
  5919. // 创建文件夹
  5920. $folder_id = DB::table('mp_products')->insertGetId([
  5921. 'user_id' => $store_uid,
  5922. 'cpid' => $cpid,
  5923. 'type' => 2,
  5924. 'parent_id' => $parent_id,
  5925. 'level' => $parent_level + 1,
  5926. 'product_name' => $folder_name,
  5927. 'product' => $product,
  5928. 'sort_order' => time(), // 使用时间戳作为排序权重
  5929. 'is_deleted' => 0,
  5930. 'created_at' => date('Y-m-d H:i:s'),
  5931. 'updated_at' => date('Y-m-d H:i:s')
  5932. ]);
  5933. return [
  5934. 'id' => $folder_id,
  5935. 'type' => 2,
  5936. 'parent_id' => $parent_id,
  5937. 'level' => $parent_level + 1,
  5938. 'product_name' => $folder_name,
  5939. 'product' => $product,
  5940. ];
  5941. }
  5942. /**
  5943. * 重命名文件夹或角色
  5944. * @param array $data 包含 id、product_name(新名称)
  5945. * @return bool
  5946. */
  5947. public function renameFolder($data) {
  5948. $uid = Site::getUid();
  5949. $cpid = Site::getCpid();
  5950. $role = Site::getRole();
  5951. $id = getProp($data, 'id');
  5952. $new_name = getProp($data, 'product_name');
  5953. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5954. if (!$id || !$new_name) {
  5955. Utils::throwError('20003:参数不完整');
  5956. }
  5957. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5958. $query_uid = $is_public ? 0 : $uid;
  5959. // 如果是公共库操作,需要admin权限
  5960. if ($is_public && $role !== 'admin') {
  5961. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5962. }
  5963. // 检查是否存在
  5964. $item = DB::table('mp_products')
  5965. ->where('id', $id)
  5966. ->where('cpid', $cpid)
  5967. ->where('user_id', $query_uid)
  5968. ->where('is_deleted', 0)
  5969. ->first();
  5970. if (!$item) {
  5971. Utils::throwError('20003:项目不存在');
  5972. }
  5973. return DB::table('mp_products')
  5974. ->where('id', $id)
  5975. ->where('cpid', $cpid)
  5976. ->where('user_id', $query_uid)
  5977. ->update([
  5978. 'product_name' => $new_name,
  5979. 'updated_at' => date('Y-m-d H:i:s')
  5980. ]);
  5981. }
  5982. /**
  5983. * 移动角色或文件夹到指定文件夹
  5984. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5985. * @return bool
  5986. */
  5987. public function moveProductOrFolder($data) {
  5988. $uid = Site::getUid();
  5989. $cpid = Site::getCpid();
  5990. $role = Site::getRole();
  5991. $id = getProp($data, 'id');
  5992. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5993. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5994. if (!$id) {
  5995. Utils::throwError('20003:请选择要移动的项目');
  5996. }
  5997. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5998. $query_uid = $is_public ? 0 : $uid;
  5999. // 如果是公共库操作,需要admin权限
  6000. if ($is_public && $role !== 'admin') {
  6001. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6002. }
  6003. // 检查要移动的项目
  6004. $item = DB::table('mp_products')
  6005. ->where('id', $id)
  6006. ->where('cpid', $cpid)
  6007. ->where('user_id', $query_uid)
  6008. ->where('is_deleted', 0)
  6009. ->first();
  6010. if (!$item) {
  6011. Utils::throwError('20003:项目不存在');
  6012. }
  6013. // 验证目标文件夹
  6014. $target_level = 0;
  6015. $target_product = $item->product; // 默认使用当前项目的 product
  6016. if ($target_parent_id > 0) {
  6017. $target_parent = DB::table('mp_products')
  6018. ->where('id', $target_parent_id)
  6019. ->where('cpid', $cpid)
  6020. ->where('user_id', $query_uid)
  6021. ->where('type', 2)
  6022. ->where('is_deleted', 0)
  6023. ->first();
  6024. if (!$target_parent) {
  6025. Utils::throwError('20003:目标文件夹不存在');
  6026. }
  6027. // 检查 product 类型是否一致
  6028. if ($target_parent->product != $item->product) {
  6029. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6030. }
  6031. $target_level = $target_parent->level;
  6032. $target_product = $target_parent->product;
  6033. // 如果移动的是文件夹,需要检查层级
  6034. if ($item->type == 2) {
  6035. // 计算移动后的最大层级
  6036. $max_child_level = $this->getMaxChildLevel($id);
  6037. $depth = $max_child_level - $item->level;
  6038. if ($target_level + 1 + $depth > 3) {
  6039. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6040. }
  6041. // 不能移动到自己或自己的子文件夹下
  6042. if ($this->isDescendant($target_parent_id, $id)) {
  6043. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6044. }
  6045. }
  6046. }
  6047. // 更新父文件夹和层级
  6048. $new_level = $target_level + 1;
  6049. DB::table('mp_products')
  6050. ->where('id', $id)
  6051. ->update([
  6052. 'parent_id' => $target_parent_id,
  6053. 'level' => $new_level,
  6054. 'updated_at' => date('Y-m-d H:i:s')
  6055. ]);
  6056. // 如果是文件夹,需要递归更新所有子项的层级
  6057. if ($item->type == 2) {
  6058. $this->updateChildrenLevel($id, $new_level);
  6059. }
  6060. return true;
  6061. }
  6062. /**
  6063. * 获取文件夹下最大子层级
  6064. * @param int $folder_id
  6065. * @return int
  6066. */
  6067. private function getMaxChildLevel($folder_id) {
  6068. $max_level = DB::table('mp_products')
  6069. ->where('parent_id', $folder_id)
  6070. ->where('is_deleted', 0)
  6071. ->max('level');
  6072. if (!$max_level) {
  6073. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6074. }
  6075. // 递归查找子文件夹
  6076. $children = DB::table('mp_products')
  6077. ->where('parent_id', $folder_id)
  6078. ->where('type', 2)
  6079. ->where('is_deleted', 0)
  6080. ->pluck('id');
  6081. foreach ($children as $child_id) {
  6082. $child_max = $this->getMaxChildLevel($child_id);
  6083. if ($child_max > $max_level) {
  6084. $max_level = $child_max;
  6085. }
  6086. }
  6087. return $max_level;
  6088. }
  6089. /**
  6090. * 检查 target_id 是否是 folder_id 的后代
  6091. * @param int $target_id
  6092. * @param int $folder_id
  6093. * @return bool
  6094. */
  6095. private function isDescendant($target_id, $folder_id) {
  6096. if ($target_id == $folder_id) {
  6097. return true;
  6098. }
  6099. $parent = DB::table('mp_products')
  6100. ->where('id', $target_id)
  6101. ->where('is_deleted', 0)
  6102. ->first();
  6103. if (!$parent || $parent->parent_id == 0) {
  6104. return false;
  6105. }
  6106. return $this->isDescendant($parent->parent_id, $folder_id);
  6107. }
  6108. /**
  6109. * 递归更新子项层级
  6110. * @param int $parent_id
  6111. * @param int $parent_level
  6112. */
  6113. private function updateChildrenLevel($parent_id, $parent_level) {
  6114. $children = DB::table('mp_products')
  6115. ->where('parent_id', $parent_id)
  6116. ->where('is_deleted', 0)
  6117. ->get();
  6118. foreach ($children as $child) {
  6119. $new_level = $parent_level + 1;
  6120. DB::table('mp_products')
  6121. ->where('id', $child->id)
  6122. ->update([
  6123. 'level' => $new_level,
  6124. 'updated_at' => date('Y-m-d H:i:s')
  6125. ]);
  6126. // 如果是文件夹,继续递归
  6127. if ($child->type == 2) {
  6128. $this->updateChildrenLevel($child->id, $new_level);
  6129. }
  6130. }
  6131. }
  6132. /**
  6133. * 获取文件夹路径(面包屑导航)
  6134. * @param array $data 包含 folder_id
  6135. * @return array 返回路径数组
  6136. */
  6137. public function getFolderPath($data) {
  6138. $uid = Site::getUid();
  6139. $cpid = Site::getCpid();
  6140. $folder_id = getProp($data, 'id', 0);
  6141. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6142. if ($folder_id == 0) {
  6143. return [
  6144. ['id' => 0, 'name' => '根目录']
  6145. ];
  6146. }
  6147. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6148. $query_uid = $is_public ? 0 : $uid;
  6149. $path = [];
  6150. $current_id = $folder_id;
  6151. while ($current_id > 0) {
  6152. $folder = DB::table('mp_products')
  6153. ->where('id', $current_id)
  6154. ->where('cpid', $cpid)
  6155. ->where('user_id', $query_uid)
  6156. ->where('type', 2)
  6157. ->where('is_deleted', 0)
  6158. ->first();
  6159. if (!$folder) {
  6160. break;
  6161. }
  6162. array_unshift($path, [
  6163. 'id' => $folder->id,
  6164. 'name' => $folder->product_name
  6165. ]);
  6166. $current_id = $folder->parent_id;
  6167. }
  6168. // 添加根目录
  6169. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6170. return $path;
  6171. }
  6172. public function createProduct($data) {
  6173. $uid = Site::getUid();
  6174. $cpid = Site::getCpid();
  6175. $role = Site::getRole();
  6176. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6177. // 如果是公共库操作,需要admin权限
  6178. if ($is_public && $role !== 'admin') {
  6179. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6180. }
  6181. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6182. $store_uid = $is_public ? 0 : $uid;
  6183. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6184. $script_id = (int)getProp($data, 'script_id', 0);
  6185. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6186. if ($script_id && empty($episode_numbers)) {
  6187. Utils::throwError('20003:剧集序号不能为空');
  6188. }
  6189. if (!$script_id && !empty($episode_numbers)) {
  6190. Utils::throwError('20003:请提供剧本ID');
  6191. }
  6192. $product_name = trim(getProp($data, 'product_name'));
  6193. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6194. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6195. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6196. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6197. $url = trim(getProp($data, 'url'));
  6198. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6199. $versions = getProp($data, 'versions');
  6200. // 检查是否是正确的图片格式
  6201. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6202. $urlPath = parse_url($url, PHP_URL_PATH);
  6203. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6204. if (!in_array($extension, $allowedExtensions)) {
  6205. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6206. }
  6207. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6208. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6209. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6210. $product = getProp($data, 'product');
  6211. if (!in_array($product, [1, 2, 3])) {
  6212. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6213. }
  6214. // 获取父文件夹ID和层级
  6215. $parent_id = getProp($data, 'parent_id', 0);
  6216. $parent_level = 0;
  6217. if ($parent_id > 0) {
  6218. $parent = DB::table('mp_products')
  6219. ->where('id', $parent_id)
  6220. ->where('cpid', $cpid)
  6221. ->where('user_id', $store_uid)
  6222. ->where('type', 2)
  6223. ->where('is_deleted', 0)
  6224. ->first();
  6225. if (!$parent) {
  6226. Utils::throwError('20003:父文件夹不存在');
  6227. }
  6228. $parent_level = $parent->level;
  6229. }
  6230. // 创建资产并保存剧本资产关联关系(同一事务)
  6231. DB::beginTransaction();
  6232. try {
  6233. $id = DB::table('mp_products')->insertGetId([
  6234. 'user_id' => $store_uid,
  6235. 'cpid' => $cpid,
  6236. 'type' => 1, // 1=角色图片
  6237. 'parent_id' => $parent_id,
  6238. 'level' => $parent_level + 1,
  6239. 'product_name' => $product_name,
  6240. 'url' => $url,
  6241. 'pic_prompt' => $pic_prompt,
  6242. 'product' => $product,
  6243. 'versions' => json_encode($versions, 256),
  6244. 'sort_order' => time(), // 使用时间戳作为排序权重
  6245. 'created_at' => date('Y-m-d H:i:s'),
  6246. 'updated_at' => date('Y-m-d H:i:s')
  6247. ]);
  6248. if (!$id) Utils::throwError('20003:创建失败');
  6249. // 保存剧本资产关联关系
  6250. if ($script_id) {
  6251. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6252. }
  6253. DB::commit();
  6254. } catch (\Exception $e) {
  6255. DB::rollback();
  6256. throw $e;
  6257. }
  6258. return [
  6259. 'id' => $id,
  6260. 'type' => 1,
  6261. 'parent_id' => $parent_id,
  6262. 'level' => $parent_level + 1,
  6263. 'product_name' => $product_name,
  6264. 'url' => $url,
  6265. 'pic_prompt' => $pic_prompt,
  6266. 'product' => $product,
  6267. 'versions' => $versions
  6268. ];
  6269. }
  6270. public function editProduct($data) {
  6271. $uid = Site::getUid();
  6272. $cpid = Site::getCpid();
  6273. $role = Site::getRole();
  6274. $id = getProp($data, 'id');
  6275. if (!$id) Utils::throwError('20003:ID不能为空');
  6276. $versions = getProp($data, 'versions');
  6277. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6278. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6279. $script_id = (int)getProp($data, 'script_id', 0);
  6280. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6281. if ($script_id && empty($episode_numbers)) {
  6282. Utils::throwError('20003:剧集序号不能为空');
  6283. }
  6284. if (!$script_id && !empty($episode_numbers)) {
  6285. Utils::throwError('20003:请提供剧本ID');
  6286. }
  6287. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6288. $query_uid = $is_public ? 0 : $uid;
  6289. // 如果是公共库操作,需要admin权限
  6290. if ($is_public && $role !== 'admin') {
  6291. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6292. }
  6293. // 检查是否存在且属于当前用户或公共库
  6294. $role = DB::table('mp_products')
  6295. ->where('id', $id)
  6296. ->where('cpid', $cpid)
  6297. ->where('user_id', $query_uid)
  6298. ->where('type', 1)->first();
  6299. if (!$role) Utils::throwError('20003:记录不存在');
  6300. $updateData = [];
  6301. // $needVersionRecord = false; // 是否需要记录版本
  6302. // 名称
  6303. $product_name = trim(getProp($data, 'product_name'));
  6304. if ($product_name) {
  6305. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6306. $updateData['product_name'] = $product_name;
  6307. }
  6308. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6309. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6310. // 图片地址
  6311. $url = trim(getProp($data, 'url'));
  6312. if ($url) {
  6313. // 检查是否是正确的图片格式
  6314. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6315. $urlPath = parse_url($url, PHP_URL_PATH);
  6316. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6317. if (!in_array($extension, $allowedExtensions)) {
  6318. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6319. }
  6320. // // 如果 url 有变更,记录版本
  6321. // if ($url !== $role->url) {
  6322. // $needVersionRecord = true;
  6323. // }
  6324. $updateData['url'] = $url;
  6325. }
  6326. // 提示词
  6327. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6328. if ($pic_prompt) {
  6329. // // 如果 pic_prompt 有变更,记录版本
  6330. // if ($pic_prompt !== $role->pic_prompt) {
  6331. // $needVersionRecord = true;
  6332. // }
  6333. $updateData['pic_prompt'] = $pic_prompt;
  6334. }
  6335. if (empty($updateData) && !$script_id) {
  6336. Utils::throwError('20003:没有需要更新的数据');
  6337. }
  6338. // // 如果需要记录版本,将数据添加到 versions 数组
  6339. // if ($needVersionRecord) {
  6340. // // 获取现有的 versions 数据
  6341. // $versions = json_decode($role->versions, true) ?: [];
  6342. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6343. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6344. // if ($isFirstVersion) {
  6345. // $oldVersion = [
  6346. // 'url' => $role->url,
  6347. // 'description' => $role->pic_prompt,
  6348. // ];
  6349. // // 旧版本添加到数组末尾
  6350. // $versions[] = $oldVersion;
  6351. // }
  6352. // // 构建新版本(变更后)
  6353. // $newVersion = [
  6354. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6355. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6356. // ];
  6357. // // 检查新版本是否已存在于历史版本中
  6358. // $existingIndex = -1;
  6359. // foreach ($versions as $index => $version) {
  6360. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6361. // $existingIndex = $index;
  6362. // break;
  6363. // }
  6364. // }
  6365. // if ($existingIndex !== -1) {
  6366. // // 如果已存在,移除旧的位置
  6367. // array_splice($versions, $existingIndex, 1);
  6368. // }
  6369. // // 新版本添加到数组开头(最新的在前)
  6370. // array_unshift($versions, $newVersion);
  6371. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6372. // // if (count($versions) > 10) {
  6373. // // $versions = array_slice($versions, 0, 10);
  6374. // // }
  6375. // $updateData['versions'] = json_encode($versions, 256);
  6376. // }
  6377. if ($versions) {
  6378. $updateData['versions'] = json_encode($versions, 256);
  6379. }
  6380. if (!empty($updateData)) {
  6381. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6382. }
  6383. // 更新资产并保存剧本资产关联关系(同一事务)
  6384. DB::beginTransaction();
  6385. try {
  6386. $updated = true;
  6387. if (!empty($updateData)) {
  6388. $updated = DB::table('mp_products')
  6389. ->where('cpid', $cpid)
  6390. ->where('id', $id)
  6391. ->update($updateData);
  6392. }
  6393. // 保存剧本资产关联关系
  6394. if ($script_id) {
  6395. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6396. }
  6397. DB::commit();
  6398. } catch (\Exception $e) {
  6399. DB::rollback();
  6400. throw $e;
  6401. }
  6402. return $updated;
  6403. }
  6404. /**
  6405. * 保存单一资产与剧本剧集的关联关系
  6406. *
  6407. * @param int $product_id 资产ID
  6408. * @param int $script_id 剧本ID
  6409. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6410. * @return int 新增关联数量
  6411. */
  6412. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6413. $uid = Site::getUid();
  6414. // 验证剧本是否存在
  6415. $script = DB::table('mp_scripts')
  6416. ->where('id', $script_id)
  6417. ->where('is_deleted', 0)
  6418. ->first();
  6419. if (!$script) {
  6420. Utils::throwError('20003:剧本不存在');
  6421. }
  6422. // 验证剧本归属:只能关联自己的剧本
  6423. if ((int)$script->user_id !== (int)$uid) {
  6424. Utils::throwError('20003:只能添加到自己的剧本');
  6425. }
  6426. // 使用 splitContent 拆分剧本内容获取总集数
  6427. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6428. // 解析剧集序号(数组)
  6429. $episodes = [];
  6430. foreach ($episode_numbers as $item) {
  6431. if (is_array($item)) {
  6432. continue;
  6433. }
  6434. $item = trim((string)$item);
  6435. if ($item === '' || !is_numeric($item)) {
  6436. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6437. }
  6438. $episodes[] = (int)$item;
  6439. }
  6440. // 去重并校验序号范围(序号从1开始)
  6441. $episodes = array_values(array_unique($episodes));
  6442. if (empty($episodes)) {
  6443. Utils::throwError('20003:剧集序号不能为空');
  6444. }
  6445. foreach ($episodes as $episode) {
  6446. if ($episode < 1 || $episode > $totalEpisodes) {
  6447. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6448. }
  6449. }
  6450. $now = now();
  6451. // 过滤已存在的关联,避免重复
  6452. $existingEpisodes = DB::table('mp_script_product_mappings')
  6453. ->where('script_id', $script_id)
  6454. ->where('product_id', $product_id)
  6455. ->whereIn('episode_number', $episodes)
  6456. ->pluck('episode_number')
  6457. ->all();
  6458. $mappingRecords = [];
  6459. foreach ($episodes as $episode) {
  6460. if (in_array($episode, $existingEpisodes)) {
  6461. continue;
  6462. }
  6463. $mappingRecords[] = [
  6464. 'script_id' => $script_id,
  6465. 'product_id' => $product_id,
  6466. 'episode_number' => $episode,
  6467. 'created_at' => $now,
  6468. 'updated_at' => $now,
  6469. ];
  6470. }
  6471. $insertedCount = 0;
  6472. if (!empty($mappingRecords)) {
  6473. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6474. }
  6475. return $insertedCount;
  6476. }
  6477. /**
  6478. * 规范化剧集序号参数,统一为数组
  6479. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6480. *
  6481. * @param mixed $episode_number 剧集序号参数
  6482. * @return array
  6483. */
  6484. private function normalizeEpisodeNumbers($episode_number) {
  6485. if (!is_array($episode_number)) {
  6486. $episode_number = explode(',', (string)$episode_number);
  6487. }
  6488. $items = [];
  6489. foreach ($episode_number as $item) {
  6490. if (is_array($item)) {
  6491. continue;
  6492. }
  6493. foreach (explode(',', (string)$item) as $part) {
  6494. $part = trim($part);
  6495. if ($part !== '') {
  6496. $items[] = $part;
  6497. }
  6498. }
  6499. }
  6500. return $items;
  6501. }
  6502. /**
  6503. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6504. *
  6505. * @param object $script 剧本记录
  6506. * @return int 总集数
  6507. */
  6508. private function getScriptTotalEpisodeCount($script) {
  6509. if (empty($script->content)) {
  6510. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6511. }
  6512. $totalEpisodes = count(splitContent($script->content));
  6513. if ($totalEpisodes < 1) {
  6514. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6515. }
  6516. return $totalEpisodes;
  6517. }
  6518. /**
  6519. * 获取剧本总集数
  6520. *
  6521. * @param array $data 包含 script_id(剧本ID)
  6522. * @return array
  6523. */
  6524. public function getScriptTotalEpisodes($data) {
  6525. $script_id = (int)getProp($data, 'script_id', 0);
  6526. if (!$script_id) {
  6527. Utils::throwError('20003:请提供剧本ID');
  6528. }
  6529. // 验证剧本是否存在
  6530. $script = DB::table('mp_scripts')
  6531. ->where('id', $script_id)
  6532. ->where('is_deleted', 0)
  6533. ->first();
  6534. if (!$script) {
  6535. Utils::throwError('20003:剧本不存在');
  6536. }
  6537. return [
  6538. 'script_id' => $script_id,
  6539. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6540. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6541. ];
  6542. }
  6543. /**
  6544. * 获取角色版本历史
  6545. * @param array $data 包含 id(角色ID)
  6546. * @return array 返回版本历史列表
  6547. */
  6548. public function getProductVersions($data) {
  6549. $cpid = Site::getCpid();
  6550. $id = getProp($data, 'id');
  6551. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6552. $role = DB::table('mp_products')
  6553. ->where('id', $id)
  6554. ->where('cpid', $cpid)
  6555. ->where('type', 1)
  6556. ->first();
  6557. if (!$role) Utils::throwError('20003:角色不存在');
  6558. // 获取版本历史
  6559. $versions = json_decode($role->versions, true) ?: [];
  6560. // 添加当前版本作为最新版本
  6561. $currentVersion = [
  6562. 'version' => 0, // 0 表示当前版本
  6563. 'url' => $role->url,
  6564. 'pic_prompt' => $role->pic_prompt,
  6565. 'updated_at' => $role->updated_at,
  6566. 'is_current' => true
  6567. ];
  6568. array_unshift($versions, $currentVersion);
  6569. return $versions;
  6570. }
  6571. /**
  6572. * 恢复到指定版本
  6573. * @param array $data 包含 id(角色ID)、version(版本号)
  6574. * @return bool
  6575. */
  6576. public function restoreProductVersion($data) {
  6577. $uid = Site::getUid();
  6578. $cpid = Site::getCpid();
  6579. $id = getProp($data, 'id');
  6580. $version = getProp($data, 'version');
  6581. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6582. if (!$version) Utils::throwError('20003:版本号不能为空');
  6583. $role = DB::table('mp_products')
  6584. ->where('id', $id)
  6585. ->where('cpid', $cpid)
  6586. ->where('type', 1)
  6587. ->first();
  6588. if (!$role) Utils::throwError('20003:角色不存在');
  6589. // 获取版本历史
  6590. $versions = json_decode($role->versions, true) ?: [];
  6591. // 查找指定版本
  6592. $targetVersion = null;
  6593. foreach ($versions as $v) {
  6594. if ($v['version'] == $version) {
  6595. $targetVersion = $v;
  6596. break;
  6597. }
  6598. }
  6599. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6600. // 先将当前版本保存到历史
  6601. $newVersion = [
  6602. 'version' => count($versions) + 1,
  6603. 'url' => $role->url,
  6604. 'pic_prompt' => $role->pic_prompt,
  6605. 'updated_at' => date('Y-m-d H:i:s'),
  6606. 'updated_by' => $uid
  6607. ];
  6608. array_unshift($versions, $newVersion);
  6609. // 限制版本数量
  6610. if (count($versions) > 10) {
  6611. $versions = array_slice($versions, 0, 10);
  6612. }
  6613. // 恢复到指定版本
  6614. return DB::table('mp_products')
  6615. ->where('id', $id)
  6616. ->where('cpid', $cpid)
  6617. ->update([
  6618. 'url' => $targetVersion['url'],
  6619. 'pic_prompt' => $targetVersion['pic_prompt'],
  6620. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6621. 'updated_at' => date('Y-m-d H:i:s')
  6622. ]);
  6623. }
  6624. public function deleteProduct($data) {
  6625. $uid = Site::getUid();
  6626. $cpid = Site::getCpid();
  6627. $role = Site::getRole();
  6628. $id = getProp($data, 'id');
  6629. if (!$id) Utils::throwError('20003:ID不能为空');
  6630. $ids = explode(',', $id);
  6631. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6632. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6633. $query_uid = $is_public ? 0 : $uid;
  6634. // 如果是公共库操作,需要admin权限
  6635. if ($is_public && $role !== 'admin') {
  6636. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6637. }
  6638. // 检查是否存在且属于当前用户或公共库
  6639. $role = DB::table('mp_products')
  6640. ->whereIn('id', $ids)
  6641. ->where('cpid', $cpid)
  6642. ->where('user_id', $query_uid)
  6643. ->get();
  6644. if (!$role) Utils::throwError('20003:记录不存在');
  6645. return DB::table('mp_products')
  6646. ->where('cpid', $cpid)
  6647. ->where('user_id', $query_uid)
  6648. ->whereIn('id', $ids)
  6649. ->update([
  6650. 'is_deleted' => 1,
  6651. 'updated_at' => date('Y-m-d H:i:s')
  6652. ]);
  6653. }
  6654. public function generateThreeView($data) {
  6655. $uid = Site::getUid();
  6656. $cpid = Site::getCpid();
  6657. $role = Site::getRole();
  6658. $id = getProp($data, 'id');
  6659. if (!$id) Utils::throwError('20003:ID不能为空');
  6660. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6661. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6662. $query_uid = $is_public ? 0 : $uid;
  6663. // 如果是公共库操作,需要admin权限
  6664. if ($is_public && $role !== 'admin') {
  6665. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6666. }
  6667. // 检查是否存在且属于当前用户或公共库
  6668. $product = DB::table('mp_products')
  6669. ->where('id', $id)
  6670. ->where('cpid', $cpid)
  6671. ->where('user_id', $query_uid)
  6672. ->where('type', 1)->first();
  6673. if (!$product) Utils::throwError('20003:资产不存在');
  6674. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6675. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6676. if (!$ref_img_url) {
  6677. // 如果没有传入参考图,使用角色表中的图片
  6678. $ref_img_url = $product->url ?? '';
  6679. if (!$ref_img_url) {
  6680. Utils::throwError('20003:参考图不能为空');
  6681. }
  6682. }
  6683. $pic_prompt = getProp($product, 'pic_prompt');
  6684. if ($pic_prompt) {
  6685. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6686. }
  6687. // 检查参考图是否是正确的图片格式
  6688. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6689. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6690. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6691. if (!in_array($extension, $allowedExtensions)) {
  6692. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6693. }
  6694. // 处理图片模型
  6695. $model = getProp($data, 'model');
  6696. if (!$model) {
  6697. // 使用默认模型
  6698. $model = 'doubao-seedream-5-0-lite-260128';
  6699. }
  6700. // 验证模型是否在可用模型表中
  6701. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6702. Utils::throwError('20003:该模型已不可用,请更换!');
  6703. }
  6704. $ratio = getProp($data, 'ratio', '16:9');
  6705. $resolution = getProp($data, 'resolution', '2k');
  6706. // 定义分辨率和宽高比对应的尺寸映射表
  6707. $sizeMap = [
  6708. '2k' => [
  6709. '1:1' => ['width' => 2048, 'height' => 2048],
  6710. '4:3' => ['width' => 2304, 'height' => 1728],
  6711. '3:4' => ['width' => 1728, 'height' => 2304],
  6712. '16:9' => ['width' => 2848, 'height' => 1600],
  6713. '9:16' => ['width' => 1600, 'height' => 2848],
  6714. '3:2' => ['width' => 2496, 'height' => 1664],
  6715. '2:3' => ['width' => 1664, 'height' => 2496],
  6716. '21:9' => ['width' => 3136, 'height' => 1344],
  6717. ],
  6718. '3k' => [
  6719. '1:1' => ['width' => 3072, 'height' => 3072],
  6720. '4:3' => ['width' => 3456, 'height' => 2592],
  6721. '3:4' => ['width' => 2592, 'height' => 3456],
  6722. '16:9' => ['width' => 4096, 'height' => 2304],
  6723. '9:16' => ['width' => 2304, 'height' => 4096],
  6724. '2:3' => ['width' => 2496, 'height' => 3744],
  6725. '3:2' => ['width' => 3744, 'height' => 2496],
  6726. '21:9' => ['width' => 4704, 'height' => 2016],
  6727. ],
  6728. '4k' => [
  6729. '1:1' => ['width' => 4096, 'height' => 4096],
  6730. '3:4' => ['width' => 3520, 'height' => 4704],
  6731. '4:3' => ['width' => 4704, 'height' => 3520],
  6732. '16:9' => ['width' => 5504, 'height' => 3040],
  6733. '9:16' => ['width' => 3040, 'height' => 5504],
  6734. '2:3' => ['width' => 3328, 'height' => 4992],
  6735. '3:2' => ['width' => 4992, 'height' => 3328],
  6736. '21:9' => ['width' => 6240, 'height' => 2656],
  6737. ],
  6738. ];
  6739. // 参数验证
  6740. $resolution = strtolower($resolution);
  6741. if (!isset($sizeMap[$resolution])) {
  6742. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6743. }
  6744. if (!isset($sizeMap[$resolution][$ratio])) {
  6745. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6746. }
  6747. // 根据 ratio 和 resolution 确定宽高
  6748. $width = $sizeMap[$resolution][$ratio]['width'];
  6749. $height = $sizeMap[$resolution][$ratio]['height'];
  6750. try {
  6751. // 创建图片生成任务
  6752. $params = [
  6753. 'prompt' => $prompt,
  6754. 'model' => $model,
  6755. 'ref_img_urls' => [$ref_img_url],
  6756. 'width' => $width,
  6757. 'height' => $height
  6758. ];
  6759. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6760. $task_id = $task->id;
  6761. if (!$task_id) {
  6762. Utils::throwError('20003:创建图片生成任务失败');
  6763. }
  6764. // 轮询获取结果
  6765. // 只查询数据库,不调用API,不更新任务表
  6766. $start_time = time();
  6767. $timeout = 1800;
  6768. $img_url = '';
  6769. while (time() - $start_time < $timeout) {
  6770. sleep(5);
  6771. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6772. $task = DB::table('mp_generate_pic_tasks')
  6773. ->where('id', $task_id)
  6774. ->first();
  6775. if (!$task) {
  6776. Utils::throwError('20003:任务不存在');
  6777. }
  6778. if ($task->status === 'success' && $task->result_url) {
  6779. $result_urls = is_string($task->result_url)
  6780. ? json_decode($task->result_url, true)
  6781. : $task->result_url;
  6782. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6783. break;
  6784. } elseif ($task->status === 'failed') {
  6785. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6786. }
  6787. // 其他状态继续轮询
  6788. }
  6789. if (empty($img_url)) {
  6790. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6791. }
  6792. // 更新 mp_products 表(不是任务表)
  6793. DB::table('mp_products')
  6794. ->where('id', $id)
  6795. ->where('cpid', $cpid)
  6796. ->update([
  6797. 'three_view_image_url' => $img_url,
  6798. 'updated_at' => date('Y-m-d H:i:s')
  6799. ]);
  6800. return ['three_view_image_url' => $img_url];
  6801. } catch (\Exception $e) {
  6802. dLog('anime')->error('生成三视图失败', [
  6803. 'error' => $e->getMessage()
  6804. ]);
  6805. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6806. Utils::throwError('20003:' . $e->getMessage());
  6807. }
  6808. }
  6809. /**
  6810. * 推送(复制)资产或文件夹到目标位置
  6811. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6812. * @return array 返回推送结果
  6813. */
  6814. public function pushProductOrFolder($data) {
  6815. $uid = Site::getUid();
  6816. $cpid = Site::getCpid();
  6817. $role = Site::getRole();
  6818. $product_id = getProp($data, 'product_id');
  6819. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6820. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6821. if (!$product_id) {
  6822. Utils::throwError('20003:请选择要推送的项目');
  6823. }
  6824. // 查询源项目(只通过cpid查询,不限制user_id)
  6825. $sourceItem = DB::table('mp_products')
  6826. ->where('id', $product_id)
  6827. ->where('cpid', $cpid)
  6828. ->where('is_deleted', 0)
  6829. ->first();
  6830. if (!$sourceItem) {
  6831. Utils::throwError('20003:要推送的项目不存在');
  6832. }
  6833. // 通过user_id判断源是公共库还是个人库
  6834. $source_uid = $sourceItem->user_id;
  6835. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6836. // 验证目标文件夹并确定目标是公共库还是个人库
  6837. $target_level = 0;
  6838. $target_uid = $uid; // 默认推送到个人库
  6839. $target_is_public = 0;
  6840. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6841. if ($target_parent_id > 0) {
  6842. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6843. $targetParent = DB::table('mp_products')
  6844. ->where('id', $target_parent_id)
  6845. ->where('cpid', $cpid)
  6846. ->where('type', 2)
  6847. ->where('is_deleted', 0)
  6848. ->first();
  6849. if (!$targetParent) {
  6850. Utils::throwError('20003:目标文件夹不存在');
  6851. }
  6852. // 通过user_id判断目标是公共库还是个人库
  6853. $target_level = $targetParent->level;
  6854. $target_uid = $targetParent->user_id;
  6855. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6856. // 使用目标文件夹的 product 类型
  6857. $final_product_type = $targetParent->product;
  6858. }
  6859. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6860. else {
  6861. $push_to_public = getProp($data, 'push_to_public');
  6862. if ($push_to_public === '') {
  6863. Utils::throwError('20003:请选择是否推送到公共库');
  6864. }
  6865. if ($push_to_public) {
  6866. $target_uid = 0;
  6867. $target_is_public = 1;
  6868. }
  6869. // 推送到根目录时,必须指定 product 类型
  6870. if ($target_product === null || $target_product === '') {
  6871. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6872. }
  6873. $final_product_type = $target_product;
  6874. }
  6875. // 如果目标是公共库,需要admin权限
  6876. if ($target_is_public && $role !== 'admin') {
  6877. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6878. }
  6879. // 权限验证:验证是否符合允许的推送规则
  6880. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6881. try {
  6882. DB::beginTransaction();
  6883. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6884. if ($sourceItem->type == 1) {
  6885. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6886. DB::commit();
  6887. return [
  6888. 'product_id' => $newId,
  6889. ];
  6890. }
  6891. // 如果是文件夹,递归复制(支持跨类型推送)
  6892. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6893. DB::commit();
  6894. return [
  6895. 'product_id' => $newFolderId,
  6896. ];
  6897. } catch (\Exception $e) {
  6898. DB::rollBack();
  6899. dLog('anime')->error('推送失败', [
  6900. 'error' => $e->getMessage(),
  6901. 'product_id' => $product_id
  6902. ]);
  6903. Utils::throwError('20003:' . $e->getMessage());
  6904. }
  6905. }
  6906. /**
  6907. * 验证推送权限
  6908. * 允许的推送规则:
  6909. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6910. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6911. * 3. 公共库推送给公共库(公共库 → 公共库)
  6912. *
  6913. * @param int $source_uid 源的user_id
  6914. * @param int $target_uid 目标的user_id
  6915. * @param int $current_uid 当前用户ID
  6916. * @throws \Exception
  6917. */
  6918. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6919. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6920. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6921. return; // 允许
  6922. }
  6923. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6924. if ($source_uid == 0 && $target_uid == $current_uid) {
  6925. return; // 允许
  6926. }
  6927. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6928. if ($source_uid == 0 && $target_uid == 0) {
  6929. return; // 允许
  6930. }
  6931. // 其他情况都不允许
  6932. if ($source_uid != 0 && $source_uid != $current_uid) {
  6933. // 源是别人的个人库
  6934. Utils::throwError('20003:无权限访问该资产');
  6935. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6936. // 个人库推送给公共库(不允许)
  6937. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6938. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6939. // 不同用户的个人库之间推送(不允许)
  6940. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6941. } else {
  6942. // 其他未知情况
  6943. Utils::throwError('20003:不允许的推送操作');
  6944. }
  6945. }
  6946. /**
  6947. * 复制单个资产
  6948. * @param object $sourceProduct 源资产对象
  6949. * @param int $targetParentId 目标父文件夹ID
  6950. * @param int $targetLevel 目标层级
  6951. * @param int $cpid 公司ID
  6952. * @param int $targetUid 目标用户ID
  6953. * @return int 返回新资产ID
  6954. */
  6955. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6956. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6957. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6958. $newProductData = [
  6959. 'user_id' => $targetUid,
  6960. 'cpid' => $cpid,
  6961. 'type' => 1,
  6962. 'parent_id' => $targetParentId,
  6963. 'level' => $targetLevel,
  6964. 'product_name' => $sourceProduct->product_name,
  6965. 'url' => $sourceProduct->url,
  6966. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6967. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6968. 'product' => $finalProductType,
  6969. 'versions' => $sourceProduct->versions ?? '',
  6970. 'sort_order' => time(),
  6971. 'is_deleted' => 0,
  6972. 'created_at' => date('Y-m-d H:i:s'),
  6973. 'updated_at' => date('Y-m-d H:i:s')
  6974. ];
  6975. return DB::table('mp_products')->insertGetId($newProductData);
  6976. }
  6977. /**
  6978. * 递归复制文件夹及其子项
  6979. * @param object $sourceFolder 源文件夹对象
  6980. * @param int $targetParentId 目标父文件夹ID
  6981. * @param int $targetLevel 目标层级
  6982. * @param int $cpid 公司ID
  6983. * @param int $targetUid 目标用户ID
  6984. * @param int $sourceUid 源用户ID
  6985. * @return int 返回新文件夹ID
  6986. */
  6987. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6988. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6989. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6990. // 创建新文件夹
  6991. $newFolderData = [
  6992. 'user_id' => $targetUid,
  6993. 'cpid' => $cpid,
  6994. 'type' => 2,
  6995. 'parent_id' => $targetParentId,
  6996. 'level' => $targetLevel,
  6997. 'product_name' => $sourceFolder->product_name,
  6998. 'product' => $finalProductType,
  6999. 'sort_order' => time(),
  7000. 'is_deleted' => 0,
  7001. 'created_at' => date('Y-m-d H:i:s'),
  7002. 'updated_at' => date('Y-m-d H:i:s')
  7003. ];
  7004. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7005. // 获取源文件夹下的所有子项
  7006. $children = DB::table('mp_products')
  7007. ->where('parent_id', $sourceFolder->id)
  7008. ->where('cpid', $cpid)
  7009. ->where('user_id', $sourceUid)
  7010. ->where('is_deleted', 0)
  7011. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7012. ->get();
  7013. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7014. foreach ($children as $child) {
  7015. if ($child->type == 1) {
  7016. // 资产
  7017. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7018. } else {
  7019. // 文件夹
  7020. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7021. }
  7022. }
  7023. return $newFolderId;
  7024. }
  7025. /**
  7026. * 保存剧本资产关联关系
  7027. * @param array $data 请求参数
  7028. * @return bool
  7029. */
  7030. public function saveScriptProducts($data) {
  7031. $uid = Site::getUid();
  7032. $cpid = Site::getCpid();
  7033. $script_id = getProp($data, 'script_id');
  7034. $products = getProp($data, 'products', []);
  7035. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7036. if (!$script_id) {
  7037. Utils::throwError('20003:请提供剧本ID');
  7038. }
  7039. // 验证剧本是否存在
  7040. $script = DB::table('mp_scripts')
  7041. ->where('id', $script_id)
  7042. ->where('is_deleted', 0)
  7043. ->first();
  7044. if (!$script) {
  7045. Utils::throwError('20003:剧本不存在');
  7046. }
  7047. // 处理图片模型
  7048. $model = getProp($data, 'model');
  7049. if (!$model) {
  7050. // 使用默认模型
  7051. $model = 'doubao-seedream-5-0-lite-260128';
  7052. }
  7053. // 验证模型是否在可用模型表中
  7054. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7055. Utils::throwError('20003:该模型已不可用,请更换!');
  7056. }
  7057. $ratio = getProp($data, 'ratio', '9:16');
  7058. $resolution = getProp($data, 'resolution', '2k');
  7059. // 定义分辨率和宽高比对应的尺寸映射表
  7060. $sizeMap = [
  7061. '2k' => [
  7062. '1:1' => ['width' => 2048, 'height' => 2048],
  7063. '4:3' => ['width' => 2304, 'height' => 1728],
  7064. '3:4' => ['width' => 1728, 'height' => 2304],
  7065. '16:9' => ['width' => 2848, 'height' => 1600],
  7066. '9:16' => ['width' => 1600, 'height' => 2848],
  7067. '3:2' => ['width' => 2496, 'height' => 1664],
  7068. '2:3' => ['width' => 1664, 'height' => 2496],
  7069. '21:9' => ['width' => 3136, 'height' => 1344],
  7070. ],
  7071. '3k' => [
  7072. '1:1' => ['width' => 3072, 'height' => 3072],
  7073. '4:3' => ['width' => 3456, 'height' => 2592],
  7074. '3:4' => ['width' => 2592, 'height' => 3456],
  7075. '16:9' => ['width' => 4096, 'height' => 2304],
  7076. '9:16' => ['width' => 2304, 'height' => 4096],
  7077. '2:3' => ['width' => 2496, 'height' => 3744],
  7078. '3:2' => ['width' => 3744, 'height' => 2496],
  7079. '21:9' => ['width' => 4704, 'height' => 2016],
  7080. ],
  7081. '4k' => [
  7082. '1:1' => ['width' => 4096, 'height' => 4096],
  7083. '3:4' => ['width' => 3520, 'height' => 4704],
  7084. '4:3' => ['width' => 4704, 'height' => 3520],
  7085. '16:9' => ['width' => 5504, 'height' => 3040],
  7086. '9:16' => ['width' => 3040, 'height' => 5504],
  7087. '2:3' => ['width' => 3328, 'height' => 4992],
  7088. '3:2' => ['width' => 4992, 'height' => 3328],
  7089. '21:9' => ['width' => 6240, 'height' => 2656],
  7090. ],
  7091. ];
  7092. // 参数验证
  7093. $resolution = strtolower($resolution);
  7094. if (!isset($sizeMap[$resolution])) {
  7095. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7096. }
  7097. if (!isset($sizeMap[$resolution][$ratio])) {
  7098. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7099. }
  7100. // 根据 ratio 和 resolution 确定宽高
  7101. $width = $sizeMap[$resolution][$ratio]['width'];
  7102. $height = $sizeMap[$resolution][$ratio]['height'];
  7103. $script_name = $script->script_name ?? 'script_' . $script_id;
  7104. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  7105. $taskCenterId = $this->createScriptProductTaskCenter(
  7106. $uid,
  7107. $cpid,
  7108. $script_id,
  7109. $products,
  7110. $model,
  7111. $ratio,
  7112. $resolution,
  7113. $auto_generate_images
  7114. );
  7115. // 检查是否已经有该剧本的资产数据
  7116. $existingMappings = DB::table('mp_script_product_mappings')
  7117. ->where('script_id', $script_id)
  7118. ->get();
  7119. if ($existingMappings->isNotEmpty()) {
  7120. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7121. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7122. // 查询这些资产的图片生成任务状态
  7123. $productsWithTasks = DB::table('mp_products')
  7124. ->whereIn('id', $productIds)
  7125. ->where('is_deleted', 0)
  7126. ->get();
  7127. $productTaskMap = [];
  7128. $typeFolderIds = [];
  7129. $hasAllTasks = true;
  7130. foreach ($productsWithTasks as $product) {
  7131. // 收集类型文件夹ID
  7132. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7133. $parentFolder = DB::table('mp_products')
  7134. ->where('id', $product->parent_id)
  7135. ->where('type', 2)
  7136. ->first();
  7137. if ($parentFolder) {
  7138. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7139. }
  7140. }
  7141. // 检查是否有图片生成任务
  7142. if (!empty($product->pic_task_id)) {
  7143. $productTaskMap[$product->id] = $product->pic_task_id;
  7144. } else if($product->url && $product->pic_task_status == '生成成功') {
  7145. continue;
  7146. } else {
  7147. // 有资产没有图片任务
  7148. $hasAllTasks = false;
  7149. }
  7150. }
  7151. // 如果所有资产都有任务ID,直接轮询返回结果
  7152. if ($hasAllTasks && !empty($productTaskMap)) {
  7153. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7154. 'script_id' => $script_id,
  7155. 'script_name' => $script_name,
  7156. 'product_count' => count($productTaskMap)
  7157. ]);
  7158. // 直接返回 SSE 流轮询结果
  7159. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7160. }
  7161. // 如果部分资产没有任务ID,只为这些资产创建任务
  7162. if (!$hasAllTasks && $auto_generate_images) {
  7163. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7164. 'script_id' => $script_id,
  7165. 'script_name' => $script_name
  7166. ]);
  7167. // 开启事务
  7168. DB::beginTransaction();
  7169. try {
  7170. foreach ($productsWithTasks as $product) {
  7171. // 跳过已有任务的资产
  7172. if (!empty($product->pic_task_id)) {
  7173. continue;
  7174. }
  7175. // 跳过没有提示词的资产
  7176. if (empty($product->pic_prompt)) {
  7177. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7178. 'product_id' => $product->id,
  7179. 'product_name' => $product->product_name
  7180. ]);
  7181. continue;
  7182. }
  7183. try {
  7184. // 创建图片生成任务
  7185. $params = [
  7186. 'prompt' => $product->pic_prompt,
  7187. 'model' => $model,
  7188. 'ref_img_urls' => [],
  7189. 'width' => $width,
  7190. 'height' => $height
  7191. ];
  7192. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7193. $task_id = $task->id;
  7194. if ($task_id) {
  7195. $productTaskMap[$product->id] = $task_id;
  7196. // 在事务中更新资产表的任务ID和状态
  7197. DB::table('mp_products')
  7198. ->where('id', $product->id)
  7199. ->update([
  7200. 'pic_task_id' => $task_id,
  7201. 'pic_task_status' => '生成中',
  7202. 'updated_at' => now()
  7203. ]);
  7204. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7205. 'product_id' => $product->id,
  7206. 'task_id' => $task_id
  7207. ]);
  7208. }
  7209. } catch (\Exception $e) {
  7210. dLog('anime')->error('创建资产图片生成任务失败', [
  7211. 'product_id' => $product->id,
  7212. 'error' => $e->getMessage()
  7213. ]);
  7214. // 标记为失败(仍在事务中)
  7215. DB::table('mp_products')
  7216. ->where('id', $product->id)
  7217. ->update([
  7218. 'pic_task_status' => '生成失败',
  7219. 'updated_at' => now()
  7220. ]);
  7221. }
  7222. }
  7223. // 提交事务
  7224. DB::commit();
  7225. // 如果有新创建的任务,返回 SSE 流
  7226. if (!empty($productTaskMap)) {
  7227. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7228. }
  7229. } catch (\Exception $e) {
  7230. // 回滚事务
  7231. DB::rollback();
  7232. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7233. 'script_id' => $script_id,
  7234. 'error' => $e->getMessage()
  7235. ]);
  7236. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7237. }
  7238. }
  7239. // 如果不需要生成图片,返回已存在的信息
  7240. $resultData = [
  7241. 'success' => true,
  7242. 'message' => '剧本资产已存在',
  7243. 'script_id' => $script_id,
  7244. 'script_name' => $script_name,
  7245. 'type_folder_ids' => $typeFolderIds,
  7246. 'existing_products' => count($productIds),
  7247. 'tasks_count' => count($productTaskMap),
  7248. 'task_center_id' => $taskCenterId
  7249. ];
  7250. // 接口已正常完成,更新任务中心状态和结果
  7251. if ($taskCenterId) {
  7252. $this->taskCenterService->updateTask($taskCenterId, [
  7253. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7254. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7255. 'error_message' => null
  7256. ]);
  7257. }
  7258. return $resultData;
  7259. }
  7260. // 解析 products(可能是 JSON 字符串或数组)
  7261. if (is_string($products)) {
  7262. $products = json_decode($products, true);
  7263. if (json_last_error() !== JSON_ERROR_NONE) {
  7264. Utils::throwError('20003:产品数据格式错误');
  7265. }
  7266. }
  7267. if (!is_array($products) || empty($products)) {
  7268. Utils::throwError('20003:产品数据不能为空');
  7269. }
  7270. // 以下是原有的创建逻辑...
  7271. // 开启事务
  7272. DB::beginTransaction();
  7273. try {
  7274. $now = now();
  7275. $mappingRecords = [];
  7276. $createdProductIds = []; // 记录所有创建的资产ID
  7277. // 获取剧本名称
  7278. $script_name = $script->script_name ?? 'script_' . $script_id;
  7279. // 存储每个类型的根文件夹ID
  7280. $typeFolderIds = [];
  7281. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7282. foreach ($products as $productGroup) {
  7283. $type = getProp($productGroup, 'type');
  7284. $title = getProp($productGroup, 'title', '');
  7285. $content = getProp($productGroup, 'content', []);
  7286. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7287. continue;
  7288. }
  7289. // 为当前类型创建根文件夹(如果还未创建)
  7290. if (!isset($typeFolderIds[$type])) {
  7291. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7292. 'user_id' => $uid,
  7293. 'cpid' => $cpid,
  7294. 'type' => 2, // 1.资产 2文件夹
  7295. 'product' => $type, // 1.主体 2.场景 3.道具
  7296. 'parent_id' => 0, // 根文件夹,parent_id=0
  7297. 'level' => 1, // 第一层级
  7298. 'product_name' => $script_name,
  7299. 'sort_order' => time() + $type,
  7300. 'is_deleted' => 0,
  7301. 'created_at' => $now,
  7302. 'updated_at' => $now
  7303. ]);
  7304. }
  7305. $folder_id = $typeFolderIds[$type];
  7306. // 获取表头(第一行)并查找关键列的位置
  7307. $headers = $content[0];
  7308. $nameColumnIndex = -1; // 资产名称列索引
  7309. $sequenceColumnIndex = -1; // 使用范围列索引
  7310. $promptColumnIndex = -1; // 参考提示词列索引
  7311. foreach ($headers as $index => $header) {
  7312. // 查找"资产名称"列
  7313. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7314. $nameColumnIndex = $index;
  7315. }
  7316. // 查找"使用范围"列
  7317. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7318. $sequenceColumnIndex = $index;
  7319. }
  7320. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7321. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7322. $promptColumnIndex = $index;
  7323. }
  7324. }
  7325. // 验证必要的列是否都找到了
  7326. if ($nameColumnIndex === -1) {
  7327. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7328. continue;
  7329. }
  7330. if ($sequenceColumnIndex === -1) {
  7331. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7332. continue;
  7333. }
  7334. // 跳过表头,解析每一行数据
  7335. for ($i = 1; $i < count($content); $i++) {
  7336. $row = $content[$i];
  7337. // 确保行数据有效
  7338. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7339. continue;
  7340. }
  7341. // 根据动态查找的列索引提取数据
  7342. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7343. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7344. $pic_prompt = '';
  7345. // 提取参考提示词(如果找到了该列)
  7346. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7347. $pic_prompt = trim($row[$promptColumnIndex]);
  7348. }
  7349. // 解析使用范围(逗号分隔的序号)
  7350. $sequences = [];
  7351. if (!empty($sequence_str)) {
  7352. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7353. foreach ($sequenceParts as $part) {
  7354. if (is_numeric($part)) {
  7355. $sequences[] = (int)$part;
  7356. }
  7357. }
  7358. }
  7359. if (empty($product_name)) {
  7360. continue;
  7361. }
  7362. // 处理product_name两边的符号
  7363. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7364. // 如果名称不存在或仅剩占位符号,则跳过
  7365. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7366. dLog('anime')->warning('资产名称无效,跳过保存', [
  7367. 'script_id' => $script_id,
  7368. 'type' => $type,
  7369. 'product_name' => $product_name
  7370. ]);
  7371. continue;
  7372. }
  7373. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7374. $product_id = DB::table('mp_products')->insertGetId([
  7375. 'product_name' => $product_name,
  7376. 'type' => 1, // 1=资产 2.文件夹
  7377. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7378. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7379. 'level' => 2, // 第二层级
  7380. 'pic_prompt' => $pic_prompt,
  7381. 'user_id' => $uid,
  7382. 'cpid' => $cpid,
  7383. 'sort_order' => time(),
  7384. 'is_deleted' => 0,
  7385. 'created_at' => $now,
  7386. 'updated_at' => $now,
  7387. ]);
  7388. // 记录创建的资产ID
  7389. $createdProductIds[] = $product_id;
  7390. // 为每个序号创建映射记录
  7391. if (!empty($sequences)) {
  7392. foreach ($sequences as $sequence) {
  7393. $mappingRecords[] = [
  7394. 'script_id' => $script_id,
  7395. 'product_id' => $product_id,
  7396. 'episode_number' => $sequence,
  7397. 'created_at' => $now,
  7398. 'updated_at' => $now,
  7399. ];
  7400. }
  7401. } else {
  7402. // 如果没有指定序号,创建一个默认映射(序号为0)
  7403. $mappingRecords[] = [
  7404. 'script_id' => $script_id,
  7405. 'product_id' => $product_id,
  7406. 'episode_number' => 0,
  7407. 'created_at' => $now,
  7408. 'updated_at' => $now,
  7409. ];
  7410. }
  7411. }
  7412. }
  7413. if (empty($mappingRecords)) {
  7414. Utils::throwError('20003:没有有效的产品数据');
  7415. }
  7416. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7417. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7418. // 剧本已有资产,同步更新is_products标记
  7419. DB::table('mp_scripts')->where('id', $script_id)->update([
  7420. 'is_products' => 1,
  7421. 'updated_at' => $now
  7422. ]);
  7423. // 如果需要自动生成图片,在事务中创建图片生成任务
  7424. $productTaskMap = [];
  7425. if ($auto_generate_images && !empty($createdProductIds)) {
  7426. // 查询所有创建的资产
  7427. $productsToGenerate = DB::table('mp_products')
  7428. ->whereIn('id', $createdProductIds)
  7429. ->where('is_deleted', 0)
  7430. ->get();
  7431. foreach ($productsToGenerate as $product) {
  7432. if (empty($product->pic_prompt)) {
  7433. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7434. 'product_id' => $product->id,
  7435. 'product_name' => $product->product_name
  7436. ]);
  7437. continue;
  7438. }
  7439. try {
  7440. // 创建图片生成任务
  7441. $params = [
  7442. 'prompt' => $product->pic_prompt,
  7443. 'model' => $model,
  7444. 'ref_img_urls' => [],
  7445. 'width' => $width,
  7446. 'height' => $height
  7447. ];
  7448. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7449. $task_id = $task->id;
  7450. if ($task_id) {
  7451. $productTaskMap[$product->id] = $task_id;
  7452. // 在事务中更新资产表的任务ID和状态
  7453. DB::table('mp_products')
  7454. ->where('id', $product->id)
  7455. ->update([
  7456. 'pic_task_id' => $task_id,
  7457. 'pic_task_status' => '生成中',
  7458. 'updated_at' => now()
  7459. ]);
  7460. dLog('anime')->info('创建资产图片生成任务', [
  7461. 'product_id' => $product->id,
  7462. 'task_id' => $task_id
  7463. ]);
  7464. }
  7465. } catch (\Exception $e) {
  7466. dLog('anime')->error('创建资产图片生成任务失败', [
  7467. 'product_id' => $product->id,
  7468. 'error' => $e->getMessage()
  7469. ]);
  7470. // 标记为失败(仍在事务中)
  7471. DB::table('mp_products')
  7472. ->where('id', $product->id)
  7473. ->update([
  7474. 'pic_task_status' => '生成失败',
  7475. 'updated_at' => now()
  7476. ]);
  7477. }
  7478. }
  7479. }
  7480. // 提交事务
  7481. DB::commit();
  7482. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7483. if ($auto_generate_images && !empty($productTaskMap)) {
  7484. // 返回 SSE 流(事务外轮询)
  7485. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7486. }
  7487. // 如果不需要生成图片,返回普通结果
  7488. $resultData = [
  7489. 'success' => true,
  7490. 'type_folder_ids' => $typeFolderIds,
  7491. 'inserted_count' => $insertedCount,
  7492. 'total_records' => count($mappingRecords),
  7493. 'created_products' => count($createdProductIds),
  7494. 'image_tasks_created' => count($productTaskMap),
  7495. 'task_center_id' => $taskCenterId
  7496. ];
  7497. // 接口已正常完成,更新任务中心状态和结果
  7498. if ($taskCenterId) {
  7499. $this->taskCenterService->updateTask($taskCenterId, [
  7500. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7501. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7502. 'error_message' => null
  7503. ]);
  7504. }
  7505. return $resultData;
  7506. } catch (\Exception $e) {
  7507. // 回滚事务
  7508. DB::rollback();
  7509. // 更新任务中心状态为失败
  7510. if (!empty($taskCenterId)) {
  7511. $this->taskCenterService->updateTask($taskCenterId, [
  7512. 'status' => MpTaskCenter::STATUS_FAILED,
  7513. 'error_message' => $e->getMessage()
  7514. ]);
  7515. }
  7516. // 记录错误日志
  7517. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7518. 'script_id' => $script_id,
  7519. 'error' => $e->getMessage(),
  7520. 'trace' => $e->getTraceAsString()
  7521. ]);
  7522. // 统一使用 Utils::throwError 抛出错误
  7523. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7524. }
  7525. }
  7526. /**
  7527. * 根据入参创建或复用任务中心记录
  7528. *
  7529. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  7530. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  7531. * 避免生成重复任务。
  7532. *
  7533. * @param int|string $uid
  7534. * @param int|string $cpid
  7535. * @param int|string $script_id
  7536. * @param mixed $products
  7537. * @param string $model
  7538. * @param string $ratio
  7539. * @param string $resolution
  7540. * @param mixed $auto_generate_images
  7541. * @return int 任务中心ID
  7542. */
  7543. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  7544. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  7545. if (is_string($products)) {
  7546. $decoded = json_decode($products, true);
  7547. if (json_last_error() === JSON_ERROR_NONE) {
  7548. $products = $decoded;
  7549. }
  7550. }
  7551. $params = [
  7552. 'script_id' => (int)$script_id,
  7553. 'products' => $products,
  7554. 'model' => $model,
  7555. 'ratio' => $ratio,
  7556. 'resolution' => $resolution,
  7557. 'auto_generate_images' => (bool)$auto_generate_images,
  7558. ];
  7559. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  7560. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  7561. $existing = DB::table('mp_task_center')
  7562. ->where('uid', (int)$uid)
  7563. ->where('cpid', (int)$cpid)
  7564. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7565. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  7566. ->where('params_md5', $paramsMd5)
  7567. ->orderBy('id', 'desc')
  7568. ->first();
  7569. if ($existing) {
  7570. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  7571. 'script_id' => $script_id,
  7572. 'task_center_id' => $existing->id,
  7573. 'params_md5' => $paramsMd5,
  7574. ]);
  7575. return (int)$existing->id;
  7576. }
  7577. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  7578. $now = date('Y-m-d H:i:s');
  7579. DB::table('mp_task_center')->insertOrIgnore([
  7580. 'uid' => (int)$uid,
  7581. 'cpid' => (int)$cpid,
  7582. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  7583. 'title' => '剧本资产图片生成',
  7584. 'ref_task_id' => 0,
  7585. 'status' => MpTaskCenter::STATUS_PROCESSING,
  7586. 'result' => null,
  7587. 'error_message' => null,
  7588. 'prompt' => null,
  7589. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  7590. 'params_md5' => $paramsMd5,
  7591. 'created_at' => $now,
  7592. 'updated_at' => $now,
  7593. ]);
  7594. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  7595. $taskId = (int)DB::table('mp_task_center')
  7596. ->where('uid', (int)$uid)
  7597. ->where('cpid', (int)$cpid)
  7598. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7599. ->where('params_md5', $paramsMd5)
  7600. ->orderBy('id', 'desc')
  7601. ->value('id');
  7602. dLog('anime')->info('创建任务中心记录', [
  7603. 'script_id' => $script_id,
  7604. 'task_center_id' => $taskId,
  7605. 'params_md5' => $paramsMd5,
  7606. ]);
  7607. return $taskId;
  7608. }
  7609. /**
  7610. * 任务结束时更新任务中心记录的状态和结果
  7611. *
  7612. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  7613. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  7614. *
  7615. * @param int|null $taskCenterId
  7616. * @param array $resultData 接口返回结果数组
  7617. * @param bool $timeout 是否超时未完成
  7618. */
  7619. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  7620. if (!$taskCenterId) {
  7621. return;
  7622. }
  7623. $stats = $resultData['stats'] ?? [];
  7624. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  7625. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  7626. $failedCount = $completedCount - $successCount;
  7627. // 与接口返回给客户端的结果保持一致
  7628. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  7629. if ($timeout) {
  7630. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7631. 'status' => MpTaskCenter::STATUS_FAILED,
  7632. 'result' => $result,
  7633. 'error_message' => '部分任务超时,请稍后查看结果',
  7634. ]);
  7635. return;
  7636. }
  7637. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7638. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  7639. 'result' => $result,
  7640. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  7641. ]);
  7642. }
  7643. /**
  7644. * 批量为剧本资产生成图片
  7645. *
  7646. * @param array $data 请求参数
  7647. * @return \Generator 返回 SSE 流
  7648. */
  7649. public function batchGenerateProductImages($data) {
  7650. $script_id = getProp($data, 'script_id');
  7651. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7652. if (!$script_id) {
  7653. Utils::throwError('20003:请提供剧本ID');
  7654. }
  7655. // 验证剧本是否存在
  7656. $script = DB::table('mp_scripts')
  7657. ->where('id', $script_id)
  7658. ->where('is_deleted', 0)
  7659. ->first();
  7660. if (!$script) {
  7661. Utils::throwError('20003:剧本不存在');
  7662. }
  7663. $script_name = $script->script_name ?? 'script_' . $script_id;
  7664. // 获取需要生成图片的所有资产
  7665. $products = DB::table('mp_products')
  7666. ->whereIn('parent_id', array_values($type_folder_ids))
  7667. ->where('is_deleted', 0)
  7668. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7669. ->get();
  7670. if ($products->isEmpty()) {
  7671. Utils::throwError('20003:没有找到需要生成图片的资产');
  7672. }
  7673. // 默认参数
  7674. $model = 'doubao-seedream-5-0-lite-260128';
  7675. $width = 1600;
  7676. $height = 2848;
  7677. // 开始为每个资产创建图片生成任务
  7678. $taskIds = [];
  7679. $productTaskMap = []; // 资产ID到任务ID的映射
  7680. foreach ($products as $product) {
  7681. if (empty($product->pic_prompt)) {
  7682. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7683. continue;
  7684. }
  7685. try {
  7686. // 创建图片生成任务
  7687. $params = [
  7688. 'prompt' => $product->pic_prompt,
  7689. 'model' => $model,
  7690. 'ref_img_urls' => [],
  7691. 'width' => $width,
  7692. 'height' => $height
  7693. ];
  7694. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7695. $task_id = $task->id;
  7696. if ($task_id) {
  7697. $taskIds[] = $task_id;
  7698. $productTaskMap[$product->id] = $task_id;
  7699. // 更新资产表的任务ID和状态
  7700. DB::table('mp_products')
  7701. ->where('id', $product->id)
  7702. ->update([
  7703. 'pic_task_id' => $task_id,
  7704. 'pic_task_status' => '生成中',
  7705. 'updated_at' => now()
  7706. ]);
  7707. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7708. }
  7709. } catch (\Exception $e) {
  7710. dLog('anime')->error('创建资产图片生成任务失败', [
  7711. 'product_id' => $product->id,
  7712. 'error' => $e->getMessage()
  7713. ]);
  7714. // 标记为失败
  7715. DB::table('mp_products')
  7716. ->where('id', $product->id)
  7717. ->update([
  7718. 'pic_task_status' => '生成失败',
  7719. 'updated_at' => now()
  7720. ]);
  7721. }
  7722. }
  7723. if (empty($taskIds)) {
  7724. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7725. }
  7726. // 返回 SSE 流
  7727. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7728. }
  7729. /**
  7730. * 轮询资产图片生成任务状态(SSE流式返回)
  7731. * 只通过查询数据库获取任务状态,不主动调用API
  7732. *
  7733. * @param int $script_id 剧本ID
  7734. * @param string $script_name 剧本名称
  7735. * @param array $productTaskMap 资产ID到任务ID的映射
  7736. * @param array $type_folder_ids 类型文件夹ID映射
  7737. * @return \Generator
  7738. */
  7739. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null) {
  7740. $startTime = time();
  7741. $timeout = 1800; // 30分钟超时
  7742. $pollInterval = 10; // 10秒轮询一次
  7743. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7744. // 定义类型名称映射
  7745. $typeNames = [
  7746. 1 => 'roles', // 角色
  7747. 2 => 'scenes', // 场景
  7748. 3 => 'props' // 道具
  7749. ];
  7750. while (time() - $startTime < $timeout) {
  7751. sleep($pollInterval);
  7752. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7753. $mappings = DB::table('mp_script_product_mappings')
  7754. ->where('script_id', $script_id)
  7755. ->pluck('product_id')
  7756. ->unique()
  7757. ->toArray();
  7758. if (empty($mappings)) {
  7759. dLog('anime')->warning('该剧本没有关联的资产', [
  7760. 'script_id' => $script_id,
  7761. 'script_name' => $script_name
  7762. ]);
  7763. break;
  7764. }
  7765. // 查询所有资产的当前状态
  7766. $products = DB::table('mp_products')
  7767. ->whereIn('id', $mappings)
  7768. ->where('is_deleted', 0)
  7769. ->get();
  7770. // 统计各类型的状态(使用类型名称作为键名)
  7771. $stats = [
  7772. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7773. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7774. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7775. ];
  7776. $allCompleted = true;
  7777. $hasStatusChange = false;
  7778. foreach ($products as $product) {
  7779. $type = $product->product;
  7780. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7781. // 如果类型名称不在 stats 中,初始化
  7782. if (!isset($stats[$typeName])) {
  7783. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7784. }
  7785. $stats[$typeName]['total']++;
  7786. $task_id = $product->pic_task_id;
  7787. $currentStatus = $product->pic_task_status;
  7788. // 检查状态是否有变化
  7789. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7790. $hasStatusChange = true;
  7791. $lastStatus[$product->id] = $currentStatus;
  7792. }
  7793. // 如果是生成中,查询任务表状态
  7794. if ($currentStatus === '生成中' && $task_id) {
  7795. // 只查询数据库,不调用API
  7796. $task = DB::table('mp_generate_pic_tasks')
  7797. ->where('id', $task_id)
  7798. ->first();
  7799. if ($task) {
  7800. // 检查任务状态
  7801. if ($task->status === 'success' && $task->result_url) {
  7802. // 解析图片URL
  7803. $result_urls = $task->result_url;
  7804. if (is_string($result_urls)) {
  7805. $result_urls = json_decode($result_urls, true);
  7806. }
  7807. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7808. // 更新资产表状态
  7809. DB::table('mp_products')
  7810. ->where('id', $product->id)
  7811. ->update([
  7812. 'pic_task_status' => '生成成功',
  7813. 'url' => $img_url,
  7814. 'updated_at' => now()
  7815. ]);
  7816. $stats[$typeName]['success']++;
  7817. $stats[$typeName]['completed']++;
  7818. $hasStatusChange = true;
  7819. dLog('anime')->info('资产图片生成成功', [
  7820. 'product_id' => $product->id,
  7821. 'task_id' => $task_id,
  7822. 'img_url' => $img_url
  7823. ]);
  7824. } elseif ($task->status === 'failed') {
  7825. // 更新资产表状态
  7826. DB::table('mp_products')
  7827. ->where('id', $product->id)
  7828. ->update([
  7829. 'pic_task_status' => '生成失败',
  7830. 'updated_at' => now()
  7831. ]);
  7832. $stats[$typeName]['completed']++;
  7833. $hasStatusChange = true;
  7834. dLog('anime')->warning('资产图片生成失败', [
  7835. 'product_id' => $product->id,
  7836. 'task_id' => $task_id,
  7837. 'error' => $task->error_message ?? '未知错误'
  7838. ]);
  7839. } else {
  7840. // 任务还在处理中
  7841. $allCompleted = false;
  7842. }
  7843. } else {
  7844. // 任务不存在,标记为失败
  7845. DB::table('mp_products')
  7846. ->where('id', $product->id)
  7847. ->update([
  7848. 'pic_task_status' => '生成失败',
  7849. 'updated_at' => now()
  7850. ]);
  7851. $stats[$type]['completed']++;
  7852. $hasStatusChange = true;
  7853. dLog('anime')->error('图片生成任务不存在', [
  7854. 'product_id' => $product->id,
  7855. 'task_id' => $task_id
  7856. ]);
  7857. }
  7858. } elseif ($currentStatus === '生成成功') {
  7859. $stats[$typeName]['success']++;
  7860. $stats[$typeName]['completed']++;
  7861. } elseif ($currentStatus === '生成失败') {
  7862. $stats[$typeName]['completed']++;
  7863. } else {
  7864. // 其他状态也认为未完成
  7865. $allCompleted = false;
  7866. }
  7867. }
  7868. // 移除没有数据的类型(total=0)
  7869. foreach ($stats as $typeName => $stat) {
  7870. if ($stat['total'] === 0) {
  7871. unset($stats[$typeName]);
  7872. }
  7873. }
  7874. // 如果有状态变化,发送 SSE 更新
  7875. if ($hasStatusChange) {
  7876. $eventType = $allCompleted ? 'complete' : 'update';
  7877. $response = [
  7878. 'type' => $eventType,
  7879. 'script_id' => $script_id,
  7880. 'script_name' => $script_name,
  7881. 'stats' => $stats,
  7882. 'timestamp' => date('Y-m-d H:i:s')
  7883. ];
  7884. if ($taskCenterId) {
  7885. $response['task_center_id'] = $taskCenterId;
  7886. }
  7887. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7888. dLog('anime')->info('SSE更新', [
  7889. 'event_type' => $eventType,
  7890. 'script_id' => $script_id,
  7891. 'script_name' => $script_name,
  7892. 'stats' => $stats
  7893. ]);
  7894. if ($allCompleted) {
  7895. dLog('anime')->info('所有资产图片生成任务已完成', [
  7896. 'script_id' => $script_id,
  7897. 'script_name' => $script_name,
  7898. 'stats' => $stats
  7899. ]);
  7900. // 全部任务完成,更新任务中心状态和结果
  7901. $this->finishScriptProductTask($taskCenterId, $response);
  7902. break;
  7903. }
  7904. }
  7905. }
  7906. // 超时处理
  7907. if (time() - $startTime >= $timeout && !$allCompleted) {
  7908. $response = [
  7909. 'type' => 'timeout',
  7910. 'message' => '部分任务超时,请稍后查看结果',
  7911. 'script_id' => $script_id,
  7912. 'script_name' => $script_name,
  7913. 'timestamp' => date('Y-m-d H:i:s')
  7914. ];
  7915. if ($taskCenterId) {
  7916. $response['task_center_id'] = $taskCenterId;
  7917. }
  7918. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7919. dLog('anime')->warning('资产图片生成任务超时', [
  7920. 'script_id' => $script_id,
  7921. 'script_name' => $script_name,
  7922. 'timeout' => $timeout
  7923. ]);
  7924. // 超时未完成,更新任务中心状态和结果
  7925. $this->finishScriptProductTask($taskCenterId, $response, true);
  7926. }
  7927. }
  7928. /**
  7929. * 定时任务:检查产品图片生成任务状态并更新产品记录
  7930. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  7931. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  7932. *
  7933. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  7934. */
  7935. public function checkProductPicTasks() {
  7936. // 查询所有生成中的产品图片任务
  7937. $products = DB::table('mp_products')
  7938. ->whereNotNull('pic_task_id')
  7939. ->where('pic_task_status', '生成中')
  7940. ->where('is_deleted', 0)
  7941. ->get();
  7942. $stats = [
  7943. 'total' => $products->count(),
  7944. 'success' => 0,
  7945. 'failed' => 0,
  7946. 'pending' => 0,
  7947. ];
  7948. foreach ($products as $product) {
  7949. try {
  7950. $task_id = $product->pic_task_id;
  7951. // 通过 pic_task_id 查询图片生成任务结果
  7952. $task = DB::table('mp_generate_pic_tasks')
  7953. ->where('id', $task_id)
  7954. ->first();
  7955. if ($task) {
  7956. if ($task->status === 'success' && $task->result_url) {
  7957. // 解析图片URL
  7958. $result_urls = $task->result_url;
  7959. if (is_string($result_urls)) {
  7960. $result_urls = json_decode($result_urls, true);
  7961. }
  7962. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  7963. // 更新资产表状态
  7964. DB::table('mp_products')
  7965. ->where('id', $product->id)
  7966. ->update([
  7967. 'pic_task_status' => '生成成功',
  7968. 'url' => $img_url,
  7969. 'updated_at' => now()
  7970. ]);
  7971. $stats['success']++;
  7972. dLog('anime')->info('资产图片生成成功', [
  7973. 'product_id' => $product->id,
  7974. 'task_id' => $task_id,
  7975. 'img_url' => $img_url
  7976. ]);
  7977. } elseif ($task->status === 'failed') {
  7978. // 更新资产表状态
  7979. DB::table('mp_products')
  7980. ->where('id', $product->id)
  7981. ->update([
  7982. 'pic_task_status' => '生成失败',
  7983. 'updated_at' => now()
  7984. ]);
  7985. $stats['failed']++;
  7986. dLog('anime')->warning('资产图片生成失败', [
  7987. 'product_id' => $product->id,
  7988. 'task_id' => $task_id,
  7989. 'error' => $task->error_message ?? '未知错误'
  7990. ]);
  7991. } else {
  7992. // 任务还在处理中
  7993. $stats['pending']++;
  7994. }
  7995. } else {
  7996. // 任务不存在,标记为失败
  7997. DB::table('mp_products')
  7998. ->where('id', $product->id)
  7999. ->update([
  8000. 'pic_task_status' => '生成失败',
  8001. 'updated_at' => now()
  8002. ]);
  8003. $stats['failed']++;
  8004. dLog('anime')->error('图片生成任务不存在', [
  8005. 'product_id' => $product->id,
  8006. 'task_id' => $task_id
  8007. ]);
  8008. }
  8009. } catch (\Exception $e) {
  8010. dLog('anime')->error('检查产品图片生成任务异常', [
  8011. 'product_id' => $product->id,
  8012. 'task_id' => $product->pic_task_id ?? null,
  8013. 'error' => $e->getMessage()
  8014. ]);
  8015. }
  8016. }
  8017. return $stats;
  8018. }
  8019. /**
  8020. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  8021. *
  8022. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  8023. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  8024. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  8025. *
  8026. * @return int 更新的任务中心记录数
  8027. */
  8028. public function checkSaveScriptProductTaskCenters() {
  8029. $updated = 0;
  8030. // 只扫描尚未结束的 saveScriptProducts 任务
  8031. $tasks = DB::table('mp_task_center')
  8032. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8033. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8034. ->orderBy('id', 'desc')
  8035. ->limit(500)
  8036. ->get();
  8037. // 与 pollProductImageTasks 保持一致的类型名称映射
  8038. $typeNames = [
  8039. 1 => 'roles', // 角色
  8040. 2 => 'scenes', // 场景
  8041. 3 => 'props', // 道具
  8042. ];
  8043. foreach ($tasks as $task) {
  8044. try {
  8045. $taskParams = json_decode((string)$task->params, true);
  8046. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  8047. if (!$script_id) {
  8048. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  8049. 'task_center_id' => $task->id,
  8050. ]);
  8051. continue;
  8052. }
  8053. // 获取该剧本关联的全部资产ID
  8054. $productIds = DB::table('mp_script_product_mappings')
  8055. ->where('script_id', $script_id)
  8056. ->pluck('product_id')
  8057. ->unique()
  8058. ->toArray();
  8059. if (empty($productIds)) {
  8060. // 剧本没有关联资产,不视为完成,等待下一次检查
  8061. continue;
  8062. }
  8063. $products = DB::table('mp_products')
  8064. ->whereIn('id', $productIds)
  8065. ->where('is_deleted', 0)
  8066. ->get();
  8067. $stats = [];
  8068. $allCompleted = true;
  8069. foreach ($products as $product) {
  8070. $typeName = $typeNames[$product->product] ?? 'unknown';
  8071. if (!isset($stats[$typeName])) {
  8072. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8073. }
  8074. $stats[$typeName]['total']++;
  8075. if ($product->pic_task_status === '生成成功') {
  8076. $stats[$typeName]['success']++;
  8077. $stats[$typeName]['completed']++;
  8078. } elseif ($product->pic_task_status === '生成失败') {
  8079. $stats[$typeName]['completed']++;
  8080. } else {
  8081. // 仍有资产在生成中或未生成,任务未完成
  8082. $allCompleted = false;
  8083. }
  8084. }
  8085. if (!$allCompleted) {
  8086. continue;
  8087. }
  8088. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  8089. $script = DB::table('mp_scripts')
  8090. ->where('id', $script_id)
  8091. ->where('is_deleted', 0)
  8092. ->first();
  8093. $script_name = $script->script_name ?? 'script_' . $script_id;
  8094. $this->finishScriptProductTask($task->id, [
  8095. 'type' => 'complete',
  8096. 'script_id' => $script_id,
  8097. 'script_name' => $script_name,
  8098. 'stats' => $stats,
  8099. 'timestamp' => date('Y-m-d H:i:s'),
  8100. 'task_center_id' => (int)$task->id,
  8101. ]);
  8102. $updated++;
  8103. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  8104. 'task_center_id' => $task->id,
  8105. 'script_id' => $script_id,
  8106. 'stats' => $stats,
  8107. ]);
  8108. } catch (\Exception $e) {
  8109. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  8110. 'task_center_id' => $task->id,
  8111. 'error' => $e->getMessage(),
  8112. ]);
  8113. }
  8114. }
  8115. return $updated;
  8116. }
  8117. /**
  8118. * 获取剧本关联的资产列表
  8119. * @param array $data 请求参数
  8120. * @return array
  8121. */
  8122. public function getScriptProducts($data) {
  8123. $uid = Site::getUid();
  8124. $cpid = Site::getCpid();
  8125. $script_id = getProp($data, 'script_id');
  8126. $episode_number = getProp($data, 'episode_number');
  8127. if (!$script_id) {
  8128. Utils::throwError('20003:请提供剧本ID');
  8129. }
  8130. // 验证剧本是否存在
  8131. $script = DB::table('mp_scripts')
  8132. ->where('id', $script_id)
  8133. ->where('is_deleted', 0)
  8134. ->first();
  8135. if (!$script) {
  8136. Utils::throwError('20003:剧本不存在');
  8137. }
  8138. // 联表查询资产信息
  8139. $query = DB::table('mp_script_product_mappings as mapping')
  8140. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8141. ->where('mapping.script_id', $script_id)
  8142. ->where('product.cpid', $cpid)
  8143. ->where('product.is_deleted', 0);
  8144. // 如果提供了 episode_number,则过滤指定集数
  8145. if ($episode_number !== null && $episode_number !== '') {
  8146. $query->where('mapping.episode_number', $episode_number);
  8147. }
  8148. $mappings = $query->select(
  8149. 'mapping.script_id',
  8150. 'mapping.product_id',
  8151. 'mapping.episode_number',
  8152. 'product.product_name',
  8153. 'product.type',
  8154. 'product.product',
  8155. 'product.pic_prompt',
  8156. 'product.url',
  8157. 'product.pic_task_id',
  8158. 'product.pic_task_status',
  8159. 'product.three_view_image_url',
  8160. 'mapping.created_at'
  8161. )
  8162. ->orderBy('mapping.product_id', 'asc')
  8163. ->orderBy('mapping.episode_number', 'asc')
  8164. ->get();
  8165. // 按 product_id 分组,合并 episode_number
  8166. $productMap = [];
  8167. foreach ($mappings as $item) {
  8168. $product_id = $item->product_id;
  8169. if (!isset($productMap[$product_id])) {
  8170. $productMap[$product_id] = [
  8171. 'product_id' => $product_id,
  8172. 'product_name' => $item->product_name,
  8173. 'type' => (int)$item->type,
  8174. 'product' => (int)$item->product,
  8175. 'pic_prompt' => $item->pic_prompt,
  8176. 'url' => $item->url,
  8177. 'pic_task_id' => $item->pic_task_id,
  8178. 'pic_task_status' => $item->pic_task_status,
  8179. 'episode_numbers' => [],
  8180. 'created_at' => $item->created_at,
  8181. ];
  8182. }
  8183. // 添加 episode_number(去重)
  8184. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8185. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8186. }
  8187. }
  8188. // 按类型分组
  8189. $roles = []; // type=1 角色/主体
  8190. $scenes = []; // type=2 场景
  8191. $props = []; // type=3 道具
  8192. foreach ($productMap as $product) {
  8193. // 将 episode_numbers 数组转换为逗号分隔的字符串
  8194. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  8195. // 构造返回数据
  8196. $productData = [
  8197. 'product_id' => $product['product_id'],
  8198. 'product_name' => $product['product_name'],
  8199. 'product' => $product['product'],
  8200. 'pic_prompt' => $product['pic_prompt'],
  8201. 'url' => $product['url'],
  8202. 'pic_task_id' => $product['pic_task_id'],
  8203. 'pic_task_status' => $product['pic_task_status'],
  8204. 'episode_numbers' => $episodeNumbersStr,
  8205. 'created_at' => $product['created_at'],
  8206. ];
  8207. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  8208. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  8209. switch ($product['product']) {
  8210. case 1:
  8211. $roles[] = $productData;
  8212. break;
  8213. case 2:
  8214. $scenes[] = $productData;
  8215. break;
  8216. case 3:
  8217. $props[] = $productData;
  8218. break;
  8219. }
  8220. }
  8221. return [
  8222. 'script_id' => $script_id,
  8223. 'script_name' => $script->script_name ?? '',
  8224. 'roles' => $roles, // 主体
  8225. 'scenes' => $scenes, // 场景
  8226. 'props' => $props, // 道具
  8227. ];
  8228. }
  8229. /**
  8230. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  8231. * @param string $actContent 原始内容
  8232. * @param array $products 产品数组(包含product_name和url)
  8233. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  8234. */
  8235. public function processActContentWithProducts($actContent, $products) {
  8236. if (empty($actContent) || empty($products)) {
  8237. return [
  8238. 'content' => $actContent,
  8239. 'reference_images' => []
  8240. ];
  8241. }
  8242. // 构建产品名称到产品信息的映射
  8243. $product_dict = [];
  8244. foreach ($products as $product) {
  8245. $product_name = getProp($product, 'product_name');
  8246. if ($product_name) {
  8247. $product_dict[$product_name] = [
  8248. 'url' => getProp($product, 'url'),
  8249. 'voice_prompt' => getProp($product, 'voice_prompt')
  8250. ];
  8251. }
  8252. }
  8253. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  8254. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  8255. $reference_images = [];
  8256. $product_index_map = []; // 产品名称 => 图片序号的映射
  8257. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  8258. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  8259. $current_index = 1;
  8260. if (!empty($matches[1])) {
  8261. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  8262. $seen_products = []; // 用于去重
  8263. foreach ($matches[1] as $product_name) {
  8264. // 跳过已处理的产品
  8265. if (isset($seen_products[$product_name])) {
  8266. continue;
  8267. }
  8268. $seen_products[$product_name] = true;
  8269. // 检查产品是否在字典中
  8270. if (isset($product_dict[$product_name])) {
  8271. $url = $product_dict[$product_name]['url'];
  8272. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8273. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8274. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8275. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8276. }
  8277. // 只有URL非空才分配序号和添加到参考图片
  8278. if (!empty($url)) {
  8279. // 检查URL是否已经在reference_images中(去重)
  8280. if (!in_array($url, $reference_images)) {
  8281. $reference_images[] = $url;
  8282. $product_index_map[$product_name] = $current_index;
  8283. $current_index++;
  8284. } else {
  8285. // URL重复,找到已有的序号
  8286. $existing_index = array_search($url, $reference_images) + 1;
  8287. $product_index_map[$product_name] = $existing_index;
  8288. }
  8289. } else {
  8290. // URL为空,不分配序号(后续直接去掉{})
  8291. $product_index_map[$product_name] = 0;
  8292. }
  8293. } else {
  8294. // 产品不在字典中,不分配序号
  8295. $product_index_map[$product_name] = 0;
  8296. }
  8297. }
  8298. }
  8299. // 第二步:替换内容中的 {产品名称}
  8300. $processedContent = $actContent;
  8301. foreach ($product_index_map as $product_name => $index) {
  8302. $escaped_name = preg_quote($product_name, '/');
  8303. if ($index > 0) {
  8304. // 有图片,替换为:产品名称(图X)
  8305. $replacement = $product_name . '<图片' . $index . '>';
  8306. } else {
  8307. // 无图片,只保留产品名称
  8308. $replacement = $product_name;
  8309. }
  8310. // 替换所有 {产品名称} 为处理后的格式
  8311. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8312. }
  8313. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8314. foreach ($products as $product) {
  8315. $product_name = getProp($product, 'product_name');
  8316. $voice_prompt = getProp($product, 'voice_prompt');
  8317. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8318. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8319. break; // 找到旁白后退出循环
  8320. }
  8321. }
  8322. // 第四步:将voice_prompt信息添加到内容最前面
  8323. $voice_prompt_prefix = '';
  8324. if (!empty($voice_prompts)) {
  8325. $voice_prompt_prefix .= implode('', $voice_prompts);
  8326. }
  8327. // 旁白的voice_prompt放在最后
  8328. if (!empty($narrator_voice_prompt)) {
  8329. $voice_prompt_prefix .= $narrator_voice_prompt;
  8330. }
  8331. // 如果有voice_prompt信息,添加到内容开头
  8332. if (!empty($voice_prompt_prefix)) {
  8333. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8334. }
  8335. return [
  8336. 'content' => $processedContent,
  8337. 'reference_images' => $reference_images
  8338. ];
  8339. }
  8340. public function saveActVideoGenerateParams($data) {
  8341. $episode_id = getProp($data, 'episode_id');
  8342. $model = getProp($data, 'video_model');
  8343. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  8344. Utils::throwError('20003:该模型不可用');
  8345. }
  8346. if (!$model) {
  8347. // 使用默认模型
  8348. $model = 'zhizhen-20';
  8349. }
  8350. // 验证模型是否在可用模型表中
  8351. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8352. Utils::throwError('20003:该模型已不可用,请更换!');
  8353. }
  8354. $video_resolution = getProp($data, 'video_resolution', '720p');
  8355. $ratio = getProp($data, 'ratio');
  8356. if (!$ratio) $ratio = '9:16';
  8357. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8358. if (!$episode) {
  8359. Utils::throwError('20003:分集不存在');
  8360. }
  8361. try {
  8362. DB::beginTransaction();
  8363. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8364. 'video_model' => $model,
  8365. 'video_resolution' => $video_resolution,
  8366. 'ratio' => $ratio,
  8367. 'updated_at' => date('Y-m-d H:i:s')
  8368. ]);
  8369. if ($result === false) {
  8370. Utils::throwError('20003:分集视频参数保存失败');
  8371. }
  8372. // 同步更新mp_animes表
  8373. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8374. 'video_model' => $model,
  8375. 'video_resolution' => $video_resolution,
  8376. 'video_ratio' => $ratio,
  8377. 'updated_at' => date('Y-m-d H:i:s')
  8378. ]);
  8379. if ($anime_result === false) {
  8380. Utils::throwError('20003:动漫视频参数保存失败');
  8381. }
  8382. } catch (\Exception $e) {
  8383. DB::rollBack();
  8384. Utils::throwError('20003:'.$e->getMessage());
  8385. }
  8386. DB::commit();
  8387. return $result;
  8388. }
  8389. public function confirmActs($data) {
  8390. $episode_id = getProp($data, 'episode_id');
  8391. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8392. if (!$episode) {
  8393. Utils::throwError('20003:分集不存在');
  8394. }
  8395. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8396. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8397. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8398. // 获取所有片段数据
  8399. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8400. // 收集所有资产名称(角色、场景、道具)
  8401. $product_names = [];
  8402. // 收集角色名称
  8403. foreach ($roles as $role) {
  8404. $role_name = getProp($role, 'role');
  8405. if ($role_name && $role_name != '旁白') {
  8406. $product_names[] = $role_name;
  8407. }
  8408. }
  8409. // 收集场景名称
  8410. foreach ($scenes as $scene) {
  8411. $scene_name = getProp($scene, 'scene');
  8412. if ($scene_name) {
  8413. $product_names[] = $scene_name;
  8414. }
  8415. }
  8416. // 收集道具名称
  8417. foreach ($props as $prop) {
  8418. $prop_name = getProp($prop, 'prop');
  8419. if ($prop_name) {
  8420. $product_names[] = $prop_name;
  8421. }
  8422. }
  8423. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8424. $product_names = array_unique($product_names);
  8425. usort($product_names, function($a, $b) {
  8426. return mb_strlen($b) - mb_strlen($a);
  8427. });
  8428. try {
  8429. DB::beginTransaction();
  8430. // 处理每个片段
  8431. foreach ($acts as $act) {
  8432. $act_content = getProp($act, 'act_content');
  8433. if (!$act_content) continue;
  8434. $processed_content = $act_content;
  8435. // 统一替换所有资产名称为 {资产名} 格式
  8436. // 使用占位符避免嵌套替换问题
  8437. $placeholder_map = [];
  8438. $placeholder_index = 0;
  8439. foreach ($product_names as $product_name) {
  8440. // 转义特殊字符
  8441. $escaped_product = preg_quote($product_name, '/');
  8442. // 检查是否匹配且未被 {} 包裹
  8443. $processed_content = preg_replace_callback(
  8444. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8445. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8446. // 使用唯一占位符
  8447. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8448. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8449. $placeholder_index++;
  8450. return $placeholder;
  8451. },
  8452. $processed_content
  8453. );
  8454. }
  8455. // 将所有占位符替换回实际内容
  8456. foreach ($placeholder_map as $placeholder => $replacement) {
  8457. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8458. }
  8459. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8460. $shot_counter = 0;
  8461. $processed_content = preg_replace_callback(
  8462. '/【(?:镜头|分镜)(\d+)】/u',
  8463. function($matches) use (&$shot_counter) {
  8464. $shot_counter++;
  8465. return '【镜头' . $shot_counter . '】';
  8466. },
  8467. $processed_content
  8468. );
  8469. // 更新数据库
  8470. $boolen = DB::table('mp_episode_segments')
  8471. ->where('id', $act->id)
  8472. ->update([
  8473. 'act_show_content' => $processed_content,
  8474. 'updated_at' => date('Y-m-d H:i:s')
  8475. ]);
  8476. if (!$boolen) {
  8477. Utils::throwError('20003:片段处理失败');
  8478. }
  8479. }
  8480. }catch (\Exception $e) {
  8481. DB::rollBack();
  8482. Utils::throwError('20003:'.$e->getMessage());
  8483. }
  8484. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8485. 'is_generated' => 1,
  8486. 'updated_at' => date('Y-m-d H:i:s')
  8487. ]);
  8488. if (!$boolen1) {
  8489. DB::rollBack();
  8490. Utils::throwError('20003:分集处理失败!');
  8491. }
  8492. DB::commit();
  8493. // 重新查询更新后的片段数据
  8494. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8495. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8496. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8497. $products = [];
  8498. // 先处理角色数组
  8499. foreach ($roles as $role) {
  8500. $product = $role;
  8501. // 将role字段重命名为product_name
  8502. if (isset($product['role'])) {
  8503. $product['product_name'] = $product['role'];
  8504. unset($product['role']);
  8505. $product['product'] = 1; // 标记类型为角色
  8506. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8507. }
  8508. }
  8509. // 处理场景数组
  8510. foreach ($scenes as $scene) {
  8511. $product = $scene;
  8512. // 将scene字段重命名为product_name
  8513. if (isset($product['scene'])) {
  8514. $product['product_name'] = $product['scene'];
  8515. unset($product['scene']);
  8516. $product['product'] = 2; // 标记类型为场景
  8517. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8518. }
  8519. }
  8520. // 处理道具数组(逻辑与场景一致)
  8521. foreach ($props as $prop) {
  8522. $product = $prop;
  8523. // 将prop字段重命名为product_name
  8524. if (isset($product['prop'])) {
  8525. $product['product_name'] = $product['prop'];
  8526. unset($product['prop']);
  8527. $product['product'] = 3; // 标记类型为道具
  8528. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8529. }
  8530. }
  8531. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8532. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8533. foreach ($extra_products as $extra_product) {
  8534. $product_name = getProp($extra_product, 'product_name');
  8535. if ($product_name) {
  8536. $products[$product_name] = $extra_product; // 覆盖同名数据
  8537. }
  8538. }
  8539. // 重新索引数组(去除key)
  8540. $products = array_values($products);
  8541. // 构建返回的acts数组
  8542. $return_acts = [];
  8543. foreach ($acts as $act) {
  8544. $return_acts[] = [
  8545. 'act_id' => getProp($act, 'id'),
  8546. 'act_number' => getProp($act, 'act_number'),
  8547. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8548. 'act_show_content' => getProp($act, 'act_show_content'),
  8549. 'video_url' => getProp($act, 'video_url'),
  8550. 'video_duration' => getProp($act, 'video_duration'),
  8551. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8552. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8553. ];
  8554. }
  8555. return [
  8556. 'anime_id' => getProp($episode, 'anime_id'),
  8557. 'episode_id' => $episode_id,
  8558. 'title' => getProp($episode, 'title'),
  8559. 'episode_number' => getProp($episode, 'episode_number'),
  8560. 'is_generated' => getProp($episode, 'is_generated'),
  8561. 'video_params' => [
  8562. 'video_model' => getProp($episode, 'video_model'),
  8563. 'video_resolution' => getProp($episode, 'video_resolution'),
  8564. 'ratio' => getProp($episode, 'ratio'),
  8565. ],
  8566. 'products' => $products,
  8567. 'acts' => $return_acts
  8568. ];
  8569. }
  8570. /**
  8571. * 导出动漫剧本为PDF(参照示例PDF版式)
  8572. * @param int $animeId 动漫ID
  8573. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8574. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8575. * @return string|null
  8576. */
  8577. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8578. // 图片下载与转换可能占用较多内存
  8579. ini_set('memory_limit', '512M');
  8580. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8581. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8582. $anime = (array)$anime;
  8583. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8584. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8585. // 获取分集(默认展示版本,按集数升序)
  8586. $episodeQuery = DB::table('mp_anime_episodes')
  8587. ->where('anime_id', $animeId)
  8588. ->where('is_default', 1)
  8589. ->orderBy('episode_number')
  8590. ->orderBy('id');
  8591. if ($episodeCount > 0) {
  8592. $episodeQuery->limit($episodeCount);
  8593. }
  8594. $episodes = $episodeQuery->get()->map(function ($value) {
  8595. return (array)$value;
  8596. })->toArray();
  8597. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8598. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8599. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8600. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8601. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8602. // 组装分集剧本数据
  8603. $episodeScripts = [];
  8604. foreach ($episodes as $episode) {
  8605. $segments = DB::table('mp_episode_segments')
  8606. ->where('anime_id', $animeId)
  8607. ->where('episode_id', $episode['id'])
  8608. ->get();
  8609. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8610. $acts = [];
  8611. foreach ($segments as $segment) {
  8612. $segment = (array)$segment;
  8613. $actNumber = (int)getProp($segment, 'act_number', 0);
  8614. if ($actNumber <= 0) continue;
  8615. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8616. $acts[$actNumber] = [
  8617. 'id' => (int)$segment['id'],
  8618. 'act_number' => $actNumber,
  8619. 'duration' => getProp($segment, 'act_duration', ''),
  8620. 'content' => getProp($segment, 'act_content', ''),
  8621. ];
  8622. }
  8623. }
  8624. ksort($acts);
  8625. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8626. $segmentCounter = 0;
  8627. foreach ($acts as &$act) {
  8628. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8629. }
  8630. unset($act);
  8631. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8632. $narratorVoice = '';
  8633. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8634. foreach ($episodeRoles as $role) {
  8635. if (getProp($role, 'role') === '旁白') {
  8636. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8637. break;
  8638. }
  8639. }
  8640. if ($narratorVoice === '') {
  8641. foreach ($acts as $act) {
  8642. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8643. $narratorVoice = trim($match[1]);
  8644. break;
  8645. }
  8646. }
  8647. }
  8648. $episodeScripts[] = [
  8649. 'episode_number' => getProp($episode, 'episode_number'),
  8650. 'title' => getProp($episode, 'title', ''),
  8651. 'act_count' => count($acts),
  8652. 'narrator_voice' => $narratorVoice,
  8653. 'acts' => array_values($acts),
  8654. ];
  8655. }
  8656. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8657. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8658. // 构建PDF
  8659. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8660. // 图片已嵌入PDF,清理临时文件
  8661. foreach ($imageCache as $imgFile) {
  8662. @unlink($imgFile);
  8663. }
  8664. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8665. if ($savePath) {
  8666. $pdf->Output($savePath, 'F');
  8667. return $savePath;
  8668. }
  8669. // 直接下载输出
  8670. header('Content-Type: application/pdf');
  8671. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8672. $pdf->Output($filename . '.pdf', 'D');
  8673. exit();
  8674. }
  8675. /**
  8676. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8677. * @param array $episodes 分集数据
  8678. * @param string $nameKey role|scene|prop
  8679. * @return array
  8680. */
  8681. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8682. $fieldMap = [
  8683. 'role' => 'roles',
  8684. 'scene' => 'scenes',
  8685. 'prop' => 'props',
  8686. ];
  8687. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8688. $items = [];
  8689. foreach ($episodes as $episode) {
  8690. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8691. foreach ($list as $item) {
  8692. if (!is_array($item)) continue;
  8693. $name = trim((string)getProp($item, $nameKey, ''));
  8694. if ($name === '') continue;
  8695. // 旁白不进入主体列表(仅作为旁白音色来源)
  8696. if ($nameKey === 'role' && $name === '旁白') continue;
  8697. if (!isset($items[$name])) {
  8698. $items[$name] = $item;
  8699. }
  8700. }
  8701. }
  8702. return array_values($items);
  8703. }
  8704. /**
  8705. * 构建动漫剧本PDF
  8706. * @param array $anime 动漫信息
  8707. * @param array $roles 主体列表
  8708. * @param array $scenes 场景列表
  8709. * @param array $props 道具列表
  8710. * @param array $episodeScripts 分集剧本数据
  8711. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8712. * @return \TCPDF
  8713. */
  8714. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8715. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8716. $pdf->SetCreator('动漫剧本导出系统');
  8717. $pdf->SetAuthor('系统');
  8718. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8719. $pdf->SetSubject('动漫剧本导出');
  8720. $pdf->SetMargins(15, 15, 15);
  8721. $pdf->SetAutoPageBreak(true, 15);
  8722. // 剧本名
  8723. $pdf->AddPage();
  8724. $pdf->SetFont('simsun', 'B', 20);
  8725. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8726. $pdf->Ln(5);
  8727. // 故事梗概
  8728. $intro = trim((string)getProp($anime, 'intro', ''));
  8729. if ($intro !== '') {
  8730. $this->pdfSectionTitle($pdf, '故事梗概');
  8731. $this->pdfBody($pdf, $intro);
  8732. }
  8733. // 美术风格
  8734. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  8735. if ($artStyle !== '') {
  8736. $this->pdfSectionTitle($pdf, '美术风格');
  8737. $this->pdfBody($pdf, $artStyle);
  8738. }
  8739. // 主体列表(文字+图片)
  8740. $this->pdfSectionTitle($pdf, '主体列表');
  8741. foreach ($roles as $index => $role) {
  8742. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  8743. }
  8744. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  8745. // 场景列表(文字+图片)
  8746. $this->pdfSectionTitle($pdf, '场景列表');
  8747. foreach ($scenes as $index => $scene) {
  8748. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  8749. }
  8750. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  8751. // 道具列表(文字+图片)
  8752. $this->pdfSectionTitle($pdf, '道具列表');
  8753. foreach ($props as $index => $prop) {
  8754. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  8755. }
  8756. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  8757. // 分镜剧本
  8758. $this->pdfSectionTitle($pdf, '分镜剧本');
  8759. foreach ($episodeScripts as $episodeScript) {
  8760. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  8761. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  8762. if ($episodeTitleRaw !== '') {
  8763. // title 字段可能已带"第N集"前缀,避免重复
  8764. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  8765. $episodeTitle = $episodeTitleRaw;
  8766. } else {
  8767. $episodeTitle .= ':' . $episodeTitleRaw;
  8768. }
  8769. }
  8770. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  8771. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  8772. if (getProp($episodeScript, 'narrator_voice') !== '') {
  8773. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  8774. }
  8775. foreach (getProp($episodeScript, 'acts', []) as $act) {
  8776. $actTitle = '片段' . getProp($act, 'act_number');
  8777. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  8778. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  8779. }
  8780. $this->pdfSubTitle($pdf, $actTitle, 12);
  8781. if (getProp($act, 'content') !== '') {
  8782. $this->pdfBody($pdf, getProp($act, 'content'));
  8783. }
  8784. }
  8785. }
  8786. return $pdf;
  8787. }
  8788. /**
  8789. * PDF章节标题(带分隔线)
  8790. */
  8791. private function pdfSectionTitle($pdf, $title) {
  8792. if ($pdf->GetY() > 230) {
  8793. $pdf->AddPage();
  8794. }
  8795. $pdf->SetFont('simsun', 'B', 15);
  8796. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  8797. $y = $pdf->GetY();
  8798. $pdf->SetLineWidth(0.4);
  8799. $pdf->Line(15, $y, 195, $y);
  8800. $pdf->Ln(4);
  8801. }
  8802. /**
  8803. * PDF子标题(集数/片段标题)
  8804. */
  8805. private function pdfSubTitle($pdf, $title, $size = 13) {
  8806. if ($pdf->GetY() > 240) {
  8807. $pdf->AddPage();
  8808. }
  8809. $pdf->SetFont('simsun', 'B', $size);
  8810. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  8811. $pdf->Ln(1);
  8812. }
  8813. /**
  8814. * PDF正文段落
  8815. */
  8816. private function pdfBody($pdf, $text) {
  8817. $pdf->SetFont('simsun', '', 11);
  8818. $pdf->MultiCell(0, 6, $text, 0, 'L');
  8819. $pdf->Ln(2);
  8820. }
  8821. /**
  8822. * 输出列表项图片(每张图单独一页,图下标注名称)
  8823. * @param \TCPDF $pdf
  8824. * @param array $items 列表项
  8825. * @param string $nameKey role|scene|prop
  8826. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8827. */
  8828. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  8829. foreach ($items as $item) {
  8830. $url = trim((string)getProp($item, 'url', ''));
  8831. $name = trim((string)getProp($item, $nameKey, ''));
  8832. if ($url === '' || !isset($imageCache[$url])) continue;
  8833. $imgPath = $imageCache[$url];
  8834. $size = @getimagesize($imgPath);
  8835. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  8836. continue;
  8837. }
  8838. $pdf->AddPage();
  8839. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  8840. $maxW = 160;
  8841. $maxH = 170;
  8842. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  8843. $drawW = $size[0] * $ratio;
  8844. $drawH = $size[1] * $ratio;
  8845. $x = (210 - $drawW) / 2;
  8846. $y = max(15, (297 - $drawH) / 2 - 10);
  8847. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  8848. // 图下标注名称
  8849. $pdf->SetFont('simsun', 'B', 13);
  8850. $pdf->SetY(297 - 28);
  8851. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  8852. }
  8853. }
  8854. /**
  8855. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  8856. * @param array $items 包含url字段的列表项
  8857. * @return array url => 临时文件路径
  8858. */
  8859. private function downloadImagesConcurrently(array $items) {
  8860. // 收集唯一的图片URL
  8861. $urls = [];
  8862. foreach ($items as $item) {
  8863. $url = trim((string)getProp($item, 'url', ''));
  8864. if ($url !== '') $urls[$url] = true;
  8865. }
  8866. if (!$urls) return [];
  8867. $urls = array_keys($urls);
  8868. $tmpDir = sys_get_temp_dir();
  8869. $rawFiles = [];
  8870. foreach ($urls as $url) {
  8871. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  8872. $rawFiles[$url] = $rawFile;
  8873. }
  8874. $client = new Client(['timeout' => 180, 'verify' => false]);
  8875. // 低并发下载,sink写入文件避免大图占用内存
  8876. $generator = (function () use ($urls, $client, $rawFiles) {
  8877. foreach ($urls as $url) {
  8878. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  8879. }
  8880. })();
  8881. $errors = [];
  8882. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  8883. 'concurrency' => 4,
  8884. 'rejected' => function ($reason, $url) use (&$errors) {
  8885. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  8886. },
  8887. ]);
  8888. $each->promise()->wait();
  8889. // 失败的图片串行重试一次(独占带宽,提高成功率)
  8890. foreach ($urls as $url) {
  8891. if (!isset($errors[$url])) continue;
  8892. try {
  8893. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  8894. unset($errors[$url]);
  8895. } catch (\Throwable $e) {
  8896. // 重试仍失败
  8897. }
  8898. }
  8899. $cache = [];
  8900. foreach ($urls as $url) {
  8901. $rawFile = $rawFiles[$url];
  8902. if (isset($errors[$url])) {
  8903. dLog('anime')->error('导出PDF图片下载失败', [
  8904. 'url' => $url,
  8905. 'error' => $errors[$url],
  8906. ]);
  8907. @unlink($rawFile);
  8908. continue;
  8909. }
  8910. $converted = $this->convertImageFile($rawFile, $url);
  8911. if ($converted !== null) {
  8912. $cache[$url] = $converted;
  8913. } else {
  8914. @unlink($rawFile);
  8915. }
  8916. }
  8917. return $cache;
  8918. }
  8919. /**
  8920. * 将已下载的图片文件缩放并转为JPEG
  8921. * @param string $rawFile 原始图片临时文件
  8922. * @param string $url 图片地址(用于命名)
  8923. * @return string|null 转换后的文件路径,转换失败返回null
  8924. */
  8925. private function convertImageFile($rawFile, $url) {
  8926. $content = @file_get_contents($rawFile);
  8927. if ($content === false || $content === '') return null;
  8928. if (!function_exists('imagecreatefromstring')) return null;
  8929. $image = @imagecreatefromstring($content);
  8930. if ($image === false) return null;
  8931. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  8932. imagedestroy($image);
  8933. if ($jpeg !== null) {
  8934. @unlink($rawFile);
  8935. }
  8936. return $jpeg;
  8937. }
  8938. /**
  8939. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  8940. * @param resource $srcImage GD图片资源
  8941. * @param string $rawFile 原始图片临时文件
  8942. * @param string $url 图片地址(用于命名)
  8943. * @return string|null 压缩后的JPEG文件路径
  8944. */
  8945. private function compressImageForPdf($srcImage, $rawFile, $url) {
  8946. $maxBytes = 2 * 1024 * 1024; // 2MB
  8947. $sizes = [2048, 1600, 1280, 1024, 800];
  8948. $qualities = [85, 70, 55, 40];
  8949. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  8950. foreach ($sizes as $size) {
  8951. $resized = $this->copyAndResize($srcImage, $size);
  8952. $flat = $this->flattenToWhite($resized);
  8953. imagedestroy($resized);
  8954. foreach ($qualities as $quality) {
  8955. ob_start();
  8956. $saved = imagejpeg($flat, null, $quality);
  8957. $data = ob_get_clean();
  8958. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  8959. file_put_contents($jpeg, $data);
  8960. imagedestroy($flat);
  8961. dLog('anime')->info('导出PDF图片压缩完成', [
  8962. 'url' => $url,
  8963. 'size' => filesize($jpeg),
  8964. 'edge' => $size,
  8965. 'quality' => $quality,
  8966. ]);
  8967. return $jpeg;
  8968. }
  8969. }
  8970. imagedestroy($flat);
  8971. }
  8972. // 兜底:最小尺寸、最低质量强制输出
  8973. $resized = $this->copyAndResize($srcImage, 800);
  8974. $flat = $this->flattenToWhite($resized);
  8975. imagedestroy($resized);
  8976. $saved = imagejpeg($flat, $jpeg, 30);
  8977. imagedestroy($flat);
  8978. if (!$saved) return null;
  8979. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  8980. 'url' => $url,
  8981. 'size' => filesize($jpeg),
  8982. ]);
  8983. return $jpeg;
  8984. }
  8985. /**
  8986. * 等比缩放图片副本(不销毁原图)
  8987. * @param resource $srcImage GD图片资源
  8988. * @param int $maxEdge 最大边长
  8989. * @return resource
  8990. */
  8991. private function copyAndResize($srcImage, $maxEdge) {
  8992. $width = imagesx($srcImage);
  8993. $height = imagesy($srcImage);
  8994. $max = max($width, $height);
  8995. if ($max <= $maxEdge) {
  8996. $copy = imagecreatetruecolor($width, $height);
  8997. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  8998. return $copy;
  8999. }
  9000. $ratio = $maxEdge / $max;
  9001. $newWidth = max(1, (int)round($width * $ratio));
  9002. $newHeight = max(1, (int)round($height * $ratio));
  9003. $resized = imagecreatetruecolor($newWidth, $newHeight);
  9004. imagealphablending($resized, false);
  9005. imagesavealpha($resized, true);
  9006. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  9007. return $resized;
  9008. }
  9009. /**
  9010. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  9011. * @param resource $image GD图片资源
  9012. * @return resource
  9013. */
  9014. private function flattenToWhite($image) {
  9015. $width = imagesx($image);
  9016. $height = imagesy($image);
  9017. $flat = imagecreatetruecolor($width, $height);
  9018. $white = imagecolorallocate($flat, 255, 255, 255);
  9019. imagefill($flat, 0, 0, $white);
  9020. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  9021. return $flat;
  9022. }
  9023. /**
  9024. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  9025. * @param string $content 片段内容
  9026. * @param int $counter 当前已编号数量(引用传递,整集累计)
  9027. * @return string
  9028. */
  9029. private function renumberSegmentBlocks($content, &$counter) {
  9030. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  9031. $counter++;
  9032. return '【' . $match[1] . $counter . '】';
  9033. }, $content);
  9034. }
  9035. }