AnimeService.php 374 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $input_art_style = getProp($data, 'art_style');
  181. $file = getProp($data, 'file');
  182. $content = getProp($data, 'content', '');
  183. $bid = getProp($data, 'bid', 0);
  184. $script_id = getProp($data, 'script_id', 0);
  185. $ace_mode = getProp($data, 'ace_mode', 0);
  186. $extra_products = getProp($data, 'products', []);
  187. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  188. if (!is_array($extra_products)) {
  189. Utils::throwError('20003:传入的资产格式不正确');
  190. }
  191. // 替换美术风格
  192. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  193. // 提取文件内容
  194. if ($file) {
  195. $content = $this->DeepSeekService->extractFileContent($file);
  196. if (!$content) {
  197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  198. }
  199. } elseif ($script_id) {
  200. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  201. if (!$content) {
  202. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  203. }
  204. } elseif ($bid) {
  205. $content = $this->DeepSeekService->getContentByBid($bid);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  208. }
  209. } elseif ($content) {
  210. $content = filterContent($content);
  211. }else {
  212. $content = '';
  213. }
  214. $anime_data = [
  215. 'user_id' => $uid,
  216. 'anime_name' => '新剧本策划',
  217. 'is_multi' => getProp($data, 'is_multi', 1),
  218. 'content' => $content,
  219. 'art_style_type' => $input_art_style,
  220. 'ace_mode' => $ace_mode,
  221. 'script_id' => $script_id,
  222. 'extra_products' => json_encode($extra_products, 256),
  223. 'created_at' => date('Y-m-d H:i:s'),
  224. 'updated_at' => date('Y-m-d H:i:s'),
  225. ];
  226. // 处理文本模型
  227. $model = getProp($data, 'model');
  228. if (!$model) {
  229. // 用户没有输入,使用默认值
  230. $model = 'deepseek-v4-pro';
  231. }
  232. // 验证模型是否在可用模型表中
  233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  234. $model = 'deepseek-v4-pro';
  235. }
  236. $anime_data['model'] = $model;
  237. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  238. return DB::table('mp_animes')->insertGetId($anime_data);
  239. }
  240. public function chatList($data) {
  241. $uid = Site::getUid();
  242. $anime_name = getProp($data, 'anime_name');
  243. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  244. if ($anime_name) {
  245. $query->where('anime_name', 'like', "%$anime_name%");
  246. }
  247. return $query->orderBy('id', 'desc')->paginate();
  248. }
  249. public function chatHistory($data) {
  250. $anime_id = getProp($data, 'anime_id');
  251. $sequence = getProp($data, 'sequence', 0);
  252. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  253. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  254. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  255. return $query->orderBy('ar.id')->get()->map(function ($value) {
  256. $value = (array)$value;
  257. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  258. $value['created_at'] = transDate($value['created_at']);
  259. $value['episode_created_at'] = transDate($value['episode_created_at']);
  260. return $value;
  261. })->toArray();
  262. }
  263. public function batchSetRoleImg($data) {
  264. $episode_id = getProp($data, 'episode_id');
  265. if (!$episode_id) Utils::throwError('1002:请选择分集');
  266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  267. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  268. $art_style = getProp($episode, 'art_style');
  269. $anime_id = getProp($episode, 'anime_id');
  270. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  271. $art_style_type = getProp($anime, 'art_style_type');
  272. $character_prefix = '';
  273. $scene_prefix = '';
  274. if ($art_style_type) {
  275. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  276. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  277. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  278. }
  279. foreach ($roles as &$role) {
  280. $role_name = getProp($role, 'role');
  281. if ($role_name == '旁白') continue;
  282. // 优先使用 pic_prompt,如果没有则使用 description
  283. $pic_prompt = getProp($role, 'pic_prompt');
  284. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  285. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  286. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  287. // 参考图地址
  288. $ref_img_url = getProp($role, 'url');
  289. if ($ref_img_url) continue; // 已有图片则跳过
  290. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  291. try {
  292. $params = [
  293. 'prompt' => $description,
  294. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  295. ];
  296. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  297. $task_id = $task->id;
  298. if (!$task_id) {
  299. Utils::throwError("20003:角色({$role_name})生成图片失败");
  300. }
  301. $role['task_id'] = $task_id;
  302. $role['task_status'] = 'processing';
  303. } catch (\Exception $e) {
  304. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  305. Utils::throwError("20003:" . $e->getMessage());
  306. }
  307. }
  308. // 保存角色信息
  309. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  310. 'roles' => json_encode($roles, 256),
  311. 'generate_status' => '执行中',
  312. 'generate_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$boolen) {
  316. Utils::throwError('20003:保存角色信息失败');
  317. }
  318. return $boolen;
  319. }
  320. public function batchSetSceneImg($data) {
  321. $episode_id = getProp($data, 'episode_id');
  322. if (!$episode_id) Utils::throwError('1002:请选择分集');
  323. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  324. $scenes = json_decode(getProp($episode, 'scenes'), true);
  325. $art_style = getProp($episode, 'art_style');
  326. $target_scene = getProp($data, 'target_scene');
  327. $anime_id = getProp($episode, 'anime_id');
  328. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  329. $art_style_type = getProp($anime, 'art_style_type');
  330. $character_prefix = '';
  331. $scene_prefix = '';
  332. if ($art_style_type) {
  333. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  334. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  335. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  336. }
  337. foreach ($scenes as &$scene) {
  338. $scene_name = getProp($scene, 'scene');
  339. if ($scene_name != $target_scene) continue;
  340. // 优先使用 pic_prompt,如果没有则使用 description
  341. $pic_prompt = getProp($scene, 'pic_prompt');
  342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  343. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  344. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  345. // 参考图地址
  346. $ref_img_url = getProp($scene, 'url');
  347. if ($ref_img_url) continue; // 已有图片则跳过
  348. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  349. try {
  350. $params = [
  351. 'prompt' => $description,
  352. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  353. ];
  354. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  355. $task_id = $task->id;
  356. if (!$task_id) {
  357. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  358. }
  359. $scene['task_id'] = $task_id;
  360. $scene['task_status'] = 'processing';
  361. } catch (\Exception $e) {
  362. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  363. Utils::throwError("20003:" . $e->getMessage());
  364. }
  365. }
  366. // 保存场景信息
  367. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  368. 'scenes' => json_encode($scenes, 256),
  369. 'generate_status' => '执行中',
  370. 'generate_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$boolen) {
  374. Utils::throwError('20003:保存角色信息失败');
  375. }
  376. return $boolen;
  377. }
  378. public function editAnime($data) {
  379. $anime_id = getProp($data, 'anime_id');
  380. $anime_name = trim(getProp($data, 'anime_name'));
  381. // 确认对话名称唯一性
  382. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  383. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  384. }
  385. if (!$anime_id || !$anime_name) {
  386. Utils::throwError('20003:参数异常');
  387. }
  388. return DB::table('mp_animes')->where('id', $anime_id)->update([
  389. 'anime_name' => $anime_name,
  390. 'updated_at' => date('Y-m-d H:i:s')
  391. ]);
  392. // $script_arr =getProp($data, 'script', []);
  393. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  394. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  395. // $anime_id = getProp($data, 'anime_id');
  396. // try {
  397. // DB::beginTransaction();
  398. // $table_data = [
  399. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  400. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  401. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  402. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  403. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  404. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  405. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  406. // 'status' => 3,
  407. // 'start_episode_sequence' => $start_episode_sequence,
  408. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  409. // 'episode_num' => count($script_arr['episodes']),
  410. // 'updated_at' => date('Y-m-d H:i:s')
  411. // ];
  412. // // 保存剧本内容
  413. // if (!empty($anime_id)) {
  414. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  415. // if (!$boolen) {
  416. // dLog('anime')->info('对话保存失败', $table_data);
  417. // Utils::throwError('20003:对话保存失败');
  418. // }
  419. // }else {
  420. // $table['created_at'] = $table_data['updated_at'];
  421. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  422. // if (!$anime_id) {
  423. // dLog('anime')->info('对话保存失败', $table_data);
  424. // Utils::throwError('20003:对话保存失败');
  425. // }
  426. // }
  427. // // 保存分集内容
  428. // // 删除历史分集内容
  429. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  430. // $episodes = [];
  431. // $sequence = 1;
  432. // foreach ($script_arr['episodes'] as $episode) {
  433. // $segment_number = 1;
  434. // foreach($episode['segments'] as $segment) {
  435. // $episodes[] = [
  436. // 'anime_id' => $anime_id,
  437. // 'episode_number' => $episode['episode_number'],
  438. // 'title' => $episode['title'],
  439. // // 'content' => $episode['content'],
  440. // 'content' => '',
  441. // 'segment_number' => $segment_number,
  442. // 'segment_content' => $segment['segment_content'],
  443. // 'sequence' => $sequence,
  444. // 'created_at' => date('Y-m-d H:i:s'),
  445. // 'updated_at' => date('Y-m-d H:i:s')
  446. // ];
  447. // $sequence++;
  448. // $segment_number++;
  449. // }
  450. // }
  451. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  452. // if (!$boolen2) {
  453. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  454. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  455. // Utils::throwError('20003:分集内容保存失败');
  456. // }
  457. // } catch (\Exception $e) {
  458. // DB::rollBack();
  459. // Utils::throwError('20003:'.$e->getMessage());
  460. // }
  461. // DB::commit();
  462. // return true;
  463. }
  464. public function delAnime($data) {
  465. $anime_id = getProp($data, 'anime_id');
  466. if (!$anime_id) {
  467. Utils::throwError('20003:请选择剧本');
  468. }
  469. return DB::table('mp_animes')->where('id', $anime_id)->update([
  470. 'is_deleted' => 1,
  471. 'updated_at' => date('Y-m-d H:i:s')
  472. ]);
  473. }
  474. public function animeDetail($data) {
  475. $uid = Site::getUid();
  476. $anime_id = getProp($data, 'anime_id');
  477. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  478. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  479. if (!$anime) Utils::throwError('20003:权限不足');
  480. $anime = (array)$anime;
  481. $anime['roles'] = json_decode($anime['roles']);
  482. $anime['scenes'] = json_decode($anime['scenes']);
  483. // 获取分集信息
  484. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  485. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  486. ->orderBy('episode_number')->get()->map(function ($value) {
  487. return (array)$value;
  488. })->toArray();
  489. $anime['episodes'] = $episodes;
  490. return $anime;
  491. }
  492. public function episodeInfo($data) {
  493. $uid = Site::getUid();
  494. $anime_id = getProp($data, 'anime_id');
  495. $episode_id = getProp($data, 'episode_id');
  496. if (!$anime_id || !$episode_id) {
  497. Utils::throwError('1002:请选择剧集');
  498. }
  499. // 验证用户权限
  500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  503. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  504. $episode = (array)$episode;
  505. $episode['roles'] = json_decode($episode['roles'], true);
  506. // foreach($episode['roles'] as &$item) {
  507. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  508. // }
  509. $episode['scenes'] = json_decode($episode['scenes'], true);
  510. // foreach($episode['scenes'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  512. // }
  513. // 获取分镜信息
  514. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  515. ->select('*')->get()->map(function ($value) {
  516. return (array)$value;
  517. })->toArray();
  518. // 使用公共方法构建分镜结构
  519. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  520. $episode['acts'] = $segmentsStructure['acts'];
  521. $episode['total_duration'] = $segmentsStructure['total_duration'];
  522. return $episode;
  523. }
  524. public function episodeInfoForAce($data) {
  525. $anime_id = getProp($data, 'anime_id');
  526. $episode_id = getProp($data, 'episode_id');
  527. if (!$anime_id || !$episode_id) {
  528. Utils::throwError('1002:请选择剧集');
  529. }
  530. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  531. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  532. $episode = (array)$episode;
  533. $episode['roles'] = json_decode($episode['roles'], true);
  534. // foreach($episode['roles'] as &$item) {
  535. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  536. // }
  537. $episode['scenes'] = json_decode($episode['scenes'], true);
  538. // foreach($episode['scenes'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  540. // }
  541. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  542. // 获取分镜信息
  543. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  544. ->select('*')->get()->map(function ($value) {
  545. return (array)$value;
  546. })->toArray();
  547. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  548. $episode['acts'] = $segmentsStructure['acts'];
  549. $episode['total_duration'] = $segmentsStructure['total_duration'];
  550. return $episode;
  551. }
  552. public function segmentInfo($data) {
  553. $uid = Site::getUid();
  554. $segment_id = getProp($data, 'segment_id');
  555. if (!$segment_id) {
  556. Utils::throwError('1002:请选择分镜');
  557. }
  558. // 获取分镜信息
  559. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  560. // 验证用户权限
  561. if ($segment) {
  562. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  563. if (!$anime) Utils::throwError('20003:权限不足');
  564. }
  565. $result = [
  566. 'segment_id' => getProp($segment, 'segment_id'),
  567. 'segment_number' => getProp($segment, 'segment_number'),
  568. 'segment_content' => getProp($segment, 'segment_content'),
  569. 'description' => getProp($segment, 'description'),
  570. 'composition' => getProp($segment, 'composition'),
  571. 'camera_movement' => getProp($segment, 'camera_movement'),
  572. 'voice_actor' => getProp($segment, 'voice_actor'),
  573. 'dialogue' => getProp($segment, 'dialogue'),
  574. 'frame_type' => getProp($segment, 'frame_type'),
  575. 'scene' => getProp($segment, 'scene'),
  576. 'characters' => getProp($segment, 'characters'),
  577. 'tail_frame' => getProp($segment, 'tail_frame'),
  578. 'emotion' => getProp($segment, 'emotion'),
  579. 'emotion_type' => getProp($segment, 'emotion_type'),
  580. 'gender' => getProp($segment, 'gender'),
  581. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  582. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  583. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  584. 'pitch' => getProp($segment, 'pitch'),
  585. 'voice_name' => getProp($segment, 'voice_name'),
  586. 'voice_type' => getProp($segment, 'voice_type'),
  587. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  588. 'img_url' => getProp($segment, 'img_url'),
  589. 'video_url' => getProp($segment, 'video_url'),
  590. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  591. ];
  592. return $result;
  593. }
  594. public function copyEpisodeVersion($data) {
  595. $episode_id = getProp($data, 'episode_id');
  596. $uid = Site::getUid();
  597. $cpid = Site::getCpid();
  598. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  599. if (!$episode) Utils::throwError('20003:该剧集不存在');
  600. $episode = (array)$episode;
  601. $anime_id = $episode['anime_id'];
  602. $episode_number = $episode['episode_number'];
  603. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  604. $sequence = $count + 1;
  605. unset($episode['id']);
  606. $now = date('Y-m-d H:i:s');
  607. $episode['created_at'] = $now;
  608. $episode['updated_at'] = $now;
  609. $episode['is_default'] = 1;
  610. // 获取版本中含有"(副本"字样的个数
  611. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  612. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  613. $episode['sequence'] = $sequence;
  614. $episode['is_generated'] = 0;
  615. $episode['cpid'] = $cpid;
  616. // 获取ace_mode
  617. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  618. try {
  619. DB::beginTransaction();
  620. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  621. // 新增副本
  622. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  623. if (!$new_episode_id) {
  624. Utils::throwError('20003:创建副本失败!');
  625. }
  626. // 获取分镜数据并准备插入
  627. $segments_for_insert = DB::table('mp_episode_segments')
  628. ->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')
  629. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  630. $item = (array)$item;
  631. $item['episode_id'] = $new_episode_id;
  632. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  633. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  634. return $item;
  635. })->toArray();
  636. // 写入分镜数据
  637. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  638. if (!$boolen2) {
  639. Utils::throwError('20003:写入分镜数据失败!');
  640. }
  641. // 写入对话历史
  642. $records = [
  643. [
  644. 'uid' => $uid,
  645. 'anime_id' => $anime_id,
  646. 'role' => 'user',
  647. 'content' => '创建副本',
  648. 'sequence' => $episode_number,
  649. 'episode_id' => $new_episode_id,
  650. 'created_at' => $now,
  651. 'updated_at' => $now
  652. ],
  653. [
  654. 'uid' => $uid,
  655. 'anime_id' => $anime_id,
  656. 'role' => 'assistant',
  657. 'content' => '好的,已为您创建副本',
  658. 'sequence' => $episode_number,
  659. 'episode_id' => $new_episode_id,
  660. 'created_at' => $now,
  661. 'updated_at' => $now
  662. ]
  663. ];
  664. $boolen3 = DB::table('mp_anime_records')->insert($records);
  665. if (!$boolen3) {
  666. Utils::throwError('20003:对话记录保存失败');
  667. }
  668. }catch (\Exception $e) {
  669. DB::rollBack();
  670. Utils::throwError('20003:'.$e->getMessage());
  671. }
  672. DB::commit();
  673. // 构建与 episodeInfo 方法一致的返回数据结构
  674. $result = [
  675. 'episode_id' => $new_episode_id,
  676. 'anime_id' => $anime_id,
  677. 'episode_number' => $episode_number,
  678. 'title' => $episode['title'],
  679. 'intro' => $episode['intro'],
  680. 'art_style' => $episode['art_style'],
  681. 'roles' => json_decode($episode['roles'], true),
  682. 'scenes' => json_decode($episode['scenes'], true),
  683. 'is_generated' => (int)$episode['is_generated']
  684. ];
  685. if ((int)$ace_mode === 1) {
  686. // 获取分镜信息
  687. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  688. ->select('*')->get()->map(function ($value) {
  689. return (array)$value;
  690. })->toArray();
  691. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  692. }else {
  693. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  694. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  695. }
  696. $result['acts'] = $segmentsStructure['acts'];
  697. $result['total_duration'] = $segmentsStructure['total_duration'];
  698. return $result;
  699. }
  700. public function episodeVersions($data) {
  701. $anime_id = getProp($data, 'anime_id');
  702. $episode_id = getProp($data, 'episode_id');
  703. if (!$anime_id || !$episode_id) {
  704. Utils::throwError('1002:请选择剧集');
  705. }
  706. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  707. $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) {
  708. return (array)$value;
  709. })->toArray();
  710. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  711. foreach($episodes as &$episode) {
  712. $episode['version'] = 'V'.$episode['sequence'];
  713. $episode['roles'] = json_decode($episode['roles'], true);
  714. $episode['scenes'] = json_decode($episode['scenes'], true);
  715. // 获取分镜信息
  716. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  717. ->select('*')->get()->map(function ($value) {
  718. return (array)$value;
  719. })->toArray();
  720. // 使用公共方法构建分镜结构
  721. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  722. $episode['acts'] = $segmentsStructure['acts'];
  723. $episode['total_duration'] = $segmentsStructure['total_duration'];
  724. }
  725. return $episodes;
  726. }
  727. public function bindEpisodeVersion($data) {
  728. $episode_id = getProp($data, 'episode_id');
  729. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  730. if (!$episode) Utils::throwError('20003:该剧集不存在');
  731. $episode = (array)$episode;
  732. if ((int)$episode['is_default'] === 1) return true;
  733. try {
  734. DB::beginTransaction();
  735. // 移除is_default标志
  736. $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')]);
  737. if (!$boolen) {
  738. Utils::throwError('20003:更新失败!');
  739. }
  740. // 绑定副本
  741. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  742. if (!$boolen2) {
  743. Utils::throwError('20003:绑定失败!');
  744. }
  745. }catch (\Exception $e) {
  746. DB::rollBack();
  747. Utils::throwError('20003:'.$e->getMessage());
  748. }
  749. DB::commit();
  750. return true;
  751. }
  752. public function chatChangeImg($data) {
  753. $segment_id = getProp($data, 'segment_id');
  754. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  755. $prompt = getProp($data, 'prompt');
  756. if (!$prompt || !$segment_id) {
  757. Utils::throwError('1002:请输入提示词,并且选择分镜');
  758. }
  759. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  760. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  761. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  762. else $ref_img_url = '';
  763. // $ref_img_url = '';
  764. if (empty($prompt)) {
  765. if (empty($ref_img_url)) {
  766. $prompt = getProp($segment, 'segment_content');
  767. }else {
  768. $prompt = '请根据图片生成';
  769. }
  770. }
  771. $anime_id = getProp($segment, 'anime_id');
  772. $episode_id = getProp($segment, 'episode_id');
  773. $episode_number = getProp($segment, 'episode_number');
  774. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  775. $ratio = getProp($data, 'ratio');
  776. if (!$ratio) {
  777. $ratio = getProp($episode, 'ratio');
  778. if (!$ratio) $ratio = '9:16';
  779. }
  780. $art_style = getProp($episode, 'art_style');
  781. if ($art_style) {
  782. $prompt = "美术风格:{$art_style}\n{$prompt}";
  783. }
  784. $dimensions = $this->getRatioDimensions($ratio);
  785. $width = $dimensions['width'];
  786. $height = $dimensions['height'];
  787. try {
  788. $params = [
  789. 'alias_segment_id' => $segment_id,
  790. 'prompt' => $prompt,
  791. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  792. 'width' => $width,
  793. 'height' => $height
  794. ];
  795. // 优化提示词(不要生成字幕)
  796. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  797. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  798. $task_id = $task->id;
  799. if (!$task_id) {
  800. Utils::throwError("20003:生成图片失败");
  801. }
  802. // 更新任务ID
  803. $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')]);
  804. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  805. } catch (\Exception $e) {
  806. Utils::throwError("20003:" . $e->getMessage());
  807. }
  808. // 创建任务之后先暂停10s等待异步任务完成
  809. sleep(10);
  810. $img_url = $this->loopGetPicTaskResult($task_id);
  811. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  812. // 图片生成后新增对话记录
  813. try {
  814. $uid = Site::getUid();
  815. $now = date('Y-m-d H:i:s');
  816. // 使用AI反推图片提示词
  817. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  818. // 保存对话记录
  819. $records = [
  820. [
  821. 'uid' => $uid,
  822. 'anime_id' => $anime_id,
  823. 'sequence' => $episode_number,
  824. 'role' => 'user',
  825. 'content' => $prompt,
  826. 'segment_id' => $segment_id,
  827. 'image_url' => '',
  828. 'created_at' => $now,
  829. 'updated_at' => $now
  830. ],
  831. [
  832. 'uid' => $uid,
  833. 'anime_id' => $anime_id,
  834. 'sequence' => $episode_number,
  835. 'role' => 'assistant',
  836. 'content' => $pic_prompt,
  837. 'segment_id' => $segment_id,
  838. 'image_url' => $img_url,
  839. 'created_at' => $now,
  840. 'updated_at' => $now
  841. ]
  842. ];
  843. DB::table('mp_anime_records')->insert($records);
  844. } catch (\Exception $e) {
  845. // 记录日志但不影响主流程
  846. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  847. 'segment_id' => $segment_id,
  848. 'img_url' => $img_url
  849. ]);
  850. logDB('anime', 'error', '保存对话记录失败', [
  851. 'segment_id' => $segment_id,
  852. 'img_url' => $img_url,
  853. 'error' => $e->getMessage()
  854. ]);
  855. }
  856. return $img_url;
  857. }
  858. public function segmentChatHistory($data) {
  859. $segment_id = getProp($data, 'segment_id');
  860. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  861. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  862. $chat = $query->orderBy('id')->get()->map(function ($value) {
  863. $value = (array)$value;
  864. $value['created_at'] = transDate($value['created_at']);
  865. return $value;
  866. })->toArray();
  867. // 获取历史图片
  868. $url = [];
  869. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  870. foreach($pic_history as $task) {
  871. $result_url = getProp($task, 'result_url');
  872. if (is_json($result_url)) {
  873. $url = array_merge($url, json_decode($result_url, true));
  874. }else {
  875. $url[] = $result_url;
  876. }
  877. }
  878. // 获取历史视频
  879. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  880. foreach($video_history as $task) {
  881. $result_url = getProp($task, 'compressed_url');
  882. if (is_json($result_url)) {
  883. $url = array_merge($url, json_decode($result_url, true));
  884. }else {
  885. $url[] = $result_url;
  886. }
  887. }
  888. return compact('chat', 'url');
  889. }
  890. public function changeEpisodeRoles($data) {
  891. $anime_id = getProp($data, 'anime_id');
  892. $episode_id = getProp($data, 'episode_id');
  893. $target_roles = getProp($data, 'roles');
  894. $is_deleted = getProp($data, 'is_deleted', 0);
  895. // 参数验证
  896. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  897. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  898. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  899. // 验证剧集是否存在
  900. $episode = DB::table('mp_anime_episodes')
  901. ->where('anime_id', $anime_id)
  902. ->where('id', $episode_id)
  903. ->first();
  904. if (!$episode) Utils::throwError('20003:该剧集不存在');
  905. $roles = json_decode(getProp($episode, 'roles'), true);
  906. // 获取anime信息,检查是否有关联的script_id
  907. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  908. if (!$anime) Utils::throwError('20003:动漫不存在');
  909. $script_id = getProp($anime, 'script_id');
  910. $episode_number = getProp($episode, 'episode_number', 1);
  911. $uid = Site::getUid();
  912. $cpid = Site::getCpid();
  913. try {
  914. $target_role_name = getProp($target_roles, 'role');
  915. // 如果是删除操作
  916. if ($is_deleted == 1) {
  917. // 从角色列表中移除该角色
  918. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  919. return getProp($role, 'role') !== $target_role_name;
  920. }));
  921. // 更新角色列表
  922. $result = DB::table('mp_anime_episodes')
  923. ->where('anime_id', $anime_id)
  924. ->where('id', $episode_id)
  925. ->update([
  926. 'roles' => json_encode($roles, 256),
  927. 'updated_at' => date('Y-m-d H:i:s')
  928. ]);
  929. if ($result === false) {
  930. Utils::throwError('20003:删除角色失败');
  931. }
  932. } else {
  933. // 新增或更新操作
  934. $role_found = false;
  935. $is_new_role = false;
  936. // 查找并更新已存在的角色
  937. foreach($roles as &$role) {
  938. if (getProp($role, 'role') === $target_role_name) {
  939. $role = $target_roles;
  940. $role_found = true;
  941. break;
  942. }
  943. }
  944. // 如果角色不存在,则新增
  945. if (!$role_found) {
  946. $roles[] = $target_roles;
  947. $is_new_role = true;
  948. }
  949. // 更新角色列表
  950. $result = DB::table('mp_anime_episodes')
  951. ->where('anime_id', $anime_id)
  952. ->where('id', $episode_id)
  953. ->update([
  954. 'roles' => json_encode($roles, 256),
  955. 'updated_at' => date('Y-m-d H:i:s')
  956. ]);
  957. if ($result === false) {
  958. Utils::throwError('20003:更新角色列表失败');
  959. }
  960. // 同步更新分镜表中对应主体的音色信息
  961. $voice_name = getProp($target_roles, 'voice_name');
  962. $voice_type = getProp($target_roles, 'voice_type');
  963. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  964. DB::table('mp_episode_segments')
  965. ->where('anime_id', $anime_id)
  966. ->where('episode_id', $episode_id)
  967. ->where('voice_actor', $target_role_name)
  968. ->update([
  969. 'voice_name' => $voice_name,
  970. 'voice_type' => $voice_type,
  971. 'voice_audio_url' => $voice_audio_url,
  972. 'updated_at' => date('Y-m-d H:i:s')
  973. ]);
  974. // 如果有关联的script_id,则同步到mp_products表
  975. if ($script_id) {
  976. // 查询剧本信息
  977. $script = DB::table('mp_scripts')
  978. ->where('id', $script_id)
  979. ->where('is_deleted', 0)
  980. ->first();
  981. if ($script) {
  982. $script_name = $script->script_name ?? 'script_' . $script_id;
  983. $product_name = getProp($target_roles, 'role');
  984. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  985. $url = getProp($target_roles, 'url', '');
  986. $product_type = 1; // 1=角色
  987. // 查找或创建以script_name命名的文件夹
  988. $folder = DB::table('mp_products')
  989. ->where('cpid', $cpid)
  990. ->where('type', 2) // 文件夹类型
  991. ->where('product', $product_type) // 角色类型
  992. ->where('product_name', $script_name)
  993. ->where('parent_id', 0)
  994. ->where('is_deleted', 0)
  995. ->first();
  996. if (!$folder) {
  997. // 创建文件夹
  998. $folder_id = DB::table('mp_products')->insertGetId([
  999. 'user_id' => $uid,
  1000. 'cpid' => $cpid,
  1001. 'type' => 2, // 文件夹
  1002. 'product' => $product_type, // 角色类型
  1003. 'parent_id' => 0,
  1004. 'level' => 1,
  1005. 'product_name' => $script_name,
  1006. 'sort_order' => time(),
  1007. 'is_deleted' => 0,
  1008. 'created_at' => date('Y-m-d H:i:s'),
  1009. 'updated_at' => date('Y-m-d H:i:s')
  1010. ]);
  1011. } else {
  1012. $folder_id = $folder->id;
  1013. }
  1014. // 查找该文件夹下是否已存在同名资产
  1015. $existing_product = DB::table('mp_products')
  1016. ->where('cpid', $cpid)
  1017. ->where('type', 1) // 资产类型
  1018. ->where('product', $product_type)
  1019. ->where('parent_id', $folder_id)
  1020. ->where('product_name', $product_name)
  1021. ->where('is_deleted', 0)
  1022. ->first();
  1023. if ($existing_product) {
  1024. // 更新已存在的资产
  1025. $updateData = [
  1026. 'pic_task_status' => '生成成功',
  1027. ];
  1028. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1029. if ($url) $updateData['url'] = $url;
  1030. // 处理versions字段
  1031. $versions = getProp($target_roles, 'versions', []);
  1032. if ($versions && is_array($versions)) {
  1033. $updateData['versions'] = json_encode($versions, 256);
  1034. }
  1035. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1036. DB::table('mp_products')
  1037. ->where('id', $existing_product->id)
  1038. ->update($updateData);
  1039. $product_id = $existing_product->id;
  1040. } else {
  1041. // 创建新资产
  1042. $versions = getProp($target_roles, 'versions', []);
  1043. $product_id = DB::table('mp_products')->insertGetId([
  1044. 'user_id' => $uid,
  1045. 'cpid' => $cpid,
  1046. 'type' => 1, // 资产
  1047. 'product' => $product_type, // 角色
  1048. 'parent_id' => $folder_id,
  1049. 'level' => 2,
  1050. 'product_name' => $product_name,
  1051. 'url' => $url,
  1052. 'pic_prompt' => $pic_prompt,
  1053. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1054. 'sort_order' => time(),
  1055. 'is_deleted' => 0,
  1056. 'pic_task_status' => '生成成功',
  1057. 'created_at' => date('Y-m-d H:i:s'),
  1058. 'updated_at' => date('Y-m-d H:i:s')
  1059. ]);
  1060. }
  1061. // 建立或更新绑定关系
  1062. $existing_mapping = DB::table('mp_script_product_mappings')
  1063. ->where('script_id', $script_id)
  1064. ->where('product_id', $product_id)
  1065. ->where('episode_number', $episode_number)
  1066. ->first();
  1067. if (!$existing_mapping) {
  1068. // 创建绑定关系
  1069. DB::table('mp_script_product_mappings')->insert([
  1070. 'script_id' => $script_id,
  1071. 'product_id' => $product_id,
  1072. 'episode_number' => $episode_number,
  1073. 'created_at' => date('Y-m-d H:i:s'),
  1074. 'updated_at' => date('Y-m-d H:i:s')
  1075. ]);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. } catch (\Exception $e) {
  1081. dLog('anime')->error('更新剧集角色失败', [
  1082. 'anime_id' => $anime_id,
  1083. 'episode_id' => $episode_id,
  1084. 'error' => $e->getMessage()
  1085. ]);
  1086. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1087. }
  1088. return true;
  1089. }
  1090. public function changeEpisodeScenes($data) {
  1091. $anime_id = getProp($data, 'anime_id');
  1092. $episode_id = getProp($data, 'episode_id');
  1093. $target_scenes = getProp($data, 'scenes');
  1094. $is_deleted = getProp($data, 'is_deleted', 0);
  1095. // 参数验证
  1096. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1097. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1098. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1099. // 验证剧集是否存在
  1100. $episode = DB::table('mp_anime_episodes')
  1101. ->where('anime_id', $anime_id)
  1102. ->where('id', $episode_id)
  1103. ->first();
  1104. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1105. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1106. // 获取anime信息,检查是否有关联的script_id
  1107. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1108. if (!$anime) Utils::throwError('20003:动漫不存在');
  1109. $script_id = getProp($anime, 'script_id');
  1110. $episode_number = getProp($episode, 'episode_number', 1);
  1111. $uid = Site::getUid();
  1112. $cpid = Site::getCpid();
  1113. try {
  1114. $target_scene_name = getProp($target_scenes, 'scene');
  1115. // 如果是删除操作
  1116. if ($is_deleted == 1) {
  1117. // 从场景列表中移除该场景
  1118. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1119. return getProp($scene, 'scene') !== $target_scene_name;
  1120. }));
  1121. // 更新场景列表
  1122. $result = DB::table('mp_anime_episodes')
  1123. ->where('anime_id', $anime_id)
  1124. ->where('id', $episode_id)
  1125. ->update([
  1126. 'scenes' => json_encode($scenes, 256),
  1127. 'updated_at' => date('Y-m-d H:i:s')
  1128. ]);
  1129. if ($result === false) {
  1130. Utils::throwError('20003:删除场景失败');
  1131. }
  1132. } else {
  1133. // 新增或更新操作
  1134. $scene_found = false;
  1135. $is_new_scene = false;
  1136. // 查找并更新已存在的场景
  1137. foreach($scenes as &$scene) {
  1138. if (getProp($scene, 'scene') === $target_scene_name) {
  1139. $scene = $target_scenes;
  1140. $scene_found = true;
  1141. break;
  1142. }
  1143. }
  1144. // 如果场景不存在,则新增
  1145. if (!$scene_found) {
  1146. $scenes[] = $target_scenes;
  1147. $is_new_scene = true;
  1148. }
  1149. // 更新场景列表
  1150. $result = DB::table('mp_anime_episodes')
  1151. ->where('anime_id', $anime_id)
  1152. ->where('id', $episode_id)
  1153. ->update([
  1154. 'scenes' => json_encode($scenes, 256),
  1155. 'updated_at' => date('Y-m-d H:i:s')
  1156. ]);
  1157. if ($result === false) {
  1158. Utils::throwError('20003:更新场景列表失败');
  1159. }
  1160. // 如果有关联的script_id,则同步到mp_products表
  1161. if ($script_id) {
  1162. // 查询剧本信息
  1163. $script = DB::table('mp_scripts')
  1164. ->where('id', $script_id)
  1165. ->where('is_deleted', 0)
  1166. ->first();
  1167. if ($script) {
  1168. $script_name = $script->script_name ?? 'script_' . $script_id;
  1169. $product_name = getProp($target_scenes, 'scene');
  1170. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1171. $url = getProp($target_scenes, 'url', '');
  1172. $product_type = 2; // 2=场景
  1173. // 查找或创建以script_name命名的文件夹
  1174. $folder = DB::table('mp_products')
  1175. ->where('cpid', $cpid)
  1176. ->where('type', 2) // 文件夹类型
  1177. ->where('product', $product_type) // 场景类型
  1178. ->where('product_name', $script_name)
  1179. ->where('parent_id', 0)
  1180. ->where('is_deleted', 0)
  1181. ->first();
  1182. if (!$folder) {
  1183. // 创建文件夹
  1184. $folder_id = DB::table('mp_products')->insertGetId([
  1185. 'user_id' => $uid,
  1186. 'cpid' => $cpid,
  1187. 'type' => 2, // 文件夹
  1188. 'product' => $product_type, // 场景类型
  1189. 'parent_id' => 0,
  1190. 'level' => 1,
  1191. 'product_name' => $script_name,
  1192. 'sort_order' => time(),
  1193. 'is_deleted' => 0,
  1194. 'created_at' => date('Y-m-d H:i:s'),
  1195. 'updated_at' => date('Y-m-d H:i:s')
  1196. ]);
  1197. } else {
  1198. $folder_id = $folder->id;
  1199. }
  1200. // 查找该文件夹下是否已存在同名资产
  1201. $existing_product = DB::table('mp_products')
  1202. ->where('cpid', $cpid)
  1203. ->where('type', 1) // 资产类型
  1204. ->where('product', $product_type)
  1205. ->where('parent_id', $folder_id)
  1206. ->where('product_name', $product_name)
  1207. ->where('is_deleted', 0)
  1208. ->first();
  1209. if ($existing_product) {
  1210. // 更新已存在的资产
  1211. $updateData = [
  1212. 'pic_task_status' => '生成成功'
  1213. ];
  1214. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1215. if ($url) $updateData['url'] = $url;
  1216. // 处理versions字段
  1217. $versions = getProp($target_scenes, 'versions', []);
  1218. if ($versions && is_array($versions)) {
  1219. $updateData['versions'] = json_encode($versions, 256);
  1220. }
  1221. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1222. DB::table('mp_products')
  1223. ->where('id', $existing_product->id)
  1224. ->update($updateData);
  1225. $product_id = $existing_product->id;
  1226. } else {
  1227. // 创建新资产
  1228. $versions = getProp($target_scenes, 'versions', []);
  1229. $product_id = DB::table('mp_products')->insertGetId([
  1230. 'user_id' => $uid,
  1231. 'cpid' => $cpid,
  1232. 'type' => 1, // 资产
  1233. 'product' => $product_type, // 场景
  1234. 'parent_id' => $folder_id,
  1235. 'level' => 2,
  1236. 'product_name' => $product_name,
  1237. 'url' => $url,
  1238. 'pic_prompt' => $pic_prompt,
  1239. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1240. 'sort_order' => time(),
  1241. 'is_deleted' => 0,
  1242. 'pic_task_status' => '生成成功',
  1243. 'created_at' => date('Y-m-d H:i:s'),
  1244. 'updated_at' => date('Y-m-d H:i:s')
  1245. ]);
  1246. }
  1247. // 建立或更新绑定关系
  1248. $existing_mapping = DB::table('mp_script_product_mappings')
  1249. ->where('script_id', $script_id)
  1250. ->where('product_id', $product_id)
  1251. ->where('episode_number', $episode_number)
  1252. ->first();
  1253. if (!$existing_mapping) {
  1254. // 创建绑定关系
  1255. DB::table('mp_script_product_mappings')->insert([
  1256. 'script_id' => $script_id,
  1257. 'product_id' => $product_id,
  1258. 'episode_number' => $episode_number,
  1259. 'created_at' => date('Y-m-d H:i:s'),
  1260. 'updated_at' => date('Y-m-d H:i:s')
  1261. ]);
  1262. }
  1263. }
  1264. }
  1265. }
  1266. } catch (\Exception $e) {
  1267. dLog('anime')->error('更新剧集场景失败', [
  1268. 'anime_id' => $anime_id,
  1269. 'episode_id' => $episode_id,
  1270. 'error' => $e->getMessage()
  1271. ]);
  1272. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1273. }
  1274. return true;
  1275. }
  1276. public function changeEpisodeProps($data) {
  1277. $anime_id = getProp($data, 'anime_id');
  1278. $episode_id = getProp($data, 'episode_id');
  1279. $target_props = getProp($data, 'props');
  1280. $is_deleted = getProp($data, 'is_deleted', 0);
  1281. // 参数验证
  1282. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1283. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1284. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1285. // 验证剧集是否存在
  1286. $episode = DB::table('mp_anime_episodes')
  1287. ->where('anime_id', $anime_id)
  1288. ->where('id', $episode_id)
  1289. ->first();
  1290. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1291. $props = json_decode(getProp($episode, 'props'), true);
  1292. // 获取anime信息,检查是否有关联的script_id
  1293. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1294. if (!$anime) Utils::throwError('20003:动漫不存在');
  1295. $script_id = getProp($anime, 'script_id');
  1296. $episode_number = getProp($episode, 'episode_number', 1);
  1297. $uid = Site::getUid();
  1298. $cpid = Site::getCpid();
  1299. try {
  1300. $target_prop_name = getProp($target_props, 'prop');
  1301. // 如果是删除操作
  1302. if ($is_deleted == 1) {
  1303. // 从道具列表中移除该道具
  1304. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1305. return getProp($prop, 'prop') !== $target_prop_name;
  1306. }));
  1307. // 更新道具列表
  1308. $result = DB::table('mp_anime_episodes')
  1309. ->where('anime_id', $anime_id)
  1310. ->where('id', $episode_id)
  1311. ->update([
  1312. 'props' => json_encode($props, 256),
  1313. 'updated_at' => date('Y-m-d H:i:s')
  1314. ]);
  1315. if ($result === false) {
  1316. Utils::throwError('20003:删除道具失败');
  1317. }
  1318. } else {
  1319. // 新增或更新操作
  1320. $prop_found = false;
  1321. $is_new_prop = false;
  1322. // 查找并更新已存在的道具
  1323. foreach($props as &$prop) {
  1324. if (getProp($prop, 'prop') === $target_prop_name) {
  1325. $prop = $target_props;
  1326. $prop_found = true;
  1327. break;
  1328. }
  1329. }
  1330. // 如果道具不存在,则新增
  1331. if (!$prop_found) {
  1332. $props[] = $target_props;
  1333. $is_new_prop = true;
  1334. }
  1335. // 更新道具列表
  1336. $result = DB::table('mp_anime_episodes')
  1337. ->where('anime_id', $anime_id)
  1338. ->where('id', $episode_id)
  1339. ->update([
  1340. 'props' => json_encode($props, 256),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. if ($result === false) {
  1344. Utils::throwError('20003:更新道具列表失败');
  1345. }
  1346. // 如果有关联的script_id,则同步到mp_products表
  1347. if ($script_id) {
  1348. // 查询剧本信息
  1349. $script = DB::table('mp_scripts')
  1350. ->where('id', $script_id)
  1351. ->where('is_deleted', 0)
  1352. ->first();
  1353. if ($script) {
  1354. $script_name = $script->script_name ?? 'script_' . $script_id;
  1355. $product_name = getProp($target_props, 'prop');
  1356. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1357. $url = getProp($target_props, 'url', '');
  1358. $product_type = 3; // 3=道具
  1359. // 查找或创建以script_name命名的文件夹
  1360. $folder = DB::table('mp_products')
  1361. ->where('cpid', $cpid)
  1362. ->where('type', 2) // 文件夹类型
  1363. ->where('product', $product_type) // 道具类型
  1364. ->where('product_name', $script_name)
  1365. ->where('parent_id', 0)
  1366. ->where('is_deleted', 0)
  1367. ->first();
  1368. if (!$folder) {
  1369. // 创建文件夹
  1370. $folder_id = DB::table('mp_products')->insertGetId([
  1371. 'user_id' => $uid,
  1372. 'cpid' => $cpid,
  1373. 'type' => 2, // 文件夹
  1374. 'product' => $product_type, // 道具类型
  1375. 'parent_id' => 0,
  1376. 'level' => 1,
  1377. 'product_name' => $script_name,
  1378. 'sort_order' => time(),
  1379. 'is_deleted' => 0,
  1380. 'created_at' => date('Y-m-d H:i:s'),
  1381. 'updated_at' => date('Y-m-d H:i:s')
  1382. ]);
  1383. } else {
  1384. $folder_id = $folder->id;
  1385. }
  1386. // 查找该文件夹下是否已存在同名资产
  1387. $existing_product = DB::table('mp_products')
  1388. ->where('cpid', $cpid)
  1389. ->where('type', 1) // 资产类型
  1390. ->where('product', $product_type)
  1391. ->where('parent_id', $folder_id)
  1392. ->where('product_name', $product_name)
  1393. ->where('is_deleted', 0)
  1394. ->first();
  1395. if ($existing_product) {
  1396. // 更新已存在的资产
  1397. $updateData = [
  1398. 'pic_task_status' => '生成成功'
  1399. ];
  1400. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1401. if ($url) $updateData['url'] = $url;
  1402. // 处理versions字段
  1403. $versions = getProp($target_props, 'versions', []);
  1404. if ($versions && is_array($versions)) {
  1405. $updateData['versions'] = json_encode($versions, 256);
  1406. }
  1407. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1408. DB::table('mp_products')
  1409. ->where('id', $existing_product->id)
  1410. ->update($updateData);
  1411. $product_id = $existing_product->id;
  1412. } else {
  1413. // 创建新资产
  1414. $versions = getProp($target_props, 'versions', []);
  1415. $product_id = DB::table('mp_products')->insertGetId([
  1416. 'user_id' => $uid,
  1417. 'cpid' => $cpid,
  1418. 'type' => 1, // 资产
  1419. 'product' => $product_type, // 道具
  1420. 'parent_id' => $folder_id,
  1421. 'level' => 2,
  1422. 'product_name' => $product_name,
  1423. 'url' => $url,
  1424. 'pic_prompt' => $pic_prompt,
  1425. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1426. 'sort_order' => time(),
  1427. 'is_deleted' => 0,
  1428. 'pic_task_status' => '生成成功',
  1429. 'created_at' => date('Y-m-d H:i:s'),
  1430. 'updated_at' => date('Y-m-d H:i:s')
  1431. ]);
  1432. }
  1433. // 建立或更新绑定关系
  1434. $existing_mapping = DB::table('mp_script_product_mappings')
  1435. ->where('script_id', $script_id)
  1436. ->where('product_id', $product_id)
  1437. ->where('episode_number', $episode_number)
  1438. ->first();
  1439. if (!$existing_mapping) {
  1440. // 创建绑定关系
  1441. DB::table('mp_script_product_mappings')->insert([
  1442. 'script_id' => $script_id,
  1443. 'product_id' => $product_id,
  1444. 'episode_number' => $episode_number,
  1445. 'created_at' => date('Y-m-d H:i:s'),
  1446. 'updated_at' => date('Y-m-d H:i:s')
  1447. ]);
  1448. }
  1449. }
  1450. }
  1451. }
  1452. } catch (\Exception $e) {
  1453. dLog('anime')->error('更新剧集道具失败', [
  1454. 'anime_id' => $anime_id,
  1455. 'episode_id' => $episode_id,
  1456. 'error' => $e->getMessage()
  1457. ]);
  1458. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1459. }
  1460. return true;
  1461. }
  1462. public function editSegment($data) {
  1463. $segment_id = getProp($data, 'segment_id');
  1464. $segment_content = getProp($data, 'segment_content');
  1465. $image_url = getProp($data, 'image_url');
  1466. $video_url = getProp($data, 'video_url');
  1467. // 参数验证
  1468. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1469. // 验证分镜是否存在
  1470. $segment = DB::table('mp_episode_segments')
  1471. ->where('segment_id', $segment_id)
  1472. ->first();
  1473. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1474. $dubTaskId = 0;
  1475. try {
  1476. DB::beginTransaction();
  1477. // 准备更新数据
  1478. $update_data = [
  1479. 'updated_at' => date('Y-m-d H:i:s')
  1480. ];
  1481. if ($segment_content) {
  1482. // 先将segment_content赋值到update_data
  1483. $update_data['segment_content'] = $segment_content;
  1484. // 使用现有方法分析segment_content,提取各个字段
  1485. $this->handleSegmentContent($update_data);
  1486. // 如果有对话内容,创建视频配音合成任务
  1487. $dialogue = getProp($update_data, 'dialogue');
  1488. if (!empty($dialogue)) {
  1489. $now = date('Y-m-d H:i:s');
  1490. $generate_json = [
  1491. 'text' => $dialogue,
  1492. 'role' => getProp($update_data, 'voice_actor'),
  1493. 'voice_type' => getProp($update_data, 'voice_type'),
  1494. 'voice_name' => getProp($update_data, 'voice_name'),
  1495. 'emotion' => getProp($update_data, 'emotion'),
  1496. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1497. 'gender' => getProp($update_data, 'gender'),
  1498. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1499. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1500. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1501. 'pitch' => getProp($update_data, 'pitch', 0),
  1502. ];
  1503. // 插入视频配音合成任务
  1504. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1505. 'alias_segment_id' => $segment_id,
  1506. 'generate_status' => '执行中',
  1507. 'audio_url' => '',
  1508. 'generate_json' => json_encode($generate_json, 256),
  1509. 'created_at' => $now,
  1510. 'updated_at' => $now,
  1511. ]);
  1512. if (!$dubTaskId) {
  1513. Utils::throwError('20003:创建配音任务失败!');
  1514. }
  1515. $update_data['audio_url'] = '';
  1516. } else {
  1517. // dialogue为空时,直接写入默认音频信息
  1518. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1519. $update_data['audio_duration'] = 2.0;
  1520. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1521. }
  1522. }
  1523. if ($image_url) {
  1524. $update_data['img_url'] = $image_url;
  1525. // 同时写入一个简单的图片生成任务
  1526. $pic_task = [
  1527. 'alias_segment_id' => $segment_id,
  1528. 'ref_img_url' => json_encode([]),
  1529. 'status' => 'success',
  1530. 'result_url' => json_encode([$image_url], 256),
  1531. 'model' => '',
  1532. 'created_at' => date('Y-m-d H:i:s'),
  1533. 'updated_at' => date('Y-m-d H:i:s'),
  1534. ];
  1535. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1536. }
  1537. if ($video_url) {
  1538. $update_data['origin_video_url'] = $video_url;
  1539. $compressed_video_url = compressVideo($video_url);
  1540. $update_data['current_type'] = 2;
  1541. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1542. // 同时写入一个简单的视频生成任务
  1543. $video_task = [
  1544. 'alias_segment_id' => $segment_id,
  1545. 'status' => 'success',
  1546. 'result_url' => $update_data['origin_video_url'],
  1547. 'compressed_url' => $update_data['video_url'],
  1548. 'created_at' => date('Y-m-d H:i:s'),
  1549. 'updated_at' => date('Y-m-d H:i:s'),
  1550. ];
  1551. DB::table('mp_generate_video_tasks')->insert($video_task);
  1552. }
  1553. // 更新分镜信息
  1554. $result = DB::table('mp_episode_segments')
  1555. ->where('segment_id', $segment_id)
  1556. ->update($update_data);
  1557. if ($result === false) {
  1558. Utils::throwError('20003:更新分镜剧本失败');
  1559. }
  1560. DB::commit();
  1561. // 如果有创建音频生成任务则调用API
  1562. if ($dubTaskId) {
  1563. // 请求远程服务器执行生成
  1564. $client = new Client(['timeout' => 300, 'verify' => false]);
  1565. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1566. $response = $result->getBody()->getContents();
  1567. $response_arr = json_decode($response, true);
  1568. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1569. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1570. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1571. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1572. Utils::throwError('20003:火山生成音频失败');
  1573. }
  1574. }
  1575. return true;
  1576. } catch (\Exception $e) {
  1577. DB::rollBack();
  1578. dLog('anime')->error('更新分镜剧本失败', [
  1579. 'segment_id' => $segment_id,
  1580. 'error' => $e->getMessage()
  1581. ]);
  1582. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1583. }
  1584. }
  1585. public function batchSetSegmentPics($data) {
  1586. $anime_id = getProp($data, 'anime_id');
  1587. $episode_id = getProp($data, 'episode_id');
  1588. $ratio = getProp($data, 'ratio');
  1589. $dimensions = $this->getRatioDimensions($ratio);
  1590. $width = $dimensions['width'];
  1591. $height = $dimensions['height'];
  1592. if (!$anime_id || !$episode_id) {
  1593. Utils::throwError('1002:请选择剧集');
  1594. }
  1595. // 获取剧集信息
  1596. $episode = DB::table('mp_anime_episodes')
  1597. ->where('anime_id', $anime_id)
  1598. ->where('id', $episode_id)
  1599. ->where('is_default', 1)
  1600. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1601. ->first();
  1602. if (!$episode) {
  1603. Utils::throwError('20003:该剧集不存在');
  1604. }
  1605. $model = getProp($data, 'model');
  1606. if (!$model) {
  1607. $model = getProp($episode, 'image_model');
  1608. if (!$model) {
  1609. // episode表也没有,使用默认值
  1610. $model = 'doubao-seedream-5-0-lite-260128';
  1611. }
  1612. }
  1613. // 验证模型是否在可用模型表中
  1614. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1615. $model = 'doubao-seedream-5-0-lite-260128';
  1616. }
  1617. $roles = json_decode(getProp($episode, 'roles'), true);
  1618. if (!$roles) {
  1619. Utils::throwError('20003:角色信息格式错误');
  1620. }
  1621. // 构建角色名称到参考图的映射
  1622. $role_map = [];
  1623. foreach ($roles as $role) {
  1624. $role_name = getProp($role, 'role');
  1625. $role_url = getProp($role, 'url');
  1626. if (!empty($role_name) && !empty($role_url)) {
  1627. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1628. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1629. // $role_map[$base_name] = $role_url;
  1630. // 同时保存完整名称的映射
  1631. $role_map[$role_name] = $role_url;
  1632. }
  1633. }
  1634. $scenes = json_decode(getProp($episode, 'roles'), true);
  1635. if (!$scenes) {
  1636. Utils::throwError('20003:场景信息格式错误');
  1637. }
  1638. // 构建角色名称到参考图的映射
  1639. $scene_map = [];
  1640. foreach ($scenes as $scene) {
  1641. $scene_name = getProp($scene, 'scene');
  1642. $scene_url = getProp($scene, 'url');
  1643. if (!empty($scene_name) && !empty($scene_url)) {
  1644. $scene_map[$scene_name] = $scene_url;
  1645. }
  1646. }
  1647. // 获取所有分镜信息
  1648. $segments = DB::table('mp_episode_segments')
  1649. ->where('anime_id', $anime_id)
  1650. ->where('episode_id', $episode_id)
  1651. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1652. ->orderBy('segment_number')
  1653. ->get()
  1654. ->toArray();
  1655. if (empty($segments)) {
  1656. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1657. }
  1658. // 保存图片比例
  1659. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1660. $updated_segments = [];
  1661. $failed_segments = [];
  1662. // 批量为每个分镜生成图片任务
  1663. foreach ($segments as $segment) {
  1664. $segment_id = $segment->segment_id;
  1665. $segment_content = $segment->segment_content;
  1666. if (empty($segment_content)) {
  1667. $failed_segments[] = [
  1668. 'segment_id' => $segment_id,
  1669. 'error' => '分镜内容为空'
  1670. ];
  1671. continue;
  1672. }
  1673. try {
  1674. $dubTaskId = 0;
  1675. // 解析分镜内容,提取画面描述作为主要提示词
  1676. $prompt = $segment_content;
  1677. $ref_img_urls = [];
  1678. // 分镜场景
  1679. $scene = getProp($segment, 'scene');
  1680. $matched_scene = '';
  1681. if (isset($scene_map[$scene])) {
  1682. $img_index = count($ref_img_urls) + 1;
  1683. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1684. $ref_img_urls[] = $scene_map[$scene];
  1685. $matched_scene = $scene;
  1686. }
  1687. // 分镜角色
  1688. $characters = getProp($segment, 'characters');
  1689. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1690. $roles = explode(',', $characters);
  1691. // 从分镜内容中提取涉及的角色
  1692. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1693. // 获取匹配角色的参考图
  1694. foreach ($segment_characters as $character) {
  1695. if (isset($role_map[$character])) {
  1696. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1697. $img_index = count($ref_img_urls) + 1;
  1698. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1699. $ref_img_urls[] = $role_map[$character];
  1700. }
  1701. }
  1702. // 如果没有找到匹配的角色参考图,不使用参考图
  1703. if (empty($ref_img_urls)) {
  1704. $ref_img_urls = [];
  1705. }
  1706. // 准备生成任务参数
  1707. $params = [
  1708. 'model' => $model,
  1709. 'alias_segment_id' => $segment_id,
  1710. 'prompt' => $prompt,
  1711. 'ref_img_urls' => $ref_img_urls,
  1712. 'width' => $width,
  1713. 'height' => $height,
  1714. ];
  1715. // 优化提示词(不要生成字幕)
  1716. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1717. // $task_id = mt_rand(100000, 999999);
  1718. // 调用AI图片生成服务
  1719. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1720. $task_id = $task->id;
  1721. if (!$task_id) {
  1722. $failed_segments[] = [
  1723. 'segment_id' => $segment_id,
  1724. 'error' => '创建生成任务失败'
  1725. ];
  1726. continue;
  1727. }
  1728. $update_data = [
  1729. 'pic_task_id' => $task_id,
  1730. 'pic_task_status' => '生成中',
  1731. 'audio_url' => '',
  1732. 'updated_at' => date('Y-m-d H:i:s')
  1733. ];
  1734. // 如果有对话内容,创建视频配音合成任务
  1735. $dialogue = getProp($segment, 'dialogue');
  1736. if (!empty($dialogue)) {
  1737. $now = date('Y-m-d H:i:s');
  1738. $generate_json = [
  1739. 'text' => $dialogue,
  1740. 'role' => getProp($segment, 'voice_actor'),
  1741. 'voice_type' => getProp($segment, 'voice_type'),
  1742. 'voice_name' => getProp($segment, 'voice_name'),
  1743. 'emotion' => getProp($segment, 'emotion'),
  1744. 'emotion_type' => getProp($segment, 'emotion_type'),
  1745. 'gender' => getProp($segment, 'gender'),
  1746. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1747. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1748. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1749. 'pitch' => getProp($segment, 'pitch', 0),
  1750. ];
  1751. // 插入视频配音合成任务
  1752. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1753. 'alias_segment_id' => $segment_id,
  1754. 'generate_status' => '执行中',
  1755. 'audio_url' => '',
  1756. 'generate_json' => json_encode($generate_json, 256),
  1757. 'created_at' => $now,
  1758. 'updated_at' => $now,
  1759. ]);
  1760. if (!$dubTaskId) {
  1761. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1762. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1763. // Utils::throwError('20003:创建配音任务失败!');
  1764. }
  1765. } else {
  1766. // dialogue为空时,直接写入默认音频信息到分镜表
  1767. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1768. $update_data['audio_duration'] = 2.0;
  1769. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1770. }
  1771. // 更新分镜的任务信息
  1772. $update_result = DB::table('mp_episode_segments')
  1773. ->where('segment_id', $segment_id)
  1774. ->update($update_data);
  1775. // 如果是第一集的首帧图片,则存入待更新数组
  1776. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1777. Redis::sadd('anime_first_frame_urls', $segment_id);
  1778. }
  1779. if ($update_result) {
  1780. $updated_segments[] = [
  1781. 'segment_id' => $segment_id,
  1782. 'task_id' => $task_id,
  1783. 'status' => '生成中',
  1784. 'matched_scenes' => $matched_scene,
  1785. 'matched_roles' => $segment_characters,
  1786. 'ref_urls_count' => count($ref_img_urls)
  1787. ];
  1788. } else {
  1789. $failed_segments[] = [
  1790. 'segment_id' => $segment_id,
  1791. 'error' => '更新分镜任务状态失败'
  1792. ];
  1793. }
  1794. if ($dubTaskId) {
  1795. sleep(1);
  1796. // 请求远程服务器执行生成
  1797. $client = new Client(['timeout' => 300, 'verify' => false]);
  1798. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1799. $response = $result->getBody()->getContents();
  1800. $response_arr = json_decode($response, true);
  1801. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1802. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1803. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1804. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1805. }
  1806. }
  1807. } catch (\Exception $e) {
  1808. $failed_segments[] = [
  1809. 'segment_id' => $segment_id,
  1810. 'error' => $e->getMessage()
  1811. ];
  1812. }
  1813. }
  1814. // 更新剧集生成状态
  1815. if (!empty($updated_segments)) {
  1816. DB::table('mp_anime_episodes')
  1817. ->where('id', $episode_id)
  1818. ->update([
  1819. 'is_generated' => 1,
  1820. 'updated_at' => date('Y-m-d H:i:s')
  1821. ]);
  1822. }
  1823. return [
  1824. 'success_count' => count($updated_segments),
  1825. 'failed_count' => count($failed_segments),
  1826. 'success_segments' => $updated_segments,
  1827. 'failed_segments' => $failed_segments,
  1828. 'total_segments' => count($segments)
  1829. ];
  1830. }
  1831. public function reGenerateSegment($data) {
  1832. $segment_id = getProp($data, 'segment_id');
  1833. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1834. $anime_id = getProp($segment, 'anime_id');
  1835. $episode_id = getProp($segment, 'episode_id');
  1836. $episode_number = getProp($segment, 'episode_number');
  1837. $segment_content = getProp($data, 'segment_content');
  1838. $ratio = getProp($data, 'ratio');
  1839. if (!$ratio) {
  1840. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1841. if (!$ratio) $ratio = '9:16';
  1842. }
  1843. $dimensions = $this->getRatioDimensions($ratio);
  1844. $width = $dimensions['width'];
  1845. $height = $dimensions['height'];
  1846. if (!$anime_id || !$episode_id) {
  1847. Utils::throwError('1002:请选择分镜');
  1848. }
  1849. // 使用文生文模型重新解析segment_content
  1850. if (!empty($segment_content)) {
  1851. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1852. }
  1853. // 获取动漫的角色信息(包含参考图)
  1854. $anime = DB::table('mp_animes')
  1855. ->where('id', $anime_id)
  1856. ->select('roles', 'scenes')
  1857. ->first();
  1858. if (!$anime || !$anime->roles) {
  1859. Utils::throwError('20003:未找到角色信息');
  1860. }
  1861. $roles = json_decode($anime->roles, true);
  1862. if (!$roles) {
  1863. Utils::throwError('20003:角色信息格式错误');
  1864. }
  1865. // 构建角色名称到参考图的映射
  1866. $role_map = [];
  1867. foreach ($roles as $role) {
  1868. $role_name = getProp($role, 'role');
  1869. $role_url = getProp($role, 'url');
  1870. if (!empty($role_name) && !empty($role_url)) {
  1871. $role_map[$role_name] = $role_url;
  1872. }
  1873. }
  1874. $scenes = json_decode($anime->scenes, true);
  1875. if (!$scenes) {
  1876. Utils::throwError('20003:角色信息格式错误');
  1877. }
  1878. // 构建角色名称到参考图的映射
  1879. $scene_map = [];
  1880. foreach ($scenes as $scene) {
  1881. $scene_name = getProp($scene, 'scene');
  1882. $scene_url = getProp($scene, 'url');
  1883. if (!empty($scene_name) && !empty($scene_url)) {
  1884. $scene_map[$scene_name] = $scene_url;
  1885. }
  1886. }
  1887. $segment_id = $segment->segment_id;
  1888. $original_segment_content = $segment->segment_content;
  1889. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1890. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1891. if (empty($final_segment_content)) {
  1892. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1893. }
  1894. try {
  1895. $dubTaskId = 0;
  1896. // 分镜剧本数组
  1897. $update_data = [
  1898. 'segment_content' => $final_segment_content,
  1899. 'pic_task_status' => '生成中',
  1900. 'updated_at' => date('Y-m-d H:i:s')
  1901. ];
  1902. // 解析分镜内容,提取画面描述作为主要提示词
  1903. $prompt = $final_segment_content;
  1904. $ref_img_urls = [];
  1905. // 分镜场景
  1906. $scene = getProp($data, 'scene');
  1907. if ($scene) {
  1908. $matched_scene = '';
  1909. if (isset($scene_map[$scene])) {
  1910. $img_index = count($ref_img_urls) + 1;
  1911. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1912. $ref_img_urls[] = $scene_map[$scene];
  1913. $matched_scene = $scene;
  1914. }
  1915. $update_data['scene'] = $scene;
  1916. }
  1917. // 分镜角色
  1918. $characters = getProp($data, 'characters');
  1919. if ($characters) {
  1920. $update_data['characters'] = $characters;
  1921. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1922. $characters = explode(',', $characters);
  1923. // 从分镜内容中提取涉及的角色
  1924. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1925. // 获取匹配角色的参考图
  1926. foreach ($segment_characters as $character) {
  1927. if (isset($role_map[$character])) {
  1928. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1929. $img_index = count($ref_img_urls) + 1;
  1930. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1931. $ref_img_urls[] = $role_map[$character];
  1932. }
  1933. }
  1934. }
  1935. // 如果没有找到匹配的角色参考图,不使用参考图
  1936. if (empty($ref_img_urls)) {
  1937. $ref_img_urls = [];
  1938. }
  1939. // 准备生成任务参数
  1940. $params = [
  1941. 'alias_segment_id' => $segment_id,
  1942. 'prompt' => $prompt,
  1943. 'ref_img_urls' => $ref_img_urls,
  1944. 'width' => $width,
  1945. 'height' => $height,
  1946. ];
  1947. // 优化提示词(不要生成字幕)
  1948. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1949. // 调用AI图片生成服务
  1950. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1951. $task_id = $task->id;
  1952. if (!$task_id) {
  1953. Utils::throwError('20003:创建生成任务失败!');
  1954. }
  1955. $update_data['pic_task_id'] = $task_id;
  1956. // 更新分镜剧本信息
  1957. $this->handleSegmentContent($update_data);
  1958. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1959. if ($segment_content) {
  1960. $dialogue = getProp($update_data, 'dialogue');
  1961. if (!empty($dialogue)) {
  1962. $now = date('Y-m-d H:i:s');
  1963. $generate_json = [
  1964. 'text' => $dialogue,
  1965. 'role' => getProp($update_data, 'voice_actor'),
  1966. 'voice_type' => getProp($update_data, 'voice_type'),
  1967. 'voice_name' => getProp($update_data, 'voice_name'),
  1968. 'emotion' => getProp($update_data, 'emotion'),
  1969. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1970. 'gender' => getProp($update_data, 'gender'),
  1971. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1972. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1973. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1974. 'pitch' => getProp($update_data, 'pitch', 0),
  1975. ];
  1976. // 插入视频配音合成任务
  1977. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1978. 'alias_segment_id' => $segment_id,
  1979. 'generate_status' => '执行中',
  1980. 'audio_url' => '',
  1981. 'generate_json' => json_encode($generate_json, 256),
  1982. 'created_at' => date('Y-m-d H:i:s'),
  1983. 'updated_at' => date('Y-m-d H:i:s'),
  1984. ]);
  1985. if (!$dubTaskId) {
  1986. Utils::throwError('20003:创建配音任务失败!');
  1987. }
  1988. $update_data['audio_url'] = '';
  1989. } else {
  1990. // dialogue为空时,直接写入默认音频信息
  1991. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1992. $update_data['audio_duration'] = 2.0;
  1993. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1994. }
  1995. }
  1996. $boolen = DB::table('mp_episode_segments')
  1997. ->where('segment_id', $segment_id)
  1998. ->update($update_data);
  1999. // 如果是第一集的首帧图片,则存入待更新数组
  2000. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2001. Redis::sadd('anime_first_frame_urls', $segment_id);
  2002. }
  2003. if ($dubTaskId) {
  2004. // 请求远程服务器执行生成
  2005. $client = new Client(['timeout' => 300, 'verify' => false]);
  2006. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2007. $response = $result->getBody()->getContents();
  2008. $response_arr = json_decode($response, true);
  2009. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2010. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2011. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2012. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2013. Utils::throwError('20003:火山生成音频失败');
  2014. }
  2015. }
  2016. } catch (\Exception $e) {
  2017. $failed_segments[] = [
  2018. 'segment_id' => $segment_id,
  2019. 'error' => $e->getMessage()
  2020. ];
  2021. }
  2022. // 创建任务之后先暂停10s等待异步任务完成
  2023. sleep(10);
  2024. $img_url = $this->loopGetPicTaskResult($task_id);
  2025. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2026. // 图片生成后新增对话记录
  2027. try {
  2028. $uid = Site::getUid();
  2029. $now = date('Y-m-d H:i:s');
  2030. // 使用AI反推图片提示词
  2031. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2032. // 保存对话记录
  2033. $records = [
  2034. [
  2035. 'uid' => $uid,
  2036. 'anime_id' => $anime_id,
  2037. 'sequence' => $episode_number,
  2038. 'role' => 'user',
  2039. 'content' => '重新生成',
  2040. 'segment_id' => $segment_id,
  2041. 'image_url' => '',
  2042. 'created_at' => $now,
  2043. 'updated_at' => $now
  2044. ],
  2045. [
  2046. 'uid' => $uid,
  2047. 'anime_id' => $anime_id,
  2048. 'sequence' => $episode_number,
  2049. 'role' => 'assistant',
  2050. 'content' => $pic_prompt,
  2051. 'segment_id' => $segment_id,
  2052. 'image_url' => $img_url,
  2053. 'created_at' => $now,
  2054. 'updated_at' => $now
  2055. ]
  2056. ];
  2057. DB::table('mp_anime_records')->insert($records);
  2058. } catch (\Exception $e) {
  2059. // 记录日志但不影响主流程
  2060. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2061. 'segment_id' => $segment_id,
  2062. 'img_url' => $img_url
  2063. ]);
  2064. }
  2065. return $img_url;
  2066. }
  2067. public function addSegment($data) {
  2068. $prev_segment_id = getProp($data, 'prev_segment_id');
  2069. $img_url = getProp($data, 'img_url');
  2070. $video_url = getProp($data, 'video_url');
  2071. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2072. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2073. $anime_id = getProp($segment, 'anime_id');
  2074. $episode_id = getProp($segment, 'episode_id');
  2075. $episode_number = getProp($segment, 'episode_number');
  2076. $segment_number = getProp($segment, 'segment_number');
  2077. $new_segment_number = $segment_number + 1;
  2078. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2079. // 分镜剧本数组
  2080. $insert_data = [
  2081. 'anime_id' => $anime_id,
  2082. 'episode_id' => $episode_id,
  2083. 'episode_number' => $episode_number,
  2084. 'act_number' => getProp($segment, 'act_number'),
  2085. 'act_title' => getProp($segment, 'act_title'),
  2086. 'segment_id' => $segment_id,
  2087. 'segment_number' => $new_segment_number,
  2088. 'segment_content' => '',
  2089. 'img_url' => '',
  2090. 'video_url' => '',
  2091. 'created_at' => date('Y-m-d H:i:s'),
  2092. 'updated_at' => date('Y-m-d H:i:s')
  2093. ];
  2094. if ($img_url) $insert_data['img_url'] = $img_url;
  2095. if ($video_url) {
  2096. $insert_data['origin_video_url'] = $video_url;
  2097. $insert_data['current_type'] = 2;
  2098. $compressed_video_url = compressVideo($video_url);
  2099. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2100. }
  2101. try {
  2102. DB::beginTransaction();
  2103. // 先更新序号
  2104. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2105. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2106. if (!$id) {
  2107. Utils::throwError('20003:新增分镜失败!');
  2108. }
  2109. }catch (\Exception $e) {
  2110. DB::rollBack();
  2111. Utils::throwError('20003:'.$e->getMessage());
  2112. }
  2113. DB::commit();
  2114. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2115. $segment = $segment ? (array)$segment : [];
  2116. return $segment;
  2117. // 以下代码暂弃用
  2118. $anime_id = getProp($segment, 'anime_id');
  2119. $episode_id = getProp($segment, 'episode_id');
  2120. $episode_number = getProp($segment, 'episode_number');
  2121. $segment_number = getProp($segment, 'segment_number');
  2122. $segment_content = getProp($data, 'segment_content');
  2123. $img_url = getProp($data, 'img_url');
  2124. $video_url = getProp($data, 'video_url');
  2125. $ratio = getProp($data, 'ratio');
  2126. $dimensions = $this->getRatioDimensions($ratio);
  2127. $width = $dimensions['width'];
  2128. $height = $dimensions['height'];
  2129. if (!$anime_id || !$episode_id) {
  2130. Utils::throwError('1002:请选择分镜');
  2131. }
  2132. // 使用文生文模型重新解析segment_content
  2133. if (!empty($segment_content)) {
  2134. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2135. }
  2136. // 获取动漫的角色信息(包含参考图)
  2137. $anime = DB::table('mp_animes')
  2138. ->where('id', $anime_id)
  2139. ->select('roles', 'scenes')
  2140. ->first();
  2141. if (!$anime || !$anime->roles) {
  2142. Utils::throwError('20003:未找到角色信息');
  2143. }
  2144. $roles = json_decode($anime->roles, true);
  2145. if (!$roles) {
  2146. Utils::throwError('20003:角色信息格式错误');
  2147. }
  2148. // 构建角色名称到参考图的映射
  2149. $role_map = [];
  2150. foreach ($roles as $role) {
  2151. $role_name = getProp($role, 'role');
  2152. $role_url = getProp($role, 'url');
  2153. if (!empty($role_name) && !empty($role_url)) {
  2154. $role_map[$role_name] = $role_url;
  2155. }
  2156. }
  2157. $scenes = json_decode($anime->scenes, true);
  2158. if (!$scenes) {
  2159. Utils::throwError('20003:角色信息格式错误');
  2160. }
  2161. // 构建角色名称到参考图的映射
  2162. $scene_map = [];
  2163. foreach ($scenes as $scene) {
  2164. $scene_name = getProp($scene, 'scene');
  2165. $scene_url = getProp($scene, 'url');
  2166. if (!empty($scene_name) && !empty($scene_url)) {
  2167. $scene_map[$scene_name] = $scene_url;
  2168. }
  2169. }
  2170. $segment_id = $segment->segment_id;
  2171. $original_segment_content = $segment->segment_content;
  2172. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2173. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2174. if (empty($final_segment_content)) {
  2175. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2176. }
  2177. try {
  2178. $dubTaskId = 0;
  2179. DB::beginTransaction();
  2180. $new_segment_number = $segment_number + 1;
  2181. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2182. // 分镜剧本数组
  2183. $insert_data = [
  2184. 'anime_id' => $anime_id,
  2185. 'episode_id' => $episode_id,
  2186. 'episode_number' => $episode_number,
  2187. 'act_number' => getProp($segment, 'act_number'),
  2188. 'act_title' => getProp($segment, 'act_title'),
  2189. 'segment_id' => $segment_id,
  2190. 'segment_number' => $new_segment_number,
  2191. 'segment_content' => $final_segment_content,
  2192. 'img_url' => $img_url,
  2193. 'video_url' => $video_url,
  2194. 'created_at' => date('Y-m-d H:i:s'),
  2195. 'updated_at' => date('Y-m-d H:i:s')
  2196. ];
  2197. // 更新分镜剧本信息
  2198. $this->handleSegmentContent($insert_data);
  2199. // 如果有对话内容,创建视频配音合成任务
  2200. $dialogue = getProp($insert_data, 'dialogue');
  2201. if (!empty($dialogue)) {
  2202. $now = date('Y-m-d H:i:s');
  2203. $generate_json = [
  2204. 'text' => $dialogue,
  2205. 'role' => getProp($insert_data, 'voice_actor'),
  2206. 'voice_type' => getProp($insert_data, 'voice_type'),
  2207. 'voice_name' => getProp($insert_data, 'voice_name'),
  2208. 'emotion' => getProp($insert_data, 'emotion'),
  2209. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2210. 'gender' => getProp($insert_data, 'gender'),
  2211. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2212. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2213. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2214. 'pitch' => getProp($insert_data, 'pitch', 0),
  2215. ];
  2216. // 插入视频配音合成任务
  2217. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2218. 'alias_segment_id' => $segment_id,
  2219. 'generate_status' => '执行中',
  2220. 'audio_url' => '',
  2221. 'generate_json' => json_encode($generate_json, 256),
  2222. 'created_at' => $now,
  2223. 'updated_at' => $now,
  2224. ]);
  2225. if (!$dubTaskId) {
  2226. Utils::throwError('20003:创建配音任务失败!');
  2227. }
  2228. $insert_data['audio_url'] = '';
  2229. } else {
  2230. // dialogue为空时,直接写入默认音频信息
  2231. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2232. $insert_data['audio_duration'] = 2.0;
  2233. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2234. }
  2235. // 如果没有上传图片则使用当前描述进行生成
  2236. if (!$img_url) {
  2237. // 解析分镜内容,提取画面描述作为主要提示词
  2238. $prompt = $final_segment_content;
  2239. $ref_img_urls = [];
  2240. // 分镜场景
  2241. $scene = getProp($insert_data, 'scene');
  2242. if ($scene) {
  2243. $matched_scene = '';
  2244. if (isset($scene_map[$scene])) {
  2245. $img_index = count($ref_img_urls) + 1;
  2246. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2247. $ref_img_urls[] = $scene_map[$scene];
  2248. $matched_scene = $scene;
  2249. }
  2250. $update_data['scene'] = $scene;
  2251. }
  2252. // 分镜角色
  2253. $characters = getProp($insert_data, 'characters');
  2254. if ($characters) {
  2255. $update_data['characters'] = $characters;
  2256. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2257. $characters = explode(',', $characters);
  2258. // 从分镜内容中提取涉及的角色
  2259. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2260. // 获取匹配角色的参考图
  2261. foreach ($segment_characters as $character) {
  2262. if (isset($role_map[$character])) {
  2263. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2264. $img_index = count($ref_img_urls) + 1;
  2265. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2266. $ref_img_urls[] = $role_map[$character];
  2267. }
  2268. }
  2269. }
  2270. // 如果没有找到匹配的角色参考图,不使用参考图
  2271. if (empty($ref_img_urls)) {
  2272. $ref_img_urls = [];
  2273. }
  2274. // 准备生成任务参数
  2275. $params = [
  2276. 'alias_segment_id' => $segment_id,
  2277. 'prompt' => $prompt,
  2278. 'ref_img_urls' => $ref_img_urls,
  2279. 'width' => $width,
  2280. 'height' => $height,
  2281. ];
  2282. // 调用AI图片生成服务
  2283. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2284. $task_id = $task->id;
  2285. // $task_id = 'whatever';
  2286. if (!$task_id) {
  2287. Utils::throwError('20003:创建生成任务失败!');
  2288. }
  2289. $insert_data['pic_task_status'] = '生成中';
  2290. $insert_data['pic_task_id'] = $task_id;
  2291. }
  2292. // 先更新序号
  2293. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2294. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2295. if (!$boolen) {
  2296. Utils::throwError('20003:新增分镜失败!');
  2297. }
  2298. // 如果是第一集的首帧图片,则存入待更新数组
  2299. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2300. Redis::sadd('anime_first_frame_urls', $segment_id);
  2301. }
  2302. if ($dubTaskId) {
  2303. // 请求远程服务器执行生成
  2304. $client = new Client(['timeout' => 300, 'verify' => false]);
  2305. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2306. $response = $result->getBody()->getContents();
  2307. $response_arr = json_decode($response, true);
  2308. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2309. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2310. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2311. Utils::throwError('20003:火山生成音频失败');
  2312. }
  2313. }
  2314. } catch (\Exception $e) {
  2315. DB::rollBack();
  2316. Utils::throwError('20003:'.$e->getMessage());
  2317. }
  2318. DB::commit();
  2319. // 创建任务之后先暂停10s等待异步任务完成
  2320. sleep(10);
  2321. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2322. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2323. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2324. $segment = $segment ? (array)$segment : [];
  2325. return $segment;
  2326. }
  2327. public function copySegment($data) {
  2328. $segment_id = getProp($data, 'segment_id');
  2329. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2330. if (!$segment) Utils::throwError('20003:请选择分镜');
  2331. $anime_id = getProp($segment, 'anime_id');
  2332. $episode_id = getProp($segment, 'episode_id');
  2333. $episode_number = getProp($segment, 'episode_number');
  2334. $segment_number = getProp($segment, 'segment_number');
  2335. $new_segment_id = 0;
  2336. try {
  2337. DB::beginTransaction();
  2338. $segment = (array)$segment;
  2339. unset($segment['id']);
  2340. $segment['segment_number'] += 1;
  2341. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2342. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2343. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2344. // 更新其他分镜序号
  2345. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2346. // 复制分镜
  2347. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2348. if (!$id) {
  2349. Utils::throwError('20003:复制分镜失败');
  2350. }
  2351. }catch (\Exception $e) {
  2352. DB::rollBack();
  2353. Utils::throwError('20003:'.$e->getMessage());
  2354. }
  2355. DB::commit();
  2356. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2357. $segment = $segment ? (array)$segment : [];
  2358. return $segment;
  2359. }
  2360. public function moveSegment($data) {
  2361. $segment_id = getProp($data, 'segment_id');
  2362. $target_segment_id = getProp($data, 'target_segment_id');
  2363. // 获取源分镜信息
  2364. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2365. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2366. // 获取目标分镜信息
  2367. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2368. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2369. $anime_id = getProp($source_segment, 'anime_id');
  2370. $episode_id = getProp($source_segment, 'episode_id');
  2371. $episode_number = getProp($source_segment, 'episode_number');
  2372. $source_segment_number = getProp($source_segment, 'segment_number');
  2373. $target_segment_number = getProp($target_segment, 'segment_number');
  2374. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2375. $target_anime_id = getProp($target_segment, 'anime_id');
  2376. $target_episode_number = getProp($target_segment, 'episode_number');
  2377. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2378. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2379. }
  2380. // 如果源分镜和目标分镜相同,无需移动
  2381. if ($source_segment_number == $target_segment_number) {
  2382. return true;
  2383. }
  2384. try {
  2385. DB::beginTransaction();
  2386. if ($source_segment_number < $target_segment_number) {
  2387. // 向后移动:源分镜移动到目标分镜之后
  2388. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2389. DB::table('mp_episode_segments')
  2390. ->where('anime_id', $anime_id)
  2391. ->where('episode_id', $episode_id)
  2392. ->where('segment_number', '>', $source_segment_number)
  2393. ->where('segment_number', '<=', $target_segment_number)
  2394. ->decrement('segment_number');
  2395. // 2. 将源分镜移动到目标分镜之后
  2396. $new_segment_number = $target_segment_number;
  2397. } else {
  2398. // 向前移动:源分镜移动到目标分镜之后
  2399. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2400. DB::table('mp_episode_segments')
  2401. ->where('anime_id', $anime_id)
  2402. ->where('episode_id', $episode_id)
  2403. ->where('segment_number', '>', $target_segment_number)
  2404. ->where('segment_number', '<', $source_segment_number)
  2405. ->increment('segment_number');
  2406. // 2. 将源分镜移动到目标分镜之后
  2407. $new_segment_number = $target_segment_number + 1;
  2408. }
  2409. // 3. 更新源分镜的序号
  2410. $update_result = DB::table('mp_episode_segments')
  2411. ->where('segment_id', $segment_id)
  2412. ->update([
  2413. 'segment_number' => $new_segment_number,
  2414. 'updated_at' => date('Y-m-d H:i:s')
  2415. ]);
  2416. if (!$update_result) {
  2417. Utils::throwError('20003:更新分镜序号失败');
  2418. }
  2419. DB::commit();
  2420. return true;
  2421. } catch (\Exception $e) {
  2422. DB::rollBack();
  2423. Utils::throwError('20003:' . $e->getMessage());
  2424. }
  2425. }
  2426. public function delSegment($data) {
  2427. $segment_id = getProp($data, 'segment_id');
  2428. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2429. if (!$segment) Utils::throwError('20003:请选择分镜');
  2430. $anime_id = getProp($segment, 'anime_id');
  2431. $episode_id = getProp($segment, 'episode_id');
  2432. $episode_number = getProp($segment, 'episode_number');
  2433. $segment_number = getProp($segment, 'segment_number');
  2434. try {
  2435. DB::beginTransaction();
  2436. // 删除分镜
  2437. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2438. if (!$boolen) {
  2439. Utils::throwError('20003:删除分镜失败');
  2440. }
  2441. // 更新其他分镜序号
  2442. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2443. }catch (\Exception $e) {
  2444. DB::rollBack();
  2445. Utils::throwError('20003:'.$e->getMessage());
  2446. }
  2447. DB::commit();
  2448. return true;
  2449. }
  2450. public function applySegment($data) {
  2451. $segment_id = getProp($data, 'segment_id');
  2452. $url = getProp($data, 'url');
  2453. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2454. if (!$url) Utils::throwError('20003:URL不能为空');
  2455. // 获取URL的文件扩展名
  2456. $urlPath = parse_url($url, PHP_URL_PATH);
  2457. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2458. // 定义图片和视频的扩展名
  2459. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2460. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2461. // 判断是图片还是视频
  2462. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2463. if (in_array($extension, $imageExtensions)) {
  2464. // 图片类型
  2465. $updateData['img_url'] = $url;
  2466. $updateData['current_type'] = 1;
  2467. } elseif (in_array($extension, $videoExtensions)) {
  2468. // 视频类型
  2469. $updateData['video_url'] = $url;
  2470. $updateData['current_type'] = 2;
  2471. } else {
  2472. Utils::throwError('20003:不支持的文件类型');
  2473. }
  2474. // 更新分镜表
  2475. $result = DB::table('mp_episode_segments')
  2476. ->where('segment_id', $segment_id)
  2477. ->update($updateData);
  2478. if (!$result) {
  2479. Utils::throwError('20003:更新分镜失败');
  2480. }
  2481. return true;
  2482. }
  2483. public function segmentHistory($data) {
  2484. $segment_id = getProp($data, 'segment_id');
  2485. // 获取历史图片
  2486. $pics = [];
  2487. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2488. foreach($pic_history as $task) {
  2489. $result_url = getProp($task, 'result_url');
  2490. if (is_json($result_url)) {
  2491. $pics = array_merge($pics, json_decode($result_url, true));
  2492. }else {
  2493. $pics[] = $result_url;
  2494. }
  2495. }
  2496. // 获取历史视频
  2497. $videos = [];
  2498. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2499. foreach($video_history as $task) {
  2500. $result_url = getProp($task, 'result_url');
  2501. if (is_json($result_url)) {
  2502. $videos = array_merge($videos, json_decode($result_url, true));
  2503. }else {
  2504. $videos[] = $result_url;
  2505. }
  2506. }
  2507. return compact('pics', 'videos');
  2508. }
  2509. public function addAct($data) {
  2510. $prev_act_id = getProp($data, 'prev_act_id');
  2511. $act_title = getProp($data, 'act_title', '');
  2512. $act_content = getProp($data, 'act_content', '');
  2513. $act_duration = getProp($data, 'act_duration', 5);
  2514. $video_url = getProp($data, 'video_url');
  2515. // 根据prev_act_id获取记录
  2516. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2517. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2518. $anime_id = getProp($prev_segment, 'anime_id');
  2519. $episode_id = getProp($prev_segment, 'episode_id');
  2520. $episode_number = getProp($prev_segment, 'episode_number');
  2521. $prev_act_number = getProp($prev_segment, 'act_number');
  2522. // 获取新的act_number
  2523. $new_act_number = $prev_act_number + 1;
  2524. try {
  2525. DB::beginTransaction();
  2526. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2527. DB::table('mp_episode_segments')
  2528. ->where('anime_id', $anime_id)
  2529. ->where('episode_id', $episode_id)
  2530. ->where('act_number', '>', $prev_act_number)
  2531. ->increment('act_number');
  2532. // 插入新片段记录
  2533. $insert_data = [
  2534. 'anime_id' => $anime_id,
  2535. 'episode_id' => $episode_id,
  2536. 'episode_number' => $episode_number,
  2537. 'act_number' => $new_act_number,
  2538. 'created_at' => date('Y-m-d H:i:s'),
  2539. 'updated_at' => date('Y-m-d H:i:s')
  2540. ];
  2541. if ($act_title) {
  2542. $insert_data['act_title'] = $act_title;
  2543. }
  2544. if ($act_content) {
  2545. $insert_data['act_content'] = $act_content;
  2546. }
  2547. if ($act_duration) {
  2548. $insert_data['act_duration'] = $act_duration;
  2549. }
  2550. if ($video_url) {
  2551. $insert_data['origin_video_url'] = $video_url;
  2552. $insert_data['current_type'] = 2;
  2553. $compressed_video_url = compressVideo($video_url);
  2554. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2555. }
  2556. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2557. if (!$id) {
  2558. Utils::throwError('20003:新增片段失败!');
  2559. }
  2560. DB::commit();
  2561. }catch (\Exception $e) {
  2562. DB::rollBack();
  2563. Utils::throwError('20003:'.$e->getMessage());
  2564. }
  2565. $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();
  2566. $segment = $segment ? (array)$segment : [];
  2567. return $segment;
  2568. }
  2569. public function editAct($data) {
  2570. $act_id = getProp($data, 'act_id');
  2571. $act_content = getProp($data, 'act_content');
  2572. $act_duration = getProp($data, 'act_duration');
  2573. $act_title = getProp($data, 'act_title');
  2574. $image_url = getProp($data, 'image_url');
  2575. $video_url = getProp($data, 'video_url');
  2576. // 参数验证
  2577. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2578. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2579. $segment = DB::table('mp_episode_segments')
  2580. ->where('id', $act_id)
  2581. ->first();
  2582. if (!$segment) Utils::throwError('20003:该片段不存在');
  2583. try {
  2584. DB::beginTransaction();
  2585. // 准备更新数据
  2586. $update_data = [
  2587. 'updated_at' => date('Y-m-d H:i:s')
  2588. ];
  2589. // 更新act相关字段
  2590. if (!empty($act_content)) {
  2591. $update_data['act_show_content'] = $act_content;
  2592. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2593. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2594. $shot_counter = 0;
  2595. $update_data['act_show_content'] = preg_replace_callback(
  2596. '/【(?:镜头|分镜)(\d+)】/u',
  2597. function($matches) use (&$shot_counter) {
  2598. $shot_counter++;
  2599. return '【镜头' . $shot_counter . '】';
  2600. },
  2601. $update_data['act_show_content']
  2602. );
  2603. }
  2604. if (!empty($act_duration)) {
  2605. $update_data['act_duration'] = $act_duration;
  2606. }
  2607. if (!empty($act_title)) {
  2608. $update_data['act_title'] = $act_title;
  2609. }
  2610. // 处理图片上传
  2611. if ($image_url) {
  2612. $update_data['img_url'] = $image_url;
  2613. $update_data['current_type'] = 1;
  2614. // 同时写入一个图片生成任务记录
  2615. if ($act_id) {
  2616. $pic_task = [
  2617. 'alias_act_id' => $act_id,
  2618. 'ref_img_url' => json_encode([]),
  2619. 'status' => 'success',
  2620. 'result_url' => json_encode([$image_url], 256),
  2621. 'model' => '',
  2622. 'created_at' => date('Y-m-d H:i:s'),
  2623. 'updated_at' => date('Y-m-d H:i:s'),
  2624. ];
  2625. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2626. }
  2627. }
  2628. // 处理视频上传
  2629. if ($video_url) {
  2630. $update_data['origin_video_url'] = $video_url;
  2631. $compressed_video_url = compressVideo($video_url);
  2632. $update_data['current_type'] = 2;
  2633. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2634. // 同时写入一个视频生成任务记录
  2635. if ($act_id) {
  2636. $video_task = [
  2637. 'alias_act_id' => $act_id,
  2638. 'status' => 'success',
  2639. 'result_url' => $update_data['origin_video_url'],
  2640. 'compressed_url' => $update_data['video_url'],
  2641. 'created_at' => date('Y-m-d H:i:s'),
  2642. 'updated_at' => date('Y-m-d H:i:s'),
  2643. ];
  2644. DB::table('mp_generate_video_tasks')->insert($video_task);
  2645. }
  2646. }
  2647. // 更新片段信息
  2648. $result = DB::table('mp_episode_segments')
  2649. ->where('id', $act_id)
  2650. ->update($update_data);
  2651. if ($result === false) {
  2652. Utils::throwError('20003:更新片段失败');
  2653. }
  2654. DB::commit();
  2655. // 返回新复制的记录
  2656. $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();
  2657. $new_segment = (array)$new_segment;
  2658. return $new_segment;
  2659. } catch (\Exception $e) {
  2660. DB::rollBack();
  2661. dLog('anime')->error('更新片段失败', [
  2662. 'act_id' => $act_id,
  2663. 'error' => $e->getMessage()
  2664. ]);
  2665. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2666. }
  2667. }
  2668. public function copyAct($data) {
  2669. $act_id = getProp($data, 'act_id');
  2670. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2671. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2672. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2673. $anime_id = getProp($source_segment, 'anime_id');
  2674. $episode_id = getProp($source_segment, 'episode_id');
  2675. $episode_number = getProp($source_segment, 'episode_number');
  2676. $act_number = getProp($source_segment, 'act_number');
  2677. try {
  2678. DB::beginTransaction();
  2679. // 新act的编号
  2680. $new_act_number = $act_number + 1;
  2681. // 更新后续所有act的act_number
  2682. DB::table('mp_episode_segments')
  2683. ->where('anime_id', $anime_id)
  2684. ->where('episode_id', $episode_id)
  2685. ->where('act_number', '>', $act_number)
  2686. ->increment('act_number');
  2687. // 复制该片段记录
  2688. $segment_data = (array)$source_segment;
  2689. unset($segment_data['id']);
  2690. $segment_data['video_url'] = '';
  2691. $segment_data['video_task_id'] = '';
  2692. $segment_data['video_task_status'] = '';
  2693. $segment_data['act_number'] = $new_act_number;
  2694. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2695. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2696. if (!$id) {
  2697. Utils::throwError('20003:复制片段失败');
  2698. }
  2699. DB::commit();
  2700. }catch (\Exception $e) {
  2701. DB::rollBack();
  2702. Utils::throwError('20003:'.$e->getMessage());
  2703. }
  2704. // 返回新复制的记录
  2705. $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();
  2706. $new_segment = $new_segment ? (array)$new_segment : [];
  2707. $new_segment['act_id'] = $id;
  2708. return $new_segment;
  2709. }
  2710. public function moveAct($data) {
  2711. $act_id = getProp($data, 'act_id');
  2712. $target_act_id = getProp($data, 'target_act_id');
  2713. // 获取源片段信息
  2714. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2715. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2716. // 获取目标片段信息
  2717. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2718. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2719. $anime_id = getProp($source_segment, 'anime_id');
  2720. $episode_id = getProp($source_segment, 'episode_id');
  2721. $source_act_number = getProp($source_segment, 'act_number');
  2722. $target_act_number = getProp($target_segment, 'act_number');
  2723. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2724. $target_anime_id = getProp($target_segment, 'anime_id');
  2725. $target_episode_id = getProp($target_segment, 'episode_id');
  2726. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2727. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2728. }
  2729. // 如果源片段和目标片段相同,无需移动
  2730. if ($source_act_number == $target_act_number) {
  2731. return true;
  2732. }
  2733. try {
  2734. DB::beginTransaction();
  2735. if ($source_act_number < $target_act_number) {
  2736. // 向后移动:源片段移动到目标片段之后
  2737. // 1. 将源片段和目标片段之间的所有片段编号减1
  2738. DB::table('mp_episode_segments')
  2739. ->where('anime_id', $anime_id)
  2740. ->where('episode_id', $episode_id)
  2741. ->where('act_number', '>', $source_act_number)
  2742. ->where('act_number', '<=', $target_act_number)
  2743. ->decrement('act_number');
  2744. // 2. 将源片段移动到目标片段之后
  2745. $new_act_number = $target_act_number;
  2746. } else {
  2747. // 向前移动:源片段移动到目标片段之后
  2748. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2749. DB::table('mp_episode_segments')
  2750. ->where('anime_id', $anime_id)
  2751. ->where('episode_id', $episode_id)
  2752. ->where('act_number', '>', $target_act_number)
  2753. ->where('act_number', '<', $source_act_number)
  2754. ->increment('act_number');
  2755. // 2. 将源片段移动到目标片段之后
  2756. $new_act_number = $target_act_number + 1;
  2757. }
  2758. // 3. 更新源片段的编号
  2759. $update_result = DB::table('mp_episode_segments')
  2760. ->where('id', $act_id)
  2761. ->update([
  2762. 'act_number' => $new_act_number,
  2763. 'updated_at' => date('Y-m-d H:i:s')
  2764. ]);
  2765. if (!$update_result) {
  2766. Utils::throwError('20003:更新片段编号失败');
  2767. }
  2768. DB::commit();
  2769. return true;
  2770. } catch (\Exception $e) {
  2771. DB::rollBack();
  2772. Utils::throwError('20003:' . $e->getMessage());
  2773. }
  2774. }
  2775. public function delAct($data) {
  2776. $act_id = getProp($data, 'act_id');
  2777. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2778. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2779. if (!$segment) Utils::throwError('20003:请选择片段');
  2780. $anime_id = getProp($segment, 'anime_id');
  2781. $episode_id = getProp($segment, 'episode_id');
  2782. $act_number = getProp($segment, 'act_number');
  2783. try {
  2784. DB::beginTransaction();
  2785. // 删除该片段记录
  2786. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2787. if (!$deleted) {
  2788. Utils::throwError('20003:删除片段失败');
  2789. }
  2790. // 更新后续act的编号
  2791. DB::table('mp_episode_segments')
  2792. ->where('anime_id', $anime_id)
  2793. ->where('episode_id', $episode_id)
  2794. ->where('act_number', '>', $act_number)
  2795. ->decrement('act_number');
  2796. DB::commit();
  2797. }catch (\Exception $e) {
  2798. DB::rollBack();
  2799. Utils::throwError('20003:'.$e->getMessage());
  2800. }
  2801. return true;
  2802. }
  2803. public function applyAct($data) {
  2804. $act_id = getProp($data, 'act_id');
  2805. $url = getProp($data, 'url');
  2806. if (!$act_id) Utils::throwError('20003:请选择片段');
  2807. if (!$url) Utils::throwError('20003:URL不能为空');
  2808. // 获取URL的文件扩展名
  2809. $urlPath = parse_url($url, PHP_URL_PATH);
  2810. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2811. // 定义图片和视频的扩展名
  2812. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2813. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2814. // 判断是图片还是视频
  2815. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2816. if (in_array($extension, $imageExtensions)) {
  2817. // 图片类型
  2818. $updateData['img_url'] = $url;
  2819. $updateData['current_type'] = 1;
  2820. } elseif (in_array($extension, $videoExtensions)) {
  2821. // 视频类型
  2822. $updateData['video_url'] = $url;
  2823. $updateData['current_type'] = 2;
  2824. } else {
  2825. Utils::throwError('20003:不支持的文件类型');
  2826. }
  2827. // 更新片段记录(全能模式下每个act只有一条记录)
  2828. $result = DB::table('mp_episode_segments')
  2829. ->where('id', $act_id)
  2830. ->update($updateData);
  2831. if (!$result) {
  2832. Utils::throwError('20003:更新片段失败');
  2833. }
  2834. return true;
  2835. }
  2836. public function actChatHistory($data) {
  2837. $act_id = getProp($data, 'act_id');
  2838. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2839. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2840. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2841. $value = (array)$value;
  2842. $value['created_at'] = transDate($value['created_at']);
  2843. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2844. else $value['reference_images'] = [];
  2845. return $value;
  2846. })->toArray();
  2847. // 获取历史图片
  2848. $url = [];
  2849. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2850. foreach($pic_history as $task) {
  2851. $result_url = getProp($task, 'result_url');
  2852. if (is_json($result_url)) {
  2853. $url = array_merge($url, json_decode($result_url, true));
  2854. }else {
  2855. $url[] = $result_url;
  2856. }
  2857. }
  2858. // 获取历史视频
  2859. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2860. foreach($video_history as $task) {
  2861. $result_url = getProp($task, 'result_url');
  2862. if (is_json($result_url)) {
  2863. $url = array_merge($url, json_decode($result_url, true));
  2864. }else {
  2865. $url[] = $result_url;
  2866. }
  2867. }
  2868. // 获取资产库
  2869. $products = [];
  2870. // 通过act_id查询片段信息获取episode_id
  2871. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2872. if ($segment) {
  2873. $episode_id = getProp($segment, 'episode_id');
  2874. // 查询剧集信息获取roles、scenes和extra_products
  2875. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2876. if ($episode) {
  2877. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2878. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2879. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2880. // 先合并roles和scenes
  2881. // 处理角色数组
  2882. foreach ($roles as $role) {
  2883. $product = $role;
  2884. // 将role字段重命名为product_name
  2885. if (isset($product['role'])) {
  2886. $product['product_name'] = $product['role'];
  2887. unset($product['role']);
  2888. }
  2889. $product['product'] = 1; // 标记类型为角色
  2890. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2891. }
  2892. // 处理场景数组
  2893. foreach ($scenes as $scene) {
  2894. $product = $scene;
  2895. // 将scene字段重命名为product_name
  2896. if (isset($product['scene'])) {
  2897. $product['product_name'] = $product['scene'];
  2898. unset($product['scene']);
  2899. }
  2900. $product['product'] = 2; // 标记类型为场景
  2901. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2902. }
  2903. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2904. foreach ($extra_products as $extra_product) {
  2905. $product_name = getProp($extra_product, 'product_name');
  2906. if ($product_name) {
  2907. $products[$product_name] = $extra_product; // 覆盖同名数据
  2908. }
  2909. }
  2910. // 重新索引数组(去除key)
  2911. $products = array_values($products);
  2912. }
  2913. }
  2914. // 获取执行中的任务
  2915. $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) {
  2916. $value = (array)$value;
  2917. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2918. else $value['ref_image_url'] = [];
  2919. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2920. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2921. if (!empty($value['prompt'])) {
  2922. $prompt = $value['prompt'];
  2923. // 查找第一个【镜头】的位置
  2924. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2925. // 从【镜头】开始截取
  2926. $prompt = substr($prompt, $matches[0][1]);
  2927. }
  2928. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2929. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2930. $value['prompt'] = $prompt;
  2931. }
  2932. return $value;
  2933. })->toArray();
  2934. return compact('chat', 'url', 'products', 'tasks');
  2935. }
  2936. public function applyAudioData($data) {
  2937. $segment_id = getProp($data, 'segment_id');
  2938. $global_data = getProp($data, 'global_data');
  2939. $segment_data = getProp($data, 'segment_data');
  2940. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2941. $global_data = is_array($global_data) ? $global_data : [];
  2942. $segment_data = is_array($segment_data) ? $segment_data : [];
  2943. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2944. $dialogue_item = null;
  2945. foreach ($global_data as $key => $item) {
  2946. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2947. $dialogue_item = $item;
  2948. unset($global_data[$key]);
  2949. break;
  2950. }
  2951. }
  2952. if ($dialogue_item) {
  2953. $segment_data[] = $dialogue_item;
  2954. }
  2955. // 特殊参数: audio_url,audio_duration,subtitle_info
  2956. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2957. // 如果不是全部存在,则仍需创建音频任务
  2958. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2959. $special_update_data = [];
  2960. $has_all_special_params = false;
  2961. // 从segment_data中提取特殊参数
  2962. $filtered_segment_data = [];
  2963. foreach ($segment_data as $item) {
  2964. $field_name = trim((string)getProp($item, 'name'));
  2965. if (in_array($field_name, $special_fields)) {
  2966. $special_update_data[$field_name] = getProp($item, 'value');
  2967. } else {
  2968. // 非特殊参数保留,继续后续处理
  2969. $filtered_segment_data[] = $item;
  2970. }
  2971. }
  2972. // 检查是否三个特殊参数都存在
  2973. if (count($special_update_data) === 3 &&
  2974. isset($special_update_data['audio_url']) &&
  2975. isset($special_update_data['audio_duration']) &&
  2976. isset($special_update_data['subtitle_info'])) {
  2977. $has_all_special_params = true;
  2978. // 立即更新到当前分镜
  2979. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2980. DB::table('mp_episode_segments')
  2981. ->where('segment_id', $segment_id)
  2982. ->update($special_update_data);
  2983. }
  2984. // 使用过滤后的segment_data继续处理其他参数
  2985. $segment_data = $filtered_segment_data;
  2986. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2987. $global_update_data = [];
  2988. $segment_update_data = [];
  2989. $global_voice_type = '';
  2990. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2991. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2992. $episode_id = getProp($target_segment, 'episode_id');
  2993. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2994. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2995. if (!$episode) Utils::throwError('20003:分集不存在');
  2996. foreach ($global_data as $item) {
  2997. $field_name = trim((string)getProp($item, 'name'));
  2998. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2999. continue;
  3000. }
  3001. $global_update_data[$field_name] = getProp($item, 'value');
  3002. if ($field_name === 'voice_type') {
  3003. $global_voice_type = trim((string)getProp($item, 'value'));
  3004. }
  3005. }
  3006. foreach ($segment_data as $item) {
  3007. $field_name = trim((string)getProp($item, 'name'));
  3008. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3009. continue;
  3010. }
  3011. $segment_update_data[$field_name] = getProp($item, 'value');
  3012. }
  3013. if ($global_voice_type) {
  3014. $timbre_info = DB::table('mp_timbres')
  3015. ->where('timbre_type', $global_voice_type)
  3016. ->select('audio_url', 'timbre_name')
  3017. ->first();
  3018. if ($timbre_info) {
  3019. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3020. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3021. }
  3022. }
  3023. try {
  3024. DB::beginTransaction();
  3025. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3026. $segment_ids_to_create_task = [];
  3027. $segments_data = [];
  3028. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3029. if (!empty($global_update_data)) {
  3030. // 如果角色不存在,则只更新当前分镜
  3031. if (!$target_voice_actor) {
  3032. // 只处理当前分镜
  3033. $affected_segments = DB::table('mp_episode_segments')
  3034. ->where('segment_id', $segment_id)
  3035. ->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')
  3036. ->get();
  3037. } else {
  3038. // 获取该角色的所有分镜
  3039. $affected_segments = DB::table('mp_episode_segments')
  3040. ->where('episode_id', $episode_id)
  3041. ->where('voice_actor', $target_voice_actor)
  3042. ->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')
  3043. ->get();
  3044. }
  3045. foreach ($affected_segments as $seg) {
  3046. $seg = (array)$seg;
  3047. $sid = getProp($seg, 'segment_id');
  3048. // 检查参数是否发生变化
  3049. $has_changed = false;
  3050. foreach ($global_update_data as $field => $new_value) {
  3051. $old_value = getProp($seg, $field);
  3052. if ($old_value != $new_value) {
  3053. $has_changed = true;
  3054. break;
  3055. }
  3056. }
  3057. if ($has_changed) {
  3058. $segment_ids_to_create_task[] = $sid;
  3059. $segments_data[$sid] = $seg;
  3060. }
  3061. }
  3062. // 只有在有变化的分镜时才更新
  3063. if (!empty($segment_ids_to_create_task)) {
  3064. $global_segment_update_data = $global_update_data;
  3065. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3066. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3067. DB::table('mp_episode_segments')
  3068. ->where('episode_id', $episode_id)
  3069. ->where('voice_actor', $target_voice_actor)
  3070. ->whereIn('segment_id', $segment_ids_to_create_task)
  3071. ->update($global_segment_update_data);
  3072. }
  3073. if ($global_voice_type) {
  3074. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3075. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3076. $roles_updated = false;
  3077. foreach ($episode_roles as &$role) {
  3078. // 通过 role 字段匹配角色名,而不是 voice_name
  3079. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3080. continue;
  3081. }
  3082. $role['voice_type'] = $global_voice_type;
  3083. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3084. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3085. $roles_updated = true;
  3086. }
  3087. unset($role);
  3088. if ($roles_updated) {
  3089. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3090. 'roles' => json_encode($episode_roles, 256),
  3091. 'updated_at' => date('Y-m-d H:i:s'),
  3092. ]);
  3093. }
  3094. }
  3095. }
  3096. // 如果有单个分镜更新,检查是否有变化
  3097. if (!empty($segment_update_data)) {
  3098. // 获取当前分镜数据
  3099. $current_segment = DB::table('mp_episode_segments')
  3100. ->where('segment_id', $segment_id)
  3101. ->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')
  3102. ->first();
  3103. if ($current_segment) {
  3104. $current_segment = (array)$current_segment;
  3105. // 检查参数是否发生变化
  3106. $has_changed = false;
  3107. foreach ($segment_update_data as $field => $new_value) {
  3108. $old_value = getProp($current_segment, $field);
  3109. if ($old_value != $new_value) {
  3110. $has_changed = true;
  3111. break;
  3112. }
  3113. }
  3114. if ($has_changed) {
  3115. // 如果该分镜还未在列表中,添加进去
  3116. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3117. $segment_ids_to_create_task[] = $segment_id;
  3118. $segments_data[$segment_id] = $current_segment;
  3119. }
  3120. // 更新分镜数据并清空音频URL
  3121. $segment_update_data['audio_url'] = '';
  3122. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3123. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3124. }
  3125. }
  3126. }
  3127. // 为所有有变化的分镜创建音频合成任务
  3128. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3129. if (!empty($segment_ids_to_create_task)) {
  3130. foreach ($segment_ids_to_create_task as $sid) {
  3131. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3132. if ($sid === $segment_id && $has_all_special_params) {
  3133. continue;
  3134. }
  3135. // 重新获取更新后的分镜数据
  3136. $updated_segment = DB::table('mp_episode_segments')
  3137. ->where('segment_id', $sid)
  3138. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3139. ->first();
  3140. if (!$updated_segment) continue;
  3141. $updated_segment = (array)$updated_segment;
  3142. // 检查dialogue是否为空
  3143. $dialogue = getProp($updated_segment, 'dialogue');
  3144. if (empty($dialogue)) {
  3145. // dialogue为空时,直接写入默认音频信息
  3146. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3147. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3148. 'audio_duration' => 2.0,
  3149. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3150. 'updated_at' => date('Y-m-d H:i:s')
  3151. ]);
  3152. continue;
  3153. }
  3154. $generate_json = [
  3155. 'text' => $dialogue,
  3156. 'role' => getProp($updated_segment, 'voice_actor'),
  3157. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3158. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3159. 'emotion' => getProp($updated_segment, 'emotion'),
  3160. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3161. 'gender' => getProp($updated_segment, 'gender'),
  3162. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3163. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3164. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3165. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3166. ];
  3167. // 插入视频配音合成任务
  3168. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3169. 'alias_segment_id' => $sid,
  3170. 'generate_status' => '执行中',
  3171. 'audio_url' => '',
  3172. 'generate_json' => json_encode($generate_json, 256),
  3173. 'created_at' => date('Y-m-d H:i:s'),
  3174. 'updated_at' => date('Y-m-d H:i:s'),
  3175. ]);
  3176. if (!$dubTaskId) {
  3177. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3178. continue;
  3179. }
  3180. // 将任务ID添加到Redis列表中
  3181. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3182. // 请求远程服务器执行生成
  3183. try {
  3184. sleep(1);
  3185. $client = new Client(['timeout' => 300, 'verify' => false]);
  3186. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3187. $response = $result->getBody()->getContents();
  3188. $response_arr = json_decode($response, true);
  3189. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3190. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3191. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3192. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3193. }
  3194. } catch (\Exception $e) {
  3195. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3196. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3197. }
  3198. }
  3199. }
  3200. DB::commit();
  3201. } catch (\Exception $e) {
  3202. DB::rollBack();
  3203. Utils::throwError('20003:'.$e->getMessage());
  3204. }
  3205. return true;
  3206. }
  3207. public function episodePicsInfo($data) {
  3208. $anime_id = getProp($data, 'anime_id');
  3209. $episode_id = getProp($data, 'episode_id');
  3210. // 参数验证
  3211. if (!$anime_id && !$episode_id) {
  3212. Utils::throwError('20003:请提供动漫ID或分集ID');
  3213. }
  3214. // 根据参数获取数据源
  3215. if ($episode_id) {
  3216. // 从剧集表获取
  3217. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3218. if (!$source) Utils::throwError('20003:该剧集不存在');
  3219. $table_name = 'mp_anime_episodes';
  3220. $id_field = 'id';
  3221. $id_value = $episode_id;
  3222. // 获取剧集的anime_id用于继承全局数据
  3223. $anime_id = getProp($source, 'anime_id');
  3224. } else {
  3225. // 从动漫表获取
  3226. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3227. if (!$source) Utils::throwError('20003:该动漫不存在');
  3228. $table_name = 'mp_animes';
  3229. $id_field = 'id';
  3230. $id_value = $anime_id;
  3231. }
  3232. $source = (array)$source;
  3233. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3234. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3235. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3236. // 如果是分集数据,需要处理继承和任务创建逻辑
  3237. if ($episode_id) {
  3238. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3239. }
  3240. // 返回生成器函数,用于 SSE 流式输出
  3241. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3242. $startTime = time();
  3243. $maxDuration = 600; // 10分钟超时
  3244. $checkInterval = 3; // 每3秒检查一次
  3245. // Redis 缓存键
  3246. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3247. // 生成当前数据的哈希值用于比较
  3248. $generateHash = function($roles, $scenes, $props) {
  3249. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3250. };
  3251. // 发送初始数据
  3252. $currentHash = $generateHash($roles, $scenes, $props);
  3253. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3254. echo "data: " . json_encode([
  3255. 'type' => 'init',
  3256. 'data' => [
  3257. 'roles' => $roles,
  3258. 'scenes' => $scenes,
  3259. 'props' => $props,
  3260. 'start_time' => $startTime
  3261. ]
  3262. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3263. if (ob_get_level() > 0) {
  3264. ob_flush();
  3265. }
  3266. flush();
  3267. // 持续轮询任务状态
  3268. while (time() - $startTime < $maxDuration) {
  3269. $hasProcessing = false;
  3270. $updated = false;
  3271. // 检查角色任务状态
  3272. foreach ($roles as $index => &$role) {
  3273. $task_id = getProp($role, 'task_id');
  3274. $task_status = getProp($role, 'task_status');
  3275. $existing_url = getProp($role, 'url');
  3276. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3277. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3278. $hasProcessing = ($task_status === 'processing');
  3279. // 查询任务状态
  3280. $task = DB::table('mp_generate_pic_tasks')
  3281. ->where('id', $task_id)
  3282. ->select('id', 'status', 'result_url', 'error_message')
  3283. ->first();
  3284. if ($task) {
  3285. $task = (array)$task;
  3286. $status = getProp($task, 'status');
  3287. // 如果任务完成或失败
  3288. if (in_array($status, ['success', 'failed'])) {
  3289. $role['task_status'] = $status;
  3290. if ($status === 'success') {
  3291. $result_url = getProp($task, 'result_url');
  3292. if ($result_url) {
  3293. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3294. if (is_array($result_urls) && !empty($result_urls[0])) {
  3295. $role['url'] = $result_urls[0];
  3296. }
  3297. }
  3298. }
  3299. $updated = true;
  3300. } else if ($status === 'processing') {
  3301. $hasProcessing = true;
  3302. }
  3303. }
  3304. }
  3305. }
  3306. // 检查场景任务状态
  3307. foreach ($scenes as $index => &$scene) {
  3308. $task_id = getProp($scene, 'task_id');
  3309. $task_status = getProp($scene, 'task_status');
  3310. $existing_url = getProp($scene, 'url');
  3311. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3312. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3313. $hasProcessing = ($task_status === 'processing');
  3314. // 查询任务状态
  3315. $task = DB::table('mp_generate_pic_tasks')
  3316. ->where('id', $task_id)
  3317. ->select('id', 'status', 'result_url', 'error_message')
  3318. ->first();
  3319. if ($task) {
  3320. $task = (array)$task;
  3321. $status = getProp($task, 'status');
  3322. // 如果任务完成或失败
  3323. if (in_array($status, ['success', 'failed'])) {
  3324. $scene['task_status'] = $status;
  3325. if ($status === 'success') {
  3326. $result_url = getProp($task, 'result_url');
  3327. if ($result_url) {
  3328. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3329. if (is_array($result_urls) && !empty($result_urls[0])) {
  3330. $scene['url'] = $result_urls[0];
  3331. }
  3332. }
  3333. }
  3334. $updated = true;
  3335. } else if ($status === 'processing') {
  3336. $hasProcessing = true;
  3337. }
  3338. }
  3339. }
  3340. }
  3341. // 检查道具任务状态
  3342. foreach ($props as $index => &$prop) {
  3343. $task_id = getProp($prop, 'task_id');
  3344. $task_status = getProp($prop, 'task_status');
  3345. $existing_url = getProp($prop, 'url');
  3346. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3347. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3348. $hasProcessing = ($task_status === 'processing');
  3349. // 查询任务状态
  3350. $task = DB::table('mp_generate_pic_tasks')
  3351. ->where('id', $task_id)
  3352. ->select('id', 'status', 'result_url', 'error_message')
  3353. ->first();
  3354. if ($task) {
  3355. $task = (array)$task;
  3356. $status = getProp($task, 'status');
  3357. // 如果任务完成或失败
  3358. if (in_array($status, ['success', 'failed'])) {
  3359. $prop['task_status'] = $status;
  3360. if ($status === 'success') {
  3361. $result_url = getProp($task, 'result_url');
  3362. if ($result_url) {
  3363. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3364. if (is_array($result_urls) && !empty($result_urls[0])) {
  3365. $prop['url'] = $result_urls[0];
  3366. }
  3367. }
  3368. }
  3369. $updated = true;
  3370. } else if ($status === 'processing') {
  3371. $hasProcessing = true;
  3372. }
  3373. }
  3374. }
  3375. }
  3376. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3377. if ($updated) {
  3378. $newHash = $generateHash($roles, $scenes, $props);
  3379. $cachedHash = Redis::get($cacheKey);
  3380. // 只有当数据真正变化时才更新数据库和发送事件
  3381. if ($newHash !== $cachedHash) {
  3382. try {
  3383. // 更新数据库
  3384. DB::table($table_name)->where($id_field, $id_value)->update([
  3385. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3386. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3387. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3388. 'updated_at' => date('Y-m-d H:i:s')
  3389. ]);
  3390. // 更新缓存
  3391. Redis::setex($cacheKey, 600, $newHash);
  3392. // 发送更新事件
  3393. echo "data: " . json_encode([
  3394. 'type' => 'update',
  3395. 'data' => [
  3396. 'roles' => $roles,
  3397. 'scenes' => $scenes,
  3398. 'props' => $props,
  3399. 'elapsed_time' => time() - $startTime
  3400. ]
  3401. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3402. if (ob_get_level() > 0) {
  3403. ob_flush();
  3404. }
  3405. flush();
  3406. } catch (\Exception $e) {
  3407. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3408. }
  3409. } else {
  3410. // 即使哈希相同,如果有URL更新也要发送事件
  3411. $hasUrlUpdate = false;
  3412. foreach ($roles as $role) {
  3413. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3414. $hasUrlUpdate = true;
  3415. break;
  3416. }
  3417. }
  3418. if (!$hasUrlUpdate) {
  3419. foreach ($scenes as $scene) {
  3420. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3421. $hasUrlUpdate = true;
  3422. break;
  3423. }
  3424. }
  3425. }
  3426. if (!$hasUrlUpdate) {
  3427. foreach ($props as $prop) {
  3428. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3429. $hasUrlUpdate = true;
  3430. break;
  3431. }
  3432. }
  3433. }
  3434. if ($hasUrlUpdate) {
  3435. // 强制更新数据库和发送事件
  3436. try {
  3437. DB::table($table_name)->where($id_field, $id_value)->update([
  3438. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3439. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3440. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3441. 'updated_at' => date('Y-m-d H:i:s')
  3442. ]);
  3443. // 更新缓存
  3444. Redis::setex($cacheKey, 600, $newHash);
  3445. // 发送更新事件
  3446. echo "data: " . json_encode([
  3447. 'type' => 'update',
  3448. 'data' => [
  3449. 'roles' => $roles,
  3450. 'scenes' => $scenes,
  3451. 'props' => $props,
  3452. 'elapsed_time' => time() - $startTime
  3453. ]
  3454. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3455. if (ob_get_level() > 0) {
  3456. ob_flush();
  3457. }
  3458. flush();
  3459. } catch (\Exception $e) {
  3460. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3461. }
  3462. }
  3463. }
  3464. }
  3465. // 如果所有任务都已完成,发送完成事件并退出
  3466. if (!$hasProcessing) {
  3467. // 查询数据库中的最终数据,确保返回最新的完整数据
  3468. try {
  3469. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3470. if ($finalSource) {
  3471. $finalSource = (array)$finalSource;
  3472. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3473. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3474. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3475. // 使用数据库中的最终数据
  3476. $roles = $finalRoles;
  3477. $scenes = $finalScenes;
  3478. $props = $finalProps;
  3479. }
  3480. } catch (\Exception $e) {
  3481. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3482. // 如果查询失败,继续使用内存中的数据
  3483. }
  3484. // 清理缓存
  3485. Redis::del($cacheKey);
  3486. echo "data: " . json_encode([
  3487. 'type' => 'completed',
  3488. 'data' => [
  3489. 'roles' => $roles,
  3490. 'scenes' => $scenes,
  3491. 'props' => $props,
  3492. 'total_time' => time() - $startTime
  3493. ]
  3494. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3495. if (ob_get_level() > 0) {
  3496. ob_flush();
  3497. }
  3498. flush();
  3499. break;
  3500. }
  3501. // 等待下次检查
  3502. sleep($checkInterval);
  3503. }
  3504. // 超时处理
  3505. if (time() - $startTime >= $maxDuration) {
  3506. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3507. try {
  3508. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3509. if ($finalSource) {
  3510. $finalSource = (array)$finalSource;
  3511. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3512. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3513. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3514. // 使用数据库中的最终数据
  3515. $roles = $finalRoles;
  3516. $scenes = $finalScenes;
  3517. $props = $finalProps;
  3518. }
  3519. } catch (\Exception $e) {
  3520. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3521. // 如果查询失败,继续使用内存中的数据
  3522. }
  3523. // 清理缓存
  3524. Redis::del($cacheKey);
  3525. echo "data: " . json_encode([
  3526. 'type' => 'timeout',
  3527. 'message' => '轮询超时,请刷新页面查看最新状态',
  3528. 'data' => [
  3529. 'roles' => $roles,
  3530. 'scenes' => $scenes,
  3531. 'props' => $props
  3532. ]
  3533. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3534. if (ob_get_level() > 0) {
  3535. ob_flush();
  3536. }
  3537. flush();
  3538. }
  3539. };
  3540. }
  3541. public function clipSegmentVideo($data) {
  3542. $segment_id = getProp($data, 'segment_id');
  3543. $video_time_point_start = getProp($data, 'video_time_point_start');
  3544. $video_time_point_end = getProp($data, 'video_time_point_end');
  3545. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3546. Utils::throwError('20003:参数异常');
  3547. }
  3548. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3549. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3550. }
  3551. $video_duration = $video_time_point_end - $video_time_point_start;
  3552. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3553. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3554. 'video_duration' => $video_duration,
  3555. 'video_time_point_start' => $video_time_point_start,
  3556. 'video_time_point_end' => $video_time_point_end,
  3557. 'updated_at' => date('Y-m-d H:i:s')
  3558. ]);
  3559. }
  3560. // 轮训获取图片任务结果
  3561. private function loopGetPicTaskResult($task_id) {
  3562. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3563. if (!$task) {
  3564. return '';
  3565. }
  3566. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3567. $model = getProp($task, 'model');
  3568. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3569. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3570. $isSyncModel = $isVolcModel || $isGptModel;
  3571. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3572. $start_count = 0;
  3573. $img_url = '';
  3574. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3575. sleep(3);
  3576. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3577. // 如果任务已经完成,直接返回结果
  3578. if ($task->status === 'success' && $task->result_url) {
  3579. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3580. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3581. }
  3582. // 如果任务已失败,返回空
  3583. if ($task->status === 'failed') {
  3584. return '';
  3585. }
  3586. if ($isSyncModel) continue;
  3587. // 查询任务状态
  3588. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3589. if ($statusInfo['status'] === 'success') {
  3590. $task->updateStatus('success', [
  3591. 'result_url' => $statusInfo['result_url'],
  3592. 'result_json' => $statusInfo['result_json'] ?? []
  3593. ]);
  3594. // 同步调整分镜图片状态和结果
  3595. if (getProp($task, 'alias_segment_id')) {
  3596. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3597. 'img_url' => $statusInfo['result_url'][0],
  3598. 'pic_task_status' => '已完成',
  3599. ]);
  3600. }
  3601. $img_url = $statusInfo['result_url'][0];
  3602. break;
  3603. } elseif ($statusInfo['status'] === 'failed') {
  3604. $task->updateStatus('failed', [
  3605. 'error_message' => $statusInfo['error_message'],
  3606. 'result_json' => $statusInfo['result_json'] ?? []
  3607. ]);
  3608. if (getProp($task, 'alias_segment_id')) {
  3609. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3610. 'pic_task_status' => '失败',
  3611. ]);
  3612. }
  3613. break;
  3614. }
  3615. $start_count++;
  3616. }
  3617. return $img_url;
  3618. }
  3619. /**
  3620. * 从分镜内容中提取涉及的角色
  3621. */
  3622. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3623. $found_characters = [];
  3624. foreach ($available_characters as $character) {
  3625. // 检查角色名称是否在分镜内容中出现
  3626. if (strpos($segment_content, $character) !== false) {
  3627. $found_characters[] = $character;
  3628. }
  3629. }
  3630. if (!$found_characters) {
  3631. foreach ($roles as $character) {
  3632. // 检查角色名称是否在分镜内容中出现
  3633. if (strpos($segment_content, $character) !== false) {
  3634. $found_characters[] = $character;
  3635. }
  3636. }
  3637. }
  3638. return array_unique($found_characters);
  3639. }
  3640. // 从分镜剧本中提取关键字段
  3641. private function handleSegmentContent(&$data) {
  3642. $segmentContent = getProp($data, 'segment_content');
  3643. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3644. $segmentData = [
  3645. 'description' => '',
  3646. 'composition' => '',
  3647. 'camera_movement' => '',
  3648. 'voice_actor' => '',
  3649. 'dialogue' => '',
  3650. 'frame_type' => '',
  3651. 'scene' => '', // 场景
  3652. 'characters' => '', // 出镜角色
  3653. 'tail_frame' => '', // 尾帧描述
  3654. 'emotion' => '中性', // 情感
  3655. 'gender' => '0', // 性别(0未知,1男,2女)
  3656. 'speed_ratio' => 0, // 语速
  3657. 'loudness_ratio' => 0, // 音量
  3658. 'emotion_scale' => 4, // 情感强度
  3659. 'pitch' => 0, // 音调
  3660. ];
  3661. // 用于存储需要从 segment_content 中移除的匹配项
  3662. $replaceEmptyArr = [];
  3663. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3664. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3665. $segmentData['description'] = trim($descMatch[1]);
  3666. $data['description'] = trim($descMatch[1]);
  3667. }
  3668. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3669. $segmentData['composition'] = trim($compMatch[1]);
  3670. $data['composition'] = trim($compMatch[1]);
  3671. }
  3672. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3673. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3674. $data['camera_movement'] = trim($cameraMatch[1]);
  3675. }
  3676. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3677. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3678. $data['voice_actor'] = trim($voiceMatch[1]);
  3679. }
  3680. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3681. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3682. $data['dialogue'] = trim($dialogueMatch[1]);
  3683. }
  3684. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3685. $segmentData['frame_type'] = trim($frameMatch[1]);
  3686. $data['frame_type'] = trim($frameMatch[1]);
  3687. }
  3688. // 场景字段
  3689. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3690. $segmentData['scene'] = trim($sceneMatch[1]);
  3691. $data['scene'] = trim($sceneMatch[1]);
  3692. }
  3693. // 出镜角色字段
  3694. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3695. $segmentData['characters'] = trim($charactersMatch[1]);
  3696. $data['characters'] = trim($charactersMatch[1]);
  3697. }
  3698. // 尾帧描述字段
  3699. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3700. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3701. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3702. }
  3703. // 情感字段
  3704. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3705. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3706. $segmentData['emotion'] = trim($emotionMatch[1]);
  3707. $data['emotion'] = trim($emotionMatch[1]);
  3708. }
  3709. // 性别字段
  3710. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3711. $replaceEmptyArr[] = trim($genderMatch[0]);
  3712. $genderStr = trim($genderMatch[1]);
  3713. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3714. $segmentData['gender'] = '1';
  3715. $data['gender'] = '1';
  3716. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3717. $segmentData['gender'] = '2';
  3718. $data['gender'] = '2';
  3719. } else {
  3720. $segmentData['gender'] = '0';
  3721. $data['gender'] = '0';
  3722. }
  3723. }
  3724. // 语速字段
  3725. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3726. $replaceEmptyArr[] = trim($speedMatch[0]);
  3727. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3728. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3729. }
  3730. // 音量字段
  3731. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3732. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3733. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3734. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3735. }
  3736. // 情感强度字段
  3737. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3738. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3739. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3740. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3741. }
  3742. // 音调字段
  3743. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3744. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3745. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3746. $data['pitch'] = (int)trim($pitchMatch[1]);
  3747. }
  3748. // 从 segment_content 中移除已提取的配音参数字段
  3749. if (!empty($replaceEmptyArr)) {
  3750. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3751. }
  3752. // 如果有配音角色,查询音色信息并验证情感
  3753. $voice_actor = $segmentData['voice_actor'];
  3754. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3755. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3756. $anime_id = getProp($data, 'anime_id');
  3757. $episode_id = getProp($data, 'episode_id');
  3758. // 优先从剧集的角色列表中查找
  3759. $roles = [];
  3760. if ($episode_id) {
  3761. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3762. if ($episode && getProp($episode, 'roles')) {
  3763. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3764. }
  3765. }
  3766. // 如果剧集中没有,从动漫的角色列表中查找
  3767. if (empty($roles) && $anime_id) {
  3768. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3769. if ($anime && getProp($anime, 'roles')) {
  3770. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3771. }
  3772. }
  3773. // 查找匹配的角色音色信息
  3774. $timbre_info = null;
  3775. foreach ($roles as $role) {
  3776. if (getProp($role, 'role') === $voice_actor) {
  3777. $timbre_info = $role;
  3778. break;
  3779. }
  3780. }
  3781. // 如果找到音色信息,添加到数据中
  3782. if ($timbre_info) {
  3783. $voice_type = getProp($timbre_info, 'voice_type');
  3784. $voice_name = getProp($timbre_info, 'voice_name');
  3785. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3786. if ($voice_type) {
  3787. $data['voice_type'] = $voice_type;
  3788. $segmentData['voice_type'] = $voice_type;
  3789. }
  3790. if ($voice_name) {
  3791. $data['voice_name'] = $voice_name;
  3792. $segmentData['voice_name'] = $voice_name;
  3793. }
  3794. if ($voice_audio_url) {
  3795. $data['voice_audio_url'] = $voice_audio_url;
  3796. $segmentData['voice_audio_url'] = $voice_audio_url;
  3797. }
  3798. // 验证情感是否在音色支持的情感列表中
  3799. if ($voice_type) {
  3800. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3801. if ($timbre_emotion) {
  3802. $timbre_emotion = explode(',', $timbre_emotion);
  3803. } else {
  3804. $timbre_emotion = [];
  3805. }
  3806. $emotion = getProp($segmentData, 'emotion', '中性');
  3807. if (!in_array($emotion, $timbre_emotion)) {
  3808. $emotion = '中性';
  3809. }
  3810. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3811. $emotion_list = array_flip($emotion_list);
  3812. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3813. $data['emotion_type'] = $emotion_type;
  3814. $segmentData['emotion_type'] = $emotion_type;
  3815. }
  3816. }
  3817. }
  3818. return $segmentData;
  3819. }
  3820. public function createSegmentVideoTask($data) {
  3821. $segment_id = getProp($data, 'segment_id');
  3822. $tail_frame = getProp($data, 'tail_frame');
  3823. $first_frame_url = getProp($data, 'first_frame_url');
  3824. $tail_frame_url = getProp($data, 'tail_frame_url');
  3825. $generate_audio = getProp($data, 'generate_audio', 0);
  3826. if (!$segment_id) {
  3827. Utils::throwError('1002:分镜ID不能为空');
  3828. }
  3829. // 获取分镜信息
  3830. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3831. if (!$segment) {
  3832. Utils::throwError('20003:分镜不存在');
  3833. }
  3834. $segment = (array)$segment;
  3835. $episode_id = getProp($segment, 'episode_id');
  3836. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3837. if (!$ratio) $ratio = '9:16';
  3838. // 获取分镜内容
  3839. $segmentContent = getProp($segment, 'segment_content', '');
  3840. // 检查 $segmentContent 中是否已有尾帧描述
  3841. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3842. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3843. $finalTailFrame = '';
  3844. if ($tail_frame) {
  3845. // 用户输入了尾帧描述,优先使用
  3846. $finalTailFrame = $tail_frame;
  3847. // 如果 segmentContent 中已有尾帧描述,需要替换
  3848. if ($contentHasTailFrame) {
  3849. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3850. }
  3851. } elseif ($contentHasTailFrame) {
  3852. // segmentContent 中有尾帧描述,使用它
  3853. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3854. } else {
  3855. // 两者都没有,使用分镜表中的尾帧描述
  3856. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3857. }
  3858. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3859. $hasDialogue = false;
  3860. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3861. $dialogue = trim($dialogueMatch[1]);
  3862. // 如果台词不为空且不是"无"
  3863. if (!empty($dialogue) && $dialogue !== '无') {
  3864. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3865. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3866. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3867. $hasDialogue = true;
  3868. }
  3869. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3870. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3871. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3872. if (!preg_match('/^[“]/', $dialogue)) {
  3873. $dialogue = '“' . $dialogue;
  3874. }
  3875. if (!preg_match('/[”]$/', $dialogue)) {
  3876. $dialogue .= '”';
  3877. }
  3878. // 将修改后的台词替换回 $segmentContent
  3879. $originalDialogue = $dialogueMatch[1];
  3880. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3881. }
  3882. }
  3883. // 构建完整的提示词
  3884. $fullPrompt = $segmentContent;
  3885. if ($finalTailFrame && !$contentHasTailFrame) {
  3886. // 只有当 segmentContent 中没有尾帧描述时才追加
  3887. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3888. }
  3889. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3890. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3891. $fullPrompt = trim($fullPrompt);
  3892. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3893. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3894. // 智能选择视频时长
  3895. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3896. $videoDuration = -1;
  3897. // 处理视频模型
  3898. $model = getProp($data, 'model');
  3899. if (!$model) {
  3900. // 用户没有输入,从episode表获取
  3901. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3902. $model = getProp($episode, 'video_model');
  3903. if (!$model) {
  3904. // episode表也没有,使用默认值
  3905. $model = 'doubao-seedance-1-5-pro-251215';
  3906. }
  3907. }
  3908. // 验证模型是否在可用模型表中
  3909. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3910. $model = 'doubao-seedance-1-5-pro-251215';
  3911. }
  3912. // 保存到episode表
  3913. $episode_id = getProp($segment, 'episode_id');
  3914. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3915. 'video_model' => $model,
  3916. 'updated_at' => date('Y-m-d H:i:s')
  3917. ]);
  3918. // 构建视频生成参数
  3919. $videoParams = [
  3920. 'model' => $model,
  3921. 'alias_segment_id' => $segment_id,
  3922. 'prompt' => trim($fullPrompt),
  3923. 'video_duration' => $videoDuration,
  3924. 'video_resolution' => '720P',
  3925. 'seed' => -1,
  3926. 'ratio' => $ratio,
  3927. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3928. 'draft' => false,
  3929. 'watermark' => false,
  3930. 'camera_fixed' => false,
  3931. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3932. ];
  3933. // 如果分镜有图片,作为首帧
  3934. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3935. $hasVideo = !empty(getProp($segment, 'video_url'));
  3936. if ($hasImage) {
  3937. if ($first_frame_url) {
  3938. $videoParams['first_frame_url'] = $first_frame_url;
  3939. }else {
  3940. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3941. }
  3942. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3943. }
  3944. // 构建content数组
  3945. $videoParams['content'] = [
  3946. [
  3947. 'type' => 'text',
  3948. 'text' => $videoParams['prompt'],
  3949. ]
  3950. ];
  3951. // 如果有首帧图片,添加到content中
  3952. if ($hasImage) {
  3953. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3954. $videoParams['content'][] = [
  3955. 'type' => 'image_url',
  3956. 'image_url' => [
  3957. 'url' => $videoParams['first_frame_url'],
  3958. ],
  3959. 'role' => 'reference_image',
  3960. ];
  3961. if (isset($videoParams['tail_frame_url'])) {
  3962. $videoParams['content'][] = [
  3963. 'type' => 'image_url',
  3964. 'image_url' => [
  3965. 'url' => $videoParams['tail_frame_url'],
  3966. ],
  3967. 'role' => 'reference_image',
  3968. ];
  3969. }
  3970. }else {
  3971. $videoParams['content'][] = [
  3972. 'type' => 'image_url',
  3973. 'image_url' => [
  3974. 'url' => $videoParams['first_frame_url'],
  3975. ],
  3976. 'role' => 'first_frame',
  3977. ];
  3978. if (isset($videoParams['tail_frame_url'])) {
  3979. $videoParams['content'][] = [
  3980. 'type' => 'image_url',
  3981. 'image_url' => [
  3982. 'url' => $videoParams['tail_frame_url'],
  3983. ],
  3984. 'role' => 'last_frame',
  3985. ];
  3986. }
  3987. }
  3988. }
  3989. // 获取配音音频URL
  3990. $audioUrl = getProp($segment, 'audio_url');
  3991. $audioDuration = getProp($segment, 'audio_duration');
  3992. // 音频传入的前提:必须有至少一张图片或一个视频
  3993. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3994. // dd($videoParams);
  3995. // 根据模型选择不同的视频生成方法
  3996. if (strpos($model, 'jimeng') !== false) {
  3997. // 即梦模型参数调整
  3998. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3999. unset($videoParams['content']); // 即梦不使用content格式
  4000. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4001. } elseif (strpos($model, 'kling') !== false) {
  4002. // Keling模型参数调整
  4003. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4004. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4005. unset($videoParams['ratio']);
  4006. unset($videoParams['content']); // Keling不使用content格式
  4007. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4008. } elseif (strpos($model, 'zhizhen') !== false) {
  4009. // 智帧20等新模型使用统一API
  4010. // 构建统一API参数
  4011. $unifiedParams = [
  4012. 'model_code' => $model,
  4013. 'alias_segment_id' => $segment_id,
  4014. 'prompt' => trim($fullPrompt),
  4015. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4016. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4017. 'video_ratio' => $ratio,
  4018. 'seed' => -1,
  4019. ];
  4020. // 构建parameters参数
  4021. $parameters = [
  4022. 'seconds' => $unifiedParams['video_duration'],
  4023. 'resolution' => $unifiedParams['video_resolution'],
  4024. 'ratio' => $ratio,
  4025. // 'video_mode' => 'multi_image',
  4026. // 'mode' => 'multi_image',
  4027. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4028. ];
  4029. $hasImage = false;
  4030. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4031. if ($hasImage) {
  4032. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4033. if (isset($videoParams['tail_frame_url'])) {
  4034. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4035. }
  4036. // 只有在有图片的情况下才能添加参考音频
  4037. if ($audioUrl) {
  4038. // $parameters['reference_audios'] = [$audioUrl];
  4039. }
  4040. } else {
  4041. // 没有图片时,记录错误日志
  4042. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4043. 'segment_id' => $segment_id,
  4044. 'model' => $model
  4045. ]);
  4046. }
  4047. $unifiedParams['parameters'] = $parameters;
  4048. // 调用统一API创建任务
  4049. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4050. } else {
  4051. // Seedance模型(默认)
  4052. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4053. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4054. // 添加配音音频到content中
  4055. $videoParams['content'][] = [
  4056. 'type' => 'audio_url',
  4057. 'audio_url' => [
  4058. 'url' => $audioUrl,
  4059. ],
  4060. 'role' => 'reference_audio',
  4061. ];
  4062. // 优化提示词,增加音频相关描述
  4063. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4064. $videoParams['prompt'] = $audioPrompt;
  4065. $videoParams['content'][0]['text'] = $audioPrompt;
  4066. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4067. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4068. }
  4069. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4070. }
  4071. // 更新分镜表的视频任务信息
  4072. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4073. 'video_task_id' => $task->id,
  4074. 'video_task_status' => '生成中',
  4075. 'generate_audio' => $generate_audio,
  4076. 'updated_at' => date('Y-m-d H:i:s')
  4077. ]);
  4078. return [
  4079. 'task_id' => $task->id,
  4080. 'status' => $task->status,
  4081. 'segment_id' => $segment_id,
  4082. 'video_duration' => $videoDuration
  4083. ];
  4084. }
  4085. public function createActVideoTask($data) {
  4086. $act_id = getProp($data, 'act_id');
  4087. $first_frame_url = getProp($data, 'first_frame_url');
  4088. $tail_frame_url = getProp($data, 'tail_frame_url');
  4089. $generate_audio = getProp($data, 'generate_audio', 1);
  4090. $video_duration = getProp($data, 'video_duration');
  4091. $video_resolution = getProp($data, 'video_resolution');
  4092. $ratio = getProp($data, 'ratio');
  4093. $products = getProp($data, 'products', []);
  4094. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4095. if (!is_array($reference_images) || !is_array($products)) {
  4096. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4097. }
  4098. if (!$act_id) {
  4099. Utils::throwError('1002:片段ID不能为空');
  4100. }
  4101. // 获取片段信息
  4102. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4103. if (!$act) {
  4104. Utils::throwError('20003:片段不存在');
  4105. }
  4106. $act = (array)$act;
  4107. $anime_id = getProp($act, 'anime_id');
  4108. $episode_id = getProp($act, 'episode_id');
  4109. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4110. $ace_mode = getProp($anime, 'ace_mode');
  4111. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4112. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4113. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4114. // 将资产中新出现的资产放到extra_products中
  4115. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4116. if (!empty($products) && $episode) {
  4117. // 获取剧集中的角色、场景和道具列表
  4118. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4119. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4120. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4121. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4122. // 构建角色名称列表
  4123. $role_names = array_column($roles, 'role');
  4124. // 构建场景名称列表
  4125. $scene_names = array_column($scenes, 'scene');
  4126. // 构建道具名称列表
  4127. $prop_names = array_column($props, 'prop');
  4128. // 遍历传入的products
  4129. foreach ($products as $product) {
  4130. $product_name = getProp($product, 'product_name');
  4131. // 如果product_name不在roles、scenes和props中
  4132. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4133. // 查找是否在extra_products中存在同名的
  4134. $found = false;
  4135. foreach ($extra_products as $key => $extra_product) {
  4136. if (getProp($extra_product, 'product_name') === $product_name) {
  4137. // 有同名的则覆盖
  4138. $extra_products[$key] = $product;
  4139. $found = true;
  4140. break;
  4141. }
  4142. }
  4143. // 没有则新增
  4144. if (!$found) {
  4145. $extra_products[] = $product;
  4146. }
  4147. }
  4148. }
  4149. if ($extra_products) {
  4150. // 保存到数据库
  4151. DB::table('mp_anime_episodes')
  4152. ->where('id', $episode_id)
  4153. ->update([
  4154. 'extra_products' => json_encode($extra_products, 256),
  4155. 'updated_at' => date('Y-m-d H:i:s')
  4156. ]);
  4157. }
  4158. }
  4159. // 获取分镜内容
  4160. $actContent = getProp($act, 'act_show_content', '');
  4161. // 音效同出(默认使用)
  4162. $current_generate_audio = $generate_audio ? 1 : 0;
  4163. // 构建完整的提示词
  4164. $processResult = $this->processActContentWithProducts($actContent, $products);
  4165. $fullPrompt = $processResult['content'];
  4166. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4167. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4168. // 处理视频模型
  4169. $model = getProp($data, 'model');
  4170. if (!$model) {
  4171. $model = getProp($episode, 'video_model');
  4172. if (!$model) {
  4173. // episode表也没有,使用默认值
  4174. $model = 'zhizhen-20';
  4175. }
  4176. }
  4177. // 验证模型是否在可用模型表中
  4178. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4179. $model = 'zhizhen-20';
  4180. }
  4181. // 保存到episode表
  4182. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4183. 'video_model' => $model,
  4184. 'updated_at' => date('Y-m-d H:i:s')
  4185. ]);
  4186. // 构建视频生成参数
  4187. $videoParams = [
  4188. 'model' => $model,
  4189. 'alias_act_id' => $act_id,
  4190. 'prompt' => trim($fullPrompt),
  4191. 'video_duration' => $videoDuration,
  4192. 'video_resolution' => $video_resolution,
  4193. 'seed' => -1,
  4194. 'ratio' => $ratio,
  4195. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4196. 'draft' => false,
  4197. 'watermark' => false,
  4198. 'camera_fixed' => false,
  4199. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4200. ];
  4201. // 如果分镜有图片,作为首帧
  4202. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4203. $hasVideo = !empty(getProp($act, 'video_url'));
  4204. if ($hasImage) {
  4205. if ($first_frame_url) {
  4206. $videoParams['first_frame_url'] = $first_frame_url;
  4207. }else {
  4208. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4209. }
  4210. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4211. }
  4212. // 构建content数组
  4213. $videoParams['content'] = [
  4214. [
  4215. 'type' => 'text',
  4216. 'text' => $videoParams['prompt'],
  4217. ]
  4218. ];
  4219. // 如果有首帧图片,添加到content中
  4220. if ($hasImage) {
  4221. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4222. $videoParams['content'][] = [
  4223. 'type' => 'image_url',
  4224. 'image_url' => [
  4225. 'url' => $videoParams['first_frame_url'],
  4226. ],
  4227. 'role' => 'reference_image',
  4228. ];
  4229. if (isset($videoParams['tail_frame_url'])) {
  4230. $videoParams['content'][] = [
  4231. 'type' => 'image_url',
  4232. 'image_url' => [
  4233. 'url' => $videoParams['tail_frame_url'],
  4234. ],
  4235. 'role' => 'reference_image',
  4236. ];
  4237. }
  4238. }else {
  4239. $videoParams['content'][] = [
  4240. 'type' => 'image_url',
  4241. 'image_url' => [
  4242. 'url' => $videoParams['first_frame_url'],
  4243. ],
  4244. 'role' => 'first_frame',
  4245. ];
  4246. if (isset($videoParams['tail_frame_url'])) {
  4247. $videoParams['content'][] = [
  4248. 'type' => 'image_url',
  4249. 'image_url' => [
  4250. 'url' => $videoParams['tail_frame_url'],
  4251. ],
  4252. 'role' => 'last_frame',
  4253. ];
  4254. }
  4255. }
  4256. }
  4257. // dd($videoParams);
  4258. // 根据模型选择不同的视频生成方法
  4259. if (strpos($model, 'jimeng') !== false) {
  4260. // 即梦模型参数调整
  4261. unset($videoParams['content']); // 即梦不使用content格式
  4262. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4263. } elseif (strpos($model, 'kling') !== false) {
  4264. // Keling模型参数调整
  4265. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4266. unset($videoParams['ratio']);
  4267. unset($videoParams['content']); // Keling不使用content格式
  4268. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4269. } elseif (strpos($model, 'zhizhen') !== false) {
  4270. // 智帧20等新模型使用统一API
  4271. // 构建统一API参数
  4272. $unifiedParams = [
  4273. 'model_code' => $model,
  4274. 'alias_act_id' => $act_id,
  4275. 'prompt' => trim($fullPrompt),
  4276. 'video_duration' => $videoDuration,
  4277. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4278. 'video_ratio' => $ratio,
  4279. 'seed' => -1,
  4280. ];
  4281. // 构建parameters参数
  4282. $parameters = [
  4283. 'seconds' => $unifiedParams['video_duration'],
  4284. 'resolution' => $unifiedParams['video_resolution'],
  4285. 'ratio' => $ratio,
  4286. // 'video_mode' => 'multi_image',
  4287. // 'mode' => 'multi_image',
  4288. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4289. ];
  4290. $hasImage = false;
  4291. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4292. if ($hasImage) {
  4293. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4294. if (isset($videoParams['tail_frame_url'])) {
  4295. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4296. }
  4297. } else {
  4298. // 没有图片时,记录错误日志
  4299. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4300. 'act_id' => $act_id,
  4301. 'model' => $model
  4302. ]);
  4303. }
  4304. if ($reference_images) {
  4305. // 限制只传入9张参考图
  4306. $reference_images = array_slice($reference_images, 0, 9);
  4307. // 在处理之前先保存原始reference_images到任务参数中
  4308. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4309. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4310. $parameters['reference_images'] = $reference_images;
  4311. $parameters['video_mode'] = 'multi_image';
  4312. $parameters['mode'] = 'multi_image';
  4313. }
  4314. $unifiedParams['parameters'] = $parameters;
  4315. // 调用统一API创建任务
  4316. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4317. } else {
  4318. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4319. }
  4320. // 更新分镜表的视频任务信息
  4321. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4322. 'video_task_id' => $task->id,
  4323. 'video_task_status' => '生成中',
  4324. 'generate_audio' => $generate_audio,
  4325. 'updated_at' => date('Y-m-d H:i:s')
  4326. ]);
  4327. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4328. $episode_number = getProp($act, 'episode_number');
  4329. $act_number = getProp($act, 'act_number');
  4330. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4331. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4332. }
  4333. return [
  4334. 'task_id' => $task->id,
  4335. 'status' => $task->status,
  4336. 'act_id' => $act_id,
  4337. 'video_duration' => $videoDuration
  4338. ];
  4339. }
  4340. /**
  4341. * 根据提示词内容智能计算最优视频时长
  4342. *
  4343. * @param string $segmentContent 分镜内容
  4344. * @param string $tailFrame 尾帧描述
  4345. * @return int 视频时长(2-12秒)
  4346. */
  4347. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4348. // 合并所有文本内容
  4349. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4350. // 如果没有内容,返回默认时长
  4351. if (empty($fullText)) {
  4352. return 5;
  4353. }
  4354. // 计算文本长度(中文字符按2个字符计算)
  4355. $textLength = mb_strlen($fullText, 'UTF-8');
  4356. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4357. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4358. // 分析内容复杂度
  4359. $complexityScore = $this->analyzeContentComplexity($fullText);
  4360. // 基础时长计算(根据文本长度)
  4361. $baseDuration = 3; // 默认2秒
  4362. // if ($adjustedLength <= 20) {
  4363. // $baseDuration = 3;
  4364. // } elseif ($adjustedLength <= 40) {
  4365. // $baseDuration = 4;
  4366. // } elseif ($adjustedLength <= 60) {
  4367. // $baseDuration = 5;
  4368. // } elseif ($adjustedLength <= 80) {
  4369. // $baseDuration = 6;
  4370. // } elseif ($adjustedLength <= 100) {
  4371. // $baseDuration = 7;
  4372. // } elseif ($adjustedLength <= 120) {
  4373. // $baseDuration = 8;
  4374. // } else {
  4375. // $baseDuration = 9;
  4376. // }
  4377. // 根据内容复杂度调整时长
  4378. $finalDuration = $baseDuration + $complexityScore;
  4379. // 确保时长在2-12秒范围内
  4380. return max(4, min(12, $finalDuration));
  4381. }
  4382. /**
  4383. * 分析内容复杂度,返回时长调整值
  4384. *
  4385. * @param string $text 文本内容
  4386. * @return int 调整值(-2到+3)
  4387. */
  4388. private function analyzeContentComplexity($text) {
  4389. $score = 0;
  4390. // 动作关键词(需要更长时间展现)
  4391. $actionKeywords = [
  4392. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4393. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4394. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4395. ];
  4396. // 静态关键词(可以用较短时间)
  4397. $staticKeywords = [
  4398. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4399. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4400. ];
  4401. // 复杂场景关键词(需要更长时间)
  4402. $complexSceneKeywords = [
  4403. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4404. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4405. ];
  4406. // 情感关键词(需要适中时间表现)
  4407. $emotionKeywords = [
  4408. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4409. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4410. ];
  4411. // 检查动作关键词
  4412. foreach ($actionKeywords as $keyword) {
  4413. if (strpos($text, $keyword) !== false) {
  4414. $score += 1;
  4415. break; // 避免重复加分
  4416. }
  4417. }
  4418. // 检查静态关键词
  4419. foreach ($staticKeywords as $keyword) {
  4420. if (strpos($text, $keyword) !== false) {
  4421. $score -= 1;
  4422. break;
  4423. }
  4424. }
  4425. // 检查复杂场景关键词
  4426. foreach ($complexSceneKeywords as $keyword) {
  4427. if (strpos($text, $keyword) !== false) {
  4428. $score += 1;
  4429. break;
  4430. }
  4431. }
  4432. // 检查情感关键词
  4433. foreach ($emotionKeywords as $keyword) {
  4434. if (strpos($text, $keyword) !== false) {
  4435. $score += 1;
  4436. break;
  4437. }
  4438. }
  4439. // 检查时间相关词汇
  4440. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4441. $score += 1;
  4442. }
  4443. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4444. $score -= 1;
  4445. }
  4446. // 检查转场词汇
  4447. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4448. $score += 1;
  4449. }
  4450. // 检查环境描述(复杂环境需要更多时间)
  4451. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4452. $score += 1;
  4453. }
  4454. // 检查对话内容(对话需要更多时间)
  4455. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4456. $score += 1;
  4457. }
  4458. // 限制调整范围
  4459. return max(-1, min(4, $score));
  4460. }
  4461. /**
  4462. * 创建完整视频合成任务
  4463. *
  4464. * @param array $data
  4465. * @return array
  4466. */
  4467. public function createCompleteVideoTask($data)
  4468. {
  4469. $animeId = getProp($data, 'anime_id');
  4470. $episodeId = getProp($data, 'episode_id');
  4471. // 验证参数
  4472. if (!$animeId || !$episodeId) {
  4473. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4474. }
  4475. // 检查是否已存在处理中的任务
  4476. $existingTask = DB::table('mp_complete_video_tasks')
  4477. ->where('anime_id', $animeId)
  4478. ->where('episode_id', $episodeId)
  4479. ->whereIn('generate_status', ['执行中'])
  4480. ->first();
  4481. if ($existingTask) {
  4482. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4483. }
  4484. // 获取全能模式状态
  4485. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4486. if ((int)$ace_mode === 1) {
  4487. // 获取所有片段的配音视频,按 act_number 排序
  4488. $segments = DB::table('mp_episode_segments')
  4489. ->where('anime_id', $animeId)
  4490. ->where('episode_id', $episodeId)
  4491. ->orderBy('segment_number')
  4492. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4493. ->get();
  4494. // 检查是否所有片段都有视频
  4495. $missingVideos = $segments->filter(function($segment) {
  4496. return empty($segment->video_url);
  4497. });
  4498. if ($missingVideos->isNotEmpty()) {
  4499. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4500. }
  4501. }else {
  4502. // 获取所有分镜的配音视频,按 segment_number 排序
  4503. $segments = DB::table('mp_episode_segments')
  4504. ->where('anime_id', $animeId)
  4505. ->where('episode_id', $episodeId)
  4506. ->orderBy('segment_number')
  4507. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4508. ->get();
  4509. // 检查是否所有分镜都有配音和视频
  4510. $missingVideos = $segments->filter(function($segment) {
  4511. return empty($segment->audio_url) || empty($segment->video_url);
  4512. });
  4513. if ($missingVideos->isNotEmpty()) {
  4514. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4515. }
  4516. }
  4517. if ($segments->isEmpty()) {
  4518. Utils::throwError('20003:未找到该剧集的分镜数据');
  4519. }
  4520. // 获取当前完整视频url
  4521. $completeVideoUrl = DB::table('mp_anime_episodes')
  4522. ->where('anime_id', $animeId)
  4523. ->where('id', $episodeId)
  4524. ->value('complete_video_url');
  4525. // 构建 generate_json
  4526. $generateJson = [];
  4527. $sequence = 1;
  4528. foreach ($segments as $segment) {
  4529. if ((int)$ace_mode === 1) {
  4530. $generateJson[] = [
  4531. 'sequence' => $sequence++,
  4532. 'video_url' => $segment->video_url,
  4533. 'video_time_point_start' => $segment->video_time_point_start,
  4534. 'video_time_point_end' => $segment->video_time_point_end
  4535. ];
  4536. }else {
  4537. $generateJson[] = [
  4538. 'sequence' => $sequence++,
  4539. 'video_url' => $segment->video_url,
  4540. 'audio_url' => $segment->audio_url,
  4541. 'video_time_point_start' => $segment->video_time_point_start,
  4542. 'video_time_point_end' => $segment->video_time_point_end
  4543. ];
  4544. }
  4545. }
  4546. // 创建任务
  4547. $now = date('Y-m-d H:i:s');
  4548. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4549. 'anime_id' => $animeId,
  4550. 'episode_id' => $episodeId,
  4551. 'generate_json' => json_encode($generateJson, 256),
  4552. 'generate_status' => '执行中',
  4553. 'complete_video_url' => '',
  4554. 'created_at' => $now,
  4555. 'updated_at' => $now
  4556. ]);
  4557. if (!$taskId) {
  4558. Utils::throwError('20003:创建任务失败');
  4559. }
  4560. // 更新剧集表的任务ID和状态
  4561. $boolen = DB::table('mp_anime_episodes')
  4562. ->where('anime_id', $animeId)
  4563. ->where('id', $episodeId)
  4564. ->update([
  4565. 'complete_video_task_id' => $taskId,
  4566. 'complete_video_task_status' => '执行中',
  4567. 'updated_at' => $now
  4568. ]);
  4569. if (!$boolen) {
  4570. Utils::throwError('20003:更新剧集表失败');
  4571. }
  4572. dLog('anime')->info('创建完整视频合成任务', [
  4573. 'task_id' => $taskId,
  4574. 'anime_id' => $animeId,
  4575. 'episode_id' => $episodeId,
  4576. 'segment_count' => count($generateJson)
  4577. ]);
  4578. // 请求远程服务器执行生成
  4579. $client = new Client(['timeout' => 600, 'verify' => false]);
  4580. try {
  4581. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4582. $response = $result->getBody()->getContents();
  4583. $response_arr = json_decode($response, true);
  4584. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4585. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4586. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4587. // // 更新任务状态为失败
  4588. // DB::table('mp_complete_video_tasks')
  4589. // ->where('id', $taskId)
  4590. // ->update([
  4591. // 'generate_status' => '执行失败',
  4592. // 'error_message' => $error_msg,
  4593. // 'updated_at' => date('Y-m-d H:i:s')
  4594. // ]);
  4595. // // 同步更新剧集表状态
  4596. // DB::table('mp_anime_episodes')
  4597. // ->where('complete_video_task_id', $taskId)
  4598. // ->update([
  4599. // 'complete_video_task_status' => '执行失败',
  4600. // 'updated_at' => date('Y-m-d H:i:s')
  4601. // ]);
  4602. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4603. }
  4604. } catch (\Exception $e) {
  4605. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4606. // 更新任务状态为失败
  4607. DB::table('mp_complete_video_tasks')
  4608. ->where('id', $taskId)
  4609. ->update([
  4610. 'generate_status' => '执行失败',
  4611. 'error_message' => $e->getMessage(),
  4612. 'updated_at' => date('Y-m-d H:i:s')
  4613. ]);
  4614. // 同步更新剧集表状态
  4615. DB::table('mp_anime_episodes')
  4616. ->where('complete_video_task_id', $taskId)
  4617. ->update([
  4618. 'complete_video_task_status' => '执行失败',
  4619. 'updated_at' => date('Y-m-d H:i:s')
  4620. ]);
  4621. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4622. }
  4623. // 开始轮询任务状态
  4624. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4625. $pollInterval = 5; // 每5秒轮询一次
  4626. $attempt = 0;
  4627. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4628. while ($attempt < $maxAttempts) {
  4629. sleep($pollInterval);
  4630. $attempt++;
  4631. // 查询任务状态
  4632. $task = DB::table('mp_complete_video_tasks')
  4633. ->where('id', $taskId)
  4634. ->first();
  4635. if (!$task) {
  4636. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4637. Utils::throwError('20003:任务不存在');
  4638. }
  4639. dLog('anime')->info('轮询任务状态', [
  4640. 'task_id' => $taskId,
  4641. 'attempt' => $attempt,
  4642. 'status' => $task->generate_status
  4643. ]);
  4644. // 检查任务是否完成
  4645. if ($task->generate_status === '执行成功') {
  4646. // 同步更新剧集表状态
  4647. $boolen3 = DB::table('mp_anime_episodes')
  4648. ->where('anime_id', $animeId)
  4649. ->where('id', $episodeId)
  4650. ->update([
  4651. 'complete_video_url' => $task->complete_video_url,
  4652. 'complete_video_task_status' => '执行成功',
  4653. 'updated_at' => date('Y-m-d H:i:s')
  4654. ]);
  4655. dLog('anime')->info('视频合成任务完成', [
  4656. 'task_id' => $taskId,
  4657. 'video_url' => $task->complete_video_url,
  4658. 'attempts' => $attempt
  4659. ]);
  4660. // 如果更新成功则远程删除之前的文件
  4661. if ($boolen3 && $completeVideoUrl) {
  4662. $encode_url = urlencode($completeVideoUrl);
  4663. $client = new Client(['timeout' => 300, 'verify' => false]);
  4664. // 根据ID通过API通知合成音频
  4665. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4666. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4667. $response = $result->getBody()->getContents();
  4668. $response_arr = json_decode($response, true);
  4669. Log::info('火山删除音频返回: '.$response);
  4670. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4671. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4672. Log::info('火山删除音频失败: '.$error_msg);
  4673. // Utils::throwError('20003:火山删除音频失败');
  4674. }
  4675. }
  4676. return [
  4677. 'task_id' => $taskId,
  4678. 'anime_id' => $animeId,
  4679. 'episode_id' => $episodeId,
  4680. 'segment_count' => count($generateJson),
  4681. 'generate_status' => '执行成功',
  4682. 'complete_video_url' => $task->complete_video_url,
  4683. ];
  4684. }
  4685. // 检查任务是否失败
  4686. if ($task->generate_status === '执行失败') {
  4687. // 同步更新剧集表状态
  4688. DB::table('mp_anime_episodes')
  4689. ->where('anime_id', $animeId)
  4690. ->where('id', $episodeId)
  4691. ->update([
  4692. 'complete_video_task_status' => '执行失败',
  4693. 'updated_at' => date('Y-m-d H:i:s')
  4694. ]);
  4695. $errorMessage = $task->error_message ?? '未知错误';
  4696. dLog('anime')->error('视频合成任务失败', [
  4697. 'task_id' => $taskId,
  4698. 'error' => $errorMessage,
  4699. 'attempts' => $attempt
  4700. ]);
  4701. return [
  4702. 'task_id' => $taskId,
  4703. 'anime_id' => $animeId,
  4704. 'episode_id' => $episodeId,
  4705. 'segment_count' => count($generateJson),
  4706. 'generate_status' => '执行失败',
  4707. 'error_message' => $errorMessage
  4708. ];
  4709. }
  4710. }
  4711. // 超时处理
  4712. dLog('anime')->warning('视频合成任务超时', [
  4713. 'task_id' => $taskId,
  4714. 'max_attempts' => $maxAttempts,
  4715. 'timeout_seconds' => $maxAttempts * $pollInterval
  4716. ]);
  4717. // 更新任务状态为超时
  4718. DB::table('mp_complete_video_tasks')
  4719. ->where('id', $taskId)
  4720. ->update([
  4721. 'generate_status' => '超时',
  4722. 'error_message' => '任务执行超时(5分钟)',
  4723. 'updated_at' => date('Y-m-d H:i:s')
  4724. ]);
  4725. return [
  4726. 'task_id' => $taskId,
  4727. 'anime_id' => $animeId,
  4728. 'episode_id' => $episodeId,
  4729. 'segment_count' => count($generateJson),
  4730. 'generate_status' => '超时',
  4731. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4732. ];
  4733. }
  4734. public function generateImg($data) {
  4735. $prompt = getProp($data, 'prompt');
  4736. $episode_id = getProp($data, 'episode_id');
  4737. $ref_img_urls = getProp($data, 'ref_img_urls');
  4738. $ratio = getProp($data, 'ratio', '9:16');
  4739. $resolution = getProp($data, 'resolution', '2k');
  4740. // 定义分辨率和宽高比对应的尺寸映射表
  4741. $sizeMap = [
  4742. '2k' => [
  4743. '1:1' => ['width' => 2048, 'height' => 2048],
  4744. '4:3' => ['width' => 2304, 'height' => 1728],
  4745. '3:4' => ['width' => 1728, 'height' => 2304],
  4746. '16:9' => ['width' => 2848, 'height' => 1600],
  4747. '9:16' => ['width' => 1600, 'height' => 2848],
  4748. '3:2' => ['width' => 2496, 'height' => 1664],
  4749. '2:3' => ['width' => 1664, 'height' => 2496],
  4750. '21:9' => ['width' => 3136, 'height' => 1344],
  4751. ],
  4752. '3k' => [
  4753. '1:1' => ['width' => 3072, 'height' => 3072],
  4754. '4:3' => ['width' => 3456, 'height' => 2592],
  4755. '3:4' => ['width' => 2592, 'height' => 3456],
  4756. '16:9' => ['width' => 4096, 'height' => 2304],
  4757. '9:16' => ['width' => 2304, 'height' => 4096],
  4758. '2:3' => ['width' => 2496, 'height' => 3744],
  4759. '3:2' => ['width' => 3744, 'height' => 2496],
  4760. '21:9' => ['width' => 4704, 'height' => 2016],
  4761. ],
  4762. '4k' => [
  4763. '1:1' => ['width' => 4096, 'height' => 4096],
  4764. '3:4' => ['width' => 3520, 'height' => 4704],
  4765. '4:3' => ['width' => 4704, 'height' => 3520],
  4766. '16:9' => ['width' => 5504, 'height' => 3040],
  4767. '9:16' => ['width' => 3040, 'height' => 5504],
  4768. '2:3' => ['width' => 3328, 'height' => 4992],
  4769. '3:2' => ['width' => 4992, 'height' => 3328],
  4770. '21:9' => ['width' => 6240, 'height' => 2656],
  4771. ],
  4772. ];
  4773. // 参数验证
  4774. $resolution = strtolower($resolution);
  4775. if (!isset($sizeMap[$resolution])) {
  4776. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4777. }
  4778. if (!isset($sizeMap[$resolution][$ratio])) {
  4779. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4780. }
  4781. // 根据 ratio 和 resolution 确定宽高
  4782. $width = $sizeMap[$resolution][$ratio]['width'];
  4783. $height = $sizeMap[$resolution][$ratio]['height'];
  4784. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4785. if (is_json($ref_img_urls)) {
  4786. $ref_img_urls = json_decode($ref_img_urls, true);
  4787. }else {
  4788. $ref_img_urls = explode(',', $ref_img_urls);
  4789. }
  4790. }
  4791. // 处理图片模型
  4792. $model = getProp($data, 'model');
  4793. if (!$model) {
  4794. // 用户没有输入,从episode表获取
  4795. if ($episode_id) {
  4796. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4797. $model = getProp($episode, 'image_model');
  4798. }
  4799. if (!$model) {
  4800. // episode表也没有,使用默认值
  4801. $model = 'doubao-seedream-5-0-lite-260128';
  4802. }
  4803. }
  4804. // 验证模型是否在可用模型表中
  4805. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4806. // $model = 'doubao-seedream-5-0-lite-260128';
  4807. Utils::throwError('20003:该模型已不可用,请更换!');
  4808. }
  4809. // 保存到episode表
  4810. if ($episode_id) {
  4811. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4812. 'image_model' => $model,
  4813. 'updated_at' => date('Y-m-d H:i:s')
  4814. ]);
  4815. }
  4816. // 参数验证
  4817. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4818. try {
  4819. // 创建图片生成任务
  4820. $params = [
  4821. 'prompt' => $prompt,
  4822. 'model' => $model,
  4823. 'ref_img_urls' => '',
  4824. 'width' => $width,
  4825. 'height' => $height
  4826. ];
  4827. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4828. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4829. $task_id = $task->id;
  4830. if (!$task_id) {
  4831. Utils::throwError('20003:创建图片生成任务失败');
  4832. }
  4833. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4834. $model = getProp($task, 'model');
  4835. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4836. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4837. $isSyncModel = $isVolcModel || $isGptModel;
  4838. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4839. $start_time = time();
  4840. $timeout = 300; // 5分钟
  4841. $img_url = '';
  4842. while (time() - $start_time < $timeout) {
  4843. sleep(3);
  4844. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4845. if ($isSyncModel) {
  4846. // 刷新任务状态
  4847. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4848. if ($task->status === 'success' && $task->result_url) {
  4849. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4850. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4851. break;
  4852. } elseif ($task->status === 'failed') {
  4853. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4854. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4855. }
  4856. // // 如果还在处理中,提示用户稍后查看
  4857. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4858. }else {
  4859. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4860. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4861. if ($statusInfo['status'] === 'success') {
  4862. $task->updateStatus('success', [
  4863. 'result_url' => $statusInfo['result_url'],
  4864. 'result_json' => $statusInfo['result_json'] ?? []
  4865. ]);
  4866. $img_url = $statusInfo['result_url'][0];
  4867. break;
  4868. } elseif ($statusInfo['status'] === 'failed') {
  4869. $task->updateStatus('failed', [
  4870. 'error_message' => $statusInfo['error_message'],
  4871. 'result_json' => $statusInfo['result_json'] ?? []
  4872. ]);
  4873. dLog('anime')->error('图片生成失败,', [
  4874. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4875. ]);
  4876. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4877. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4878. }
  4879. }
  4880. }
  4881. if (empty($img_url)) {
  4882. Utils::throwError('20003:图片生成超时,请稍后重试');
  4883. }
  4884. return $img_url;
  4885. } catch (\Exception $e) {
  4886. dLog('anime')->error('更新角色或场景失败', [
  4887. 'error' => $e->getMessage()
  4888. ]);
  4889. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4890. Utils::throwError('20003:' . $e->getMessage());
  4891. }
  4892. }
  4893. /**
  4894. * 使用文生文模型解析分镜内容
  4895. */
  4896. private function parseSegmentContentWithAI($segment_content) {
  4897. try {
  4898. // 使用DeepSeek服务的公开方法解析分镜内容
  4899. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4900. } catch (\Exception $e) {
  4901. // 如果AI解析失败,记录日志并返回原内容
  4902. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4903. return $segment_content;
  4904. }
  4905. }
  4906. /**
  4907. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4908. *
  4909. * @param int $episode_id 分集ID
  4910. * @param int $anime_id 动漫ID
  4911. * @param array $roles 分集角色数组(引用传递)
  4912. * @param array $scenes 分集场景数组(引用传递)
  4913. * @param array $episode 分集数据
  4914. */
  4915. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4916. // 获取全局动漫的角色和场景数据
  4917. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4918. if (!$anime) return;
  4919. $art_style_type = getProp($anime, 'art_style_type');
  4920. $character_prefix = '';
  4921. $scene_prefix = '';
  4922. if ($art_style_type) {
  4923. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4924. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4925. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4926. }
  4927. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4928. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4929. $roles_updated = false;
  4930. $scenes_updated = false;
  4931. // 处理角色
  4932. foreach ($roles as &$role) {
  4933. $role_name = getProp($role, 'role');
  4934. $role_description = getProp($role, 'description');
  4935. $role_pic_prompt = getProp($role, 'pic_prompt');
  4936. $role_url = getProp($role, 'url');
  4937. $role_task_id = getProp($role, 'task_id');
  4938. // 如果已有URL或已有任务ID,跳过
  4939. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4940. continue;
  4941. }
  4942. $url_inherited = false;
  4943. // 尝试从全局数据中继承
  4944. foreach ($global_roles as $global_role) {
  4945. $global_role_name = getProp($global_role, 'role');
  4946. $global_role_description = getProp($global_role, 'description');
  4947. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4948. $global_role_url = getProp($global_role, 'url');
  4949. $global_role_task_id = getProp($global_role, 'task_id');
  4950. $global_role_task_status = getProp($global_role, 'task_status');
  4951. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4952. if ($role_name === $global_role_name
  4953. && $role_description === $global_role_description
  4954. && $role_pic_prompt === $global_role_pic_prompt
  4955. && !empty($global_role_url)) {
  4956. // 继承 task_id、task_status 和 url
  4957. $role['task_id'] = $global_role_task_id;
  4958. $role['task_status'] = $global_role_task_status;
  4959. $role['url'] = $global_role_url;
  4960. $roles_updated = true;
  4961. $url_inherited = true;
  4962. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4963. break;
  4964. }
  4965. }
  4966. // 如果无法继承且没有任务ID,创建新任务
  4967. if (!$url_inherited && empty($role_task_id)) {
  4968. try {
  4969. $art_style = getProp($episode, 'art_style');
  4970. // 优先使用 pic_prompt,如果没有则使用 description
  4971. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4972. // if ($art_style) {
  4973. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4974. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4975. // }
  4976. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4977. $params = [
  4978. 'prompt' => $description,
  4979. 'ref_img_urls' => []
  4980. ];
  4981. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4982. $task_id = $task->id;
  4983. if ($task_id) {
  4984. $role['task_id'] = $task_id;
  4985. $role['task_status'] = 'processing';
  4986. $roles_updated = true;
  4987. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4988. }
  4989. } catch (\Exception $e) {
  4990. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4991. }
  4992. }
  4993. }
  4994. // 处理场景
  4995. foreach ($scenes as &$scene) {
  4996. $scene_name = getProp($scene, 'scene');
  4997. $scene_description = getProp($scene, 'description');
  4998. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4999. $scene_url = getProp($scene, 'url');
  5000. $scene_task_id = getProp($scene, 'task_id');
  5001. // 如果已有URL或已有任务ID,跳过
  5002. if (!empty($scene_url) || !empty($scene_task_id)) {
  5003. continue;
  5004. }
  5005. $url_inherited = false;
  5006. // 尝试从全局数据中继承
  5007. foreach ($global_scenes as $global_scene) {
  5008. $global_scene_name = getProp($global_scene, 'scene');
  5009. $global_scene_description = getProp($global_scene, 'description');
  5010. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5011. $global_scene_url = getProp($global_scene, 'url');
  5012. $global_scene_task_id = getProp($global_scene, 'task_id');
  5013. $global_scene_task_status = getProp($global_scene, 'task_status');
  5014. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5015. if ($scene_name === $global_scene_name
  5016. && $scene_description === $global_scene_description
  5017. && $scene_pic_prompt === $global_scene_pic_prompt
  5018. && !empty($global_scene_url)) {
  5019. // 继承 task_id、task_status 和 url
  5020. $scene['task_id'] = $global_scene_task_id;
  5021. $scene['task_status'] = $global_scene_task_status;
  5022. $scene['url'] = $global_scene_url;
  5023. $scenes_updated = true;
  5024. $url_inherited = true;
  5025. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5026. break;
  5027. }
  5028. }
  5029. // 如果无法继承且没有任务ID,创建新任务
  5030. if (!$url_inherited && empty($scene_task_id)) {
  5031. try {
  5032. $art_style = getProp($episode, 'art_style');
  5033. // 优先使用 pic_prompt,如果没有则使用 description
  5034. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5035. // if ($art_style) {
  5036. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5037. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5038. // }
  5039. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5040. $params = [
  5041. 'prompt' => $description,
  5042. 'ref_img_urls' => []
  5043. ];
  5044. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5045. $task_id = $task->id;
  5046. if ($task_id) {
  5047. $scene['task_id'] = $task_id;
  5048. $scene['task_status'] = 'processing';
  5049. $scenes_updated = true;
  5050. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5051. }
  5052. } catch (\Exception $e) {
  5053. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5054. }
  5055. }
  5056. }
  5057. // 如果有更新,保存到数据库
  5058. if ($roles_updated || $scenes_updated) {
  5059. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5060. if ($roles_updated) {
  5061. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5062. }
  5063. if ($scenes_updated) {
  5064. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5065. }
  5066. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5067. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5068. }
  5069. }
  5070. /**
  5071. * 根据图片URL使用AI反推图片提示词
  5072. *
  5073. * @param string $img_url 图片URL
  5074. * @return string 反推的提示词
  5075. */
  5076. private function generateImagePromptFromUrl($img_url) {
  5077. try {
  5078. // 获取默认模型
  5079. $model = 'doubao-seed-2-0-mini-260215';
  5080. // 构建messages参数
  5081. $messages = [
  5082. [
  5083. 'role' => 'user',
  5084. 'content' => [
  5085. [
  5086. 'type' => 'text',
  5087. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5088. ],
  5089. [
  5090. 'type' => 'image_url',
  5091. 'image_url' => [
  5092. 'url' => $img_url
  5093. ]
  5094. ]
  5095. ]
  5096. ]
  5097. ];
  5098. // 构建请求参数
  5099. $params = [
  5100. 'model' => $model,
  5101. 'messages' => $messages,
  5102. 'stream' => false,
  5103. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5104. ];
  5105. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5106. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5107. // 返回生成的内容
  5108. return getProp($result, 'fullContent', '图片描述生成失败');
  5109. } catch (\Exception $e) {
  5110. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5111. 'img_url' => $img_url
  5112. ]);
  5113. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5114. 'error' => $e->getMessage(),
  5115. 'img_url' => $img_url
  5116. ]);
  5117. return '图片描述生成失败: ' . $e->getMessage();
  5118. }
  5119. }
  5120. /**
  5121. * 音频试听接口
  5122. * 创建音频任务并轮询获取结果
  5123. *
  5124. * @param array $data 参数数组
  5125. * @return array 返回音频URL或错误信息
  5126. */
  5127. public function previewAudio($data) {
  5128. $dialogue = getProp($data, 'dialogue');
  5129. // 必填参数验证
  5130. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5131. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5132. $voice_type = getProp($data, 'voice_type');
  5133. $voice_name = getProp($data, 'voice_name');
  5134. $voice_actor = getProp($data, 'voice_actor');
  5135. $emotion_type = getProp($data, 'emotion_type');
  5136. $gender = getProp($data, 'gender', 0);
  5137. $emotion = getProp($data, 'emotion');
  5138. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5139. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5140. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5141. $pitch = getProp($data, 'pitch', 0);
  5142. try {
  5143. $now = date('Y-m-d H:i:s');
  5144. // 构建生成参数
  5145. $generate_json = json_encode([
  5146. 'text' => $dialogue,
  5147. 'role' => $voice_actor,
  5148. 'voice_type' => $voice_type,
  5149. 'voice_name' => $voice_name,
  5150. 'emotion' => $emotion,
  5151. 'emotion_type' => $emotion_type,
  5152. 'gender' => $gender,
  5153. 'speed_ratio' => $speed_ratio,
  5154. 'loudness_ratio' => $loudness_ratio,
  5155. 'emotion_scale' => $emotion_scale,
  5156. 'pitch' => $pitch,
  5157. ], 256);
  5158. // 请求远程服务器执行生成
  5159. $client = new Client(['timeout' => 600, 'verify' => false]);
  5160. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5161. $response = $result->getBody()->getContents();
  5162. $response_arr = json_decode($response, true);
  5163. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5164. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5165. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5166. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5167. }
  5168. $arr = $response_arr['data'];
  5169. $subtitle_info = $arr['subtitle_info'];
  5170. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5171. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5172. return [
  5173. 'audio_url' => $arr['url'],
  5174. 'subtitle_info' => $subtitle_info,
  5175. 'audio_duration' => round($audio_duration, 2)
  5176. ];
  5177. } catch (\Exception $e) {
  5178. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5179. Utils::throwError('20003:' . $e->getMessage());
  5180. }
  5181. }
  5182. /**
  5183. * 获取角色库列表(支持文件夹递归查询)
  5184. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5185. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5186. */
  5187. public function globalProducts($data) {
  5188. $uid = Site::getUid();
  5189. $cpid = Site::getCpid();
  5190. $role = Site::getRole();
  5191. $id = getProp($data, 'id', 0);
  5192. $parent_id = getProp($data, 'parent_id', 0);
  5193. $product_name = getProp($data, 'product_name');
  5194. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5195. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5196. if (!$product) {
  5197. Utils::throwError('20003:请选择产品类型');
  5198. }
  5199. // 根据角色和is_public参数确定查询范围
  5200. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5201. // user角色:根据is_public参数筛选
  5202. $query_user_ids = [];
  5203. if ($role === 'admin') {
  5204. // admin获取所有个人库和公共库
  5205. $query_user_ids = [$uid, 0];
  5206. } else {
  5207. // user角色根据is_public参数筛选
  5208. if ($is_public == 2) {
  5209. // 个人库+公共库
  5210. $query_user_ids = [$uid, 0];
  5211. } elseif ($is_public == 0) {
  5212. // 仅个人库
  5213. $query_user_ids = [$uid];
  5214. } elseif ($is_public == 1) {
  5215. // 仅公共库
  5216. $query_user_ids = [0];
  5217. }
  5218. }
  5219. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5220. if ($id || $product_name) {
  5221. $query = DB::table('mp_products')
  5222. ->where('cpid', $cpid)
  5223. ->whereIn('user_id', $query_user_ids)
  5224. ->where('is_deleted', 0);
  5225. // 如果指定了 id,按 id 精确查询
  5226. if ($id) {
  5227. $query->where('id', $id);
  5228. }
  5229. // 如果指定了 product_name,按名称模糊查询
  5230. if ($product_name) {
  5231. $query->where('product_name', 'like', "%{$product_name}%");
  5232. }
  5233. // 如果指定了 product,添加筛选条件
  5234. if ($product) {
  5235. $query->where('product', $product);
  5236. }
  5237. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5238. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5239. ->get()
  5240. ->map(function($value) {
  5241. $value = (array)$value;
  5242. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5243. $value['type'] = (int)$value['type'];
  5244. $value['parent_id'] = (int)$value['parent_id'];
  5245. $value['level'] = (int)$value['level'];
  5246. $value['product'] = (int)($value['product'] ?? 1);
  5247. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5248. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5249. unset($value['user_id']);
  5250. return $value;
  5251. })
  5252. ->toArray();
  5253. return $result;
  5254. }
  5255. // 递归获取所有子目录和角色
  5256. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5257. }
  5258. /**
  5259. * 递归获取指定目录下的所有子目录和角色
  5260. * @param int $cpid 公司ID
  5261. * @param int $parent_id 父目录ID
  5262. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5263. * @param array $query_user_ids 用户ID数组(支持多个)
  5264. * @param int $current_uid 当前用户ID(用于排序)
  5265. * @return array
  5266. */
  5267. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5268. // 查询当前层级的所有项(文件夹和角色)
  5269. $query = DB::table('mp_products')
  5270. ->where('cpid', $cpid)
  5271. ->where('is_deleted', 0)
  5272. ->where('parent_id', $parent_id);
  5273. // 添加用户ID验证(支持多个user_id)
  5274. if (!empty($query_user_ids)) {
  5275. $query->whereIn('user_id', $query_user_ids);
  5276. }
  5277. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5278. if ($product) {
  5279. $query->where('product', $product);
  5280. }
  5281. // 排序规则:
  5282. // 1. 文件夹在前(type DESC)
  5283. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5284. // 3. 其他排序规则
  5285. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5286. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5287. ->get();
  5288. $result = [];
  5289. foreach ($items as $item) {
  5290. $itemArray = [
  5291. 'id' => $item->id,
  5292. 'type' => (int)$item->type,
  5293. 'parent_id' => (int)$item->parent_id,
  5294. 'level' => (int)$item->level,
  5295. 'product_name' => $item->product_name,
  5296. 'url' => $item->url,
  5297. 'pic_prompt' => $item->pic_prompt ?? '',
  5298. 'three_view_image_url' => $item->three_view_image_url,
  5299. 'product' => (int)($item->product ?? 1),
  5300. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5301. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5302. ];
  5303. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5304. // 如果是文件夹,递归获取其子项
  5305. if ($item->type == 2) {
  5306. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5307. if (!empty($children)) {
  5308. $itemArray['children'] = $children;
  5309. }
  5310. }
  5311. $result[] = $itemArray;
  5312. }
  5313. return $result;
  5314. }
  5315. /**
  5316. * 创建文件夹
  5317. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5318. * @return int 返回新建文件夹ID
  5319. */
  5320. public function createFolder($data) {
  5321. $uid = Site::getUid();
  5322. $cpid = Site::getCpid();
  5323. $role = Site::getRole();
  5324. $parent_id = getProp($data, 'parent_id', 0);
  5325. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5326. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5327. // 如果是公共库操作,需要admin权限
  5328. if ($is_public && $role !== 'admin') {
  5329. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5330. }
  5331. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5332. $store_uid = $is_public ? 0 : $uid;
  5333. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5334. $product = getProp($data, 'product');
  5335. if (!in_array($product, [1, 2, 3])) {
  5336. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5337. }
  5338. // 验证父文件夹
  5339. $parent_level = 0;
  5340. if ($parent_id > 0) {
  5341. $parent = DB::table('mp_products')
  5342. ->where('id', $parent_id)
  5343. ->where('cpid', $cpid)
  5344. ->where('user_id', $store_uid)
  5345. ->where('type', 2)
  5346. ->where('is_deleted', 0)
  5347. ->first();
  5348. if (!$parent) {
  5349. Utils::throwError('20003:父文件夹不存在');
  5350. }
  5351. // 检查父文件夹的 product 类型是否一致
  5352. if ($parent->product != $product) {
  5353. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5354. }
  5355. $parent_level = $parent->level;
  5356. // 检查层级限制(最多3层)
  5357. if ($parent_level >= 3) {
  5358. Utils::throwError('20003:文件夹层级不能超过3层');
  5359. }
  5360. }
  5361. // 检查当前目录下是否已存在空白文件夹
  5362. $empty_folder_exists = DB::table('mp_products')
  5363. ->where('parent_id', $parent_id)
  5364. ->where('cpid', $cpid)
  5365. ->where('user_id', $store_uid)
  5366. ->where('type', 2)
  5367. ->where('product', $product)
  5368. ->where('product_name', '新建文件夹')
  5369. ->where('is_deleted', 0)
  5370. ->exists();
  5371. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5372. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5373. }
  5374. // 创建文件夹
  5375. $folder_id = DB::table('mp_products')->insertGetId([
  5376. 'user_id' => $store_uid,
  5377. 'cpid' => $cpid,
  5378. 'type' => 2,
  5379. 'parent_id' => $parent_id,
  5380. 'level' => $parent_level + 1,
  5381. 'product_name' => $folder_name,
  5382. 'product' => $product,
  5383. 'sort_order' => time(), // 使用时间戳作为排序权重
  5384. 'is_deleted' => 0,
  5385. 'created_at' => date('Y-m-d H:i:s'),
  5386. 'updated_at' => date('Y-m-d H:i:s')
  5387. ]);
  5388. return [
  5389. 'id' => $folder_id,
  5390. 'type' => 2,
  5391. 'parent_id' => $parent_id,
  5392. 'level' => $parent_level + 1,
  5393. 'product_name' => $folder_name,
  5394. 'product' => $product,
  5395. ];
  5396. }
  5397. /**
  5398. * 重命名文件夹或角色
  5399. * @param array $data 包含 id、product_name(新名称)
  5400. * @return bool
  5401. */
  5402. public function renameFolder($data) {
  5403. $uid = Site::getUid();
  5404. $cpid = Site::getCpid();
  5405. $role = Site::getRole();
  5406. $id = getProp($data, 'id');
  5407. $new_name = getProp($data, 'product_name');
  5408. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5409. if (!$id || !$new_name) {
  5410. Utils::throwError('20003:参数不完整');
  5411. }
  5412. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5413. $query_uid = $is_public ? 0 : $uid;
  5414. // 如果是公共库操作,需要admin权限
  5415. if ($is_public && $role !== 'admin') {
  5416. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5417. }
  5418. // 检查是否存在
  5419. $item = DB::table('mp_products')
  5420. ->where('id', $id)
  5421. ->where('cpid', $cpid)
  5422. ->where('user_id', $query_uid)
  5423. ->where('is_deleted', 0)
  5424. ->first();
  5425. if (!$item) {
  5426. Utils::throwError('20003:项目不存在');
  5427. }
  5428. return DB::table('mp_products')
  5429. ->where('id', $id)
  5430. ->where('cpid', $cpid)
  5431. ->where('user_id', $query_uid)
  5432. ->update([
  5433. 'product_name' => $new_name,
  5434. 'updated_at' => date('Y-m-d H:i:s')
  5435. ]);
  5436. }
  5437. /**
  5438. * 移动角色或文件夹到指定文件夹
  5439. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5440. * @return bool
  5441. */
  5442. public function moveProductOrFolder($data) {
  5443. $uid = Site::getUid();
  5444. $cpid = Site::getCpid();
  5445. $role = Site::getRole();
  5446. $id = getProp($data, 'id');
  5447. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5448. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5449. if (!$id) {
  5450. Utils::throwError('20003:请选择要移动的项目');
  5451. }
  5452. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5453. $query_uid = $is_public ? 0 : $uid;
  5454. // 如果是公共库操作,需要admin权限
  5455. if ($is_public && $role !== 'admin') {
  5456. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5457. }
  5458. // 检查要移动的项目
  5459. $item = DB::table('mp_products')
  5460. ->where('id', $id)
  5461. ->where('cpid', $cpid)
  5462. ->where('user_id', $query_uid)
  5463. ->where('is_deleted', 0)
  5464. ->first();
  5465. if (!$item) {
  5466. Utils::throwError('20003:项目不存在');
  5467. }
  5468. // 验证目标文件夹
  5469. $target_level = 0;
  5470. $target_product = $item->product; // 默认使用当前项目的 product
  5471. if ($target_parent_id > 0) {
  5472. $target_parent = DB::table('mp_products')
  5473. ->where('id', $target_parent_id)
  5474. ->where('cpid', $cpid)
  5475. ->where('user_id', $query_uid)
  5476. ->where('type', 2)
  5477. ->where('is_deleted', 0)
  5478. ->first();
  5479. if (!$target_parent) {
  5480. Utils::throwError('20003:目标文件夹不存在');
  5481. }
  5482. // 检查 product 类型是否一致
  5483. if ($target_parent->product != $item->product) {
  5484. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5485. }
  5486. $target_level = $target_parent->level;
  5487. $target_product = $target_parent->product;
  5488. // 如果移动的是文件夹,需要检查层级
  5489. if ($item->type == 2) {
  5490. // 计算移动后的最大层级
  5491. $max_child_level = $this->getMaxChildLevel($id);
  5492. $depth = $max_child_level - $item->level;
  5493. if ($target_level + 1 + $depth > 3) {
  5494. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5495. }
  5496. // 不能移动到自己或自己的子文件夹下
  5497. if ($this->isDescendant($target_parent_id, $id)) {
  5498. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5499. }
  5500. }
  5501. }
  5502. // 更新父文件夹和层级
  5503. $new_level = $target_level + 1;
  5504. DB::table('mp_products')
  5505. ->where('id', $id)
  5506. ->update([
  5507. 'parent_id' => $target_parent_id,
  5508. 'level' => $new_level,
  5509. 'updated_at' => date('Y-m-d H:i:s')
  5510. ]);
  5511. // 如果是文件夹,需要递归更新所有子项的层级
  5512. if ($item->type == 2) {
  5513. $this->updateChildrenLevel($id, $new_level);
  5514. }
  5515. return true;
  5516. }
  5517. /**
  5518. * 获取文件夹下最大子层级
  5519. * @param int $folder_id
  5520. * @return int
  5521. */
  5522. private function getMaxChildLevel($folder_id) {
  5523. $max_level = DB::table('mp_products')
  5524. ->where('parent_id', $folder_id)
  5525. ->where('is_deleted', 0)
  5526. ->max('level');
  5527. if (!$max_level) {
  5528. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5529. }
  5530. // 递归查找子文件夹
  5531. $children = DB::table('mp_products')
  5532. ->where('parent_id', $folder_id)
  5533. ->where('type', 2)
  5534. ->where('is_deleted', 0)
  5535. ->pluck('id');
  5536. foreach ($children as $child_id) {
  5537. $child_max = $this->getMaxChildLevel($child_id);
  5538. if ($child_max > $max_level) {
  5539. $max_level = $child_max;
  5540. }
  5541. }
  5542. return $max_level;
  5543. }
  5544. /**
  5545. * 检查 target_id 是否是 folder_id 的后代
  5546. * @param int $target_id
  5547. * @param int $folder_id
  5548. * @return bool
  5549. */
  5550. private function isDescendant($target_id, $folder_id) {
  5551. if ($target_id == $folder_id) {
  5552. return true;
  5553. }
  5554. $parent = DB::table('mp_products')
  5555. ->where('id', $target_id)
  5556. ->where('is_deleted', 0)
  5557. ->first();
  5558. if (!$parent || $parent->parent_id == 0) {
  5559. return false;
  5560. }
  5561. return $this->isDescendant($parent->parent_id, $folder_id);
  5562. }
  5563. /**
  5564. * 递归更新子项层级
  5565. * @param int $parent_id
  5566. * @param int $parent_level
  5567. */
  5568. private function updateChildrenLevel($parent_id, $parent_level) {
  5569. $children = DB::table('mp_products')
  5570. ->where('parent_id', $parent_id)
  5571. ->where('is_deleted', 0)
  5572. ->get();
  5573. foreach ($children as $child) {
  5574. $new_level = $parent_level + 1;
  5575. DB::table('mp_products')
  5576. ->where('id', $child->id)
  5577. ->update([
  5578. 'level' => $new_level,
  5579. 'updated_at' => date('Y-m-d H:i:s')
  5580. ]);
  5581. // 如果是文件夹,继续递归
  5582. if ($child->type == 2) {
  5583. $this->updateChildrenLevel($child->id, $new_level);
  5584. }
  5585. }
  5586. }
  5587. /**
  5588. * 获取文件夹路径(面包屑导航)
  5589. * @param array $data 包含 folder_id
  5590. * @return array 返回路径数组
  5591. */
  5592. public function getFolderPath($data) {
  5593. $uid = Site::getUid();
  5594. $cpid = Site::getCpid();
  5595. $folder_id = getProp($data, 'id', 0);
  5596. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5597. if ($folder_id == 0) {
  5598. return [
  5599. ['id' => 0, 'name' => '根目录']
  5600. ];
  5601. }
  5602. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5603. $query_uid = $is_public ? 0 : $uid;
  5604. $path = [];
  5605. $current_id = $folder_id;
  5606. while ($current_id > 0) {
  5607. $folder = DB::table('mp_products')
  5608. ->where('id', $current_id)
  5609. ->where('cpid', $cpid)
  5610. ->where('user_id', $query_uid)
  5611. ->where('type', 2)
  5612. ->where('is_deleted', 0)
  5613. ->first();
  5614. if (!$folder) {
  5615. break;
  5616. }
  5617. array_unshift($path, [
  5618. 'id' => $folder->id,
  5619. 'name' => $folder->product_name
  5620. ]);
  5621. $current_id = $folder->parent_id;
  5622. }
  5623. // 添加根目录
  5624. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5625. return $path;
  5626. }
  5627. public function createProduct($data) {
  5628. $uid = Site::getUid();
  5629. $cpid = Site::getCpid();
  5630. $role = Site::getRole();
  5631. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5632. // 如果是公共库操作,需要admin权限
  5633. if ($is_public && $role !== 'admin') {
  5634. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5635. }
  5636. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5637. $store_uid = $is_public ? 0 : $uid;
  5638. $product_name = trim(getProp($data, 'product_name'));
  5639. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5640. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5641. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5642. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5643. $url = trim(getProp($data, 'url'));
  5644. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5645. $versions = getProp($data, 'versions');
  5646. // 检查是否是正确的图片格式
  5647. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5648. $urlPath = parse_url($url, PHP_URL_PATH);
  5649. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5650. if (!in_array($extension, $allowedExtensions)) {
  5651. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5652. }
  5653. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5654. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5655. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5656. $product = getProp($data, 'product');
  5657. if (!in_array($product, [1, 2, 3])) {
  5658. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5659. }
  5660. // 获取父文件夹ID和层级
  5661. $parent_id = getProp($data, 'parent_id', 0);
  5662. $parent_level = 0;
  5663. if ($parent_id > 0) {
  5664. $parent = DB::table('mp_products')
  5665. ->where('id', $parent_id)
  5666. ->where('cpid', $cpid)
  5667. ->where('user_id', $store_uid)
  5668. ->where('type', 2)
  5669. ->where('is_deleted', 0)
  5670. ->first();
  5671. if (!$parent) {
  5672. Utils::throwError('20003:父文件夹不存在');
  5673. }
  5674. $parent_level = $parent->level;
  5675. }
  5676. $id = DB::table('mp_products')->insertGetId([
  5677. 'user_id' => $store_uid,
  5678. 'cpid' => $cpid,
  5679. 'type' => 1, // 1=角色图片
  5680. 'parent_id' => $parent_id,
  5681. 'level' => $parent_level + 1,
  5682. 'product_name' => $product_name,
  5683. 'url' => $url,
  5684. 'pic_prompt' => $pic_prompt,
  5685. 'product' => $product,
  5686. 'versions' => json_encode($versions, 256),
  5687. 'sort_order' => time(), // 使用时间戳作为排序权重
  5688. 'created_at' => date('Y-m-d H:i:s'),
  5689. 'updated_at' => date('Y-m-d H:i:s')
  5690. ]);
  5691. if (!$id) Utils::throwError('20003:创建失败');
  5692. return [
  5693. 'id' => $id,
  5694. 'type' => 1,
  5695. 'parent_id' => $parent_id,
  5696. 'level' => $parent_level + 1,
  5697. 'product_name' => $product_name,
  5698. 'url' => $url,
  5699. 'pic_prompt' => $pic_prompt,
  5700. 'product' => $product,
  5701. 'versions' => $versions
  5702. ];
  5703. }
  5704. public function editProduct($data) {
  5705. $uid = Site::getUid();
  5706. $cpid = Site::getCpid();
  5707. $role = Site::getRole();
  5708. $id = getProp($data, 'id');
  5709. if (!$id) Utils::throwError('20003:ID不能为空');
  5710. $versions = getProp($data, 'versions');
  5711. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5712. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5713. $query_uid = $is_public ? 0 : $uid;
  5714. // 如果是公共库操作,需要admin权限
  5715. if ($is_public && $role !== 'admin') {
  5716. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5717. }
  5718. // 检查是否存在且属于当前用户或公共库
  5719. $role = DB::table('mp_products')
  5720. ->where('id', $id)
  5721. ->where('cpid', $cpid)
  5722. ->where('user_id', $query_uid)
  5723. ->where('type', 1)->first();
  5724. if (!$role) Utils::throwError('20003:记录不存在');
  5725. $updateData = [];
  5726. // $needVersionRecord = false; // 是否需要记录版本
  5727. // 名称
  5728. $product_name = trim(getProp($data, 'product_name'));
  5729. if ($product_name) {
  5730. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5731. $updateData['product_name'] = $product_name;
  5732. }
  5733. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5734. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5735. // 图片地址
  5736. $url = trim(getProp($data, 'url'));
  5737. if ($url) {
  5738. // 检查是否是正确的图片格式
  5739. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5740. $urlPath = parse_url($url, PHP_URL_PATH);
  5741. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5742. if (!in_array($extension, $allowedExtensions)) {
  5743. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5744. }
  5745. // // 如果 url 有变更,记录版本
  5746. // if ($url !== $role->url) {
  5747. // $needVersionRecord = true;
  5748. // }
  5749. $updateData['url'] = $url;
  5750. }
  5751. // 提示词
  5752. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5753. if ($pic_prompt) {
  5754. // // 如果 pic_prompt 有变更,记录版本
  5755. // if ($pic_prompt !== $role->pic_prompt) {
  5756. // $needVersionRecord = true;
  5757. // }
  5758. $updateData['pic_prompt'] = $pic_prompt;
  5759. }
  5760. if (empty($updateData)) {
  5761. Utils::throwError('20003:没有需要更新的数据');
  5762. }
  5763. // // 如果需要记录版本,将数据添加到 versions 数组
  5764. // if ($needVersionRecord) {
  5765. // // 获取现有的 versions 数据
  5766. // $versions = json_decode($role->versions, true) ?: [];
  5767. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5768. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5769. // if ($isFirstVersion) {
  5770. // $oldVersion = [
  5771. // 'url' => $role->url,
  5772. // 'description' => $role->pic_prompt,
  5773. // ];
  5774. // // 旧版本添加到数组末尾
  5775. // $versions[] = $oldVersion;
  5776. // }
  5777. // // 构建新版本(变更后)
  5778. // $newVersion = [
  5779. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5780. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5781. // ];
  5782. // // 检查新版本是否已存在于历史版本中
  5783. // $existingIndex = -1;
  5784. // foreach ($versions as $index => $version) {
  5785. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5786. // $existingIndex = $index;
  5787. // break;
  5788. // }
  5789. // }
  5790. // if ($existingIndex !== -1) {
  5791. // // 如果已存在,移除旧的位置
  5792. // array_splice($versions, $existingIndex, 1);
  5793. // }
  5794. // // 新版本添加到数组开头(最新的在前)
  5795. // array_unshift($versions, $newVersion);
  5796. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5797. // // if (count($versions) > 10) {
  5798. // // $versions = array_slice($versions, 0, 10);
  5799. // // }
  5800. // $updateData['versions'] = json_encode($versions, 256);
  5801. // }
  5802. if ($versions) {
  5803. $updateData['versions'] = json_encode($versions, 256);
  5804. }
  5805. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5806. return DB::table('mp_products')
  5807. ->where('cpid', $cpid)
  5808. ->where('id', $id)->update($updateData);
  5809. }
  5810. /**
  5811. * 获取角色版本历史
  5812. * @param array $data 包含 id(角色ID)
  5813. * @return array 返回版本历史列表
  5814. */
  5815. public function getProductVersions($data) {
  5816. $cpid = Site::getCpid();
  5817. $id = getProp($data, 'id');
  5818. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5819. $role = DB::table('mp_products')
  5820. ->where('id', $id)
  5821. ->where('cpid', $cpid)
  5822. ->where('type', 1)
  5823. ->first();
  5824. if (!$role) Utils::throwError('20003:角色不存在');
  5825. // 获取版本历史
  5826. $versions = json_decode($role->versions, true) ?: [];
  5827. // 添加当前版本作为最新版本
  5828. $currentVersion = [
  5829. 'version' => 0, // 0 表示当前版本
  5830. 'url' => $role->url,
  5831. 'pic_prompt' => $role->pic_prompt,
  5832. 'updated_at' => $role->updated_at,
  5833. 'is_current' => true
  5834. ];
  5835. array_unshift($versions, $currentVersion);
  5836. return $versions;
  5837. }
  5838. /**
  5839. * 恢复到指定版本
  5840. * @param array $data 包含 id(角色ID)、version(版本号)
  5841. * @return bool
  5842. */
  5843. public function restoreProductVersion($data) {
  5844. $uid = Site::getUid();
  5845. $cpid = Site::getCpid();
  5846. $id = getProp($data, 'id');
  5847. $version = getProp($data, 'version');
  5848. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5849. if (!$version) Utils::throwError('20003:版本号不能为空');
  5850. $role = DB::table('mp_products')
  5851. ->where('id', $id)
  5852. ->where('cpid', $cpid)
  5853. ->where('type', 1)
  5854. ->first();
  5855. if (!$role) Utils::throwError('20003:角色不存在');
  5856. // 获取版本历史
  5857. $versions = json_decode($role->versions, true) ?: [];
  5858. // 查找指定版本
  5859. $targetVersion = null;
  5860. foreach ($versions as $v) {
  5861. if ($v['version'] == $version) {
  5862. $targetVersion = $v;
  5863. break;
  5864. }
  5865. }
  5866. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5867. // 先将当前版本保存到历史
  5868. $newVersion = [
  5869. 'version' => count($versions) + 1,
  5870. 'url' => $role->url,
  5871. 'pic_prompt' => $role->pic_prompt,
  5872. 'updated_at' => date('Y-m-d H:i:s'),
  5873. 'updated_by' => $uid
  5874. ];
  5875. array_unshift($versions, $newVersion);
  5876. // 限制版本数量
  5877. if (count($versions) > 10) {
  5878. $versions = array_slice($versions, 0, 10);
  5879. }
  5880. // 恢复到指定版本
  5881. return DB::table('mp_products')
  5882. ->where('id', $id)
  5883. ->where('cpid', $cpid)
  5884. ->update([
  5885. 'url' => $targetVersion['url'],
  5886. 'pic_prompt' => $targetVersion['pic_prompt'],
  5887. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5888. 'updated_at' => date('Y-m-d H:i:s')
  5889. ]);
  5890. }
  5891. public function deleteProduct($data) {
  5892. $uid = Site::getUid();
  5893. $cpid = Site::getCpid();
  5894. $role = Site::getRole();
  5895. $id = getProp($data, 'id');
  5896. if (!$id) Utils::throwError('20003:ID不能为空');
  5897. $ids = explode(',', $id);
  5898. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5899. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5900. $query_uid = $is_public ? 0 : $uid;
  5901. // 如果是公共库操作,需要admin权限
  5902. if ($is_public && $role !== 'admin') {
  5903. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5904. }
  5905. // 检查是否存在且属于当前用户或公共库
  5906. $role = DB::table('mp_products')
  5907. ->whereIn('id', $ids)
  5908. ->where('cpid', $cpid)
  5909. ->where('user_id', $query_uid)
  5910. ->get();
  5911. if (!$role) Utils::throwError('20003:记录不存在');
  5912. return DB::table('mp_products')
  5913. ->where('cpid', $cpid)
  5914. ->where('user_id', $query_uid)
  5915. ->whereIn('id', $ids)
  5916. ->update([
  5917. 'is_deleted' => 1,
  5918. 'updated_at' => date('Y-m-d H:i:s')
  5919. ]);
  5920. }
  5921. public function generateThreeView($data) {
  5922. $uid = Site::getUid();
  5923. $cpid = Site::getCpid();
  5924. $role = Site::getRole();
  5925. $id = getProp($data, 'id');
  5926. if (!$id) Utils::throwError('20003:ID不能为空');
  5927. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5928. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5929. $query_uid = $is_public ? 0 : $uid;
  5930. // 如果是公共库操作,需要admin权限
  5931. if ($is_public && $role !== 'admin') {
  5932. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5933. }
  5934. // 检查是否存在且属于当前用户或公共库
  5935. $product = DB::table('mp_products')
  5936. ->where('id', $id)
  5937. ->where('cpid', $cpid)
  5938. ->where('user_id', $query_uid)
  5939. ->where('type', 1)->first();
  5940. if (!$product) Utils::throwError('20003:资产不存在');
  5941. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5942. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5943. if (!$ref_img_url) {
  5944. // 如果没有传入参考图,使用角色表中的图片
  5945. $ref_img_url = $product->url ?? '';
  5946. if (!$ref_img_url) {
  5947. Utils::throwError('20003:参考图不能为空');
  5948. }
  5949. }
  5950. $pic_prompt = getProp($product, 'pic_prompt');
  5951. if ($pic_prompt) {
  5952. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  5953. }
  5954. // 检查参考图是否是正确的图片格式
  5955. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5956. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5957. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5958. if (!in_array($extension, $allowedExtensions)) {
  5959. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5960. }
  5961. // 处理图片模型
  5962. $model = getProp($data, 'model');
  5963. if (!$model) {
  5964. // 使用默认模型
  5965. $model = 'doubao-seedream-5-0-lite-260128';
  5966. }
  5967. // 验证模型是否在可用模型表中
  5968. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5969. Utils::throwError('20003:该模型已不可用,请更换!');
  5970. }
  5971. $ratio = getProp($data, 'ratio', '16:9');
  5972. $resolution = getProp($data, 'resolution', '2k');
  5973. // 定义分辨率和宽高比对应的尺寸映射表
  5974. $sizeMap = [
  5975. '2k' => [
  5976. '1:1' => ['width' => 2048, 'height' => 2048],
  5977. '4:3' => ['width' => 2304, 'height' => 1728],
  5978. '3:4' => ['width' => 1728, 'height' => 2304],
  5979. '16:9' => ['width' => 2848, 'height' => 1600],
  5980. '9:16' => ['width' => 1600, 'height' => 2848],
  5981. '3:2' => ['width' => 2496, 'height' => 1664],
  5982. '2:3' => ['width' => 1664, 'height' => 2496],
  5983. '21:9' => ['width' => 3136, 'height' => 1344],
  5984. ],
  5985. '3k' => [
  5986. '1:1' => ['width' => 3072, 'height' => 3072],
  5987. '4:3' => ['width' => 3456, 'height' => 2592],
  5988. '3:4' => ['width' => 2592, 'height' => 3456],
  5989. '16:9' => ['width' => 4096, 'height' => 2304],
  5990. '9:16' => ['width' => 2304, 'height' => 4096],
  5991. '2:3' => ['width' => 2496, 'height' => 3744],
  5992. '3:2' => ['width' => 3744, 'height' => 2496],
  5993. '21:9' => ['width' => 4704, 'height' => 2016],
  5994. ],
  5995. '4k' => [
  5996. '1:1' => ['width' => 4096, 'height' => 4096],
  5997. '3:4' => ['width' => 3520, 'height' => 4704],
  5998. '4:3' => ['width' => 4704, 'height' => 3520],
  5999. '16:9' => ['width' => 5504, 'height' => 3040],
  6000. '9:16' => ['width' => 3040, 'height' => 5504],
  6001. '2:3' => ['width' => 3328, 'height' => 4992],
  6002. '3:2' => ['width' => 4992, 'height' => 3328],
  6003. '21:9' => ['width' => 6240, 'height' => 2656],
  6004. ],
  6005. ];
  6006. // 参数验证
  6007. $resolution = strtolower($resolution);
  6008. if (!isset($sizeMap[$resolution])) {
  6009. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6010. }
  6011. if (!isset($sizeMap[$resolution][$ratio])) {
  6012. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6013. }
  6014. // 根据 ratio 和 resolution 确定宽高
  6015. $width = $sizeMap[$resolution][$ratio]['width'];
  6016. $height = $sizeMap[$resolution][$ratio]['height'];
  6017. try {
  6018. // 创建图片生成任务
  6019. $params = [
  6020. 'prompt' => $prompt,
  6021. 'model' => $model,
  6022. 'ref_img_urls' => [$ref_img_url],
  6023. 'width' => $width,
  6024. 'height' => $height
  6025. ];
  6026. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6027. $task_id = $task->id;
  6028. if (!$task_id) {
  6029. Utils::throwError('20003:创建图片生成任务失败');
  6030. }
  6031. // 轮询获取结果
  6032. // 只查询数据库,不调用API,不更新任务表
  6033. $start_time = time();
  6034. $timeout = 1800;
  6035. $img_url = '';
  6036. while (time() - $start_time < $timeout) {
  6037. sleep(5);
  6038. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6039. $task = DB::table('mp_generate_pic_tasks')
  6040. ->where('id', $task_id)
  6041. ->first();
  6042. if (!$task) {
  6043. Utils::throwError('20003:任务不存在');
  6044. }
  6045. if ($task->status === 'success' && $task->result_url) {
  6046. $result_urls = is_string($task->result_url)
  6047. ? json_decode($task->result_url, true)
  6048. : $task->result_url;
  6049. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6050. break;
  6051. } elseif ($task->status === 'failed') {
  6052. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6053. }
  6054. // 其他状态继续轮询
  6055. }
  6056. if (empty($img_url)) {
  6057. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6058. }
  6059. // 更新 mp_products 表(不是任务表)
  6060. DB::table('mp_products')
  6061. ->where('id', $id)
  6062. ->where('cpid', $cpid)
  6063. ->update([
  6064. 'three_view_image_url' => $img_url,
  6065. 'updated_at' => date('Y-m-d H:i:s')
  6066. ]);
  6067. return ['three_view_image_url' => $img_url];
  6068. } catch (\Exception $e) {
  6069. dLog('anime')->error('生成三视图失败', [
  6070. 'error' => $e->getMessage()
  6071. ]);
  6072. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6073. Utils::throwError('20003:' . $e->getMessage());
  6074. }
  6075. }
  6076. /**
  6077. * 推送(复制)资产或文件夹到目标位置
  6078. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6079. * @return array 返回推送结果
  6080. */
  6081. public function pushProductOrFolder($data) {
  6082. $uid = Site::getUid();
  6083. $cpid = Site::getCpid();
  6084. $role = Site::getRole();
  6085. $product_id = getProp($data, 'product_id');
  6086. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6087. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6088. if (!$product_id) {
  6089. Utils::throwError('20003:请选择要推送的项目');
  6090. }
  6091. // 查询源项目(只通过cpid查询,不限制user_id)
  6092. $sourceItem = DB::table('mp_products')
  6093. ->where('id', $product_id)
  6094. ->where('cpid', $cpid)
  6095. ->where('is_deleted', 0)
  6096. ->first();
  6097. if (!$sourceItem) {
  6098. Utils::throwError('20003:要推送的项目不存在');
  6099. }
  6100. // 通过user_id判断源是公共库还是个人库
  6101. $source_uid = $sourceItem->user_id;
  6102. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6103. // 验证目标文件夹并确定目标是公共库还是个人库
  6104. $target_level = 0;
  6105. $target_uid = $uid; // 默认推送到个人库
  6106. $target_is_public = 0;
  6107. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6108. if ($target_parent_id > 0) {
  6109. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6110. $targetParent = DB::table('mp_products')
  6111. ->where('id', $target_parent_id)
  6112. ->where('cpid', $cpid)
  6113. ->where('type', 2)
  6114. ->where('is_deleted', 0)
  6115. ->first();
  6116. if (!$targetParent) {
  6117. Utils::throwError('20003:目标文件夹不存在');
  6118. }
  6119. // 通过user_id判断目标是公共库还是个人库
  6120. $target_level = $targetParent->level;
  6121. $target_uid = $targetParent->user_id;
  6122. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6123. // 使用目标文件夹的 product 类型
  6124. $final_product_type = $targetParent->product;
  6125. }
  6126. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6127. else {
  6128. $push_to_public = getProp($data, 'push_to_public');
  6129. if ($push_to_public === '') {
  6130. Utils::throwError('20003:请选择是否推送到公共库');
  6131. }
  6132. if ($push_to_public) {
  6133. $target_uid = 0;
  6134. $target_is_public = 1;
  6135. }
  6136. // 推送到根目录时,必须指定 product 类型
  6137. if ($target_product === null || $target_product === '') {
  6138. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6139. }
  6140. $final_product_type = $target_product;
  6141. }
  6142. // 如果目标是公共库,需要admin权限
  6143. if ($target_is_public && $role !== 'admin') {
  6144. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6145. }
  6146. // 权限验证:验证是否符合允许的推送规则
  6147. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6148. try {
  6149. DB::beginTransaction();
  6150. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6151. if ($sourceItem->type == 1) {
  6152. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6153. DB::commit();
  6154. return [
  6155. 'product_id' => $newId,
  6156. ];
  6157. }
  6158. // 如果是文件夹,递归复制(支持跨类型推送)
  6159. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6160. DB::commit();
  6161. return [
  6162. 'product_id' => $newFolderId,
  6163. ];
  6164. } catch (\Exception $e) {
  6165. DB::rollBack();
  6166. dLog('anime')->error('推送失败', [
  6167. 'error' => $e->getMessage(),
  6168. 'product_id' => $product_id
  6169. ]);
  6170. Utils::throwError('20003:' . $e->getMessage());
  6171. }
  6172. }
  6173. /**
  6174. * 验证推送权限
  6175. * 允许的推送规则:
  6176. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6177. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6178. * 3. 公共库推送给公共库(公共库 → 公共库)
  6179. *
  6180. * @param int $source_uid 源的user_id
  6181. * @param int $target_uid 目标的user_id
  6182. * @param int $current_uid 当前用户ID
  6183. * @throws \Exception
  6184. */
  6185. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6186. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6187. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6188. return; // 允许
  6189. }
  6190. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6191. if ($source_uid == 0 && $target_uid == $current_uid) {
  6192. return; // 允许
  6193. }
  6194. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6195. if ($source_uid == 0 && $target_uid == 0) {
  6196. return; // 允许
  6197. }
  6198. // 其他情况都不允许
  6199. if ($source_uid != 0 && $source_uid != $current_uid) {
  6200. // 源是别人的个人库
  6201. Utils::throwError('20003:无权限访问该资产');
  6202. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6203. // 个人库推送给公共库(不允许)
  6204. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6205. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6206. // 不同用户的个人库之间推送(不允许)
  6207. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6208. } else {
  6209. // 其他未知情况
  6210. Utils::throwError('20003:不允许的推送操作');
  6211. }
  6212. }
  6213. /**
  6214. * 复制单个资产
  6215. * @param object $sourceProduct 源资产对象
  6216. * @param int $targetParentId 目标父文件夹ID
  6217. * @param int $targetLevel 目标层级
  6218. * @param int $cpid 公司ID
  6219. * @param int $targetUid 目标用户ID
  6220. * @return int 返回新资产ID
  6221. */
  6222. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6223. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6224. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6225. $newProductData = [
  6226. 'user_id' => $targetUid,
  6227. 'cpid' => $cpid,
  6228. 'type' => 1,
  6229. 'parent_id' => $targetParentId,
  6230. 'level' => $targetLevel,
  6231. 'product_name' => $sourceProduct->product_name,
  6232. 'url' => $sourceProduct->url,
  6233. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6234. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6235. 'product' => $finalProductType,
  6236. 'versions' => $sourceProduct->versions ?? '',
  6237. 'sort_order' => time(),
  6238. 'is_deleted' => 0,
  6239. 'created_at' => date('Y-m-d H:i:s'),
  6240. 'updated_at' => date('Y-m-d H:i:s')
  6241. ];
  6242. return DB::table('mp_products')->insertGetId($newProductData);
  6243. }
  6244. /**
  6245. * 递归复制文件夹及其子项
  6246. * @param object $sourceFolder 源文件夹对象
  6247. * @param int $targetParentId 目标父文件夹ID
  6248. * @param int $targetLevel 目标层级
  6249. * @param int $cpid 公司ID
  6250. * @param int $targetUid 目标用户ID
  6251. * @param int $sourceUid 源用户ID
  6252. * @return int 返回新文件夹ID
  6253. */
  6254. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6255. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6256. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6257. // 创建新文件夹
  6258. $newFolderData = [
  6259. 'user_id' => $targetUid,
  6260. 'cpid' => $cpid,
  6261. 'type' => 2,
  6262. 'parent_id' => $targetParentId,
  6263. 'level' => $targetLevel,
  6264. 'product_name' => $sourceFolder->product_name,
  6265. 'product' => $finalProductType,
  6266. 'sort_order' => time(),
  6267. 'is_deleted' => 0,
  6268. 'created_at' => date('Y-m-d H:i:s'),
  6269. 'updated_at' => date('Y-m-d H:i:s')
  6270. ];
  6271. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6272. // 获取源文件夹下的所有子项
  6273. $children = DB::table('mp_products')
  6274. ->where('parent_id', $sourceFolder->id)
  6275. ->where('cpid', $cpid)
  6276. ->where('user_id', $sourceUid)
  6277. ->where('is_deleted', 0)
  6278. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6279. ->get();
  6280. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6281. foreach ($children as $child) {
  6282. if ($child->type == 1) {
  6283. // 资产
  6284. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6285. } else {
  6286. // 文件夹
  6287. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6288. }
  6289. }
  6290. return $newFolderId;
  6291. }
  6292. /**
  6293. * 保存剧本资产关联关系
  6294. * @param array $data 请求参数
  6295. * @return bool
  6296. */
  6297. public function saveScriptProducts($data) {
  6298. $uid = Site::getUid();
  6299. $cpid = Site::getCpid();
  6300. $script_id = getProp($data, 'script_id');
  6301. $products = getProp($data, 'products', []);
  6302. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6303. if (!$script_id) {
  6304. Utils::throwError('20003:请提供剧本ID');
  6305. }
  6306. // 验证剧本是否存在
  6307. $script = DB::table('mp_scripts')
  6308. ->where('id', $script_id)
  6309. ->where('is_deleted', 0)
  6310. ->first();
  6311. if (!$script) {
  6312. Utils::throwError('20003:剧本不存在');
  6313. }
  6314. // 处理图片模型
  6315. $model = getProp($data, 'model');
  6316. if (!$model) {
  6317. // 使用默认模型
  6318. $model = 'doubao-seedream-5-0-lite-260128';
  6319. }
  6320. // 验证模型是否在可用模型表中
  6321. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6322. Utils::throwError('20003:该模型已不可用,请更换!');
  6323. }
  6324. $ratio = getProp($data, 'ratio', '9:16');
  6325. $resolution = getProp($data, 'resolution', '2k');
  6326. // 定义分辨率和宽高比对应的尺寸映射表
  6327. $sizeMap = [
  6328. '2k' => [
  6329. '1:1' => ['width' => 2048, 'height' => 2048],
  6330. '4:3' => ['width' => 2304, 'height' => 1728],
  6331. '3:4' => ['width' => 1728, 'height' => 2304],
  6332. '16:9' => ['width' => 2848, 'height' => 1600],
  6333. '9:16' => ['width' => 1600, 'height' => 2848],
  6334. '3:2' => ['width' => 2496, 'height' => 1664],
  6335. '2:3' => ['width' => 1664, 'height' => 2496],
  6336. '21:9' => ['width' => 3136, 'height' => 1344],
  6337. ],
  6338. '3k' => [
  6339. '1:1' => ['width' => 3072, 'height' => 3072],
  6340. '4:3' => ['width' => 3456, 'height' => 2592],
  6341. '3:4' => ['width' => 2592, 'height' => 3456],
  6342. '16:9' => ['width' => 4096, 'height' => 2304],
  6343. '9:16' => ['width' => 2304, 'height' => 4096],
  6344. '2:3' => ['width' => 2496, 'height' => 3744],
  6345. '3:2' => ['width' => 3744, 'height' => 2496],
  6346. '21:9' => ['width' => 4704, 'height' => 2016],
  6347. ],
  6348. '4k' => [
  6349. '1:1' => ['width' => 4096, 'height' => 4096],
  6350. '3:4' => ['width' => 3520, 'height' => 4704],
  6351. '4:3' => ['width' => 4704, 'height' => 3520],
  6352. '16:9' => ['width' => 5504, 'height' => 3040],
  6353. '9:16' => ['width' => 3040, 'height' => 5504],
  6354. '2:3' => ['width' => 3328, 'height' => 4992],
  6355. '3:2' => ['width' => 4992, 'height' => 3328],
  6356. '21:9' => ['width' => 6240, 'height' => 2656],
  6357. ],
  6358. ];
  6359. // 参数验证
  6360. $resolution = strtolower($resolution);
  6361. if (!isset($sizeMap[$resolution])) {
  6362. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6363. }
  6364. if (!isset($sizeMap[$resolution][$ratio])) {
  6365. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6366. }
  6367. // 根据 ratio 和 resolution 确定宽高
  6368. $width = $sizeMap[$resolution][$ratio]['width'];
  6369. $height = $sizeMap[$resolution][$ratio]['height'];
  6370. $script_name = $script->script_name ?? 'script_' . $script_id;
  6371. // 检查是否已经有该剧本的资产数据
  6372. $existingMappings = DB::table('mp_script_product_mappings')
  6373. ->where('script_id', $script_id)
  6374. ->get();
  6375. if ($existingMappings->isNotEmpty()) {
  6376. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6377. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6378. // 查询这些资产的图片生成任务状态
  6379. $productsWithTasks = DB::table('mp_products')
  6380. ->whereIn('id', $productIds)
  6381. ->where('is_deleted', 0)
  6382. ->get();
  6383. $productTaskMap = [];
  6384. $typeFolderIds = [];
  6385. $hasAllTasks = true;
  6386. foreach ($productsWithTasks as $product) {
  6387. // 收集类型文件夹ID
  6388. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6389. $parentFolder = DB::table('mp_products')
  6390. ->where('id', $product->parent_id)
  6391. ->where('type', 2)
  6392. ->first();
  6393. if ($parentFolder) {
  6394. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6395. }
  6396. }
  6397. // 检查是否有图片生成任务
  6398. if (!empty($product->pic_task_id)) {
  6399. $productTaskMap[$product->id] = $product->pic_task_id;
  6400. } else if($product->url && $product->pic_task_status == '生成成功') {
  6401. continue;
  6402. } else {
  6403. // 有资产没有图片任务
  6404. $hasAllTasks = false;
  6405. }
  6406. }
  6407. // 如果所有资产都有任务ID,直接轮询返回结果
  6408. if ($hasAllTasks && !empty($productTaskMap)) {
  6409. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6410. 'script_id' => $script_id,
  6411. 'script_name' => $script_name,
  6412. 'product_count' => count($productTaskMap)
  6413. ]);
  6414. // 直接返回 SSE 流轮询结果
  6415. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6416. }
  6417. // 如果部分资产没有任务ID,只为这些资产创建任务
  6418. if (!$hasAllTasks && $auto_generate_images) {
  6419. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6420. 'script_id' => $script_id,
  6421. 'script_name' => $script_name
  6422. ]);
  6423. // 开启事务
  6424. DB::beginTransaction();
  6425. try {
  6426. foreach ($productsWithTasks as $product) {
  6427. // 跳过已有任务的资产
  6428. if (!empty($product->pic_task_id)) {
  6429. continue;
  6430. }
  6431. // 跳过没有提示词的资产
  6432. if (empty($product->pic_prompt)) {
  6433. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6434. 'product_id' => $product->id,
  6435. 'product_name' => $product->product_name
  6436. ]);
  6437. continue;
  6438. }
  6439. try {
  6440. // 创建图片生成任务
  6441. $params = [
  6442. 'prompt' => $product->pic_prompt,
  6443. 'model' => $model,
  6444. 'ref_img_urls' => [],
  6445. 'width' => $width,
  6446. 'height' => $height
  6447. ];
  6448. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6449. $task_id = $task->id;
  6450. if ($task_id) {
  6451. $productTaskMap[$product->id] = $task_id;
  6452. // 在事务中更新资产表的任务ID和状态
  6453. DB::table('mp_products')
  6454. ->where('id', $product->id)
  6455. ->update([
  6456. 'pic_task_id' => $task_id,
  6457. 'pic_task_status' => '生成中',
  6458. 'updated_at' => now()
  6459. ]);
  6460. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6461. 'product_id' => $product->id,
  6462. 'task_id' => $task_id
  6463. ]);
  6464. }
  6465. } catch (\Exception $e) {
  6466. dLog('anime')->error('创建资产图片生成任务失败', [
  6467. 'product_id' => $product->id,
  6468. 'error' => $e->getMessage()
  6469. ]);
  6470. // 标记为失败(仍在事务中)
  6471. DB::table('mp_products')
  6472. ->where('id', $product->id)
  6473. ->update([
  6474. 'pic_task_status' => '生成失败',
  6475. 'updated_at' => now()
  6476. ]);
  6477. }
  6478. }
  6479. // 提交事务
  6480. DB::commit();
  6481. // 如果有新创建的任务,返回 SSE 流
  6482. if (!empty($productTaskMap)) {
  6483. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6484. }
  6485. } catch (\Exception $e) {
  6486. // 回滚事务
  6487. DB::rollback();
  6488. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6489. 'script_id' => $script_id,
  6490. 'error' => $e->getMessage()
  6491. ]);
  6492. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6493. }
  6494. }
  6495. // 如果不需要生成图片,返回已存在的信息
  6496. return [
  6497. 'success' => true,
  6498. 'message' => '剧本资产已存在',
  6499. 'script_id' => $script_id,
  6500. 'script_name' => $script_name,
  6501. 'type_folder_ids' => $typeFolderIds,
  6502. 'existing_products' => count($productIds),
  6503. 'tasks_count' => count($productTaskMap)
  6504. ];
  6505. }
  6506. // 解析 products(可能是 JSON 字符串或数组)
  6507. if (is_string($products)) {
  6508. $products = json_decode($products, true);
  6509. if (json_last_error() !== JSON_ERROR_NONE) {
  6510. Utils::throwError('20003:产品数据格式错误');
  6511. }
  6512. }
  6513. if (!is_array($products) || empty($products)) {
  6514. Utils::throwError('20003:产品数据不能为空');
  6515. }
  6516. // 以下是原有的创建逻辑...
  6517. // 开启事务
  6518. DB::beginTransaction();
  6519. try {
  6520. $now = now();
  6521. $mappingRecords = [];
  6522. $createdProductIds = []; // 记录所有创建的资产ID
  6523. // 获取剧本名称
  6524. $script_name = $script->script_name ?? 'script_' . $script_id;
  6525. // 存储每个类型的根文件夹ID
  6526. $typeFolderIds = [];
  6527. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6528. foreach ($products as $productGroup) {
  6529. $type = getProp($productGroup, 'type');
  6530. $title = getProp($productGroup, 'title', '');
  6531. $content = getProp($productGroup, 'content', []);
  6532. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6533. continue;
  6534. }
  6535. // 为当前类型创建根文件夹(如果还未创建)
  6536. if (!isset($typeFolderIds[$type])) {
  6537. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6538. 'user_id' => $uid,
  6539. 'cpid' => $cpid,
  6540. 'type' => 2, // 1.资产 2文件夹
  6541. 'product' => $type, // 1.主体 2.场景 3.道具
  6542. 'parent_id' => 0, // 根文件夹,parent_id=0
  6543. 'level' => 1, // 第一层级
  6544. 'product_name' => $script_name,
  6545. 'sort_order' => time() + $type,
  6546. 'is_deleted' => 0,
  6547. 'created_at' => $now,
  6548. 'updated_at' => $now
  6549. ]);
  6550. }
  6551. $folder_id = $typeFolderIds[$type];
  6552. // 获取表头(第一行)并查找关键列的位置
  6553. $headers = $content[0];
  6554. $nameColumnIndex = -1; // 资产名称列索引
  6555. $sequenceColumnIndex = -1; // 使用范围列索引
  6556. $promptColumnIndex = -1; // 参考提示词列索引
  6557. foreach ($headers as $index => $header) {
  6558. // 查找"资产名称"列
  6559. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6560. $nameColumnIndex = $index;
  6561. }
  6562. // 查找"使用范围"列
  6563. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6564. $sequenceColumnIndex = $index;
  6565. }
  6566. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6567. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6568. $promptColumnIndex = $index;
  6569. }
  6570. }
  6571. // 验证必要的列是否都找到了
  6572. if ($nameColumnIndex === -1) {
  6573. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6574. continue;
  6575. }
  6576. if ($sequenceColumnIndex === -1) {
  6577. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6578. continue;
  6579. }
  6580. // 跳过表头,解析每一行数据
  6581. for ($i = 1; $i < count($content); $i++) {
  6582. $row = $content[$i];
  6583. // 确保行数据有效
  6584. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6585. continue;
  6586. }
  6587. // 根据动态查找的列索引提取数据
  6588. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6589. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6590. $pic_prompt = '';
  6591. // 提取参考提示词(如果找到了该列)
  6592. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6593. $pic_prompt = trim($row[$promptColumnIndex]);
  6594. }
  6595. // 解析使用范围(逗号分隔的序号)
  6596. $sequences = [];
  6597. if (!empty($sequence_str)) {
  6598. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6599. foreach ($sequenceParts as $part) {
  6600. if (is_numeric($part)) {
  6601. $sequences[] = (int)$part;
  6602. }
  6603. }
  6604. }
  6605. if (empty($product_name)) {
  6606. continue;
  6607. }
  6608. // 处理product_name两边的符号
  6609. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6610. // 如果名称不存在则跳过
  6611. if (!$product_name) continue;
  6612. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6613. $product_id = DB::table('mp_products')->insertGetId([
  6614. 'product_name' => $product_name,
  6615. 'type' => 1, // 1=资产 2.文件夹
  6616. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6617. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6618. 'level' => 2, // 第二层级
  6619. 'pic_prompt' => $pic_prompt,
  6620. 'user_id' => $uid,
  6621. 'cpid' => $cpid,
  6622. 'sort_order' => time(),
  6623. 'is_deleted' => 0,
  6624. 'created_at' => $now,
  6625. 'updated_at' => $now,
  6626. ]);
  6627. // 记录创建的资产ID
  6628. $createdProductIds[] = $product_id;
  6629. // 为每个序号创建映射记录
  6630. if (!empty($sequences)) {
  6631. foreach ($sequences as $sequence) {
  6632. $mappingRecords[] = [
  6633. 'script_id' => $script_id,
  6634. 'product_id' => $product_id,
  6635. 'episode_number' => $sequence,
  6636. 'created_at' => $now,
  6637. 'updated_at' => $now,
  6638. ];
  6639. }
  6640. } else {
  6641. // 如果没有指定序号,创建一个默认映射(序号为0)
  6642. $mappingRecords[] = [
  6643. 'script_id' => $script_id,
  6644. 'product_id' => $product_id,
  6645. 'episode_number' => 0,
  6646. 'created_at' => $now,
  6647. 'updated_at' => $now,
  6648. ];
  6649. }
  6650. }
  6651. }
  6652. if (empty($mappingRecords)) {
  6653. Utils::throwError('20003:没有有效的产品数据');
  6654. }
  6655. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6656. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6657. // 如果需要自动生成图片,在事务中创建图片生成任务
  6658. $productTaskMap = [];
  6659. if ($auto_generate_images && !empty($createdProductIds)) {
  6660. // 查询所有创建的资产
  6661. $productsToGenerate = DB::table('mp_products')
  6662. ->whereIn('id', $createdProductIds)
  6663. ->where('is_deleted', 0)
  6664. ->get();
  6665. foreach ($productsToGenerate as $product) {
  6666. if (empty($product->pic_prompt)) {
  6667. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6668. 'product_id' => $product->id,
  6669. 'product_name' => $product->product_name
  6670. ]);
  6671. continue;
  6672. }
  6673. try {
  6674. // 创建图片生成任务
  6675. $params = [
  6676. 'prompt' => $product->pic_prompt,
  6677. 'model' => $model,
  6678. 'ref_img_urls' => [],
  6679. 'width' => $width,
  6680. 'height' => $height
  6681. ];
  6682. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6683. $task_id = $task->id;
  6684. if ($task_id) {
  6685. $productTaskMap[$product->id] = $task_id;
  6686. // 在事务中更新资产表的任务ID和状态
  6687. DB::table('mp_products')
  6688. ->where('id', $product->id)
  6689. ->update([
  6690. 'pic_task_id' => $task_id,
  6691. 'pic_task_status' => '生成中',
  6692. 'updated_at' => now()
  6693. ]);
  6694. dLog('anime')->info('创建资产图片生成任务', [
  6695. 'product_id' => $product->id,
  6696. 'task_id' => $task_id
  6697. ]);
  6698. }
  6699. } catch (\Exception $e) {
  6700. dLog('anime')->error('创建资产图片生成任务失败', [
  6701. 'product_id' => $product->id,
  6702. 'error' => $e->getMessage()
  6703. ]);
  6704. // 标记为失败(仍在事务中)
  6705. DB::table('mp_products')
  6706. ->where('id', $product->id)
  6707. ->update([
  6708. 'pic_task_status' => '生成失败',
  6709. 'updated_at' => now()
  6710. ]);
  6711. }
  6712. }
  6713. }
  6714. // 提交事务
  6715. DB::commit();
  6716. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6717. if ($auto_generate_images && !empty($productTaskMap)) {
  6718. // 返回 SSE 流(事务外轮询)
  6719. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6720. }
  6721. // 如果不需要生成图片,返回普通结果
  6722. return [
  6723. 'success' => true,
  6724. 'type_folder_ids' => $typeFolderIds,
  6725. 'inserted_count' => $insertedCount,
  6726. 'total_records' => count($mappingRecords),
  6727. 'created_products' => count($createdProductIds),
  6728. 'image_tasks_created' => count($productTaskMap)
  6729. ];
  6730. } catch (\Exception $e) {
  6731. // 回滚事务
  6732. DB::rollback();
  6733. // 记录错误日志
  6734. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6735. 'script_id' => $script_id,
  6736. 'error' => $e->getMessage(),
  6737. 'trace' => $e->getTraceAsString()
  6738. ]);
  6739. // 统一使用 Utils::throwError 抛出错误
  6740. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6741. }
  6742. }
  6743. /**
  6744. * 批量为剧本资产生成图片
  6745. *
  6746. * @param array $data 请求参数
  6747. * @return \Generator 返回 SSE 流
  6748. */
  6749. public function batchGenerateProductImages($data) {
  6750. $script_id = getProp($data, 'script_id');
  6751. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6752. if (!$script_id) {
  6753. Utils::throwError('20003:请提供剧本ID');
  6754. }
  6755. // 验证剧本是否存在
  6756. $script = DB::table('mp_scripts')
  6757. ->where('id', $script_id)
  6758. ->where('is_deleted', 0)
  6759. ->first();
  6760. if (!$script) {
  6761. Utils::throwError('20003:剧本不存在');
  6762. }
  6763. $script_name = $script->script_name ?? 'script_' . $script_id;
  6764. // 获取需要生成图片的所有资产
  6765. $products = DB::table('mp_products')
  6766. ->whereIn('parent_id', array_values($type_folder_ids))
  6767. ->where('is_deleted', 0)
  6768. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6769. ->get();
  6770. if ($products->isEmpty()) {
  6771. Utils::throwError('20003:没有找到需要生成图片的资产');
  6772. }
  6773. // 默认参数
  6774. $model = 'doubao-seedream-5-0-lite-260128';
  6775. $width = 1600;
  6776. $height = 2848;
  6777. // 开始为每个资产创建图片生成任务
  6778. $taskIds = [];
  6779. $productTaskMap = []; // 资产ID到任务ID的映射
  6780. foreach ($products as $product) {
  6781. if (empty($product->pic_prompt)) {
  6782. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6783. continue;
  6784. }
  6785. try {
  6786. // 创建图片生成任务
  6787. $params = [
  6788. 'prompt' => $product->pic_prompt,
  6789. 'model' => $model,
  6790. 'ref_img_urls' => [],
  6791. 'width' => $width,
  6792. 'height' => $height
  6793. ];
  6794. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6795. $task_id = $task->id;
  6796. if ($task_id) {
  6797. $taskIds[] = $task_id;
  6798. $productTaskMap[$product->id] = $task_id;
  6799. // 更新资产表的任务ID和状态
  6800. DB::table('mp_products')
  6801. ->where('id', $product->id)
  6802. ->update([
  6803. 'pic_task_id' => $task_id,
  6804. 'pic_task_status' => '生成中',
  6805. 'updated_at' => now()
  6806. ]);
  6807. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6808. }
  6809. } catch (\Exception $e) {
  6810. dLog('anime')->error('创建资产图片生成任务失败', [
  6811. 'product_id' => $product->id,
  6812. 'error' => $e->getMessage()
  6813. ]);
  6814. // 标记为失败
  6815. DB::table('mp_products')
  6816. ->where('id', $product->id)
  6817. ->update([
  6818. 'pic_task_status' => '生成失败',
  6819. 'updated_at' => now()
  6820. ]);
  6821. }
  6822. }
  6823. if (empty($taskIds)) {
  6824. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6825. }
  6826. // 返回 SSE 流
  6827. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6828. }
  6829. /**
  6830. * 轮询资产图片生成任务状态(SSE流式返回)
  6831. * 只通过查询数据库获取任务状态,不主动调用API
  6832. *
  6833. * @param int $script_id 剧本ID
  6834. * @param string $script_name 剧本名称
  6835. * @param array $productTaskMap 资产ID到任务ID的映射
  6836. * @param array $type_folder_ids 类型文件夹ID映射
  6837. * @return \Generator
  6838. */
  6839. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6840. $startTime = time();
  6841. $timeout = 1800; // 30分钟超时
  6842. $pollInterval = 10; // 10秒轮询一次
  6843. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6844. // 定义类型名称映射
  6845. $typeNames = [
  6846. 1 => 'roles', // 角色
  6847. 2 => 'scenes', // 场景
  6848. 3 => 'props' // 道具
  6849. ];
  6850. while (time() - $startTime < $timeout) {
  6851. sleep($pollInterval);
  6852. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6853. $mappings = DB::table('mp_script_product_mappings')
  6854. ->where('script_id', $script_id)
  6855. ->pluck('product_id')
  6856. ->unique()
  6857. ->toArray();
  6858. if (empty($mappings)) {
  6859. dLog('anime')->warning('该剧本没有关联的资产', [
  6860. 'script_id' => $script_id,
  6861. 'script_name' => $script_name
  6862. ]);
  6863. break;
  6864. }
  6865. // 查询所有资产的当前状态
  6866. $products = DB::table('mp_products')
  6867. ->whereIn('id', $mappings)
  6868. ->where('is_deleted', 0)
  6869. ->get();
  6870. // 统计各类型的状态(使用类型名称作为键名)
  6871. $stats = [
  6872. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6873. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6874. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6875. ];
  6876. $allCompleted = true;
  6877. $hasStatusChange = false;
  6878. foreach ($products as $product) {
  6879. $type = $product->product;
  6880. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6881. // 如果类型名称不在 stats 中,初始化
  6882. if (!isset($stats[$typeName])) {
  6883. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6884. }
  6885. $stats[$typeName]['total']++;
  6886. $task_id = $product->pic_task_id;
  6887. $currentStatus = $product->pic_task_status;
  6888. // 检查状态是否有变化
  6889. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6890. $hasStatusChange = true;
  6891. $lastStatus[$product->id] = $currentStatus;
  6892. }
  6893. // 如果是生成中,查询任务表状态
  6894. if ($currentStatus === '生成中' && $task_id) {
  6895. // 只查询数据库,不调用API
  6896. $task = DB::table('mp_generate_pic_tasks')
  6897. ->where('id', $task_id)
  6898. ->first();
  6899. if ($task) {
  6900. // 检查任务状态
  6901. if ($task->status === 'success' && $task->result_url) {
  6902. // 解析图片URL
  6903. $result_urls = $task->result_url;
  6904. if (is_string($result_urls)) {
  6905. $result_urls = json_decode($result_urls, true);
  6906. }
  6907. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6908. // 更新资产表状态
  6909. DB::table('mp_products')
  6910. ->where('id', $product->id)
  6911. ->update([
  6912. 'pic_task_status' => '生成成功',
  6913. 'url' => $img_url,
  6914. 'updated_at' => now()
  6915. ]);
  6916. $stats[$typeName]['success']++;
  6917. $stats[$typeName]['completed']++;
  6918. $hasStatusChange = true;
  6919. dLog('anime')->info('资产图片生成成功', [
  6920. 'product_id' => $product->id,
  6921. 'task_id' => $task_id,
  6922. 'img_url' => $img_url
  6923. ]);
  6924. } elseif ($task->status === 'failed') {
  6925. // 更新资产表状态
  6926. DB::table('mp_products')
  6927. ->where('id', $product->id)
  6928. ->update([
  6929. 'pic_task_status' => '生成失败',
  6930. 'updated_at' => now()
  6931. ]);
  6932. $stats[$typeName]['completed']++;
  6933. $hasStatusChange = true;
  6934. dLog('anime')->warning('资产图片生成失败', [
  6935. 'product_id' => $product->id,
  6936. 'task_id' => $task_id,
  6937. 'error' => $task->error_message ?? '未知错误'
  6938. ]);
  6939. } else {
  6940. // 任务还在处理中
  6941. $allCompleted = false;
  6942. }
  6943. } else {
  6944. // 任务不存在,标记为失败
  6945. DB::table('mp_products')
  6946. ->where('id', $product->id)
  6947. ->update([
  6948. 'pic_task_status' => '生成失败',
  6949. 'updated_at' => now()
  6950. ]);
  6951. $stats[$type]['completed']++;
  6952. $hasStatusChange = true;
  6953. dLog('anime')->error('图片生成任务不存在', [
  6954. 'product_id' => $product->id,
  6955. 'task_id' => $task_id
  6956. ]);
  6957. }
  6958. } elseif ($currentStatus === '生成成功') {
  6959. $stats[$typeName]['success']++;
  6960. $stats[$typeName]['completed']++;
  6961. } elseif ($currentStatus === '生成失败') {
  6962. $stats[$typeName]['completed']++;
  6963. } else {
  6964. // 其他状态也认为未完成
  6965. $allCompleted = false;
  6966. }
  6967. }
  6968. // 移除没有数据的类型(total=0)
  6969. foreach ($stats as $typeName => $stat) {
  6970. if ($stat['total'] === 0) {
  6971. unset($stats[$typeName]);
  6972. }
  6973. }
  6974. // 如果有状态变化,发送 SSE 更新
  6975. if ($hasStatusChange) {
  6976. $eventType = $allCompleted ? 'complete' : 'update';
  6977. $response = [
  6978. 'type' => $eventType,
  6979. 'script_id' => $script_id,
  6980. 'script_name' => $script_name,
  6981. 'stats' => $stats,
  6982. 'timestamp' => date('Y-m-d H:i:s')
  6983. ];
  6984. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6985. dLog('anime')->info('SSE更新', [
  6986. 'event_type' => $eventType,
  6987. 'script_id' => $script_id,
  6988. 'script_name' => $script_name,
  6989. 'stats' => $stats
  6990. ]);
  6991. if ($allCompleted) {
  6992. dLog('anime')->info('所有资产图片生成任务已完成', [
  6993. 'script_id' => $script_id,
  6994. 'script_name' => $script_name,
  6995. 'stats' => $stats
  6996. ]);
  6997. break;
  6998. }
  6999. }
  7000. }
  7001. // 超时处理
  7002. if (time() - $startTime >= $timeout && !$allCompleted) {
  7003. $response = [
  7004. 'type' => 'timeout',
  7005. 'message' => '部分任务超时,请稍后查看结果',
  7006. 'script_id' => $script_id,
  7007. 'script_name' => $script_name,
  7008. 'timestamp' => date('Y-m-d H:i:s')
  7009. ];
  7010. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7011. dLog('anime')->warning('资产图片生成任务超时', [
  7012. 'script_id' => $script_id,
  7013. 'script_name' => $script_name,
  7014. 'timeout' => $timeout
  7015. ]);
  7016. }
  7017. }
  7018. /**
  7019. * 获取剧本关联的资产列表
  7020. * @param array $data 请求参数
  7021. * @return array
  7022. */
  7023. public function getScriptProducts($data) {
  7024. $uid = Site::getUid();
  7025. $cpid = Site::getCpid();
  7026. $script_id = getProp($data, 'script_id');
  7027. $episode_number = getProp($data, 'episode_number');
  7028. if (!$script_id) {
  7029. Utils::throwError('20003:请提供剧本ID');
  7030. }
  7031. // 验证剧本是否存在
  7032. $script = DB::table('mp_scripts')
  7033. ->where('id', $script_id)
  7034. ->where('is_deleted', 0)
  7035. ->first();
  7036. if (!$script) {
  7037. Utils::throwError('20003:剧本不存在');
  7038. }
  7039. // 联表查询资产信息
  7040. $query = DB::table('mp_script_product_mappings as mapping')
  7041. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7042. ->where('mapping.script_id', $script_id)
  7043. ->where('product.cpid', $cpid)
  7044. ->where('product.is_deleted', 0);
  7045. // 如果提供了 episode_number,则过滤指定集数
  7046. if ($episode_number !== null && $episode_number !== '') {
  7047. $query->where('mapping.episode_number', $episode_number);
  7048. }
  7049. $mappings = $query->select(
  7050. 'mapping.script_id',
  7051. 'mapping.product_id',
  7052. 'mapping.episode_number',
  7053. 'product.product_name',
  7054. 'product.type',
  7055. 'product.product',
  7056. 'product.pic_prompt',
  7057. 'product.url',
  7058. 'product.pic_task_id',
  7059. 'product.pic_task_status',
  7060. 'product.three_view_image_url',
  7061. 'mapping.created_at'
  7062. )
  7063. ->orderBy('mapping.product_id', 'asc')
  7064. ->orderBy('mapping.episode_number', 'asc')
  7065. ->get();
  7066. // 按 product_id 分组,合并 episode_number
  7067. $productMap = [];
  7068. foreach ($mappings as $item) {
  7069. $product_id = $item->product_id;
  7070. if (!isset($productMap[$product_id])) {
  7071. $productMap[$product_id] = [
  7072. 'product_id' => $product_id,
  7073. 'product_name' => $item->product_name,
  7074. 'type' => (int)$item->type,
  7075. 'product' => (int)$item->product,
  7076. 'pic_prompt' => $item->pic_prompt,
  7077. 'url' => $item->url,
  7078. 'pic_task_id' => $item->pic_task_id,
  7079. 'pic_task_status' => $item->pic_task_status,
  7080. 'episode_numbers' => [],
  7081. 'created_at' => $item->created_at,
  7082. ];
  7083. }
  7084. // 添加 episode_number(去重)
  7085. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7086. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7087. }
  7088. }
  7089. // 按类型分组
  7090. $roles = []; // type=1 角色/主体
  7091. $scenes = []; // type=2 场景
  7092. $props = []; // type=3 道具
  7093. foreach ($productMap as $product) {
  7094. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7095. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7096. // 构造返回数据
  7097. $productData = [
  7098. 'product_id' => $product['product_id'],
  7099. 'product_name' => $product['product_name'],
  7100. 'product' => $product['product'],
  7101. 'pic_prompt' => $product['pic_prompt'],
  7102. 'url' => $product['url'],
  7103. 'pic_task_id' => $product['pic_task_id'],
  7104. 'pic_task_status' => $product['pic_task_status'],
  7105. 'episode_numbers' => $episodeNumbersStr,
  7106. 'created_at' => $product['created_at'],
  7107. ];
  7108. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7109. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7110. switch ($product['product']) {
  7111. case 1:
  7112. $roles[] = $productData;
  7113. break;
  7114. case 2:
  7115. $scenes[] = $productData;
  7116. break;
  7117. case 3:
  7118. $props[] = $productData;
  7119. break;
  7120. }
  7121. }
  7122. return [
  7123. 'script_id' => $script_id,
  7124. 'script_name' => $script->script_name ?? '',
  7125. 'roles' => $roles, // 主体
  7126. 'scenes' => $scenes, // 场景
  7127. 'props' => $props, // 道具
  7128. ];
  7129. }
  7130. /**
  7131. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7132. * @param string $actContent 原始内容
  7133. * @param array $products 产品数组(包含product_name和url)
  7134. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7135. */
  7136. public function processActContentWithProducts($actContent, $products) {
  7137. if (empty($actContent) || empty($products)) {
  7138. return [
  7139. 'content' => $actContent,
  7140. 'reference_images' => []
  7141. ];
  7142. }
  7143. // 构建产品名称到产品信息的映射
  7144. $product_dict = [];
  7145. foreach ($products as $product) {
  7146. $product_name = getProp($product, 'product_name');
  7147. if ($product_name) {
  7148. $product_dict[$product_name] = [
  7149. 'url' => getProp($product, 'url'),
  7150. 'voice_prompt' => getProp($product, 'voice_prompt')
  7151. ];
  7152. }
  7153. }
  7154. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7155. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7156. $reference_images = [];
  7157. $product_index_map = []; // 产品名称 => 图片序号的映射
  7158. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7159. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7160. $current_index = 1;
  7161. if (!empty($matches[1])) {
  7162. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7163. $seen_products = []; // 用于去重
  7164. foreach ($matches[1] as $product_name) {
  7165. // 跳过已处理的产品
  7166. if (isset($seen_products[$product_name])) {
  7167. continue;
  7168. }
  7169. $seen_products[$product_name] = true;
  7170. // 检查产品是否在字典中
  7171. if (isset($product_dict[$product_name])) {
  7172. $url = $product_dict[$product_name]['url'];
  7173. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7174. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7175. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7176. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7177. }
  7178. // 只有URL非空才分配序号和添加到参考图片
  7179. if (!empty($url)) {
  7180. // 检查URL是否已经在reference_images中(去重)
  7181. if (!in_array($url, $reference_images)) {
  7182. $reference_images[] = $url;
  7183. $product_index_map[$product_name] = $current_index;
  7184. $current_index++;
  7185. } else {
  7186. // URL重复,找到已有的序号
  7187. $existing_index = array_search($url, $reference_images) + 1;
  7188. $product_index_map[$product_name] = $existing_index;
  7189. }
  7190. } else {
  7191. // URL为空,不分配序号(后续直接去掉{})
  7192. $product_index_map[$product_name] = 0;
  7193. }
  7194. } else {
  7195. // 产品不在字典中,不分配序号
  7196. $product_index_map[$product_name] = 0;
  7197. }
  7198. }
  7199. }
  7200. // 第二步:替换内容中的 {产品名称}
  7201. $processedContent = $actContent;
  7202. foreach ($product_index_map as $product_name => $index) {
  7203. $escaped_name = preg_quote($product_name, '/');
  7204. if ($index > 0) {
  7205. // 有图片,替换为:产品名称(图X)
  7206. $replacement = $product_name . '<图片' . $index . '>';
  7207. } else {
  7208. // 无图片,只保留产品名称
  7209. $replacement = $product_name;
  7210. }
  7211. // 替换所有 {产品名称} 为处理后的格式
  7212. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7213. }
  7214. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7215. foreach ($products as $product) {
  7216. $product_name = getProp($product, 'product_name');
  7217. $voice_prompt = getProp($product, 'voice_prompt');
  7218. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7219. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7220. break; // 找到旁白后退出循环
  7221. }
  7222. }
  7223. // 第四步:将voice_prompt信息添加到内容最前面
  7224. $voice_prompt_prefix = '';
  7225. if (!empty($voice_prompts)) {
  7226. $voice_prompt_prefix .= implode('', $voice_prompts);
  7227. }
  7228. // 旁白的voice_prompt放在最后
  7229. if (!empty($narrator_voice_prompt)) {
  7230. $voice_prompt_prefix .= $narrator_voice_prompt;
  7231. }
  7232. // 如果有voice_prompt信息,添加到内容开头
  7233. if (!empty($voice_prompt_prefix)) {
  7234. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7235. }
  7236. return [
  7237. 'content' => $processedContent,
  7238. 'reference_images' => $reference_images
  7239. ];
  7240. }
  7241. public function saveActVideoGenerateParams($data) {
  7242. $episode_id = getProp($data, 'episode_id');
  7243. $model = getProp($data, 'video_model');
  7244. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7245. Utils::throwError('20003:该模型不可用');
  7246. }
  7247. if (!$model) {
  7248. // 使用默认模型
  7249. $model = 'zhizhen-20';
  7250. }
  7251. // 验证模型是否在可用模型表中
  7252. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7253. Utils::throwError('20003:该模型已不可用,请更换!');
  7254. }
  7255. $video_resolution = getProp($data, 'video_resolution', '720p');
  7256. $ratio = getProp($data, 'ratio');
  7257. if (!$ratio) $ratio = '9:16';
  7258. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7259. 'video_model' => $model,
  7260. 'video_resolution' => $video_resolution,
  7261. 'ratio' => $ratio,
  7262. 'updated_at' => date('Y-m-d H:i:s')
  7263. ]);
  7264. }
  7265. public function confirmActs($data) {
  7266. $episode_id = getProp($data, 'episode_id');
  7267. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7268. if (!$episode) {
  7269. Utils::throwError('20003:分集不存在');
  7270. }
  7271. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7272. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7273. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7274. // 获取所有片段数据
  7275. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7276. // 收集所有资产名称(角色、场景、道具)
  7277. $product_names = [];
  7278. // 收集角色名称
  7279. foreach ($roles as $role) {
  7280. $role_name = getProp($role, 'role');
  7281. if ($role_name && $role_name != '旁白') {
  7282. $product_names[] = $role_name;
  7283. }
  7284. }
  7285. // 收集场景名称
  7286. foreach ($scenes as $scene) {
  7287. $scene_name = getProp($scene, 'scene');
  7288. if ($scene_name) {
  7289. $product_names[] = $scene_name;
  7290. }
  7291. }
  7292. // 收集道具名称
  7293. foreach ($props as $prop) {
  7294. $prop_name = getProp($prop, 'prop');
  7295. if ($prop_name) {
  7296. $product_names[] = $prop_name;
  7297. }
  7298. }
  7299. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7300. $product_names = array_unique($product_names);
  7301. usort($product_names, function($a, $b) {
  7302. return mb_strlen($b) - mb_strlen($a);
  7303. });
  7304. try {
  7305. DB::beginTransaction();
  7306. // 处理每个片段
  7307. foreach ($acts as $act) {
  7308. $act_content = getProp($act, 'act_content');
  7309. if (!$act_content) continue;
  7310. $processed_content = $act_content;
  7311. // 统一替换所有资产名称为 {资产名} 格式
  7312. // 使用占位符避免嵌套替换问题
  7313. $placeholder_map = [];
  7314. $placeholder_index = 0;
  7315. foreach ($product_names as $product_name) {
  7316. // 转义特殊字符
  7317. $escaped_product = preg_quote($product_name, '/');
  7318. // 检查是否匹配且未被 {} 包裹
  7319. $processed_content = preg_replace_callback(
  7320. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7321. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7322. // 使用唯一占位符
  7323. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7324. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7325. $placeholder_index++;
  7326. return $placeholder;
  7327. },
  7328. $processed_content
  7329. );
  7330. }
  7331. // 将所有占位符替换回实际内容
  7332. foreach ($placeholder_map as $placeholder => $replacement) {
  7333. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7334. }
  7335. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7336. $shot_counter = 0;
  7337. $processed_content = preg_replace_callback(
  7338. '/【(?:镜头|分镜)(\d+)】/u',
  7339. function($matches) use (&$shot_counter) {
  7340. $shot_counter++;
  7341. return '【镜头' . $shot_counter . '】';
  7342. },
  7343. $processed_content
  7344. );
  7345. // 更新数据库
  7346. $boolen = DB::table('mp_episode_segments')
  7347. ->where('id', $act->id)
  7348. ->update([
  7349. 'act_show_content' => $processed_content,
  7350. 'updated_at' => date('Y-m-d H:i:s')
  7351. ]);
  7352. if (!$boolen) {
  7353. Utils::throwError('20003:片段处理失败');
  7354. }
  7355. }
  7356. }catch (\Exception $e) {
  7357. DB::rollBack();
  7358. Utils::throwError('20003:'.$e->getMessage());
  7359. }
  7360. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7361. 'is_generated' => 1,
  7362. 'updated_at' => date('Y-m-d H:i:s')
  7363. ]);
  7364. if (!$boolen1) {
  7365. DB::rollBack();
  7366. Utils::throwError('20003:分集处理失败!');
  7367. }
  7368. DB::commit();
  7369. // 重新查询更新后的片段数据
  7370. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7371. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7372. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7373. $products = [];
  7374. // 先处理角色数组
  7375. foreach ($roles as $role) {
  7376. $product = $role;
  7377. // 将role字段重命名为product_name
  7378. if (isset($product['role'])) {
  7379. $product['product_name'] = $product['role'];
  7380. unset($product['role']);
  7381. $product['product'] = 1; // 标记类型为角色
  7382. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7383. }
  7384. }
  7385. // 处理场景数组
  7386. foreach ($scenes as $scene) {
  7387. $product = $scene;
  7388. // 将scene字段重命名为product_name
  7389. if (isset($product['scene'])) {
  7390. $product['product_name'] = $product['scene'];
  7391. unset($product['scene']);
  7392. $product['product'] = 2; // 标记类型为场景
  7393. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7394. }
  7395. }
  7396. // 处理道具数组(逻辑与场景一致)
  7397. foreach ($props as $prop) {
  7398. $product = $prop;
  7399. // 将prop字段重命名为product_name
  7400. if (isset($product['prop'])) {
  7401. $product['product_name'] = $product['prop'];
  7402. unset($product['prop']);
  7403. $product['product'] = 3; // 标记类型为道具
  7404. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7405. }
  7406. }
  7407. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7408. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7409. foreach ($extra_products as $extra_product) {
  7410. $product_name = getProp($extra_product, 'product_name');
  7411. if ($product_name) {
  7412. $products[$product_name] = $extra_product; // 覆盖同名数据
  7413. }
  7414. }
  7415. // 重新索引数组(去除key)
  7416. $products = array_values($products);
  7417. // 构建返回的acts数组
  7418. $return_acts = [];
  7419. foreach ($acts as $act) {
  7420. $return_acts[] = [
  7421. 'act_id' => getProp($act, 'id'),
  7422. 'act_number' => getProp($act, 'act_number'),
  7423. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7424. 'act_show_content' => getProp($act, 'act_show_content'),
  7425. 'video_url' => getProp($act, 'video_url'),
  7426. 'video_duration' => getProp($act, 'video_duration'),
  7427. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7428. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7429. ];
  7430. }
  7431. return [
  7432. 'anime_id' => getProp($episode, 'anime_id'),
  7433. 'episode_id' => $episode_id,
  7434. 'title' => getProp($episode, 'title'),
  7435. 'episode_number' => getProp($episode, 'episode_number'),
  7436. 'is_generated' => getProp($episode, 'is_generated'),
  7437. 'products' => $products,
  7438. 'acts' => $return_acts
  7439. ];
  7440. }
  7441. }