AnimeService.php 378 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $cpid = Site::getCpid();
  181. $input_art_style = getProp($data, 'art_style');
  182. $file = getProp($data, 'file');
  183. $content = getProp($data, 'content', '');
  184. $bid = getProp($data, 'bid', 0);
  185. $script_id = getProp($data, 'script_id', 0);
  186. $ace_mode = getProp($data, 'ace_mode', 0);
  187. $extra_products = getProp($data, 'products', []);
  188. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  189. if (!is_array($extra_products)) {
  190. Utils::throwError('20003:传入的资产格式不正确');
  191. }
  192. // 替换美术风格
  193. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  194. // 提取文件内容
  195. if ($file) {
  196. $content = $this->DeepSeekService->extractFileContent($file);
  197. if (!$content) {
  198. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  199. }
  200. } elseif ($script_id) {
  201. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  202. if (!$content) {
  203. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  204. }
  205. } elseif ($bid) {
  206. $content = $this->DeepSeekService->getContentByBid($bid);
  207. if (!$content) {
  208. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  209. }
  210. } elseif ($content) {
  211. $content = filterContent($content);
  212. }else {
  213. $content = '';
  214. }
  215. $anime_data = [
  216. 'user_id' => $uid,
  217. 'cpid' => $cpid,
  218. 'anime_name' => '新剧本策划',
  219. 'is_multi' => getProp($data, 'is_multi', 1),
  220. 'content' => $content,
  221. 'art_style_type' => $input_art_style,
  222. 'ace_mode' => $ace_mode,
  223. 'script_id' => $script_id,
  224. 'extra_products' => json_encode($extra_products, 256),
  225. 'created_at' => date('Y-m-d H:i:s'),
  226. 'updated_at' => date('Y-m-d H:i:s'),
  227. ];
  228. // 处理文本模型
  229. $model = getProp($data, 'model');
  230. if (!$model) {
  231. // 用户没有输入,使用默认值
  232. $model = 'deepseek-v4-pro';
  233. }
  234. // 验证模型是否在可用模型表中
  235. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  236. $model = 'deepseek-v4-pro';
  237. }
  238. $anime_data['model'] = $model;
  239. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  240. return DB::table('mp_animes')->insertGetId($anime_data);
  241. }
  242. public function chatList($data) {
  243. $uid = Site::getUid();
  244. $anime_name = getProp($data, 'anime_name');
  245. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  246. if ($anime_name) {
  247. $query->where('anime_name', 'like', "%$anime_name%");
  248. }
  249. return $query->orderBy('id', 'desc')->paginate();
  250. }
  251. public function chatHistory($data) {
  252. $anime_id = getProp($data, 'anime_id');
  253. $sequence = getProp($data, 'sequence', 0);
  254. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  255. $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)
  256. ->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');
  257. return $query->orderBy('ar.id')->get()->map(function ($value) {
  258. $value = (array)$value;
  259. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  260. $value['created_at'] = transDate($value['created_at']);
  261. $value['episode_created_at'] = transDate($value['episode_created_at']);
  262. return $value;
  263. })->toArray();
  264. }
  265. public function batchSetRoleImg($data) {
  266. $episode_id = getProp($data, 'episode_id');
  267. if (!$episode_id) Utils::throwError('1002:请选择分集');
  268. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  269. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  270. $art_style = getProp($episode, 'art_style');
  271. $anime_id = getProp($episode, 'anime_id');
  272. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  273. $art_style_type = getProp($anime, 'art_style_type');
  274. $character_prefix = '';
  275. $scene_prefix = '';
  276. if ($art_style_type) {
  277. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  278. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  279. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  280. }
  281. foreach ($roles as &$role) {
  282. $role_name = getProp($role, 'role');
  283. if ($role_name == '旁白') continue;
  284. // 优先使用 pic_prompt,如果没有则使用 description
  285. $pic_prompt = getProp($role, 'pic_prompt');
  286. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  287. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  288. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  289. // 参考图地址
  290. $ref_img_url = getProp($role, 'url');
  291. if ($ref_img_url) continue; // 已有图片则跳过
  292. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  293. try {
  294. $params = [
  295. 'prompt' => $description,
  296. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  297. ];
  298. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  299. $task_id = $task->id;
  300. if (!$task_id) {
  301. Utils::throwError("20003:角色({$role_name})生成图片失败");
  302. }
  303. $role['task_id'] = $task_id;
  304. $role['task_status'] = 'processing';
  305. } catch (\Exception $e) {
  306. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  307. Utils::throwError("20003:" . $e->getMessage());
  308. }
  309. }
  310. // 保存角色信息
  311. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  312. 'roles' => json_encode($roles, 256),
  313. 'generate_status' => '执行中',
  314. 'generate_at' => date('Y-m-d H:i:s'),
  315. 'updated_at' => date('Y-m-d H:i:s')
  316. ]);
  317. if (!$boolen) {
  318. Utils::throwError('20003:保存角色信息失败');
  319. }
  320. return $boolen;
  321. }
  322. public function batchSetSceneImg($data) {
  323. $episode_id = getProp($data, 'episode_id');
  324. if (!$episode_id) Utils::throwError('1002:请选择分集');
  325. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  326. $scenes = json_decode(getProp($episode, 'scenes'), true);
  327. $art_style = getProp($episode, 'art_style');
  328. $target_scene = getProp($data, 'target_scene');
  329. $anime_id = getProp($episode, 'anime_id');
  330. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  331. $art_style_type = getProp($anime, 'art_style_type');
  332. $character_prefix = '';
  333. $scene_prefix = '';
  334. if ($art_style_type) {
  335. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  336. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  337. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  338. }
  339. foreach ($scenes as &$scene) {
  340. $scene_name = getProp($scene, 'scene');
  341. if ($scene_name != $target_scene) continue;
  342. // 优先使用 pic_prompt,如果没有则使用 description
  343. $pic_prompt = getProp($scene, 'pic_prompt');
  344. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  345. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  346. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  347. // 参考图地址
  348. $ref_img_url = getProp($scene, 'url');
  349. if ($ref_img_url) continue; // 已有图片则跳过
  350. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  351. try {
  352. $params = [
  353. 'prompt' => $description,
  354. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  355. ];
  356. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  357. $task_id = $task->id;
  358. if (!$task_id) {
  359. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  360. }
  361. $scene['task_id'] = $task_id;
  362. $scene['task_status'] = 'processing';
  363. } catch (\Exception $e) {
  364. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  365. Utils::throwError("20003:" . $e->getMessage());
  366. }
  367. }
  368. // 保存场景信息
  369. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  370. 'scenes' => json_encode($scenes, 256),
  371. 'generate_status' => '执行中',
  372. 'generate_at' => date('Y-m-d H:i:s'),
  373. 'updated_at' => date('Y-m-d H:i:s')
  374. ]);
  375. if (!$boolen) {
  376. Utils::throwError('20003:保存角色信息失败');
  377. }
  378. return $boolen;
  379. }
  380. public function editAnime($data) {
  381. $anime_id = getProp($data, 'anime_id');
  382. $anime_name = trim(getProp($data, 'anime_name'));
  383. // 确认对话名称唯一性
  384. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  385. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  386. }
  387. if (!$anime_id || !$anime_name) {
  388. Utils::throwError('20003:参数异常');
  389. }
  390. return DB::table('mp_animes')->where('id', $anime_id)->update([
  391. 'anime_name' => $anime_name,
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. // $script_arr =getProp($data, 'script', []);
  395. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  396. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  397. // $anime_id = getProp($data, 'anime_id');
  398. // try {
  399. // DB::beginTransaction();
  400. // $table_data = [
  401. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  402. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  403. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  404. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  405. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  406. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  407. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  408. // 'status' => 3,
  409. // 'start_episode_sequence' => $start_episode_sequence,
  410. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  411. // 'episode_num' => count($script_arr['episodes']),
  412. // 'updated_at' => date('Y-m-d H:i:s')
  413. // ];
  414. // // 保存剧本内容
  415. // if (!empty($anime_id)) {
  416. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  417. // if (!$boolen) {
  418. // dLog('anime')->info('对话保存失败', $table_data);
  419. // Utils::throwError('20003:对话保存失败');
  420. // }
  421. // }else {
  422. // $table['created_at'] = $table_data['updated_at'];
  423. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  424. // if (!$anime_id) {
  425. // dLog('anime')->info('对话保存失败', $table_data);
  426. // Utils::throwError('20003:对话保存失败');
  427. // }
  428. // }
  429. // // 保存分集内容
  430. // // 删除历史分集内容
  431. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  432. // $episodes = [];
  433. // $sequence = 1;
  434. // foreach ($script_arr['episodes'] as $episode) {
  435. // $segment_number = 1;
  436. // foreach($episode['segments'] as $segment) {
  437. // $episodes[] = [
  438. // 'anime_id' => $anime_id,
  439. // 'episode_number' => $episode['episode_number'],
  440. // 'title' => $episode['title'],
  441. // // 'content' => $episode['content'],
  442. // 'content' => '',
  443. // 'segment_number' => $segment_number,
  444. // 'segment_content' => $segment['segment_content'],
  445. // 'sequence' => $sequence,
  446. // 'created_at' => date('Y-m-d H:i:s'),
  447. // 'updated_at' => date('Y-m-d H:i:s')
  448. // ];
  449. // $sequence++;
  450. // $segment_number++;
  451. // }
  452. // }
  453. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  454. // if (!$boolen2) {
  455. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  456. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  457. // Utils::throwError('20003:分集内容保存失败');
  458. // }
  459. // } catch (\Exception $e) {
  460. // DB::rollBack();
  461. // Utils::throwError('20003:'.$e->getMessage());
  462. // }
  463. // DB::commit();
  464. // return true;
  465. }
  466. public function delAnime($data) {
  467. $anime_id = getProp($data, 'anime_id');
  468. if (!$anime_id) {
  469. Utils::throwError('20003:请选择剧本');
  470. }
  471. return DB::table('mp_animes')->where('id', $anime_id)->update([
  472. 'is_deleted' => 1,
  473. 'updated_at' => date('Y-m-d H:i:s')
  474. ]);
  475. }
  476. public function animeDetail($data) {
  477. $uid = Site::getUid();
  478. $anime_id = getProp($data, 'anime_id');
  479. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  480. ->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();
  481. if (!$anime) Utils::throwError('20003:权限不足');
  482. $anime = (array)$anime;
  483. $anime['roles'] = json_decode($anime['roles']);
  484. $anime['scenes'] = json_decode($anime['scenes']);
  485. // 获取分集信息
  486. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  487. ->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"))
  488. ->orderBy('episode_number')->get()->map(function ($value) {
  489. return (array)$value;
  490. })->toArray();
  491. $anime['episodes'] = $episodes;
  492. return $anime;
  493. }
  494. public function episodeInfo($data) {
  495. $uid = Site::getUid();
  496. $anime_id = getProp($data, 'anime_id');
  497. $episode_id = getProp($data, 'episode_id');
  498. if (!$anime_id || !$episode_id) {
  499. Utils::throwError('1002:请选择剧集');
  500. }
  501. // 验证用户权限
  502. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  503. if (!$anime) Utils::throwError('20003:权限不足');
  504. $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();
  505. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  506. $episode = (array)$episode;
  507. $episode['roles'] = json_decode($episode['roles'], true);
  508. // foreach($episode['roles'] as &$item) {
  509. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  510. // }
  511. $episode['scenes'] = json_decode($episode['scenes'], true);
  512. // foreach($episode['scenes'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  514. // }
  515. // 获取分镜信息
  516. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  517. ->select('*')->get()->map(function ($value) {
  518. return (array)$value;
  519. })->toArray();
  520. // 使用公共方法构建分镜结构
  521. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  522. $episode['acts'] = $segmentsStructure['acts'];
  523. $episode['total_duration'] = $segmentsStructure['total_duration'];
  524. return $episode;
  525. }
  526. public function episodeInfoForAce($data) {
  527. $anime_id = getProp($data, 'anime_id');
  528. $episode_id = getProp($data, 'episode_id');
  529. if (!$anime_id || !$episode_id) {
  530. Utils::throwError('1002:请选择剧集');
  531. }
  532. $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();
  533. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  534. $episode = (array)$episode;
  535. $episode['roles'] = json_decode($episode['roles'], true);
  536. // foreach($episode['roles'] as &$item) {
  537. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  538. // }
  539. $episode['scenes'] = json_decode($episode['scenes'], true);
  540. // foreach($episode['scenes'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  542. // }
  543. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  544. // 获取分镜信息
  545. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  546. ->select('*')->get()->map(function ($value) {
  547. return (array)$value;
  548. })->toArray();
  549. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  550. $episode['acts'] = $segmentsStructure['acts'];
  551. $episode['total_duration'] = $segmentsStructure['total_duration'];
  552. return $episode;
  553. }
  554. public function segmentInfo($data) {
  555. $uid = Site::getUid();
  556. $segment_id = getProp($data, 'segment_id');
  557. if (!$segment_id) {
  558. Utils::throwError('1002:请选择分镜');
  559. }
  560. // 获取分镜信息
  561. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  562. // 验证用户权限
  563. if ($segment) {
  564. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  565. if (!$anime) Utils::throwError('20003:权限不足');
  566. }
  567. $result = [
  568. 'segment_id' => getProp($segment, 'segment_id'),
  569. 'segment_number' => getProp($segment, 'segment_number'),
  570. 'segment_content' => getProp($segment, 'segment_content'),
  571. 'description' => getProp($segment, 'description'),
  572. 'composition' => getProp($segment, 'composition'),
  573. 'camera_movement' => getProp($segment, 'camera_movement'),
  574. 'voice_actor' => getProp($segment, 'voice_actor'),
  575. 'dialogue' => getProp($segment, 'dialogue'),
  576. 'frame_type' => getProp($segment, 'frame_type'),
  577. 'scene' => getProp($segment, 'scene'),
  578. 'characters' => getProp($segment, 'characters'),
  579. 'tail_frame' => getProp($segment, 'tail_frame'),
  580. 'emotion' => getProp($segment, 'emotion'),
  581. 'emotion_type' => getProp($segment, 'emotion_type'),
  582. 'gender' => getProp($segment, 'gender'),
  583. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  584. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  585. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  586. 'pitch' => getProp($segment, 'pitch'),
  587. 'voice_name' => getProp($segment, 'voice_name'),
  588. 'voice_type' => getProp($segment, 'voice_type'),
  589. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  590. 'img_url' => getProp($segment, 'img_url'),
  591. 'video_url' => getProp($segment, 'video_url'),
  592. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  593. ];
  594. return $result;
  595. }
  596. public function copyEpisodeVersion($data) {
  597. $episode_id = getProp($data, 'episode_id');
  598. $uid = Site::getUid();
  599. $cpid = Site::getCpid();
  600. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  601. if (!$episode) Utils::throwError('20003:该剧集不存在');
  602. $episode = (array)$episode;
  603. $anime_id = $episode['anime_id'];
  604. $episode_number = $episode['episode_number'];
  605. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  606. $sequence = $count + 1;
  607. unset($episode['id']);
  608. $now = date('Y-m-d H:i:s');
  609. $episode['created_at'] = $now;
  610. $episode['updated_at'] = $now;
  611. $episode['is_default'] = 1;
  612. // 获取版本中含有"(副本"字样的个数
  613. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  614. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  615. $episode['sequence'] = $sequence;
  616. $episode['is_generated'] = 0;
  617. $episode['cpid'] = $cpid;
  618. // 获取ace_mode
  619. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  620. try {
  621. DB::beginTransaction();
  622. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  623. // 新增副本
  624. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  625. if (!$new_episode_id) {
  626. Utils::throwError('20003:创建副本失败!');
  627. }
  628. // 获取分镜数据并准备插入
  629. $segments_for_insert = DB::table('mp_episode_segments')
  630. ->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')
  631. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  632. $item = (array)$item;
  633. $item['episode_id'] = $new_episode_id;
  634. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  635. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  636. return $item;
  637. })->toArray();
  638. // 写入分镜数据
  639. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  640. if (!$boolen2) {
  641. Utils::throwError('20003:写入分镜数据失败!');
  642. }
  643. // 写入对话历史
  644. $records = [
  645. [
  646. 'uid' => $uid,
  647. 'anime_id' => $anime_id,
  648. 'role' => 'user',
  649. 'content' => '创建副本',
  650. 'sequence' => $episode_number,
  651. 'episode_id' => $new_episode_id,
  652. 'created_at' => $now,
  653. 'updated_at' => $now
  654. ],
  655. [
  656. 'uid' => $uid,
  657. 'anime_id' => $anime_id,
  658. 'role' => 'assistant',
  659. 'content' => '好的,已为您创建副本',
  660. 'sequence' => $episode_number,
  661. 'episode_id' => $new_episode_id,
  662. 'created_at' => $now,
  663. 'updated_at' => $now
  664. ]
  665. ];
  666. $boolen3 = DB::table('mp_anime_records')->insert($records);
  667. if (!$boolen3) {
  668. Utils::throwError('20003:对话记录保存失败');
  669. }
  670. }catch (\Exception $e) {
  671. DB::rollBack();
  672. Utils::throwError('20003:'.$e->getMessage());
  673. }
  674. DB::commit();
  675. // 构建与 episodeInfo 方法一致的返回数据结构
  676. $result = [
  677. 'episode_id' => $new_episode_id,
  678. 'anime_id' => $anime_id,
  679. 'episode_number' => $episode_number,
  680. 'title' => $episode['title'],
  681. 'intro' => $episode['intro'],
  682. 'art_style' => $episode['art_style'],
  683. 'roles' => json_decode($episode['roles'], true),
  684. 'scenes' => json_decode($episode['scenes'], true),
  685. 'is_generated' => (int)$episode['is_generated']
  686. ];
  687. if ((int)$ace_mode === 1) {
  688. // 获取分镜信息
  689. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  690. ->select('*')->get()->map(function ($value) {
  691. return (array)$value;
  692. })->toArray();
  693. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  694. }else {
  695. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  696. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  697. }
  698. $result['acts'] = $segmentsStructure['acts'];
  699. $result['total_duration'] = $segmentsStructure['total_duration'];
  700. return $result;
  701. }
  702. public function episodeVersions($data) {
  703. $anime_id = getProp($data, 'anime_id');
  704. $episode_id = getProp($data, 'episode_id');
  705. if (!$anime_id || !$episode_id) {
  706. Utils::throwError('1002:请选择剧集');
  707. }
  708. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  709. $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) {
  710. return (array)$value;
  711. })->toArray();
  712. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  713. foreach($episodes as &$episode) {
  714. $episode['version'] = 'V'.$episode['sequence'];
  715. $episode['roles'] = json_decode($episode['roles'], true);
  716. $episode['scenes'] = json_decode($episode['scenes'], true);
  717. // 获取分镜信息
  718. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  719. ->select('*')->get()->map(function ($value) {
  720. return (array)$value;
  721. })->toArray();
  722. // 使用公共方法构建分镜结构
  723. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  724. $episode['acts'] = $segmentsStructure['acts'];
  725. $episode['total_duration'] = $segmentsStructure['total_duration'];
  726. }
  727. return $episodes;
  728. }
  729. public function bindEpisodeVersion($data) {
  730. $episode_id = getProp($data, 'episode_id');
  731. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  732. if (!$episode) Utils::throwError('20003:该剧集不存在');
  733. $episode = (array)$episode;
  734. if ((int)$episode['is_default'] === 1) return true;
  735. try {
  736. DB::beginTransaction();
  737. // 移除is_default标志
  738. $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')]);
  739. if (!$boolen) {
  740. Utils::throwError('20003:更新失败!');
  741. }
  742. // 绑定副本
  743. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  744. if (!$boolen2) {
  745. Utils::throwError('20003:绑定失败!');
  746. }
  747. }catch (\Exception $e) {
  748. DB::rollBack();
  749. Utils::throwError('20003:'.$e->getMessage());
  750. }
  751. DB::commit();
  752. return true;
  753. }
  754. public function chatChangeImg($data) {
  755. $segment_id = getProp($data, 'segment_id');
  756. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  757. $prompt = getProp($data, 'prompt');
  758. if (!$prompt || !$segment_id) {
  759. Utils::throwError('1002:请输入提示词,并且选择分镜');
  760. }
  761. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  762. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  763. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  764. else $ref_img_url = '';
  765. // $ref_img_url = '';
  766. if (empty($prompt)) {
  767. if (empty($ref_img_url)) {
  768. $prompt = getProp($segment, 'segment_content');
  769. }else {
  770. $prompt = '请根据图片生成';
  771. }
  772. }
  773. $anime_id = getProp($segment, 'anime_id');
  774. $episode_id = getProp($segment, 'episode_id');
  775. $episode_number = getProp($segment, 'episode_number');
  776. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  777. $ratio = getProp($data, 'ratio');
  778. if (!$ratio) {
  779. $ratio = getProp($episode, 'ratio');
  780. if (!$ratio) $ratio = '9:16';
  781. }
  782. $art_style = getProp($episode, 'art_style');
  783. if ($art_style) {
  784. $prompt = "美术风格:{$art_style}\n{$prompt}";
  785. }
  786. $dimensions = $this->getRatioDimensions($ratio);
  787. $width = $dimensions['width'];
  788. $height = $dimensions['height'];
  789. try {
  790. $params = [
  791. 'alias_segment_id' => $segment_id,
  792. 'prompt' => $prompt,
  793. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  794. 'width' => $width,
  795. 'height' => $height
  796. ];
  797. // 优化提示词(不要生成字幕)
  798. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  799. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  800. $task_id = $task->id;
  801. if (!$task_id) {
  802. Utils::throwError("20003:生成图片失败");
  803. }
  804. // 更新任务ID
  805. $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')]);
  806. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  807. } catch (\Exception $e) {
  808. Utils::throwError("20003:" . $e->getMessage());
  809. }
  810. // 创建任务之后先暂停10s等待异步任务完成
  811. sleep(10);
  812. $img_url = $this->loopGetPicTaskResult($task_id);
  813. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  814. // 图片生成后新增对话记录
  815. try {
  816. $uid = Site::getUid();
  817. $now = date('Y-m-d H:i:s');
  818. // 使用AI反推图片提示词
  819. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  820. // 保存对话记录
  821. $records = [
  822. [
  823. 'uid' => $uid,
  824. 'anime_id' => $anime_id,
  825. 'sequence' => $episode_number,
  826. 'role' => 'user',
  827. 'content' => $prompt,
  828. 'segment_id' => $segment_id,
  829. 'image_url' => '',
  830. 'created_at' => $now,
  831. 'updated_at' => $now
  832. ],
  833. [
  834. 'uid' => $uid,
  835. 'anime_id' => $anime_id,
  836. 'sequence' => $episode_number,
  837. 'role' => 'assistant',
  838. 'content' => $pic_prompt,
  839. 'segment_id' => $segment_id,
  840. 'image_url' => $img_url,
  841. 'created_at' => $now,
  842. 'updated_at' => $now
  843. ]
  844. ];
  845. DB::table('mp_anime_records')->insert($records);
  846. } catch (\Exception $e) {
  847. // 记录日志但不影响主流程
  848. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  849. 'segment_id' => $segment_id,
  850. 'img_url' => $img_url
  851. ]);
  852. logDB('anime', 'error', '保存对话记录失败', [
  853. 'segment_id' => $segment_id,
  854. 'img_url' => $img_url,
  855. 'error' => $e->getMessage()
  856. ]);
  857. }
  858. return $img_url;
  859. }
  860. public function segmentChatHistory($data) {
  861. $segment_id = getProp($data, 'segment_id');
  862. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  863. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  864. $chat = $query->orderBy('id')->get()->map(function ($value) {
  865. $value = (array)$value;
  866. $value['created_at'] = transDate($value['created_at']);
  867. return $value;
  868. })->toArray();
  869. // 获取历史图片
  870. $url = [];
  871. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  872. foreach($pic_history as $task) {
  873. $result_url = getProp($task, 'result_url');
  874. if (is_json($result_url)) {
  875. $url = array_merge($url, json_decode($result_url, true));
  876. }else {
  877. $url[] = $result_url;
  878. }
  879. }
  880. // 获取历史视频
  881. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  882. foreach($video_history as $task) {
  883. $result_url = getProp($task, 'compressed_url');
  884. if (is_json($result_url)) {
  885. $url = array_merge($url, json_decode($result_url, true));
  886. }else {
  887. $url[] = $result_url;
  888. }
  889. }
  890. return compact('chat', 'url');
  891. }
  892. public function changeEpisodeRoles($data) {
  893. $anime_id = getProp($data, 'anime_id');
  894. $episode_id = getProp($data, 'episode_id');
  895. $target_roles = getProp($data, 'roles');
  896. $is_deleted = getProp($data, 'is_deleted', 0);
  897. // 参数验证
  898. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  899. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  900. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  901. // 验证剧集是否存在
  902. $episode = DB::table('mp_anime_episodes')
  903. ->where('anime_id', $anime_id)
  904. ->where('id', $episode_id)
  905. ->first();
  906. if (!$episode) Utils::throwError('20003:该剧集不存在');
  907. $roles = json_decode(getProp($episode, 'roles'), true);
  908. // 获取anime信息,检查是否有关联的script_id
  909. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  910. if (!$anime) Utils::throwError('20003:动漫不存在');
  911. $script_id = getProp($anime, 'script_id');
  912. $episode_number = getProp($episode, 'episode_number', 1);
  913. $uid = Site::getUid();
  914. $cpid = Site::getCpid();
  915. try {
  916. $target_role_name = getProp($target_roles, 'role');
  917. // 如果是删除操作
  918. if ($is_deleted == 1) {
  919. // 从角色列表中移除该角色
  920. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  921. return getProp($role, 'role') !== $target_role_name;
  922. }));
  923. // 更新角色列表
  924. $result = DB::table('mp_anime_episodes')
  925. ->where('anime_id', $anime_id)
  926. ->where('id', $episode_id)
  927. ->update([
  928. 'roles' => json_encode($roles, 256),
  929. 'updated_at' => date('Y-m-d H:i:s')
  930. ]);
  931. if ($result === false) {
  932. Utils::throwError('20003:删除角色失败');
  933. }
  934. } else {
  935. // 新增或更新操作
  936. $role_found = false;
  937. $is_new_role = false;
  938. // 查找并更新已存在的角色
  939. foreach($roles as &$role) {
  940. if (getProp($role, 'role') === $target_role_name) {
  941. $role = $target_roles;
  942. $role_found = true;
  943. break;
  944. }
  945. }
  946. // 如果角色不存在,则新增
  947. if (!$role_found) {
  948. $roles[] = $target_roles;
  949. $is_new_role = true;
  950. }
  951. // 更新角色列表
  952. $result = DB::table('mp_anime_episodes')
  953. ->where('anime_id', $anime_id)
  954. ->where('id', $episode_id)
  955. ->update([
  956. 'roles' => json_encode($roles, 256),
  957. 'updated_at' => date('Y-m-d H:i:s')
  958. ]);
  959. if ($result === false) {
  960. Utils::throwError('20003:更新角色列表失败');
  961. }
  962. // 同步更新分镜表中对应主体的音色信息
  963. $voice_name = getProp($target_roles, 'voice_name');
  964. $voice_type = getProp($target_roles, 'voice_type');
  965. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  966. DB::table('mp_episode_segments')
  967. ->where('anime_id', $anime_id)
  968. ->where('episode_id', $episode_id)
  969. ->where('voice_actor', $target_role_name)
  970. ->update([
  971. 'voice_name' => $voice_name,
  972. 'voice_type' => $voice_type,
  973. 'voice_audio_url' => $voice_audio_url,
  974. 'updated_at' => date('Y-m-d H:i:s')
  975. ]);
  976. // 如果有关联的script_id,则同步到mp_products表
  977. if ($script_id) {
  978. // 查询剧本信息
  979. $script = DB::table('mp_scripts')
  980. ->where('id', $script_id)
  981. ->where('is_deleted', 0)
  982. ->first();
  983. if ($script) {
  984. $script_name = $script->script_name ?? 'script_' . $script_id;
  985. $product_name = getProp($target_roles, 'role');
  986. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  987. $url = getProp($target_roles, 'url', '');
  988. $product_type = 1; // 1=角色
  989. // 查找或创建以script_name命名的文件夹
  990. $folder = DB::table('mp_products')
  991. ->where('cpid', $cpid)
  992. ->where('type', 2) // 文件夹类型
  993. ->where('product', $product_type) // 角色类型
  994. ->where('product_name', $script_name)
  995. ->where('parent_id', 0)
  996. ->where('is_deleted', 0)
  997. ->first();
  998. if (!$folder) {
  999. // 创建文件夹
  1000. $folder_id = DB::table('mp_products')->insertGetId([
  1001. 'user_id' => $uid,
  1002. 'cpid' => $cpid,
  1003. 'type' => 2, // 文件夹
  1004. 'product' => $product_type, // 角色类型
  1005. 'parent_id' => 0,
  1006. 'level' => 1,
  1007. 'product_name' => $script_name,
  1008. 'sort_order' => time(),
  1009. 'is_deleted' => 0,
  1010. 'created_at' => date('Y-m-d H:i:s'),
  1011. 'updated_at' => date('Y-m-d H:i:s')
  1012. ]);
  1013. } else {
  1014. $folder_id = $folder->id;
  1015. }
  1016. // 查找该文件夹下是否已存在同名资产
  1017. $existing_product = DB::table('mp_products')
  1018. ->where('cpid', $cpid)
  1019. ->where('type', 1) // 资产类型
  1020. ->where('product', $product_type)
  1021. ->where('parent_id', $folder_id)
  1022. ->where('product_name', $product_name)
  1023. ->where('is_deleted', 0)
  1024. ->first();
  1025. if ($existing_product) {
  1026. // 更新已存在的资产
  1027. $updateData = [
  1028. 'pic_task_status' => '生成成功',
  1029. ];
  1030. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1031. if ($url) $updateData['url'] = $url;
  1032. // 处理versions字段
  1033. $versions = getProp($target_roles, 'versions', []);
  1034. if ($versions && is_array($versions)) {
  1035. $updateData['versions'] = json_encode($versions, 256);
  1036. }
  1037. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1038. DB::table('mp_products')
  1039. ->where('id', $existing_product->id)
  1040. ->update($updateData);
  1041. $product_id = $existing_product->id;
  1042. } else {
  1043. // 创建新资产
  1044. $versions = getProp($target_roles, 'versions', []);
  1045. $product_id = DB::table('mp_products')->insertGetId([
  1046. 'user_id' => $uid,
  1047. 'cpid' => $cpid,
  1048. 'type' => 1, // 资产
  1049. 'product' => $product_type, // 角色
  1050. 'parent_id' => $folder_id,
  1051. 'level' => 2,
  1052. 'product_name' => $product_name,
  1053. 'url' => $url,
  1054. 'pic_prompt' => $pic_prompt,
  1055. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1056. 'sort_order' => time(),
  1057. 'is_deleted' => 0,
  1058. 'pic_task_status' => '生成成功',
  1059. 'created_at' => date('Y-m-d H:i:s'),
  1060. 'updated_at' => date('Y-m-d H:i:s')
  1061. ]);
  1062. }
  1063. // 建立或更新绑定关系
  1064. $existing_mapping = DB::table('mp_script_product_mappings')
  1065. ->where('script_id', $script_id)
  1066. ->where('product_id', $product_id)
  1067. ->where('episode_number', $episode_number)
  1068. ->first();
  1069. if (!$existing_mapping) {
  1070. // 创建绑定关系
  1071. DB::table('mp_script_product_mappings')->insert([
  1072. 'script_id' => $script_id,
  1073. 'product_id' => $product_id,
  1074. 'episode_number' => $episode_number,
  1075. 'created_at' => date('Y-m-d H:i:s'),
  1076. 'updated_at' => date('Y-m-d H:i:s')
  1077. ]);
  1078. }
  1079. }
  1080. }
  1081. }
  1082. } catch (\Exception $e) {
  1083. dLog('anime')->error('更新剧集角色失败', [
  1084. 'anime_id' => $anime_id,
  1085. 'episode_id' => $episode_id,
  1086. 'error' => $e->getMessage()
  1087. ]);
  1088. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1089. }
  1090. return true;
  1091. }
  1092. public function changeEpisodeScenes($data) {
  1093. $anime_id = getProp($data, 'anime_id');
  1094. $episode_id = getProp($data, 'episode_id');
  1095. $target_scenes = getProp($data, 'scenes');
  1096. $is_deleted = getProp($data, 'is_deleted', 0);
  1097. // 参数验证
  1098. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1099. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1100. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1101. // 验证剧集是否存在
  1102. $episode = DB::table('mp_anime_episodes')
  1103. ->where('anime_id', $anime_id)
  1104. ->where('id', $episode_id)
  1105. ->first();
  1106. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1107. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1108. // 获取anime信息,检查是否有关联的script_id
  1109. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1110. if (!$anime) Utils::throwError('20003:动漫不存在');
  1111. $script_id = getProp($anime, 'script_id');
  1112. $episode_number = getProp($episode, 'episode_number', 1);
  1113. $uid = Site::getUid();
  1114. $cpid = Site::getCpid();
  1115. try {
  1116. $target_scene_name = getProp($target_scenes, 'scene');
  1117. // 如果是删除操作
  1118. if ($is_deleted == 1) {
  1119. // 从场景列表中移除该场景
  1120. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1121. return getProp($scene, 'scene') !== $target_scene_name;
  1122. }));
  1123. // 更新场景列表
  1124. $result = DB::table('mp_anime_episodes')
  1125. ->where('anime_id', $anime_id)
  1126. ->where('id', $episode_id)
  1127. ->update([
  1128. 'scenes' => json_encode($scenes, 256),
  1129. 'updated_at' => date('Y-m-d H:i:s')
  1130. ]);
  1131. if ($result === false) {
  1132. Utils::throwError('20003:删除场景失败');
  1133. }
  1134. } else {
  1135. // 新增或更新操作
  1136. $scene_found = false;
  1137. $is_new_scene = false;
  1138. // 查找并更新已存在的场景
  1139. foreach($scenes as &$scene) {
  1140. if (getProp($scene, 'scene') === $target_scene_name) {
  1141. $scene = $target_scenes;
  1142. $scene_found = true;
  1143. break;
  1144. }
  1145. }
  1146. // 如果场景不存在,则新增
  1147. if (!$scene_found) {
  1148. $scenes[] = $target_scenes;
  1149. $is_new_scene = true;
  1150. }
  1151. // 更新场景列表
  1152. $result = DB::table('mp_anime_episodes')
  1153. ->where('anime_id', $anime_id)
  1154. ->where('id', $episode_id)
  1155. ->update([
  1156. 'scenes' => json_encode($scenes, 256),
  1157. 'updated_at' => date('Y-m-d H:i:s')
  1158. ]);
  1159. if ($result === false) {
  1160. Utils::throwError('20003:更新场景列表失败');
  1161. }
  1162. // 如果有关联的script_id,则同步到mp_products表
  1163. if ($script_id) {
  1164. // 查询剧本信息
  1165. $script = DB::table('mp_scripts')
  1166. ->where('id', $script_id)
  1167. ->where('is_deleted', 0)
  1168. ->first();
  1169. if ($script) {
  1170. $script_name = $script->script_name ?? 'script_' . $script_id;
  1171. $product_name = getProp($target_scenes, 'scene');
  1172. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1173. $url = getProp($target_scenes, 'url', '');
  1174. $product_type = 2; // 2=场景
  1175. // 查找或创建以script_name命名的文件夹
  1176. $folder = DB::table('mp_products')
  1177. ->where('cpid', $cpid)
  1178. ->where('type', 2) // 文件夹类型
  1179. ->where('product', $product_type) // 场景类型
  1180. ->where('product_name', $script_name)
  1181. ->where('parent_id', 0)
  1182. ->where('is_deleted', 0)
  1183. ->first();
  1184. if (!$folder) {
  1185. // 创建文件夹
  1186. $folder_id = DB::table('mp_products')->insertGetId([
  1187. 'user_id' => $uid,
  1188. 'cpid' => $cpid,
  1189. 'type' => 2, // 文件夹
  1190. 'product' => $product_type, // 场景类型
  1191. 'parent_id' => 0,
  1192. 'level' => 1,
  1193. 'product_name' => $script_name,
  1194. 'sort_order' => time(),
  1195. 'is_deleted' => 0,
  1196. 'created_at' => date('Y-m-d H:i:s'),
  1197. 'updated_at' => date('Y-m-d H:i:s')
  1198. ]);
  1199. } else {
  1200. $folder_id = $folder->id;
  1201. }
  1202. // 查找该文件夹下是否已存在同名资产
  1203. $existing_product = DB::table('mp_products')
  1204. ->where('cpid', $cpid)
  1205. ->where('type', 1) // 资产类型
  1206. ->where('product', $product_type)
  1207. ->where('parent_id', $folder_id)
  1208. ->where('product_name', $product_name)
  1209. ->where('is_deleted', 0)
  1210. ->first();
  1211. if ($existing_product) {
  1212. // 更新已存在的资产
  1213. $updateData = [
  1214. 'pic_task_status' => '生成成功'
  1215. ];
  1216. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1217. if ($url) $updateData['url'] = $url;
  1218. // 处理versions字段
  1219. $versions = getProp($target_scenes, 'versions', []);
  1220. if ($versions && is_array($versions)) {
  1221. $updateData['versions'] = json_encode($versions, 256);
  1222. }
  1223. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1224. DB::table('mp_products')
  1225. ->where('id', $existing_product->id)
  1226. ->update($updateData);
  1227. $product_id = $existing_product->id;
  1228. } else {
  1229. // 创建新资产
  1230. $versions = getProp($target_scenes, 'versions', []);
  1231. $product_id = DB::table('mp_products')->insertGetId([
  1232. 'user_id' => $uid,
  1233. 'cpid' => $cpid,
  1234. 'type' => 1, // 资产
  1235. 'product' => $product_type, // 场景
  1236. 'parent_id' => $folder_id,
  1237. 'level' => 2,
  1238. 'product_name' => $product_name,
  1239. 'url' => $url,
  1240. 'pic_prompt' => $pic_prompt,
  1241. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1242. 'sort_order' => time(),
  1243. 'is_deleted' => 0,
  1244. 'pic_task_status' => '生成成功',
  1245. 'created_at' => date('Y-m-d H:i:s'),
  1246. 'updated_at' => date('Y-m-d H:i:s')
  1247. ]);
  1248. }
  1249. // 建立或更新绑定关系
  1250. $existing_mapping = DB::table('mp_script_product_mappings')
  1251. ->where('script_id', $script_id)
  1252. ->where('product_id', $product_id)
  1253. ->where('episode_number', $episode_number)
  1254. ->first();
  1255. if (!$existing_mapping) {
  1256. // 创建绑定关系
  1257. DB::table('mp_script_product_mappings')->insert([
  1258. 'script_id' => $script_id,
  1259. 'product_id' => $product_id,
  1260. 'episode_number' => $episode_number,
  1261. 'created_at' => date('Y-m-d H:i:s'),
  1262. 'updated_at' => date('Y-m-d H:i:s')
  1263. ]);
  1264. }
  1265. }
  1266. }
  1267. }
  1268. } catch (\Exception $e) {
  1269. dLog('anime')->error('更新剧集场景失败', [
  1270. 'anime_id' => $anime_id,
  1271. 'episode_id' => $episode_id,
  1272. 'error' => $e->getMessage()
  1273. ]);
  1274. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1275. }
  1276. return true;
  1277. }
  1278. public function changeEpisodeProps($data) {
  1279. $anime_id = getProp($data, 'anime_id');
  1280. $episode_id = getProp($data, 'episode_id');
  1281. $target_props = getProp($data, 'props');
  1282. $is_deleted = getProp($data, 'is_deleted', 0);
  1283. // 参数验证
  1284. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1285. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1286. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1287. // 验证剧集是否存在
  1288. $episode = DB::table('mp_anime_episodes')
  1289. ->where('anime_id', $anime_id)
  1290. ->where('id', $episode_id)
  1291. ->first();
  1292. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1293. $props = json_decode(getProp($episode, 'props'), true);
  1294. // 获取anime信息,检查是否有关联的script_id
  1295. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1296. if (!$anime) Utils::throwError('20003:动漫不存在');
  1297. $script_id = getProp($anime, 'script_id');
  1298. $episode_number = getProp($episode, 'episode_number', 1);
  1299. $uid = Site::getUid();
  1300. $cpid = Site::getCpid();
  1301. try {
  1302. $target_prop_name = getProp($target_props, 'prop');
  1303. // 如果是删除操作
  1304. if ($is_deleted == 1) {
  1305. // 从道具列表中移除该道具
  1306. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1307. return getProp($prop, 'prop') !== $target_prop_name;
  1308. }));
  1309. // 更新道具列表
  1310. $result = DB::table('mp_anime_episodes')
  1311. ->where('anime_id', $anime_id)
  1312. ->where('id', $episode_id)
  1313. ->update([
  1314. 'props' => json_encode($props, 256),
  1315. 'updated_at' => date('Y-m-d H:i:s')
  1316. ]);
  1317. if ($result === false) {
  1318. Utils::throwError('20003:删除道具失败');
  1319. }
  1320. } else {
  1321. // 新增或更新操作
  1322. $prop_found = false;
  1323. $is_new_prop = false;
  1324. // 查找并更新已存在的道具
  1325. foreach($props as &$prop) {
  1326. if (getProp($prop, 'prop') === $target_prop_name) {
  1327. $prop = $target_props;
  1328. $prop_found = true;
  1329. break;
  1330. }
  1331. }
  1332. // 如果道具不存在,则新增
  1333. if (!$prop_found) {
  1334. $props[] = $target_props;
  1335. $is_new_prop = true;
  1336. }
  1337. // 更新道具列表
  1338. $result = DB::table('mp_anime_episodes')
  1339. ->where('anime_id', $anime_id)
  1340. ->where('id', $episode_id)
  1341. ->update([
  1342. 'props' => json_encode($props, 256),
  1343. 'updated_at' => date('Y-m-d H:i:s')
  1344. ]);
  1345. if ($result === false) {
  1346. Utils::throwError('20003:更新道具列表失败');
  1347. }
  1348. // 如果有关联的script_id,则同步到mp_products表
  1349. if ($script_id) {
  1350. // 查询剧本信息
  1351. $script = DB::table('mp_scripts')
  1352. ->where('id', $script_id)
  1353. ->where('is_deleted', 0)
  1354. ->first();
  1355. if ($script) {
  1356. $script_name = $script->script_name ?? 'script_' . $script_id;
  1357. $product_name = getProp($target_props, 'prop');
  1358. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1359. $url = getProp($target_props, 'url', '');
  1360. $product_type = 3; // 3=道具
  1361. // 查找或创建以script_name命名的文件夹
  1362. $folder = DB::table('mp_products')
  1363. ->where('cpid', $cpid)
  1364. ->where('type', 2) // 文件夹类型
  1365. ->where('product', $product_type) // 道具类型
  1366. ->where('product_name', $script_name)
  1367. ->where('parent_id', 0)
  1368. ->where('is_deleted', 0)
  1369. ->first();
  1370. if (!$folder) {
  1371. // 创建文件夹
  1372. $folder_id = DB::table('mp_products')->insertGetId([
  1373. 'user_id' => $uid,
  1374. 'cpid' => $cpid,
  1375. 'type' => 2, // 文件夹
  1376. 'product' => $product_type, // 道具类型
  1377. 'parent_id' => 0,
  1378. 'level' => 1,
  1379. 'product_name' => $script_name,
  1380. 'sort_order' => time(),
  1381. 'is_deleted' => 0,
  1382. 'created_at' => date('Y-m-d H:i:s'),
  1383. 'updated_at' => date('Y-m-d H:i:s')
  1384. ]);
  1385. } else {
  1386. $folder_id = $folder->id;
  1387. }
  1388. // 查找该文件夹下是否已存在同名资产
  1389. $existing_product = DB::table('mp_products')
  1390. ->where('cpid', $cpid)
  1391. ->where('type', 1) // 资产类型
  1392. ->where('product', $product_type)
  1393. ->where('parent_id', $folder_id)
  1394. ->where('product_name', $product_name)
  1395. ->where('is_deleted', 0)
  1396. ->first();
  1397. if ($existing_product) {
  1398. // 更新已存在的资产
  1399. $updateData = [
  1400. 'pic_task_status' => '生成成功'
  1401. ];
  1402. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1403. if ($url) $updateData['url'] = $url;
  1404. // 处理versions字段
  1405. $versions = getProp($target_props, 'versions', []);
  1406. if ($versions && is_array($versions)) {
  1407. $updateData['versions'] = json_encode($versions, 256);
  1408. }
  1409. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1410. DB::table('mp_products')
  1411. ->where('id', $existing_product->id)
  1412. ->update($updateData);
  1413. $product_id = $existing_product->id;
  1414. } else {
  1415. // 创建新资产
  1416. $versions = getProp($target_props, 'versions', []);
  1417. $product_id = DB::table('mp_products')->insertGetId([
  1418. 'user_id' => $uid,
  1419. 'cpid' => $cpid,
  1420. 'type' => 1, // 资产
  1421. 'product' => $product_type, // 道具
  1422. 'parent_id' => $folder_id,
  1423. 'level' => 2,
  1424. 'product_name' => $product_name,
  1425. 'url' => $url,
  1426. 'pic_prompt' => $pic_prompt,
  1427. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1428. 'sort_order' => time(),
  1429. 'is_deleted' => 0,
  1430. 'pic_task_status' => '生成成功',
  1431. 'created_at' => date('Y-m-d H:i:s'),
  1432. 'updated_at' => date('Y-m-d H:i:s')
  1433. ]);
  1434. }
  1435. // 建立或更新绑定关系
  1436. $existing_mapping = DB::table('mp_script_product_mappings')
  1437. ->where('script_id', $script_id)
  1438. ->where('product_id', $product_id)
  1439. ->where('episode_number', $episode_number)
  1440. ->first();
  1441. if (!$existing_mapping) {
  1442. // 创建绑定关系
  1443. DB::table('mp_script_product_mappings')->insert([
  1444. 'script_id' => $script_id,
  1445. 'product_id' => $product_id,
  1446. 'episode_number' => $episode_number,
  1447. 'created_at' => date('Y-m-d H:i:s'),
  1448. 'updated_at' => date('Y-m-d H:i:s')
  1449. ]);
  1450. }
  1451. }
  1452. }
  1453. }
  1454. } catch (\Exception $e) {
  1455. dLog('anime')->error('更新剧集道具失败', [
  1456. 'anime_id' => $anime_id,
  1457. 'episode_id' => $episode_id,
  1458. 'error' => $e->getMessage()
  1459. ]);
  1460. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1461. }
  1462. return true;
  1463. }
  1464. public function editSegment($data) {
  1465. $segment_id = getProp($data, 'segment_id');
  1466. $segment_content = getProp($data, 'segment_content');
  1467. $image_url = getProp($data, 'image_url');
  1468. $video_url = getProp($data, 'video_url');
  1469. // 参数验证
  1470. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1471. // 验证分镜是否存在
  1472. $segment = DB::table('mp_episode_segments')
  1473. ->where('segment_id', $segment_id)
  1474. ->first();
  1475. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1476. $dubTaskId = 0;
  1477. try {
  1478. DB::beginTransaction();
  1479. // 准备更新数据
  1480. $update_data = [
  1481. 'updated_at' => date('Y-m-d H:i:s')
  1482. ];
  1483. if ($segment_content) {
  1484. // 先将segment_content赋值到update_data
  1485. $update_data['segment_content'] = $segment_content;
  1486. // 使用现有方法分析segment_content,提取各个字段
  1487. $this->handleSegmentContent($update_data);
  1488. // 如果有对话内容,创建视频配音合成任务
  1489. $dialogue = getProp($update_data, 'dialogue');
  1490. if (!empty($dialogue)) {
  1491. $now = date('Y-m-d H:i:s');
  1492. $generate_json = [
  1493. 'text' => $dialogue,
  1494. 'role' => getProp($update_data, 'voice_actor'),
  1495. 'voice_type' => getProp($update_data, 'voice_type'),
  1496. 'voice_name' => getProp($update_data, 'voice_name'),
  1497. 'emotion' => getProp($update_data, 'emotion'),
  1498. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1499. 'gender' => getProp($update_data, 'gender'),
  1500. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1501. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1502. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1503. 'pitch' => getProp($update_data, 'pitch', 0),
  1504. ];
  1505. // 插入视频配音合成任务
  1506. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1507. 'alias_segment_id' => $segment_id,
  1508. 'generate_status' => '执行中',
  1509. 'audio_url' => '',
  1510. 'generate_json' => json_encode($generate_json, 256),
  1511. 'created_at' => $now,
  1512. 'updated_at' => $now,
  1513. ]);
  1514. if (!$dubTaskId) {
  1515. Utils::throwError('20003:创建配音任务失败!');
  1516. }
  1517. $update_data['audio_url'] = '';
  1518. } else {
  1519. // dialogue为空时,直接写入默认音频信息
  1520. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1521. $update_data['audio_duration'] = 2.0;
  1522. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1523. }
  1524. }
  1525. if ($image_url) {
  1526. $update_data['img_url'] = $image_url;
  1527. // 同时写入一个简单的图片生成任务
  1528. $pic_task = [
  1529. 'alias_segment_id' => $segment_id,
  1530. 'ref_img_url' => json_encode([]),
  1531. 'status' => 'success',
  1532. 'result_url' => json_encode([$image_url], 256),
  1533. 'model' => '',
  1534. 'created_at' => date('Y-m-d H:i:s'),
  1535. 'updated_at' => date('Y-m-d H:i:s'),
  1536. ];
  1537. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1538. }
  1539. if ($video_url) {
  1540. $update_data['origin_video_url'] = $video_url;
  1541. $compressed_video_url = compressVideo($video_url);
  1542. $update_data['current_type'] = 2;
  1543. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1544. // 同时写入一个简单的视频生成任务
  1545. $video_task = [
  1546. 'alias_segment_id' => $segment_id,
  1547. 'status' => 'success',
  1548. 'result_url' => $update_data['origin_video_url'],
  1549. 'compressed_url' => $update_data['video_url'],
  1550. 'created_at' => date('Y-m-d H:i:s'),
  1551. 'updated_at' => date('Y-m-d H:i:s'),
  1552. ];
  1553. DB::table('mp_generate_video_tasks')->insert($video_task);
  1554. }
  1555. // 更新分镜信息
  1556. $result = DB::table('mp_episode_segments')
  1557. ->where('segment_id', $segment_id)
  1558. ->update($update_data);
  1559. if ($result === false) {
  1560. Utils::throwError('20003:更新分镜剧本失败');
  1561. }
  1562. DB::commit();
  1563. // 如果有创建音频生成任务则调用API
  1564. if ($dubTaskId) {
  1565. // 请求远程服务器执行生成
  1566. $client = new Client(['timeout' => 300, 'verify' => false]);
  1567. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1568. $response = $result->getBody()->getContents();
  1569. $response_arr = json_decode($response, true);
  1570. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1571. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1572. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1573. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1574. Utils::throwError('20003:火山生成音频失败');
  1575. }
  1576. }
  1577. return true;
  1578. } catch (\Exception $e) {
  1579. DB::rollBack();
  1580. dLog('anime')->error('更新分镜剧本失败', [
  1581. 'segment_id' => $segment_id,
  1582. 'error' => $e->getMessage()
  1583. ]);
  1584. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1585. }
  1586. }
  1587. public function batchSetSegmentPics($data) {
  1588. $anime_id = getProp($data, 'anime_id');
  1589. $episode_id = getProp($data, 'episode_id');
  1590. $ratio = getProp($data, 'ratio');
  1591. $dimensions = $this->getRatioDimensions($ratio);
  1592. $width = $dimensions['width'];
  1593. $height = $dimensions['height'];
  1594. if (!$anime_id || !$episode_id) {
  1595. Utils::throwError('1002:请选择剧集');
  1596. }
  1597. // 获取剧集信息
  1598. $episode = DB::table('mp_anime_episodes')
  1599. ->where('anime_id', $anime_id)
  1600. ->where('id', $episode_id)
  1601. ->where('is_default', 1)
  1602. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1603. ->first();
  1604. if (!$episode) {
  1605. Utils::throwError('20003:该剧集不存在');
  1606. }
  1607. $model = getProp($data, 'model');
  1608. if (!$model) {
  1609. $model = getProp($episode, 'image_model');
  1610. if (!$model) {
  1611. // episode表也没有,使用默认值
  1612. $model = 'doubao-seedream-5-0-lite-260128';
  1613. }
  1614. }
  1615. // 验证模型是否在可用模型表中
  1616. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1617. $model = 'doubao-seedream-5-0-lite-260128';
  1618. }
  1619. $roles = json_decode(getProp($episode, 'roles'), true);
  1620. if (!$roles) {
  1621. Utils::throwError('20003:角色信息格式错误');
  1622. }
  1623. // 构建角色名称到参考图的映射
  1624. $role_map = [];
  1625. foreach ($roles as $role) {
  1626. $role_name = getProp($role, 'role');
  1627. $role_url = getProp($role, 'url');
  1628. if (!empty($role_name) && !empty($role_url)) {
  1629. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1630. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1631. // $role_map[$base_name] = $role_url;
  1632. // 同时保存完整名称的映射
  1633. $role_map[$role_name] = $role_url;
  1634. }
  1635. }
  1636. $scenes = json_decode(getProp($episode, 'roles'), true);
  1637. if (!$scenes) {
  1638. Utils::throwError('20003:场景信息格式错误');
  1639. }
  1640. // 构建角色名称到参考图的映射
  1641. $scene_map = [];
  1642. foreach ($scenes as $scene) {
  1643. $scene_name = getProp($scene, 'scene');
  1644. $scene_url = getProp($scene, 'url');
  1645. if (!empty($scene_name) && !empty($scene_url)) {
  1646. $scene_map[$scene_name] = $scene_url;
  1647. }
  1648. }
  1649. // 获取所有分镜信息
  1650. $segments = DB::table('mp_episode_segments')
  1651. ->where('anime_id', $anime_id)
  1652. ->where('episode_id', $episode_id)
  1653. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1654. ->orderBy('segment_number')
  1655. ->get()
  1656. ->toArray();
  1657. if (empty($segments)) {
  1658. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1659. }
  1660. // 保存图片比例
  1661. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1662. $updated_segments = [];
  1663. $failed_segments = [];
  1664. // 批量为每个分镜生成图片任务
  1665. foreach ($segments as $segment) {
  1666. $segment_id = $segment->segment_id;
  1667. $segment_content = $segment->segment_content;
  1668. if (empty($segment_content)) {
  1669. $failed_segments[] = [
  1670. 'segment_id' => $segment_id,
  1671. 'error' => '分镜内容为空'
  1672. ];
  1673. continue;
  1674. }
  1675. try {
  1676. $dubTaskId = 0;
  1677. // 解析分镜内容,提取画面描述作为主要提示词
  1678. $prompt = $segment_content;
  1679. $ref_img_urls = [];
  1680. // 分镜场景
  1681. $scene = getProp($segment, 'scene');
  1682. $matched_scene = '';
  1683. if (isset($scene_map[$scene])) {
  1684. $img_index = count($ref_img_urls) + 1;
  1685. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1686. $ref_img_urls[] = $scene_map[$scene];
  1687. $matched_scene = $scene;
  1688. }
  1689. // 分镜角色
  1690. $characters = getProp($segment, 'characters');
  1691. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1692. $roles = explode(',', $characters);
  1693. // 从分镜内容中提取涉及的角色
  1694. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1695. // 获取匹配角色的参考图
  1696. foreach ($segment_characters as $character) {
  1697. if (isset($role_map[$character])) {
  1698. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1699. $img_index = count($ref_img_urls) + 1;
  1700. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1701. $ref_img_urls[] = $role_map[$character];
  1702. }
  1703. }
  1704. // 如果没有找到匹配的角色参考图,不使用参考图
  1705. if (empty($ref_img_urls)) {
  1706. $ref_img_urls = [];
  1707. }
  1708. // 准备生成任务参数
  1709. $params = [
  1710. 'model' => $model,
  1711. 'alias_segment_id' => $segment_id,
  1712. 'prompt' => $prompt,
  1713. 'ref_img_urls' => $ref_img_urls,
  1714. 'width' => $width,
  1715. 'height' => $height,
  1716. ];
  1717. // 优化提示词(不要生成字幕)
  1718. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1719. // $task_id = mt_rand(100000, 999999);
  1720. // 调用AI图片生成服务
  1721. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1722. $task_id = $task->id;
  1723. if (!$task_id) {
  1724. $failed_segments[] = [
  1725. 'segment_id' => $segment_id,
  1726. 'error' => '创建生成任务失败'
  1727. ];
  1728. continue;
  1729. }
  1730. $update_data = [
  1731. 'pic_task_id' => $task_id,
  1732. 'pic_task_status' => '生成中',
  1733. 'audio_url' => '',
  1734. 'updated_at' => date('Y-m-d H:i:s')
  1735. ];
  1736. // 如果有对话内容,创建视频配音合成任务
  1737. $dialogue = getProp($segment, 'dialogue');
  1738. if (!empty($dialogue)) {
  1739. $now = date('Y-m-d H:i:s');
  1740. $generate_json = [
  1741. 'text' => $dialogue,
  1742. 'role' => getProp($segment, 'voice_actor'),
  1743. 'voice_type' => getProp($segment, 'voice_type'),
  1744. 'voice_name' => getProp($segment, 'voice_name'),
  1745. 'emotion' => getProp($segment, 'emotion'),
  1746. 'emotion_type' => getProp($segment, 'emotion_type'),
  1747. 'gender' => getProp($segment, 'gender'),
  1748. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1749. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1750. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1751. 'pitch' => getProp($segment, 'pitch', 0),
  1752. ];
  1753. // 插入视频配音合成任务
  1754. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1755. 'alias_segment_id' => $segment_id,
  1756. 'generate_status' => '执行中',
  1757. 'audio_url' => '',
  1758. 'generate_json' => json_encode($generate_json, 256),
  1759. 'created_at' => $now,
  1760. 'updated_at' => $now,
  1761. ]);
  1762. if (!$dubTaskId) {
  1763. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1764. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1765. // Utils::throwError('20003:创建配音任务失败!');
  1766. }
  1767. } else {
  1768. // dialogue为空时,直接写入默认音频信息到分镜表
  1769. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1770. $update_data['audio_duration'] = 2.0;
  1771. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1772. }
  1773. // 更新分镜的任务信息
  1774. $update_result = DB::table('mp_episode_segments')
  1775. ->where('segment_id', $segment_id)
  1776. ->update($update_data);
  1777. // 如果是第一集的首帧图片,则存入待更新数组
  1778. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1779. Redis::sadd('anime_first_frame_urls', $segment_id);
  1780. }
  1781. if ($update_result) {
  1782. $updated_segments[] = [
  1783. 'segment_id' => $segment_id,
  1784. 'task_id' => $task_id,
  1785. 'status' => '生成中',
  1786. 'matched_scenes' => $matched_scene,
  1787. 'matched_roles' => $segment_characters,
  1788. 'ref_urls_count' => count($ref_img_urls)
  1789. ];
  1790. } else {
  1791. $failed_segments[] = [
  1792. 'segment_id' => $segment_id,
  1793. 'error' => '更新分镜任务状态失败'
  1794. ];
  1795. }
  1796. if ($dubTaskId) {
  1797. sleep(1);
  1798. // 请求远程服务器执行生成
  1799. $client = new Client(['timeout' => 300, 'verify' => false]);
  1800. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1801. $response = $result->getBody()->getContents();
  1802. $response_arr = json_decode($response, true);
  1803. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1804. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1805. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1806. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1807. }
  1808. }
  1809. } catch (\Exception $e) {
  1810. $failed_segments[] = [
  1811. 'segment_id' => $segment_id,
  1812. 'error' => $e->getMessage()
  1813. ];
  1814. }
  1815. }
  1816. // 更新剧集生成状态
  1817. if (!empty($updated_segments)) {
  1818. DB::table('mp_anime_episodes')
  1819. ->where('id', $episode_id)
  1820. ->update([
  1821. 'is_generated' => 1,
  1822. 'updated_at' => date('Y-m-d H:i:s')
  1823. ]);
  1824. }
  1825. return [
  1826. 'success_count' => count($updated_segments),
  1827. 'failed_count' => count($failed_segments),
  1828. 'success_segments' => $updated_segments,
  1829. 'failed_segments' => $failed_segments,
  1830. 'total_segments' => count($segments)
  1831. ];
  1832. }
  1833. public function reGenerateSegment($data) {
  1834. $segment_id = getProp($data, 'segment_id');
  1835. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1836. $anime_id = getProp($segment, 'anime_id');
  1837. $episode_id = getProp($segment, 'episode_id');
  1838. $episode_number = getProp($segment, 'episode_number');
  1839. $segment_content = getProp($data, 'segment_content');
  1840. $ratio = getProp($data, 'ratio');
  1841. if (!$ratio) {
  1842. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1843. if (!$ratio) $ratio = '9:16';
  1844. }
  1845. $dimensions = $this->getRatioDimensions($ratio);
  1846. $width = $dimensions['width'];
  1847. $height = $dimensions['height'];
  1848. if (!$anime_id || !$episode_id) {
  1849. Utils::throwError('1002:请选择分镜');
  1850. }
  1851. // 使用文生文模型重新解析segment_content
  1852. if (!empty($segment_content)) {
  1853. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1854. }
  1855. // 获取动漫的角色信息(包含参考图)
  1856. $anime = DB::table('mp_animes')
  1857. ->where('id', $anime_id)
  1858. ->select('roles', 'scenes')
  1859. ->first();
  1860. if (!$anime || !$anime->roles) {
  1861. Utils::throwError('20003:未找到角色信息');
  1862. }
  1863. $roles = json_decode($anime->roles, true);
  1864. if (!$roles) {
  1865. Utils::throwError('20003:角色信息格式错误');
  1866. }
  1867. // 构建角色名称到参考图的映射
  1868. $role_map = [];
  1869. foreach ($roles as $role) {
  1870. $role_name = getProp($role, 'role');
  1871. $role_url = getProp($role, 'url');
  1872. if (!empty($role_name) && !empty($role_url)) {
  1873. $role_map[$role_name] = $role_url;
  1874. }
  1875. }
  1876. $scenes = json_decode($anime->scenes, true);
  1877. if (!$scenes) {
  1878. Utils::throwError('20003:角色信息格式错误');
  1879. }
  1880. // 构建角色名称到参考图的映射
  1881. $scene_map = [];
  1882. foreach ($scenes as $scene) {
  1883. $scene_name = getProp($scene, 'scene');
  1884. $scene_url = getProp($scene, 'url');
  1885. if (!empty($scene_name) && !empty($scene_url)) {
  1886. $scene_map[$scene_name] = $scene_url;
  1887. }
  1888. }
  1889. $segment_id = $segment->segment_id;
  1890. $original_segment_content = $segment->segment_content;
  1891. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1892. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1893. if (empty($final_segment_content)) {
  1894. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1895. }
  1896. try {
  1897. $dubTaskId = 0;
  1898. // 分镜剧本数组
  1899. $update_data = [
  1900. 'segment_content' => $final_segment_content,
  1901. 'pic_task_status' => '生成中',
  1902. 'updated_at' => date('Y-m-d H:i:s')
  1903. ];
  1904. // 解析分镜内容,提取画面描述作为主要提示词
  1905. $prompt = $final_segment_content;
  1906. $ref_img_urls = [];
  1907. // 分镜场景
  1908. $scene = getProp($data, 'scene');
  1909. if ($scene) {
  1910. $matched_scene = '';
  1911. if (isset($scene_map[$scene])) {
  1912. $img_index = count($ref_img_urls) + 1;
  1913. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1914. $ref_img_urls[] = $scene_map[$scene];
  1915. $matched_scene = $scene;
  1916. }
  1917. $update_data['scene'] = $scene;
  1918. }
  1919. // 分镜角色
  1920. $characters = getProp($data, 'characters');
  1921. if ($characters) {
  1922. $update_data['characters'] = $characters;
  1923. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1924. $characters = explode(',', $characters);
  1925. // 从分镜内容中提取涉及的角色
  1926. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1927. // 获取匹配角色的参考图
  1928. foreach ($segment_characters as $character) {
  1929. if (isset($role_map[$character])) {
  1930. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1931. $img_index = count($ref_img_urls) + 1;
  1932. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1933. $ref_img_urls[] = $role_map[$character];
  1934. }
  1935. }
  1936. }
  1937. // 如果没有找到匹配的角色参考图,不使用参考图
  1938. if (empty($ref_img_urls)) {
  1939. $ref_img_urls = [];
  1940. }
  1941. // 准备生成任务参数
  1942. $params = [
  1943. 'alias_segment_id' => $segment_id,
  1944. 'prompt' => $prompt,
  1945. 'ref_img_urls' => $ref_img_urls,
  1946. 'width' => $width,
  1947. 'height' => $height,
  1948. ];
  1949. // 优化提示词(不要生成字幕)
  1950. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1951. // 调用AI图片生成服务
  1952. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1953. $task_id = $task->id;
  1954. if (!$task_id) {
  1955. Utils::throwError('20003:创建生成任务失败!');
  1956. }
  1957. $update_data['pic_task_id'] = $task_id;
  1958. // 更新分镜剧本信息
  1959. $this->handleSegmentContent($update_data);
  1960. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1961. if ($segment_content) {
  1962. $dialogue = getProp($update_data, 'dialogue');
  1963. if (!empty($dialogue)) {
  1964. $now = date('Y-m-d H:i:s');
  1965. $generate_json = [
  1966. 'text' => $dialogue,
  1967. 'role' => getProp($update_data, 'voice_actor'),
  1968. 'voice_type' => getProp($update_data, 'voice_type'),
  1969. 'voice_name' => getProp($update_data, 'voice_name'),
  1970. 'emotion' => getProp($update_data, 'emotion'),
  1971. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1972. 'gender' => getProp($update_data, 'gender'),
  1973. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1974. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1975. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1976. 'pitch' => getProp($update_data, 'pitch', 0),
  1977. ];
  1978. // 插入视频配音合成任务
  1979. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1980. 'alias_segment_id' => $segment_id,
  1981. 'generate_status' => '执行中',
  1982. 'audio_url' => '',
  1983. 'generate_json' => json_encode($generate_json, 256),
  1984. 'created_at' => date('Y-m-d H:i:s'),
  1985. 'updated_at' => date('Y-m-d H:i:s'),
  1986. ]);
  1987. if (!$dubTaskId) {
  1988. Utils::throwError('20003:创建配音任务失败!');
  1989. }
  1990. $update_data['audio_url'] = '';
  1991. } else {
  1992. // dialogue为空时,直接写入默认音频信息
  1993. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1994. $update_data['audio_duration'] = 2.0;
  1995. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1996. }
  1997. }
  1998. $boolen = DB::table('mp_episode_segments')
  1999. ->where('segment_id', $segment_id)
  2000. ->update($update_data);
  2001. // 如果是第一集的首帧图片,则存入待更新数组
  2002. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2003. Redis::sadd('anime_first_frame_urls', $segment_id);
  2004. }
  2005. if ($dubTaskId) {
  2006. // 请求远程服务器执行生成
  2007. $client = new Client(['timeout' => 300, 'verify' => false]);
  2008. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2009. $response = $result->getBody()->getContents();
  2010. $response_arr = json_decode($response, true);
  2011. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2012. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2013. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2014. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2015. Utils::throwError('20003:火山生成音频失败');
  2016. }
  2017. }
  2018. } catch (\Exception $e) {
  2019. $failed_segments[] = [
  2020. 'segment_id' => $segment_id,
  2021. 'error' => $e->getMessage()
  2022. ];
  2023. }
  2024. // 创建任务之后先暂停10s等待异步任务完成
  2025. sleep(10);
  2026. $img_url = $this->loopGetPicTaskResult($task_id);
  2027. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2028. // 图片生成后新增对话记录
  2029. try {
  2030. $uid = Site::getUid();
  2031. $now = date('Y-m-d H:i:s');
  2032. // 使用AI反推图片提示词
  2033. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2034. // 保存对话记录
  2035. $records = [
  2036. [
  2037. 'uid' => $uid,
  2038. 'anime_id' => $anime_id,
  2039. 'sequence' => $episode_number,
  2040. 'role' => 'user',
  2041. 'content' => '重新生成',
  2042. 'segment_id' => $segment_id,
  2043. 'image_url' => '',
  2044. 'created_at' => $now,
  2045. 'updated_at' => $now
  2046. ],
  2047. [
  2048. 'uid' => $uid,
  2049. 'anime_id' => $anime_id,
  2050. 'sequence' => $episode_number,
  2051. 'role' => 'assistant',
  2052. 'content' => $pic_prompt,
  2053. 'segment_id' => $segment_id,
  2054. 'image_url' => $img_url,
  2055. 'created_at' => $now,
  2056. 'updated_at' => $now
  2057. ]
  2058. ];
  2059. DB::table('mp_anime_records')->insert($records);
  2060. } catch (\Exception $e) {
  2061. // 记录日志但不影响主流程
  2062. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2063. 'segment_id' => $segment_id,
  2064. 'img_url' => $img_url
  2065. ]);
  2066. }
  2067. return $img_url;
  2068. }
  2069. public function addSegment($data) {
  2070. $prev_segment_id = getProp($data, 'prev_segment_id');
  2071. $img_url = getProp($data, 'img_url');
  2072. $video_url = getProp($data, 'video_url');
  2073. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2074. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2075. $anime_id = getProp($segment, 'anime_id');
  2076. $episode_id = getProp($segment, 'episode_id');
  2077. $episode_number = getProp($segment, 'episode_number');
  2078. $segment_number = getProp($segment, 'segment_number');
  2079. $new_segment_number = $segment_number + 1;
  2080. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2081. // 分镜剧本数组
  2082. $insert_data = [
  2083. 'anime_id' => $anime_id,
  2084. 'episode_id' => $episode_id,
  2085. 'episode_number' => $episode_number,
  2086. 'act_number' => getProp($segment, 'act_number'),
  2087. 'act_title' => getProp($segment, 'act_title'),
  2088. 'segment_id' => $segment_id,
  2089. 'segment_number' => $new_segment_number,
  2090. 'segment_content' => '',
  2091. 'img_url' => '',
  2092. 'video_url' => '',
  2093. 'created_at' => date('Y-m-d H:i:s'),
  2094. 'updated_at' => date('Y-m-d H:i:s')
  2095. ];
  2096. if ($img_url) $insert_data['img_url'] = $img_url;
  2097. if ($video_url) {
  2098. $insert_data['origin_video_url'] = $video_url;
  2099. $insert_data['current_type'] = 2;
  2100. $compressed_video_url = compressVideo($video_url);
  2101. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2102. }
  2103. try {
  2104. DB::beginTransaction();
  2105. // 先更新序号
  2106. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2107. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2108. if (!$id) {
  2109. Utils::throwError('20003:新增分镜失败!');
  2110. }
  2111. }catch (\Exception $e) {
  2112. DB::rollBack();
  2113. Utils::throwError('20003:'.$e->getMessage());
  2114. }
  2115. DB::commit();
  2116. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2117. $segment = $segment ? (array)$segment : [];
  2118. return $segment;
  2119. // 以下代码暂弃用
  2120. $anime_id = getProp($segment, 'anime_id');
  2121. $episode_id = getProp($segment, 'episode_id');
  2122. $episode_number = getProp($segment, 'episode_number');
  2123. $segment_number = getProp($segment, 'segment_number');
  2124. $segment_content = getProp($data, 'segment_content');
  2125. $img_url = getProp($data, 'img_url');
  2126. $video_url = getProp($data, 'video_url');
  2127. $ratio = getProp($data, 'ratio');
  2128. $dimensions = $this->getRatioDimensions($ratio);
  2129. $width = $dimensions['width'];
  2130. $height = $dimensions['height'];
  2131. if (!$anime_id || !$episode_id) {
  2132. Utils::throwError('1002:请选择分镜');
  2133. }
  2134. // 使用文生文模型重新解析segment_content
  2135. if (!empty($segment_content)) {
  2136. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2137. }
  2138. // 获取动漫的角色信息(包含参考图)
  2139. $anime = DB::table('mp_animes')
  2140. ->where('id', $anime_id)
  2141. ->select('roles', 'scenes')
  2142. ->first();
  2143. if (!$anime || !$anime->roles) {
  2144. Utils::throwError('20003:未找到角色信息');
  2145. }
  2146. $roles = json_decode($anime->roles, true);
  2147. if (!$roles) {
  2148. Utils::throwError('20003:角色信息格式错误');
  2149. }
  2150. // 构建角色名称到参考图的映射
  2151. $role_map = [];
  2152. foreach ($roles as $role) {
  2153. $role_name = getProp($role, 'role');
  2154. $role_url = getProp($role, 'url');
  2155. if (!empty($role_name) && !empty($role_url)) {
  2156. $role_map[$role_name] = $role_url;
  2157. }
  2158. }
  2159. $scenes = json_decode($anime->scenes, true);
  2160. if (!$scenes) {
  2161. Utils::throwError('20003:角色信息格式错误');
  2162. }
  2163. // 构建角色名称到参考图的映射
  2164. $scene_map = [];
  2165. foreach ($scenes as $scene) {
  2166. $scene_name = getProp($scene, 'scene');
  2167. $scene_url = getProp($scene, 'url');
  2168. if (!empty($scene_name) && !empty($scene_url)) {
  2169. $scene_map[$scene_name] = $scene_url;
  2170. }
  2171. }
  2172. $segment_id = $segment->segment_id;
  2173. $original_segment_content = $segment->segment_content;
  2174. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2175. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2176. if (empty($final_segment_content)) {
  2177. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2178. }
  2179. try {
  2180. $dubTaskId = 0;
  2181. DB::beginTransaction();
  2182. $new_segment_number = $segment_number + 1;
  2183. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2184. // 分镜剧本数组
  2185. $insert_data = [
  2186. 'anime_id' => $anime_id,
  2187. 'episode_id' => $episode_id,
  2188. 'episode_number' => $episode_number,
  2189. 'act_number' => getProp($segment, 'act_number'),
  2190. 'act_title' => getProp($segment, 'act_title'),
  2191. 'segment_id' => $segment_id,
  2192. 'segment_number' => $new_segment_number,
  2193. 'segment_content' => $final_segment_content,
  2194. 'img_url' => $img_url,
  2195. 'video_url' => $video_url,
  2196. 'created_at' => date('Y-m-d H:i:s'),
  2197. 'updated_at' => date('Y-m-d H:i:s')
  2198. ];
  2199. // 更新分镜剧本信息
  2200. $this->handleSegmentContent($insert_data);
  2201. // 如果有对话内容,创建视频配音合成任务
  2202. $dialogue = getProp($insert_data, 'dialogue');
  2203. if (!empty($dialogue)) {
  2204. $now = date('Y-m-d H:i:s');
  2205. $generate_json = [
  2206. 'text' => $dialogue,
  2207. 'role' => getProp($insert_data, 'voice_actor'),
  2208. 'voice_type' => getProp($insert_data, 'voice_type'),
  2209. 'voice_name' => getProp($insert_data, 'voice_name'),
  2210. 'emotion' => getProp($insert_data, 'emotion'),
  2211. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2212. 'gender' => getProp($insert_data, 'gender'),
  2213. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2214. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2215. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2216. 'pitch' => getProp($insert_data, 'pitch', 0),
  2217. ];
  2218. // 插入视频配音合成任务
  2219. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2220. 'alias_segment_id' => $segment_id,
  2221. 'generate_status' => '执行中',
  2222. 'audio_url' => '',
  2223. 'generate_json' => json_encode($generate_json, 256),
  2224. 'created_at' => $now,
  2225. 'updated_at' => $now,
  2226. ]);
  2227. if (!$dubTaskId) {
  2228. Utils::throwError('20003:创建配音任务失败!');
  2229. }
  2230. $insert_data['audio_url'] = '';
  2231. } else {
  2232. // dialogue为空时,直接写入默认音频信息
  2233. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2234. $insert_data['audio_duration'] = 2.0;
  2235. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2236. }
  2237. // 如果没有上传图片则使用当前描述进行生成
  2238. if (!$img_url) {
  2239. // 解析分镜内容,提取画面描述作为主要提示词
  2240. $prompt = $final_segment_content;
  2241. $ref_img_urls = [];
  2242. // 分镜场景
  2243. $scene = getProp($insert_data, 'scene');
  2244. if ($scene) {
  2245. $matched_scene = '';
  2246. if (isset($scene_map[$scene])) {
  2247. $img_index = count($ref_img_urls) + 1;
  2248. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2249. $ref_img_urls[] = $scene_map[$scene];
  2250. $matched_scene = $scene;
  2251. }
  2252. $update_data['scene'] = $scene;
  2253. }
  2254. // 分镜角色
  2255. $characters = getProp($insert_data, 'characters');
  2256. if ($characters) {
  2257. $update_data['characters'] = $characters;
  2258. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2259. $characters = explode(',', $characters);
  2260. // 从分镜内容中提取涉及的角色
  2261. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2262. // 获取匹配角色的参考图
  2263. foreach ($segment_characters as $character) {
  2264. if (isset($role_map[$character])) {
  2265. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2266. $img_index = count($ref_img_urls) + 1;
  2267. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2268. $ref_img_urls[] = $role_map[$character];
  2269. }
  2270. }
  2271. }
  2272. // 如果没有找到匹配的角色参考图,不使用参考图
  2273. if (empty($ref_img_urls)) {
  2274. $ref_img_urls = [];
  2275. }
  2276. // 准备生成任务参数
  2277. $params = [
  2278. 'alias_segment_id' => $segment_id,
  2279. 'prompt' => $prompt,
  2280. 'ref_img_urls' => $ref_img_urls,
  2281. 'width' => $width,
  2282. 'height' => $height,
  2283. ];
  2284. // 调用AI图片生成服务
  2285. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2286. $task_id = $task->id;
  2287. // $task_id = 'whatever';
  2288. if (!$task_id) {
  2289. Utils::throwError('20003:创建生成任务失败!');
  2290. }
  2291. $insert_data['pic_task_status'] = '生成中';
  2292. $insert_data['pic_task_id'] = $task_id;
  2293. }
  2294. // 先更新序号
  2295. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2296. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2297. if (!$boolen) {
  2298. Utils::throwError('20003:新增分镜失败!');
  2299. }
  2300. // 如果是第一集的首帧图片,则存入待更新数组
  2301. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2302. Redis::sadd('anime_first_frame_urls', $segment_id);
  2303. }
  2304. if ($dubTaskId) {
  2305. // 请求远程服务器执行生成
  2306. $client = new Client(['timeout' => 300, 'verify' => false]);
  2307. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2308. $response = $result->getBody()->getContents();
  2309. $response_arr = json_decode($response, true);
  2310. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2311. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2312. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2313. Utils::throwError('20003:火山生成音频失败');
  2314. }
  2315. }
  2316. } catch (\Exception $e) {
  2317. DB::rollBack();
  2318. Utils::throwError('20003:'.$e->getMessage());
  2319. }
  2320. DB::commit();
  2321. // 创建任务之后先暂停10s等待异步任务完成
  2322. sleep(10);
  2323. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2324. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2325. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2326. $segment = $segment ? (array)$segment : [];
  2327. return $segment;
  2328. }
  2329. public function copySegment($data) {
  2330. $segment_id = getProp($data, 'segment_id');
  2331. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2332. if (!$segment) Utils::throwError('20003:请选择分镜');
  2333. $anime_id = getProp($segment, 'anime_id');
  2334. $episode_id = getProp($segment, 'episode_id');
  2335. $episode_number = getProp($segment, 'episode_number');
  2336. $segment_number = getProp($segment, 'segment_number');
  2337. $new_segment_id = 0;
  2338. try {
  2339. DB::beginTransaction();
  2340. $segment = (array)$segment;
  2341. unset($segment['id']);
  2342. $segment['segment_number'] += 1;
  2343. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2344. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2345. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2346. // 更新其他分镜序号
  2347. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2348. // 复制分镜
  2349. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2350. if (!$id) {
  2351. Utils::throwError('20003:复制分镜失败');
  2352. }
  2353. }catch (\Exception $e) {
  2354. DB::rollBack();
  2355. Utils::throwError('20003:'.$e->getMessage());
  2356. }
  2357. DB::commit();
  2358. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2359. $segment = $segment ? (array)$segment : [];
  2360. return $segment;
  2361. }
  2362. public function moveSegment($data) {
  2363. $segment_id = getProp($data, 'segment_id');
  2364. $target_segment_id = getProp($data, 'target_segment_id');
  2365. // 获取源分镜信息
  2366. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2367. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2368. // 获取目标分镜信息
  2369. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2370. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2371. $anime_id = getProp($source_segment, 'anime_id');
  2372. $episode_id = getProp($source_segment, 'episode_id');
  2373. $episode_number = getProp($source_segment, 'episode_number');
  2374. $source_segment_number = getProp($source_segment, 'segment_number');
  2375. $target_segment_number = getProp($target_segment, 'segment_number');
  2376. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2377. $target_anime_id = getProp($target_segment, 'anime_id');
  2378. $target_episode_number = getProp($target_segment, 'episode_number');
  2379. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2380. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2381. }
  2382. // 如果源分镜和目标分镜相同,无需移动
  2383. if ($source_segment_number == $target_segment_number) {
  2384. return true;
  2385. }
  2386. try {
  2387. DB::beginTransaction();
  2388. if ($source_segment_number < $target_segment_number) {
  2389. // 向后移动:源分镜移动到目标分镜之后
  2390. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2391. DB::table('mp_episode_segments')
  2392. ->where('anime_id', $anime_id)
  2393. ->where('episode_id', $episode_id)
  2394. ->where('segment_number', '>', $source_segment_number)
  2395. ->where('segment_number', '<=', $target_segment_number)
  2396. ->decrement('segment_number');
  2397. // 2. 将源分镜移动到目标分镜之后
  2398. $new_segment_number = $target_segment_number;
  2399. } else {
  2400. // 向前移动:源分镜移动到目标分镜之后
  2401. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2402. DB::table('mp_episode_segments')
  2403. ->where('anime_id', $anime_id)
  2404. ->where('episode_id', $episode_id)
  2405. ->where('segment_number', '>', $target_segment_number)
  2406. ->where('segment_number', '<', $source_segment_number)
  2407. ->increment('segment_number');
  2408. // 2. 将源分镜移动到目标分镜之后
  2409. $new_segment_number = $target_segment_number + 1;
  2410. }
  2411. // 3. 更新源分镜的序号
  2412. $update_result = DB::table('mp_episode_segments')
  2413. ->where('segment_id', $segment_id)
  2414. ->update([
  2415. 'segment_number' => $new_segment_number,
  2416. 'updated_at' => date('Y-m-d H:i:s')
  2417. ]);
  2418. if (!$update_result) {
  2419. Utils::throwError('20003:更新分镜序号失败');
  2420. }
  2421. DB::commit();
  2422. return true;
  2423. } catch (\Exception $e) {
  2424. DB::rollBack();
  2425. Utils::throwError('20003:' . $e->getMessage());
  2426. }
  2427. }
  2428. public function delSegment($data) {
  2429. $segment_id = getProp($data, 'segment_id');
  2430. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2431. if (!$segment) Utils::throwError('20003:请选择分镜');
  2432. $anime_id = getProp($segment, 'anime_id');
  2433. $episode_id = getProp($segment, 'episode_id');
  2434. $episode_number = getProp($segment, 'episode_number');
  2435. $segment_number = getProp($segment, 'segment_number');
  2436. try {
  2437. DB::beginTransaction();
  2438. // 删除分镜
  2439. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2440. if (!$boolen) {
  2441. Utils::throwError('20003:删除分镜失败');
  2442. }
  2443. // 更新其他分镜序号
  2444. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2445. }catch (\Exception $e) {
  2446. DB::rollBack();
  2447. Utils::throwError('20003:'.$e->getMessage());
  2448. }
  2449. DB::commit();
  2450. return true;
  2451. }
  2452. public function applySegment($data) {
  2453. $segment_id = getProp($data, 'segment_id');
  2454. $url = getProp($data, 'url');
  2455. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2456. if (!$url) Utils::throwError('20003:URL不能为空');
  2457. // 获取URL的文件扩展名
  2458. $urlPath = parse_url($url, PHP_URL_PATH);
  2459. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2460. // 定义图片和视频的扩展名
  2461. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2462. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2463. // 判断是图片还是视频
  2464. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2465. if (in_array($extension, $imageExtensions)) {
  2466. // 图片类型
  2467. $updateData['img_url'] = $url;
  2468. $updateData['current_type'] = 1;
  2469. } elseif (in_array($extension, $videoExtensions)) {
  2470. // 视频类型
  2471. $updateData['video_url'] = $url;
  2472. $updateData['current_type'] = 2;
  2473. } else {
  2474. Utils::throwError('20003:不支持的文件类型');
  2475. }
  2476. // 更新分镜表
  2477. $result = DB::table('mp_episode_segments')
  2478. ->where('segment_id', $segment_id)
  2479. ->update($updateData);
  2480. if (!$result) {
  2481. Utils::throwError('20003:更新分镜失败');
  2482. }
  2483. return true;
  2484. }
  2485. public function segmentHistory($data) {
  2486. $segment_id = getProp($data, 'segment_id');
  2487. // 获取历史图片
  2488. $pics = [];
  2489. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2490. foreach($pic_history as $task) {
  2491. $result_url = getProp($task, 'result_url');
  2492. if (is_json($result_url)) {
  2493. $pics = array_merge($pics, json_decode($result_url, true));
  2494. }else {
  2495. $pics[] = $result_url;
  2496. }
  2497. }
  2498. // 获取历史视频
  2499. $videos = [];
  2500. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2501. foreach($video_history as $task) {
  2502. $result_url = getProp($task, 'result_url');
  2503. if (is_json($result_url)) {
  2504. $videos = array_merge($videos, json_decode($result_url, true));
  2505. }else {
  2506. $videos[] = $result_url;
  2507. }
  2508. }
  2509. return compact('pics', 'videos');
  2510. }
  2511. public function addAct($data) {
  2512. $prev_act_id = getProp($data, 'prev_act_id');
  2513. $act_title = getProp($data, 'act_title', '');
  2514. $act_content = getProp($data, 'act_content', '');
  2515. $act_duration = getProp($data, 'act_duration', 5);
  2516. $video_url = getProp($data, 'video_url');
  2517. // 根据prev_act_id获取记录
  2518. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2519. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2520. $anime_id = getProp($prev_segment, 'anime_id');
  2521. $episode_id = getProp($prev_segment, 'episode_id');
  2522. $episode_number = getProp($prev_segment, 'episode_number');
  2523. $prev_act_number = getProp($prev_segment, 'act_number');
  2524. // 获取新的act_number
  2525. $new_act_number = $prev_act_number + 1;
  2526. try {
  2527. DB::beginTransaction();
  2528. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2529. DB::table('mp_episode_segments')
  2530. ->where('anime_id', $anime_id)
  2531. ->where('episode_id', $episode_id)
  2532. ->where('act_number', '>', $prev_act_number)
  2533. ->increment('act_number');
  2534. // 插入新片段记录
  2535. $insert_data = [
  2536. 'anime_id' => $anime_id,
  2537. 'episode_id' => $episode_id,
  2538. 'episode_number' => $episode_number,
  2539. 'act_number' => $new_act_number,
  2540. 'created_at' => date('Y-m-d H:i:s'),
  2541. 'updated_at' => date('Y-m-d H:i:s')
  2542. ];
  2543. if ($act_title) {
  2544. $insert_data['act_title'] = $act_title;
  2545. }
  2546. if ($act_content) {
  2547. $insert_data['act_content'] = $act_content;
  2548. }
  2549. if ($act_duration) {
  2550. $insert_data['act_duration'] = $act_duration;
  2551. }
  2552. if ($video_url) {
  2553. $insert_data['origin_video_url'] = $video_url;
  2554. $insert_data['current_type'] = 2;
  2555. $compressed_video_url = compressVideo($video_url);
  2556. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2557. }
  2558. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2559. if (!$id) {
  2560. Utils::throwError('20003:新增片段失败!');
  2561. }
  2562. DB::commit();
  2563. }catch (\Exception $e) {
  2564. DB::rollBack();
  2565. Utils::throwError('20003:'.$e->getMessage());
  2566. }
  2567. $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();
  2568. $segment = $segment ? (array)$segment : [];
  2569. return $segment;
  2570. }
  2571. public function editAct($data) {
  2572. $act_id = getProp($data, 'act_id');
  2573. $act_content = getProp($data, 'act_content');
  2574. $act_duration = getProp($data, 'act_duration');
  2575. $act_title = getProp($data, 'act_title');
  2576. $image_url = getProp($data, 'image_url');
  2577. $video_url = getProp($data, 'video_url');
  2578. // 参数验证
  2579. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2580. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2581. $segment = DB::table('mp_episode_segments')
  2582. ->where('id', $act_id)
  2583. ->first();
  2584. if (!$segment) Utils::throwError('20003:该片段不存在');
  2585. try {
  2586. DB::beginTransaction();
  2587. // 准备更新数据
  2588. $update_data = [
  2589. 'updated_at' => date('Y-m-d H:i:s')
  2590. ];
  2591. // 更新act相关字段
  2592. if (!empty($act_content)) {
  2593. $update_data['act_show_content'] = $act_content;
  2594. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2595. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2596. $shot_counter = 0;
  2597. $update_data['act_show_content'] = preg_replace_callback(
  2598. '/【(?:镜头|分镜)(\d+)】/u',
  2599. function($matches) use (&$shot_counter) {
  2600. $shot_counter++;
  2601. return '【镜头' . $shot_counter . '】';
  2602. },
  2603. $update_data['act_show_content']
  2604. );
  2605. }
  2606. if (!empty($act_duration)) {
  2607. $update_data['act_duration'] = $act_duration;
  2608. }
  2609. if (!empty($act_title)) {
  2610. $update_data['act_title'] = $act_title;
  2611. }
  2612. // 处理图片上传
  2613. if ($image_url) {
  2614. $update_data['img_url'] = $image_url;
  2615. $update_data['current_type'] = 1;
  2616. // 同时写入一个图片生成任务记录
  2617. if ($act_id) {
  2618. $pic_task = [
  2619. 'alias_act_id' => $act_id,
  2620. 'ref_img_url' => json_encode([]),
  2621. 'status' => 'success',
  2622. 'result_url' => json_encode([$image_url], 256),
  2623. 'model' => '',
  2624. 'created_at' => date('Y-m-d H:i:s'),
  2625. 'updated_at' => date('Y-m-d H:i:s'),
  2626. ];
  2627. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2628. }
  2629. }
  2630. // 处理视频上传
  2631. if ($video_url) {
  2632. $update_data['origin_video_url'] = $video_url;
  2633. $compressed_video_url = compressVideo($video_url);
  2634. $update_data['current_type'] = 2;
  2635. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2636. // 同时写入一个视频生成任务记录
  2637. if ($act_id) {
  2638. $video_task = [
  2639. 'alias_act_id' => $act_id,
  2640. 'status' => 'success',
  2641. 'result_url' => $update_data['origin_video_url'],
  2642. 'compressed_url' => $update_data['video_url'],
  2643. 'created_at' => date('Y-m-d H:i:s'),
  2644. 'updated_at' => date('Y-m-d H:i:s'),
  2645. ];
  2646. DB::table('mp_generate_video_tasks')->insert($video_task);
  2647. }
  2648. }
  2649. // 更新片段信息
  2650. $result = DB::table('mp_episode_segments')
  2651. ->where('id', $act_id)
  2652. ->update($update_data);
  2653. if ($result === false) {
  2654. Utils::throwError('20003:更新片段失败');
  2655. }
  2656. DB::commit();
  2657. // 返回新复制的记录
  2658. $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();
  2659. $new_segment = (array)$new_segment;
  2660. return $new_segment;
  2661. } catch (\Exception $e) {
  2662. DB::rollBack();
  2663. dLog('anime')->error('更新片段失败', [
  2664. 'act_id' => $act_id,
  2665. 'error' => $e->getMessage()
  2666. ]);
  2667. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2668. }
  2669. }
  2670. public function copyAct($data) {
  2671. $act_id = getProp($data, 'act_id');
  2672. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2673. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2674. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2675. $anime_id = getProp($source_segment, 'anime_id');
  2676. $episode_id = getProp($source_segment, 'episode_id');
  2677. $episode_number = getProp($source_segment, 'episode_number');
  2678. $act_number = getProp($source_segment, 'act_number');
  2679. try {
  2680. DB::beginTransaction();
  2681. // 新act的编号
  2682. $new_act_number = $act_number + 1;
  2683. // 更新后续所有act的act_number
  2684. DB::table('mp_episode_segments')
  2685. ->where('anime_id', $anime_id)
  2686. ->where('episode_id', $episode_id)
  2687. ->where('act_number', '>', $act_number)
  2688. ->increment('act_number');
  2689. // 复制该片段记录
  2690. $segment_data = (array)$source_segment;
  2691. unset($segment_data['id']);
  2692. $segment_data['video_url'] = '';
  2693. $segment_data['video_task_id'] = '';
  2694. $segment_data['video_task_status'] = '';
  2695. $segment_data['act_number'] = $new_act_number;
  2696. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2697. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2698. if (!$id) {
  2699. Utils::throwError('20003:复制片段失败');
  2700. }
  2701. DB::commit();
  2702. }catch (\Exception $e) {
  2703. DB::rollBack();
  2704. Utils::throwError('20003:'.$e->getMessage());
  2705. }
  2706. // 返回新复制的记录
  2707. $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();
  2708. $new_segment = $new_segment ? (array)$new_segment : [];
  2709. $new_segment['act_id'] = $id;
  2710. return $new_segment;
  2711. }
  2712. public function moveAct($data) {
  2713. $act_id = getProp($data, 'act_id');
  2714. $target_act_id = getProp($data, 'target_act_id');
  2715. // 获取源片段信息
  2716. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2717. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2718. // 获取目标片段信息
  2719. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2720. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2721. $anime_id = getProp($source_segment, 'anime_id');
  2722. $episode_id = getProp($source_segment, 'episode_id');
  2723. $source_act_number = getProp($source_segment, 'act_number');
  2724. $target_act_number = getProp($target_segment, 'act_number');
  2725. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2726. $target_anime_id = getProp($target_segment, 'anime_id');
  2727. $target_episode_id = getProp($target_segment, 'episode_id');
  2728. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2729. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2730. }
  2731. // 如果源片段和目标片段相同,无需移动
  2732. if ($source_act_number == $target_act_number) {
  2733. return true;
  2734. }
  2735. try {
  2736. DB::beginTransaction();
  2737. if ($source_act_number < $target_act_number) {
  2738. // 向后移动:源片段移动到目标片段之后
  2739. // 1. 将源片段和目标片段之间的所有片段编号减1
  2740. DB::table('mp_episode_segments')
  2741. ->where('anime_id', $anime_id)
  2742. ->where('episode_id', $episode_id)
  2743. ->where('act_number', '>', $source_act_number)
  2744. ->where('act_number', '<=', $target_act_number)
  2745. ->decrement('act_number');
  2746. // 2. 将源片段移动到目标片段之后
  2747. $new_act_number = $target_act_number;
  2748. } else {
  2749. // 向前移动:源片段移动到目标片段之后
  2750. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2751. DB::table('mp_episode_segments')
  2752. ->where('anime_id', $anime_id)
  2753. ->where('episode_id', $episode_id)
  2754. ->where('act_number', '>', $target_act_number)
  2755. ->where('act_number', '<', $source_act_number)
  2756. ->increment('act_number');
  2757. // 2. 将源片段移动到目标片段之后
  2758. $new_act_number = $target_act_number + 1;
  2759. }
  2760. // 3. 更新源片段的编号
  2761. $update_result = DB::table('mp_episode_segments')
  2762. ->where('id', $act_id)
  2763. ->update([
  2764. 'act_number' => $new_act_number,
  2765. 'updated_at' => date('Y-m-d H:i:s')
  2766. ]);
  2767. if (!$update_result) {
  2768. Utils::throwError('20003:更新片段编号失败');
  2769. }
  2770. DB::commit();
  2771. return true;
  2772. } catch (\Exception $e) {
  2773. DB::rollBack();
  2774. Utils::throwError('20003:' . $e->getMessage());
  2775. }
  2776. }
  2777. public function delAct($data) {
  2778. $act_id = getProp($data, 'act_id');
  2779. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2780. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2781. if (!$segment) Utils::throwError('20003:请选择片段');
  2782. $anime_id = getProp($segment, 'anime_id');
  2783. $episode_id = getProp($segment, 'episode_id');
  2784. $act_number = getProp($segment, 'act_number');
  2785. try {
  2786. DB::beginTransaction();
  2787. // 删除该片段记录
  2788. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2789. if (!$deleted) {
  2790. Utils::throwError('20003:删除片段失败');
  2791. }
  2792. // 更新后续act的编号
  2793. DB::table('mp_episode_segments')
  2794. ->where('anime_id', $anime_id)
  2795. ->where('episode_id', $episode_id)
  2796. ->where('act_number', '>', $act_number)
  2797. ->decrement('act_number');
  2798. DB::commit();
  2799. }catch (\Exception $e) {
  2800. DB::rollBack();
  2801. Utils::throwError('20003:'.$e->getMessage());
  2802. }
  2803. return true;
  2804. }
  2805. public function applyAct($data) {
  2806. $act_id = getProp($data, 'act_id');
  2807. $url = getProp($data, 'url');
  2808. if (!$act_id) Utils::throwError('20003:请选择片段');
  2809. if (!$url) Utils::throwError('20003:URL不能为空');
  2810. // 获取URL的文件扩展名
  2811. $urlPath = parse_url($url, PHP_URL_PATH);
  2812. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2813. // 定义图片和视频的扩展名
  2814. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2815. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2816. // 判断是图片还是视频
  2817. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2818. if (in_array($extension, $imageExtensions)) {
  2819. // 图片类型
  2820. $updateData['img_url'] = $url;
  2821. $updateData['current_type'] = 1;
  2822. } elseif (in_array($extension, $videoExtensions)) {
  2823. // 视频类型
  2824. $updateData['video_url'] = $url;
  2825. $updateData['current_type'] = 2;
  2826. } else {
  2827. Utils::throwError('20003:不支持的文件类型');
  2828. }
  2829. // 更新片段记录(全能模式下每个act只有一条记录)
  2830. $result = DB::table('mp_episode_segments')
  2831. ->where('id', $act_id)
  2832. ->update($updateData);
  2833. if (!$result) {
  2834. Utils::throwError('20003:更新片段失败');
  2835. }
  2836. return true;
  2837. }
  2838. public function actChatHistory($data) {
  2839. $act_id = getProp($data, 'act_id');
  2840. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2841. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2842. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2843. $value = (array)$value;
  2844. $value['created_at'] = transDate($value['created_at']);
  2845. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2846. else $value['reference_images'] = [];
  2847. return $value;
  2848. })->toArray();
  2849. // 获取历史图片
  2850. $url = [];
  2851. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2852. foreach($pic_history as $task) {
  2853. $result_url = getProp($task, 'result_url');
  2854. if (is_json($result_url)) {
  2855. $url = array_merge($url, json_decode($result_url, true));
  2856. }else {
  2857. $url[] = $result_url;
  2858. }
  2859. }
  2860. // 获取历史视频
  2861. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2862. foreach($video_history as $task) {
  2863. $result_url = getProp($task, 'result_url');
  2864. if (is_json($result_url)) {
  2865. $url = array_merge($url, json_decode($result_url, true));
  2866. }else {
  2867. $url[] = $result_url;
  2868. }
  2869. }
  2870. // 获取资产库
  2871. $products = [];
  2872. // 通过act_id查询片段信息获取episode_id
  2873. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2874. if ($segment) {
  2875. $episode_id = getProp($segment, 'episode_id');
  2876. // 查询剧集信息获取roles、scenes和extra_products
  2877. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2878. if ($episode) {
  2879. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2880. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2881. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2882. // 先合并roles和scenes
  2883. // 处理角色数组
  2884. foreach ($roles as $role) {
  2885. $product = $role;
  2886. // 将role字段重命名为product_name
  2887. if (isset($product['role'])) {
  2888. $product['product_name'] = $product['role'];
  2889. unset($product['role']);
  2890. }
  2891. $product['product'] = 1; // 标记类型为角色
  2892. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2893. }
  2894. // 处理场景数组
  2895. foreach ($scenes as $scene) {
  2896. $product = $scene;
  2897. // 将scene字段重命名为product_name
  2898. if (isset($product['scene'])) {
  2899. $product['product_name'] = $product['scene'];
  2900. unset($product['scene']);
  2901. }
  2902. $product['product'] = 2; // 标记类型为场景
  2903. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2904. }
  2905. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2906. foreach ($extra_products as $extra_product) {
  2907. $product_name = getProp($extra_product, 'product_name');
  2908. if ($product_name) {
  2909. $products[$product_name] = $extra_product; // 覆盖同名数据
  2910. }
  2911. }
  2912. // 重新索引数组(去除key)
  2913. $products = array_values($products);
  2914. }
  2915. }
  2916. // 获取执行中的任务
  2917. $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) {
  2918. $value = (array)$value;
  2919. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2920. else $value['ref_image_url'] = [];
  2921. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2922. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2923. if (!empty($value['prompt'])) {
  2924. $prompt = $value['prompt'];
  2925. // 查找第一个【镜头】的位置
  2926. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2927. // 从【镜头】开始截取
  2928. $prompt = substr($prompt, $matches[0][1]);
  2929. }
  2930. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2931. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2932. $value['prompt'] = $prompt;
  2933. }
  2934. return $value;
  2935. })->toArray();
  2936. return compact('chat', 'url', 'products', 'tasks');
  2937. }
  2938. public function applyAudioData($data) {
  2939. $segment_id = getProp($data, 'segment_id');
  2940. $global_data = getProp($data, 'global_data');
  2941. $segment_data = getProp($data, 'segment_data');
  2942. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2943. $global_data = is_array($global_data) ? $global_data : [];
  2944. $segment_data = is_array($segment_data) ? $segment_data : [];
  2945. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2946. $dialogue_item = null;
  2947. foreach ($global_data as $key => $item) {
  2948. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2949. $dialogue_item = $item;
  2950. unset($global_data[$key]);
  2951. break;
  2952. }
  2953. }
  2954. if ($dialogue_item) {
  2955. $segment_data[] = $dialogue_item;
  2956. }
  2957. // 特殊参数: audio_url,audio_duration,subtitle_info
  2958. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2959. // 如果不是全部存在,则仍需创建音频任务
  2960. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2961. $special_update_data = [];
  2962. $has_all_special_params = false;
  2963. // 从segment_data中提取特殊参数
  2964. $filtered_segment_data = [];
  2965. foreach ($segment_data as $item) {
  2966. $field_name = trim((string)getProp($item, 'name'));
  2967. if (in_array($field_name, $special_fields)) {
  2968. $special_update_data[$field_name] = getProp($item, 'value');
  2969. } else {
  2970. // 非特殊参数保留,继续后续处理
  2971. $filtered_segment_data[] = $item;
  2972. }
  2973. }
  2974. // 检查是否三个特殊参数都存在
  2975. if (count($special_update_data) === 3 &&
  2976. isset($special_update_data['audio_url']) &&
  2977. isset($special_update_data['audio_duration']) &&
  2978. isset($special_update_data['subtitle_info'])) {
  2979. $has_all_special_params = true;
  2980. // 立即更新到当前分镜
  2981. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2982. DB::table('mp_episode_segments')
  2983. ->where('segment_id', $segment_id)
  2984. ->update($special_update_data);
  2985. }
  2986. // 使用过滤后的segment_data继续处理其他参数
  2987. $segment_data = $filtered_segment_data;
  2988. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2989. $global_update_data = [];
  2990. $segment_update_data = [];
  2991. $global_voice_type = '';
  2992. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2993. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2994. $episode_id = getProp($target_segment, 'episode_id');
  2995. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2996. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2997. if (!$episode) Utils::throwError('20003:分集不存在');
  2998. foreach ($global_data as $item) {
  2999. $field_name = trim((string)getProp($item, 'name'));
  3000. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3001. continue;
  3002. }
  3003. $global_update_data[$field_name] = getProp($item, 'value');
  3004. if ($field_name === 'voice_type') {
  3005. $global_voice_type = trim((string)getProp($item, 'value'));
  3006. }
  3007. }
  3008. foreach ($segment_data as $item) {
  3009. $field_name = trim((string)getProp($item, 'name'));
  3010. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3011. continue;
  3012. }
  3013. $segment_update_data[$field_name] = getProp($item, 'value');
  3014. }
  3015. if ($global_voice_type) {
  3016. $timbre_info = DB::table('mp_timbres')
  3017. ->where('timbre_type', $global_voice_type)
  3018. ->select('audio_url', 'timbre_name')
  3019. ->first();
  3020. if ($timbre_info) {
  3021. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3022. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3023. }
  3024. }
  3025. try {
  3026. DB::beginTransaction();
  3027. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3028. $segment_ids_to_create_task = [];
  3029. $segments_data = [];
  3030. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3031. if (!empty($global_update_data)) {
  3032. // 如果角色不存在,则只更新当前分镜
  3033. if (!$target_voice_actor) {
  3034. // 只处理当前分镜
  3035. $affected_segments = DB::table('mp_episode_segments')
  3036. ->where('segment_id', $segment_id)
  3037. ->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')
  3038. ->get();
  3039. } else {
  3040. // 获取该角色的所有分镜
  3041. $affected_segments = DB::table('mp_episode_segments')
  3042. ->where('episode_id', $episode_id)
  3043. ->where('voice_actor', $target_voice_actor)
  3044. ->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')
  3045. ->get();
  3046. }
  3047. foreach ($affected_segments as $seg) {
  3048. $seg = (array)$seg;
  3049. $sid = getProp($seg, 'segment_id');
  3050. // 检查参数是否发生变化
  3051. $has_changed = false;
  3052. foreach ($global_update_data as $field => $new_value) {
  3053. $old_value = getProp($seg, $field);
  3054. if ($old_value != $new_value) {
  3055. $has_changed = true;
  3056. break;
  3057. }
  3058. }
  3059. if ($has_changed) {
  3060. $segment_ids_to_create_task[] = $sid;
  3061. $segments_data[$sid] = $seg;
  3062. }
  3063. }
  3064. // 只有在有变化的分镜时才更新
  3065. if (!empty($segment_ids_to_create_task)) {
  3066. $global_segment_update_data = $global_update_data;
  3067. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3068. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3069. DB::table('mp_episode_segments')
  3070. ->where('episode_id', $episode_id)
  3071. ->where('voice_actor', $target_voice_actor)
  3072. ->whereIn('segment_id', $segment_ids_to_create_task)
  3073. ->update($global_segment_update_data);
  3074. }
  3075. if ($global_voice_type) {
  3076. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3077. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3078. $roles_updated = false;
  3079. foreach ($episode_roles as &$role) {
  3080. // 通过 role 字段匹配角色名,而不是 voice_name
  3081. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3082. continue;
  3083. }
  3084. $role['voice_type'] = $global_voice_type;
  3085. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3086. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3087. $roles_updated = true;
  3088. }
  3089. unset($role);
  3090. if ($roles_updated) {
  3091. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3092. 'roles' => json_encode($episode_roles, 256),
  3093. 'updated_at' => date('Y-m-d H:i:s'),
  3094. ]);
  3095. }
  3096. }
  3097. }
  3098. // 如果有单个分镜更新,检查是否有变化
  3099. if (!empty($segment_update_data)) {
  3100. // 获取当前分镜数据
  3101. $current_segment = DB::table('mp_episode_segments')
  3102. ->where('segment_id', $segment_id)
  3103. ->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')
  3104. ->first();
  3105. if ($current_segment) {
  3106. $current_segment = (array)$current_segment;
  3107. // 检查参数是否发生变化
  3108. $has_changed = false;
  3109. foreach ($segment_update_data as $field => $new_value) {
  3110. $old_value = getProp($current_segment, $field);
  3111. if ($old_value != $new_value) {
  3112. $has_changed = true;
  3113. break;
  3114. }
  3115. }
  3116. if ($has_changed) {
  3117. // 如果该分镜还未在列表中,添加进去
  3118. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3119. $segment_ids_to_create_task[] = $segment_id;
  3120. $segments_data[$segment_id] = $current_segment;
  3121. }
  3122. // 更新分镜数据并清空音频URL
  3123. $segment_update_data['audio_url'] = '';
  3124. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3125. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3126. }
  3127. }
  3128. }
  3129. // 为所有有变化的分镜创建音频合成任务
  3130. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3131. if (!empty($segment_ids_to_create_task)) {
  3132. foreach ($segment_ids_to_create_task as $sid) {
  3133. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3134. if ($sid === $segment_id && $has_all_special_params) {
  3135. continue;
  3136. }
  3137. // 重新获取更新后的分镜数据
  3138. $updated_segment = DB::table('mp_episode_segments')
  3139. ->where('segment_id', $sid)
  3140. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3141. ->first();
  3142. if (!$updated_segment) continue;
  3143. $updated_segment = (array)$updated_segment;
  3144. // 检查dialogue是否为空
  3145. $dialogue = getProp($updated_segment, 'dialogue');
  3146. if (empty($dialogue)) {
  3147. // dialogue为空时,直接写入默认音频信息
  3148. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3149. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3150. 'audio_duration' => 2.0,
  3151. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3152. 'updated_at' => date('Y-m-d H:i:s')
  3153. ]);
  3154. continue;
  3155. }
  3156. $generate_json = [
  3157. 'text' => $dialogue,
  3158. 'role' => getProp($updated_segment, 'voice_actor'),
  3159. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3160. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3161. 'emotion' => getProp($updated_segment, 'emotion'),
  3162. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3163. 'gender' => getProp($updated_segment, 'gender'),
  3164. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3165. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3166. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3167. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3168. ];
  3169. // 插入视频配音合成任务
  3170. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3171. 'alias_segment_id' => $sid,
  3172. 'generate_status' => '执行中',
  3173. 'audio_url' => '',
  3174. 'generate_json' => json_encode($generate_json, 256),
  3175. 'created_at' => date('Y-m-d H:i:s'),
  3176. 'updated_at' => date('Y-m-d H:i:s'),
  3177. ]);
  3178. if (!$dubTaskId) {
  3179. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3180. continue;
  3181. }
  3182. // 将任务ID添加到Redis列表中
  3183. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3184. // 请求远程服务器执行生成
  3185. try {
  3186. sleep(1);
  3187. $client = new Client(['timeout' => 300, 'verify' => false]);
  3188. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3189. $response = $result->getBody()->getContents();
  3190. $response_arr = json_decode($response, true);
  3191. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3192. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3193. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3194. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3195. }
  3196. } catch (\Exception $e) {
  3197. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3198. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3199. }
  3200. }
  3201. }
  3202. DB::commit();
  3203. } catch (\Exception $e) {
  3204. DB::rollBack();
  3205. Utils::throwError('20003:'.$e->getMessage());
  3206. }
  3207. return true;
  3208. }
  3209. public function episodePicsInfo($data) {
  3210. $anime_id = getProp($data, 'anime_id');
  3211. $episode_id = getProp($data, 'episode_id');
  3212. // 参数验证
  3213. if (!$anime_id && !$episode_id) {
  3214. Utils::throwError('20003:请提供动漫ID或分集ID');
  3215. }
  3216. // 根据参数获取数据源
  3217. if ($episode_id) {
  3218. // 从剧集表获取
  3219. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3220. if (!$source) Utils::throwError('20003:该剧集不存在');
  3221. $table_name = 'mp_anime_episodes';
  3222. $id_field = 'id';
  3223. $id_value = $episode_id;
  3224. // 获取剧集的anime_id用于继承全局数据
  3225. $anime_id = getProp($source, 'anime_id');
  3226. } else {
  3227. // 从动漫表获取
  3228. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3229. if (!$source) Utils::throwError('20003:该动漫不存在');
  3230. $table_name = 'mp_animes';
  3231. $id_field = 'id';
  3232. $id_value = $anime_id;
  3233. }
  3234. $source = (array)$source;
  3235. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3236. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3237. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3238. // 如果是分集数据,需要处理继承和任务创建逻辑
  3239. if ($episode_id) {
  3240. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3241. }
  3242. // 返回生成器函数,用于 SSE 流式输出
  3243. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3244. $startTime = time();
  3245. $maxDuration = 600; // 10分钟超时
  3246. $checkInterval = 3; // 每3秒检查一次
  3247. // Redis 缓存键
  3248. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3249. // 生成当前数据的哈希值用于比较
  3250. $generateHash = function($roles, $scenes, $props) {
  3251. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3252. };
  3253. // 发送初始数据
  3254. $currentHash = $generateHash($roles, $scenes, $props);
  3255. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3256. echo "data: " . json_encode([
  3257. 'type' => 'init',
  3258. 'data' => [
  3259. 'roles' => $roles,
  3260. 'scenes' => $scenes,
  3261. 'props' => $props,
  3262. 'start_time' => $startTime
  3263. ]
  3264. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3265. if (ob_get_level() > 0) {
  3266. ob_flush();
  3267. }
  3268. flush();
  3269. // 持续轮询任务状态
  3270. while (time() - $startTime < $maxDuration) {
  3271. $hasProcessing = false;
  3272. $updated = false;
  3273. // 检查角色任务状态
  3274. foreach ($roles as $index => &$role) {
  3275. $task_id = getProp($role, 'task_id');
  3276. $task_status = getProp($role, 'task_status');
  3277. $existing_url = getProp($role, 'url');
  3278. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3279. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3280. $hasProcessing = ($task_status === 'processing');
  3281. // 查询任务状态
  3282. $task = DB::table('mp_generate_pic_tasks')
  3283. ->where('id', $task_id)
  3284. ->select('id', 'status', 'result_url', 'error_message')
  3285. ->first();
  3286. if ($task) {
  3287. $task = (array)$task;
  3288. $status = getProp($task, 'status');
  3289. // 如果任务完成或失败
  3290. if (in_array($status, ['success', 'failed'])) {
  3291. $role['task_status'] = $status;
  3292. if ($status === 'success') {
  3293. $result_url = getProp($task, 'result_url');
  3294. if ($result_url) {
  3295. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3296. if (is_array($result_urls) && !empty($result_urls[0])) {
  3297. $role['url'] = $result_urls[0];
  3298. }
  3299. }
  3300. }
  3301. $updated = true;
  3302. } else if ($status === 'processing') {
  3303. $hasProcessing = true;
  3304. }
  3305. }
  3306. }
  3307. }
  3308. // 检查场景任务状态
  3309. foreach ($scenes as $index => &$scene) {
  3310. $task_id = getProp($scene, 'task_id');
  3311. $task_status = getProp($scene, 'task_status');
  3312. $existing_url = getProp($scene, 'url');
  3313. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3314. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3315. $hasProcessing = ($task_status === 'processing');
  3316. // 查询任务状态
  3317. $task = DB::table('mp_generate_pic_tasks')
  3318. ->where('id', $task_id)
  3319. ->select('id', 'status', 'result_url', 'error_message')
  3320. ->first();
  3321. if ($task) {
  3322. $task = (array)$task;
  3323. $status = getProp($task, 'status');
  3324. // 如果任务完成或失败
  3325. if (in_array($status, ['success', 'failed'])) {
  3326. $scene['task_status'] = $status;
  3327. if ($status === 'success') {
  3328. $result_url = getProp($task, 'result_url');
  3329. if ($result_url) {
  3330. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3331. if (is_array($result_urls) && !empty($result_urls[0])) {
  3332. $scene['url'] = $result_urls[0];
  3333. }
  3334. }
  3335. }
  3336. $updated = true;
  3337. } else if ($status === 'processing') {
  3338. $hasProcessing = true;
  3339. }
  3340. }
  3341. }
  3342. }
  3343. // 检查道具任务状态
  3344. foreach ($props as $index => &$prop) {
  3345. $task_id = getProp($prop, 'task_id');
  3346. $task_status = getProp($prop, 'task_status');
  3347. $existing_url = getProp($prop, 'url');
  3348. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3349. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3350. $hasProcessing = ($task_status === 'processing');
  3351. // 查询任务状态
  3352. $task = DB::table('mp_generate_pic_tasks')
  3353. ->where('id', $task_id)
  3354. ->select('id', 'status', 'result_url', 'error_message')
  3355. ->first();
  3356. if ($task) {
  3357. $task = (array)$task;
  3358. $status = getProp($task, 'status');
  3359. // 如果任务完成或失败
  3360. if (in_array($status, ['success', 'failed'])) {
  3361. $prop['task_status'] = $status;
  3362. if ($status === 'success') {
  3363. $result_url = getProp($task, 'result_url');
  3364. if ($result_url) {
  3365. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3366. if (is_array($result_urls) && !empty($result_urls[0])) {
  3367. $prop['url'] = $result_urls[0];
  3368. }
  3369. }
  3370. }
  3371. $updated = true;
  3372. } else if ($status === 'processing') {
  3373. $hasProcessing = true;
  3374. }
  3375. }
  3376. }
  3377. }
  3378. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3379. if ($updated) {
  3380. $newHash = $generateHash($roles, $scenes, $props);
  3381. $cachedHash = Redis::get($cacheKey);
  3382. // 只有当数据真正变化时才更新数据库和发送事件
  3383. if ($newHash !== $cachedHash) {
  3384. try {
  3385. // 更新数据库
  3386. DB::table($table_name)->where($id_field, $id_value)->update([
  3387. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3388. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3389. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3390. 'updated_at' => date('Y-m-d H:i:s')
  3391. ]);
  3392. // 更新缓存
  3393. Redis::setex($cacheKey, 600, $newHash);
  3394. // 发送更新事件
  3395. echo "data: " . json_encode([
  3396. 'type' => 'update',
  3397. 'data' => [
  3398. 'roles' => $roles,
  3399. 'scenes' => $scenes,
  3400. 'props' => $props,
  3401. 'elapsed_time' => time() - $startTime
  3402. ]
  3403. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3404. if (ob_get_level() > 0) {
  3405. ob_flush();
  3406. }
  3407. flush();
  3408. } catch (\Exception $e) {
  3409. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3410. }
  3411. } else {
  3412. // 即使哈希相同,如果有URL更新也要发送事件
  3413. $hasUrlUpdate = false;
  3414. foreach ($roles as $role) {
  3415. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3416. $hasUrlUpdate = true;
  3417. break;
  3418. }
  3419. }
  3420. if (!$hasUrlUpdate) {
  3421. foreach ($scenes as $scene) {
  3422. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3423. $hasUrlUpdate = true;
  3424. break;
  3425. }
  3426. }
  3427. }
  3428. if (!$hasUrlUpdate) {
  3429. foreach ($props as $prop) {
  3430. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3431. $hasUrlUpdate = true;
  3432. break;
  3433. }
  3434. }
  3435. }
  3436. if ($hasUrlUpdate) {
  3437. // 强制更新数据库和发送事件
  3438. try {
  3439. DB::table($table_name)->where($id_field, $id_value)->update([
  3440. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3441. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3442. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3443. 'updated_at' => date('Y-m-d H:i:s')
  3444. ]);
  3445. // 更新缓存
  3446. Redis::setex($cacheKey, 600, $newHash);
  3447. // 发送更新事件
  3448. echo "data: " . json_encode([
  3449. 'type' => 'update',
  3450. 'data' => [
  3451. 'roles' => $roles,
  3452. 'scenes' => $scenes,
  3453. 'props' => $props,
  3454. 'elapsed_time' => time() - $startTime
  3455. ]
  3456. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3457. if (ob_get_level() > 0) {
  3458. ob_flush();
  3459. }
  3460. flush();
  3461. } catch (\Exception $e) {
  3462. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3463. }
  3464. }
  3465. }
  3466. }
  3467. // 如果所有任务都已完成,发送完成事件并退出
  3468. if (!$hasProcessing) {
  3469. // 查询数据库中的最终数据,确保返回最新的完整数据
  3470. try {
  3471. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3472. if ($finalSource) {
  3473. $finalSource = (array)$finalSource;
  3474. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3475. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3476. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3477. // 使用数据库中的最终数据
  3478. $roles = $finalRoles;
  3479. $scenes = $finalScenes;
  3480. $props = $finalProps;
  3481. }
  3482. } catch (\Exception $e) {
  3483. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3484. // 如果查询失败,继续使用内存中的数据
  3485. }
  3486. // 清理缓存
  3487. Redis::del($cacheKey);
  3488. echo "data: " . json_encode([
  3489. 'type' => 'completed',
  3490. 'data' => [
  3491. 'roles' => $roles,
  3492. 'scenes' => $scenes,
  3493. 'props' => $props,
  3494. 'total_time' => time() - $startTime
  3495. ]
  3496. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3497. if (ob_get_level() > 0) {
  3498. ob_flush();
  3499. }
  3500. flush();
  3501. break;
  3502. }
  3503. // 等待下次检查
  3504. sleep($checkInterval);
  3505. }
  3506. // 超时处理
  3507. if (time() - $startTime >= $maxDuration) {
  3508. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3509. try {
  3510. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3511. if ($finalSource) {
  3512. $finalSource = (array)$finalSource;
  3513. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3514. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3515. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3516. // 使用数据库中的最终数据
  3517. $roles = $finalRoles;
  3518. $scenes = $finalScenes;
  3519. $props = $finalProps;
  3520. }
  3521. } catch (\Exception $e) {
  3522. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3523. // 如果查询失败,继续使用内存中的数据
  3524. }
  3525. // 清理缓存
  3526. Redis::del($cacheKey);
  3527. echo "data: " . json_encode([
  3528. 'type' => 'timeout',
  3529. 'message' => '轮询超时,请刷新页面查看最新状态',
  3530. 'data' => [
  3531. 'roles' => $roles,
  3532. 'scenes' => $scenes,
  3533. 'props' => $props
  3534. ]
  3535. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3536. if (ob_get_level() > 0) {
  3537. ob_flush();
  3538. }
  3539. flush();
  3540. }
  3541. };
  3542. }
  3543. public function clipSegmentVideo($data) {
  3544. $segment_id = getProp($data, 'segment_id');
  3545. $video_time_point_start = getProp($data, 'video_time_point_start');
  3546. $video_time_point_end = getProp($data, 'video_time_point_end');
  3547. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3548. Utils::throwError('20003:参数异常');
  3549. }
  3550. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3551. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3552. }
  3553. $video_duration = $video_time_point_end - $video_time_point_start;
  3554. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3555. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3556. 'video_duration' => $video_duration,
  3557. 'video_time_point_start' => $video_time_point_start,
  3558. 'video_time_point_end' => $video_time_point_end,
  3559. 'updated_at' => date('Y-m-d H:i:s')
  3560. ]);
  3561. }
  3562. // 轮训获取图片任务结果
  3563. private function loopGetPicTaskResult($task_id) {
  3564. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3565. if (!$task) {
  3566. return '';
  3567. }
  3568. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3569. $model = getProp($task, 'model');
  3570. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3571. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3572. $isSyncModel = $isVolcModel || $isGptModel;
  3573. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3574. $start_count = 0;
  3575. $img_url = '';
  3576. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3577. sleep(3);
  3578. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3579. // 如果任务已经完成,直接返回结果
  3580. if ($task->status === 'success' && $task->result_url) {
  3581. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3582. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3583. }
  3584. // 如果任务已失败,返回空
  3585. if ($task->status === 'failed') {
  3586. return '';
  3587. }
  3588. if ($isSyncModel) continue;
  3589. // 查询任务状态
  3590. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3591. if ($statusInfo['status'] === 'success') {
  3592. $task->updateStatus('success', [
  3593. 'result_url' => $statusInfo['result_url'],
  3594. 'result_json' => $statusInfo['result_json'] ?? []
  3595. ]);
  3596. // 同步调整分镜图片状态和结果
  3597. if (getProp($task, 'alias_segment_id')) {
  3598. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3599. 'img_url' => $statusInfo['result_url'][0],
  3600. 'pic_task_status' => '已完成',
  3601. ]);
  3602. }
  3603. $img_url = $statusInfo['result_url'][0];
  3604. break;
  3605. } elseif ($statusInfo['status'] === 'failed') {
  3606. $task->updateStatus('failed', [
  3607. 'error_message' => $statusInfo['error_message'],
  3608. 'result_json' => $statusInfo['result_json'] ?? []
  3609. ]);
  3610. if (getProp($task, 'alias_segment_id')) {
  3611. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3612. 'pic_task_status' => '失败',
  3613. ]);
  3614. }
  3615. break;
  3616. }
  3617. $start_count++;
  3618. }
  3619. return $img_url;
  3620. }
  3621. /**
  3622. * 从分镜内容中提取涉及的角色
  3623. */
  3624. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3625. $found_characters = [];
  3626. foreach ($available_characters as $character) {
  3627. // 检查角色名称是否在分镜内容中出现
  3628. if (strpos($segment_content, $character) !== false) {
  3629. $found_characters[] = $character;
  3630. }
  3631. }
  3632. if (!$found_characters) {
  3633. foreach ($roles as $character) {
  3634. // 检查角色名称是否在分镜内容中出现
  3635. if (strpos($segment_content, $character) !== false) {
  3636. $found_characters[] = $character;
  3637. }
  3638. }
  3639. }
  3640. return array_unique($found_characters);
  3641. }
  3642. // 从分镜剧本中提取关键字段
  3643. private function handleSegmentContent(&$data) {
  3644. $segmentContent = getProp($data, 'segment_content');
  3645. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3646. $segmentData = [
  3647. 'description' => '',
  3648. 'composition' => '',
  3649. 'camera_movement' => '',
  3650. 'voice_actor' => '',
  3651. 'dialogue' => '',
  3652. 'frame_type' => '',
  3653. 'scene' => '', // 场景
  3654. 'characters' => '', // 出镜角色
  3655. 'tail_frame' => '', // 尾帧描述
  3656. 'emotion' => '中性', // 情感
  3657. 'gender' => '0', // 性别(0未知,1男,2女)
  3658. 'speed_ratio' => 0, // 语速
  3659. 'loudness_ratio' => 0, // 音量
  3660. 'emotion_scale' => 4, // 情感强度
  3661. 'pitch' => 0, // 音调
  3662. ];
  3663. // 用于存储需要从 segment_content 中移除的匹配项
  3664. $replaceEmptyArr = [];
  3665. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3666. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3667. $segmentData['description'] = trim($descMatch[1]);
  3668. $data['description'] = trim($descMatch[1]);
  3669. }
  3670. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3671. $segmentData['composition'] = trim($compMatch[1]);
  3672. $data['composition'] = trim($compMatch[1]);
  3673. }
  3674. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3675. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3676. $data['camera_movement'] = trim($cameraMatch[1]);
  3677. }
  3678. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3679. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3680. $data['voice_actor'] = trim($voiceMatch[1]);
  3681. }
  3682. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3683. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3684. $data['dialogue'] = trim($dialogueMatch[1]);
  3685. }
  3686. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3687. $segmentData['frame_type'] = trim($frameMatch[1]);
  3688. $data['frame_type'] = trim($frameMatch[1]);
  3689. }
  3690. // 场景字段
  3691. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3692. $segmentData['scene'] = trim($sceneMatch[1]);
  3693. $data['scene'] = trim($sceneMatch[1]);
  3694. }
  3695. // 出镜角色字段
  3696. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3697. $segmentData['characters'] = trim($charactersMatch[1]);
  3698. $data['characters'] = trim($charactersMatch[1]);
  3699. }
  3700. // 尾帧描述字段
  3701. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3702. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3703. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3704. }
  3705. // 情感字段
  3706. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3707. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3708. $segmentData['emotion'] = trim($emotionMatch[1]);
  3709. $data['emotion'] = trim($emotionMatch[1]);
  3710. }
  3711. // 性别字段
  3712. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3713. $replaceEmptyArr[] = trim($genderMatch[0]);
  3714. $genderStr = trim($genderMatch[1]);
  3715. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3716. $segmentData['gender'] = '1';
  3717. $data['gender'] = '1';
  3718. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3719. $segmentData['gender'] = '2';
  3720. $data['gender'] = '2';
  3721. } else {
  3722. $segmentData['gender'] = '0';
  3723. $data['gender'] = '0';
  3724. }
  3725. }
  3726. // 语速字段
  3727. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3728. $replaceEmptyArr[] = trim($speedMatch[0]);
  3729. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3730. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3731. }
  3732. // 音量字段
  3733. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3734. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3735. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3736. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3737. }
  3738. // 情感强度字段
  3739. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3740. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3741. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3742. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3743. }
  3744. // 音调字段
  3745. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3746. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3747. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3748. $data['pitch'] = (int)trim($pitchMatch[1]);
  3749. }
  3750. // 从 segment_content 中移除已提取的配音参数字段
  3751. if (!empty($replaceEmptyArr)) {
  3752. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3753. }
  3754. // 如果有配音角色,查询音色信息并验证情感
  3755. $voice_actor = $segmentData['voice_actor'];
  3756. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3757. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3758. $anime_id = getProp($data, 'anime_id');
  3759. $episode_id = getProp($data, 'episode_id');
  3760. // 优先从剧集的角色列表中查找
  3761. $roles = [];
  3762. if ($episode_id) {
  3763. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3764. if ($episode && getProp($episode, 'roles')) {
  3765. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3766. }
  3767. }
  3768. // 如果剧集中没有,从动漫的角色列表中查找
  3769. if (empty($roles) && $anime_id) {
  3770. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3771. if ($anime && getProp($anime, 'roles')) {
  3772. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3773. }
  3774. }
  3775. // 查找匹配的角色音色信息
  3776. $timbre_info = null;
  3777. foreach ($roles as $role) {
  3778. if (getProp($role, 'role') === $voice_actor) {
  3779. $timbre_info = $role;
  3780. break;
  3781. }
  3782. }
  3783. // 如果找到音色信息,添加到数据中
  3784. if ($timbre_info) {
  3785. $voice_type = getProp($timbre_info, 'voice_type');
  3786. $voice_name = getProp($timbre_info, 'voice_name');
  3787. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3788. if ($voice_type) {
  3789. $data['voice_type'] = $voice_type;
  3790. $segmentData['voice_type'] = $voice_type;
  3791. }
  3792. if ($voice_name) {
  3793. $data['voice_name'] = $voice_name;
  3794. $segmentData['voice_name'] = $voice_name;
  3795. }
  3796. if ($voice_audio_url) {
  3797. $data['voice_audio_url'] = $voice_audio_url;
  3798. $segmentData['voice_audio_url'] = $voice_audio_url;
  3799. }
  3800. // 验证情感是否在音色支持的情感列表中
  3801. if ($voice_type) {
  3802. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3803. if ($timbre_emotion) {
  3804. $timbre_emotion = explode(',', $timbre_emotion);
  3805. } else {
  3806. $timbre_emotion = [];
  3807. }
  3808. $emotion = getProp($segmentData, 'emotion', '中性');
  3809. if (!in_array($emotion, $timbre_emotion)) {
  3810. $emotion = '中性';
  3811. }
  3812. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3813. $emotion_list = array_flip($emotion_list);
  3814. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3815. $data['emotion_type'] = $emotion_type;
  3816. $segmentData['emotion_type'] = $emotion_type;
  3817. }
  3818. }
  3819. }
  3820. return $segmentData;
  3821. }
  3822. public function createSegmentVideoTask($data) {
  3823. $segment_id = getProp($data, 'segment_id');
  3824. $tail_frame = getProp($data, 'tail_frame');
  3825. $first_frame_url = getProp($data, 'first_frame_url');
  3826. $tail_frame_url = getProp($data, 'tail_frame_url');
  3827. $generate_audio = getProp($data, 'generate_audio', 0);
  3828. if (!$segment_id) {
  3829. Utils::throwError('1002:分镜ID不能为空');
  3830. }
  3831. // 获取分镜信息
  3832. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3833. if (!$segment) {
  3834. Utils::throwError('20003:分镜不存在');
  3835. }
  3836. $segment = (array)$segment;
  3837. $episode_id = getProp($segment, 'episode_id');
  3838. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3839. if (!$ratio) $ratio = '9:16';
  3840. // 获取分镜内容
  3841. $segmentContent = getProp($segment, 'segment_content', '');
  3842. // 检查 $segmentContent 中是否已有尾帧描述
  3843. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3844. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3845. $finalTailFrame = '';
  3846. if ($tail_frame) {
  3847. // 用户输入了尾帧描述,优先使用
  3848. $finalTailFrame = $tail_frame;
  3849. // 如果 segmentContent 中已有尾帧描述,需要替换
  3850. if ($contentHasTailFrame) {
  3851. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3852. }
  3853. } elseif ($contentHasTailFrame) {
  3854. // segmentContent 中有尾帧描述,使用它
  3855. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3856. } else {
  3857. // 两者都没有,使用分镜表中的尾帧描述
  3858. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3859. }
  3860. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3861. $hasDialogue = false;
  3862. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3863. $dialogue = trim($dialogueMatch[1]);
  3864. // 如果台词不为空且不是"无"
  3865. if (!empty($dialogue) && $dialogue !== '无') {
  3866. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3867. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3868. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3869. $hasDialogue = true;
  3870. }
  3871. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3872. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3873. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3874. if (!preg_match('/^[“]/', $dialogue)) {
  3875. $dialogue = '“' . $dialogue;
  3876. }
  3877. if (!preg_match('/[”]$/', $dialogue)) {
  3878. $dialogue .= '”';
  3879. }
  3880. // 将修改后的台词替换回 $segmentContent
  3881. $originalDialogue = $dialogueMatch[1];
  3882. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3883. }
  3884. }
  3885. // 构建完整的提示词
  3886. $fullPrompt = $segmentContent;
  3887. if ($finalTailFrame && !$contentHasTailFrame) {
  3888. // 只有当 segmentContent 中没有尾帧描述时才追加
  3889. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3890. }
  3891. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3892. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3893. $fullPrompt = trim($fullPrompt);
  3894. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3895. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3896. // 智能选择视频时长
  3897. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3898. $videoDuration = -1;
  3899. // 处理视频模型
  3900. $model = getProp($data, 'model');
  3901. if (!$model) {
  3902. // 用户没有输入,从episode表获取
  3903. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3904. $model = getProp($episode, 'video_model');
  3905. if (!$model) {
  3906. // episode表也没有,使用默认值
  3907. $model = 'doubao-seedance-1-5-pro-251215';
  3908. }
  3909. }
  3910. // 验证模型是否在可用模型表中
  3911. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3912. $model = 'doubao-seedance-1-5-pro-251215';
  3913. }
  3914. // 保存到episode表
  3915. $episode_id = getProp($segment, 'episode_id');
  3916. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3917. 'video_model' => $model,
  3918. 'updated_at' => date('Y-m-d H:i:s')
  3919. ]);
  3920. // 构建视频生成参数
  3921. $videoParams = [
  3922. 'model' => $model,
  3923. 'alias_segment_id' => $segment_id,
  3924. 'prompt' => trim($fullPrompt),
  3925. 'video_duration' => $videoDuration,
  3926. 'video_resolution' => '720P',
  3927. 'seed' => -1,
  3928. 'ratio' => $ratio,
  3929. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3930. 'draft' => false,
  3931. 'watermark' => false,
  3932. 'camera_fixed' => false,
  3933. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3934. ];
  3935. // 如果分镜有图片,作为首帧
  3936. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3937. $hasVideo = !empty(getProp($segment, 'video_url'));
  3938. if ($hasImage) {
  3939. if ($first_frame_url) {
  3940. $videoParams['first_frame_url'] = $first_frame_url;
  3941. }else {
  3942. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3943. }
  3944. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3945. }
  3946. // 构建content数组
  3947. $videoParams['content'] = [
  3948. [
  3949. 'type' => 'text',
  3950. 'text' => $videoParams['prompt'],
  3951. ]
  3952. ];
  3953. // 如果有首帧图片,添加到content中
  3954. if ($hasImage) {
  3955. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3956. $videoParams['content'][] = [
  3957. 'type' => 'image_url',
  3958. 'image_url' => [
  3959. 'url' => $videoParams['first_frame_url'],
  3960. ],
  3961. 'role' => 'reference_image',
  3962. ];
  3963. if (isset($videoParams['tail_frame_url'])) {
  3964. $videoParams['content'][] = [
  3965. 'type' => 'image_url',
  3966. 'image_url' => [
  3967. 'url' => $videoParams['tail_frame_url'],
  3968. ],
  3969. 'role' => 'reference_image',
  3970. ];
  3971. }
  3972. }else {
  3973. $videoParams['content'][] = [
  3974. 'type' => 'image_url',
  3975. 'image_url' => [
  3976. 'url' => $videoParams['first_frame_url'],
  3977. ],
  3978. 'role' => 'first_frame',
  3979. ];
  3980. if (isset($videoParams['tail_frame_url'])) {
  3981. $videoParams['content'][] = [
  3982. 'type' => 'image_url',
  3983. 'image_url' => [
  3984. 'url' => $videoParams['tail_frame_url'],
  3985. ],
  3986. 'role' => 'last_frame',
  3987. ];
  3988. }
  3989. }
  3990. }
  3991. // 获取配音音频URL
  3992. $audioUrl = getProp($segment, 'audio_url');
  3993. $audioDuration = getProp($segment, 'audio_duration');
  3994. // 音频传入的前提:必须有至少一张图片或一个视频
  3995. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3996. // dd($videoParams);
  3997. // 根据模型选择不同的视频生成方法
  3998. if (strpos($model, 'jimeng') !== false) {
  3999. // 即梦模型参数调整
  4000. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4001. unset($videoParams['content']); // 即梦不使用content格式
  4002. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4003. } elseif (strpos($model, 'kling') !== false) {
  4004. // Keling模型参数调整
  4005. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4006. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4007. unset($videoParams['ratio']);
  4008. unset($videoParams['content']); // Keling不使用content格式
  4009. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4010. } elseif (strpos($model, 'zhizhen') !== false) {
  4011. // 智帧20等新模型使用统一API
  4012. // 构建统一API参数
  4013. $unifiedParams = [
  4014. 'model_code' => $model,
  4015. 'alias_segment_id' => $segment_id,
  4016. 'prompt' => trim($fullPrompt),
  4017. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4018. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4019. 'video_ratio' => $ratio,
  4020. 'seed' => -1,
  4021. ];
  4022. // 构建parameters参数
  4023. $parameters = [
  4024. 'seconds' => $unifiedParams['video_duration'],
  4025. 'resolution' => $unifiedParams['video_resolution'],
  4026. 'ratio' => $ratio,
  4027. // 'video_mode' => 'multi_image',
  4028. // 'mode' => 'multi_image',
  4029. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4030. ];
  4031. $hasImage = false;
  4032. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4033. if ($hasImage) {
  4034. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4035. if (isset($videoParams['tail_frame_url'])) {
  4036. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4037. }
  4038. // 只有在有图片的情况下才能添加参考音频
  4039. if ($audioUrl) {
  4040. // $parameters['reference_audios'] = [$audioUrl];
  4041. }
  4042. } else {
  4043. // 没有图片时,记录错误日志
  4044. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4045. 'segment_id' => $segment_id,
  4046. 'model' => $model
  4047. ]);
  4048. }
  4049. $unifiedParams['parameters'] = $parameters;
  4050. // 调用统一API创建任务
  4051. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4052. } else {
  4053. // Seedance模型(默认)
  4054. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4055. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4056. // 添加配音音频到content中
  4057. $videoParams['content'][] = [
  4058. 'type' => 'audio_url',
  4059. 'audio_url' => [
  4060. 'url' => $audioUrl,
  4061. ],
  4062. 'role' => 'reference_audio',
  4063. ];
  4064. // 优化提示词,增加音频相关描述
  4065. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4066. $videoParams['prompt'] = $audioPrompt;
  4067. $videoParams['content'][0]['text'] = $audioPrompt;
  4068. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4069. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4070. }
  4071. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4072. }
  4073. // 更新分镜表的视频任务信息
  4074. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4075. 'video_task_id' => $task->id,
  4076. 'video_task_status' => '生成中',
  4077. 'generate_audio' => $generate_audio,
  4078. 'updated_at' => date('Y-m-d H:i:s')
  4079. ]);
  4080. return [
  4081. 'task_id' => $task->id,
  4082. 'status' => $task->status,
  4083. 'segment_id' => $segment_id,
  4084. 'video_duration' => $videoDuration
  4085. ];
  4086. }
  4087. public function createActVideoTask($data) {
  4088. $act_id = getProp($data, 'act_id');
  4089. $first_frame_url = getProp($data, 'first_frame_url');
  4090. $tail_frame_url = getProp($data, 'tail_frame_url');
  4091. $generate_audio = getProp($data, 'generate_audio', 1);
  4092. $video_duration = getProp($data, 'video_duration');
  4093. $video_resolution = getProp($data, 'video_resolution');
  4094. $ratio = getProp($data, 'ratio');
  4095. $products = getProp($data, 'products', []);
  4096. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4097. if (!is_array($reference_images) || !is_array($products)) {
  4098. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4099. }
  4100. if (!$act_id) {
  4101. Utils::throwError('1002:片段ID不能为空');
  4102. }
  4103. // 获取片段信息
  4104. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4105. if (!$act) {
  4106. Utils::throwError('20003:片段不存在');
  4107. }
  4108. $act = (array)$act;
  4109. $anime_id = getProp($act, 'anime_id');
  4110. $episode_id = getProp($act, 'episode_id');
  4111. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4112. $ace_mode = getProp($anime, 'ace_mode');
  4113. $art_style_type = getProp($anime, 'art_style_type');
  4114. $art_style = getProp($anime, 'art_style');
  4115. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4116. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4117. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4118. // 将资产中新出现的资产放到extra_products中
  4119. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4120. if (!empty($products) && $episode) {
  4121. // 获取剧集中的角色、场景和道具列表
  4122. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4123. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4124. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4125. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4126. // 构建角色名称列表
  4127. $role_names = array_column($roles, 'role');
  4128. // 构建场景名称列表
  4129. $scene_names = array_column($scenes, 'scene');
  4130. // 构建道具名称列表
  4131. $prop_names = array_column($props, 'prop');
  4132. // 遍历传入的products
  4133. foreach ($products as $product) {
  4134. $product_name = getProp($product, 'product_name');
  4135. // 如果product_name不在roles、scenes和props中
  4136. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4137. // 查找是否在extra_products中存在同名的
  4138. $found = false;
  4139. foreach ($extra_products as $key => $extra_product) {
  4140. if (getProp($extra_product, 'product_name') === $product_name) {
  4141. // 有同名的则覆盖
  4142. $extra_products[$key] = $product;
  4143. $found = true;
  4144. break;
  4145. }
  4146. }
  4147. // 没有则新增
  4148. if (!$found) {
  4149. $extra_products[] = $product;
  4150. }
  4151. }
  4152. }
  4153. if ($extra_products) {
  4154. // 保存到数据库
  4155. DB::table('mp_anime_episodes')
  4156. ->where('id', $episode_id)
  4157. ->update([
  4158. 'extra_products' => json_encode($extra_products, 256),
  4159. 'updated_at' => date('Y-m-d H:i:s')
  4160. ]);
  4161. }
  4162. }
  4163. // 获取分镜内容
  4164. $actContent = getProp($act, 'act_show_content', '');
  4165. // 音效同出(默认使用)
  4166. $current_generate_audio = $generate_audio ? 1 : 0;
  4167. // 构建完整的提示词
  4168. $processResult = $this->processActContentWithProducts($actContent, $products);
  4169. $fullPrompt = $processResult['content'];
  4170. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4171. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4172. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4173. // 处理视频模型
  4174. $model = getProp($data, 'model');
  4175. if (!$model) {
  4176. $model = getProp($episode, 'video_model');
  4177. if (!$model) {
  4178. // episode表也没有,使用默认值
  4179. $model = 'zhizhen-20';
  4180. }
  4181. }
  4182. // 验证模型是否在可用模型表中
  4183. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4184. $model = 'zhizhen-20';
  4185. }
  4186. // 保存到episode表
  4187. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4188. 'video_model' => $model,
  4189. 'updated_at' => date('Y-m-d H:i:s')
  4190. ]);
  4191. // 构建视频生成参数
  4192. $videoParams = [
  4193. 'model' => $model,
  4194. 'alias_act_id' => $act_id,
  4195. 'prompt' => trim($fullPrompt),
  4196. 'video_duration' => $videoDuration,
  4197. 'video_resolution' => $video_resolution,
  4198. 'seed' => -1,
  4199. 'ratio' => $ratio,
  4200. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4201. 'draft' => false,
  4202. 'watermark' => false,
  4203. 'camera_fixed' => false,
  4204. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4205. ];
  4206. // 如果分镜有图片,作为首帧
  4207. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4208. $hasVideo = !empty(getProp($act, 'video_url'));
  4209. if ($hasImage) {
  4210. if ($first_frame_url) {
  4211. $videoParams['first_frame_url'] = $first_frame_url;
  4212. }else {
  4213. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4214. }
  4215. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4216. }
  4217. // 构建content数组
  4218. $videoParams['content'] = [
  4219. [
  4220. 'type' => 'text',
  4221. 'text' => $videoParams['prompt'],
  4222. ]
  4223. ];
  4224. // 如果有首帧图片,添加到content中
  4225. if ($hasImage) {
  4226. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4227. $videoParams['content'][] = [
  4228. 'type' => 'image_url',
  4229. 'image_url' => [
  4230. 'url' => $videoParams['first_frame_url'],
  4231. ],
  4232. 'role' => 'reference_image',
  4233. ];
  4234. if (isset($videoParams['tail_frame_url'])) {
  4235. $videoParams['content'][] = [
  4236. 'type' => 'image_url',
  4237. 'image_url' => [
  4238. 'url' => $videoParams['tail_frame_url'],
  4239. ],
  4240. 'role' => 'reference_image',
  4241. ];
  4242. }
  4243. }else {
  4244. $videoParams['content'][] = [
  4245. 'type' => 'image_url',
  4246. 'image_url' => [
  4247. 'url' => $videoParams['first_frame_url'],
  4248. ],
  4249. 'role' => 'first_frame',
  4250. ];
  4251. if (isset($videoParams['tail_frame_url'])) {
  4252. $videoParams['content'][] = [
  4253. 'type' => 'image_url',
  4254. 'image_url' => [
  4255. 'url' => $videoParams['tail_frame_url'],
  4256. ],
  4257. 'role' => 'last_frame',
  4258. ];
  4259. }
  4260. }
  4261. }
  4262. // dd($videoParams);
  4263. // 根据模型选择不同的视频生成方法
  4264. if (strpos($model, 'jimeng') !== false) {
  4265. // 即梦模型参数调整
  4266. unset($videoParams['content']); // 即梦不使用content格式
  4267. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4268. } elseif (strpos($model, 'kling') !== false) {
  4269. // Keling模型参数调整
  4270. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4271. unset($videoParams['ratio']);
  4272. unset($videoParams['content']); // Keling不使用content格式
  4273. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4274. } elseif (strpos($model, 'zhizhen') !== false) {
  4275. // 智帧20等新模型使用统一API
  4276. // 构建统一API参数
  4277. $unifiedParams = [
  4278. 'model_code' => $model,
  4279. 'alias_act_id' => $act_id,
  4280. 'prompt' => trim($fullPrompt),
  4281. 'video_duration' => $videoDuration,
  4282. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4283. 'video_ratio' => $ratio,
  4284. 'seed' => -1,
  4285. ];
  4286. // 构建parameters参数
  4287. $parameters = [
  4288. 'seconds' => $unifiedParams['video_duration'],
  4289. 'resolution' => $unifiedParams['video_resolution'],
  4290. 'ratio' => $ratio,
  4291. // 'video_mode' => 'multi_image',
  4292. // 'mode' => 'multi_image',
  4293. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4294. ];
  4295. $hasImage = false;
  4296. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4297. if ($hasImage) {
  4298. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4299. if (isset($videoParams['tail_frame_url'])) {
  4300. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4301. }
  4302. } else {
  4303. // 没有图片时,记录错误日志
  4304. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4305. 'act_id' => $act_id,
  4306. 'model' => $model
  4307. ]);
  4308. }
  4309. if ($reference_images) {
  4310. // 限制只传入9张参考图
  4311. $reference_images = array_slice($reference_images, 0, 9);
  4312. // 在处理之前先保存原始reference_images到任务参数中
  4313. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4314. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4315. $parameters['reference_images'] = $reference_images;
  4316. $parameters['video_mode'] = 'multi_image';
  4317. $parameters['mode'] = 'multi_image';
  4318. }
  4319. $unifiedParams['parameters'] = $parameters;
  4320. // 调用统一API创建任务
  4321. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4322. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4323. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4324. // 保存原始参考图用于任务记录
  4325. $videoParams['reference_images'] = $reference_images;
  4326. if ($reference_images) {
  4327. // 限制只传入9张参考图
  4328. $reference_images = array_slice($reference_images, 0, 9);
  4329. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4330. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4331. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4332. $videoParams['prompt'] = trim($fullPrompt);
  4333. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4334. $videoParams['reference_image_assets'] = $reference_image_assets;
  4335. }
  4336. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4337. } else {
  4338. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4339. }
  4340. // 更新分镜表的视频任务信息
  4341. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4342. 'video_task_id' => $task->id,
  4343. 'video_task_status' => '生成中',
  4344. 'generate_audio' => $generate_audio,
  4345. 'updated_at' => date('Y-m-d H:i:s')
  4346. ]);
  4347. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4348. $episode_number = getProp($act, 'episode_number');
  4349. $act_number = getProp($act, 'act_number');
  4350. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4351. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4352. }
  4353. return [
  4354. 'task_id' => $task->id,
  4355. 'status' => $task->status,
  4356. 'act_id' => $act_id,
  4357. 'video_duration' => $videoDuration
  4358. ];
  4359. }
  4360. /**
  4361. * 根据提示词内容智能计算最优视频时长
  4362. *
  4363. * @param string $segmentContent 分镜内容
  4364. * @param string $tailFrame 尾帧描述
  4365. * @return int 视频时长(2-12秒)
  4366. */
  4367. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4368. // 合并所有文本内容
  4369. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4370. // 如果没有内容,返回默认时长
  4371. if (empty($fullText)) {
  4372. return 5;
  4373. }
  4374. // 计算文本长度(中文字符按2个字符计算)
  4375. $textLength = mb_strlen($fullText, 'UTF-8');
  4376. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4377. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4378. // 分析内容复杂度
  4379. $complexityScore = $this->analyzeContentComplexity($fullText);
  4380. // 基础时长计算(根据文本长度)
  4381. $baseDuration = 3; // 默认2秒
  4382. // if ($adjustedLength <= 20) {
  4383. // $baseDuration = 3;
  4384. // } elseif ($adjustedLength <= 40) {
  4385. // $baseDuration = 4;
  4386. // } elseif ($adjustedLength <= 60) {
  4387. // $baseDuration = 5;
  4388. // } elseif ($adjustedLength <= 80) {
  4389. // $baseDuration = 6;
  4390. // } elseif ($adjustedLength <= 100) {
  4391. // $baseDuration = 7;
  4392. // } elseif ($adjustedLength <= 120) {
  4393. // $baseDuration = 8;
  4394. // } else {
  4395. // $baseDuration = 9;
  4396. // }
  4397. // 根据内容复杂度调整时长
  4398. $finalDuration = $baseDuration + $complexityScore;
  4399. // 确保时长在2-12秒范围内
  4400. return max(4, min(12, $finalDuration));
  4401. }
  4402. /**
  4403. * 分析内容复杂度,返回时长调整值
  4404. *
  4405. * @param string $text 文本内容
  4406. * @return int 调整值(-2到+3)
  4407. */
  4408. private function analyzeContentComplexity($text) {
  4409. $score = 0;
  4410. // 动作关键词(需要更长时间展现)
  4411. $actionKeywords = [
  4412. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4413. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4414. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4415. ];
  4416. // 静态关键词(可以用较短时间)
  4417. $staticKeywords = [
  4418. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4419. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4420. ];
  4421. // 复杂场景关键词(需要更长时间)
  4422. $complexSceneKeywords = [
  4423. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4424. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4425. ];
  4426. // 情感关键词(需要适中时间表现)
  4427. $emotionKeywords = [
  4428. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4429. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4430. ];
  4431. // 检查动作关键词
  4432. foreach ($actionKeywords as $keyword) {
  4433. if (strpos($text, $keyword) !== false) {
  4434. $score += 1;
  4435. break; // 避免重复加分
  4436. }
  4437. }
  4438. // 检查静态关键词
  4439. foreach ($staticKeywords as $keyword) {
  4440. if (strpos($text, $keyword) !== false) {
  4441. $score -= 1;
  4442. break;
  4443. }
  4444. }
  4445. // 检查复杂场景关键词
  4446. foreach ($complexSceneKeywords as $keyword) {
  4447. if (strpos($text, $keyword) !== false) {
  4448. $score += 1;
  4449. break;
  4450. }
  4451. }
  4452. // 检查情感关键词
  4453. foreach ($emotionKeywords as $keyword) {
  4454. if (strpos($text, $keyword) !== false) {
  4455. $score += 1;
  4456. break;
  4457. }
  4458. }
  4459. // 检查时间相关词汇
  4460. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4461. $score += 1;
  4462. }
  4463. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4464. $score -= 1;
  4465. }
  4466. // 检查转场词汇
  4467. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4468. $score += 1;
  4469. }
  4470. // 检查环境描述(复杂环境需要更多时间)
  4471. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4472. $score += 1;
  4473. }
  4474. // 检查对话内容(对话需要更多时间)
  4475. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4476. $score += 1;
  4477. }
  4478. // 限制调整范围
  4479. return max(-1, min(4, $score));
  4480. }
  4481. /**
  4482. * 创建完整视频合成任务
  4483. *
  4484. * @param array $data
  4485. * @return array
  4486. */
  4487. public function createCompleteVideoTask($data)
  4488. {
  4489. $animeId = getProp($data, 'anime_id');
  4490. $episodeId = getProp($data, 'episode_id');
  4491. // 验证参数
  4492. if (!$animeId || !$episodeId) {
  4493. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4494. }
  4495. // 检查是否已存在处理中的任务
  4496. $existingTask = DB::table('mp_complete_video_tasks')
  4497. ->where('anime_id', $animeId)
  4498. ->where('episode_id', $episodeId)
  4499. ->whereIn('generate_status', ['执行中'])
  4500. ->first();
  4501. if ($existingTask) {
  4502. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4503. }
  4504. // 获取全能模式状态
  4505. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4506. if ((int)$ace_mode === 1) {
  4507. // 获取所有片段的配音视频,按 act_number 排序
  4508. $segments = DB::table('mp_episode_segments')
  4509. ->where('anime_id', $animeId)
  4510. ->where('episode_id', $episodeId)
  4511. ->orderBy('segment_number')
  4512. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4513. ->get();
  4514. // 检查是否所有片段都有视频
  4515. $missingVideos = $segments->filter(function($segment) {
  4516. return empty($segment->video_url);
  4517. });
  4518. if ($missingVideos->isNotEmpty()) {
  4519. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4520. }
  4521. }else {
  4522. // 获取所有分镜的配音视频,按 segment_number 排序
  4523. $segments = DB::table('mp_episode_segments')
  4524. ->where('anime_id', $animeId)
  4525. ->where('episode_id', $episodeId)
  4526. ->orderBy('segment_number')
  4527. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4528. ->get();
  4529. // 检查是否所有分镜都有配音和视频
  4530. $missingVideos = $segments->filter(function($segment) {
  4531. return empty($segment->audio_url) || empty($segment->video_url);
  4532. });
  4533. if ($missingVideos->isNotEmpty()) {
  4534. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4535. }
  4536. }
  4537. if ($segments->isEmpty()) {
  4538. Utils::throwError('20003:未找到该剧集的分镜数据');
  4539. }
  4540. // 获取当前完整视频url
  4541. $completeVideoUrl = DB::table('mp_anime_episodes')
  4542. ->where('anime_id', $animeId)
  4543. ->where('id', $episodeId)
  4544. ->value('complete_video_url');
  4545. // 构建 generate_json
  4546. $generateJson = [];
  4547. $sequence = 1;
  4548. foreach ($segments as $segment) {
  4549. if ((int)$ace_mode === 1) {
  4550. $generateJson[] = [
  4551. 'sequence' => $sequence++,
  4552. 'video_url' => $segment->video_url,
  4553. 'video_time_point_start' => $segment->video_time_point_start,
  4554. 'video_time_point_end' => $segment->video_time_point_end
  4555. ];
  4556. }else {
  4557. $generateJson[] = [
  4558. 'sequence' => $sequence++,
  4559. 'video_url' => $segment->video_url,
  4560. 'audio_url' => $segment->audio_url,
  4561. 'video_time_point_start' => $segment->video_time_point_start,
  4562. 'video_time_point_end' => $segment->video_time_point_end
  4563. ];
  4564. }
  4565. }
  4566. // 创建任务
  4567. $now = date('Y-m-d H:i:s');
  4568. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4569. 'anime_id' => $animeId,
  4570. 'episode_id' => $episodeId,
  4571. 'generate_json' => json_encode($generateJson, 256),
  4572. 'generate_status' => '执行中',
  4573. 'complete_video_url' => '',
  4574. 'created_at' => $now,
  4575. 'updated_at' => $now
  4576. ]);
  4577. if (!$taskId) {
  4578. Utils::throwError('20003:创建任务失败');
  4579. }
  4580. // 更新剧集表的任务ID和状态
  4581. $boolen = DB::table('mp_anime_episodes')
  4582. ->where('anime_id', $animeId)
  4583. ->where('id', $episodeId)
  4584. ->update([
  4585. 'complete_video_task_id' => $taskId,
  4586. 'complete_video_task_status' => '执行中',
  4587. 'updated_at' => $now
  4588. ]);
  4589. if (!$boolen) {
  4590. Utils::throwError('20003:更新剧集表失败');
  4591. }
  4592. dLog('anime')->info('创建完整视频合成任务', [
  4593. 'task_id' => $taskId,
  4594. 'anime_id' => $animeId,
  4595. 'episode_id' => $episodeId,
  4596. 'segment_count' => count($generateJson)
  4597. ]);
  4598. // 请求远程服务器执行生成
  4599. $client = new Client(['timeout' => 600, 'verify' => false]);
  4600. try {
  4601. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4602. $response = $result->getBody()->getContents();
  4603. $response_arr = json_decode($response, true);
  4604. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4605. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4606. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4607. // // 更新任务状态为失败
  4608. // DB::table('mp_complete_video_tasks')
  4609. // ->where('id', $taskId)
  4610. // ->update([
  4611. // 'generate_status' => '执行失败',
  4612. // 'error_message' => $error_msg,
  4613. // 'updated_at' => date('Y-m-d H:i:s')
  4614. // ]);
  4615. // // 同步更新剧集表状态
  4616. // DB::table('mp_anime_episodes')
  4617. // ->where('complete_video_task_id', $taskId)
  4618. // ->update([
  4619. // 'complete_video_task_status' => '执行失败',
  4620. // 'updated_at' => date('Y-m-d H:i:s')
  4621. // ]);
  4622. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4623. }
  4624. } catch (\Exception $e) {
  4625. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4626. // 更新任务状态为失败
  4627. DB::table('mp_complete_video_tasks')
  4628. ->where('id', $taskId)
  4629. ->update([
  4630. 'generate_status' => '执行失败',
  4631. 'error_message' => $e->getMessage(),
  4632. 'updated_at' => date('Y-m-d H:i:s')
  4633. ]);
  4634. // 同步更新剧集表状态
  4635. DB::table('mp_anime_episodes')
  4636. ->where('complete_video_task_id', $taskId)
  4637. ->update([
  4638. 'complete_video_task_status' => '执行失败',
  4639. 'updated_at' => date('Y-m-d H:i:s')
  4640. ]);
  4641. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4642. }
  4643. // 开始轮询任务状态
  4644. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4645. $pollInterval = 5; // 每5秒轮询一次
  4646. $attempt = 0;
  4647. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4648. while ($attempt < $maxAttempts) {
  4649. sleep($pollInterval);
  4650. $attempt++;
  4651. // 查询任务状态
  4652. $task = DB::table('mp_complete_video_tasks')
  4653. ->where('id', $taskId)
  4654. ->first();
  4655. if (!$task) {
  4656. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4657. Utils::throwError('20003:任务不存在');
  4658. }
  4659. dLog('anime')->info('轮询任务状态', [
  4660. 'task_id' => $taskId,
  4661. 'attempt' => $attempt,
  4662. 'status' => $task->generate_status
  4663. ]);
  4664. // 检查任务是否完成
  4665. if ($task->generate_status === '执行成功') {
  4666. // 同步更新剧集表状态
  4667. $boolen3 = DB::table('mp_anime_episodes')
  4668. ->where('anime_id', $animeId)
  4669. ->where('id', $episodeId)
  4670. ->update([
  4671. 'complete_video_url' => $task->complete_video_url,
  4672. 'complete_video_task_status' => '执行成功',
  4673. 'updated_at' => date('Y-m-d H:i:s')
  4674. ]);
  4675. dLog('anime')->info('视频合成任务完成', [
  4676. 'task_id' => $taskId,
  4677. 'video_url' => $task->complete_video_url,
  4678. 'attempts' => $attempt
  4679. ]);
  4680. // 如果更新成功则远程删除之前的文件
  4681. if ($boolen3 && $completeVideoUrl) {
  4682. $encode_url = urlencode($completeVideoUrl);
  4683. $client = new Client(['timeout' => 300, 'verify' => false]);
  4684. // 根据ID通过API通知合成音频
  4685. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4686. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4687. $response = $result->getBody()->getContents();
  4688. $response_arr = json_decode($response, true);
  4689. Log::info('火山删除音频返回: '.$response);
  4690. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4691. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4692. Log::info('火山删除音频失败: '.$error_msg);
  4693. // Utils::throwError('20003:火山删除音频失败');
  4694. }
  4695. }
  4696. return [
  4697. 'task_id' => $taskId,
  4698. 'anime_id' => $animeId,
  4699. 'episode_id' => $episodeId,
  4700. 'segment_count' => count($generateJson),
  4701. 'generate_status' => '执行成功',
  4702. 'complete_video_url' => $task->complete_video_url,
  4703. ];
  4704. }
  4705. // 检查任务是否失败
  4706. if ($task->generate_status === '执行失败') {
  4707. // 同步更新剧集表状态
  4708. DB::table('mp_anime_episodes')
  4709. ->where('anime_id', $animeId)
  4710. ->where('id', $episodeId)
  4711. ->update([
  4712. 'complete_video_task_status' => '执行失败',
  4713. 'updated_at' => date('Y-m-d H:i:s')
  4714. ]);
  4715. $errorMessage = $task->error_message ?? '未知错误';
  4716. dLog('anime')->error('视频合成任务失败', [
  4717. 'task_id' => $taskId,
  4718. 'error' => $errorMessage,
  4719. 'attempts' => $attempt
  4720. ]);
  4721. return [
  4722. 'task_id' => $taskId,
  4723. 'anime_id' => $animeId,
  4724. 'episode_id' => $episodeId,
  4725. 'segment_count' => count($generateJson),
  4726. 'generate_status' => '执行失败',
  4727. 'error_message' => $errorMessage
  4728. ];
  4729. }
  4730. }
  4731. // 超时处理
  4732. dLog('anime')->warning('视频合成任务超时', [
  4733. 'task_id' => $taskId,
  4734. 'max_attempts' => $maxAttempts,
  4735. 'timeout_seconds' => $maxAttempts * $pollInterval
  4736. ]);
  4737. // 更新任务状态为超时
  4738. DB::table('mp_complete_video_tasks')
  4739. ->where('id', $taskId)
  4740. ->update([
  4741. 'generate_status' => '超时',
  4742. 'error_message' => '任务执行超时(5分钟)',
  4743. 'updated_at' => date('Y-m-d H:i:s')
  4744. ]);
  4745. return [
  4746. 'task_id' => $taskId,
  4747. 'anime_id' => $animeId,
  4748. 'episode_id' => $episodeId,
  4749. 'segment_count' => count($generateJson),
  4750. 'generate_status' => '超时',
  4751. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4752. ];
  4753. }
  4754. /**
  4755. * 根据 inner_prompt_type 附加内置提示词
  4756. *
  4757. * @param string $prompt 用户提示词
  4758. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4759. * @return string 合并后的提示词
  4760. */
  4761. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4762. {
  4763. $innerPromptMap = [
  4764. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4765. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4766. ];
  4767. if (!isset($innerPromptMap[$innerPromptType])) {
  4768. return $prompt;
  4769. }
  4770. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4771. }
  4772. /**
  4773. * 根据 inner_prompt_type 获取生成图片数量
  4774. *
  4775. * @param int $innerPromptType 内置提示词类型
  4776. * @return int 图片数量
  4777. */
  4778. public static function getInnerImageNum($innerPromptType = 0)
  4779. {
  4780. return (int)$innerPromptType === 2 ? 9 : 1;
  4781. }
  4782. /**
  4783. * 提取图片生成结果URL
  4784. *
  4785. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4786. * @param int $innerPromptType 内置提示词类型
  4787. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4788. */
  4789. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4790. {
  4791. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4792. if (is_array($resultUrls) && !empty($resultUrls)) {
  4793. $resultUrls = array_values($resultUrls);
  4794. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4795. }
  4796. if (!empty($resultUrl)) {
  4797. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4798. }
  4799. return (int)$innerPromptType === 2 ? [] : '';
  4800. }
  4801. public function generateImg($data) {
  4802. $prompt = getProp($data, 'prompt');
  4803. $episode_id = getProp($data, 'episode_id');
  4804. $ref_img_urls = getProp($data, 'ref_img_urls');
  4805. $ratio = getProp($data, 'ratio', '9:16');
  4806. $resolution = getProp($data, 'resolution', '2k');
  4807. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4808. // 定义分辨率和宽高比对应的尺寸映射表
  4809. $sizeMap = [
  4810. '2k' => [
  4811. '1:1' => ['width' => 2048, 'height' => 2048],
  4812. '4:3' => ['width' => 2304, 'height' => 1728],
  4813. '3:4' => ['width' => 1728, 'height' => 2304],
  4814. '16:9' => ['width' => 2848, 'height' => 1600],
  4815. '9:16' => ['width' => 1600, 'height' => 2848],
  4816. '3:2' => ['width' => 2496, 'height' => 1664],
  4817. '2:3' => ['width' => 1664, 'height' => 2496],
  4818. '21:9' => ['width' => 3136, 'height' => 1344],
  4819. ],
  4820. '3k' => [
  4821. '1:1' => ['width' => 3072, 'height' => 3072],
  4822. '4:3' => ['width' => 3456, 'height' => 2592],
  4823. '3:4' => ['width' => 2592, 'height' => 3456],
  4824. '16:9' => ['width' => 4096, 'height' => 2304],
  4825. '9:16' => ['width' => 2304, 'height' => 4096],
  4826. '2:3' => ['width' => 2496, 'height' => 3744],
  4827. '3:2' => ['width' => 3744, 'height' => 2496],
  4828. '21:9' => ['width' => 4704, 'height' => 2016],
  4829. ],
  4830. '4k' => [
  4831. '1:1' => ['width' => 4096, 'height' => 4096],
  4832. '3:4' => ['width' => 3520, 'height' => 4704],
  4833. '4:3' => ['width' => 4704, 'height' => 3520],
  4834. '16:9' => ['width' => 5504, 'height' => 3040],
  4835. '9:16' => ['width' => 3040, 'height' => 5504],
  4836. '2:3' => ['width' => 3328, 'height' => 4992],
  4837. '3:2' => ['width' => 4992, 'height' => 3328],
  4838. '21:9' => ['width' => 6240, 'height' => 2656],
  4839. ],
  4840. ];
  4841. // 参数验证
  4842. $resolution = strtolower($resolution);
  4843. if (!isset($sizeMap[$resolution])) {
  4844. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4845. }
  4846. if (!isset($sizeMap[$resolution][$ratio])) {
  4847. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4848. }
  4849. // 根据 ratio 和 resolution 确定宽高
  4850. $width = $sizeMap[$resolution][$ratio]['width'];
  4851. $height = $sizeMap[$resolution][$ratio]['height'];
  4852. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4853. if (is_json($ref_img_urls)) {
  4854. $ref_img_urls = json_decode($ref_img_urls, true);
  4855. }else {
  4856. $ref_img_urls = explode(',', $ref_img_urls);
  4857. }
  4858. }
  4859. // 处理图片模型
  4860. $model = getProp($data, 'model');
  4861. if (!$model) {
  4862. // 用户没有输入,从episode表获取
  4863. if ($episode_id) {
  4864. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4865. $model = getProp($episode, 'image_model');
  4866. }
  4867. if (!$model) {
  4868. // episode表也没有,使用默认值
  4869. $model = 'doubao-seedream-5-0-lite-260128';
  4870. }
  4871. }
  4872. // 验证模型是否在可用模型表中
  4873. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4874. // $model = 'doubao-seedream-5-0-lite-260128';
  4875. Utils::throwError('20003:该模型已不可用,请更换!');
  4876. }
  4877. // 保存到episode表
  4878. if ($episode_id) {
  4879. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4880. 'image_model' => $model,
  4881. 'updated_at' => date('Y-m-d H:i:s')
  4882. ]);
  4883. }
  4884. // 参数验证
  4885. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4886. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  4887. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  4888. $imageNum = self::getInnerImageNum($inner_prompt_type);
  4889. try {
  4890. // 创建图片生成任务
  4891. $params = [
  4892. 'prompt' => $prompt,
  4893. 'model' => $model,
  4894. 'ref_img_urls' => '',
  4895. 'width' => $width,
  4896. 'height' => $height,
  4897. 'image_num' => $imageNum
  4898. ];
  4899. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4900. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4901. $task_id = $task->id;
  4902. if (!$task_id) {
  4903. Utils::throwError('20003:创建图片生成任务失败');
  4904. }
  4905. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4906. $model = getProp($task, 'model');
  4907. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4908. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4909. $isSyncModel = $isVolcModel || $isGptModel;
  4910. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4911. $start_time = time();
  4912. $timeout = 300; // 5分钟
  4913. $img_url = '';
  4914. while (time() - $start_time < $timeout) {
  4915. sleep(3);
  4916. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4917. if ($isSyncModel) {
  4918. // 刷新任务状态
  4919. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4920. if ($task->status === 'success' && $task->result_url) {
  4921. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  4922. break;
  4923. } elseif ($task->status === 'failed') {
  4924. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4925. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4926. }
  4927. // // 如果还在处理中,提示用户稍后查看
  4928. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4929. }else {
  4930. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4931. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4932. if ($statusInfo['status'] === 'success') {
  4933. $task->updateStatus('success', [
  4934. 'result_url' => $statusInfo['result_url'],
  4935. 'result_json' => $statusInfo['result_json'] ?? []
  4936. ]);
  4937. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  4938. break;
  4939. } elseif ($statusInfo['status'] === 'failed') {
  4940. $task->updateStatus('failed', [
  4941. 'error_message' => $statusInfo['error_message'],
  4942. 'result_json' => $statusInfo['result_json'] ?? []
  4943. ]);
  4944. dLog('anime')->error('图片生成失败,', [
  4945. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4946. ]);
  4947. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4948. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4949. }
  4950. }
  4951. }
  4952. if (empty($img_url)) {
  4953. Utils::throwError('20003:图片生成超时,请稍后重试');
  4954. }
  4955. return $img_url;
  4956. } catch (\Exception $e) {
  4957. dLog('anime')->error('更新角色或场景失败', [
  4958. 'error' => $e->getMessage()
  4959. ]);
  4960. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4961. Utils::throwError('20003:' . $e->getMessage());
  4962. }
  4963. }
  4964. /**
  4965. * 使用文生文模型解析分镜内容
  4966. */
  4967. private function parseSegmentContentWithAI($segment_content) {
  4968. try {
  4969. // 使用DeepSeek服务的公开方法解析分镜内容
  4970. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4971. } catch (\Exception $e) {
  4972. // 如果AI解析失败,记录日志并返回原内容
  4973. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4974. return $segment_content;
  4975. }
  4976. }
  4977. /**
  4978. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4979. *
  4980. * @param int $episode_id 分集ID
  4981. * @param int $anime_id 动漫ID
  4982. * @param array $roles 分集角色数组(引用传递)
  4983. * @param array $scenes 分集场景数组(引用传递)
  4984. * @param array $episode 分集数据
  4985. */
  4986. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4987. // 获取全局动漫的角色和场景数据
  4988. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4989. if (!$anime) return;
  4990. $art_style_type = getProp($anime, 'art_style_type');
  4991. $character_prefix = '';
  4992. $scene_prefix = '';
  4993. if ($art_style_type) {
  4994. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4995. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4996. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4997. }
  4998. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4999. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5000. $roles_updated = false;
  5001. $scenes_updated = false;
  5002. // 处理角色
  5003. foreach ($roles as &$role) {
  5004. $role_name = getProp($role, 'role');
  5005. $role_description = getProp($role, 'description');
  5006. $role_pic_prompt = getProp($role, 'pic_prompt');
  5007. $role_url = getProp($role, 'url');
  5008. $role_task_id = getProp($role, 'task_id');
  5009. // 如果已有URL或已有任务ID,跳过
  5010. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5011. continue;
  5012. }
  5013. $url_inherited = false;
  5014. // 尝试从全局数据中继承
  5015. foreach ($global_roles as $global_role) {
  5016. $global_role_name = getProp($global_role, 'role');
  5017. $global_role_description = getProp($global_role, 'description');
  5018. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5019. $global_role_url = getProp($global_role, 'url');
  5020. $global_role_task_id = getProp($global_role, 'task_id');
  5021. $global_role_task_status = getProp($global_role, 'task_status');
  5022. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5023. if ($role_name === $global_role_name
  5024. && $role_description === $global_role_description
  5025. && $role_pic_prompt === $global_role_pic_prompt
  5026. && !empty($global_role_url)) {
  5027. // 继承 task_id、task_status 和 url
  5028. $role['task_id'] = $global_role_task_id;
  5029. $role['task_status'] = $global_role_task_status;
  5030. $role['url'] = $global_role_url;
  5031. $roles_updated = true;
  5032. $url_inherited = true;
  5033. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5034. break;
  5035. }
  5036. }
  5037. // 如果无法继承且没有任务ID,创建新任务
  5038. if (!$url_inherited && empty($role_task_id)) {
  5039. try {
  5040. $art_style = getProp($episode, 'art_style');
  5041. // 优先使用 pic_prompt,如果没有则使用 description
  5042. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5043. // if ($art_style) {
  5044. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5045. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5046. // }
  5047. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5048. $params = [
  5049. 'prompt' => $description,
  5050. 'ref_img_urls' => []
  5051. ];
  5052. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5053. $task_id = $task->id;
  5054. if ($task_id) {
  5055. $role['task_id'] = $task_id;
  5056. $role['task_status'] = 'processing';
  5057. $roles_updated = true;
  5058. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5059. }
  5060. } catch (\Exception $e) {
  5061. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5062. }
  5063. }
  5064. }
  5065. // 处理场景
  5066. foreach ($scenes as &$scene) {
  5067. $scene_name = getProp($scene, 'scene');
  5068. $scene_description = getProp($scene, 'description');
  5069. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5070. $scene_url = getProp($scene, 'url');
  5071. $scene_task_id = getProp($scene, 'task_id');
  5072. // 如果已有URL或已有任务ID,跳过
  5073. if (!empty($scene_url) || !empty($scene_task_id)) {
  5074. continue;
  5075. }
  5076. $url_inherited = false;
  5077. // 尝试从全局数据中继承
  5078. foreach ($global_scenes as $global_scene) {
  5079. $global_scene_name = getProp($global_scene, 'scene');
  5080. $global_scene_description = getProp($global_scene, 'description');
  5081. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5082. $global_scene_url = getProp($global_scene, 'url');
  5083. $global_scene_task_id = getProp($global_scene, 'task_id');
  5084. $global_scene_task_status = getProp($global_scene, 'task_status');
  5085. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5086. if ($scene_name === $global_scene_name
  5087. && $scene_description === $global_scene_description
  5088. && $scene_pic_prompt === $global_scene_pic_prompt
  5089. && !empty($global_scene_url)) {
  5090. // 继承 task_id、task_status 和 url
  5091. $scene['task_id'] = $global_scene_task_id;
  5092. $scene['task_status'] = $global_scene_task_status;
  5093. $scene['url'] = $global_scene_url;
  5094. $scenes_updated = true;
  5095. $url_inherited = true;
  5096. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5097. break;
  5098. }
  5099. }
  5100. // 如果无法继承且没有任务ID,创建新任务
  5101. if (!$url_inherited && empty($scene_task_id)) {
  5102. try {
  5103. $art_style = getProp($episode, 'art_style');
  5104. // 优先使用 pic_prompt,如果没有则使用 description
  5105. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5106. // if ($art_style) {
  5107. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5108. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5109. // }
  5110. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5111. $params = [
  5112. 'prompt' => $description,
  5113. 'ref_img_urls' => []
  5114. ];
  5115. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5116. $task_id = $task->id;
  5117. if ($task_id) {
  5118. $scene['task_id'] = $task_id;
  5119. $scene['task_status'] = 'processing';
  5120. $scenes_updated = true;
  5121. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5122. }
  5123. } catch (\Exception $e) {
  5124. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5125. }
  5126. }
  5127. }
  5128. // 如果有更新,保存到数据库
  5129. if ($roles_updated || $scenes_updated) {
  5130. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5131. if ($roles_updated) {
  5132. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5133. }
  5134. if ($scenes_updated) {
  5135. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5136. }
  5137. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5138. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5139. }
  5140. }
  5141. /**
  5142. * 根据图片URL使用AI反推图片提示词
  5143. *
  5144. * @param string $img_url 图片URL
  5145. * @return string 反推的提示词
  5146. */
  5147. private function generateImagePromptFromUrl($img_url) {
  5148. try {
  5149. // 获取默认模型
  5150. $model = 'doubao-seed-2-0-mini-260215';
  5151. // 构建messages参数
  5152. $messages = [
  5153. [
  5154. 'role' => 'user',
  5155. 'content' => [
  5156. [
  5157. 'type' => 'text',
  5158. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5159. ],
  5160. [
  5161. 'type' => 'image_url',
  5162. 'image_url' => [
  5163. 'url' => $img_url
  5164. ]
  5165. ]
  5166. ]
  5167. ]
  5168. ];
  5169. // 构建请求参数
  5170. $params = [
  5171. 'model' => $model,
  5172. 'messages' => $messages,
  5173. 'stream' => false,
  5174. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5175. ];
  5176. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5177. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5178. // 返回生成的内容
  5179. return getProp($result, 'fullContent', '图片描述生成失败');
  5180. } catch (\Exception $e) {
  5181. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5182. 'img_url' => $img_url
  5183. ]);
  5184. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5185. 'error' => $e->getMessage(),
  5186. 'img_url' => $img_url
  5187. ]);
  5188. return '图片描述生成失败: ' . $e->getMessage();
  5189. }
  5190. }
  5191. /**
  5192. * 音频试听接口
  5193. * 创建音频任务并轮询获取结果
  5194. *
  5195. * @param array $data 参数数组
  5196. * @return array 返回音频URL或错误信息
  5197. */
  5198. public function previewAudio($data) {
  5199. $dialogue = getProp($data, 'dialogue');
  5200. // 必填参数验证
  5201. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5202. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5203. $voice_type = getProp($data, 'voice_type');
  5204. $voice_name = getProp($data, 'voice_name');
  5205. $voice_actor = getProp($data, 'voice_actor');
  5206. $emotion_type = getProp($data, 'emotion_type');
  5207. $gender = getProp($data, 'gender', 0);
  5208. $emotion = getProp($data, 'emotion');
  5209. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5210. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5211. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5212. $pitch = getProp($data, 'pitch', 0);
  5213. try {
  5214. $now = date('Y-m-d H:i:s');
  5215. // 构建生成参数
  5216. $generate_json = json_encode([
  5217. 'text' => $dialogue,
  5218. 'role' => $voice_actor,
  5219. 'voice_type' => $voice_type,
  5220. 'voice_name' => $voice_name,
  5221. 'emotion' => $emotion,
  5222. 'emotion_type' => $emotion_type,
  5223. 'gender' => $gender,
  5224. 'speed_ratio' => $speed_ratio,
  5225. 'loudness_ratio' => $loudness_ratio,
  5226. 'emotion_scale' => $emotion_scale,
  5227. 'pitch' => $pitch,
  5228. ], 256);
  5229. // 请求远程服务器执行生成
  5230. $client = new Client(['timeout' => 600, 'verify' => false]);
  5231. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5232. $response = $result->getBody()->getContents();
  5233. $response_arr = json_decode($response, true);
  5234. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5235. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5236. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5237. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5238. }
  5239. $arr = $response_arr['data'];
  5240. $subtitle_info = $arr['subtitle_info'];
  5241. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5242. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5243. return [
  5244. 'audio_url' => $arr['url'],
  5245. 'subtitle_info' => $subtitle_info,
  5246. 'audio_duration' => round($audio_duration, 2)
  5247. ];
  5248. } catch (\Exception $e) {
  5249. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5250. Utils::throwError('20003:' . $e->getMessage());
  5251. }
  5252. }
  5253. /**
  5254. * 获取角色库列表(支持文件夹递归查询)
  5255. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5256. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5257. */
  5258. public function globalProducts($data) {
  5259. $uid = Site::getUid();
  5260. $cpid = Site::getCpid();
  5261. $role = Site::getRole();
  5262. $id = getProp($data, 'id', 0);
  5263. $parent_id = getProp($data, 'parent_id', 0);
  5264. $product_name = getProp($data, 'product_name');
  5265. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5266. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5267. if (!$product) {
  5268. Utils::throwError('20003:请选择产品类型');
  5269. }
  5270. // 根据角色和is_public参数确定查询范围
  5271. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5272. // user角色:根据is_public参数筛选
  5273. $query_user_ids = [];
  5274. if ($role === 'admin') {
  5275. // admin获取所有个人库和公共库
  5276. $query_user_ids = [$uid, 0];
  5277. } else {
  5278. // user角色根据is_public参数筛选
  5279. if ($is_public == 2) {
  5280. // 个人库+公共库
  5281. $query_user_ids = [$uid, 0];
  5282. } elseif ($is_public == 0) {
  5283. // 仅个人库
  5284. $query_user_ids = [$uid];
  5285. } elseif ($is_public == 1) {
  5286. // 仅公共库
  5287. $query_user_ids = [0];
  5288. }
  5289. }
  5290. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5291. if ($id || $product_name) {
  5292. $query = DB::table('mp_products')
  5293. ->where('cpid', $cpid)
  5294. ->whereIn('user_id', $query_user_ids)
  5295. ->where('is_deleted', 0);
  5296. // 如果指定了 id,按 id 精确查询
  5297. if ($id) {
  5298. $query->where('id', $id);
  5299. }
  5300. // 如果指定了 product_name,按名称模糊查询
  5301. if ($product_name) {
  5302. $query->where('product_name', 'like', "%{$product_name}%");
  5303. }
  5304. // 如果指定了 product,添加筛选条件
  5305. if ($product) {
  5306. $query->where('product', $product);
  5307. }
  5308. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5309. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5310. ->get()
  5311. ->map(function($value) {
  5312. $value = (array)$value;
  5313. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5314. $value['type'] = (int)$value['type'];
  5315. $value['parent_id'] = (int)$value['parent_id'];
  5316. $value['level'] = (int)$value['level'];
  5317. $value['product'] = (int)($value['product'] ?? 1);
  5318. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5319. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5320. unset($value['user_id']);
  5321. return $value;
  5322. })
  5323. ->toArray();
  5324. return $result;
  5325. }
  5326. // 递归获取所有子目录和角色
  5327. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5328. }
  5329. /**
  5330. * 递归获取指定目录下的所有子目录和角色
  5331. * @param int $cpid 公司ID
  5332. * @param int $parent_id 父目录ID
  5333. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5334. * @param array $query_user_ids 用户ID数组(支持多个)
  5335. * @param int $current_uid 当前用户ID(用于排序)
  5336. * @return array
  5337. */
  5338. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5339. // 查询当前层级的所有项(文件夹和角色)
  5340. $query = DB::table('mp_products')
  5341. ->where('cpid', $cpid)
  5342. ->where('is_deleted', 0)
  5343. ->where('parent_id', $parent_id);
  5344. // 添加用户ID验证(支持多个user_id)
  5345. if (!empty($query_user_ids)) {
  5346. $query->whereIn('user_id', $query_user_ids);
  5347. }
  5348. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5349. if ($product) {
  5350. $query->where('product', $product);
  5351. }
  5352. // 排序规则:
  5353. // 1. 文件夹在前(type DESC)
  5354. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5355. // 3. 其他排序规则
  5356. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5357. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5358. ->get();
  5359. $result = [];
  5360. foreach ($items as $item) {
  5361. $itemArray = [
  5362. 'id' => $item->id,
  5363. 'type' => (int)$item->type,
  5364. 'parent_id' => (int)$item->parent_id,
  5365. 'level' => (int)$item->level,
  5366. 'product_name' => $item->product_name,
  5367. 'url' => $item->url,
  5368. 'pic_prompt' => $item->pic_prompt ?? '',
  5369. 'three_view_image_url' => $item->three_view_image_url,
  5370. 'product' => (int)($item->product ?? 1),
  5371. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5372. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5373. ];
  5374. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5375. // 如果是文件夹,递归获取其子项
  5376. if ($item->type == 2) {
  5377. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5378. if (!empty($children)) {
  5379. $itemArray['children'] = $children;
  5380. }
  5381. }
  5382. $result[] = $itemArray;
  5383. }
  5384. return $result;
  5385. }
  5386. /**
  5387. * 创建文件夹
  5388. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5389. * @return int 返回新建文件夹ID
  5390. */
  5391. public function createFolder($data) {
  5392. $uid = Site::getUid();
  5393. $cpid = Site::getCpid();
  5394. $role = Site::getRole();
  5395. $parent_id = getProp($data, 'parent_id', 0);
  5396. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5397. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5398. // 如果是公共库操作,需要admin权限
  5399. if ($is_public && $role !== 'admin') {
  5400. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5401. }
  5402. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5403. $store_uid = $is_public ? 0 : $uid;
  5404. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5405. $product = getProp($data, 'product');
  5406. if (!in_array($product, [1, 2, 3])) {
  5407. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5408. }
  5409. // 验证父文件夹
  5410. $parent_level = 0;
  5411. if ($parent_id > 0) {
  5412. $parent = DB::table('mp_products')
  5413. ->where('id', $parent_id)
  5414. ->where('cpid', $cpid)
  5415. ->where('user_id', $store_uid)
  5416. ->where('type', 2)
  5417. ->where('is_deleted', 0)
  5418. ->first();
  5419. if (!$parent) {
  5420. Utils::throwError('20003:父文件夹不存在');
  5421. }
  5422. // 检查父文件夹的 product 类型是否一致
  5423. if ($parent->product != $product) {
  5424. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5425. }
  5426. $parent_level = $parent->level;
  5427. // 检查层级限制(最多3层)
  5428. if ($parent_level >= 3) {
  5429. Utils::throwError('20003:文件夹层级不能超过3层');
  5430. }
  5431. }
  5432. // 检查当前目录下是否已存在空白文件夹
  5433. $empty_folder_exists = DB::table('mp_products')
  5434. ->where('parent_id', $parent_id)
  5435. ->where('cpid', $cpid)
  5436. ->where('user_id', $store_uid)
  5437. ->where('type', 2)
  5438. ->where('product', $product)
  5439. ->where('product_name', '新建文件夹')
  5440. ->where('is_deleted', 0)
  5441. ->exists();
  5442. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5443. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5444. }
  5445. // 创建文件夹
  5446. $folder_id = DB::table('mp_products')->insertGetId([
  5447. 'user_id' => $store_uid,
  5448. 'cpid' => $cpid,
  5449. 'type' => 2,
  5450. 'parent_id' => $parent_id,
  5451. 'level' => $parent_level + 1,
  5452. 'product_name' => $folder_name,
  5453. 'product' => $product,
  5454. 'sort_order' => time(), // 使用时间戳作为排序权重
  5455. 'is_deleted' => 0,
  5456. 'created_at' => date('Y-m-d H:i:s'),
  5457. 'updated_at' => date('Y-m-d H:i:s')
  5458. ]);
  5459. return [
  5460. 'id' => $folder_id,
  5461. 'type' => 2,
  5462. 'parent_id' => $parent_id,
  5463. 'level' => $parent_level + 1,
  5464. 'product_name' => $folder_name,
  5465. 'product' => $product,
  5466. ];
  5467. }
  5468. /**
  5469. * 重命名文件夹或角色
  5470. * @param array $data 包含 id、product_name(新名称)
  5471. * @return bool
  5472. */
  5473. public function renameFolder($data) {
  5474. $uid = Site::getUid();
  5475. $cpid = Site::getCpid();
  5476. $role = Site::getRole();
  5477. $id = getProp($data, 'id');
  5478. $new_name = getProp($data, 'product_name');
  5479. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5480. if (!$id || !$new_name) {
  5481. Utils::throwError('20003:参数不完整');
  5482. }
  5483. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5484. $query_uid = $is_public ? 0 : $uid;
  5485. // 如果是公共库操作,需要admin权限
  5486. if ($is_public && $role !== 'admin') {
  5487. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5488. }
  5489. // 检查是否存在
  5490. $item = DB::table('mp_products')
  5491. ->where('id', $id)
  5492. ->where('cpid', $cpid)
  5493. ->where('user_id', $query_uid)
  5494. ->where('is_deleted', 0)
  5495. ->first();
  5496. if (!$item) {
  5497. Utils::throwError('20003:项目不存在');
  5498. }
  5499. return DB::table('mp_products')
  5500. ->where('id', $id)
  5501. ->where('cpid', $cpid)
  5502. ->where('user_id', $query_uid)
  5503. ->update([
  5504. 'product_name' => $new_name,
  5505. 'updated_at' => date('Y-m-d H:i:s')
  5506. ]);
  5507. }
  5508. /**
  5509. * 移动角色或文件夹到指定文件夹
  5510. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5511. * @return bool
  5512. */
  5513. public function moveProductOrFolder($data) {
  5514. $uid = Site::getUid();
  5515. $cpid = Site::getCpid();
  5516. $role = Site::getRole();
  5517. $id = getProp($data, 'id');
  5518. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5519. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5520. if (!$id) {
  5521. Utils::throwError('20003:请选择要移动的项目');
  5522. }
  5523. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5524. $query_uid = $is_public ? 0 : $uid;
  5525. // 如果是公共库操作,需要admin权限
  5526. if ($is_public && $role !== 'admin') {
  5527. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5528. }
  5529. // 检查要移动的项目
  5530. $item = DB::table('mp_products')
  5531. ->where('id', $id)
  5532. ->where('cpid', $cpid)
  5533. ->where('user_id', $query_uid)
  5534. ->where('is_deleted', 0)
  5535. ->first();
  5536. if (!$item) {
  5537. Utils::throwError('20003:项目不存在');
  5538. }
  5539. // 验证目标文件夹
  5540. $target_level = 0;
  5541. $target_product = $item->product; // 默认使用当前项目的 product
  5542. if ($target_parent_id > 0) {
  5543. $target_parent = DB::table('mp_products')
  5544. ->where('id', $target_parent_id)
  5545. ->where('cpid', $cpid)
  5546. ->where('user_id', $query_uid)
  5547. ->where('type', 2)
  5548. ->where('is_deleted', 0)
  5549. ->first();
  5550. if (!$target_parent) {
  5551. Utils::throwError('20003:目标文件夹不存在');
  5552. }
  5553. // 检查 product 类型是否一致
  5554. if ($target_parent->product != $item->product) {
  5555. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5556. }
  5557. $target_level = $target_parent->level;
  5558. $target_product = $target_parent->product;
  5559. // 如果移动的是文件夹,需要检查层级
  5560. if ($item->type == 2) {
  5561. // 计算移动后的最大层级
  5562. $max_child_level = $this->getMaxChildLevel($id);
  5563. $depth = $max_child_level - $item->level;
  5564. if ($target_level + 1 + $depth > 3) {
  5565. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5566. }
  5567. // 不能移动到自己或自己的子文件夹下
  5568. if ($this->isDescendant($target_parent_id, $id)) {
  5569. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5570. }
  5571. }
  5572. }
  5573. // 更新父文件夹和层级
  5574. $new_level = $target_level + 1;
  5575. DB::table('mp_products')
  5576. ->where('id', $id)
  5577. ->update([
  5578. 'parent_id' => $target_parent_id,
  5579. 'level' => $new_level,
  5580. 'updated_at' => date('Y-m-d H:i:s')
  5581. ]);
  5582. // 如果是文件夹,需要递归更新所有子项的层级
  5583. if ($item->type == 2) {
  5584. $this->updateChildrenLevel($id, $new_level);
  5585. }
  5586. return true;
  5587. }
  5588. /**
  5589. * 获取文件夹下最大子层级
  5590. * @param int $folder_id
  5591. * @return int
  5592. */
  5593. private function getMaxChildLevel($folder_id) {
  5594. $max_level = DB::table('mp_products')
  5595. ->where('parent_id', $folder_id)
  5596. ->where('is_deleted', 0)
  5597. ->max('level');
  5598. if (!$max_level) {
  5599. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5600. }
  5601. // 递归查找子文件夹
  5602. $children = DB::table('mp_products')
  5603. ->where('parent_id', $folder_id)
  5604. ->where('type', 2)
  5605. ->where('is_deleted', 0)
  5606. ->pluck('id');
  5607. foreach ($children as $child_id) {
  5608. $child_max = $this->getMaxChildLevel($child_id);
  5609. if ($child_max > $max_level) {
  5610. $max_level = $child_max;
  5611. }
  5612. }
  5613. return $max_level;
  5614. }
  5615. /**
  5616. * 检查 target_id 是否是 folder_id 的后代
  5617. * @param int $target_id
  5618. * @param int $folder_id
  5619. * @return bool
  5620. */
  5621. private function isDescendant($target_id, $folder_id) {
  5622. if ($target_id == $folder_id) {
  5623. return true;
  5624. }
  5625. $parent = DB::table('mp_products')
  5626. ->where('id', $target_id)
  5627. ->where('is_deleted', 0)
  5628. ->first();
  5629. if (!$parent || $parent->parent_id == 0) {
  5630. return false;
  5631. }
  5632. return $this->isDescendant($parent->parent_id, $folder_id);
  5633. }
  5634. /**
  5635. * 递归更新子项层级
  5636. * @param int $parent_id
  5637. * @param int $parent_level
  5638. */
  5639. private function updateChildrenLevel($parent_id, $parent_level) {
  5640. $children = DB::table('mp_products')
  5641. ->where('parent_id', $parent_id)
  5642. ->where('is_deleted', 0)
  5643. ->get();
  5644. foreach ($children as $child) {
  5645. $new_level = $parent_level + 1;
  5646. DB::table('mp_products')
  5647. ->where('id', $child->id)
  5648. ->update([
  5649. 'level' => $new_level,
  5650. 'updated_at' => date('Y-m-d H:i:s')
  5651. ]);
  5652. // 如果是文件夹,继续递归
  5653. if ($child->type == 2) {
  5654. $this->updateChildrenLevel($child->id, $new_level);
  5655. }
  5656. }
  5657. }
  5658. /**
  5659. * 获取文件夹路径(面包屑导航)
  5660. * @param array $data 包含 folder_id
  5661. * @return array 返回路径数组
  5662. */
  5663. public function getFolderPath($data) {
  5664. $uid = Site::getUid();
  5665. $cpid = Site::getCpid();
  5666. $folder_id = getProp($data, 'id', 0);
  5667. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5668. if ($folder_id == 0) {
  5669. return [
  5670. ['id' => 0, 'name' => '根目录']
  5671. ];
  5672. }
  5673. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5674. $query_uid = $is_public ? 0 : $uid;
  5675. $path = [];
  5676. $current_id = $folder_id;
  5677. while ($current_id > 0) {
  5678. $folder = DB::table('mp_products')
  5679. ->where('id', $current_id)
  5680. ->where('cpid', $cpid)
  5681. ->where('user_id', $query_uid)
  5682. ->where('type', 2)
  5683. ->where('is_deleted', 0)
  5684. ->first();
  5685. if (!$folder) {
  5686. break;
  5687. }
  5688. array_unshift($path, [
  5689. 'id' => $folder->id,
  5690. 'name' => $folder->product_name
  5691. ]);
  5692. $current_id = $folder->parent_id;
  5693. }
  5694. // 添加根目录
  5695. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5696. return $path;
  5697. }
  5698. public function createProduct($data) {
  5699. $uid = Site::getUid();
  5700. $cpid = Site::getCpid();
  5701. $role = Site::getRole();
  5702. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5703. // 如果是公共库操作,需要admin权限
  5704. if ($is_public && $role !== 'admin') {
  5705. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5706. }
  5707. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5708. $store_uid = $is_public ? 0 : $uid;
  5709. $product_name = trim(getProp($data, 'product_name'));
  5710. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5711. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5712. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5713. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5714. $url = trim(getProp($data, 'url'));
  5715. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5716. $versions = getProp($data, 'versions');
  5717. // 检查是否是正确的图片格式
  5718. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5719. $urlPath = parse_url($url, PHP_URL_PATH);
  5720. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5721. if (!in_array($extension, $allowedExtensions)) {
  5722. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5723. }
  5724. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5725. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5726. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5727. $product = getProp($data, 'product');
  5728. if (!in_array($product, [1, 2, 3])) {
  5729. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5730. }
  5731. // 获取父文件夹ID和层级
  5732. $parent_id = getProp($data, 'parent_id', 0);
  5733. $parent_level = 0;
  5734. if ($parent_id > 0) {
  5735. $parent = DB::table('mp_products')
  5736. ->where('id', $parent_id)
  5737. ->where('cpid', $cpid)
  5738. ->where('user_id', $store_uid)
  5739. ->where('type', 2)
  5740. ->where('is_deleted', 0)
  5741. ->first();
  5742. if (!$parent) {
  5743. Utils::throwError('20003:父文件夹不存在');
  5744. }
  5745. $parent_level = $parent->level;
  5746. }
  5747. $id = DB::table('mp_products')->insertGetId([
  5748. 'user_id' => $store_uid,
  5749. 'cpid' => $cpid,
  5750. 'type' => 1, // 1=角色图片
  5751. 'parent_id' => $parent_id,
  5752. 'level' => $parent_level + 1,
  5753. 'product_name' => $product_name,
  5754. 'url' => $url,
  5755. 'pic_prompt' => $pic_prompt,
  5756. 'product' => $product,
  5757. 'versions' => json_encode($versions, 256),
  5758. 'sort_order' => time(), // 使用时间戳作为排序权重
  5759. 'created_at' => date('Y-m-d H:i:s'),
  5760. 'updated_at' => date('Y-m-d H:i:s')
  5761. ]);
  5762. if (!$id) Utils::throwError('20003:创建失败');
  5763. return [
  5764. 'id' => $id,
  5765. 'type' => 1,
  5766. 'parent_id' => $parent_id,
  5767. 'level' => $parent_level + 1,
  5768. 'product_name' => $product_name,
  5769. 'url' => $url,
  5770. 'pic_prompt' => $pic_prompt,
  5771. 'product' => $product,
  5772. 'versions' => $versions
  5773. ];
  5774. }
  5775. public function editProduct($data) {
  5776. $uid = Site::getUid();
  5777. $cpid = Site::getCpid();
  5778. $role = Site::getRole();
  5779. $id = getProp($data, 'id');
  5780. if (!$id) Utils::throwError('20003:ID不能为空');
  5781. $versions = getProp($data, 'versions');
  5782. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5783. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5784. $query_uid = $is_public ? 0 : $uid;
  5785. // 如果是公共库操作,需要admin权限
  5786. if ($is_public && $role !== 'admin') {
  5787. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5788. }
  5789. // 检查是否存在且属于当前用户或公共库
  5790. $role = DB::table('mp_products')
  5791. ->where('id', $id)
  5792. ->where('cpid', $cpid)
  5793. ->where('user_id', $query_uid)
  5794. ->where('type', 1)->first();
  5795. if (!$role) Utils::throwError('20003:记录不存在');
  5796. $updateData = [];
  5797. // $needVersionRecord = false; // 是否需要记录版本
  5798. // 名称
  5799. $product_name = trim(getProp($data, 'product_name'));
  5800. if ($product_name) {
  5801. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5802. $updateData['product_name'] = $product_name;
  5803. }
  5804. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5805. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5806. // 图片地址
  5807. $url = trim(getProp($data, 'url'));
  5808. if ($url) {
  5809. // 检查是否是正确的图片格式
  5810. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5811. $urlPath = parse_url($url, PHP_URL_PATH);
  5812. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5813. if (!in_array($extension, $allowedExtensions)) {
  5814. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5815. }
  5816. // // 如果 url 有变更,记录版本
  5817. // if ($url !== $role->url) {
  5818. // $needVersionRecord = true;
  5819. // }
  5820. $updateData['url'] = $url;
  5821. }
  5822. // 提示词
  5823. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5824. if ($pic_prompt) {
  5825. // // 如果 pic_prompt 有变更,记录版本
  5826. // if ($pic_prompt !== $role->pic_prompt) {
  5827. // $needVersionRecord = true;
  5828. // }
  5829. $updateData['pic_prompt'] = $pic_prompt;
  5830. }
  5831. if (empty($updateData)) {
  5832. Utils::throwError('20003:没有需要更新的数据');
  5833. }
  5834. // // 如果需要记录版本,将数据添加到 versions 数组
  5835. // if ($needVersionRecord) {
  5836. // // 获取现有的 versions 数据
  5837. // $versions = json_decode($role->versions, true) ?: [];
  5838. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5839. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5840. // if ($isFirstVersion) {
  5841. // $oldVersion = [
  5842. // 'url' => $role->url,
  5843. // 'description' => $role->pic_prompt,
  5844. // ];
  5845. // // 旧版本添加到数组末尾
  5846. // $versions[] = $oldVersion;
  5847. // }
  5848. // // 构建新版本(变更后)
  5849. // $newVersion = [
  5850. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5851. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5852. // ];
  5853. // // 检查新版本是否已存在于历史版本中
  5854. // $existingIndex = -1;
  5855. // foreach ($versions as $index => $version) {
  5856. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5857. // $existingIndex = $index;
  5858. // break;
  5859. // }
  5860. // }
  5861. // if ($existingIndex !== -1) {
  5862. // // 如果已存在,移除旧的位置
  5863. // array_splice($versions, $existingIndex, 1);
  5864. // }
  5865. // // 新版本添加到数组开头(最新的在前)
  5866. // array_unshift($versions, $newVersion);
  5867. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5868. // // if (count($versions) > 10) {
  5869. // // $versions = array_slice($versions, 0, 10);
  5870. // // }
  5871. // $updateData['versions'] = json_encode($versions, 256);
  5872. // }
  5873. if ($versions) {
  5874. $updateData['versions'] = json_encode($versions, 256);
  5875. }
  5876. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5877. return DB::table('mp_products')
  5878. ->where('cpid', $cpid)
  5879. ->where('id', $id)->update($updateData);
  5880. }
  5881. /**
  5882. * 获取角色版本历史
  5883. * @param array $data 包含 id(角色ID)
  5884. * @return array 返回版本历史列表
  5885. */
  5886. public function getProductVersions($data) {
  5887. $cpid = Site::getCpid();
  5888. $id = getProp($data, 'id');
  5889. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5890. $role = DB::table('mp_products')
  5891. ->where('id', $id)
  5892. ->where('cpid', $cpid)
  5893. ->where('type', 1)
  5894. ->first();
  5895. if (!$role) Utils::throwError('20003:角色不存在');
  5896. // 获取版本历史
  5897. $versions = json_decode($role->versions, true) ?: [];
  5898. // 添加当前版本作为最新版本
  5899. $currentVersion = [
  5900. 'version' => 0, // 0 表示当前版本
  5901. 'url' => $role->url,
  5902. 'pic_prompt' => $role->pic_prompt,
  5903. 'updated_at' => $role->updated_at,
  5904. 'is_current' => true
  5905. ];
  5906. array_unshift($versions, $currentVersion);
  5907. return $versions;
  5908. }
  5909. /**
  5910. * 恢复到指定版本
  5911. * @param array $data 包含 id(角色ID)、version(版本号)
  5912. * @return bool
  5913. */
  5914. public function restoreProductVersion($data) {
  5915. $uid = Site::getUid();
  5916. $cpid = Site::getCpid();
  5917. $id = getProp($data, 'id');
  5918. $version = getProp($data, 'version');
  5919. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5920. if (!$version) Utils::throwError('20003:版本号不能为空');
  5921. $role = DB::table('mp_products')
  5922. ->where('id', $id)
  5923. ->where('cpid', $cpid)
  5924. ->where('type', 1)
  5925. ->first();
  5926. if (!$role) Utils::throwError('20003:角色不存在');
  5927. // 获取版本历史
  5928. $versions = json_decode($role->versions, true) ?: [];
  5929. // 查找指定版本
  5930. $targetVersion = null;
  5931. foreach ($versions as $v) {
  5932. if ($v['version'] == $version) {
  5933. $targetVersion = $v;
  5934. break;
  5935. }
  5936. }
  5937. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5938. // 先将当前版本保存到历史
  5939. $newVersion = [
  5940. 'version' => count($versions) + 1,
  5941. 'url' => $role->url,
  5942. 'pic_prompt' => $role->pic_prompt,
  5943. 'updated_at' => date('Y-m-d H:i:s'),
  5944. 'updated_by' => $uid
  5945. ];
  5946. array_unshift($versions, $newVersion);
  5947. // 限制版本数量
  5948. if (count($versions) > 10) {
  5949. $versions = array_slice($versions, 0, 10);
  5950. }
  5951. // 恢复到指定版本
  5952. return DB::table('mp_products')
  5953. ->where('id', $id)
  5954. ->where('cpid', $cpid)
  5955. ->update([
  5956. 'url' => $targetVersion['url'],
  5957. 'pic_prompt' => $targetVersion['pic_prompt'],
  5958. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5959. 'updated_at' => date('Y-m-d H:i:s')
  5960. ]);
  5961. }
  5962. public function deleteProduct($data) {
  5963. $uid = Site::getUid();
  5964. $cpid = Site::getCpid();
  5965. $role = Site::getRole();
  5966. $id = getProp($data, 'id');
  5967. if (!$id) Utils::throwError('20003:ID不能为空');
  5968. $ids = explode(',', $id);
  5969. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5970. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5971. $query_uid = $is_public ? 0 : $uid;
  5972. // 如果是公共库操作,需要admin权限
  5973. if ($is_public && $role !== 'admin') {
  5974. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5975. }
  5976. // 检查是否存在且属于当前用户或公共库
  5977. $role = DB::table('mp_products')
  5978. ->whereIn('id', $ids)
  5979. ->where('cpid', $cpid)
  5980. ->where('user_id', $query_uid)
  5981. ->get();
  5982. if (!$role) Utils::throwError('20003:记录不存在');
  5983. return DB::table('mp_products')
  5984. ->where('cpid', $cpid)
  5985. ->where('user_id', $query_uid)
  5986. ->whereIn('id', $ids)
  5987. ->update([
  5988. 'is_deleted' => 1,
  5989. 'updated_at' => date('Y-m-d H:i:s')
  5990. ]);
  5991. }
  5992. public function generateThreeView($data) {
  5993. $uid = Site::getUid();
  5994. $cpid = Site::getCpid();
  5995. $role = Site::getRole();
  5996. $id = getProp($data, 'id');
  5997. if (!$id) Utils::throwError('20003:ID不能为空');
  5998. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5999. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6000. $query_uid = $is_public ? 0 : $uid;
  6001. // 如果是公共库操作,需要admin权限
  6002. if ($is_public && $role !== 'admin') {
  6003. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6004. }
  6005. // 检查是否存在且属于当前用户或公共库
  6006. $product = DB::table('mp_products')
  6007. ->where('id', $id)
  6008. ->where('cpid', $cpid)
  6009. ->where('user_id', $query_uid)
  6010. ->where('type', 1)->first();
  6011. if (!$product) Utils::throwError('20003:资产不存在');
  6012. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6013. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6014. if (!$ref_img_url) {
  6015. // 如果没有传入参考图,使用角色表中的图片
  6016. $ref_img_url = $product->url ?? '';
  6017. if (!$ref_img_url) {
  6018. Utils::throwError('20003:参考图不能为空');
  6019. }
  6020. }
  6021. $pic_prompt = getProp($product, 'pic_prompt');
  6022. if ($pic_prompt) {
  6023. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6024. }
  6025. // 检查参考图是否是正确的图片格式
  6026. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6027. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6028. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6029. if (!in_array($extension, $allowedExtensions)) {
  6030. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6031. }
  6032. // 处理图片模型
  6033. $model = getProp($data, 'model');
  6034. if (!$model) {
  6035. // 使用默认模型
  6036. $model = 'doubao-seedream-5-0-lite-260128';
  6037. }
  6038. // 验证模型是否在可用模型表中
  6039. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6040. Utils::throwError('20003:该模型已不可用,请更换!');
  6041. }
  6042. $ratio = getProp($data, 'ratio', '16:9');
  6043. $resolution = getProp($data, 'resolution', '2k');
  6044. // 定义分辨率和宽高比对应的尺寸映射表
  6045. $sizeMap = [
  6046. '2k' => [
  6047. '1:1' => ['width' => 2048, 'height' => 2048],
  6048. '4:3' => ['width' => 2304, 'height' => 1728],
  6049. '3:4' => ['width' => 1728, 'height' => 2304],
  6050. '16:9' => ['width' => 2848, 'height' => 1600],
  6051. '9:16' => ['width' => 1600, 'height' => 2848],
  6052. '3:2' => ['width' => 2496, 'height' => 1664],
  6053. '2:3' => ['width' => 1664, 'height' => 2496],
  6054. '21:9' => ['width' => 3136, 'height' => 1344],
  6055. ],
  6056. '3k' => [
  6057. '1:1' => ['width' => 3072, 'height' => 3072],
  6058. '4:3' => ['width' => 3456, 'height' => 2592],
  6059. '3:4' => ['width' => 2592, 'height' => 3456],
  6060. '16:9' => ['width' => 4096, 'height' => 2304],
  6061. '9:16' => ['width' => 2304, 'height' => 4096],
  6062. '2:3' => ['width' => 2496, 'height' => 3744],
  6063. '3:2' => ['width' => 3744, 'height' => 2496],
  6064. '21:9' => ['width' => 4704, 'height' => 2016],
  6065. ],
  6066. '4k' => [
  6067. '1:1' => ['width' => 4096, 'height' => 4096],
  6068. '3:4' => ['width' => 3520, 'height' => 4704],
  6069. '4:3' => ['width' => 4704, 'height' => 3520],
  6070. '16:9' => ['width' => 5504, 'height' => 3040],
  6071. '9:16' => ['width' => 3040, 'height' => 5504],
  6072. '2:3' => ['width' => 3328, 'height' => 4992],
  6073. '3:2' => ['width' => 4992, 'height' => 3328],
  6074. '21:9' => ['width' => 6240, 'height' => 2656],
  6075. ],
  6076. ];
  6077. // 参数验证
  6078. $resolution = strtolower($resolution);
  6079. if (!isset($sizeMap[$resolution])) {
  6080. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6081. }
  6082. if (!isset($sizeMap[$resolution][$ratio])) {
  6083. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6084. }
  6085. // 根据 ratio 和 resolution 确定宽高
  6086. $width = $sizeMap[$resolution][$ratio]['width'];
  6087. $height = $sizeMap[$resolution][$ratio]['height'];
  6088. try {
  6089. // 创建图片生成任务
  6090. $params = [
  6091. 'prompt' => $prompt,
  6092. 'model' => $model,
  6093. 'ref_img_urls' => [$ref_img_url],
  6094. 'width' => $width,
  6095. 'height' => $height
  6096. ];
  6097. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6098. $task_id = $task->id;
  6099. if (!$task_id) {
  6100. Utils::throwError('20003:创建图片生成任务失败');
  6101. }
  6102. // 轮询获取结果
  6103. // 只查询数据库,不调用API,不更新任务表
  6104. $start_time = time();
  6105. $timeout = 1800;
  6106. $img_url = '';
  6107. while (time() - $start_time < $timeout) {
  6108. sleep(5);
  6109. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6110. $task = DB::table('mp_generate_pic_tasks')
  6111. ->where('id', $task_id)
  6112. ->first();
  6113. if (!$task) {
  6114. Utils::throwError('20003:任务不存在');
  6115. }
  6116. if ($task->status === 'success' && $task->result_url) {
  6117. $result_urls = is_string($task->result_url)
  6118. ? json_decode($task->result_url, true)
  6119. : $task->result_url;
  6120. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6121. break;
  6122. } elseif ($task->status === 'failed') {
  6123. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6124. }
  6125. // 其他状态继续轮询
  6126. }
  6127. if (empty($img_url)) {
  6128. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6129. }
  6130. // 更新 mp_products 表(不是任务表)
  6131. DB::table('mp_products')
  6132. ->where('id', $id)
  6133. ->where('cpid', $cpid)
  6134. ->update([
  6135. 'three_view_image_url' => $img_url,
  6136. 'updated_at' => date('Y-m-d H:i:s')
  6137. ]);
  6138. return ['three_view_image_url' => $img_url];
  6139. } catch (\Exception $e) {
  6140. dLog('anime')->error('生成三视图失败', [
  6141. 'error' => $e->getMessage()
  6142. ]);
  6143. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6144. Utils::throwError('20003:' . $e->getMessage());
  6145. }
  6146. }
  6147. /**
  6148. * 推送(复制)资产或文件夹到目标位置
  6149. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6150. * @return array 返回推送结果
  6151. */
  6152. public function pushProductOrFolder($data) {
  6153. $uid = Site::getUid();
  6154. $cpid = Site::getCpid();
  6155. $role = Site::getRole();
  6156. $product_id = getProp($data, 'product_id');
  6157. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6158. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6159. if (!$product_id) {
  6160. Utils::throwError('20003:请选择要推送的项目');
  6161. }
  6162. // 查询源项目(只通过cpid查询,不限制user_id)
  6163. $sourceItem = DB::table('mp_products')
  6164. ->where('id', $product_id)
  6165. ->where('cpid', $cpid)
  6166. ->where('is_deleted', 0)
  6167. ->first();
  6168. if (!$sourceItem) {
  6169. Utils::throwError('20003:要推送的项目不存在');
  6170. }
  6171. // 通过user_id判断源是公共库还是个人库
  6172. $source_uid = $sourceItem->user_id;
  6173. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6174. // 验证目标文件夹并确定目标是公共库还是个人库
  6175. $target_level = 0;
  6176. $target_uid = $uid; // 默认推送到个人库
  6177. $target_is_public = 0;
  6178. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6179. if ($target_parent_id > 0) {
  6180. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6181. $targetParent = DB::table('mp_products')
  6182. ->where('id', $target_parent_id)
  6183. ->where('cpid', $cpid)
  6184. ->where('type', 2)
  6185. ->where('is_deleted', 0)
  6186. ->first();
  6187. if (!$targetParent) {
  6188. Utils::throwError('20003:目标文件夹不存在');
  6189. }
  6190. // 通过user_id判断目标是公共库还是个人库
  6191. $target_level = $targetParent->level;
  6192. $target_uid = $targetParent->user_id;
  6193. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6194. // 使用目标文件夹的 product 类型
  6195. $final_product_type = $targetParent->product;
  6196. }
  6197. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6198. else {
  6199. $push_to_public = getProp($data, 'push_to_public');
  6200. if ($push_to_public === '') {
  6201. Utils::throwError('20003:请选择是否推送到公共库');
  6202. }
  6203. if ($push_to_public) {
  6204. $target_uid = 0;
  6205. $target_is_public = 1;
  6206. }
  6207. // 推送到根目录时,必须指定 product 类型
  6208. if ($target_product === null || $target_product === '') {
  6209. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6210. }
  6211. $final_product_type = $target_product;
  6212. }
  6213. // 如果目标是公共库,需要admin权限
  6214. if ($target_is_public && $role !== 'admin') {
  6215. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6216. }
  6217. // 权限验证:验证是否符合允许的推送规则
  6218. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6219. try {
  6220. DB::beginTransaction();
  6221. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6222. if ($sourceItem->type == 1) {
  6223. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6224. DB::commit();
  6225. return [
  6226. 'product_id' => $newId,
  6227. ];
  6228. }
  6229. // 如果是文件夹,递归复制(支持跨类型推送)
  6230. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6231. DB::commit();
  6232. return [
  6233. 'product_id' => $newFolderId,
  6234. ];
  6235. } catch (\Exception $e) {
  6236. DB::rollBack();
  6237. dLog('anime')->error('推送失败', [
  6238. 'error' => $e->getMessage(),
  6239. 'product_id' => $product_id
  6240. ]);
  6241. Utils::throwError('20003:' . $e->getMessage());
  6242. }
  6243. }
  6244. /**
  6245. * 验证推送权限
  6246. * 允许的推送规则:
  6247. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6248. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6249. * 3. 公共库推送给公共库(公共库 → 公共库)
  6250. *
  6251. * @param int $source_uid 源的user_id
  6252. * @param int $target_uid 目标的user_id
  6253. * @param int $current_uid 当前用户ID
  6254. * @throws \Exception
  6255. */
  6256. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6257. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6258. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6259. return; // 允许
  6260. }
  6261. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6262. if ($source_uid == 0 && $target_uid == $current_uid) {
  6263. return; // 允许
  6264. }
  6265. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6266. if ($source_uid == 0 && $target_uid == 0) {
  6267. return; // 允许
  6268. }
  6269. // 其他情况都不允许
  6270. if ($source_uid != 0 && $source_uid != $current_uid) {
  6271. // 源是别人的个人库
  6272. Utils::throwError('20003:无权限访问该资产');
  6273. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6274. // 个人库推送给公共库(不允许)
  6275. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6276. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6277. // 不同用户的个人库之间推送(不允许)
  6278. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6279. } else {
  6280. // 其他未知情况
  6281. Utils::throwError('20003:不允许的推送操作');
  6282. }
  6283. }
  6284. /**
  6285. * 复制单个资产
  6286. * @param object $sourceProduct 源资产对象
  6287. * @param int $targetParentId 目标父文件夹ID
  6288. * @param int $targetLevel 目标层级
  6289. * @param int $cpid 公司ID
  6290. * @param int $targetUid 目标用户ID
  6291. * @return int 返回新资产ID
  6292. */
  6293. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6294. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6295. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6296. $newProductData = [
  6297. 'user_id' => $targetUid,
  6298. 'cpid' => $cpid,
  6299. 'type' => 1,
  6300. 'parent_id' => $targetParentId,
  6301. 'level' => $targetLevel,
  6302. 'product_name' => $sourceProduct->product_name,
  6303. 'url' => $sourceProduct->url,
  6304. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6305. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6306. 'product' => $finalProductType,
  6307. 'versions' => $sourceProduct->versions ?? '',
  6308. 'sort_order' => time(),
  6309. 'is_deleted' => 0,
  6310. 'created_at' => date('Y-m-d H:i:s'),
  6311. 'updated_at' => date('Y-m-d H:i:s')
  6312. ];
  6313. return DB::table('mp_products')->insertGetId($newProductData);
  6314. }
  6315. /**
  6316. * 递归复制文件夹及其子项
  6317. * @param object $sourceFolder 源文件夹对象
  6318. * @param int $targetParentId 目标父文件夹ID
  6319. * @param int $targetLevel 目标层级
  6320. * @param int $cpid 公司ID
  6321. * @param int $targetUid 目标用户ID
  6322. * @param int $sourceUid 源用户ID
  6323. * @return int 返回新文件夹ID
  6324. */
  6325. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6326. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6327. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6328. // 创建新文件夹
  6329. $newFolderData = [
  6330. 'user_id' => $targetUid,
  6331. 'cpid' => $cpid,
  6332. 'type' => 2,
  6333. 'parent_id' => $targetParentId,
  6334. 'level' => $targetLevel,
  6335. 'product_name' => $sourceFolder->product_name,
  6336. 'product' => $finalProductType,
  6337. 'sort_order' => time(),
  6338. 'is_deleted' => 0,
  6339. 'created_at' => date('Y-m-d H:i:s'),
  6340. 'updated_at' => date('Y-m-d H:i:s')
  6341. ];
  6342. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6343. // 获取源文件夹下的所有子项
  6344. $children = DB::table('mp_products')
  6345. ->where('parent_id', $sourceFolder->id)
  6346. ->where('cpid', $cpid)
  6347. ->where('user_id', $sourceUid)
  6348. ->where('is_deleted', 0)
  6349. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6350. ->get();
  6351. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6352. foreach ($children as $child) {
  6353. if ($child->type == 1) {
  6354. // 资产
  6355. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6356. } else {
  6357. // 文件夹
  6358. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6359. }
  6360. }
  6361. return $newFolderId;
  6362. }
  6363. /**
  6364. * 保存剧本资产关联关系
  6365. * @param array $data 请求参数
  6366. * @return bool
  6367. */
  6368. public function saveScriptProducts($data) {
  6369. $uid = Site::getUid();
  6370. $cpid = Site::getCpid();
  6371. $script_id = getProp($data, 'script_id');
  6372. $products = getProp($data, 'products', []);
  6373. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6374. if (!$script_id) {
  6375. Utils::throwError('20003:请提供剧本ID');
  6376. }
  6377. // 验证剧本是否存在
  6378. $script = DB::table('mp_scripts')
  6379. ->where('id', $script_id)
  6380. ->where('is_deleted', 0)
  6381. ->first();
  6382. if (!$script) {
  6383. Utils::throwError('20003:剧本不存在');
  6384. }
  6385. // 处理图片模型
  6386. $model = getProp($data, 'model');
  6387. if (!$model) {
  6388. // 使用默认模型
  6389. $model = 'doubao-seedream-5-0-lite-260128';
  6390. }
  6391. // 验证模型是否在可用模型表中
  6392. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6393. Utils::throwError('20003:该模型已不可用,请更换!');
  6394. }
  6395. $ratio = getProp($data, 'ratio', '9:16');
  6396. $resolution = getProp($data, 'resolution', '2k');
  6397. // 定义分辨率和宽高比对应的尺寸映射表
  6398. $sizeMap = [
  6399. '2k' => [
  6400. '1:1' => ['width' => 2048, 'height' => 2048],
  6401. '4:3' => ['width' => 2304, 'height' => 1728],
  6402. '3:4' => ['width' => 1728, 'height' => 2304],
  6403. '16:9' => ['width' => 2848, 'height' => 1600],
  6404. '9:16' => ['width' => 1600, 'height' => 2848],
  6405. '3:2' => ['width' => 2496, 'height' => 1664],
  6406. '2:3' => ['width' => 1664, 'height' => 2496],
  6407. '21:9' => ['width' => 3136, 'height' => 1344],
  6408. ],
  6409. '3k' => [
  6410. '1:1' => ['width' => 3072, 'height' => 3072],
  6411. '4:3' => ['width' => 3456, 'height' => 2592],
  6412. '3:4' => ['width' => 2592, 'height' => 3456],
  6413. '16:9' => ['width' => 4096, 'height' => 2304],
  6414. '9:16' => ['width' => 2304, 'height' => 4096],
  6415. '2:3' => ['width' => 2496, 'height' => 3744],
  6416. '3:2' => ['width' => 3744, 'height' => 2496],
  6417. '21:9' => ['width' => 4704, 'height' => 2016],
  6418. ],
  6419. '4k' => [
  6420. '1:1' => ['width' => 4096, 'height' => 4096],
  6421. '3:4' => ['width' => 3520, 'height' => 4704],
  6422. '4:3' => ['width' => 4704, 'height' => 3520],
  6423. '16:9' => ['width' => 5504, 'height' => 3040],
  6424. '9:16' => ['width' => 3040, 'height' => 5504],
  6425. '2:3' => ['width' => 3328, 'height' => 4992],
  6426. '3:2' => ['width' => 4992, 'height' => 3328],
  6427. '21:9' => ['width' => 6240, 'height' => 2656],
  6428. ],
  6429. ];
  6430. // 参数验证
  6431. $resolution = strtolower($resolution);
  6432. if (!isset($sizeMap[$resolution])) {
  6433. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6434. }
  6435. if (!isset($sizeMap[$resolution][$ratio])) {
  6436. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6437. }
  6438. // 根据 ratio 和 resolution 确定宽高
  6439. $width = $sizeMap[$resolution][$ratio]['width'];
  6440. $height = $sizeMap[$resolution][$ratio]['height'];
  6441. $script_name = $script->script_name ?? 'script_' . $script_id;
  6442. // 检查是否已经有该剧本的资产数据
  6443. $existingMappings = DB::table('mp_script_product_mappings')
  6444. ->where('script_id', $script_id)
  6445. ->get();
  6446. if ($existingMappings->isNotEmpty()) {
  6447. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6448. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6449. // 查询这些资产的图片生成任务状态
  6450. $productsWithTasks = DB::table('mp_products')
  6451. ->whereIn('id', $productIds)
  6452. ->where('is_deleted', 0)
  6453. ->get();
  6454. $productTaskMap = [];
  6455. $typeFolderIds = [];
  6456. $hasAllTasks = true;
  6457. foreach ($productsWithTasks as $product) {
  6458. // 收集类型文件夹ID
  6459. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6460. $parentFolder = DB::table('mp_products')
  6461. ->where('id', $product->parent_id)
  6462. ->where('type', 2)
  6463. ->first();
  6464. if ($parentFolder) {
  6465. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6466. }
  6467. }
  6468. // 检查是否有图片生成任务
  6469. if (!empty($product->pic_task_id)) {
  6470. $productTaskMap[$product->id] = $product->pic_task_id;
  6471. } else if($product->url && $product->pic_task_status == '生成成功') {
  6472. continue;
  6473. } else {
  6474. // 有资产没有图片任务
  6475. $hasAllTasks = false;
  6476. }
  6477. }
  6478. // 如果所有资产都有任务ID,直接轮询返回结果
  6479. if ($hasAllTasks && !empty($productTaskMap)) {
  6480. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6481. 'script_id' => $script_id,
  6482. 'script_name' => $script_name,
  6483. 'product_count' => count($productTaskMap)
  6484. ]);
  6485. // 直接返回 SSE 流轮询结果
  6486. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6487. }
  6488. // 如果部分资产没有任务ID,只为这些资产创建任务
  6489. if (!$hasAllTasks && $auto_generate_images) {
  6490. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6491. 'script_id' => $script_id,
  6492. 'script_name' => $script_name
  6493. ]);
  6494. // 开启事务
  6495. DB::beginTransaction();
  6496. try {
  6497. foreach ($productsWithTasks as $product) {
  6498. // 跳过已有任务的资产
  6499. if (!empty($product->pic_task_id)) {
  6500. continue;
  6501. }
  6502. // 跳过没有提示词的资产
  6503. if (empty($product->pic_prompt)) {
  6504. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6505. 'product_id' => $product->id,
  6506. 'product_name' => $product->product_name
  6507. ]);
  6508. continue;
  6509. }
  6510. try {
  6511. // 创建图片生成任务
  6512. $params = [
  6513. 'prompt' => $product->pic_prompt,
  6514. 'model' => $model,
  6515. 'ref_img_urls' => [],
  6516. 'width' => $width,
  6517. 'height' => $height
  6518. ];
  6519. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6520. $task_id = $task->id;
  6521. if ($task_id) {
  6522. $productTaskMap[$product->id] = $task_id;
  6523. // 在事务中更新资产表的任务ID和状态
  6524. DB::table('mp_products')
  6525. ->where('id', $product->id)
  6526. ->update([
  6527. 'pic_task_id' => $task_id,
  6528. 'pic_task_status' => '生成中',
  6529. 'updated_at' => now()
  6530. ]);
  6531. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6532. 'product_id' => $product->id,
  6533. 'task_id' => $task_id
  6534. ]);
  6535. }
  6536. } catch (\Exception $e) {
  6537. dLog('anime')->error('创建资产图片生成任务失败', [
  6538. 'product_id' => $product->id,
  6539. 'error' => $e->getMessage()
  6540. ]);
  6541. // 标记为失败(仍在事务中)
  6542. DB::table('mp_products')
  6543. ->where('id', $product->id)
  6544. ->update([
  6545. 'pic_task_status' => '生成失败',
  6546. 'updated_at' => now()
  6547. ]);
  6548. }
  6549. }
  6550. // 提交事务
  6551. DB::commit();
  6552. // 如果有新创建的任务,返回 SSE 流
  6553. if (!empty($productTaskMap)) {
  6554. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6555. }
  6556. } catch (\Exception $e) {
  6557. // 回滚事务
  6558. DB::rollback();
  6559. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6560. 'script_id' => $script_id,
  6561. 'error' => $e->getMessage()
  6562. ]);
  6563. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6564. }
  6565. }
  6566. // 如果不需要生成图片,返回已存在的信息
  6567. return [
  6568. 'success' => true,
  6569. 'message' => '剧本资产已存在',
  6570. 'script_id' => $script_id,
  6571. 'script_name' => $script_name,
  6572. 'type_folder_ids' => $typeFolderIds,
  6573. 'existing_products' => count($productIds),
  6574. 'tasks_count' => count($productTaskMap)
  6575. ];
  6576. }
  6577. // 解析 products(可能是 JSON 字符串或数组)
  6578. if (is_string($products)) {
  6579. $products = json_decode($products, true);
  6580. if (json_last_error() !== JSON_ERROR_NONE) {
  6581. Utils::throwError('20003:产品数据格式错误');
  6582. }
  6583. }
  6584. if (!is_array($products) || empty($products)) {
  6585. Utils::throwError('20003:产品数据不能为空');
  6586. }
  6587. // 以下是原有的创建逻辑...
  6588. // 开启事务
  6589. DB::beginTransaction();
  6590. try {
  6591. $now = now();
  6592. $mappingRecords = [];
  6593. $createdProductIds = []; // 记录所有创建的资产ID
  6594. // 获取剧本名称
  6595. $script_name = $script->script_name ?? 'script_' . $script_id;
  6596. // 存储每个类型的根文件夹ID
  6597. $typeFolderIds = [];
  6598. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6599. foreach ($products as $productGroup) {
  6600. $type = getProp($productGroup, 'type');
  6601. $title = getProp($productGroup, 'title', '');
  6602. $content = getProp($productGroup, 'content', []);
  6603. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6604. continue;
  6605. }
  6606. // 为当前类型创建根文件夹(如果还未创建)
  6607. if (!isset($typeFolderIds[$type])) {
  6608. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6609. 'user_id' => $uid,
  6610. 'cpid' => $cpid,
  6611. 'type' => 2, // 1.资产 2文件夹
  6612. 'product' => $type, // 1.主体 2.场景 3.道具
  6613. 'parent_id' => 0, // 根文件夹,parent_id=0
  6614. 'level' => 1, // 第一层级
  6615. 'product_name' => $script_name,
  6616. 'sort_order' => time() + $type,
  6617. 'is_deleted' => 0,
  6618. 'created_at' => $now,
  6619. 'updated_at' => $now
  6620. ]);
  6621. }
  6622. $folder_id = $typeFolderIds[$type];
  6623. // 获取表头(第一行)并查找关键列的位置
  6624. $headers = $content[0];
  6625. $nameColumnIndex = -1; // 资产名称列索引
  6626. $sequenceColumnIndex = -1; // 使用范围列索引
  6627. $promptColumnIndex = -1; // 参考提示词列索引
  6628. foreach ($headers as $index => $header) {
  6629. // 查找"资产名称"列
  6630. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6631. $nameColumnIndex = $index;
  6632. }
  6633. // 查找"使用范围"列
  6634. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6635. $sequenceColumnIndex = $index;
  6636. }
  6637. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6638. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6639. $promptColumnIndex = $index;
  6640. }
  6641. }
  6642. // 验证必要的列是否都找到了
  6643. if ($nameColumnIndex === -1) {
  6644. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6645. continue;
  6646. }
  6647. if ($sequenceColumnIndex === -1) {
  6648. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6649. continue;
  6650. }
  6651. // 跳过表头,解析每一行数据
  6652. for ($i = 1; $i < count($content); $i++) {
  6653. $row = $content[$i];
  6654. // 确保行数据有效
  6655. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6656. continue;
  6657. }
  6658. // 根据动态查找的列索引提取数据
  6659. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6660. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6661. $pic_prompt = '';
  6662. // 提取参考提示词(如果找到了该列)
  6663. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6664. $pic_prompt = trim($row[$promptColumnIndex]);
  6665. }
  6666. // 解析使用范围(逗号分隔的序号)
  6667. $sequences = [];
  6668. if (!empty($sequence_str)) {
  6669. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6670. foreach ($sequenceParts as $part) {
  6671. if (is_numeric($part)) {
  6672. $sequences[] = (int)$part;
  6673. }
  6674. }
  6675. }
  6676. if (empty($product_name)) {
  6677. continue;
  6678. }
  6679. // 处理product_name两边的符号
  6680. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6681. // 如果名称不存在则跳过
  6682. if (!$product_name) continue;
  6683. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6684. $product_id = DB::table('mp_products')->insertGetId([
  6685. 'product_name' => $product_name,
  6686. 'type' => 1, // 1=资产 2.文件夹
  6687. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6688. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6689. 'level' => 2, // 第二层级
  6690. 'pic_prompt' => $pic_prompt,
  6691. 'user_id' => $uid,
  6692. 'cpid' => $cpid,
  6693. 'sort_order' => time(),
  6694. 'is_deleted' => 0,
  6695. 'created_at' => $now,
  6696. 'updated_at' => $now,
  6697. ]);
  6698. // 记录创建的资产ID
  6699. $createdProductIds[] = $product_id;
  6700. // 为每个序号创建映射记录
  6701. if (!empty($sequences)) {
  6702. foreach ($sequences as $sequence) {
  6703. $mappingRecords[] = [
  6704. 'script_id' => $script_id,
  6705. 'product_id' => $product_id,
  6706. 'episode_number' => $sequence,
  6707. 'created_at' => $now,
  6708. 'updated_at' => $now,
  6709. ];
  6710. }
  6711. } else {
  6712. // 如果没有指定序号,创建一个默认映射(序号为0)
  6713. $mappingRecords[] = [
  6714. 'script_id' => $script_id,
  6715. 'product_id' => $product_id,
  6716. 'episode_number' => 0,
  6717. 'created_at' => $now,
  6718. 'updated_at' => $now,
  6719. ];
  6720. }
  6721. }
  6722. }
  6723. if (empty($mappingRecords)) {
  6724. Utils::throwError('20003:没有有效的产品数据');
  6725. }
  6726. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6727. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6728. // 如果需要自动生成图片,在事务中创建图片生成任务
  6729. $productTaskMap = [];
  6730. if ($auto_generate_images && !empty($createdProductIds)) {
  6731. // 查询所有创建的资产
  6732. $productsToGenerate = DB::table('mp_products')
  6733. ->whereIn('id', $createdProductIds)
  6734. ->where('is_deleted', 0)
  6735. ->get();
  6736. foreach ($productsToGenerate as $product) {
  6737. if (empty($product->pic_prompt)) {
  6738. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6739. 'product_id' => $product->id,
  6740. 'product_name' => $product->product_name
  6741. ]);
  6742. continue;
  6743. }
  6744. try {
  6745. // 创建图片生成任务
  6746. $params = [
  6747. 'prompt' => $product->pic_prompt,
  6748. 'model' => $model,
  6749. 'ref_img_urls' => [],
  6750. 'width' => $width,
  6751. 'height' => $height
  6752. ];
  6753. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6754. $task_id = $task->id;
  6755. if ($task_id) {
  6756. $productTaskMap[$product->id] = $task_id;
  6757. // 在事务中更新资产表的任务ID和状态
  6758. DB::table('mp_products')
  6759. ->where('id', $product->id)
  6760. ->update([
  6761. 'pic_task_id' => $task_id,
  6762. 'pic_task_status' => '生成中',
  6763. 'updated_at' => now()
  6764. ]);
  6765. dLog('anime')->info('创建资产图片生成任务', [
  6766. 'product_id' => $product->id,
  6767. 'task_id' => $task_id
  6768. ]);
  6769. }
  6770. } catch (\Exception $e) {
  6771. dLog('anime')->error('创建资产图片生成任务失败', [
  6772. 'product_id' => $product->id,
  6773. 'error' => $e->getMessage()
  6774. ]);
  6775. // 标记为失败(仍在事务中)
  6776. DB::table('mp_products')
  6777. ->where('id', $product->id)
  6778. ->update([
  6779. 'pic_task_status' => '生成失败',
  6780. 'updated_at' => now()
  6781. ]);
  6782. }
  6783. }
  6784. }
  6785. // 提交事务
  6786. DB::commit();
  6787. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6788. if ($auto_generate_images && !empty($productTaskMap)) {
  6789. // 返回 SSE 流(事务外轮询)
  6790. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6791. }
  6792. // 如果不需要生成图片,返回普通结果
  6793. return [
  6794. 'success' => true,
  6795. 'type_folder_ids' => $typeFolderIds,
  6796. 'inserted_count' => $insertedCount,
  6797. 'total_records' => count($mappingRecords),
  6798. 'created_products' => count($createdProductIds),
  6799. 'image_tasks_created' => count($productTaskMap)
  6800. ];
  6801. } catch (\Exception $e) {
  6802. // 回滚事务
  6803. DB::rollback();
  6804. // 记录错误日志
  6805. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6806. 'script_id' => $script_id,
  6807. 'error' => $e->getMessage(),
  6808. 'trace' => $e->getTraceAsString()
  6809. ]);
  6810. // 统一使用 Utils::throwError 抛出错误
  6811. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6812. }
  6813. }
  6814. /**
  6815. * 批量为剧本资产生成图片
  6816. *
  6817. * @param array $data 请求参数
  6818. * @return \Generator 返回 SSE 流
  6819. */
  6820. public function batchGenerateProductImages($data) {
  6821. $script_id = getProp($data, 'script_id');
  6822. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6823. if (!$script_id) {
  6824. Utils::throwError('20003:请提供剧本ID');
  6825. }
  6826. // 验证剧本是否存在
  6827. $script = DB::table('mp_scripts')
  6828. ->where('id', $script_id)
  6829. ->where('is_deleted', 0)
  6830. ->first();
  6831. if (!$script) {
  6832. Utils::throwError('20003:剧本不存在');
  6833. }
  6834. $script_name = $script->script_name ?? 'script_' . $script_id;
  6835. // 获取需要生成图片的所有资产
  6836. $products = DB::table('mp_products')
  6837. ->whereIn('parent_id', array_values($type_folder_ids))
  6838. ->where('is_deleted', 0)
  6839. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6840. ->get();
  6841. if ($products->isEmpty()) {
  6842. Utils::throwError('20003:没有找到需要生成图片的资产');
  6843. }
  6844. // 默认参数
  6845. $model = 'doubao-seedream-5-0-lite-260128';
  6846. $width = 1600;
  6847. $height = 2848;
  6848. // 开始为每个资产创建图片生成任务
  6849. $taskIds = [];
  6850. $productTaskMap = []; // 资产ID到任务ID的映射
  6851. foreach ($products as $product) {
  6852. if (empty($product->pic_prompt)) {
  6853. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6854. continue;
  6855. }
  6856. try {
  6857. // 创建图片生成任务
  6858. $params = [
  6859. 'prompt' => $product->pic_prompt,
  6860. 'model' => $model,
  6861. 'ref_img_urls' => [],
  6862. 'width' => $width,
  6863. 'height' => $height
  6864. ];
  6865. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6866. $task_id = $task->id;
  6867. if ($task_id) {
  6868. $taskIds[] = $task_id;
  6869. $productTaskMap[$product->id] = $task_id;
  6870. // 更新资产表的任务ID和状态
  6871. DB::table('mp_products')
  6872. ->where('id', $product->id)
  6873. ->update([
  6874. 'pic_task_id' => $task_id,
  6875. 'pic_task_status' => '生成中',
  6876. 'updated_at' => now()
  6877. ]);
  6878. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6879. }
  6880. } catch (\Exception $e) {
  6881. dLog('anime')->error('创建资产图片生成任务失败', [
  6882. 'product_id' => $product->id,
  6883. 'error' => $e->getMessage()
  6884. ]);
  6885. // 标记为失败
  6886. DB::table('mp_products')
  6887. ->where('id', $product->id)
  6888. ->update([
  6889. 'pic_task_status' => '生成失败',
  6890. 'updated_at' => now()
  6891. ]);
  6892. }
  6893. }
  6894. if (empty($taskIds)) {
  6895. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6896. }
  6897. // 返回 SSE 流
  6898. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6899. }
  6900. /**
  6901. * 轮询资产图片生成任务状态(SSE流式返回)
  6902. * 只通过查询数据库获取任务状态,不主动调用API
  6903. *
  6904. * @param int $script_id 剧本ID
  6905. * @param string $script_name 剧本名称
  6906. * @param array $productTaskMap 资产ID到任务ID的映射
  6907. * @param array $type_folder_ids 类型文件夹ID映射
  6908. * @return \Generator
  6909. */
  6910. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6911. $startTime = time();
  6912. $timeout = 1800; // 30分钟超时
  6913. $pollInterval = 10; // 10秒轮询一次
  6914. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6915. // 定义类型名称映射
  6916. $typeNames = [
  6917. 1 => 'roles', // 角色
  6918. 2 => 'scenes', // 场景
  6919. 3 => 'props' // 道具
  6920. ];
  6921. while (time() - $startTime < $timeout) {
  6922. sleep($pollInterval);
  6923. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6924. $mappings = DB::table('mp_script_product_mappings')
  6925. ->where('script_id', $script_id)
  6926. ->pluck('product_id')
  6927. ->unique()
  6928. ->toArray();
  6929. if (empty($mappings)) {
  6930. dLog('anime')->warning('该剧本没有关联的资产', [
  6931. 'script_id' => $script_id,
  6932. 'script_name' => $script_name
  6933. ]);
  6934. break;
  6935. }
  6936. // 查询所有资产的当前状态
  6937. $products = DB::table('mp_products')
  6938. ->whereIn('id', $mappings)
  6939. ->where('is_deleted', 0)
  6940. ->get();
  6941. // 统计各类型的状态(使用类型名称作为键名)
  6942. $stats = [
  6943. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6944. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6945. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6946. ];
  6947. $allCompleted = true;
  6948. $hasStatusChange = false;
  6949. foreach ($products as $product) {
  6950. $type = $product->product;
  6951. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6952. // 如果类型名称不在 stats 中,初始化
  6953. if (!isset($stats[$typeName])) {
  6954. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6955. }
  6956. $stats[$typeName]['total']++;
  6957. $task_id = $product->pic_task_id;
  6958. $currentStatus = $product->pic_task_status;
  6959. // 检查状态是否有变化
  6960. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6961. $hasStatusChange = true;
  6962. $lastStatus[$product->id] = $currentStatus;
  6963. }
  6964. // 如果是生成中,查询任务表状态
  6965. if ($currentStatus === '生成中' && $task_id) {
  6966. // 只查询数据库,不调用API
  6967. $task = DB::table('mp_generate_pic_tasks')
  6968. ->where('id', $task_id)
  6969. ->first();
  6970. if ($task) {
  6971. // 检查任务状态
  6972. if ($task->status === 'success' && $task->result_url) {
  6973. // 解析图片URL
  6974. $result_urls = $task->result_url;
  6975. if (is_string($result_urls)) {
  6976. $result_urls = json_decode($result_urls, true);
  6977. }
  6978. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6979. // 更新资产表状态
  6980. DB::table('mp_products')
  6981. ->where('id', $product->id)
  6982. ->update([
  6983. 'pic_task_status' => '生成成功',
  6984. 'url' => $img_url,
  6985. 'updated_at' => now()
  6986. ]);
  6987. $stats[$typeName]['success']++;
  6988. $stats[$typeName]['completed']++;
  6989. $hasStatusChange = true;
  6990. dLog('anime')->info('资产图片生成成功', [
  6991. 'product_id' => $product->id,
  6992. 'task_id' => $task_id,
  6993. 'img_url' => $img_url
  6994. ]);
  6995. } elseif ($task->status === 'failed') {
  6996. // 更新资产表状态
  6997. DB::table('mp_products')
  6998. ->where('id', $product->id)
  6999. ->update([
  7000. 'pic_task_status' => '生成失败',
  7001. 'updated_at' => now()
  7002. ]);
  7003. $stats[$typeName]['completed']++;
  7004. $hasStatusChange = true;
  7005. dLog('anime')->warning('资产图片生成失败', [
  7006. 'product_id' => $product->id,
  7007. 'task_id' => $task_id,
  7008. 'error' => $task->error_message ?? '未知错误'
  7009. ]);
  7010. } else {
  7011. // 任务还在处理中
  7012. $allCompleted = false;
  7013. }
  7014. } else {
  7015. // 任务不存在,标记为失败
  7016. DB::table('mp_products')
  7017. ->where('id', $product->id)
  7018. ->update([
  7019. 'pic_task_status' => '生成失败',
  7020. 'updated_at' => now()
  7021. ]);
  7022. $stats[$type]['completed']++;
  7023. $hasStatusChange = true;
  7024. dLog('anime')->error('图片生成任务不存在', [
  7025. 'product_id' => $product->id,
  7026. 'task_id' => $task_id
  7027. ]);
  7028. }
  7029. } elseif ($currentStatus === '生成成功') {
  7030. $stats[$typeName]['success']++;
  7031. $stats[$typeName]['completed']++;
  7032. } elseif ($currentStatus === '生成失败') {
  7033. $stats[$typeName]['completed']++;
  7034. } else {
  7035. // 其他状态也认为未完成
  7036. $allCompleted = false;
  7037. }
  7038. }
  7039. // 移除没有数据的类型(total=0)
  7040. foreach ($stats as $typeName => $stat) {
  7041. if ($stat['total'] === 0) {
  7042. unset($stats[$typeName]);
  7043. }
  7044. }
  7045. // 如果有状态变化,发送 SSE 更新
  7046. if ($hasStatusChange) {
  7047. $eventType = $allCompleted ? 'complete' : 'update';
  7048. $response = [
  7049. 'type' => $eventType,
  7050. 'script_id' => $script_id,
  7051. 'script_name' => $script_name,
  7052. 'stats' => $stats,
  7053. 'timestamp' => date('Y-m-d H:i:s')
  7054. ];
  7055. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7056. dLog('anime')->info('SSE更新', [
  7057. 'event_type' => $eventType,
  7058. 'script_id' => $script_id,
  7059. 'script_name' => $script_name,
  7060. 'stats' => $stats
  7061. ]);
  7062. if ($allCompleted) {
  7063. dLog('anime')->info('所有资产图片生成任务已完成', [
  7064. 'script_id' => $script_id,
  7065. 'script_name' => $script_name,
  7066. 'stats' => $stats
  7067. ]);
  7068. break;
  7069. }
  7070. }
  7071. }
  7072. // 超时处理
  7073. if (time() - $startTime >= $timeout && !$allCompleted) {
  7074. $response = [
  7075. 'type' => 'timeout',
  7076. 'message' => '部分任务超时,请稍后查看结果',
  7077. 'script_id' => $script_id,
  7078. 'script_name' => $script_name,
  7079. 'timestamp' => date('Y-m-d H:i:s')
  7080. ];
  7081. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7082. dLog('anime')->warning('资产图片生成任务超时', [
  7083. 'script_id' => $script_id,
  7084. 'script_name' => $script_name,
  7085. 'timeout' => $timeout
  7086. ]);
  7087. }
  7088. }
  7089. /**
  7090. * 获取剧本关联的资产列表
  7091. * @param array $data 请求参数
  7092. * @return array
  7093. */
  7094. public function getScriptProducts($data) {
  7095. $uid = Site::getUid();
  7096. $cpid = Site::getCpid();
  7097. $script_id = getProp($data, 'script_id');
  7098. $episode_number = getProp($data, 'episode_number');
  7099. if (!$script_id) {
  7100. Utils::throwError('20003:请提供剧本ID');
  7101. }
  7102. // 验证剧本是否存在
  7103. $script = DB::table('mp_scripts')
  7104. ->where('id', $script_id)
  7105. ->where('is_deleted', 0)
  7106. ->first();
  7107. if (!$script) {
  7108. Utils::throwError('20003:剧本不存在');
  7109. }
  7110. // 联表查询资产信息
  7111. $query = DB::table('mp_script_product_mappings as mapping')
  7112. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7113. ->where('mapping.script_id', $script_id)
  7114. ->where('product.cpid', $cpid)
  7115. ->where('product.is_deleted', 0);
  7116. // 如果提供了 episode_number,则过滤指定集数
  7117. if ($episode_number !== null && $episode_number !== '') {
  7118. $query->where('mapping.episode_number', $episode_number);
  7119. }
  7120. $mappings = $query->select(
  7121. 'mapping.script_id',
  7122. 'mapping.product_id',
  7123. 'mapping.episode_number',
  7124. 'product.product_name',
  7125. 'product.type',
  7126. 'product.product',
  7127. 'product.pic_prompt',
  7128. 'product.url',
  7129. 'product.pic_task_id',
  7130. 'product.pic_task_status',
  7131. 'product.three_view_image_url',
  7132. 'mapping.created_at'
  7133. )
  7134. ->orderBy('mapping.product_id', 'asc')
  7135. ->orderBy('mapping.episode_number', 'asc')
  7136. ->get();
  7137. // 按 product_id 分组,合并 episode_number
  7138. $productMap = [];
  7139. foreach ($mappings as $item) {
  7140. $product_id = $item->product_id;
  7141. if (!isset($productMap[$product_id])) {
  7142. $productMap[$product_id] = [
  7143. 'product_id' => $product_id,
  7144. 'product_name' => $item->product_name,
  7145. 'type' => (int)$item->type,
  7146. 'product' => (int)$item->product,
  7147. 'pic_prompt' => $item->pic_prompt,
  7148. 'url' => $item->url,
  7149. 'pic_task_id' => $item->pic_task_id,
  7150. 'pic_task_status' => $item->pic_task_status,
  7151. 'episode_numbers' => [],
  7152. 'created_at' => $item->created_at,
  7153. ];
  7154. }
  7155. // 添加 episode_number(去重)
  7156. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7157. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7158. }
  7159. }
  7160. // 按类型分组
  7161. $roles = []; // type=1 角色/主体
  7162. $scenes = []; // type=2 场景
  7163. $props = []; // type=3 道具
  7164. foreach ($productMap as $product) {
  7165. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7166. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7167. // 构造返回数据
  7168. $productData = [
  7169. 'product_id' => $product['product_id'],
  7170. 'product_name' => $product['product_name'],
  7171. 'product' => $product['product'],
  7172. 'pic_prompt' => $product['pic_prompt'],
  7173. 'url' => $product['url'],
  7174. 'pic_task_id' => $product['pic_task_id'],
  7175. 'pic_task_status' => $product['pic_task_status'],
  7176. 'episode_numbers' => $episodeNumbersStr,
  7177. 'created_at' => $product['created_at'],
  7178. ];
  7179. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7180. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7181. switch ($product['product']) {
  7182. case 1:
  7183. $roles[] = $productData;
  7184. break;
  7185. case 2:
  7186. $scenes[] = $productData;
  7187. break;
  7188. case 3:
  7189. $props[] = $productData;
  7190. break;
  7191. }
  7192. }
  7193. return [
  7194. 'script_id' => $script_id,
  7195. 'script_name' => $script->script_name ?? '',
  7196. 'roles' => $roles, // 主体
  7197. 'scenes' => $scenes, // 场景
  7198. 'props' => $props, // 道具
  7199. ];
  7200. }
  7201. /**
  7202. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7203. * @param string $actContent 原始内容
  7204. * @param array $products 产品数组(包含product_name和url)
  7205. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7206. */
  7207. public function processActContentWithProducts($actContent, $products) {
  7208. if (empty($actContent) || empty($products)) {
  7209. return [
  7210. 'content' => $actContent,
  7211. 'reference_images' => []
  7212. ];
  7213. }
  7214. // 构建产品名称到产品信息的映射
  7215. $product_dict = [];
  7216. foreach ($products as $product) {
  7217. $product_name = getProp($product, 'product_name');
  7218. if ($product_name) {
  7219. $product_dict[$product_name] = [
  7220. 'url' => getProp($product, 'url'),
  7221. 'voice_prompt' => getProp($product, 'voice_prompt')
  7222. ];
  7223. }
  7224. }
  7225. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7226. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7227. $reference_images = [];
  7228. $product_index_map = []; // 产品名称 => 图片序号的映射
  7229. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7230. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7231. $current_index = 1;
  7232. if (!empty($matches[1])) {
  7233. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7234. $seen_products = []; // 用于去重
  7235. foreach ($matches[1] as $product_name) {
  7236. // 跳过已处理的产品
  7237. if (isset($seen_products[$product_name])) {
  7238. continue;
  7239. }
  7240. $seen_products[$product_name] = true;
  7241. // 检查产品是否在字典中
  7242. if (isset($product_dict[$product_name])) {
  7243. $url = $product_dict[$product_name]['url'];
  7244. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7245. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7246. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7247. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7248. }
  7249. // 只有URL非空才分配序号和添加到参考图片
  7250. if (!empty($url)) {
  7251. // 检查URL是否已经在reference_images中(去重)
  7252. if (!in_array($url, $reference_images)) {
  7253. $reference_images[] = $url;
  7254. $product_index_map[$product_name] = $current_index;
  7255. $current_index++;
  7256. } else {
  7257. // URL重复,找到已有的序号
  7258. $existing_index = array_search($url, $reference_images) + 1;
  7259. $product_index_map[$product_name] = $existing_index;
  7260. }
  7261. } else {
  7262. // URL为空,不分配序号(后续直接去掉{})
  7263. $product_index_map[$product_name] = 0;
  7264. }
  7265. } else {
  7266. // 产品不在字典中,不分配序号
  7267. $product_index_map[$product_name] = 0;
  7268. }
  7269. }
  7270. }
  7271. // 第二步:替换内容中的 {产品名称}
  7272. $processedContent = $actContent;
  7273. foreach ($product_index_map as $product_name => $index) {
  7274. $escaped_name = preg_quote($product_name, '/');
  7275. if ($index > 0) {
  7276. // 有图片,替换为:产品名称(图X)
  7277. $replacement = $product_name . '<图片' . $index . '>';
  7278. } else {
  7279. // 无图片,只保留产品名称
  7280. $replacement = $product_name;
  7281. }
  7282. // 替换所有 {产品名称} 为处理后的格式
  7283. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7284. }
  7285. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7286. foreach ($products as $product) {
  7287. $product_name = getProp($product, 'product_name');
  7288. $voice_prompt = getProp($product, 'voice_prompt');
  7289. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7290. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7291. break; // 找到旁白后退出循环
  7292. }
  7293. }
  7294. // 第四步:将voice_prompt信息添加到内容最前面
  7295. $voice_prompt_prefix = '';
  7296. if (!empty($voice_prompts)) {
  7297. $voice_prompt_prefix .= implode('', $voice_prompts);
  7298. }
  7299. // 旁白的voice_prompt放在最后
  7300. if (!empty($narrator_voice_prompt)) {
  7301. $voice_prompt_prefix .= $narrator_voice_prompt;
  7302. }
  7303. // 如果有voice_prompt信息,添加到内容开头
  7304. if (!empty($voice_prompt_prefix)) {
  7305. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7306. }
  7307. return [
  7308. 'content' => $processedContent,
  7309. 'reference_images' => $reference_images
  7310. ];
  7311. }
  7312. public function saveActVideoGenerateParams($data) {
  7313. $episode_id = getProp($data, 'episode_id');
  7314. $model = getProp($data, 'video_model');
  7315. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7316. Utils::throwError('20003:该模型不可用');
  7317. }
  7318. if (!$model) {
  7319. // 使用默认模型
  7320. $model = 'zhizhen-20';
  7321. }
  7322. // 验证模型是否在可用模型表中
  7323. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7324. Utils::throwError('20003:该模型已不可用,请更换!');
  7325. }
  7326. $video_resolution = getProp($data, 'video_resolution', '720p');
  7327. $ratio = getProp($data, 'ratio');
  7328. if (!$ratio) $ratio = '9:16';
  7329. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7330. 'video_model' => $model,
  7331. 'video_resolution' => $video_resolution,
  7332. 'ratio' => $ratio,
  7333. 'updated_at' => date('Y-m-d H:i:s')
  7334. ]);
  7335. }
  7336. public function confirmActs($data) {
  7337. $episode_id = getProp($data, 'episode_id');
  7338. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7339. if (!$episode) {
  7340. Utils::throwError('20003:分集不存在');
  7341. }
  7342. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7343. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7344. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7345. // 获取所有片段数据
  7346. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7347. // 收集所有资产名称(角色、场景、道具)
  7348. $product_names = [];
  7349. // 收集角色名称
  7350. foreach ($roles as $role) {
  7351. $role_name = getProp($role, 'role');
  7352. if ($role_name && $role_name != '旁白') {
  7353. $product_names[] = $role_name;
  7354. }
  7355. }
  7356. // 收集场景名称
  7357. foreach ($scenes as $scene) {
  7358. $scene_name = getProp($scene, 'scene');
  7359. if ($scene_name) {
  7360. $product_names[] = $scene_name;
  7361. }
  7362. }
  7363. // 收集道具名称
  7364. foreach ($props as $prop) {
  7365. $prop_name = getProp($prop, 'prop');
  7366. if ($prop_name) {
  7367. $product_names[] = $prop_name;
  7368. }
  7369. }
  7370. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7371. $product_names = array_unique($product_names);
  7372. usort($product_names, function($a, $b) {
  7373. return mb_strlen($b) - mb_strlen($a);
  7374. });
  7375. try {
  7376. DB::beginTransaction();
  7377. // 处理每个片段
  7378. foreach ($acts as $act) {
  7379. $act_content = getProp($act, 'act_content');
  7380. if (!$act_content) continue;
  7381. $processed_content = $act_content;
  7382. // 统一替换所有资产名称为 {资产名} 格式
  7383. // 使用占位符避免嵌套替换问题
  7384. $placeholder_map = [];
  7385. $placeholder_index = 0;
  7386. foreach ($product_names as $product_name) {
  7387. // 转义特殊字符
  7388. $escaped_product = preg_quote($product_name, '/');
  7389. // 检查是否匹配且未被 {} 包裹
  7390. $processed_content = preg_replace_callback(
  7391. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7392. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7393. // 使用唯一占位符
  7394. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7395. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7396. $placeholder_index++;
  7397. return $placeholder;
  7398. },
  7399. $processed_content
  7400. );
  7401. }
  7402. // 将所有占位符替换回实际内容
  7403. foreach ($placeholder_map as $placeholder => $replacement) {
  7404. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7405. }
  7406. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7407. $shot_counter = 0;
  7408. $processed_content = preg_replace_callback(
  7409. '/【(?:镜头|分镜)(\d+)】/u',
  7410. function($matches) use (&$shot_counter) {
  7411. $shot_counter++;
  7412. return '【镜头' . $shot_counter . '】';
  7413. },
  7414. $processed_content
  7415. );
  7416. // 更新数据库
  7417. $boolen = DB::table('mp_episode_segments')
  7418. ->where('id', $act->id)
  7419. ->update([
  7420. 'act_show_content' => $processed_content,
  7421. 'updated_at' => date('Y-m-d H:i:s')
  7422. ]);
  7423. if (!$boolen) {
  7424. Utils::throwError('20003:片段处理失败');
  7425. }
  7426. }
  7427. }catch (\Exception $e) {
  7428. DB::rollBack();
  7429. Utils::throwError('20003:'.$e->getMessage());
  7430. }
  7431. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7432. 'is_generated' => 1,
  7433. 'updated_at' => date('Y-m-d H:i:s')
  7434. ]);
  7435. if (!$boolen1) {
  7436. DB::rollBack();
  7437. Utils::throwError('20003:分集处理失败!');
  7438. }
  7439. DB::commit();
  7440. // 重新查询更新后的片段数据
  7441. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7442. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7443. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7444. $products = [];
  7445. // 先处理角色数组
  7446. foreach ($roles as $role) {
  7447. $product = $role;
  7448. // 将role字段重命名为product_name
  7449. if (isset($product['role'])) {
  7450. $product['product_name'] = $product['role'];
  7451. unset($product['role']);
  7452. $product['product'] = 1; // 标记类型为角色
  7453. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7454. }
  7455. }
  7456. // 处理场景数组
  7457. foreach ($scenes as $scene) {
  7458. $product = $scene;
  7459. // 将scene字段重命名为product_name
  7460. if (isset($product['scene'])) {
  7461. $product['product_name'] = $product['scene'];
  7462. unset($product['scene']);
  7463. $product['product'] = 2; // 标记类型为场景
  7464. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7465. }
  7466. }
  7467. // 处理道具数组(逻辑与场景一致)
  7468. foreach ($props as $prop) {
  7469. $product = $prop;
  7470. // 将prop字段重命名为product_name
  7471. if (isset($product['prop'])) {
  7472. $product['product_name'] = $product['prop'];
  7473. unset($product['prop']);
  7474. $product['product'] = 3; // 标记类型为道具
  7475. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7476. }
  7477. }
  7478. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7479. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7480. foreach ($extra_products as $extra_product) {
  7481. $product_name = getProp($extra_product, 'product_name');
  7482. if ($product_name) {
  7483. $products[$product_name] = $extra_product; // 覆盖同名数据
  7484. }
  7485. }
  7486. // 重新索引数组(去除key)
  7487. $products = array_values($products);
  7488. // 构建返回的acts数组
  7489. $return_acts = [];
  7490. foreach ($acts as $act) {
  7491. $return_acts[] = [
  7492. 'act_id' => getProp($act, 'id'),
  7493. 'act_number' => getProp($act, 'act_number'),
  7494. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7495. 'act_show_content' => getProp($act, 'act_show_content'),
  7496. 'video_url' => getProp($act, 'video_url'),
  7497. 'video_duration' => getProp($act, 'video_duration'),
  7498. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7499. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7500. ];
  7501. }
  7502. return [
  7503. 'anime_id' => getProp($episode, 'anime_id'),
  7504. 'episode_id' => $episode_id,
  7505. 'title' => getProp($episode, 'title'),
  7506. 'episode_number' => getProp($episode, 'episode_number'),
  7507. 'is_generated' => getProp($episode, 'is_generated'),
  7508. 'products' => $products,
  7509. 'acts' => $return_acts
  7510. ];
  7511. }
  7512. }