AnimeService.php 395 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $cpid = Site::getCpid();
  181. $input_art_style = getProp($data, 'art_style');
  182. $file = getProp($data, 'file');
  183. $content = getProp($data, 'content', '');
  184. $bid = getProp($data, 'bid', 0);
  185. $script_id = getProp($data, 'script_id', 0);
  186. $ace_mode = getProp($data, 'ace_mode', 0);
  187. $extra_products = getProp($data, 'products', []);
  188. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  189. if (!is_array($extra_products)) {
  190. Utils::throwError('20003:传入的资产格式不正确');
  191. }
  192. // 替换美术风格
  193. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  194. // 提取文件内容
  195. if ($file) {
  196. $content = $this->DeepSeekService->extractFileContent($file);
  197. if (!$content) {
  198. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  199. }
  200. } elseif ($script_id) {
  201. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  202. if (!$content) {
  203. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  204. }
  205. } elseif ($bid) {
  206. $content = $this->DeepSeekService->getContentByBid($bid);
  207. if (!$content) {
  208. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  209. }
  210. } elseif ($content) {
  211. $content = filterContent($content);
  212. }else {
  213. $content = '';
  214. }
  215. $anime_data = [
  216. 'user_id' => $uid,
  217. 'cpid' => $cpid,
  218. 'anime_name' => '新剧本策划',
  219. 'is_multi' => getProp($data, 'is_multi', 1),
  220. 'content' => $content,
  221. 'art_style_type' => $input_art_style,
  222. 'ace_mode' => $ace_mode,
  223. 'script_id' => $script_id,
  224. 'extra_products' => json_encode($extra_products, 256),
  225. 'created_at' => date('Y-m-d H:i:s'),
  226. 'updated_at' => date('Y-m-d H:i:s'),
  227. ];
  228. // 处理文本模型
  229. $model = getProp($data, 'model');
  230. if (!$model) {
  231. // 用户没有输入,使用默认值
  232. $model = 'deepseek-v4-pro';
  233. }
  234. // 验证模型是否在可用模型表中
  235. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  236. $model = 'deepseek-v4-pro';
  237. }
  238. $anime_data['model'] = $model;
  239. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  240. return DB::table('mp_animes')->insertGetId($anime_data);
  241. }
  242. public function chatList($data) {
  243. $uid = Site::getUid();
  244. $anime_name = getProp($data, 'anime_name');
  245. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  246. if ($anime_name) {
  247. $query->where('anime_name', 'like', "%$anime_name%");
  248. }
  249. return $query->orderBy('id', 'desc')->paginate();
  250. }
  251. public function chatHistory($data) {
  252. $anime_id = getProp($data, 'anime_id');
  253. $sequence = getProp($data, 'sequence', 0);
  254. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  255. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  256. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  257. return $query->orderBy('ar.id')->get()->map(function ($value) {
  258. $value = (array)$value;
  259. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  260. $value['created_at'] = transDate($value['created_at']);
  261. $value['episode_created_at'] = transDate($value['episode_created_at']);
  262. return $value;
  263. })->toArray();
  264. }
  265. public function batchSetRoleImg($data) {
  266. $episode_id = getProp($data, 'episode_id');
  267. if (!$episode_id) Utils::throwError('1002:请选择分集');
  268. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  269. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  270. $art_style = getProp($episode, 'art_style');
  271. $anime_id = getProp($episode, 'anime_id');
  272. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  273. $art_style_type = getProp($anime, 'art_style_type');
  274. $character_prefix = '';
  275. $scene_prefix = '';
  276. if ($art_style_type) {
  277. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  278. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  279. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  280. }
  281. foreach ($roles as &$role) {
  282. $role_name = getProp($role, 'role');
  283. if ($role_name == '旁白') continue;
  284. // 优先使用 pic_prompt,如果没有则使用 description
  285. $pic_prompt = getProp($role, 'pic_prompt');
  286. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  287. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  288. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  289. // 参考图地址
  290. $ref_img_url = getProp($role, 'url');
  291. if ($ref_img_url) continue; // 已有图片则跳过
  292. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  293. try {
  294. $params = [
  295. 'prompt' => $description,
  296. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  297. ];
  298. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  299. $task_id = $task->id;
  300. if (!$task_id) {
  301. Utils::throwError("20003:角色({$role_name})生成图片失败");
  302. }
  303. $role['task_id'] = $task_id;
  304. $role['task_status'] = 'processing';
  305. } catch (\Exception $e) {
  306. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  307. Utils::throwError("20003:" . $e->getMessage());
  308. }
  309. }
  310. // 保存角色信息
  311. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  312. 'roles' => json_encode($roles, 256),
  313. 'generate_status' => '执行中',
  314. 'generate_at' => date('Y-m-d H:i:s'),
  315. 'updated_at' => date('Y-m-d H:i:s')
  316. ]);
  317. if (!$boolen) {
  318. Utils::throwError('20003:保存角色信息失败');
  319. }
  320. return $boolen;
  321. }
  322. public function batchSetSceneImg($data) {
  323. $episode_id = getProp($data, 'episode_id');
  324. if (!$episode_id) Utils::throwError('1002:请选择分集');
  325. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  326. $scenes = json_decode(getProp($episode, 'scenes'), true);
  327. $art_style = getProp($episode, 'art_style');
  328. $target_scene = getProp($data, 'target_scene');
  329. $anime_id = getProp($episode, 'anime_id');
  330. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  331. $art_style_type = getProp($anime, 'art_style_type');
  332. $character_prefix = '';
  333. $scene_prefix = '';
  334. if ($art_style_type) {
  335. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  336. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  337. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  338. }
  339. foreach ($scenes as &$scene) {
  340. $scene_name = getProp($scene, 'scene');
  341. if ($scene_name != $target_scene) continue;
  342. // 优先使用 pic_prompt,如果没有则使用 description
  343. $pic_prompt = getProp($scene, 'pic_prompt');
  344. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  345. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  346. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  347. // 参考图地址
  348. $ref_img_url = getProp($scene, 'url');
  349. if ($ref_img_url) continue; // 已有图片则跳过
  350. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  351. try {
  352. $params = [
  353. 'prompt' => $description,
  354. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  355. ];
  356. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  357. $task_id = $task->id;
  358. if (!$task_id) {
  359. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  360. }
  361. $scene['task_id'] = $task_id;
  362. $scene['task_status'] = 'processing';
  363. } catch (\Exception $e) {
  364. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  365. Utils::throwError("20003:" . $e->getMessage());
  366. }
  367. }
  368. // 保存场景信息
  369. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  370. 'scenes' => json_encode($scenes, 256),
  371. 'generate_status' => '执行中',
  372. 'generate_at' => date('Y-m-d H:i:s'),
  373. 'updated_at' => date('Y-m-d H:i:s')
  374. ]);
  375. if (!$boolen) {
  376. Utils::throwError('20003:保存角色信息失败');
  377. }
  378. return $boolen;
  379. }
  380. public function editAnime($data) {
  381. $anime_id = getProp($data, 'anime_id');
  382. $anime_name = trim(getProp($data, 'anime_name'));
  383. // 确认对话名称唯一性
  384. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  385. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  386. }
  387. if (!$anime_id || !$anime_name) {
  388. Utils::throwError('20003:参数异常');
  389. }
  390. return DB::table('mp_animes')->where('id', $anime_id)->update([
  391. 'anime_name' => $anime_name,
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. // $script_arr =getProp($data, 'script', []);
  395. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  396. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  397. // $anime_id = getProp($data, 'anime_id');
  398. // try {
  399. // DB::beginTransaction();
  400. // $table_data = [
  401. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  402. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  403. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  404. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  405. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  406. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  407. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  408. // 'status' => 3,
  409. // 'start_episode_sequence' => $start_episode_sequence,
  410. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  411. // 'episode_num' => count($script_arr['episodes']),
  412. // 'updated_at' => date('Y-m-d H:i:s')
  413. // ];
  414. // // 保存剧本内容
  415. // if (!empty($anime_id)) {
  416. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  417. // if (!$boolen) {
  418. // dLog('anime')->info('对话保存失败', $table_data);
  419. // Utils::throwError('20003:对话保存失败');
  420. // }
  421. // }else {
  422. // $table['created_at'] = $table_data['updated_at'];
  423. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  424. // if (!$anime_id) {
  425. // dLog('anime')->info('对话保存失败', $table_data);
  426. // Utils::throwError('20003:对话保存失败');
  427. // }
  428. // }
  429. // // 保存分集内容
  430. // // 删除历史分集内容
  431. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  432. // $episodes = [];
  433. // $sequence = 1;
  434. // foreach ($script_arr['episodes'] as $episode) {
  435. // $segment_number = 1;
  436. // foreach($episode['segments'] as $segment) {
  437. // $episodes[] = [
  438. // 'anime_id' => $anime_id,
  439. // 'episode_number' => $episode['episode_number'],
  440. // 'title' => $episode['title'],
  441. // // 'content' => $episode['content'],
  442. // 'content' => '',
  443. // 'segment_number' => $segment_number,
  444. // 'segment_content' => $segment['segment_content'],
  445. // 'sequence' => $sequence,
  446. // 'created_at' => date('Y-m-d H:i:s'),
  447. // 'updated_at' => date('Y-m-d H:i:s')
  448. // ];
  449. // $sequence++;
  450. // $segment_number++;
  451. // }
  452. // }
  453. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  454. // if (!$boolen2) {
  455. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  456. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  457. // Utils::throwError('20003:分集内容保存失败');
  458. // }
  459. // } catch (\Exception $e) {
  460. // DB::rollBack();
  461. // Utils::throwError('20003:'.$e->getMessage());
  462. // }
  463. // DB::commit();
  464. // return true;
  465. }
  466. public function delAnime($data) {
  467. $anime_id = getProp($data, 'anime_id');
  468. if (!$anime_id) {
  469. Utils::throwError('20003:请选择剧本');
  470. }
  471. return DB::table('mp_animes')->where('id', $anime_id)->update([
  472. 'is_deleted' => 1,
  473. 'updated_at' => date('Y-m-d H:i:s')
  474. ]);
  475. }
  476. public function animeDetail($data) {
  477. $uid = Site::getUid();
  478. $anime_id = getProp($data, 'anime_id');
  479. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  480. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  481. if (!$anime) Utils::throwError('20003:权限不足');
  482. $anime = (array)$anime;
  483. $anime['roles'] = json_decode($anime['roles']);
  484. $anime['scenes'] = json_decode($anime['scenes']);
  485. // 获取分集信息
  486. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  487. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  488. ->orderBy('episode_number')->get()->map(function ($value) {
  489. return (array)$value;
  490. })->toArray();
  491. $anime['episodes'] = $episodes;
  492. return $anime;
  493. }
  494. public function episodeInfo($data) {
  495. $uid = Site::getUid();
  496. $anime_id = getProp($data, 'anime_id');
  497. $episode_id = getProp($data, 'episode_id');
  498. if (!$anime_id || !$episode_id) {
  499. Utils::throwError('1002:请选择剧集');
  500. }
  501. // 验证用户权限
  502. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  503. if (!$anime) Utils::throwError('20003:权限不足');
  504. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  505. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  506. $episode = (array)$episode;
  507. $episode['roles'] = json_decode($episode['roles'], true);
  508. // foreach($episode['roles'] as &$item) {
  509. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  510. // }
  511. $episode['scenes'] = json_decode($episode['scenes'], true);
  512. // foreach($episode['scenes'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  514. // }
  515. // 获取分镜信息
  516. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  517. ->select('*')->get()->map(function ($value) {
  518. return (array)$value;
  519. })->toArray();
  520. // 使用公共方法构建分镜结构
  521. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  522. $episode['acts'] = $segmentsStructure['acts'];
  523. $episode['total_duration'] = $segmentsStructure['total_duration'];
  524. return $episode;
  525. }
  526. public function episodeInfoForAce($data) {
  527. $anime_id = getProp($data, 'anime_id');
  528. $episode_id = getProp($data, 'episode_id');
  529. if (!$anime_id || !$episode_id) {
  530. Utils::throwError('1002:请选择剧集');
  531. }
  532. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  533. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  534. $episode = (array)$episode;
  535. $episode['roles'] = json_decode($episode['roles'], true);
  536. // foreach($episode['roles'] as &$item) {
  537. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  538. // }
  539. $episode['scenes'] = json_decode($episode['scenes'], true);
  540. // foreach($episode['scenes'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  542. // }
  543. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  544. // 获取分镜信息
  545. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  546. ->select('*')->get()->map(function ($value) {
  547. return (array)$value;
  548. })->toArray();
  549. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  550. $episode['acts'] = $segmentsStructure['acts'];
  551. $episode['total_duration'] = $segmentsStructure['total_duration'];
  552. // 获取mp_animes表中的视频参数
  553. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  554. $episode['video_params'] = [
  555. 'video_model' => getProp($anime, 'video_model'),
  556. 'video_resolution' => getProp($anime, 'video_resolution'),
  557. 'ratio' => getProp($anime, 'video_ratio'),
  558. ];
  559. return $episode;
  560. }
  561. public function segmentInfo($data) {
  562. $uid = Site::getUid();
  563. $segment_id = getProp($data, 'segment_id');
  564. if (!$segment_id) {
  565. Utils::throwError('1002:请选择分镜');
  566. }
  567. // 获取分镜信息
  568. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  569. // 验证用户权限
  570. if ($segment) {
  571. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  572. if (!$anime) Utils::throwError('20003:权限不足');
  573. }
  574. $result = [
  575. 'segment_id' => getProp($segment, 'segment_id'),
  576. 'segment_number' => getProp($segment, 'segment_number'),
  577. 'segment_content' => getProp($segment, 'segment_content'),
  578. 'description' => getProp($segment, 'description'),
  579. 'composition' => getProp($segment, 'composition'),
  580. 'camera_movement' => getProp($segment, 'camera_movement'),
  581. 'voice_actor' => getProp($segment, 'voice_actor'),
  582. 'dialogue' => getProp($segment, 'dialogue'),
  583. 'frame_type' => getProp($segment, 'frame_type'),
  584. 'scene' => getProp($segment, 'scene'),
  585. 'characters' => getProp($segment, 'characters'),
  586. 'tail_frame' => getProp($segment, 'tail_frame'),
  587. 'emotion' => getProp($segment, 'emotion'),
  588. 'emotion_type' => getProp($segment, 'emotion_type'),
  589. 'gender' => getProp($segment, 'gender'),
  590. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  591. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  592. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  593. 'pitch' => getProp($segment, 'pitch'),
  594. 'voice_name' => getProp($segment, 'voice_name'),
  595. 'voice_type' => getProp($segment, 'voice_type'),
  596. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  597. 'img_url' => getProp($segment, 'img_url'),
  598. 'video_url' => getProp($segment, 'video_url'),
  599. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  600. ];
  601. return $result;
  602. }
  603. public function copyEpisodeVersion($data) {
  604. $episode_id = getProp($data, 'episode_id');
  605. $uid = Site::getUid();
  606. $cpid = Site::getCpid();
  607. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  608. if (!$episode) Utils::throwError('20003:该剧集不存在');
  609. $episode = (array)$episode;
  610. $anime_id = $episode['anime_id'];
  611. $episode_number = $episode['episode_number'];
  612. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  613. $sequence = $count + 1;
  614. unset($episode['id']);
  615. $now = date('Y-m-d H:i:s');
  616. $episode['created_at'] = $now;
  617. $episode['updated_at'] = $now;
  618. $episode['is_default'] = 1;
  619. // 获取版本中含有"(副本"字样的个数
  620. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  621. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  622. $episode['sequence'] = $sequence;
  623. $episode['is_generated'] = 0;
  624. $episode['cpid'] = $cpid;
  625. // 获取ace_mode
  626. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  627. try {
  628. DB::beginTransaction();
  629. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  630. // 新增副本
  631. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  632. if (!$new_episode_id) {
  633. Utils::throwError('20003:创建副本失败!');
  634. }
  635. // 获取分镜数据并准备插入
  636. $segments_for_insert = DB::table('mp_episode_segments')
  637. ->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')
  638. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  639. $item = (array)$item;
  640. $item['episode_id'] = $new_episode_id;
  641. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  642. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  643. return $item;
  644. })->toArray();
  645. // 写入分镜数据
  646. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  647. if (!$boolen2) {
  648. Utils::throwError('20003:写入分镜数据失败!');
  649. }
  650. // 写入对话历史
  651. $records = [
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'user',
  656. 'content' => '创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ],
  662. [
  663. 'uid' => $uid,
  664. 'anime_id' => $anime_id,
  665. 'role' => 'assistant',
  666. 'content' => '好的,已为您创建副本',
  667. 'sequence' => $episode_number,
  668. 'episode_id' => $new_episode_id,
  669. 'created_at' => $now,
  670. 'updated_at' => $now
  671. ]
  672. ];
  673. $boolen3 = DB::table('mp_anime_records')->insert($records);
  674. if (!$boolen3) {
  675. Utils::throwError('20003:对话记录保存失败');
  676. }
  677. }catch (\Exception $e) {
  678. DB::rollBack();
  679. Utils::throwError('20003:'.$e->getMessage());
  680. }
  681. DB::commit();
  682. // 构建与 episodeInfo 方法一致的返回数据结构
  683. $result = [
  684. 'episode_id' => $new_episode_id,
  685. 'anime_id' => $anime_id,
  686. 'episode_number' => $episode_number,
  687. 'title' => $episode['title'],
  688. 'intro' => $episode['intro'],
  689. 'art_style' => $episode['art_style'],
  690. 'roles' => json_decode($episode['roles'], true),
  691. 'scenes' => json_decode($episode['scenes'], true),
  692. 'is_generated' => (int)$episode['is_generated']
  693. ];
  694. if ((int)$ace_mode === 1) {
  695. // 获取分镜信息
  696. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  697. ->select('*')->get()->map(function ($value) {
  698. return (array)$value;
  699. })->toArray();
  700. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  701. }else {
  702. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  703. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  704. }
  705. $result['acts'] = $segmentsStructure['acts'];
  706. $result['total_duration'] = $segmentsStructure['total_duration'];
  707. return $result;
  708. }
  709. public function episodeVersions($data) {
  710. $anime_id = getProp($data, 'anime_id');
  711. $episode_id = getProp($data, 'episode_id');
  712. if (!$anime_id || !$episode_id) {
  713. Utils::throwError('1002:请选择剧集');
  714. }
  715. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  716. $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) {
  717. return (array)$value;
  718. })->toArray();
  719. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  720. foreach($episodes as &$episode) {
  721. $episode['version'] = 'V'.$episode['sequence'];
  722. $episode['roles'] = json_decode($episode['roles'], true);
  723. $episode['scenes'] = json_decode($episode['scenes'], true);
  724. // 获取分镜信息
  725. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  726. ->select('*')->get()->map(function ($value) {
  727. return (array)$value;
  728. })->toArray();
  729. // 使用公共方法构建分镜结构
  730. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  731. $episode['acts'] = $segmentsStructure['acts'];
  732. $episode['total_duration'] = $segmentsStructure['total_duration'];
  733. }
  734. return $episodes;
  735. }
  736. public function bindEpisodeVersion($data) {
  737. $episode_id = getProp($data, 'episode_id');
  738. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  739. if (!$episode) Utils::throwError('20003:该剧集不存在');
  740. $episode = (array)$episode;
  741. if ((int)$episode['is_default'] === 1) return true;
  742. try {
  743. DB::beginTransaction();
  744. // 移除is_default标志
  745. $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')]);
  746. if (!$boolen) {
  747. Utils::throwError('20003:更新失败!');
  748. }
  749. // 绑定副本
  750. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  751. if (!$boolen2) {
  752. Utils::throwError('20003:绑定失败!');
  753. }
  754. }catch (\Exception $e) {
  755. DB::rollBack();
  756. Utils::throwError('20003:'.$e->getMessage());
  757. }
  758. DB::commit();
  759. return true;
  760. }
  761. public function chatChangeImg($data) {
  762. $segment_id = getProp($data, 'segment_id');
  763. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  764. $prompt = getProp($data, 'prompt');
  765. if (!$prompt || !$segment_id) {
  766. Utils::throwError('1002:请输入提示词,并且选择分镜');
  767. }
  768. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  769. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  770. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  771. else $ref_img_url = '';
  772. // $ref_img_url = '';
  773. if (empty($prompt)) {
  774. if (empty($ref_img_url)) {
  775. $prompt = getProp($segment, 'segment_content');
  776. }else {
  777. $prompt = '请根据图片生成';
  778. }
  779. }
  780. $anime_id = getProp($segment, 'anime_id');
  781. $episode_id = getProp($segment, 'episode_id');
  782. $episode_number = getProp($segment, 'episode_number');
  783. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  784. $ratio = getProp($data, 'ratio');
  785. if (!$ratio) {
  786. $ratio = getProp($episode, 'ratio');
  787. if (!$ratio) $ratio = '9:16';
  788. }
  789. $art_style = getProp($episode, 'art_style');
  790. if ($art_style) {
  791. $prompt = "美术风格:{$art_style}\n{$prompt}";
  792. }
  793. $dimensions = $this->getRatioDimensions($ratio);
  794. $width = $dimensions['width'];
  795. $height = $dimensions['height'];
  796. try {
  797. $params = [
  798. 'alias_segment_id' => $segment_id,
  799. 'prompt' => $prompt,
  800. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  801. 'width' => $width,
  802. 'height' => $height
  803. ];
  804. // 优化提示词(不要生成字幕)
  805. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  806. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  807. $task_id = $task->id;
  808. if (!$task_id) {
  809. Utils::throwError("20003:生成图片失败");
  810. }
  811. // 更新任务ID
  812. $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')]);
  813. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  814. } catch (\Exception $e) {
  815. Utils::throwError("20003:" . $e->getMessage());
  816. }
  817. // 创建任务之后先暂停10s等待异步任务完成
  818. sleep(10);
  819. $img_url = $this->loopGetPicTaskResult($task_id);
  820. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  821. // 图片生成后新增对话记录
  822. try {
  823. $uid = Site::getUid();
  824. $now = date('Y-m-d H:i:s');
  825. // 使用AI反推图片提示词
  826. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  827. // 保存对话记录
  828. $records = [
  829. [
  830. 'uid' => $uid,
  831. 'anime_id' => $anime_id,
  832. 'sequence' => $episode_number,
  833. 'role' => 'user',
  834. 'content' => $prompt,
  835. 'segment_id' => $segment_id,
  836. 'pic_task_id' => $task_id,
  837. 'image_url' => '',
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ],
  841. [
  842. 'uid' => $uid,
  843. 'anime_id' => $anime_id,
  844. 'sequence' => $episode_number,
  845. 'role' => 'assistant',
  846. 'content' => $pic_prompt,
  847. 'segment_id' => $segment_id,
  848. 'pic_task_id' => $task_id,
  849. 'image_url' => $img_url,
  850. 'created_at' => $now,
  851. 'updated_at' => $now
  852. ]
  853. ];
  854. DB::table('mp_anime_records')->insert($records);
  855. } catch (\Exception $e) {
  856. // 记录日志但不影响主流程
  857. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  858. 'segment_id' => $segment_id,
  859. 'img_url' => $img_url
  860. ]);
  861. logDB('anime', 'error', '保存对话记录失败', [
  862. 'segment_id' => $segment_id,
  863. 'img_url' => $img_url,
  864. 'error' => $e->getMessage()
  865. ]);
  866. }
  867. return $img_url;
  868. }
  869. public function segmentChatHistory($data) {
  870. $segment_id = getProp($data, 'segment_id');
  871. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  872. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'created_at');
  873. $chat = $query->orderBy('id')->get()->map(function ($value) {
  874. $value = (array)$value;
  875. $value['created_at'] = transDate($value['created_at']);
  876. return $value;
  877. })->toArray();
  878. // 获取历史图片
  879. $url = [];
  880. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  881. foreach($pic_history as $task) {
  882. $result_url = getProp($task, 'result_url');
  883. if (is_json($result_url)) {
  884. $url = array_merge($url, json_decode($result_url, true));
  885. }else {
  886. $url[] = $result_url;
  887. }
  888. }
  889. // 获取历史视频
  890. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  891. foreach($video_history as $task) {
  892. $result_url = getProp($task, 'compressed_url');
  893. if (is_json($result_url)) {
  894. $url = array_merge($url, json_decode($result_url, true));
  895. }else {
  896. $url[] = $result_url;
  897. }
  898. }
  899. return compact('chat', 'url');
  900. }
  901. public function changeEpisodeRoles($data) {
  902. $anime_id = getProp($data, 'anime_id');
  903. $episode_id = getProp($data, 'episode_id');
  904. $target_roles = getProp($data, 'roles');
  905. $is_deleted = getProp($data, 'is_deleted', 0);
  906. // 参数验证
  907. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  908. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  909. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  910. // 验证剧集是否存在
  911. $episode = DB::table('mp_anime_episodes')
  912. ->where('anime_id', $anime_id)
  913. ->where('id', $episode_id)
  914. ->first();
  915. if (!$episode) Utils::throwError('20003:该剧集不存在');
  916. $roles = json_decode(getProp($episode, 'roles'), true);
  917. // 获取anime信息,检查是否有关联的script_id
  918. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  919. if (!$anime) Utils::throwError('20003:动漫不存在');
  920. $script_id = getProp($anime, 'script_id');
  921. $episode_number = getProp($episode, 'episode_number', 1);
  922. $uid = Site::getUid();
  923. $cpid = Site::getCpid();
  924. try {
  925. $target_role_name = getProp($target_roles, 'role');
  926. if (empty($target_role_name)) {
  927. Utils::throwError('20003:角色名称不能为空');
  928. }
  929. // 如果是删除操作
  930. if ($is_deleted == 1) {
  931. // 从角色列表中移除该角色
  932. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  933. return getProp($role, 'role') !== $target_role_name;
  934. }));
  935. // 更新角色列表
  936. $result = DB::table('mp_anime_episodes')
  937. ->where('anime_id', $anime_id)
  938. ->where('id', $episode_id)
  939. ->update([
  940. 'roles' => json_encode($roles, 256),
  941. 'updated_at' => date('Y-m-d H:i:s')
  942. ]);
  943. if ($result === false) {
  944. Utils::throwError('20003:删除角色失败');
  945. }
  946. } else {
  947. // 新增或更新操作
  948. $role_found = false;
  949. $is_new_role = false;
  950. // 查找并更新已存在的角色
  951. foreach($roles as &$role) {
  952. if (getProp($role, 'role') === $target_role_name) {
  953. $role = $target_roles;
  954. $role_found = true;
  955. break;
  956. }
  957. }
  958. // 如果角色不存在,则新增
  959. if (!$role_found) {
  960. $roles[] = $target_roles;
  961. $is_new_role = true;
  962. }
  963. // 更新角色列表
  964. $result = DB::table('mp_anime_episodes')
  965. ->where('anime_id', $anime_id)
  966. ->where('id', $episode_id)
  967. ->update([
  968. 'roles' => json_encode($roles, 256),
  969. 'updated_at' => date('Y-m-d H:i:s')
  970. ]);
  971. if ($result === false) {
  972. Utils::throwError('20003:更新角色列表失败');
  973. }
  974. // 同步更新分镜表中对应主体的音色信息
  975. $voice_name = getProp($target_roles, 'voice_name');
  976. $voice_type = getProp($target_roles, 'voice_type');
  977. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  978. DB::table('mp_episode_segments')
  979. ->where('anime_id', $anime_id)
  980. ->where('episode_id', $episode_id)
  981. ->where('voice_actor', $target_role_name)
  982. ->update([
  983. 'voice_name' => $voice_name,
  984. 'voice_type' => $voice_type,
  985. 'voice_audio_url' => $voice_audio_url,
  986. 'updated_at' => date('Y-m-d H:i:s')
  987. ]);
  988. // 如果有关联的script_id,则同步到mp_products表
  989. if ($script_id) {
  990. // 查询剧本信息
  991. $script = DB::table('mp_scripts')
  992. ->where('id', $script_id)
  993. ->where('is_deleted', 0)
  994. ->first();
  995. if ($script) {
  996. $script_name = $script->script_name ?? 'script_' . $script_id;
  997. $product_name = getProp($target_roles, 'role');
  998. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  999. $url = getProp($target_roles, 'url', '');
  1000. $product_type = 1; // 1=角色
  1001. // 查找或创建以script_name命名的文件夹
  1002. $folder = DB::table('mp_products')
  1003. ->where('cpid', $cpid)
  1004. ->where('type', 2) // 文件夹类型
  1005. ->where('product', $product_type) // 角色类型
  1006. ->where('product_name', $script_name)
  1007. ->where('parent_id', 0)
  1008. ->where('is_deleted', 0)
  1009. ->first();
  1010. if (!$folder) {
  1011. // 创建文件夹
  1012. $folder_id = DB::table('mp_products')->insertGetId([
  1013. 'user_id' => $uid,
  1014. 'cpid' => $cpid,
  1015. 'type' => 2, // 文件夹
  1016. 'product' => $product_type, // 角色类型
  1017. 'parent_id' => 0,
  1018. 'level' => 1,
  1019. 'product_name' => $script_name,
  1020. 'sort_order' => time(),
  1021. 'is_deleted' => 0,
  1022. 'created_at' => date('Y-m-d H:i:s'),
  1023. 'updated_at' => date('Y-m-d H:i:s')
  1024. ]);
  1025. } else {
  1026. $folder_id = $folder->id;
  1027. }
  1028. // 查找该文件夹下是否已存在同名资产
  1029. $existing_product = DB::table('mp_products')
  1030. ->where('cpid', $cpid)
  1031. ->where('type', 1) // 资产类型
  1032. ->where('product', $product_type)
  1033. ->where('parent_id', $folder_id)
  1034. ->where('product_name', $product_name)
  1035. ->where('is_deleted', 0)
  1036. ->first();
  1037. if ($existing_product) {
  1038. // 更新已存在的资产
  1039. $updateData = [
  1040. 'pic_task_status' => '生成成功',
  1041. ];
  1042. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1043. if ($url) $updateData['url'] = $url;
  1044. // 处理versions字段
  1045. $versions = getProp($target_roles, 'versions', []);
  1046. if ($versions && is_array($versions)) {
  1047. $updateData['versions'] = json_encode($versions, 256);
  1048. }
  1049. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1050. DB::table('mp_products')
  1051. ->where('id', $existing_product->id)
  1052. ->update($updateData);
  1053. $product_id = $existing_product->id;
  1054. } else {
  1055. // 创建新资产
  1056. $versions = getProp($target_roles, 'versions', []);
  1057. $product_id = DB::table('mp_products')->insertGetId([
  1058. 'user_id' => $uid,
  1059. 'cpid' => $cpid,
  1060. 'type' => 1, // 资产
  1061. 'product' => $product_type, // 角色
  1062. 'parent_id' => $folder_id,
  1063. 'level' => 2,
  1064. 'product_name' => $product_name,
  1065. 'url' => $url,
  1066. 'pic_prompt' => $pic_prompt,
  1067. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1068. 'sort_order' => time(),
  1069. 'is_deleted' => 0,
  1070. 'pic_task_status' => '生成成功',
  1071. 'created_at' => date('Y-m-d H:i:s'),
  1072. 'updated_at' => date('Y-m-d H:i:s')
  1073. ]);
  1074. }
  1075. // 建立或更新绑定关系
  1076. $existing_mapping = DB::table('mp_script_product_mappings')
  1077. ->where('script_id', $script_id)
  1078. ->where('product_id', $product_id)
  1079. ->where('episode_number', $episode_number)
  1080. ->first();
  1081. if (!$existing_mapping) {
  1082. // 创建绑定关系
  1083. DB::table('mp_script_product_mappings')->insert([
  1084. 'script_id' => $script_id,
  1085. 'product_id' => $product_id,
  1086. 'episode_number' => $episode_number,
  1087. 'created_at' => date('Y-m-d H:i:s'),
  1088. 'updated_at' => date('Y-m-d H:i:s')
  1089. ]);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. } catch (\Exception $e) {
  1095. dLog('anime')->error('更新剧集角色失败', [
  1096. 'anime_id' => $anime_id,
  1097. 'episode_id' => $episode_id,
  1098. 'error' => $e->getMessage()
  1099. ]);
  1100. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1101. }
  1102. return true;
  1103. }
  1104. public function changeEpisodeScenes($data) {
  1105. $anime_id = getProp($data, 'anime_id');
  1106. $episode_id = getProp($data, 'episode_id');
  1107. $target_scenes = getProp($data, 'scenes');
  1108. $is_deleted = getProp($data, 'is_deleted', 0);
  1109. // 参数验证
  1110. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1111. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1112. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1113. // 验证剧集是否存在
  1114. $episode = DB::table('mp_anime_episodes')
  1115. ->where('anime_id', $anime_id)
  1116. ->where('id', $episode_id)
  1117. ->first();
  1118. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1119. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1120. // 获取anime信息,检查是否有关联的script_id
  1121. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1122. if (!$anime) Utils::throwError('20003:动漫不存在');
  1123. $script_id = getProp($anime, 'script_id');
  1124. $episode_number = getProp($episode, 'episode_number', 1);
  1125. $uid = Site::getUid();
  1126. $cpid = Site::getCpid();
  1127. try {
  1128. $target_scene_name = getProp($target_scenes, 'scene');
  1129. if (empty($target_scene_name)) {
  1130. Utils::throwError('20003:场景名称不能为空');
  1131. }
  1132. // 如果是删除操作
  1133. if ($is_deleted == 1) {
  1134. // 从场景列表中移除该场景
  1135. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1136. return getProp($scene, 'scene') !== $target_scene_name;
  1137. }));
  1138. // 更新场景列表
  1139. $result = DB::table('mp_anime_episodes')
  1140. ->where('anime_id', $anime_id)
  1141. ->where('id', $episode_id)
  1142. ->update([
  1143. 'scenes' => json_encode($scenes, 256),
  1144. 'updated_at' => date('Y-m-d H:i:s')
  1145. ]);
  1146. if ($result === false) {
  1147. Utils::throwError('20003:删除场景失败');
  1148. }
  1149. } else {
  1150. // 新增或更新操作
  1151. $scene_found = false;
  1152. $is_new_scene = false;
  1153. // 查找并更新已存在的场景
  1154. foreach($scenes as &$scene) {
  1155. if (getProp($scene, 'scene') === $target_scene_name) {
  1156. $scene = $target_scenes;
  1157. $scene_found = true;
  1158. break;
  1159. }
  1160. }
  1161. // 如果场景不存在,则新增
  1162. if (!$scene_found) {
  1163. $scenes[] = $target_scenes;
  1164. $is_new_scene = true;
  1165. }
  1166. // 更新场景列表
  1167. $result = DB::table('mp_anime_episodes')
  1168. ->where('anime_id', $anime_id)
  1169. ->where('id', $episode_id)
  1170. ->update([
  1171. 'scenes' => json_encode($scenes, 256),
  1172. 'updated_at' => date('Y-m-d H:i:s')
  1173. ]);
  1174. if ($result === false) {
  1175. Utils::throwError('20003:更新场景列表失败');
  1176. }
  1177. // 如果有关联的script_id,则同步到mp_products表
  1178. if ($script_id) {
  1179. // 查询剧本信息
  1180. $script = DB::table('mp_scripts')
  1181. ->where('id', $script_id)
  1182. ->where('is_deleted', 0)
  1183. ->first();
  1184. if ($script) {
  1185. $script_name = $script->script_name ?? 'script_' . $script_id;
  1186. $product_name = getProp($target_scenes, 'scene');
  1187. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1188. $url = getProp($target_scenes, 'url', '');
  1189. $product_type = 2; // 2=场景
  1190. // 查找或创建以script_name命名的文件夹
  1191. $folder = DB::table('mp_products')
  1192. ->where('cpid', $cpid)
  1193. ->where('type', 2) // 文件夹类型
  1194. ->where('product', $product_type) // 场景类型
  1195. ->where('product_name', $script_name)
  1196. ->where('parent_id', 0)
  1197. ->where('is_deleted', 0)
  1198. ->first();
  1199. if (!$folder) {
  1200. // 创建文件夹
  1201. $folder_id = DB::table('mp_products')->insertGetId([
  1202. 'user_id' => $uid,
  1203. 'cpid' => $cpid,
  1204. 'type' => 2, // 文件夹
  1205. 'product' => $product_type, // 场景类型
  1206. 'parent_id' => 0,
  1207. 'level' => 1,
  1208. 'product_name' => $script_name,
  1209. 'sort_order' => time(),
  1210. 'is_deleted' => 0,
  1211. 'created_at' => date('Y-m-d H:i:s'),
  1212. 'updated_at' => date('Y-m-d H:i:s')
  1213. ]);
  1214. } else {
  1215. $folder_id = $folder->id;
  1216. }
  1217. // 查找该文件夹下是否已存在同名资产
  1218. $existing_product = DB::table('mp_products')
  1219. ->where('cpid', $cpid)
  1220. ->where('type', 1) // 资产类型
  1221. ->where('product', $product_type)
  1222. ->where('parent_id', $folder_id)
  1223. ->where('product_name', $product_name)
  1224. ->where('is_deleted', 0)
  1225. ->first();
  1226. if ($existing_product) {
  1227. // 更新已存在的资产
  1228. $updateData = [
  1229. 'pic_task_status' => '生成成功'
  1230. ];
  1231. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1232. if ($url) $updateData['url'] = $url;
  1233. // 处理versions字段
  1234. $versions = getProp($target_scenes, 'versions', []);
  1235. if ($versions && is_array($versions)) {
  1236. $updateData['versions'] = json_encode($versions, 256);
  1237. }
  1238. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1239. DB::table('mp_products')
  1240. ->where('id', $existing_product->id)
  1241. ->update($updateData);
  1242. $product_id = $existing_product->id;
  1243. } else {
  1244. // 创建新资产
  1245. $versions = getProp($target_scenes, 'versions', []);
  1246. $product_id = DB::table('mp_products')->insertGetId([
  1247. 'user_id' => $uid,
  1248. 'cpid' => $cpid,
  1249. 'type' => 1, // 资产
  1250. 'product' => $product_type, // 场景
  1251. 'parent_id' => $folder_id,
  1252. 'level' => 2,
  1253. 'product_name' => $product_name,
  1254. 'url' => $url,
  1255. 'pic_prompt' => $pic_prompt,
  1256. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1257. 'sort_order' => time(),
  1258. 'is_deleted' => 0,
  1259. 'pic_task_status' => '生成成功',
  1260. 'created_at' => date('Y-m-d H:i:s'),
  1261. 'updated_at' => date('Y-m-d H:i:s')
  1262. ]);
  1263. }
  1264. // 建立或更新绑定关系
  1265. $existing_mapping = DB::table('mp_script_product_mappings')
  1266. ->where('script_id', $script_id)
  1267. ->where('product_id', $product_id)
  1268. ->where('episode_number', $episode_number)
  1269. ->first();
  1270. if (!$existing_mapping) {
  1271. // 创建绑定关系
  1272. DB::table('mp_script_product_mappings')->insert([
  1273. 'script_id' => $script_id,
  1274. 'product_id' => $product_id,
  1275. 'episode_number' => $episode_number,
  1276. 'created_at' => date('Y-m-d H:i:s'),
  1277. 'updated_at' => date('Y-m-d H:i:s')
  1278. ]);
  1279. }
  1280. }
  1281. }
  1282. }
  1283. } catch (\Exception $e) {
  1284. dLog('anime')->error('更新剧集场景失败', [
  1285. 'anime_id' => $anime_id,
  1286. 'episode_id' => $episode_id,
  1287. 'error' => $e->getMessage()
  1288. ]);
  1289. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1290. }
  1291. return true;
  1292. }
  1293. public function changeEpisodeProps($data) {
  1294. $anime_id = getProp($data, 'anime_id');
  1295. $episode_id = getProp($data, 'episode_id');
  1296. $target_props = getProp($data, 'props');
  1297. $is_deleted = getProp($data, 'is_deleted', 0);
  1298. // 参数验证
  1299. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1300. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1301. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1302. // 验证剧集是否存在
  1303. $episode = DB::table('mp_anime_episodes')
  1304. ->where('anime_id', $anime_id)
  1305. ->where('id', $episode_id)
  1306. ->first();
  1307. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1308. $props = json_decode(getProp($episode, 'props'), true);
  1309. // 获取anime信息,检查是否有关联的script_id
  1310. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1311. if (!$anime) Utils::throwError('20003:动漫不存在');
  1312. $script_id = getProp($anime, 'script_id');
  1313. $episode_number = getProp($episode, 'episode_number', 1);
  1314. $uid = Site::getUid();
  1315. $cpid = Site::getCpid();
  1316. try {
  1317. $target_prop_name = getProp($target_props, 'prop');
  1318. if (empty($target_prop_name)) {
  1319. Utils::throwError('20003:道具名称不能为空');
  1320. }
  1321. // 如果是删除操作
  1322. if ($is_deleted == 1) {
  1323. // 从道具列表中移除该道具
  1324. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1325. return getProp($prop, 'prop') !== $target_prop_name;
  1326. }));
  1327. // 更新道具列表
  1328. $result = DB::table('mp_anime_episodes')
  1329. ->where('anime_id', $anime_id)
  1330. ->where('id', $episode_id)
  1331. ->update([
  1332. 'props' => json_encode($props, 256),
  1333. 'updated_at' => date('Y-m-d H:i:s')
  1334. ]);
  1335. if ($result === false) {
  1336. Utils::throwError('20003:删除道具失败');
  1337. }
  1338. } else {
  1339. // 新增或更新操作
  1340. $prop_found = false;
  1341. $is_new_prop = false;
  1342. // 查找并更新已存在的道具
  1343. foreach($props as &$prop) {
  1344. if (getProp($prop, 'prop') === $target_prop_name) {
  1345. $prop = $target_props;
  1346. $prop_found = true;
  1347. break;
  1348. }
  1349. }
  1350. // 如果道具不存在,则新增
  1351. if (!$prop_found) {
  1352. $props[] = $target_props;
  1353. $is_new_prop = true;
  1354. }
  1355. // 更新道具列表
  1356. $result = DB::table('mp_anime_episodes')
  1357. ->where('anime_id', $anime_id)
  1358. ->where('id', $episode_id)
  1359. ->update([
  1360. 'props' => json_encode($props, 256),
  1361. 'updated_at' => date('Y-m-d H:i:s')
  1362. ]);
  1363. if ($result === false) {
  1364. Utils::throwError('20003:更新道具列表失败');
  1365. }
  1366. // 如果有关联的script_id,则同步到mp_products表
  1367. if ($script_id) {
  1368. // 查询剧本信息
  1369. $script = DB::table('mp_scripts')
  1370. ->where('id', $script_id)
  1371. ->where('is_deleted', 0)
  1372. ->first();
  1373. if ($script) {
  1374. $script_name = $script->script_name ?? 'script_' . $script_id;
  1375. $product_name = getProp($target_props, 'prop');
  1376. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1377. $url = getProp($target_props, 'url', '');
  1378. $product_type = 3; // 3=道具
  1379. // 查找或创建以script_name命名的文件夹
  1380. $folder = DB::table('mp_products')
  1381. ->where('cpid', $cpid)
  1382. ->where('type', 2) // 文件夹类型
  1383. ->where('product', $product_type) // 道具类型
  1384. ->where('product_name', $script_name)
  1385. ->where('parent_id', 0)
  1386. ->where('is_deleted', 0)
  1387. ->first();
  1388. if (!$folder) {
  1389. // 创建文件夹
  1390. $folder_id = DB::table('mp_products')->insertGetId([
  1391. 'user_id' => $uid,
  1392. 'cpid' => $cpid,
  1393. 'type' => 2, // 文件夹
  1394. 'product' => $product_type, // 道具类型
  1395. 'parent_id' => 0,
  1396. 'level' => 1,
  1397. 'product_name' => $script_name,
  1398. 'sort_order' => time(),
  1399. 'is_deleted' => 0,
  1400. 'created_at' => date('Y-m-d H:i:s'),
  1401. 'updated_at' => date('Y-m-d H:i:s')
  1402. ]);
  1403. } else {
  1404. $folder_id = $folder->id;
  1405. }
  1406. // 查找该文件夹下是否已存在同名资产
  1407. $existing_product = DB::table('mp_products')
  1408. ->where('cpid', $cpid)
  1409. ->where('type', 1) // 资产类型
  1410. ->where('product', $product_type)
  1411. ->where('parent_id', $folder_id)
  1412. ->where('product_name', $product_name)
  1413. ->where('is_deleted', 0)
  1414. ->first();
  1415. if ($existing_product) {
  1416. // 更新已存在的资产
  1417. $updateData = [
  1418. 'pic_task_status' => '生成成功'
  1419. ];
  1420. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1421. if ($url) $updateData['url'] = $url;
  1422. // 处理versions字段
  1423. $versions = getProp($target_props, 'versions', []);
  1424. if ($versions && is_array($versions)) {
  1425. $updateData['versions'] = json_encode($versions, 256);
  1426. }
  1427. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1428. DB::table('mp_products')
  1429. ->where('id', $existing_product->id)
  1430. ->update($updateData);
  1431. $product_id = $existing_product->id;
  1432. } else {
  1433. // 创建新资产
  1434. $versions = getProp($target_props, 'versions', []);
  1435. $product_id = DB::table('mp_products')->insertGetId([
  1436. 'user_id' => $uid,
  1437. 'cpid' => $cpid,
  1438. 'type' => 1, // 资产
  1439. 'product' => $product_type, // 道具
  1440. 'parent_id' => $folder_id,
  1441. 'level' => 2,
  1442. 'product_name' => $product_name,
  1443. 'url' => $url,
  1444. 'pic_prompt' => $pic_prompt,
  1445. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1446. 'sort_order' => time(),
  1447. 'is_deleted' => 0,
  1448. 'pic_task_status' => '生成成功',
  1449. 'created_at' => date('Y-m-d H:i:s'),
  1450. 'updated_at' => date('Y-m-d H:i:s')
  1451. ]);
  1452. }
  1453. // 建立或更新绑定关系
  1454. $existing_mapping = DB::table('mp_script_product_mappings')
  1455. ->where('script_id', $script_id)
  1456. ->where('product_id', $product_id)
  1457. ->where('episode_number', $episode_number)
  1458. ->first();
  1459. if (!$existing_mapping) {
  1460. // 创建绑定关系
  1461. DB::table('mp_script_product_mappings')->insert([
  1462. 'script_id' => $script_id,
  1463. 'product_id' => $product_id,
  1464. 'episode_number' => $episode_number,
  1465. 'created_at' => date('Y-m-d H:i:s'),
  1466. 'updated_at' => date('Y-m-d H:i:s')
  1467. ]);
  1468. }
  1469. }
  1470. }
  1471. }
  1472. } catch (\Exception $e) {
  1473. dLog('anime')->error('更新剧集道具失败', [
  1474. 'anime_id' => $anime_id,
  1475. 'episode_id' => $episode_id,
  1476. 'error' => $e->getMessage()
  1477. ]);
  1478. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1479. }
  1480. return true;
  1481. }
  1482. public function editSegment($data) {
  1483. $segment_id = getProp($data, 'segment_id');
  1484. $segment_content = getProp($data, 'segment_content');
  1485. $image_url = getProp($data, 'image_url');
  1486. $video_url = getProp($data, 'video_url');
  1487. // 参数验证
  1488. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1489. // 验证分镜是否存在
  1490. $segment = DB::table('mp_episode_segments')
  1491. ->where('segment_id', $segment_id)
  1492. ->first();
  1493. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1494. $dubTaskId = 0;
  1495. try {
  1496. DB::beginTransaction();
  1497. // 准备更新数据
  1498. $update_data = [
  1499. 'updated_at' => date('Y-m-d H:i:s')
  1500. ];
  1501. if ($segment_content) {
  1502. // 先将segment_content赋值到update_data
  1503. $update_data['segment_content'] = $segment_content;
  1504. // 使用现有方法分析segment_content,提取各个字段
  1505. $this->handleSegmentContent($update_data);
  1506. // 如果有对话内容,创建视频配音合成任务
  1507. $dialogue = getProp($update_data, 'dialogue');
  1508. if (!empty($dialogue)) {
  1509. $now = date('Y-m-d H:i:s');
  1510. $generate_json = [
  1511. 'text' => $dialogue,
  1512. 'role' => getProp($update_data, 'voice_actor'),
  1513. 'voice_type' => getProp($update_data, 'voice_type'),
  1514. 'voice_name' => getProp($update_data, 'voice_name'),
  1515. 'emotion' => getProp($update_data, 'emotion'),
  1516. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1517. 'gender' => getProp($update_data, 'gender'),
  1518. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1519. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1520. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1521. 'pitch' => getProp($update_data, 'pitch', 0),
  1522. ];
  1523. // 插入视频配音合成任务
  1524. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1525. 'alias_segment_id' => $segment_id,
  1526. 'generate_status' => '执行中',
  1527. 'audio_url' => '',
  1528. 'generate_json' => json_encode($generate_json, 256),
  1529. 'created_at' => $now,
  1530. 'updated_at' => $now,
  1531. ]);
  1532. if (!$dubTaskId) {
  1533. Utils::throwError('20003:创建配音任务失败!');
  1534. }
  1535. $update_data['audio_url'] = '';
  1536. } else {
  1537. // dialogue为空时,直接写入默认音频信息
  1538. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1539. $update_data['audio_duration'] = 2.0;
  1540. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1541. }
  1542. }
  1543. if ($image_url) {
  1544. $update_data['img_url'] = $image_url;
  1545. // 同时写入一个简单的图片生成任务
  1546. $pic_task = [
  1547. 'alias_segment_id' => $segment_id,
  1548. 'ref_img_url' => json_encode([]),
  1549. 'status' => 'success',
  1550. 'result_url' => json_encode([$image_url], 256),
  1551. 'model' => '',
  1552. 'created_at' => date('Y-m-d H:i:s'),
  1553. 'updated_at' => date('Y-m-d H:i:s'),
  1554. ];
  1555. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1556. }
  1557. if ($video_url) {
  1558. $update_data['origin_video_url'] = $video_url;
  1559. $compressed_video_url = compressVideo($video_url);
  1560. $update_data['current_type'] = 2;
  1561. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1562. // 同时写入一个简单的视频生成任务
  1563. $video_task = [
  1564. 'alias_segment_id' => $segment_id,
  1565. 'status' => 'success',
  1566. 'result_url' => $update_data['origin_video_url'],
  1567. 'compressed_url' => $update_data['video_url'],
  1568. 'created_at' => date('Y-m-d H:i:s'),
  1569. 'updated_at' => date('Y-m-d H:i:s'),
  1570. ];
  1571. DB::table('mp_generate_video_tasks')->insert($video_task);
  1572. }
  1573. // 更新分镜信息
  1574. $result = DB::table('mp_episode_segments')
  1575. ->where('segment_id', $segment_id)
  1576. ->update($update_data);
  1577. if ($result === false) {
  1578. Utils::throwError('20003:更新分镜剧本失败');
  1579. }
  1580. DB::commit();
  1581. // 如果有创建音频生成任务则调用API
  1582. if ($dubTaskId) {
  1583. // 请求远程服务器执行生成
  1584. $client = new Client(['timeout' => 300, 'verify' => false]);
  1585. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1586. $response = $result->getBody()->getContents();
  1587. $response_arr = json_decode($response, true);
  1588. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1589. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1590. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1591. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1592. Utils::throwError('20003:火山生成音频失败');
  1593. }
  1594. }
  1595. return true;
  1596. } catch (\Exception $e) {
  1597. DB::rollBack();
  1598. dLog('anime')->error('更新分镜剧本失败', [
  1599. 'segment_id' => $segment_id,
  1600. 'error' => $e->getMessage()
  1601. ]);
  1602. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1603. }
  1604. }
  1605. public function batchSetSegmentPics($data) {
  1606. $anime_id = getProp($data, 'anime_id');
  1607. $episode_id = getProp($data, 'episode_id');
  1608. $ratio = getProp($data, 'ratio');
  1609. $dimensions = $this->getRatioDimensions($ratio);
  1610. $width = $dimensions['width'];
  1611. $height = $dimensions['height'];
  1612. if (!$anime_id || !$episode_id) {
  1613. Utils::throwError('1002:请选择剧集');
  1614. }
  1615. // 获取剧集信息
  1616. $episode = DB::table('mp_anime_episodes')
  1617. ->where('anime_id', $anime_id)
  1618. ->where('id', $episode_id)
  1619. ->where('is_default', 1)
  1620. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1621. ->first();
  1622. if (!$episode) {
  1623. Utils::throwError('20003:该剧集不存在');
  1624. }
  1625. $model = getProp($data, 'model');
  1626. if (!$model) {
  1627. $model = getProp($episode, 'image_model');
  1628. if (!$model) {
  1629. // episode表也没有,使用默认值
  1630. $model = 'doubao-seedream-5-0-lite-260128';
  1631. }
  1632. }
  1633. // 验证模型是否在可用模型表中
  1634. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1635. $model = 'doubao-seedream-5-0-lite-260128';
  1636. }
  1637. $roles = json_decode(getProp($episode, 'roles'), true);
  1638. if (!$roles) {
  1639. Utils::throwError('20003:角色信息格式错误');
  1640. }
  1641. // 构建角色名称到参考图的映射
  1642. $role_map = [];
  1643. foreach ($roles as $role) {
  1644. $role_name = getProp($role, 'role');
  1645. $role_url = getProp($role, 'url');
  1646. if (!empty($role_name) && !empty($role_url)) {
  1647. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1648. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1649. // $role_map[$base_name] = $role_url;
  1650. // 同时保存完整名称的映射
  1651. $role_map[$role_name] = $role_url;
  1652. }
  1653. }
  1654. $scenes = json_decode(getProp($episode, 'roles'), true);
  1655. if (!$scenes) {
  1656. Utils::throwError('20003:场景信息格式错误');
  1657. }
  1658. // 构建角色名称到参考图的映射
  1659. $scene_map = [];
  1660. foreach ($scenes as $scene) {
  1661. $scene_name = getProp($scene, 'scene');
  1662. $scene_url = getProp($scene, 'url');
  1663. if (!empty($scene_name) && !empty($scene_url)) {
  1664. $scene_map[$scene_name] = $scene_url;
  1665. }
  1666. }
  1667. // 获取所有分镜信息
  1668. $segments = DB::table('mp_episode_segments')
  1669. ->where('anime_id', $anime_id)
  1670. ->where('episode_id', $episode_id)
  1671. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1672. ->orderBy('segment_number')
  1673. ->get()
  1674. ->toArray();
  1675. if (empty($segments)) {
  1676. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1677. }
  1678. // 保存图片比例
  1679. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1680. $updated_segments = [];
  1681. $failed_segments = [];
  1682. // 批量为每个分镜生成图片任务
  1683. foreach ($segments as $segment) {
  1684. $segment_id = $segment->segment_id;
  1685. $segment_content = $segment->segment_content;
  1686. if (empty($segment_content)) {
  1687. $failed_segments[] = [
  1688. 'segment_id' => $segment_id,
  1689. 'error' => '分镜内容为空'
  1690. ];
  1691. continue;
  1692. }
  1693. try {
  1694. $dubTaskId = 0;
  1695. // 解析分镜内容,提取画面描述作为主要提示词
  1696. $prompt = $segment_content;
  1697. $ref_img_urls = [];
  1698. // 分镜场景
  1699. $scene = getProp($segment, 'scene');
  1700. $matched_scene = '';
  1701. if (isset($scene_map[$scene])) {
  1702. $img_index = count($ref_img_urls) + 1;
  1703. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1704. $ref_img_urls[] = $scene_map[$scene];
  1705. $matched_scene = $scene;
  1706. }
  1707. // 分镜角色
  1708. $characters = getProp($segment, 'characters');
  1709. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1710. $roles = explode(',', $characters);
  1711. // 从分镜内容中提取涉及的角色
  1712. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1713. // 获取匹配角色的参考图
  1714. foreach ($segment_characters as $character) {
  1715. if (isset($role_map[$character])) {
  1716. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1717. $img_index = count($ref_img_urls) + 1;
  1718. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1719. $ref_img_urls[] = $role_map[$character];
  1720. }
  1721. }
  1722. // 如果没有找到匹配的角色参考图,不使用参考图
  1723. if (empty($ref_img_urls)) {
  1724. $ref_img_urls = [];
  1725. }
  1726. // 准备生成任务参数
  1727. $params = [
  1728. 'model' => $model,
  1729. 'alias_segment_id' => $segment_id,
  1730. 'prompt' => $prompt,
  1731. 'ref_img_urls' => $ref_img_urls,
  1732. 'width' => $width,
  1733. 'height' => $height,
  1734. ];
  1735. // 优化提示词(不要生成字幕)
  1736. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1737. // $task_id = mt_rand(100000, 999999);
  1738. // 调用AI图片生成服务
  1739. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1740. $task_id = $task->id;
  1741. if (!$task_id) {
  1742. $failed_segments[] = [
  1743. 'segment_id' => $segment_id,
  1744. 'error' => '创建生成任务失败'
  1745. ];
  1746. continue;
  1747. }
  1748. $update_data = [
  1749. 'pic_task_id' => $task_id,
  1750. 'pic_task_status' => '生成中',
  1751. 'audio_url' => '',
  1752. 'updated_at' => date('Y-m-d H:i:s')
  1753. ];
  1754. // 如果有对话内容,创建视频配音合成任务
  1755. $dialogue = getProp($segment, 'dialogue');
  1756. if (!empty($dialogue)) {
  1757. $now = date('Y-m-d H:i:s');
  1758. $generate_json = [
  1759. 'text' => $dialogue,
  1760. 'role' => getProp($segment, 'voice_actor'),
  1761. 'voice_type' => getProp($segment, 'voice_type'),
  1762. 'voice_name' => getProp($segment, 'voice_name'),
  1763. 'emotion' => getProp($segment, 'emotion'),
  1764. 'emotion_type' => getProp($segment, 'emotion_type'),
  1765. 'gender' => getProp($segment, 'gender'),
  1766. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1767. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1768. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1769. 'pitch' => getProp($segment, 'pitch', 0),
  1770. ];
  1771. // 插入视频配音合成任务
  1772. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1773. 'alias_segment_id' => $segment_id,
  1774. 'generate_status' => '执行中',
  1775. 'audio_url' => '',
  1776. 'generate_json' => json_encode($generate_json, 256),
  1777. 'created_at' => $now,
  1778. 'updated_at' => $now,
  1779. ]);
  1780. if (!$dubTaskId) {
  1781. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1782. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1783. // Utils::throwError('20003:创建配音任务失败!');
  1784. }
  1785. } else {
  1786. // dialogue为空时,直接写入默认音频信息到分镜表
  1787. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1788. $update_data['audio_duration'] = 2.0;
  1789. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1790. }
  1791. // 更新分镜的任务信息
  1792. $update_result = DB::table('mp_episode_segments')
  1793. ->where('segment_id', $segment_id)
  1794. ->update($update_data);
  1795. // 如果是第一集的首帧图片,则存入待更新数组
  1796. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1797. Redis::sadd('anime_first_frame_urls', $segment_id);
  1798. }
  1799. if ($update_result) {
  1800. $updated_segments[] = [
  1801. 'segment_id' => $segment_id,
  1802. 'task_id' => $task_id,
  1803. 'status' => '生成中',
  1804. 'matched_scenes' => $matched_scene,
  1805. 'matched_roles' => $segment_characters,
  1806. 'ref_urls_count' => count($ref_img_urls)
  1807. ];
  1808. } else {
  1809. $failed_segments[] = [
  1810. 'segment_id' => $segment_id,
  1811. 'error' => '更新分镜任务状态失败'
  1812. ];
  1813. }
  1814. if ($dubTaskId) {
  1815. sleep(1);
  1816. // 请求远程服务器执行生成
  1817. $client = new Client(['timeout' => 300, 'verify' => false]);
  1818. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1819. $response = $result->getBody()->getContents();
  1820. $response_arr = json_decode($response, true);
  1821. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1822. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1823. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1824. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1825. }
  1826. }
  1827. } catch (\Exception $e) {
  1828. $failed_segments[] = [
  1829. 'segment_id' => $segment_id,
  1830. 'error' => $e->getMessage()
  1831. ];
  1832. }
  1833. }
  1834. // 更新剧集生成状态
  1835. if (!empty($updated_segments)) {
  1836. DB::table('mp_anime_episodes')
  1837. ->where('id', $episode_id)
  1838. ->update([
  1839. 'is_generated' => 1,
  1840. 'updated_at' => date('Y-m-d H:i:s')
  1841. ]);
  1842. }
  1843. return [
  1844. 'success_count' => count($updated_segments),
  1845. 'failed_count' => count($failed_segments),
  1846. 'success_segments' => $updated_segments,
  1847. 'failed_segments' => $failed_segments,
  1848. 'total_segments' => count($segments)
  1849. ];
  1850. }
  1851. public function reGenerateSegment($data) {
  1852. $segment_id = getProp($data, 'segment_id');
  1853. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1854. $anime_id = getProp($segment, 'anime_id');
  1855. $episode_id = getProp($segment, 'episode_id');
  1856. $episode_number = getProp($segment, 'episode_number');
  1857. $segment_content = getProp($data, 'segment_content');
  1858. $ratio = getProp($data, 'ratio');
  1859. if (!$ratio) {
  1860. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1861. if (!$ratio) $ratio = '9:16';
  1862. }
  1863. $dimensions = $this->getRatioDimensions($ratio);
  1864. $width = $dimensions['width'];
  1865. $height = $dimensions['height'];
  1866. if (!$anime_id || !$episode_id) {
  1867. Utils::throwError('1002:请选择分镜');
  1868. }
  1869. // 使用文生文模型重新解析segment_content
  1870. if (!empty($segment_content)) {
  1871. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1872. }
  1873. // 获取动漫的角色信息(包含参考图)
  1874. $anime = DB::table('mp_animes')
  1875. ->where('id', $anime_id)
  1876. ->select('roles', 'scenes')
  1877. ->first();
  1878. if (!$anime || !$anime->roles) {
  1879. Utils::throwError('20003:未找到角色信息');
  1880. }
  1881. $roles = json_decode($anime->roles, true);
  1882. if (!$roles) {
  1883. Utils::throwError('20003:角色信息格式错误');
  1884. }
  1885. // 构建角色名称到参考图的映射
  1886. $role_map = [];
  1887. foreach ($roles as $role) {
  1888. $role_name = getProp($role, 'role');
  1889. $role_url = getProp($role, 'url');
  1890. if (!empty($role_name) && !empty($role_url)) {
  1891. $role_map[$role_name] = $role_url;
  1892. }
  1893. }
  1894. $scenes = json_decode($anime->scenes, true);
  1895. if (!$scenes) {
  1896. Utils::throwError('20003:角色信息格式错误');
  1897. }
  1898. // 构建角色名称到参考图的映射
  1899. $scene_map = [];
  1900. foreach ($scenes as $scene) {
  1901. $scene_name = getProp($scene, 'scene');
  1902. $scene_url = getProp($scene, 'url');
  1903. if (!empty($scene_name) && !empty($scene_url)) {
  1904. $scene_map[$scene_name] = $scene_url;
  1905. }
  1906. }
  1907. $segment_id = $segment->segment_id;
  1908. $original_segment_content = $segment->segment_content;
  1909. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1910. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1911. if (empty($final_segment_content)) {
  1912. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1913. }
  1914. try {
  1915. $dubTaskId = 0;
  1916. // 分镜剧本数组
  1917. $update_data = [
  1918. 'segment_content' => $final_segment_content,
  1919. 'pic_task_status' => '生成中',
  1920. 'updated_at' => date('Y-m-d H:i:s')
  1921. ];
  1922. // 解析分镜内容,提取画面描述作为主要提示词
  1923. $prompt = $final_segment_content;
  1924. $ref_img_urls = [];
  1925. // 分镜场景
  1926. $scene = getProp($data, 'scene');
  1927. if ($scene) {
  1928. $matched_scene = '';
  1929. if (isset($scene_map[$scene])) {
  1930. $img_index = count($ref_img_urls) + 1;
  1931. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1932. $ref_img_urls[] = $scene_map[$scene];
  1933. $matched_scene = $scene;
  1934. }
  1935. $update_data['scene'] = $scene;
  1936. }
  1937. // 分镜角色
  1938. $characters = getProp($data, 'characters');
  1939. if ($characters) {
  1940. $update_data['characters'] = $characters;
  1941. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1942. $characters = explode(',', $characters);
  1943. // 从分镜内容中提取涉及的角色
  1944. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1945. // 获取匹配角色的参考图
  1946. foreach ($segment_characters as $character) {
  1947. if (isset($role_map[$character])) {
  1948. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1949. $img_index = count($ref_img_urls) + 1;
  1950. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1951. $ref_img_urls[] = $role_map[$character];
  1952. }
  1953. }
  1954. }
  1955. // 如果没有找到匹配的角色参考图,不使用参考图
  1956. if (empty($ref_img_urls)) {
  1957. $ref_img_urls = [];
  1958. }
  1959. // 准备生成任务参数
  1960. $params = [
  1961. 'alias_segment_id' => $segment_id,
  1962. 'prompt' => $prompt,
  1963. 'ref_img_urls' => $ref_img_urls,
  1964. 'width' => $width,
  1965. 'height' => $height,
  1966. ];
  1967. // 优化提示词(不要生成字幕)
  1968. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1969. // 调用AI图片生成服务
  1970. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1971. $task_id = $task->id;
  1972. if (!$task_id) {
  1973. Utils::throwError('20003:创建生成任务失败!');
  1974. }
  1975. $update_data['pic_task_id'] = $task_id;
  1976. // 更新分镜剧本信息
  1977. $this->handleSegmentContent($update_data);
  1978. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1979. if ($segment_content) {
  1980. $dialogue = getProp($update_data, 'dialogue');
  1981. if (!empty($dialogue)) {
  1982. $now = date('Y-m-d H:i:s');
  1983. $generate_json = [
  1984. 'text' => $dialogue,
  1985. 'role' => getProp($update_data, 'voice_actor'),
  1986. 'voice_type' => getProp($update_data, 'voice_type'),
  1987. 'voice_name' => getProp($update_data, 'voice_name'),
  1988. 'emotion' => getProp($update_data, 'emotion'),
  1989. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1990. 'gender' => getProp($update_data, 'gender'),
  1991. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1992. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1993. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1994. 'pitch' => getProp($update_data, 'pitch', 0),
  1995. ];
  1996. // 插入视频配音合成任务
  1997. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1998. 'alias_segment_id' => $segment_id,
  1999. 'generate_status' => '执行中',
  2000. 'audio_url' => '',
  2001. 'generate_json' => json_encode($generate_json, 256),
  2002. 'created_at' => date('Y-m-d H:i:s'),
  2003. 'updated_at' => date('Y-m-d H:i:s'),
  2004. ]);
  2005. if (!$dubTaskId) {
  2006. Utils::throwError('20003:创建配音任务失败!');
  2007. }
  2008. $update_data['audio_url'] = '';
  2009. } else {
  2010. // dialogue为空时,直接写入默认音频信息
  2011. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2012. $update_data['audio_duration'] = 2.0;
  2013. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2014. }
  2015. }
  2016. $boolen = DB::table('mp_episode_segments')
  2017. ->where('segment_id', $segment_id)
  2018. ->update($update_data);
  2019. // 如果是第一集的首帧图片,则存入待更新数组
  2020. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2021. Redis::sadd('anime_first_frame_urls', $segment_id);
  2022. }
  2023. if ($dubTaskId) {
  2024. // 请求远程服务器执行生成
  2025. $client = new Client(['timeout' => 300, 'verify' => false]);
  2026. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2027. $response = $result->getBody()->getContents();
  2028. $response_arr = json_decode($response, true);
  2029. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2030. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2031. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2032. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2033. Utils::throwError('20003:火山生成音频失败');
  2034. }
  2035. }
  2036. } catch (\Exception $e) {
  2037. $failed_segments[] = [
  2038. 'segment_id' => $segment_id,
  2039. 'error' => $e->getMessage()
  2040. ];
  2041. }
  2042. // 创建任务之后先暂停10s等待异步任务完成
  2043. sleep(10);
  2044. $img_url = $this->loopGetPicTaskResult($task_id);
  2045. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2046. // 图片生成后新增对话记录
  2047. try {
  2048. $uid = Site::getUid();
  2049. $now = date('Y-m-d H:i:s');
  2050. // 使用AI反推图片提示词
  2051. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2052. // 保存对话记录
  2053. $records = [
  2054. [
  2055. 'uid' => $uid,
  2056. 'anime_id' => $anime_id,
  2057. 'sequence' => $episode_number,
  2058. 'role' => 'user',
  2059. 'content' => '重新生成',
  2060. 'segment_id' => $segment_id,
  2061. 'pic_task_id' => $task_id,
  2062. 'image_url' => '',
  2063. 'created_at' => $now,
  2064. 'updated_at' => $now
  2065. ],
  2066. [
  2067. 'uid' => $uid,
  2068. 'anime_id' => $anime_id,
  2069. 'sequence' => $episode_number,
  2070. 'role' => 'assistant',
  2071. 'content' => $pic_prompt,
  2072. 'segment_id' => $segment_id,
  2073. 'pic_task_id' => $task_id,
  2074. 'image_url' => $img_url,
  2075. 'created_at' => $now,
  2076. 'updated_at' => $now
  2077. ]
  2078. ];
  2079. DB::table('mp_anime_records')->insert($records);
  2080. } catch (\Exception $e) {
  2081. // 记录日志但不影响主流程
  2082. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2083. 'segment_id' => $segment_id,
  2084. 'img_url' => $img_url
  2085. ]);
  2086. }
  2087. return $img_url;
  2088. }
  2089. public function addSegment($data) {
  2090. $prev_segment_id = getProp($data, 'prev_segment_id');
  2091. $img_url = getProp($data, 'img_url');
  2092. $video_url = getProp($data, 'video_url');
  2093. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2094. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2095. $anime_id = getProp($segment, 'anime_id');
  2096. $episode_id = getProp($segment, 'episode_id');
  2097. $episode_number = getProp($segment, 'episode_number');
  2098. $segment_number = getProp($segment, 'segment_number');
  2099. $new_segment_number = $segment_number + 1;
  2100. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2101. // 分镜剧本数组
  2102. $insert_data = [
  2103. 'anime_id' => $anime_id,
  2104. 'episode_id' => $episode_id,
  2105. 'episode_number' => $episode_number,
  2106. 'act_number' => getProp($segment, 'act_number'),
  2107. 'act_title' => getProp($segment, 'act_title'),
  2108. 'segment_id' => $segment_id,
  2109. 'segment_number' => $new_segment_number,
  2110. 'segment_content' => '',
  2111. 'img_url' => '',
  2112. 'video_url' => '',
  2113. 'created_at' => date('Y-m-d H:i:s'),
  2114. 'updated_at' => date('Y-m-d H:i:s')
  2115. ];
  2116. if ($img_url) $insert_data['img_url'] = $img_url;
  2117. if ($video_url) {
  2118. $insert_data['origin_video_url'] = $video_url;
  2119. $insert_data['current_type'] = 2;
  2120. $compressed_video_url = compressVideo($video_url);
  2121. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2122. }
  2123. try {
  2124. DB::beginTransaction();
  2125. // 先更新序号
  2126. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2127. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2128. if (!$id) {
  2129. Utils::throwError('20003:新增分镜失败!');
  2130. }
  2131. }catch (\Exception $e) {
  2132. DB::rollBack();
  2133. Utils::throwError('20003:'.$e->getMessage());
  2134. }
  2135. DB::commit();
  2136. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2137. $segment = $segment ? (array)$segment : [];
  2138. return $segment;
  2139. // 以下代码暂弃用
  2140. $anime_id = getProp($segment, 'anime_id');
  2141. $episode_id = getProp($segment, 'episode_id');
  2142. $episode_number = getProp($segment, 'episode_number');
  2143. $segment_number = getProp($segment, 'segment_number');
  2144. $segment_content = getProp($data, 'segment_content');
  2145. $img_url = getProp($data, 'img_url');
  2146. $video_url = getProp($data, 'video_url');
  2147. $ratio = getProp($data, 'ratio');
  2148. $dimensions = $this->getRatioDimensions($ratio);
  2149. $width = $dimensions['width'];
  2150. $height = $dimensions['height'];
  2151. if (!$anime_id || !$episode_id) {
  2152. Utils::throwError('1002:请选择分镜');
  2153. }
  2154. // 使用文生文模型重新解析segment_content
  2155. if (!empty($segment_content)) {
  2156. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2157. }
  2158. // 获取动漫的角色信息(包含参考图)
  2159. $anime = DB::table('mp_animes')
  2160. ->where('id', $anime_id)
  2161. ->select('roles', 'scenes')
  2162. ->first();
  2163. if (!$anime || !$anime->roles) {
  2164. Utils::throwError('20003:未找到角色信息');
  2165. }
  2166. $roles = json_decode($anime->roles, true);
  2167. if (!$roles) {
  2168. Utils::throwError('20003:角色信息格式错误');
  2169. }
  2170. // 构建角色名称到参考图的映射
  2171. $role_map = [];
  2172. foreach ($roles as $role) {
  2173. $role_name = getProp($role, 'role');
  2174. $role_url = getProp($role, 'url');
  2175. if (!empty($role_name) && !empty($role_url)) {
  2176. $role_map[$role_name] = $role_url;
  2177. }
  2178. }
  2179. $scenes = json_decode($anime->scenes, true);
  2180. if (!$scenes) {
  2181. Utils::throwError('20003:角色信息格式错误');
  2182. }
  2183. // 构建角色名称到参考图的映射
  2184. $scene_map = [];
  2185. foreach ($scenes as $scene) {
  2186. $scene_name = getProp($scene, 'scene');
  2187. $scene_url = getProp($scene, 'url');
  2188. if (!empty($scene_name) && !empty($scene_url)) {
  2189. $scene_map[$scene_name] = $scene_url;
  2190. }
  2191. }
  2192. $segment_id = $segment->segment_id;
  2193. $original_segment_content = $segment->segment_content;
  2194. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2195. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2196. if (empty($final_segment_content)) {
  2197. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2198. }
  2199. try {
  2200. $dubTaskId = 0;
  2201. DB::beginTransaction();
  2202. $new_segment_number = $segment_number + 1;
  2203. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2204. // 分镜剧本数组
  2205. $insert_data = [
  2206. 'anime_id' => $anime_id,
  2207. 'episode_id' => $episode_id,
  2208. 'episode_number' => $episode_number,
  2209. 'act_number' => getProp($segment, 'act_number'),
  2210. 'act_title' => getProp($segment, 'act_title'),
  2211. 'segment_id' => $segment_id,
  2212. 'segment_number' => $new_segment_number,
  2213. 'segment_content' => $final_segment_content,
  2214. 'img_url' => $img_url,
  2215. 'video_url' => $video_url,
  2216. 'created_at' => date('Y-m-d H:i:s'),
  2217. 'updated_at' => date('Y-m-d H:i:s')
  2218. ];
  2219. // 更新分镜剧本信息
  2220. $this->handleSegmentContent($insert_data);
  2221. // 如果有对话内容,创建视频配音合成任务
  2222. $dialogue = getProp($insert_data, 'dialogue');
  2223. if (!empty($dialogue)) {
  2224. $now = date('Y-m-d H:i:s');
  2225. $generate_json = [
  2226. 'text' => $dialogue,
  2227. 'role' => getProp($insert_data, 'voice_actor'),
  2228. 'voice_type' => getProp($insert_data, 'voice_type'),
  2229. 'voice_name' => getProp($insert_data, 'voice_name'),
  2230. 'emotion' => getProp($insert_data, 'emotion'),
  2231. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2232. 'gender' => getProp($insert_data, 'gender'),
  2233. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2234. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2235. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2236. 'pitch' => getProp($insert_data, 'pitch', 0),
  2237. ];
  2238. // 插入视频配音合成任务
  2239. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2240. 'alias_segment_id' => $segment_id,
  2241. 'generate_status' => '执行中',
  2242. 'audio_url' => '',
  2243. 'generate_json' => json_encode($generate_json, 256),
  2244. 'created_at' => $now,
  2245. 'updated_at' => $now,
  2246. ]);
  2247. if (!$dubTaskId) {
  2248. Utils::throwError('20003:创建配音任务失败!');
  2249. }
  2250. $insert_data['audio_url'] = '';
  2251. } else {
  2252. // dialogue为空时,直接写入默认音频信息
  2253. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2254. $insert_data['audio_duration'] = 2.0;
  2255. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2256. }
  2257. // 如果没有上传图片则使用当前描述进行生成
  2258. if (!$img_url) {
  2259. // 解析分镜内容,提取画面描述作为主要提示词
  2260. $prompt = $final_segment_content;
  2261. $ref_img_urls = [];
  2262. // 分镜场景
  2263. $scene = getProp($insert_data, 'scene');
  2264. if ($scene) {
  2265. $matched_scene = '';
  2266. if (isset($scene_map[$scene])) {
  2267. $img_index = count($ref_img_urls) + 1;
  2268. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2269. $ref_img_urls[] = $scene_map[$scene];
  2270. $matched_scene = $scene;
  2271. }
  2272. $update_data['scene'] = $scene;
  2273. }
  2274. // 分镜角色
  2275. $characters = getProp($insert_data, 'characters');
  2276. if ($characters) {
  2277. $update_data['characters'] = $characters;
  2278. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2279. $characters = explode(',', $characters);
  2280. // 从分镜内容中提取涉及的角色
  2281. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2282. // 获取匹配角色的参考图
  2283. foreach ($segment_characters as $character) {
  2284. if (isset($role_map[$character])) {
  2285. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2286. $img_index = count($ref_img_urls) + 1;
  2287. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2288. $ref_img_urls[] = $role_map[$character];
  2289. }
  2290. }
  2291. }
  2292. // 如果没有找到匹配的角色参考图,不使用参考图
  2293. if (empty($ref_img_urls)) {
  2294. $ref_img_urls = [];
  2295. }
  2296. // 准备生成任务参数
  2297. $params = [
  2298. 'alias_segment_id' => $segment_id,
  2299. 'prompt' => $prompt,
  2300. 'ref_img_urls' => $ref_img_urls,
  2301. 'width' => $width,
  2302. 'height' => $height,
  2303. ];
  2304. // 调用AI图片生成服务
  2305. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2306. $task_id = $task->id;
  2307. // $task_id = 'whatever';
  2308. if (!$task_id) {
  2309. Utils::throwError('20003:创建生成任务失败!');
  2310. }
  2311. $insert_data['pic_task_status'] = '生成中';
  2312. $insert_data['pic_task_id'] = $task_id;
  2313. }
  2314. // 先更新序号
  2315. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2316. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2317. if (!$boolen) {
  2318. Utils::throwError('20003:新增分镜失败!');
  2319. }
  2320. // 如果是第一集的首帧图片,则存入待更新数组
  2321. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2322. Redis::sadd('anime_first_frame_urls', $segment_id);
  2323. }
  2324. if ($dubTaskId) {
  2325. // 请求远程服务器执行生成
  2326. $client = new Client(['timeout' => 300, 'verify' => false]);
  2327. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2328. $response = $result->getBody()->getContents();
  2329. $response_arr = json_decode($response, true);
  2330. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2331. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2332. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2333. Utils::throwError('20003:火山生成音频失败');
  2334. }
  2335. }
  2336. } catch (\Exception $e) {
  2337. DB::rollBack();
  2338. Utils::throwError('20003:'.$e->getMessage());
  2339. }
  2340. DB::commit();
  2341. // 创建任务之后先暂停10s等待异步任务完成
  2342. sleep(10);
  2343. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2344. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2345. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2346. $segment = $segment ? (array)$segment : [];
  2347. return $segment;
  2348. }
  2349. public function copySegment($data) {
  2350. $segment_id = getProp($data, 'segment_id');
  2351. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2352. if (!$segment) Utils::throwError('20003:请选择分镜');
  2353. $anime_id = getProp($segment, 'anime_id');
  2354. $episode_id = getProp($segment, 'episode_id');
  2355. $episode_number = getProp($segment, 'episode_number');
  2356. $segment_number = getProp($segment, 'segment_number');
  2357. $new_segment_id = 0;
  2358. try {
  2359. DB::beginTransaction();
  2360. $segment = (array)$segment;
  2361. unset($segment['id']);
  2362. $segment['segment_number'] += 1;
  2363. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2364. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2365. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2366. // 更新其他分镜序号
  2367. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2368. // 复制分镜
  2369. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2370. if (!$id) {
  2371. Utils::throwError('20003:复制分镜失败');
  2372. }
  2373. }catch (\Exception $e) {
  2374. DB::rollBack();
  2375. Utils::throwError('20003:'.$e->getMessage());
  2376. }
  2377. DB::commit();
  2378. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2379. $segment = $segment ? (array)$segment : [];
  2380. return $segment;
  2381. }
  2382. public function moveSegment($data) {
  2383. $segment_id = getProp($data, 'segment_id');
  2384. $target_segment_id = getProp($data, 'target_segment_id');
  2385. // 获取源分镜信息
  2386. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2387. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2388. // 获取目标分镜信息
  2389. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2390. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2391. $anime_id = getProp($source_segment, 'anime_id');
  2392. $episode_id = getProp($source_segment, 'episode_id');
  2393. $episode_number = getProp($source_segment, 'episode_number');
  2394. $source_segment_number = getProp($source_segment, 'segment_number');
  2395. $target_segment_number = getProp($target_segment, 'segment_number');
  2396. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2397. $target_anime_id = getProp($target_segment, 'anime_id');
  2398. $target_episode_number = getProp($target_segment, 'episode_number');
  2399. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2400. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2401. }
  2402. // 如果源分镜和目标分镜相同,无需移动
  2403. if ($source_segment_number == $target_segment_number) {
  2404. return true;
  2405. }
  2406. try {
  2407. DB::beginTransaction();
  2408. if ($source_segment_number < $target_segment_number) {
  2409. // 向后移动:源分镜移动到目标分镜之后
  2410. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2411. DB::table('mp_episode_segments')
  2412. ->where('anime_id', $anime_id)
  2413. ->where('episode_id', $episode_id)
  2414. ->where('segment_number', '>', $source_segment_number)
  2415. ->where('segment_number', '<=', $target_segment_number)
  2416. ->decrement('segment_number');
  2417. // 2. 将源分镜移动到目标分镜之后
  2418. $new_segment_number = $target_segment_number;
  2419. } else {
  2420. // 向前移动:源分镜移动到目标分镜之后
  2421. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2422. DB::table('mp_episode_segments')
  2423. ->where('anime_id', $anime_id)
  2424. ->where('episode_id', $episode_id)
  2425. ->where('segment_number', '>', $target_segment_number)
  2426. ->where('segment_number', '<', $source_segment_number)
  2427. ->increment('segment_number');
  2428. // 2. 将源分镜移动到目标分镜之后
  2429. $new_segment_number = $target_segment_number + 1;
  2430. }
  2431. // 3. 更新源分镜的序号
  2432. $update_result = DB::table('mp_episode_segments')
  2433. ->where('segment_id', $segment_id)
  2434. ->update([
  2435. 'segment_number' => $new_segment_number,
  2436. 'updated_at' => date('Y-m-d H:i:s')
  2437. ]);
  2438. if (!$update_result) {
  2439. Utils::throwError('20003:更新分镜序号失败');
  2440. }
  2441. DB::commit();
  2442. return true;
  2443. } catch (\Exception $e) {
  2444. DB::rollBack();
  2445. Utils::throwError('20003:' . $e->getMessage());
  2446. }
  2447. }
  2448. public function delSegment($data) {
  2449. $segment_id = getProp($data, 'segment_id');
  2450. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2451. if (!$segment) Utils::throwError('20003:请选择分镜');
  2452. $anime_id = getProp($segment, 'anime_id');
  2453. $episode_id = getProp($segment, 'episode_id');
  2454. $episode_number = getProp($segment, 'episode_number');
  2455. $segment_number = getProp($segment, 'segment_number');
  2456. try {
  2457. DB::beginTransaction();
  2458. // 删除分镜
  2459. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2460. if (!$boolen) {
  2461. Utils::throwError('20003:删除分镜失败');
  2462. }
  2463. // 更新其他分镜序号
  2464. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2465. }catch (\Exception $e) {
  2466. DB::rollBack();
  2467. Utils::throwError('20003:'.$e->getMessage());
  2468. }
  2469. DB::commit();
  2470. return true;
  2471. }
  2472. public function applySegment($data) {
  2473. $segment_id = getProp($data, 'segment_id');
  2474. $url = getProp($data, 'url');
  2475. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2476. if (!$url) Utils::throwError('20003:URL不能为空');
  2477. // 获取URL的文件扩展名
  2478. $urlPath = parse_url($url, PHP_URL_PATH);
  2479. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2480. // 定义图片和视频的扩展名
  2481. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2482. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2483. // 判断是图片还是视频
  2484. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2485. if (in_array($extension, $imageExtensions)) {
  2486. // 图片类型
  2487. $updateData['img_url'] = $url;
  2488. $updateData['current_type'] = 1;
  2489. } elseif (in_array($extension, $videoExtensions)) {
  2490. // 视频类型
  2491. $updateData['video_url'] = $url;
  2492. $updateData['current_type'] = 2;
  2493. } else {
  2494. Utils::throwError('20003:不支持的文件类型');
  2495. }
  2496. // 更新分镜表
  2497. $result = DB::table('mp_episode_segments')
  2498. ->where('segment_id', $segment_id)
  2499. ->update($updateData);
  2500. if (!$result) {
  2501. Utils::throwError('20003:更新分镜失败');
  2502. }
  2503. return true;
  2504. }
  2505. public function segmentHistory($data) {
  2506. $segment_id = getProp($data, 'segment_id');
  2507. // 获取历史图片
  2508. $pics = [];
  2509. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2510. foreach($pic_history as $task) {
  2511. $result_url = getProp($task, 'result_url');
  2512. if (is_json($result_url)) {
  2513. $pics = array_merge($pics, json_decode($result_url, true));
  2514. }else {
  2515. $pics[] = $result_url;
  2516. }
  2517. }
  2518. // 获取历史视频
  2519. $videos = [];
  2520. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2521. foreach($video_history as $task) {
  2522. $result_url = getProp($task, 'result_url');
  2523. if (is_json($result_url)) {
  2524. $videos = array_merge($videos, json_decode($result_url, true));
  2525. }else {
  2526. $videos[] = $result_url;
  2527. }
  2528. }
  2529. return compact('pics', 'videos');
  2530. }
  2531. public function addAct($data) {
  2532. $prev_act_id = getProp($data, 'prev_act_id');
  2533. $act_title = getProp($data, 'act_title', '');
  2534. $act_content = getProp($data, 'act_content', '');
  2535. $act_duration = getProp($data, 'act_duration', 5);
  2536. $video_url = getProp($data, 'video_url');
  2537. // 根据prev_act_id获取记录
  2538. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2539. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2540. $anime_id = getProp($prev_segment, 'anime_id');
  2541. $episode_id = getProp($prev_segment, 'episode_id');
  2542. $episode_number = getProp($prev_segment, 'episode_number');
  2543. $prev_act_number = getProp($prev_segment, 'act_number');
  2544. // 获取新的act_number
  2545. $new_act_number = $prev_act_number + 1;
  2546. try {
  2547. DB::beginTransaction();
  2548. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2549. DB::table('mp_episode_segments')
  2550. ->where('anime_id', $anime_id)
  2551. ->where('episode_id', $episode_id)
  2552. ->where('act_number', '>', $prev_act_number)
  2553. ->increment('act_number');
  2554. // 插入新片段记录
  2555. $insert_data = [
  2556. 'anime_id' => $anime_id,
  2557. 'episode_id' => $episode_id,
  2558. 'episode_number' => $episode_number,
  2559. 'act_number' => $new_act_number,
  2560. 'created_at' => date('Y-m-d H:i:s'),
  2561. 'updated_at' => date('Y-m-d H:i:s')
  2562. ];
  2563. if ($act_title) {
  2564. $insert_data['act_title'] = $act_title;
  2565. }
  2566. if ($act_content) {
  2567. $insert_data['act_content'] = $act_content;
  2568. }
  2569. if ($act_duration) {
  2570. $insert_data['act_duration'] = $act_duration;
  2571. }
  2572. if ($video_url) {
  2573. $insert_data['origin_video_url'] = $video_url;
  2574. $insert_data['current_type'] = 2;
  2575. $compressed_video_url = compressVideo($video_url);
  2576. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2577. }
  2578. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2579. if (!$id) {
  2580. Utils::throwError('20003:新增片段失败!');
  2581. }
  2582. DB::commit();
  2583. }catch (\Exception $e) {
  2584. DB::rollBack();
  2585. Utils::throwError('20003:'.$e->getMessage());
  2586. }
  2587. $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();
  2588. $segment = $segment ? (array)$segment : [];
  2589. return $segment;
  2590. }
  2591. public function editAct($data) {
  2592. $act_id = getProp($data, 'act_id');
  2593. $act_content = getProp($data, 'act_content');
  2594. $act_duration = getProp($data, 'act_duration');
  2595. $act_title = getProp($data, 'act_title');
  2596. $image_url = getProp($data, 'image_url');
  2597. $video_url = getProp($data, 'video_url');
  2598. // 参数验证
  2599. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2600. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2601. $segment = DB::table('mp_episode_segments')
  2602. ->where('id', $act_id)
  2603. ->first();
  2604. if (!$segment) Utils::throwError('20003:该片段不存在');
  2605. try {
  2606. DB::beginTransaction();
  2607. // 准备更新数据
  2608. $update_data = [
  2609. 'updated_at' => date('Y-m-d H:i:s')
  2610. ];
  2611. // 更新act相关字段
  2612. if (!empty($act_content)) {
  2613. $update_data['act_show_content'] = $act_content;
  2614. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2615. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2616. $shot_counter = 0;
  2617. $update_data['act_show_content'] = preg_replace_callback(
  2618. '/【(?:镜头|分镜)(\d+)】/u',
  2619. function($matches) use (&$shot_counter) {
  2620. $shot_counter++;
  2621. return '【镜头' . $shot_counter . '】';
  2622. },
  2623. $update_data['act_show_content']
  2624. );
  2625. }
  2626. if (!empty($act_duration)) {
  2627. $update_data['act_duration'] = $act_duration;
  2628. }
  2629. if (!empty($act_title)) {
  2630. $update_data['act_title'] = $act_title;
  2631. }
  2632. // 处理图片上传
  2633. if ($image_url) {
  2634. $update_data['img_url'] = $image_url;
  2635. $update_data['current_type'] = 1;
  2636. // 同时写入一个图片生成任务记录
  2637. if ($act_id) {
  2638. $pic_task = [
  2639. 'alias_act_id' => $act_id,
  2640. 'ref_img_url' => json_encode([]),
  2641. 'status' => 'success',
  2642. 'result_url' => json_encode([$image_url], 256),
  2643. 'model' => '',
  2644. 'created_at' => date('Y-m-d H:i:s'),
  2645. 'updated_at' => date('Y-m-d H:i:s'),
  2646. ];
  2647. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2648. }
  2649. }
  2650. // 处理视频上传
  2651. if ($video_url) {
  2652. $update_data['origin_video_url'] = $video_url;
  2653. $compressed_video_url = compressVideo($video_url);
  2654. $update_data['current_type'] = 2;
  2655. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2656. // 同时写入一个视频生成任务记录
  2657. if ($act_id) {
  2658. $video_task = [
  2659. 'alias_act_id' => $act_id,
  2660. 'status' => 'success',
  2661. 'result_url' => $update_data['origin_video_url'],
  2662. 'compressed_url' => $update_data['video_url'],
  2663. 'created_at' => date('Y-m-d H:i:s'),
  2664. 'updated_at' => date('Y-m-d H:i:s'),
  2665. ];
  2666. DB::table('mp_generate_video_tasks')->insert($video_task);
  2667. }
  2668. }
  2669. // 更新片段信息
  2670. $result = DB::table('mp_episode_segments')
  2671. ->where('id', $act_id)
  2672. ->update($update_data);
  2673. if ($result === false) {
  2674. Utils::throwError('20003:更新片段失败');
  2675. }
  2676. DB::commit();
  2677. // 返回新复制的记录
  2678. $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();
  2679. $new_segment = (array)$new_segment;
  2680. return $new_segment;
  2681. } catch (\Exception $e) {
  2682. DB::rollBack();
  2683. dLog('anime')->error('更新片段失败', [
  2684. 'act_id' => $act_id,
  2685. 'error' => $e->getMessage()
  2686. ]);
  2687. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2688. }
  2689. }
  2690. public function copyAct($data) {
  2691. $act_id = getProp($data, 'act_id');
  2692. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2693. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2694. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2695. $anime_id = getProp($source_segment, 'anime_id');
  2696. $episode_id = getProp($source_segment, 'episode_id');
  2697. $episode_number = getProp($source_segment, 'episode_number');
  2698. $act_number = getProp($source_segment, 'act_number');
  2699. try {
  2700. DB::beginTransaction();
  2701. // 新act的编号
  2702. $new_act_number = $act_number + 1;
  2703. // 更新后续所有act的act_number
  2704. DB::table('mp_episode_segments')
  2705. ->where('anime_id', $anime_id)
  2706. ->where('episode_id', $episode_id)
  2707. ->where('act_number', '>', $act_number)
  2708. ->increment('act_number');
  2709. // 复制该片段记录
  2710. $segment_data = (array)$source_segment;
  2711. unset($segment_data['id']);
  2712. $segment_data['video_url'] = '';
  2713. $segment_data['video_task_id'] = '';
  2714. $segment_data['video_task_status'] = '';
  2715. $segment_data['act_number'] = $new_act_number;
  2716. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2717. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2718. if (!$id) {
  2719. Utils::throwError('20003:复制片段失败');
  2720. }
  2721. DB::commit();
  2722. }catch (\Exception $e) {
  2723. DB::rollBack();
  2724. Utils::throwError('20003:'.$e->getMessage());
  2725. }
  2726. // 返回新复制的记录
  2727. $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();
  2728. $new_segment = $new_segment ? (array)$new_segment : [];
  2729. $new_segment['act_id'] = $id;
  2730. return $new_segment;
  2731. }
  2732. public function moveAct($data) {
  2733. $act_id = getProp($data, 'act_id');
  2734. $target_act_id = getProp($data, 'target_act_id');
  2735. // 获取源片段信息
  2736. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2737. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2738. // 获取目标片段信息
  2739. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2740. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2741. $anime_id = getProp($source_segment, 'anime_id');
  2742. $episode_id = getProp($source_segment, 'episode_id');
  2743. $source_act_number = getProp($source_segment, 'act_number');
  2744. $target_act_number = getProp($target_segment, 'act_number');
  2745. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2746. $target_anime_id = getProp($target_segment, 'anime_id');
  2747. $target_episode_id = getProp($target_segment, 'episode_id');
  2748. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2749. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2750. }
  2751. // 如果源片段和目标片段相同,无需移动
  2752. if ($source_act_number == $target_act_number) {
  2753. return true;
  2754. }
  2755. try {
  2756. DB::beginTransaction();
  2757. if ($source_act_number < $target_act_number) {
  2758. // 向后移动:源片段移动到目标片段之后
  2759. // 1. 将源片段和目标片段之间的所有片段编号减1
  2760. DB::table('mp_episode_segments')
  2761. ->where('anime_id', $anime_id)
  2762. ->where('episode_id', $episode_id)
  2763. ->where('act_number', '>', $source_act_number)
  2764. ->where('act_number', '<=', $target_act_number)
  2765. ->decrement('act_number');
  2766. // 2. 将源片段移动到目标片段之后
  2767. $new_act_number = $target_act_number;
  2768. } else {
  2769. // 向前移动:源片段移动到目标片段之后
  2770. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2771. DB::table('mp_episode_segments')
  2772. ->where('anime_id', $anime_id)
  2773. ->where('episode_id', $episode_id)
  2774. ->where('act_number', '>', $target_act_number)
  2775. ->where('act_number', '<', $source_act_number)
  2776. ->increment('act_number');
  2777. // 2. 将源片段移动到目标片段之后
  2778. $new_act_number = $target_act_number + 1;
  2779. }
  2780. // 3. 更新源片段的编号
  2781. $update_result = DB::table('mp_episode_segments')
  2782. ->where('id', $act_id)
  2783. ->update([
  2784. 'act_number' => $new_act_number,
  2785. 'updated_at' => date('Y-m-d H:i:s')
  2786. ]);
  2787. if (!$update_result) {
  2788. Utils::throwError('20003:更新片段编号失败');
  2789. }
  2790. DB::commit();
  2791. return true;
  2792. } catch (\Exception $e) {
  2793. DB::rollBack();
  2794. Utils::throwError('20003:' . $e->getMessage());
  2795. }
  2796. }
  2797. public function delAct($data) {
  2798. $act_id = getProp($data, 'act_id');
  2799. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2800. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2801. if (!$segment) Utils::throwError('20003:请选择片段');
  2802. $anime_id = getProp($segment, 'anime_id');
  2803. $episode_id = getProp($segment, 'episode_id');
  2804. $act_number = getProp($segment, 'act_number');
  2805. try {
  2806. DB::beginTransaction();
  2807. // 删除该片段记录
  2808. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2809. if (!$deleted) {
  2810. Utils::throwError('20003:删除片段失败');
  2811. }
  2812. // 更新后续act的编号
  2813. DB::table('mp_episode_segments')
  2814. ->where('anime_id', $anime_id)
  2815. ->where('episode_id', $episode_id)
  2816. ->where('act_number', '>', $act_number)
  2817. ->decrement('act_number');
  2818. DB::commit();
  2819. }catch (\Exception $e) {
  2820. DB::rollBack();
  2821. Utils::throwError('20003:'.$e->getMessage());
  2822. }
  2823. return true;
  2824. }
  2825. public function applyAct($data) {
  2826. $act_id = getProp($data, 'act_id');
  2827. $url = getProp($data, 'url');
  2828. if (!$act_id) Utils::throwError('20003:请选择片段');
  2829. if (!$url) Utils::throwError('20003:URL不能为空');
  2830. // 获取URL的文件扩展名
  2831. $urlPath = parse_url($url, PHP_URL_PATH);
  2832. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2833. // 定义图片和视频的扩展名
  2834. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2835. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2836. // 判断是图片还是视频
  2837. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2838. if (in_array($extension, $imageExtensions)) {
  2839. // 图片类型
  2840. $updateData['img_url'] = $url;
  2841. $updateData['current_type'] = 1;
  2842. } elseif (in_array($extension, $videoExtensions)) {
  2843. // 视频类型
  2844. $updateData['video_url'] = $url;
  2845. $updateData['current_type'] = 2;
  2846. } else {
  2847. Utils::throwError('20003:不支持的文件类型');
  2848. }
  2849. // 更新片段记录(全能模式下每个act只有一条记录)
  2850. $result = DB::table('mp_episode_segments')
  2851. ->where('id', $act_id)
  2852. ->update($updateData);
  2853. if (!$result) {
  2854. Utils::throwError('20003:更新片段失败');
  2855. }
  2856. return true;
  2857. }
  2858. public function actChatHistory($data) {
  2859. $act_id = getProp($data, 'act_id');
  2860. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2861. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'reference_images', 'created_at');
  2862. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2863. $value = (array)$value;
  2864. $value['created_at'] = transDate($value['created_at']);
  2865. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2866. else $value['reference_images'] = [];
  2867. return $value;
  2868. })->toArray();
  2869. // 获取历史图片
  2870. $url = [];
  2871. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2872. foreach($pic_history as $task) {
  2873. $result_url = getProp($task, 'result_url');
  2874. if (is_json($result_url)) {
  2875. $url = array_merge($url, json_decode($result_url, true));
  2876. }else {
  2877. $url[] = $result_url;
  2878. }
  2879. }
  2880. // 获取历史视频
  2881. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2882. foreach($video_history as $task) {
  2883. $result_url = getProp($task, 'result_url');
  2884. if (is_json($result_url)) {
  2885. $url = array_merge($url, json_decode($result_url, true));
  2886. }else {
  2887. $url[] = $result_url;
  2888. }
  2889. }
  2890. // 获取资产库
  2891. $products = [];
  2892. // 通过act_id查询片段信息获取episode_id
  2893. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2894. if ($segment) {
  2895. $episode_id = getProp($segment, 'episode_id');
  2896. // 查询剧集信息获取roles、scenes和extra_products
  2897. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2898. if ($episode) {
  2899. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2900. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2901. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2902. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2903. // 先合并roles、scenes和props
  2904. // 处理角色数组
  2905. foreach ($roles as $role) {
  2906. $product = $role;
  2907. // 将role字段重命名为product_name
  2908. if (is_array($product) && !empty($product['role'] ?? null)) {
  2909. $product['product_name'] = $product['role'];
  2910. unset($product['role']);
  2911. $product['product'] = 1; // 标记类型为角色
  2912. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2913. }
  2914. }
  2915. // 处理场景数组
  2916. foreach ($scenes as $scene) {
  2917. $product = $scene;
  2918. // 将scene字段重命名为product_name
  2919. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2920. $product['product_name'] = $product['scene'];
  2921. unset($product['scene']);
  2922. $product['product'] = 2; // 标记类型为场景
  2923. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2924. }
  2925. }
  2926. // 处理道具数组
  2927. foreach ($props as $prop) {
  2928. $product = $prop;
  2929. // 将prop字段重命名为product_name
  2930. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2931. $product['product_name'] = $product['prop'];
  2932. unset($product['prop']);
  2933. $product['product'] = 3; // 标记类型为道具
  2934. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2935. }
  2936. }
  2937. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2938. foreach ($extra_products as $extra_product) {
  2939. $product_name = getProp($extra_product, 'product_name');
  2940. if ($product_name) {
  2941. $products[$product_name] = $extra_product; // 覆盖同名数据
  2942. }
  2943. }
  2944. // 重新索引数组(去除key)
  2945. $products = array_values($products);
  2946. }
  2947. }
  2948. // 获取执行中的任务
  2949. $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) {
  2950. $value = (array)$value;
  2951. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2952. else $value['ref_image_url'] = [];
  2953. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2954. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2955. if (!empty($value['prompt'])) {
  2956. $prompt = $value['prompt'];
  2957. // 查找第一个【镜头】的位置
  2958. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2959. // 从【镜头】开始截取
  2960. $prompt = substr($prompt, $matches[0][1]);
  2961. }
  2962. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2963. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2964. $value['prompt'] = $prompt;
  2965. }
  2966. return $value;
  2967. })->toArray();
  2968. return compact('chat', 'url', 'products', 'tasks');
  2969. }
  2970. public function applyAudioData($data) {
  2971. $segment_id = getProp($data, 'segment_id');
  2972. $global_data = getProp($data, 'global_data');
  2973. $segment_data = getProp($data, 'segment_data');
  2974. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2975. $global_data = is_array($global_data) ? $global_data : [];
  2976. $segment_data = is_array($segment_data) ? $segment_data : [];
  2977. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2978. $dialogue_item = null;
  2979. foreach ($global_data as $key => $item) {
  2980. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2981. $dialogue_item = $item;
  2982. unset($global_data[$key]);
  2983. break;
  2984. }
  2985. }
  2986. if ($dialogue_item) {
  2987. $segment_data[] = $dialogue_item;
  2988. }
  2989. // 特殊参数: audio_url,audio_duration,subtitle_info
  2990. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2991. // 如果不是全部存在,则仍需创建音频任务
  2992. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2993. $special_update_data = [];
  2994. $has_all_special_params = false;
  2995. // 从segment_data中提取特殊参数
  2996. $filtered_segment_data = [];
  2997. foreach ($segment_data as $item) {
  2998. $field_name = trim((string)getProp($item, 'name'));
  2999. if (in_array($field_name, $special_fields)) {
  3000. $special_update_data[$field_name] = getProp($item, 'value');
  3001. } else {
  3002. // 非特殊参数保留,继续后续处理
  3003. $filtered_segment_data[] = $item;
  3004. }
  3005. }
  3006. // 检查是否三个特殊参数都存在
  3007. if (count($special_update_data) === 3 &&
  3008. isset($special_update_data['audio_url']) &&
  3009. isset($special_update_data['audio_duration']) &&
  3010. isset($special_update_data['subtitle_info'])) {
  3011. $has_all_special_params = true;
  3012. // 立即更新到当前分镜
  3013. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3014. DB::table('mp_episode_segments')
  3015. ->where('segment_id', $segment_id)
  3016. ->update($special_update_data);
  3017. }
  3018. // 使用过滤后的segment_data继续处理其他参数
  3019. $segment_data = $filtered_segment_data;
  3020. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3021. $global_update_data = [];
  3022. $segment_update_data = [];
  3023. $global_voice_type = '';
  3024. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3025. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3026. $episode_id = getProp($target_segment, 'episode_id');
  3027. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3028. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3029. if (!$episode) Utils::throwError('20003:分集不存在');
  3030. foreach ($global_data as $item) {
  3031. $field_name = trim((string)getProp($item, 'name'));
  3032. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3033. continue;
  3034. }
  3035. $global_update_data[$field_name] = getProp($item, 'value');
  3036. if ($field_name === 'voice_type') {
  3037. $global_voice_type = trim((string)getProp($item, 'value'));
  3038. }
  3039. }
  3040. foreach ($segment_data as $item) {
  3041. $field_name = trim((string)getProp($item, 'name'));
  3042. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3043. continue;
  3044. }
  3045. $segment_update_data[$field_name] = getProp($item, 'value');
  3046. }
  3047. if ($global_voice_type) {
  3048. $timbre_info = DB::table('mp_timbres')
  3049. ->where('timbre_type', $global_voice_type)
  3050. ->select('audio_url', 'timbre_name')
  3051. ->first();
  3052. if ($timbre_info) {
  3053. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3054. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3055. }
  3056. }
  3057. try {
  3058. DB::beginTransaction();
  3059. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3060. $segment_ids_to_create_task = [];
  3061. $segments_data = [];
  3062. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3063. if (!empty($global_update_data)) {
  3064. // 如果角色不存在,则只更新当前分镜
  3065. if (!$target_voice_actor) {
  3066. // 只处理当前分镜
  3067. $affected_segments = DB::table('mp_episode_segments')
  3068. ->where('segment_id', $segment_id)
  3069. ->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')
  3070. ->get();
  3071. } else {
  3072. // 获取该角色的所有分镜
  3073. $affected_segments = DB::table('mp_episode_segments')
  3074. ->where('episode_id', $episode_id)
  3075. ->where('voice_actor', $target_voice_actor)
  3076. ->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')
  3077. ->get();
  3078. }
  3079. foreach ($affected_segments as $seg) {
  3080. $seg = (array)$seg;
  3081. $sid = getProp($seg, 'segment_id');
  3082. // 检查参数是否发生变化
  3083. $has_changed = false;
  3084. foreach ($global_update_data as $field => $new_value) {
  3085. $old_value = getProp($seg, $field);
  3086. if ($old_value != $new_value) {
  3087. $has_changed = true;
  3088. break;
  3089. }
  3090. }
  3091. if ($has_changed) {
  3092. $segment_ids_to_create_task[] = $sid;
  3093. $segments_data[$sid] = $seg;
  3094. }
  3095. }
  3096. // 只有在有变化的分镜时才更新
  3097. if (!empty($segment_ids_to_create_task)) {
  3098. $global_segment_update_data = $global_update_data;
  3099. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3100. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3101. DB::table('mp_episode_segments')
  3102. ->where('episode_id', $episode_id)
  3103. ->where('voice_actor', $target_voice_actor)
  3104. ->whereIn('segment_id', $segment_ids_to_create_task)
  3105. ->update($global_segment_update_data);
  3106. }
  3107. if ($global_voice_type) {
  3108. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3109. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3110. $roles_updated = false;
  3111. foreach ($episode_roles as &$role) {
  3112. // 通过 role 字段匹配角色名,而不是 voice_name
  3113. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3114. continue;
  3115. }
  3116. $role['voice_type'] = $global_voice_type;
  3117. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3118. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3119. $roles_updated = true;
  3120. }
  3121. unset($role);
  3122. if ($roles_updated) {
  3123. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3124. 'roles' => json_encode($episode_roles, 256),
  3125. 'updated_at' => date('Y-m-d H:i:s'),
  3126. ]);
  3127. }
  3128. }
  3129. }
  3130. // 如果有单个分镜更新,检查是否有变化
  3131. if (!empty($segment_update_data)) {
  3132. // 获取当前分镜数据
  3133. $current_segment = DB::table('mp_episode_segments')
  3134. ->where('segment_id', $segment_id)
  3135. ->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')
  3136. ->first();
  3137. if ($current_segment) {
  3138. $current_segment = (array)$current_segment;
  3139. // 检查参数是否发生变化
  3140. $has_changed = false;
  3141. foreach ($segment_update_data as $field => $new_value) {
  3142. $old_value = getProp($current_segment, $field);
  3143. if ($old_value != $new_value) {
  3144. $has_changed = true;
  3145. break;
  3146. }
  3147. }
  3148. if ($has_changed) {
  3149. // 如果该分镜还未在列表中,添加进去
  3150. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3151. $segment_ids_to_create_task[] = $segment_id;
  3152. $segments_data[$segment_id] = $current_segment;
  3153. }
  3154. // 更新分镜数据并清空音频URL
  3155. $segment_update_data['audio_url'] = '';
  3156. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3157. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3158. }
  3159. }
  3160. }
  3161. // 为所有有变化的分镜创建音频合成任务
  3162. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3163. if (!empty($segment_ids_to_create_task)) {
  3164. foreach ($segment_ids_to_create_task as $sid) {
  3165. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3166. if ($sid === $segment_id && $has_all_special_params) {
  3167. continue;
  3168. }
  3169. // 重新获取更新后的分镜数据
  3170. $updated_segment = DB::table('mp_episode_segments')
  3171. ->where('segment_id', $sid)
  3172. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3173. ->first();
  3174. if (!$updated_segment) continue;
  3175. $updated_segment = (array)$updated_segment;
  3176. // 检查dialogue是否为空
  3177. $dialogue = getProp($updated_segment, 'dialogue');
  3178. if (empty($dialogue)) {
  3179. // dialogue为空时,直接写入默认音频信息
  3180. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3181. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3182. 'audio_duration' => 2.0,
  3183. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3184. 'updated_at' => date('Y-m-d H:i:s')
  3185. ]);
  3186. continue;
  3187. }
  3188. $generate_json = [
  3189. 'text' => $dialogue,
  3190. 'role' => getProp($updated_segment, 'voice_actor'),
  3191. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3192. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3193. 'emotion' => getProp($updated_segment, 'emotion'),
  3194. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3195. 'gender' => getProp($updated_segment, 'gender'),
  3196. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3197. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3198. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3199. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3200. ];
  3201. // 插入视频配音合成任务
  3202. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3203. 'alias_segment_id' => $sid,
  3204. 'generate_status' => '执行中',
  3205. 'audio_url' => '',
  3206. 'generate_json' => json_encode($generate_json, 256),
  3207. 'created_at' => date('Y-m-d H:i:s'),
  3208. 'updated_at' => date('Y-m-d H:i:s'),
  3209. ]);
  3210. if (!$dubTaskId) {
  3211. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3212. continue;
  3213. }
  3214. // 将任务ID添加到Redis列表中
  3215. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3216. // 请求远程服务器执行生成
  3217. try {
  3218. sleep(1);
  3219. $client = new Client(['timeout' => 300, 'verify' => false]);
  3220. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3221. $response = $result->getBody()->getContents();
  3222. $response_arr = json_decode($response, true);
  3223. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3224. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3225. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3226. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3227. }
  3228. } catch (\Exception $e) {
  3229. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3230. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3231. }
  3232. }
  3233. }
  3234. DB::commit();
  3235. } catch (\Exception $e) {
  3236. DB::rollBack();
  3237. Utils::throwError('20003:'.$e->getMessage());
  3238. }
  3239. return true;
  3240. }
  3241. public function episodePicsInfo($data) {
  3242. $anime_id = getProp($data, 'anime_id');
  3243. $episode_id = getProp($data, 'episode_id');
  3244. // 参数验证
  3245. if (!$anime_id && !$episode_id) {
  3246. Utils::throwError('20003:请提供动漫ID或分集ID');
  3247. }
  3248. // 根据参数获取数据源
  3249. if ($episode_id) {
  3250. // 从剧集表获取
  3251. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3252. if (!$source) Utils::throwError('20003:该剧集不存在');
  3253. $table_name = 'mp_anime_episodes';
  3254. $id_field = 'id';
  3255. $id_value = $episode_id;
  3256. // 获取剧集的anime_id用于继承全局数据
  3257. $anime_id = getProp($source, 'anime_id');
  3258. } else {
  3259. // 从动漫表获取
  3260. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3261. if (!$source) Utils::throwError('20003:该动漫不存在');
  3262. $table_name = 'mp_animes';
  3263. $id_field = 'id';
  3264. $id_value = $anime_id;
  3265. }
  3266. $source = (array)$source;
  3267. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3268. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3269. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3270. // 如果是分集数据,需要处理继承和任务创建逻辑
  3271. if ($episode_id) {
  3272. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3273. }
  3274. // 返回生成器函数,用于 SSE 流式输出
  3275. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3276. $startTime = time();
  3277. $maxDuration = 600; // 10分钟超时
  3278. $checkInterval = 3; // 每3秒检查一次
  3279. // Redis 缓存键
  3280. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3281. // 生成当前数据的哈希值用于比较
  3282. $generateHash = function($roles, $scenes, $props) {
  3283. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3284. };
  3285. // 发送初始数据
  3286. $currentHash = $generateHash($roles, $scenes, $props);
  3287. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3288. echo "data: " . json_encode([
  3289. 'type' => 'init',
  3290. 'data' => [
  3291. 'roles' => $roles,
  3292. 'scenes' => $scenes,
  3293. 'props' => $props,
  3294. 'start_time' => $startTime
  3295. ]
  3296. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3297. if (ob_get_level() > 0) {
  3298. ob_flush();
  3299. }
  3300. flush();
  3301. // 持续轮询任务状态
  3302. while (time() - $startTime < $maxDuration) {
  3303. $hasProcessing = false;
  3304. $updated = false;
  3305. // 检查角色任务状态
  3306. foreach ($roles as $index => &$role) {
  3307. $task_id = getProp($role, 'task_id');
  3308. $task_status = getProp($role, 'task_status');
  3309. $existing_url = getProp($role, 'url');
  3310. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3311. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3312. $hasProcessing = ($task_status === 'processing');
  3313. // 查询任务状态
  3314. $task = DB::table('mp_generate_pic_tasks')
  3315. ->where('id', $task_id)
  3316. ->select('id', 'status', 'result_url', 'error_message')
  3317. ->first();
  3318. if ($task) {
  3319. $task = (array)$task;
  3320. $status = getProp($task, 'status');
  3321. // 如果任务完成或失败
  3322. if (in_array($status, ['success', 'failed'])) {
  3323. $role['task_status'] = $status;
  3324. if ($status === 'success') {
  3325. $result_url = getProp($task, 'result_url');
  3326. if ($result_url) {
  3327. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3328. if (is_array($result_urls) && !empty($result_urls[0])) {
  3329. $role['url'] = $result_urls[0];
  3330. }
  3331. }
  3332. }
  3333. $updated = true;
  3334. } else if ($status === 'processing') {
  3335. $hasProcessing = true;
  3336. }
  3337. }
  3338. }
  3339. }
  3340. // 检查场景任务状态
  3341. foreach ($scenes as $index => &$scene) {
  3342. $task_id = getProp($scene, 'task_id');
  3343. $task_status = getProp($scene, 'task_status');
  3344. $existing_url = getProp($scene, 'url');
  3345. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3346. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3347. $hasProcessing = ($task_status === 'processing');
  3348. // 查询任务状态
  3349. $task = DB::table('mp_generate_pic_tasks')
  3350. ->where('id', $task_id)
  3351. ->select('id', 'status', 'result_url', 'error_message')
  3352. ->first();
  3353. if ($task) {
  3354. $task = (array)$task;
  3355. $status = getProp($task, 'status');
  3356. // 如果任务完成或失败
  3357. if (in_array($status, ['success', 'failed'])) {
  3358. $scene['task_status'] = $status;
  3359. if ($status === 'success') {
  3360. $result_url = getProp($task, 'result_url');
  3361. if ($result_url) {
  3362. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3363. if (is_array($result_urls) && !empty($result_urls[0])) {
  3364. $scene['url'] = $result_urls[0];
  3365. }
  3366. }
  3367. }
  3368. $updated = true;
  3369. } else if ($status === 'processing') {
  3370. $hasProcessing = true;
  3371. }
  3372. }
  3373. }
  3374. }
  3375. // 检查道具任务状态
  3376. foreach ($props as $index => &$prop) {
  3377. $task_id = getProp($prop, 'task_id');
  3378. $task_status = getProp($prop, 'task_status');
  3379. $existing_url = getProp($prop, 'url');
  3380. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3381. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3382. $hasProcessing = ($task_status === 'processing');
  3383. // 查询任务状态
  3384. $task = DB::table('mp_generate_pic_tasks')
  3385. ->where('id', $task_id)
  3386. ->select('id', 'status', 'result_url', 'error_message')
  3387. ->first();
  3388. if ($task) {
  3389. $task = (array)$task;
  3390. $status = getProp($task, 'status');
  3391. // 如果任务完成或失败
  3392. if (in_array($status, ['success', 'failed'])) {
  3393. $prop['task_status'] = $status;
  3394. if ($status === 'success') {
  3395. $result_url = getProp($task, 'result_url');
  3396. if ($result_url) {
  3397. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3398. if (is_array($result_urls) && !empty($result_urls[0])) {
  3399. $prop['url'] = $result_urls[0];
  3400. }
  3401. }
  3402. }
  3403. $updated = true;
  3404. } else if ($status === 'processing') {
  3405. $hasProcessing = true;
  3406. }
  3407. }
  3408. }
  3409. }
  3410. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3411. if ($updated) {
  3412. $newHash = $generateHash($roles, $scenes, $props);
  3413. $cachedHash = Redis::get($cacheKey);
  3414. // 只有当数据真正变化时才更新数据库和发送事件
  3415. if ($newHash !== $cachedHash) {
  3416. try {
  3417. // 更新数据库
  3418. DB::table($table_name)->where($id_field, $id_value)->update([
  3419. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3420. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3421. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3422. 'updated_at' => date('Y-m-d H:i:s')
  3423. ]);
  3424. // 更新缓存
  3425. Redis::setex($cacheKey, 600, $newHash);
  3426. // 发送更新事件
  3427. echo "data: " . json_encode([
  3428. 'type' => 'update',
  3429. 'data' => [
  3430. 'roles' => $roles,
  3431. 'scenes' => $scenes,
  3432. 'props' => $props,
  3433. 'elapsed_time' => time() - $startTime
  3434. ]
  3435. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3436. if (ob_get_level() > 0) {
  3437. ob_flush();
  3438. }
  3439. flush();
  3440. } catch (\Exception $e) {
  3441. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3442. }
  3443. } else {
  3444. // 即使哈希相同,如果有URL更新也要发送事件
  3445. $hasUrlUpdate = false;
  3446. foreach ($roles as $role) {
  3447. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3448. $hasUrlUpdate = true;
  3449. break;
  3450. }
  3451. }
  3452. if (!$hasUrlUpdate) {
  3453. foreach ($scenes as $scene) {
  3454. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3455. $hasUrlUpdate = true;
  3456. break;
  3457. }
  3458. }
  3459. }
  3460. if (!$hasUrlUpdate) {
  3461. foreach ($props as $prop) {
  3462. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3463. $hasUrlUpdate = true;
  3464. break;
  3465. }
  3466. }
  3467. }
  3468. if ($hasUrlUpdate) {
  3469. // 强制更新数据库和发送事件
  3470. try {
  3471. DB::table($table_name)->where($id_field, $id_value)->update([
  3472. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3473. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3474. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3475. 'updated_at' => date('Y-m-d H:i:s')
  3476. ]);
  3477. // 更新缓存
  3478. Redis::setex($cacheKey, 600, $newHash);
  3479. // 发送更新事件
  3480. echo "data: " . json_encode([
  3481. 'type' => 'update',
  3482. 'data' => [
  3483. 'roles' => $roles,
  3484. 'scenes' => $scenes,
  3485. 'props' => $props,
  3486. 'elapsed_time' => time() - $startTime
  3487. ]
  3488. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3489. if (ob_get_level() > 0) {
  3490. ob_flush();
  3491. }
  3492. flush();
  3493. } catch (\Exception $e) {
  3494. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3495. }
  3496. }
  3497. }
  3498. }
  3499. // 如果所有任务都已完成,发送完成事件并退出
  3500. if (!$hasProcessing) {
  3501. // 查询数据库中的最终数据,确保返回最新的完整数据
  3502. try {
  3503. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3504. if ($finalSource) {
  3505. $finalSource = (array)$finalSource;
  3506. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3507. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3508. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3509. // 使用数据库中的最终数据
  3510. $roles = $finalRoles;
  3511. $scenes = $finalScenes;
  3512. $props = $finalProps;
  3513. }
  3514. } catch (\Exception $e) {
  3515. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3516. // 如果查询失败,继续使用内存中的数据
  3517. }
  3518. // 清理缓存
  3519. Redis::del($cacheKey);
  3520. echo "data: " . json_encode([
  3521. 'type' => 'completed',
  3522. 'data' => [
  3523. 'roles' => $roles,
  3524. 'scenes' => $scenes,
  3525. 'props' => $props,
  3526. 'total_time' => time() - $startTime
  3527. ]
  3528. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3529. if (ob_get_level() > 0) {
  3530. ob_flush();
  3531. }
  3532. flush();
  3533. break;
  3534. }
  3535. // 等待下次检查
  3536. sleep($checkInterval);
  3537. }
  3538. // 超时处理
  3539. if (time() - $startTime >= $maxDuration) {
  3540. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3541. try {
  3542. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3543. if ($finalSource) {
  3544. $finalSource = (array)$finalSource;
  3545. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3546. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3547. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3548. // 使用数据库中的最终数据
  3549. $roles = $finalRoles;
  3550. $scenes = $finalScenes;
  3551. $props = $finalProps;
  3552. }
  3553. } catch (\Exception $e) {
  3554. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3555. // 如果查询失败,继续使用内存中的数据
  3556. }
  3557. // 清理缓存
  3558. Redis::del($cacheKey);
  3559. echo "data: " . json_encode([
  3560. 'type' => 'timeout',
  3561. 'message' => '轮询超时,请刷新页面查看最新状态',
  3562. 'data' => [
  3563. 'roles' => $roles,
  3564. 'scenes' => $scenes,
  3565. 'props' => $props
  3566. ]
  3567. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3568. if (ob_get_level() > 0) {
  3569. ob_flush();
  3570. }
  3571. flush();
  3572. }
  3573. };
  3574. }
  3575. public function clipSegmentVideo($data) {
  3576. $segment_id = getProp($data, 'segment_id');
  3577. $video_time_point_start = getProp($data, 'video_time_point_start');
  3578. $video_time_point_end = getProp($data, 'video_time_point_end');
  3579. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3580. Utils::throwError('20003:参数异常');
  3581. }
  3582. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3583. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3584. }
  3585. $video_duration = $video_time_point_end - $video_time_point_start;
  3586. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3587. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3588. 'video_duration' => $video_duration,
  3589. 'video_time_point_start' => $video_time_point_start,
  3590. 'video_time_point_end' => $video_time_point_end,
  3591. 'updated_at' => date('Y-m-d H:i:s')
  3592. ]);
  3593. }
  3594. // 轮训获取图片任务结果
  3595. private function loopGetPicTaskResult($task_id) {
  3596. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3597. if (!$task) {
  3598. return '';
  3599. }
  3600. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3601. $model = getProp($task, 'model');
  3602. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3603. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3604. $isSyncModel = $isVolcModel || $isGptModel;
  3605. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3606. $start_count = 0;
  3607. $img_url = '';
  3608. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3609. sleep(3);
  3610. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3611. // 如果任务已经完成,直接返回结果
  3612. if ($task->status === 'success' && $task->result_url) {
  3613. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3614. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3615. }
  3616. // 如果任务已失败,返回空
  3617. if ($task->status === 'failed') {
  3618. return '';
  3619. }
  3620. if ($isSyncModel) continue;
  3621. // 查询任务状态
  3622. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3623. if ($statusInfo['status'] === 'success') {
  3624. $task->updateStatus('success', [
  3625. 'result_url' => $statusInfo['result_url'],
  3626. 'result_json' => $statusInfo['result_json'] ?? []
  3627. ]);
  3628. // 同步调整分镜图片状态和结果
  3629. if (getProp($task, 'alias_segment_id')) {
  3630. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3631. 'img_url' => $statusInfo['result_url'][0],
  3632. 'pic_task_status' => '已完成',
  3633. ]);
  3634. }
  3635. $img_url = $statusInfo['result_url'][0];
  3636. break;
  3637. } elseif ($statusInfo['status'] === 'failed') {
  3638. $task->updateStatus('failed', [
  3639. 'error_message' => $statusInfo['error_message'],
  3640. 'result_json' => $statusInfo['result_json'] ?? []
  3641. ]);
  3642. if (getProp($task, 'alias_segment_id')) {
  3643. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3644. 'pic_task_status' => '失败',
  3645. ]);
  3646. }
  3647. break;
  3648. }
  3649. $start_count++;
  3650. }
  3651. return $img_url;
  3652. }
  3653. /**
  3654. * 从分镜内容中提取涉及的角色
  3655. */
  3656. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3657. $found_characters = [];
  3658. foreach ($available_characters as $character) {
  3659. // 检查角色名称是否在分镜内容中出现
  3660. if (strpos($segment_content, $character) !== false) {
  3661. $found_characters[] = $character;
  3662. }
  3663. }
  3664. if (!$found_characters) {
  3665. foreach ($roles as $character) {
  3666. // 检查角色名称是否在分镜内容中出现
  3667. if (strpos($segment_content, $character) !== false) {
  3668. $found_characters[] = $character;
  3669. }
  3670. }
  3671. }
  3672. return array_unique($found_characters);
  3673. }
  3674. // 从分镜剧本中提取关键字段
  3675. private function handleSegmentContent(&$data) {
  3676. $segmentContent = getProp($data, 'segment_content');
  3677. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3678. $segmentData = [
  3679. 'description' => '',
  3680. 'composition' => '',
  3681. 'camera_movement' => '',
  3682. 'voice_actor' => '',
  3683. 'dialogue' => '',
  3684. 'frame_type' => '',
  3685. 'scene' => '', // 场景
  3686. 'characters' => '', // 出镜角色
  3687. 'tail_frame' => '', // 尾帧描述
  3688. 'emotion' => '中性', // 情感
  3689. 'gender' => '0', // 性别(0未知,1男,2女)
  3690. 'speed_ratio' => 0, // 语速
  3691. 'loudness_ratio' => 0, // 音量
  3692. 'emotion_scale' => 4, // 情感强度
  3693. 'pitch' => 0, // 音调
  3694. ];
  3695. // 用于存储需要从 segment_content 中移除的匹配项
  3696. $replaceEmptyArr = [];
  3697. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3698. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3699. $segmentData['description'] = trim($descMatch[1]);
  3700. $data['description'] = trim($descMatch[1]);
  3701. }
  3702. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3703. $segmentData['composition'] = trim($compMatch[1]);
  3704. $data['composition'] = trim($compMatch[1]);
  3705. }
  3706. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3707. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3708. $data['camera_movement'] = trim($cameraMatch[1]);
  3709. }
  3710. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3711. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3712. $data['voice_actor'] = trim($voiceMatch[1]);
  3713. }
  3714. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3715. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3716. $data['dialogue'] = trim($dialogueMatch[1]);
  3717. }
  3718. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3719. $segmentData['frame_type'] = trim($frameMatch[1]);
  3720. $data['frame_type'] = trim($frameMatch[1]);
  3721. }
  3722. // 场景字段
  3723. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3724. $segmentData['scene'] = trim($sceneMatch[1]);
  3725. $data['scene'] = trim($sceneMatch[1]);
  3726. }
  3727. // 出镜角色字段
  3728. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3729. $segmentData['characters'] = trim($charactersMatch[1]);
  3730. $data['characters'] = trim($charactersMatch[1]);
  3731. }
  3732. // 尾帧描述字段
  3733. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3734. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3735. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3736. }
  3737. // 情感字段
  3738. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3739. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3740. $segmentData['emotion'] = trim($emotionMatch[1]);
  3741. $data['emotion'] = trim($emotionMatch[1]);
  3742. }
  3743. // 性别字段
  3744. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3745. $replaceEmptyArr[] = trim($genderMatch[0]);
  3746. $genderStr = trim($genderMatch[1]);
  3747. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3748. $segmentData['gender'] = '1';
  3749. $data['gender'] = '1';
  3750. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3751. $segmentData['gender'] = '2';
  3752. $data['gender'] = '2';
  3753. } else {
  3754. $segmentData['gender'] = '0';
  3755. $data['gender'] = '0';
  3756. }
  3757. }
  3758. // 语速字段
  3759. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3760. $replaceEmptyArr[] = trim($speedMatch[0]);
  3761. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3762. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3763. }
  3764. // 音量字段
  3765. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3766. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3767. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3768. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3769. }
  3770. // 情感强度字段
  3771. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3772. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3773. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3774. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3775. }
  3776. // 音调字段
  3777. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3778. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3779. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3780. $data['pitch'] = (int)trim($pitchMatch[1]);
  3781. }
  3782. // 从 segment_content 中移除已提取的配音参数字段
  3783. if (!empty($replaceEmptyArr)) {
  3784. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3785. }
  3786. // 如果有配音角色,查询音色信息并验证情感
  3787. $voice_actor = $segmentData['voice_actor'];
  3788. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3789. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3790. $anime_id = getProp($data, 'anime_id');
  3791. $episode_id = getProp($data, 'episode_id');
  3792. // 优先从剧集的角色列表中查找
  3793. $roles = [];
  3794. if ($episode_id) {
  3795. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3796. if ($episode && getProp($episode, 'roles')) {
  3797. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3798. }
  3799. }
  3800. // 如果剧集中没有,从动漫的角色列表中查找
  3801. if (empty($roles) && $anime_id) {
  3802. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3803. if ($anime && getProp($anime, 'roles')) {
  3804. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3805. }
  3806. }
  3807. // 查找匹配的角色音色信息
  3808. $timbre_info = null;
  3809. foreach ($roles as $role) {
  3810. if (getProp($role, 'role') === $voice_actor) {
  3811. $timbre_info = $role;
  3812. break;
  3813. }
  3814. }
  3815. // 如果找到音色信息,添加到数据中
  3816. if ($timbre_info) {
  3817. $voice_type = getProp($timbre_info, 'voice_type');
  3818. $voice_name = getProp($timbre_info, 'voice_name');
  3819. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3820. if ($voice_type) {
  3821. $data['voice_type'] = $voice_type;
  3822. $segmentData['voice_type'] = $voice_type;
  3823. }
  3824. if ($voice_name) {
  3825. $data['voice_name'] = $voice_name;
  3826. $segmentData['voice_name'] = $voice_name;
  3827. }
  3828. if ($voice_audio_url) {
  3829. $data['voice_audio_url'] = $voice_audio_url;
  3830. $segmentData['voice_audio_url'] = $voice_audio_url;
  3831. }
  3832. // 验证情感是否在音色支持的情感列表中
  3833. if ($voice_type) {
  3834. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3835. if ($timbre_emotion) {
  3836. $timbre_emotion = explode(',', $timbre_emotion);
  3837. } else {
  3838. $timbre_emotion = [];
  3839. }
  3840. $emotion = getProp($segmentData, 'emotion', '中性');
  3841. if (!in_array($emotion, $timbre_emotion)) {
  3842. $emotion = '中性';
  3843. }
  3844. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3845. $emotion_list = array_flip($emotion_list);
  3846. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3847. $data['emotion_type'] = $emotion_type;
  3848. $segmentData['emotion_type'] = $emotion_type;
  3849. }
  3850. }
  3851. }
  3852. return $segmentData;
  3853. }
  3854. public function createSegmentVideoTask($data) {
  3855. $segment_id = getProp($data, 'segment_id');
  3856. $tail_frame = getProp($data, 'tail_frame');
  3857. $first_frame_url = getProp($data, 'first_frame_url');
  3858. $tail_frame_url = getProp($data, 'tail_frame_url');
  3859. $generate_audio = getProp($data, 'generate_audio', 0);
  3860. if (!$segment_id) {
  3861. Utils::throwError('1002:分镜ID不能为空');
  3862. }
  3863. // 获取分镜信息
  3864. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3865. if (!$segment) {
  3866. Utils::throwError('20003:分镜不存在');
  3867. }
  3868. $segment = (array)$segment;
  3869. $episode_id = getProp($segment, 'episode_id');
  3870. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3871. if (!$ratio) $ratio = '9:16';
  3872. // 获取分镜内容
  3873. $segmentContent = getProp($segment, 'segment_content', '');
  3874. // 检查 $segmentContent 中是否已有尾帧描述
  3875. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3876. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3877. $finalTailFrame = '';
  3878. if ($tail_frame) {
  3879. // 用户输入了尾帧描述,优先使用
  3880. $finalTailFrame = $tail_frame;
  3881. // 如果 segmentContent 中已有尾帧描述,需要替换
  3882. if ($contentHasTailFrame) {
  3883. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3884. }
  3885. } elseif ($contentHasTailFrame) {
  3886. // segmentContent 中有尾帧描述,使用它
  3887. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3888. } else {
  3889. // 两者都没有,使用分镜表中的尾帧描述
  3890. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3891. }
  3892. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3893. $hasDialogue = false;
  3894. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3895. $dialogue = trim($dialogueMatch[1]);
  3896. // 如果台词不为空且不是"无"
  3897. if (!empty($dialogue) && $dialogue !== '无') {
  3898. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3899. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3900. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3901. $hasDialogue = true;
  3902. }
  3903. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3904. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3905. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3906. if (!preg_match('/^[“]/', $dialogue)) {
  3907. $dialogue = '“' . $dialogue;
  3908. }
  3909. if (!preg_match('/[”]$/', $dialogue)) {
  3910. $dialogue .= '”';
  3911. }
  3912. // 将修改后的台词替换回 $segmentContent
  3913. $originalDialogue = $dialogueMatch[1];
  3914. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3915. }
  3916. }
  3917. // 构建完整的提示词
  3918. $fullPrompt = $segmentContent;
  3919. if ($finalTailFrame && !$contentHasTailFrame) {
  3920. // 只有当 segmentContent 中没有尾帧描述时才追加
  3921. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3922. }
  3923. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3924. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3925. $fullPrompt = trim($fullPrompt);
  3926. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3927. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3928. // 智能选择视频时长
  3929. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3930. $videoDuration = -1;
  3931. // 处理视频模型
  3932. $model = getProp($data, 'model');
  3933. if (!$model) {
  3934. // 用户没有输入,从episode表获取
  3935. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3936. $model = getProp($episode, 'video_model');
  3937. if (!$model) {
  3938. // episode表也没有,使用默认值
  3939. $model = 'doubao-seedance-1-5-pro-251215';
  3940. }
  3941. }
  3942. // 验证模型是否在可用模型表中
  3943. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3944. $model = 'doubao-seedance-1-5-pro-251215';
  3945. }
  3946. // 保存到episode表
  3947. $episode_id = getProp($segment, 'episode_id');
  3948. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3949. 'video_model' => $model,
  3950. 'updated_at' => date('Y-m-d H:i:s')
  3951. ]);
  3952. // 构建视频生成参数
  3953. $videoParams = [
  3954. 'model' => $model,
  3955. 'alias_segment_id' => $segment_id,
  3956. 'prompt' => trim($fullPrompt),
  3957. 'video_duration' => $videoDuration,
  3958. 'video_resolution' => '720P',
  3959. 'seed' => -1,
  3960. 'ratio' => $ratio,
  3961. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3962. 'draft' => false,
  3963. 'watermark' => false,
  3964. 'camera_fixed' => false,
  3965. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3966. ];
  3967. // 如果分镜有图片,作为首帧
  3968. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3969. $hasVideo = !empty(getProp($segment, 'video_url'));
  3970. if ($hasImage) {
  3971. if ($first_frame_url) {
  3972. $videoParams['first_frame_url'] = $first_frame_url;
  3973. }else {
  3974. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3975. }
  3976. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3977. }
  3978. // 构建content数组
  3979. $videoParams['content'] = [
  3980. [
  3981. 'type' => 'text',
  3982. 'text' => $videoParams['prompt'],
  3983. ]
  3984. ];
  3985. // 如果有首帧图片,添加到content中
  3986. if ($hasImage) {
  3987. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3988. $videoParams['content'][] = [
  3989. 'type' => 'image_url',
  3990. 'image_url' => [
  3991. 'url' => $videoParams['first_frame_url'],
  3992. ],
  3993. 'role' => 'reference_image',
  3994. ];
  3995. if (isset($videoParams['tail_frame_url'])) {
  3996. $videoParams['content'][] = [
  3997. 'type' => 'image_url',
  3998. 'image_url' => [
  3999. 'url' => $videoParams['tail_frame_url'],
  4000. ],
  4001. 'role' => 'reference_image',
  4002. ];
  4003. }
  4004. }else {
  4005. $videoParams['content'][] = [
  4006. 'type' => 'image_url',
  4007. 'image_url' => [
  4008. 'url' => $videoParams['first_frame_url'],
  4009. ],
  4010. 'role' => 'first_frame',
  4011. ];
  4012. if (isset($videoParams['tail_frame_url'])) {
  4013. $videoParams['content'][] = [
  4014. 'type' => 'image_url',
  4015. 'image_url' => [
  4016. 'url' => $videoParams['tail_frame_url'],
  4017. ],
  4018. 'role' => 'last_frame',
  4019. ];
  4020. }
  4021. }
  4022. }
  4023. // 获取配音音频URL
  4024. $audioUrl = getProp($segment, 'audio_url');
  4025. $audioDuration = getProp($segment, 'audio_duration');
  4026. // 音频传入的前提:必须有至少一张图片或一个视频
  4027. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4028. // dd($videoParams);
  4029. // 根据模型选择不同的视频生成方法
  4030. if (strpos($model, 'jimeng') !== false) {
  4031. // 即梦模型参数调整
  4032. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4033. unset($videoParams['content']); // 即梦不使用content格式
  4034. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4035. } elseif (strpos($model, 'kling') !== false) {
  4036. // Keling模型参数调整
  4037. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4038. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4039. unset($videoParams['ratio']);
  4040. unset($videoParams['content']); // Keling不使用content格式
  4041. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4042. } elseif (strpos($model, 'zhizhen') !== false) {
  4043. // 智帧20等新模型使用统一API
  4044. // 构建统一API参数
  4045. $unifiedParams = [
  4046. 'model_code' => $model,
  4047. 'alias_segment_id' => $segment_id,
  4048. 'prompt' => trim($fullPrompt),
  4049. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4050. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4051. 'video_ratio' => $ratio,
  4052. 'seed' => -1,
  4053. ];
  4054. // 构建parameters参数
  4055. $parameters = [
  4056. 'seconds' => $unifiedParams['video_duration'],
  4057. 'resolution' => $unifiedParams['video_resolution'],
  4058. 'ratio' => $ratio,
  4059. // 'video_mode' => 'multi_image',
  4060. // 'mode' => 'multi_image',
  4061. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4062. ];
  4063. $hasImage = false;
  4064. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4065. if ($hasImage) {
  4066. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4067. if (isset($videoParams['tail_frame_url'])) {
  4068. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4069. }
  4070. // 只有在有图片的情况下才能添加参考音频
  4071. if ($audioUrl) {
  4072. // $parameters['reference_audios'] = [$audioUrl];
  4073. }
  4074. } else {
  4075. // 没有图片时,记录错误日志
  4076. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4077. 'segment_id' => $segment_id,
  4078. 'model' => $model
  4079. ]);
  4080. }
  4081. $unifiedParams['parameters'] = $parameters;
  4082. // 调用统一API创建任务
  4083. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4084. } else {
  4085. // Seedance模型(默认)
  4086. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4087. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4088. // 添加配音音频到content中
  4089. $videoParams['content'][] = [
  4090. 'type' => 'audio_url',
  4091. 'audio_url' => [
  4092. 'url' => $audioUrl,
  4093. ],
  4094. 'role' => 'reference_audio',
  4095. ];
  4096. // 优化提示词,增加音频相关描述
  4097. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4098. $videoParams['prompt'] = $audioPrompt;
  4099. $videoParams['content'][0]['text'] = $audioPrompt;
  4100. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4101. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4102. }
  4103. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4104. }
  4105. // 更新分镜表的视频任务信息
  4106. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4107. 'video_task_id' => $task->id,
  4108. 'video_task_status' => '生成中',
  4109. 'generate_audio' => $generate_audio,
  4110. 'updated_at' => date('Y-m-d H:i:s')
  4111. ]);
  4112. return [
  4113. 'task_id' => $task->id,
  4114. 'status' => $task->status,
  4115. 'segment_id' => $segment_id,
  4116. 'video_duration' => $videoDuration
  4117. ];
  4118. }
  4119. public function createActVideoTask($data) {
  4120. $act_id = getProp($data, 'act_id');
  4121. $first_frame_url = getProp($data, 'first_frame_url');
  4122. $tail_frame_url = getProp($data, 'tail_frame_url');
  4123. $generate_audio = getProp($data, 'generate_audio', 1);
  4124. $video_duration = getProp($data, 'video_duration');
  4125. $video_resolution = getProp($data, 'video_resolution');
  4126. $ratio = getProp($data, 'ratio');
  4127. $products = getProp($data, 'products', []);
  4128. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4129. if (!is_array($reference_images) || !is_array($products)) {
  4130. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4131. }
  4132. if (!$act_id) {
  4133. Utils::throwError('1002:片段ID不能为空');
  4134. }
  4135. // 获取片段信息
  4136. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4137. if (!$act) {
  4138. Utils::throwError('20003:片段不存在');
  4139. }
  4140. $act = (array)$act;
  4141. $anime_id = getProp($act, 'anime_id');
  4142. $episode_id = getProp($act, 'episode_id');
  4143. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4144. $ace_mode = getProp($anime, 'ace_mode');
  4145. $art_style_type = getProp($anime, 'art_style_type');
  4146. $art_style = getProp($anime, 'art_style');
  4147. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4148. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4149. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4150. // 将资产中新出现的资产放到extra_products中
  4151. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4152. if (!empty($products) && $episode) {
  4153. // 获取剧集中的角色、场景和道具列表
  4154. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4155. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4156. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4157. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4158. // 构建角色名称列表
  4159. $role_names = array_column($roles, 'role');
  4160. // 构建场景名称列表
  4161. $scene_names = array_column($scenes, 'scene');
  4162. // 构建道具名称列表
  4163. $prop_names = array_column($props, 'prop');
  4164. // 遍历传入的products
  4165. foreach ($products as $product) {
  4166. $product_name = getProp($product, 'product_name');
  4167. // 如果product_name不在roles、scenes和props中
  4168. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4169. // 查找是否在extra_products中存在同名的
  4170. $found = false;
  4171. foreach ($extra_products as $key => $extra_product) {
  4172. if (getProp($extra_product, 'product_name') === $product_name) {
  4173. // 有同名的则覆盖
  4174. $extra_products[$key] = $product;
  4175. $found = true;
  4176. break;
  4177. }
  4178. }
  4179. // 没有则新增
  4180. if (!$found) {
  4181. $extra_products[] = $product;
  4182. }
  4183. }
  4184. }
  4185. if ($extra_products) {
  4186. // 保存到数据库
  4187. DB::table('mp_anime_episodes')
  4188. ->where('id', $episode_id)
  4189. ->update([
  4190. 'extra_products' => json_encode($extra_products, 256),
  4191. 'updated_at' => date('Y-m-d H:i:s')
  4192. ]);
  4193. }
  4194. }
  4195. // 获取分镜内容
  4196. $actContent = getProp($act, 'act_show_content', '');
  4197. // 音效同出(默认使用)
  4198. $current_generate_audio = $generate_audio ? 1 : 0;
  4199. // 构建完整的提示词
  4200. $processResult = $this->processActContentWithProducts($actContent, $products);
  4201. $fullPrompt = $processResult['content'];
  4202. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4203. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4204. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4205. // 处理视频模型
  4206. $model = getProp($data, 'model');
  4207. if (!$model) {
  4208. $model = getProp($episode, 'video_model');
  4209. if (!$model) {
  4210. // episode表也没有,使用默认值
  4211. $model = 'zhizhen-20';
  4212. }
  4213. }
  4214. // 验证模型是否在可用模型表中
  4215. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4216. $model = 'zhizhen-20';
  4217. }
  4218. // 保存到episode表
  4219. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4220. 'video_model' => $model,
  4221. 'updated_at' => date('Y-m-d H:i:s')
  4222. ]);
  4223. // 构建视频生成参数
  4224. $videoParams = [
  4225. 'model' => $model,
  4226. 'alias_act_id' => $act_id,
  4227. 'prompt' => trim($fullPrompt),
  4228. 'video_duration' => $videoDuration,
  4229. 'video_resolution' => $video_resolution,
  4230. 'seed' => -1,
  4231. 'ratio' => $ratio,
  4232. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4233. 'draft' => false,
  4234. 'watermark' => false,
  4235. 'camera_fixed' => false,
  4236. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4237. ];
  4238. // 如果分镜有图片,作为首帧
  4239. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4240. $hasVideo = !empty(getProp($act, 'video_url'));
  4241. if ($hasImage) {
  4242. if ($first_frame_url) {
  4243. $videoParams['first_frame_url'] = $first_frame_url;
  4244. }else {
  4245. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4246. }
  4247. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4248. }
  4249. // 构建content数组
  4250. $videoParams['content'] = [
  4251. [
  4252. 'type' => 'text',
  4253. 'text' => $videoParams['prompt'],
  4254. ]
  4255. ];
  4256. // 如果有首帧图片,添加到content中
  4257. if ($hasImage) {
  4258. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4259. $videoParams['content'][] = [
  4260. 'type' => 'image_url',
  4261. 'image_url' => [
  4262. 'url' => $videoParams['first_frame_url'],
  4263. ],
  4264. 'role' => 'reference_image',
  4265. ];
  4266. if (isset($videoParams['tail_frame_url'])) {
  4267. $videoParams['content'][] = [
  4268. 'type' => 'image_url',
  4269. 'image_url' => [
  4270. 'url' => $videoParams['tail_frame_url'],
  4271. ],
  4272. 'role' => 'reference_image',
  4273. ];
  4274. }
  4275. }else {
  4276. $videoParams['content'][] = [
  4277. 'type' => 'image_url',
  4278. 'image_url' => [
  4279. 'url' => $videoParams['first_frame_url'],
  4280. ],
  4281. 'role' => 'first_frame',
  4282. ];
  4283. if (isset($videoParams['tail_frame_url'])) {
  4284. $videoParams['content'][] = [
  4285. 'type' => 'image_url',
  4286. 'image_url' => [
  4287. 'url' => $videoParams['tail_frame_url'],
  4288. ],
  4289. 'role' => 'last_frame',
  4290. ];
  4291. }
  4292. }
  4293. }
  4294. // dd($videoParams);
  4295. // 根据模型选择不同的视频生成方法
  4296. if (strpos($model, 'jimeng') !== false) {
  4297. // 即梦模型参数调整
  4298. unset($videoParams['content']); // 即梦不使用content格式
  4299. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4300. } elseif (strpos($model, 'kling') !== false) {
  4301. // Keling模型参数调整
  4302. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4303. unset($videoParams['ratio']);
  4304. unset($videoParams['content']); // Keling不使用content格式
  4305. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4306. } elseif (strpos($model, 'zhizhen') !== false) {
  4307. // 智帧20等新模型使用统一API
  4308. // 构建统一API参数
  4309. $unifiedParams = [
  4310. 'model_code' => $model,
  4311. 'alias_act_id' => $act_id,
  4312. 'prompt' => trim($fullPrompt),
  4313. 'video_duration' => $videoDuration,
  4314. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4315. 'video_ratio' => $ratio,
  4316. 'seed' => -1,
  4317. ];
  4318. // 构建parameters参数
  4319. $parameters = [
  4320. 'seconds' => $unifiedParams['video_duration'],
  4321. 'resolution' => $unifiedParams['video_resolution'],
  4322. 'ratio' => $ratio,
  4323. // 'video_mode' => 'multi_image',
  4324. // 'mode' => 'multi_image',
  4325. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4326. ];
  4327. $hasImage = false;
  4328. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4329. if ($hasImage) {
  4330. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4331. if (isset($videoParams['tail_frame_url'])) {
  4332. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4333. }
  4334. } else {
  4335. // 没有图片时,记录错误日志
  4336. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4337. 'act_id' => $act_id,
  4338. 'model' => $model
  4339. ]);
  4340. }
  4341. if ($reference_images) {
  4342. // 限制只传入9张参考图
  4343. $reference_images = array_slice($reference_images, 0, 9);
  4344. // 在处理之前先保存原始reference_images到任务参数中
  4345. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4346. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4347. $parameters['reference_images'] = $reference_images;
  4348. $parameters['video_mode'] = 'multi_image';
  4349. $parameters['mode'] = 'multi_image';
  4350. }
  4351. $unifiedParams['parameters'] = $parameters;
  4352. // 调用统一API创建任务
  4353. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4354. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4355. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4356. // 保存原始参考图用于任务记录
  4357. $videoParams['reference_images'] = $reference_images;
  4358. if ($reference_images) {
  4359. // 限制只传入9张参考图
  4360. $reference_images = array_slice($reference_images, 0, 9);
  4361. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4362. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4363. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4364. $videoParams['prompt'] = trim($fullPrompt);
  4365. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4366. $videoParams['reference_image_assets'] = $reference_image_assets;
  4367. }
  4368. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4369. } else {
  4370. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4371. }
  4372. // 更新分镜表的视频任务信息
  4373. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4374. 'video_task_id' => $task->id,
  4375. 'video_task_status' => '生成中',
  4376. 'generate_audio' => $generate_audio,
  4377. 'updated_at' => date('Y-m-d H:i:s')
  4378. ]);
  4379. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4380. $episode_number = getProp($act, 'episode_number');
  4381. $act_number = getProp($act, 'act_number');
  4382. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4383. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4384. }
  4385. return [
  4386. 'task_id' => $task->id,
  4387. 'status' => $task->status,
  4388. 'act_id' => $act_id,
  4389. 'video_duration' => $videoDuration
  4390. ];
  4391. }
  4392. /**
  4393. * 文生视频通用方法
  4394. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4395. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4396. *
  4397. * @param array $data 请求参数
  4398. * @return array
  4399. */
  4400. public function generateVideo($data) {
  4401. $prompt = getProp($data, 'prompt');
  4402. if (empty($prompt)) {
  4403. Utils::throwError('20003:提示词不能为空');
  4404. }
  4405. $model = getProp($data, 'model');
  4406. if (!$model) {
  4407. $model = 'zhizhen-20';
  4408. }
  4409. // 验证模型是否在可用模型表中
  4410. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4411. Utils::throwError('20003:该模型已不可用,请更换!');
  4412. }
  4413. $video_duration = getProp($data, 'video_duration', 5);
  4414. $video_resolution = getProp($data, 'video_resolution', '480p');
  4415. $ratio = getProp($data, 'ratio', '9:16');
  4416. $generate_audio = getProp($data, 'generate_audio', 1);
  4417. $seed = getProp($data, 'seed', -1);
  4418. $first_frame_url = getProp($data, 'first_frame_url');
  4419. $tail_frame_url = getProp($data, 'tail_frame_url');
  4420. // 参考图(支持数组或JSON字符串,最多9张)
  4421. $reference_images = getProp($data, 'reference_images', []);
  4422. if (is_string($reference_images)) {
  4423. $reference_images = json_decode($reference_images, true) ?: [];
  4424. }
  4425. if (!is_array($reference_images)) {
  4426. Utils::throwError('20003:参考图格式不正确');
  4427. }
  4428. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4429. $reference_images = array_slice($reference_images, 0, 9);
  4430. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4431. $videoParams = [
  4432. 'model' => $model,
  4433. 'prompt' => $prompt,
  4434. 'video_duration' => $video_duration,
  4435. 'video_resolution' => $video_resolution,
  4436. 'seed' => $seed,
  4437. 'ratio' => $ratio,
  4438. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4439. 'draft' => getProp($data, 'draft', false),
  4440. 'watermark' => getProp($data, 'watermark', false),
  4441. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4442. ];
  4443. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4444. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4445. // 构建content数组
  4446. $videoParams['content'] = [
  4447. [
  4448. 'type' => 'text',
  4449. 'text' => $prompt,
  4450. ]
  4451. ];
  4452. // 根据模型选择不同的视频生成方法
  4453. if (strpos($model, 'jimeng') !== false) {
  4454. // 即梦模型参数调整
  4455. unset($videoParams['content']); // 即梦不使用content格式
  4456. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4457. } elseif (strpos($model, 'kling') !== false) {
  4458. // 可灵模型参数调整
  4459. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4460. unset($videoParams['ratio']);
  4461. unset($videoParams['content']); // 可灵不使用content格式
  4462. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4463. } elseif (strpos($model, 'zhizhen') !== false) {
  4464. // 智帧等新模型使用统一API
  4465. $unifiedParams = [
  4466. 'model_code' => $model,
  4467. 'prompt' => $prompt,
  4468. 'video_duration' => $video_duration,
  4469. 'video_resolution' => strtolower($video_resolution),
  4470. 'video_ratio' => $ratio,
  4471. 'seed' => $seed,
  4472. ];
  4473. // 构建parameters参数
  4474. $parameters = [
  4475. 'seconds' => $unifiedParams['video_duration'],
  4476. 'resolution' => $unifiedParams['video_resolution'],
  4477. 'ratio' => $ratio,
  4478. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4479. ];
  4480. // 首帧和尾帧
  4481. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4482. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4483. // 参考图处理
  4484. if ($reference_images) {
  4485. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4486. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4487. $parameters['reference_images'] = $reference_images;
  4488. $parameters['video_mode'] = 'multi_image';
  4489. $parameters['mode'] = 'multi_image';
  4490. }
  4491. $unifiedParams['parameters'] = $parameters;
  4492. // 调用统一API创建任务
  4493. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4494. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4495. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4496. $videoParams['reference_images'] = $reference_images;
  4497. if ($reference_images) {
  4498. // 参考图上传为百度网关素材
  4499. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4500. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4501. $videoParams['reference_image_assets'] = $reference_image_assets;
  4502. }
  4503. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4504. } else {
  4505. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4506. }
  4507. return [
  4508. 'task_id' => $task->id,
  4509. 'status' => $task->status,
  4510. 'model' => $model,
  4511. 'video_duration' => $video_duration,
  4512. 'video_resolution' => $video_resolution,
  4513. 'ratio' => $ratio
  4514. ];
  4515. }
  4516. /**
  4517. * 根据提示词内容智能计算最优视频时长
  4518. *
  4519. * @param string $segmentContent 分镜内容
  4520. * @param string $tailFrame 尾帧描述
  4521. * @return int 视频时长(2-12秒)
  4522. */
  4523. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4524. // 合并所有文本内容
  4525. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4526. // 如果没有内容,返回默认时长
  4527. if (empty($fullText)) {
  4528. return 5;
  4529. }
  4530. // 计算文本长度(中文字符按2个字符计算)
  4531. $textLength = mb_strlen($fullText, 'UTF-8');
  4532. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4533. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4534. // 分析内容复杂度
  4535. $complexityScore = $this->analyzeContentComplexity($fullText);
  4536. // 基础时长计算(根据文本长度)
  4537. $baseDuration = 3; // 默认2秒
  4538. // if ($adjustedLength <= 20) {
  4539. // $baseDuration = 3;
  4540. // } elseif ($adjustedLength <= 40) {
  4541. // $baseDuration = 4;
  4542. // } elseif ($adjustedLength <= 60) {
  4543. // $baseDuration = 5;
  4544. // } elseif ($adjustedLength <= 80) {
  4545. // $baseDuration = 6;
  4546. // } elseif ($adjustedLength <= 100) {
  4547. // $baseDuration = 7;
  4548. // } elseif ($adjustedLength <= 120) {
  4549. // $baseDuration = 8;
  4550. // } else {
  4551. // $baseDuration = 9;
  4552. // }
  4553. // 根据内容复杂度调整时长
  4554. $finalDuration = $baseDuration + $complexityScore;
  4555. // 确保时长在2-12秒范围内
  4556. return max(4, min(12, $finalDuration));
  4557. }
  4558. /**
  4559. * 分析内容复杂度,返回时长调整值
  4560. *
  4561. * @param string $text 文本内容
  4562. * @return int 调整值(-2到+3)
  4563. */
  4564. private function analyzeContentComplexity($text) {
  4565. $score = 0;
  4566. // 动作关键词(需要更长时间展现)
  4567. $actionKeywords = [
  4568. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4569. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4570. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4571. ];
  4572. // 静态关键词(可以用较短时间)
  4573. $staticKeywords = [
  4574. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4575. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4576. ];
  4577. // 复杂场景关键词(需要更长时间)
  4578. $complexSceneKeywords = [
  4579. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4580. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4581. ];
  4582. // 情感关键词(需要适中时间表现)
  4583. $emotionKeywords = [
  4584. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4585. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4586. ];
  4587. // 检查动作关键词
  4588. foreach ($actionKeywords as $keyword) {
  4589. if (strpos($text, $keyword) !== false) {
  4590. $score += 1;
  4591. break; // 避免重复加分
  4592. }
  4593. }
  4594. // 检查静态关键词
  4595. foreach ($staticKeywords as $keyword) {
  4596. if (strpos($text, $keyword) !== false) {
  4597. $score -= 1;
  4598. break;
  4599. }
  4600. }
  4601. // 检查复杂场景关键词
  4602. foreach ($complexSceneKeywords as $keyword) {
  4603. if (strpos($text, $keyword) !== false) {
  4604. $score += 1;
  4605. break;
  4606. }
  4607. }
  4608. // 检查情感关键词
  4609. foreach ($emotionKeywords as $keyword) {
  4610. if (strpos($text, $keyword) !== false) {
  4611. $score += 1;
  4612. break;
  4613. }
  4614. }
  4615. // 检查时间相关词汇
  4616. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4617. $score += 1;
  4618. }
  4619. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4620. $score -= 1;
  4621. }
  4622. // 检查转场词汇
  4623. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4624. $score += 1;
  4625. }
  4626. // 检查环境描述(复杂环境需要更多时间)
  4627. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4628. $score += 1;
  4629. }
  4630. // 检查对话内容(对话需要更多时间)
  4631. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4632. $score += 1;
  4633. }
  4634. // 限制调整范围
  4635. return max(-1, min(4, $score));
  4636. }
  4637. /**
  4638. * 创建完整视频合成任务
  4639. *
  4640. * @param array $data
  4641. * @return array
  4642. */
  4643. public function createCompleteVideoTask($data)
  4644. {
  4645. $animeId = getProp($data, 'anime_id');
  4646. $episodeId = getProp($data, 'episode_id');
  4647. // 验证参数
  4648. if (!$animeId || !$episodeId) {
  4649. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4650. }
  4651. // 检查是否已存在处理中的任务
  4652. $existingTask = DB::table('mp_complete_video_tasks')
  4653. ->where('anime_id', $animeId)
  4654. ->where('episode_id', $episodeId)
  4655. ->whereIn('generate_status', ['执行中'])
  4656. ->first();
  4657. if ($existingTask) {
  4658. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4659. }
  4660. // 获取全能模式状态
  4661. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4662. if ((int)$ace_mode === 1) {
  4663. // 获取所有片段的配音视频,按 act_number 排序
  4664. $segments = DB::table('mp_episode_segments')
  4665. ->where('anime_id', $animeId)
  4666. ->where('episode_id', $episodeId)
  4667. ->orderBy('segment_number')
  4668. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4669. ->get();
  4670. // 检查是否所有片段都有视频
  4671. $missingVideos = $segments->filter(function($segment) {
  4672. return empty($segment->video_url);
  4673. });
  4674. if ($missingVideos->isNotEmpty()) {
  4675. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4676. }
  4677. }else {
  4678. // 获取所有分镜的配音视频,按 segment_number 排序
  4679. $segments = DB::table('mp_episode_segments')
  4680. ->where('anime_id', $animeId)
  4681. ->where('episode_id', $episodeId)
  4682. ->orderBy('segment_number')
  4683. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4684. ->get();
  4685. // 检查是否所有分镜都有配音和视频
  4686. $missingVideos = $segments->filter(function($segment) {
  4687. return empty($segment->audio_url) || empty($segment->video_url);
  4688. });
  4689. if ($missingVideos->isNotEmpty()) {
  4690. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4691. }
  4692. }
  4693. if ($segments->isEmpty()) {
  4694. Utils::throwError('20003:未找到该剧集的分镜数据');
  4695. }
  4696. // 获取当前完整视频url
  4697. $completeVideoUrl = DB::table('mp_anime_episodes')
  4698. ->where('anime_id', $animeId)
  4699. ->where('id', $episodeId)
  4700. ->value('complete_video_url');
  4701. // 构建 generate_json
  4702. $generateJson = [];
  4703. $sequence = 1;
  4704. foreach ($segments as $segment) {
  4705. if ((int)$ace_mode === 1) {
  4706. $generateJson[] = [
  4707. 'sequence' => $sequence++,
  4708. 'video_url' => $segment->video_url,
  4709. 'video_time_point_start' => $segment->video_time_point_start,
  4710. 'video_time_point_end' => $segment->video_time_point_end
  4711. ];
  4712. }else {
  4713. $generateJson[] = [
  4714. 'sequence' => $sequence++,
  4715. 'video_url' => $segment->video_url,
  4716. 'audio_url' => $segment->audio_url,
  4717. 'video_time_point_start' => $segment->video_time_point_start,
  4718. 'video_time_point_end' => $segment->video_time_point_end
  4719. ];
  4720. }
  4721. }
  4722. // 创建任务
  4723. $now = date('Y-m-d H:i:s');
  4724. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4725. 'anime_id' => $animeId,
  4726. 'episode_id' => $episodeId,
  4727. 'generate_json' => json_encode($generateJson, 256),
  4728. 'generate_status' => '执行中',
  4729. 'complete_video_url' => '',
  4730. 'created_at' => $now,
  4731. 'updated_at' => $now
  4732. ]);
  4733. if (!$taskId) {
  4734. Utils::throwError('20003:创建任务失败');
  4735. }
  4736. // 更新剧集表的任务ID和状态
  4737. $boolen = DB::table('mp_anime_episodes')
  4738. ->where('anime_id', $animeId)
  4739. ->where('id', $episodeId)
  4740. ->update([
  4741. 'complete_video_task_id' => $taskId,
  4742. 'complete_video_task_status' => '执行中',
  4743. 'updated_at' => $now
  4744. ]);
  4745. if (!$boolen) {
  4746. Utils::throwError('20003:更新剧集表失败');
  4747. }
  4748. dLog('anime')->info('创建完整视频合成任务', [
  4749. 'task_id' => $taskId,
  4750. 'anime_id' => $animeId,
  4751. 'episode_id' => $episodeId,
  4752. 'segment_count' => count($generateJson)
  4753. ]);
  4754. // 请求远程服务器执行生成
  4755. $client = new Client(['timeout' => 600, 'verify' => false]);
  4756. try {
  4757. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4758. $response = $result->getBody()->getContents();
  4759. $response_arr = json_decode($response, true);
  4760. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4761. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4762. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4763. // // 更新任务状态为失败
  4764. // DB::table('mp_complete_video_tasks')
  4765. // ->where('id', $taskId)
  4766. // ->update([
  4767. // 'generate_status' => '执行失败',
  4768. // 'error_message' => $error_msg,
  4769. // 'updated_at' => date('Y-m-d H:i:s')
  4770. // ]);
  4771. // // 同步更新剧集表状态
  4772. // DB::table('mp_anime_episodes')
  4773. // ->where('complete_video_task_id', $taskId)
  4774. // ->update([
  4775. // 'complete_video_task_status' => '执行失败',
  4776. // 'updated_at' => date('Y-m-d H:i:s')
  4777. // ]);
  4778. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4779. }
  4780. } catch (\Exception $e) {
  4781. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4782. // 更新任务状态为失败
  4783. DB::table('mp_complete_video_tasks')
  4784. ->where('id', $taskId)
  4785. ->update([
  4786. 'generate_status' => '执行失败',
  4787. 'error_message' => $e->getMessage(),
  4788. 'updated_at' => date('Y-m-d H:i:s')
  4789. ]);
  4790. // 同步更新剧集表状态
  4791. DB::table('mp_anime_episodes')
  4792. ->where('complete_video_task_id', $taskId)
  4793. ->update([
  4794. 'complete_video_task_status' => '执行失败',
  4795. 'updated_at' => date('Y-m-d H:i:s')
  4796. ]);
  4797. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4798. }
  4799. // 开始轮询任务状态
  4800. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4801. $pollInterval = 5; // 每5秒轮询一次
  4802. $attempt = 0;
  4803. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4804. while ($attempt < $maxAttempts) {
  4805. sleep($pollInterval);
  4806. $attempt++;
  4807. // 查询任务状态
  4808. $task = DB::table('mp_complete_video_tasks')
  4809. ->where('id', $taskId)
  4810. ->first();
  4811. if (!$task) {
  4812. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4813. Utils::throwError('20003:任务不存在');
  4814. }
  4815. dLog('anime')->info('轮询任务状态', [
  4816. 'task_id' => $taskId,
  4817. 'attempt' => $attempt,
  4818. 'status' => $task->generate_status
  4819. ]);
  4820. // 检查任务是否完成
  4821. if ($task->generate_status === '执行成功') {
  4822. // 同步更新剧集表状态
  4823. $boolen3 = DB::table('mp_anime_episodes')
  4824. ->where('anime_id', $animeId)
  4825. ->where('id', $episodeId)
  4826. ->update([
  4827. 'complete_video_url' => $task->complete_video_url,
  4828. 'complete_video_task_status' => '执行成功',
  4829. 'updated_at' => date('Y-m-d H:i:s')
  4830. ]);
  4831. dLog('anime')->info('视频合成任务完成', [
  4832. 'task_id' => $taskId,
  4833. 'video_url' => $task->complete_video_url,
  4834. 'attempts' => $attempt
  4835. ]);
  4836. // 如果更新成功则远程删除之前的文件
  4837. if ($boolen3 && $completeVideoUrl) {
  4838. $encode_url = urlencode($completeVideoUrl);
  4839. $client = new Client(['timeout' => 300, 'verify' => false]);
  4840. // 根据ID通过API通知合成音频
  4841. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4842. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4843. $response = $result->getBody()->getContents();
  4844. $response_arr = json_decode($response, true);
  4845. Log::info('火山删除音频返回: '.$response);
  4846. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4847. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4848. Log::info('火山删除音频失败: '.$error_msg);
  4849. // Utils::throwError('20003:火山删除音频失败');
  4850. }
  4851. }
  4852. return [
  4853. 'task_id' => $taskId,
  4854. 'anime_id' => $animeId,
  4855. 'episode_id' => $episodeId,
  4856. 'segment_count' => count($generateJson),
  4857. 'generate_status' => '执行成功',
  4858. 'complete_video_url' => $task->complete_video_url,
  4859. ];
  4860. }
  4861. // 检查任务是否失败
  4862. if ($task->generate_status === '执行失败') {
  4863. // 同步更新剧集表状态
  4864. DB::table('mp_anime_episodes')
  4865. ->where('anime_id', $animeId)
  4866. ->where('id', $episodeId)
  4867. ->update([
  4868. 'complete_video_task_status' => '执行失败',
  4869. 'updated_at' => date('Y-m-d H:i:s')
  4870. ]);
  4871. $errorMessage = $task->error_message ?? '未知错误';
  4872. dLog('anime')->error('视频合成任务失败', [
  4873. 'task_id' => $taskId,
  4874. 'error' => $errorMessage,
  4875. 'attempts' => $attempt
  4876. ]);
  4877. return [
  4878. 'task_id' => $taskId,
  4879. 'anime_id' => $animeId,
  4880. 'episode_id' => $episodeId,
  4881. 'segment_count' => count($generateJson),
  4882. 'generate_status' => '执行失败',
  4883. 'error_message' => $errorMessage
  4884. ];
  4885. }
  4886. }
  4887. // 超时处理
  4888. dLog('anime')->warning('视频合成任务超时', [
  4889. 'task_id' => $taskId,
  4890. 'max_attempts' => $maxAttempts,
  4891. 'timeout_seconds' => $maxAttempts * $pollInterval
  4892. ]);
  4893. // 更新任务状态为超时
  4894. DB::table('mp_complete_video_tasks')
  4895. ->where('id', $taskId)
  4896. ->update([
  4897. 'generate_status' => '超时',
  4898. 'error_message' => '任务执行超时(5分钟)',
  4899. 'updated_at' => date('Y-m-d H:i:s')
  4900. ]);
  4901. return [
  4902. 'task_id' => $taskId,
  4903. 'anime_id' => $animeId,
  4904. 'episode_id' => $episodeId,
  4905. 'segment_count' => count($generateJson),
  4906. 'generate_status' => '超时',
  4907. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4908. ];
  4909. }
  4910. /**
  4911. * 根据 inner_prompt_type 附加内置提示词
  4912. *
  4913. * @param string $prompt 用户提示词
  4914. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4915. * @return string 合并后的提示词
  4916. */
  4917. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4918. {
  4919. $innerPromptMap = [
  4920. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4921. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4922. ];
  4923. if (!isset($innerPromptMap[$innerPromptType])) {
  4924. return $prompt;
  4925. }
  4926. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4927. }
  4928. /**
  4929. * 根据 inner_prompt_type 获取生成图片数量
  4930. *
  4931. * @param int $innerPromptType 内置提示词类型
  4932. * @param int $imageNum 传入的图片张数
  4933. * @return int 图片数量
  4934. */
  4935. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  4936. {
  4937. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  4938. }
  4939. /**
  4940. * 提取图片生成结果URL
  4941. *
  4942. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4943. * @param int $innerPromptType 内置提示词类型
  4944. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4945. */
  4946. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4947. {
  4948. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4949. if (is_array($resultUrls) && !empty($resultUrls)) {
  4950. $resultUrls = array_values($resultUrls);
  4951. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4952. }
  4953. if (!empty($resultUrl)) {
  4954. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4955. }
  4956. return (int)$innerPromptType === 2 ? [] : '';
  4957. }
  4958. public function generateImg($data) {
  4959. $prompt = getProp($data, 'prompt');
  4960. $episode_id = getProp($data, 'episode_id');
  4961. $ref_img_urls = getProp($data, 'ref_img_urls');
  4962. $ratio = getProp($data, 'ratio', '9:16');
  4963. $resolution = getProp($data, 'resolution', '2k');
  4964. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4965. $imageNum = (int)getProp($data, 'image_num', 1);
  4966. // 定义分辨率和宽高比对应的尺寸映射表
  4967. $sizeMap = [
  4968. '2k' => [
  4969. '1:1' => ['width' => 2048, 'height' => 2048],
  4970. '4:3' => ['width' => 2304, 'height' => 1728],
  4971. '3:4' => ['width' => 1728, 'height' => 2304],
  4972. '16:9' => ['width' => 2848, 'height' => 1600],
  4973. '9:16' => ['width' => 1600, 'height' => 2848],
  4974. '3:2' => ['width' => 2496, 'height' => 1664],
  4975. '2:3' => ['width' => 1664, 'height' => 2496],
  4976. '21:9' => ['width' => 3136, 'height' => 1344],
  4977. ],
  4978. '3k' => [
  4979. '1:1' => ['width' => 3072, 'height' => 3072],
  4980. '4:3' => ['width' => 3456, 'height' => 2592],
  4981. '3:4' => ['width' => 2592, 'height' => 3456],
  4982. '16:9' => ['width' => 4096, 'height' => 2304],
  4983. '9:16' => ['width' => 2304, 'height' => 4096],
  4984. '2:3' => ['width' => 2496, 'height' => 3744],
  4985. '3:2' => ['width' => 3744, 'height' => 2496],
  4986. '21:9' => ['width' => 4704, 'height' => 2016],
  4987. ],
  4988. '4k' => [
  4989. '1:1' => ['width' => 4096, 'height' => 4096],
  4990. '3:4' => ['width' => 3520, 'height' => 4704],
  4991. '4:3' => ['width' => 4704, 'height' => 3520],
  4992. '16:9' => ['width' => 5504, 'height' => 3040],
  4993. '9:16' => ['width' => 3040, 'height' => 5504],
  4994. '2:3' => ['width' => 3328, 'height' => 4992],
  4995. '3:2' => ['width' => 4992, 'height' => 3328],
  4996. '21:9' => ['width' => 6240, 'height' => 2656],
  4997. ],
  4998. ];
  4999. // 参数验证
  5000. $resolution = strtolower($resolution);
  5001. if (!isset($sizeMap[$resolution])) {
  5002. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5003. }
  5004. if (!isset($sizeMap[$resolution][$ratio])) {
  5005. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5006. }
  5007. // 根据 ratio 和 resolution 确定宽高
  5008. $width = $sizeMap[$resolution][$ratio]['width'];
  5009. $height = $sizeMap[$resolution][$ratio]['height'];
  5010. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5011. if (is_json($ref_img_urls)) {
  5012. $ref_img_urls = json_decode($ref_img_urls, true);
  5013. }else {
  5014. $ref_img_urls = explode(',', $ref_img_urls);
  5015. }
  5016. }
  5017. // 处理图片模型
  5018. $model = getProp($data, 'model');
  5019. if (!$model) {
  5020. // 用户没有输入,从episode表获取
  5021. if ($episode_id) {
  5022. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5023. $model = getProp($episode, 'image_model');
  5024. }
  5025. if (!$model) {
  5026. // episode表也没有,使用默认值
  5027. $model = 'doubao-seedream-5-0-lite-260128';
  5028. }
  5029. }
  5030. // 验证模型是否在可用模型表中
  5031. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5032. // $model = 'doubao-seedream-5-0-lite-260128';
  5033. Utils::throwError('20003:该模型已不可用,请更换!');
  5034. }
  5035. // 保存到episode表
  5036. if ($episode_id) {
  5037. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5038. 'image_model' => $model,
  5039. 'updated_at' => date('Y-m-d H:i:s')
  5040. ]);
  5041. }
  5042. // 参数验证
  5043. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5044. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5045. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5046. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5047. try {
  5048. // 创建图片生成任务
  5049. $params = [
  5050. 'prompt' => $prompt,
  5051. 'model' => $model,
  5052. 'ref_img_urls' => '',
  5053. 'width' => $width,
  5054. 'height' => $height,
  5055. 'image_num' => $imageNum
  5056. ];
  5057. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5058. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5059. $task_id = $task->id;
  5060. if (!$task_id) {
  5061. Utils::throwError('20003:创建图片生成任务失败');
  5062. }
  5063. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5064. $model = getProp($task, 'model');
  5065. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5066. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5067. $isSyncModel = $isVolcModel || $isGptModel;
  5068. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5069. $start_time = time();
  5070. $timeout = 300; // 5分钟
  5071. $img_url = '';
  5072. $img_urls = [];
  5073. while (time() - $start_time < $timeout) {
  5074. sleep(3);
  5075. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5076. if ($isSyncModel) {
  5077. // 刷新任务状态
  5078. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5079. if ($task->status === 'success' && $task->result_url) {
  5080. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5081. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5082. if (!empty($resultUrls)) {
  5083. $img_urls = $resultUrls;
  5084. $img_url = $resultUrls[0];
  5085. } else {
  5086. $img_url = (string)$task->result_url;
  5087. }
  5088. break;
  5089. } elseif ($task->status === 'failed') {
  5090. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5091. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5092. }
  5093. // // 如果还在处理中,提示用户稍后查看
  5094. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5095. }else {
  5096. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5097. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5098. if ($statusInfo['status'] === 'success') {
  5099. $task->updateStatus('success', [
  5100. 'result_url' => $statusInfo['result_url'],
  5101. 'result_json' => $statusInfo['result_json'] ?? []
  5102. ]);
  5103. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5104. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5105. if (!empty($resultUrls)) {
  5106. $img_urls = $resultUrls;
  5107. $img_url = $resultUrls[0];
  5108. } else {
  5109. $img_url = (string)$statusInfo['result_url'];
  5110. }
  5111. break;
  5112. } elseif ($statusInfo['status'] === 'failed') {
  5113. $task->updateStatus('failed', [
  5114. 'error_message' => $statusInfo['error_message'],
  5115. 'result_json' => $statusInfo['result_json'] ?? []
  5116. ]);
  5117. dLog('anime')->error('图片生成失败,', [
  5118. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5119. ]);
  5120. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5121. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5122. }
  5123. }
  5124. }
  5125. if (empty($img_url)) {
  5126. Utils::throwError('20003:图片生成超时,请稍后重试');
  5127. }
  5128. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5129. if (count($img_urls) > 1) {
  5130. return [
  5131. 'img_url' => $img_url,
  5132. 'image_urls' => $img_urls
  5133. ];
  5134. }
  5135. return $img_url;
  5136. } catch (\Exception $e) {
  5137. dLog('anime')->error('更新角色或场景失败', [
  5138. 'error' => $e->getMessage()
  5139. ]);
  5140. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5141. Utils::throwError('20003:' . $e->getMessage());
  5142. }
  5143. }
  5144. /**
  5145. * 使用文生文模型解析分镜内容
  5146. */
  5147. private function parseSegmentContentWithAI($segment_content) {
  5148. try {
  5149. // 使用DeepSeek服务的公开方法解析分镜内容
  5150. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5151. } catch (\Exception $e) {
  5152. // 如果AI解析失败,记录日志并返回原内容
  5153. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5154. return $segment_content;
  5155. }
  5156. }
  5157. /**
  5158. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5159. *
  5160. * @param int $episode_id 分集ID
  5161. * @param int $anime_id 动漫ID
  5162. * @param array $roles 分集角色数组(引用传递)
  5163. * @param array $scenes 分集场景数组(引用传递)
  5164. * @param array $episode 分集数据
  5165. */
  5166. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5167. // 获取全局动漫的角色和场景数据
  5168. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5169. if (!$anime) return;
  5170. $art_style_type = getProp($anime, 'art_style_type');
  5171. $character_prefix = '';
  5172. $scene_prefix = '';
  5173. if ($art_style_type) {
  5174. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5175. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5176. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5177. }
  5178. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5179. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5180. $roles_updated = false;
  5181. $scenes_updated = false;
  5182. // 处理角色
  5183. foreach ($roles as &$role) {
  5184. $role_name = getProp($role, 'role');
  5185. $role_description = getProp($role, 'description');
  5186. $role_pic_prompt = getProp($role, 'pic_prompt');
  5187. $role_url = getProp($role, 'url');
  5188. $role_task_id = getProp($role, 'task_id');
  5189. // 如果已有URL或已有任务ID,跳过
  5190. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5191. continue;
  5192. }
  5193. $url_inherited = false;
  5194. // 尝试从全局数据中继承
  5195. foreach ($global_roles as $global_role) {
  5196. $global_role_name = getProp($global_role, 'role');
  5197. $global_role_description = getProp($global_role, 'description');
  5198. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5199. $global_role_url = getProp($global_role, 'url');
  5200. $global_role_task_id = getProp($global_role, 'task_id');
  5201. $global_role_task_status = getProp($global_role, 'task_status');
  5202. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5203. if ($role_name === $global_role_name
  5204. && $role_description === $global_role_description
  5205. && $role_pic_prompt === $global_role_pic_prompt
  5206. && !empty($global_role_url)) {
  5207. // 继承 task_id、task_status 和 url
  5208. $role['task_id'] = $global_role_task_id;
  5209. $role['task_status'] = $global_role_task_status;
  5210. $role['url'] = $global_role_url;
  5211. $roles_updated = true;
  5212. $url_inherited = true;
  5213. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5214. break;
  5215. }
  5216. }
  5217. // 如果无法继承且没有任务ID,创建新任务
  5218. if (!$url_inherited && empty($role_task_id)) {
  5219. try {
  5220. $art_style = getProp($episode, 'art_style');
  5221. // 优先使用 pic_prompt,如果没有则使用 description
  5222. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5223. // if ($art_style) {
  5224. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5225. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5226. // }
  5227. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5228. $params = [
  5229. 'prompt' => $description,
  5230. 'ref_img_urls' => []
  5231. ];
  5232. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5233. $task_id = $task->id;
  5234. if ($task_id) {
  5235. $role['task_id'] = $task_id;
  5236. $role['task_status'] = 'processing';
  5237. $roles_updated = true;
  5238. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5239. }
  5240. } catch (\Exception $e) {
  5241. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5242. }
  5243. }
  5244. }
  5245. // 处理场景
  5246. foreach ($scenes as &$scene) {
  5247. $scene_name = getProp($scene, 'scene');
  5248. $scene_description = getProp($scene, 'description');
  5249. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5250. $scene_url = getProp($scene, 'url');
  5251. $scene_task_id = getProp($scene, 'task_id');
  5252. // 如果已有URL或已有任务ID,跳过
  5253. if (!empty($scene_url) || !empty($scene_task_id)) {
  5254. continue;
  5255. }
  5256. $url_inherited = false;
  5257. // 尝试从全局数据中继承
  5258. foreach ($global_scenes as $global_scene) {
  5259. $global_scene_name = getProp($global_scene, 'scene');
  5260. $global_scene_description = getProp($global_scene, 'description');
  5261. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5262. $global_scene_url = getProp($global_scene, 'url');
  5263. $global_scene_task_id = getProp($global_scene, 'task_id');
  5264. $global_scene_task_status = getProp($global_scene, 'task_status');
  5265. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5266. if ($scene_name === $global_scene_name
  5267. && $scene_description === $global_scene_description
  5268. && $scene_pic_prompt === $global_scene_pic_prompt
  5269. && !empty($global_scene_url)) {
  5270. // 继承 task_id、task_status 和 url
  5271. $scene['task_id'] = $global_scene_task_id;
  5272. $scene['task_status'] = $global_scene_task_status;
  5273. $scene['url'] = $global_scene_url;
  5274. $scenes_updated = true;
  5275. $url_inherited = true;
  5276. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5277. break;
  5278. }
  5279. }
  5280. // 如果无法继承且没有任务ID,创建新任务
  5281. if (!$url_inherited && empty($scene_task_id)) {
  5282. try {
  5283. $art_style = getProp($episode, 'art_style');
  5284. // 优先使用 pic_prompt,如果没有则使用 description
  5285. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5286. // if ($art_style) {
  5287. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5288. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5289. // }
  5290. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5291. $params = [
  5292. 'prompt' => $description,
  5293. 'ref_img_urls' => []
  5294. ];
  5295. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5296. $task_id = $task->id;
  5297. if ($task_id) {
  5298. $scene['task_id'] = $task_id;
  5299. $scene['task_status'] = 'processing';
  5300. $scenes_updated = true;
  5301. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5302. }
  5303. } catch (\Exception $e) {
  5304. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5305. }
  5306. }
  5307. }
  5308. // 如果有更新,保存到数据库
  5309. if ($roles_updated || $scenes_updated) {
  5310. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5311. if ($roles_updated) {
  5312. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5313. }
  5314. if ($scenes_updated) {
  5315. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5316. }
  5317. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5318. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5319. }
  5320. }
  5321. /**
  5322. * 根据图片URL使用AI反推图片提示词
  5323. *
  5324. * @param string $img_url 图片URL
  5325. * @return string 反推的提示词
  5326. */
  5327. private function generateImagePromptFromUrl($img_url) {
  5328. try {
  5329. // 获取默认模型
  5330. $model = 'doubao-seed-2-0-mini-260215';
  5331. // 构建messages参数
  5332. $messages = [
  5333. [
  5334. 'role' => 'user',
  5335. 'content' => [
  5336. [
  5337. 'type' => 'text',
  5338. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5339. ],
  5340. [
  5341. 'type' => 'image_url',
  5342. 'image_url' => [
  5343. 'url' => $img_url
  5344. ]
  5345. ]
  5346. ]
  5347. ]
  5348. ];
  5349. // 构建请求参数
  5350. $params = [
  5351. 'model' => $model,
  5352. 'messages' => $messages,
  5353. 'stream' => false,
  5354. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5355. ];
  5356. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5357. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5358. // 返回生成的内容
  5359. return getProp($result, 'fullContent', '图片描述生成失败');
  5360. } catch (\Exception $e) {
  5361. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5362. 'img_url' => $img_url
  5363. ]);
  5364. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5365. 'error' => $e->getMessage(),
  5366. 'img_url' => $img_url
  5367. ]);
  5368. return '图片描述生成失败: ' . $e->getMessage();
  5369. }
  5370. }
  5371. /**
  5372. * 音频试听接口
  5373. * 创建音频任务并轮询获取结果
  5374. *
  5375. * @param array $data 参数数组
  5376. * @return array 返回音频URL或错误信息
  5377. */
  5378. public function previewAudio($data) {
  5379. $dialogue = getProp($data, 'dialogue');
  5380. // 必填参数验证
  5381. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5382. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5383. $voice_type = getProp($data, 'voice_type');
  5384. $voice_name = getProp($data, 'voice_name');
  5385. $voice_actor = getProp($data, 'voice_actor');
  5386. $emotion_type = getProp($data, 'emotion_type');
  5387. $gender = getProp($data, 'gender', 0);
  5388. $emotion = getProp($data, 'emotion');
  5389. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5390. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5391. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5392. $pitch = getProp($data, 'pitch', 0);
  5393. try {
  5394. $now = date('Y-m-d H:i:s');
  5395. // 构建生成参数
  5396. $generate_json = json_encode([
  5397. 'text' => $dialogue,
  5398. 'role' => $voice_actor,
  5399. 'voice_type' => $voice_type,
  5400. 'voice_name' => $voice_name,
  5401. 'emotion' => $emotion,
  5402. 'emotion_type' => $emotion_type,
  5403. 'gender' => $gender,
  5404. 'speed_ratio' => $speed_ratio,
  5405. 'loudness_ratio' => $loudness_ratio,
  5406. 'emotion_scale' => $emotion_scale,
  5407. 'pitch' => $pitch,
  5408. ], 256);
  5409. // 请求远程服务器执行生成
  5410. $client = new Client(['timeout' => 600, 'verify' => false]);
  5411. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5412. $response = $result->getBody()->getContents();
  5413. $response_arr = json_decode($response, true);
  5414. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5415. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5416. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5417. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5418. }
  5419. $arr = $response_arr['data'];
  5420. $subtitle_info = $arr['subtitle_info'];
  5421. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5422. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5423. return [
  5424. 'audio_url' => $arr['url'],
  5425. 'subtitle_info' => $subtitle_info,
  5426. 'audio_duration' => round($audio_duration, 2)
  5427. ];
  5428. } catch (\Exception $e) {
  5429. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5430. Utils::throwError('20003:' . $e->getMessage());
  5431. }
  5432. }
  5433. /**
  5434. * 获取角色库列表(支持文件夹递归查询)
  5435. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5436. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5437. */
  5438. public function globalProducts($data) {
  5439. $uid = Site::getUid();
  5440. $cpid = Site::getCpid();
  5441. $role = Site::getRole();
  5442. $id = getProp($data, 'id', 0);
  5443. $parent_id = getProp($data, 'parent_id', 0);
  5444. $product_name = getProp($data, 'product_name');
  5445. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5446. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5447. if (!$product) {
  5448. Utils::throwError('20003:请选择产品类型');
  5449. }
  5450. // 根据角色和is_public参数确定查询范围
  5451. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5452. // user角色:根据is_public参数筛选
  5453. $query_user_ids = [];
  5454. if ($role === 'admin') {
  5455. // admin获取所有个人库和公共库
  5456. $query_user_ids = [$uid, 0];
  5457. } else {
  5458. // user角色根据is_public参数筛选
  5459. if ($is_public == 2) {
  5460. // 个人库+公共库
  5461. $query_user_ids = [$uid, 0];
  5462. } elseif ($is_public == 0) {
  5463. // 仅个人库
  5464. $query_user_ids = [$uid];
  5465. } elseif ($is_public == 1) {
  5466. // 仅公共库
  5467. $query_user_ids = [0];
  5468. }
  5469. }
  5470. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5471. if ($id || $product_name) {
  5472. $query = DB::table('mp_products')
  5473. ->where('cpid', $cpid)
  5474. ->whereIn('user_id', $query_user_ids)
  5475. ->where('is_deleted', 0);
  5476. // 如果指定了 id,按 id 精确查询
  5477. if ($id) {
  5478. $query->where('id', $id);
  5479. }
  5480. // 如果指定了 product_name,按名称模糊查询
  5481. if ($product_name) {
  5482. $query->where('product_name', 'like', "%{$product_name}%");
  5483. }
  5484. // 如果指定了 product,添加筛选条件
  5485. if ($product) {
  5486. $query->where('product', $product);
  5487. }
  5488. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5489. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5490. ->get()
  5491. ->map(function($value) {
  5492. $value = (array)$value;
  5493. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5494. $value['type'] = (int)$value['type'];
  5495. $value['parent_id'] = (int)$value['parent_id'];
  5496. $value['level'] = (int)$value['level'];
  5497. $value['product'] = (int)($value['product'] ?? 1);
  5498. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5499. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5500. unset($value['user_id']);
  5501. return $value;
  5502. })
  5503. ->toArray();
  5504. return $result;
  5505. }
  5506. // 递归获取所有子目录和角色
  5507. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5508. }
  5509. /**
  5510. * 递归获取指定目录下的所有子目录和角色
  5511. * @param int $cpid 公司ID
  5512. * @param int $parent_id 父目录ID
  5513. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5514. * @param array $query_user_ids 用户ID数组(支持多个)
  5515. * @param int $current_uid 当前用户ID(用于排序)
  5516. * @return array
  5517. */
  5518. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5519. // 查询当前层级的所有项(文件夹和角色)
  5520. $query = DB::table('mp_products')
  5521. ->where('cpid', $cpid)
  5522. ->where('is_deleted', 0)
  5523. ->where('parent_id', $parent_id);
  5524. // 添加用户ID验证(支持多个user_id)
  5525. if (!empty($query_user_ids)) {
  5526. $query->whereIn('user_id', $query_user_ids);
  5527. }
  5528. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5529. if ($product) {
  5530. $query->where('product', $product);
  5531. }
  5532. // 排序规则:
  5533. // 1. 文件夹在前(type DESC)
  5534. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5535. // 3. 其他排序规则
  5536. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5537. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5538. ->get();
  5539. $result = [];
  5540. foreach ($items as $item) {
  5541. $itemArray = [
  5542. 'id' => $item->id,
  5543. 'type' => (int)$item->type,
  5544. 'parent_id' => (int)$item->parent_id,
  5545. 'level' => (int)$item->level,
  5546. 'product_name' => $item->product_name,
  5547. 'url' => $item->url,
  5548. 'pic_prompt' => $item->pic_prompt ?? '',
  5549. 'three_view_image_url' => $item->three_view_image_url,
  5550. 'product' => (int)($item->product ?? 1),
  5551. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5552. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5553. ];
  5554. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5555. // 如果是文件夹,递归获取其子项
  5556. if ($item->type == 2) {
  5557. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5558. if (!empty($children)) {
  5559. $itemArray['children'] = $children;
  5560. }
  5561. }
  5562. $result[] = $itemArray;
  5563. }
  5564. return $result;
  5565. }
  5566. /**
  5567. * 创建文件夹
  5568. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5569. * @return int 返回新建文件夹ID
  5570. */
  5571. public function createFolder($data) {
  5572. $uid = Site::getUid();
  5573. $cpid = Site::getCpid();
  5574. $role = Site::getRole();
  5575. $parent_id = getProp($data, 'parent_id', 0);
  5576. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5577. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5578. // 如果是公共库操作,需要admin权限
  5579. if ($is_public && $role !== 'admin') {
  5580. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5581. }
  5582. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5583. $store_uid = $is_public ? 0 : $uid;
  5584. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5585. $product = getProp($data, 'product');
  5586. if (!in_array($product, [1, 2, 3])) {
  5587. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5588. }
  5589. // 验证父文件夹
  5590. $parent_level = 0;
  5591. if ($parent_id > 0) {
  5592. $parent = DB::table('mp_products')
  5593. ->where('id', $parent_id)
  5594. ->where('cpid', $cpid)
  5595. ->where('user_id', $store_uid)
  5596. ->where('type', 2)
  5597. ->where('is_deleted', 0)
  5598. ->first();
  5599. if (!$parent) {
  5600. Utils::throwError('20003:父文件夹不存在');
  5601. }
  5602. // 检查父文件夹的 product 类型是否一致
  5603. if ($parent->product != $product) {
  5604. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5605. }
  5606. $parent_level = $parent->level;
  5607. // 检查层级限制(最多3层)
  5608. if ($parent_level >= 3) {
  5609. Utils::throwError('20003:文件夹层级不能超过3层');
  5610. }
  5611. }
  5612. // 检查当前目录下是否已存在空白文件夹
  5613. $empty_folder_exists = DB::table('mp_products')
  5614. ->where('parent_id', $parent_id)
  5615. ->where('cpid', $cpid)
  5616. ->where('user_id', $store_uid)
  5617. ->where('type', 2)
  5618. ->where('product', $product)
  5619. ->where('product_name', '新建文件夹')
  5620. ->where('is_deleted', 0)
  5621. ->exists();
  5622. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5623. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5624. }
  5625. // 创建文件夹
  5626. $folder_id = DB::table('mp_products')->insertGetId([
  5627. 'user_id' => $store_uid,
  5628. 'cpid' => $cpid,
  5629. 'type' => 2,
  5630. 'parent_id' => $parent_id,
  5631. 'level' => $parent_level + 1,
  5632. 'product_name' => $folder_name,
  5633. 'product' => $product,
  5634. 'sort_order' => time(), // 使用时间戳作为排序权重
  5635. 'is_deleted' => 0,
  5636. 'created_at' => date('Y-m-d H:i:s'),
  5637. 'updated_at' => date('Y-m-d H:i:s')
  5638. ]);
  5639. return [
  5640. 'id' => $folder_id,
  5641. 'type' => 2,
  5642. 'parent_id' => $parent_id,
  5643. 'level' => $parent_level + 1,
  5644. 'product_name' => $folder_name,
  5645. 'product' => $product,
  5646. ];
  5647. }
  5648. /**
  5649. * 重命名文件夹或角色
  5650. * @param array $data 包含 id、product_name(新名称)
  5651. * @return bool
  5652. */
  5653. public function renameFolder($data) {
  5654. $uid = Site::getUid();
  5655. $cpid = Site::getCpid();
  5656. $role = Site::getRole();
  5657. $id = getProp($data, 'id');
  5658. $new_name = getProp($data, 'product_name');
  5659. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5660. if (!$id || !$new_name) {
  5661. Utils::throwError('20003:参数不完整');
  5662. }
  5663. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5664. $query_uid = $is_public ? 0 : $uid;
  5665. // 如果是公共库操作,需要admin权限
  5666. if ($is_public && $role !== 'admin') {
  5667. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5668. }
  5669. // 检查是否存在
  5670. $item = DB::table('mp_products')
  5671. ->where('id', $id)
  5672. ->where('cpid', $cpid)
  5673. ->where('user_id', $query_uid)
  5674. ->where('is_deleted', 0)
  5675. ->first();
  5676. if (!$item) {
  5677. Utils::throwError('20003:项目不存在');
  5678. }
  5679. return DB::table('mp_products')
  5680. ->where('id', $id)
  5681. ->where('cpid', $cpid)
  5682. ->where('user_id', $query_uid)
  5683. ->update([
  5684. 'product_name' => $new_name,
  5685. 'updated_at' => date('Y-m-d H:i:s')
  5686. ]);
  5687. }
  5688. /**
  5689. * 移动角色或文件夹到指定文件夹
  5690. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5691. * @return bool
  5692. */
  5693. public function moveProductOrFolder($data) {
  5694. $uid = Site::getUid();
  5695. $cpid = Site::getCpid();
  5696. $role = Site::getRole();
  5697. $id = getProp($data, 'id');
  5698. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5699. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5700. if (!$id) {
  5701. Utils::throwError('20003:请选择要移动的项目');
  5702. }
  5703. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5704. $query_uid = $is_public ? 0 : $uid;
  5705. // 如果是公共库操作,需要admin权限
  5706. if ($is_public && $role !== 'admin') {
  5707. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5708. }
  5709. // 检查要移动的项目
  5710. $item = DB::table('mp_products')
  5711. ->where('id', $id)
  5712. ->where('cpid', $cpid)
  5713. ->where('user_id', $query_uid)
  5714. ->where('is_deleted', 0)
  5715. ->first();
  5716. if (!$item) {
  5717. Utils::throwError('20003:项目不存在');
  5718. }
  5719. // 验证目标文件夹
  5720. $target_level = 0;
  5721. $target_product = $item->product; // 默认使用当前项目的 product
  5722. if ($target_parent_id > 0) {
  5723. $target_parent = DB::table('mp_products')
  5724. ->where('id', $target_parent_id)
  5725. ->where('cpid', $cpid)
  5726. ->where('user_id', $query_uid)
  5727. ->where('type', 2)
  5728. ->where('is_deleted', 0)
  5729. ->first();
  5730. if (!$target_parent) {
  5731. Utils::throwError('20003:目标文件夹不存在');
  5732. }
  5733. // 检查 product 类型是否一致
  5734. if ($target_parent->product != $item->product) {
  5735. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5736. }
  5737. $target_level = $target_parent->level;
  5738. $target_product = $target_parent->product;
  5739. // 如果移动的是文件夹,需要检查层级
  5740. if ($item->type == 2) {
  5741. // 计算移动后的最大层级
  5742. $max_child_level = $this->getMaxChildLevel($id);
  5743. $depth = $max_child_level - $item->level;
  5744. if ($target_level + 1 + $depth > 3) {
  5745. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5746. }
  5747. // 不能移动到自己或自己的子文件夹下
  5748. if ($this->isDescendant($target_parent_id, $id)) {
  5749. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5750. }
  5751. }
  5752. }
  5753. // 更新父文件夹和层级
  5754. $new_level = $target_level + 1;
  5755. DB::table('mp_products')
  5756. ->where('id', $id)
  5757. ->update([
  5758. 'parent_id' => $target_parent_id,
  5759. 'level' => $new_level,
  5760. 'updated_at' => date('Y-m-d H:i:s')
  5761. ]);
  5762. // 如果是文件夹,需要递归更新所有子项的层级
  5763. if ($item->type == 2) {
  5764. $this->updateChildrenLevel($id, $new_level);
  5765. }
  5766. return true;
  5767. }
  5768. /**
  5769. * 获取文件夹下最大子层级
  5770. * @param int $folder_id
  5771. * @return int
  5772. */
  5773. private function getMaxChildLevel($folder_id) {
  5774. $max_level = DB::table('mp_products')
  5775. ->where('parent_id', $folder_id)
  5776. ->where('is_deleted', 0)
  5777. ->max('level');
  5778. if (!$max_level) {
  5779. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5780. }
  5781. // 递归查找子文件夹
  5782. $children = DB::table('mp_products')
  5783. ->where('parent_id', $folder_id)
  5784. ->where('type', 2)
  5785. ->where('is_deleted', 0)
  5786. ->pluck('id');
  5787. foreach ($children as $child_id) {
  5788. $child_max = $this->getMaxChildLevel($child_id);
  5789. if ($child_max > $max_level) {
  5790. $max_level = $child_max;
  5791. }
  5792. }
  5793. return $max_level;
  5794. }
  5795. /**
  5796. * 检查 target_id 是否是 folder_id 的后代
  5797. * @param int $target_id
  5798. * @param int $folder_id
  5799. * @return bool
  5800. */
  5801. private function isDescendant($target_id, $folder_id) {
  5802. if ($target_id == $folder_id) {
  5803. return true;
  5804. }
  5805. $parent = DB::table('mp_products')
  5806. ->where('id', $target_id)
  5807. ->where('is_deleted', 0)
  5808. ->first();
  5809. if (!$parent || $parent->parent_id == 0) {
  5810. return false;
  5811. }
  5812. return $this->isDescendant($parent->parent_id, $folder_id);
  5813. }
  5814. /**
  5815. * 递归更新子项层级
  5816. * @param int $parent_id
  5817. * @param int $parent_level
  5818. */
  5819. private function updateChildrenLevel($parent_id, $parent_level) {
  5820. $children = DB::table('mp_products')
  5821. ->where('parent_id', $parent_id)
  5822. ->where('is_deleted', 0)
  5823. ->get();
  5824. foreach ($children as $child) {
  5825. $new_level = $parent_level + 1;
  5826. DB::table('mp_products')
  5827. ->where('id', $child->id)
  5828. ->update([
  5829. 'level' => $new_level,
  5830. 'updated_at' => date('Y-m-d H:i:s')
  5831. ]);
  5832. // 如果是文件夹,继续递归
  5833. if ($child->type == 2) {
  5834. $this->updateChildrenLevel($child->id, $new_level);
  5835. }
  5836. }
  5837. }
  5838. /**
  5839. * 获取文件夹路径(面包屑导航)
  5840. * @param array $data 包含 folder_id
  5841. * @return array 返回路径数组
  5842. */
  5843. public function getFolderPath($data) {
  5844. $uid = Site::getUid();
  5845. $cpid = Site::getCpid();
  5846. $folder_id = getProp($data, 'id', 0);
  5847. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5848. if ($folder_id == 0) {
  5849. return [
  5850. ['id' => 0, 'name' => '根目录']
  5851. ];
  5852. }
  5853. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5854. $query_uid = $is_public ? 0 : $uid;
  5855. $path = [];
  5856. $current_id = $folder_id;
  5857. while ($current_id > 0) {
  5858. $folder = DB::table('mp_products')
  5859. ->where('id', $current_id)
  5860. ->where('cpid', $cpid)
  5861. ->where('user_id', $query_uid)
  5862. ->where('type', 2)
  5863. ->where('is_deleted', 0)
  5864. ->first();
  5865. if (!$folder) {
  5866. break;
  5867. }
  5868. array_unshift($path, [
  5869. 'id' => $folder->id,
  5870. 'name' => $folder->product_name
  5871. ]);
  5872. $current_id = $folder->parent_id;
  5873. }
  5874. // 添加根目录
  5875. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5876. return $path;
  5877. }
  5878. public function createProduct($data) {
  5879. $uid = Site::getUid();
  5880. $cpid = Site::getCpid();
  5881. $role = Site::getRole();
  5882. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5883. // 如果是公共库操作,需要admin权限
  5884. if ($is_public && $role !== 'admin') {
  5885. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5886. }
  5887. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5888. $store_uid = $is_public ? 0 : $uid;
  5889. // 新增参数:剧本ID和剧集序号(多个序号用英文逗号隔开)
  5890. $script_id = (int)getProp($data, 'script_id', 0);
  5891. $episode_number = trim(getProp($data, 'episode_number', ''));
  5892. if ($script_id && $episode_number === '') {
  5893. Utils::throwError('20003:剧集序号不能为空');
  5894. }
  5895. if (!$script_id && $episode_number !== '') {
  5896. Utils::throwError('20003:请提供剧本ID');
  5897. }
  5898. $product_name = trim(getProp($data, 'product_name'));
  5899. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5900. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5901. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5902. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5903. $url = trim(getProp($data, 'url'));
  5904. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5905. $versions = getProp($data, 'versions');
  5906. // 检查是否是正确的图片格式
  5907. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5908. $urlPath = parse_url($url, PHP_URL_PATH);
  5909. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5910. if (!in_array($extension, $allowedExtensions)) {
  5911. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5912. }
  5913. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5914. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5915. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5916. $product = getProp($data, 'product');
  5917. if (!in_array($product, [1, 2, 3])) {
  5918. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5919. }
  5920. // 获取父文件夹ID和层级
  5921. $parent_id = getProp($data, 'parent_id', 0);
  5922. $parent_level = 0;
  5923. if ($parent_id > 0) {
  5924. $parent = DB::table('mp_products')
  5925. ->where('id', $parent_id)
  5926. ->where('cpid', $cpid)
  5927. ->where('user_id', $store_uid)
  5928. ->where('type', 2)
  5929. ->where('is_deleted', 0)
  5930. ->first();
  5931. if (!$parent) {
  5932. Utils::throwError('20003:父文件夹不存在');
  5933. }
  5934. $parent_level = $parent->level;
  5935. }
  5936. // 创建资产并保存剧本资产关联关系(同一事务)
  5937. DB::beginTransaction();
  5938. try {
  5939. $id = DB::table('mp_products')->insertGetId([
  5940. 'user_id' => $store_uid,
  5941. 'cpid' => $cpid,
  5942. 'type' => 1, // 1=角色图片
  5943. 'parent_id' => $parent_id,
  5944. 'level' => $parent_level + 1,
  5945. 'product_name' => $product_name,
  5946. 'url' => $url,
  5947. 'pic_prompt' => $pic_prompt,
  5948. 'product' => $product,
  5949. 'versions' => json_encode($versions, 256),
  5950. 'sort_order' => time(), // 使用时间戳作为排序权重
  5951. 'created_at' => date('Y-m-d H:i:s'),
  5952. 'updated_at' => date('Y-m-d H:i:s')
  5953. ]);
  5954. if (!$id) Utils::throwError('20003:创建失败');
  5955. // 保存剧本资产关联关系
  5956. if ($script_id) {
  5957. $this->saveProductScriptMapping($id, $script_id, $episode_number);
  5958. }
  5959. DB::commit();
  5960. } catch (\Exception $e) {
  5961. DB::rollback();
  5962. throw $e;
  5963. }
  5964. return [
  5965. 'id' => $id,
  5966. 'type' => 1,
  5967. 'parent_id' => $parent_id,
  5968. 'level' => $parent_level + 1,
  5969. 'product_name' => $product_name,
  5970. 'url' => $url,
  5971. 'pic_prompt' => $pic_prompt,
  5972. 'product' => $product,
  5973. 'versions' => $versions
  5974. ];
  5975. }
  5976. public function editProduct($data) {
  5977. $uid = Site::getUid();
  5978. $cpid = Site::getCpid();
  5979. $role = Site::getRole();
  5980. $id = getProp($data, 'id');
  5981. if (!$id) Utils::throwError('20003:ID不能为空');
  5982. $versions = getProp($data, 'versions');
  5983. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5984. // 新增参数:剧本ID和剧集序号(多个序号用英文逗号隔开)
  5985. $script_id = (int)getProp($data, 'script_id', 0);
  5986. $episode_number = trim(getProp($data, 'episode_number', ''));
  5987. if ($script_id && $episode_number === '') {
  5988. Utils::throwError('20003:剧集序号不能为空');
  5989. }
  5990. if (!$script_id && $episode_number !== '') {
  5991. Utils::throwError('20003:请提供剧本ID');
  5992. }
  5993. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5994. $query_uid = $is_public ? 0 : $uid;
  5995. // 如果是公共库操作,需要admin权限
  5996. if ($is_public && $role !== 'admin') {
  5997. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5998. }
  5999. // 检查是否存在且属于当前用户或公共库
  6000. $role = DB::table('mp_products')
  6001. ->where('id', $id)
  6002. ->where('cpid', $cpid)
  6003. ->where('user_id', $query_uid)
  6004. ->where('type', 1)->first();
  6005. if (!$role) Utils::throwError('20003:记录不存在');
  6006. $updateData = [];
  6007. // $needVersionRecord = false; // 是否需要记录版本
  6008. // 名称
  6009. $product_name = trim(getProp($data, 'product_name'));
  6010. if ($product_name) {
  6011. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6012. $updateData['product_name'] = $product_name;
  6013. }
  6014. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6015. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6016. // 图片地址
  6017. $url = trim(getProp($data, 'url'));
  6018. if ($url) {
  6019. // 检查是否是正确的图片格式
  6020. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6021. $urlPath = parse_url($url, PHP_URL_PATH);
  6022. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6023. if (!in_array($extension, $allowedExtensions)) {
  6024. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6025. }
  6026. // // 如果 url 有变更,记录版本
  6027. // if ($url !== $role->url) {
  6028. // $needVersionRecord = true;
  6029. // }
  6030. $updateData['url'] = $url;
  6031. }
  6032. // 提示词
  6033. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6034. if ($pic_prompt) {
  6035. // // 如果 pic_prompt 有变更,记录版本
  6036. // if ($pic_prompt !== $role->pic_prompt) {
  6037. // $needVersionRecord = true;
  6038. // }
  6039. $updateData['pic_prompt'] = $pic_prompt;
  6040. }
  6041. if (empty($updateData) && !$script_id) {
  6042. Utils::throwError('20003:没有需要更新的数据');
  6043. }
  6044. // // 如果需要记录版本,将数据添加到 versions 数组
  6045. // if ($needVersionRecord) {
  6046. // // 获取现有的 versions 数据
  6047. // $versions = json_decode($role->versions, true) ?: [];
  6048. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6049. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6050. // if ($isFirstVersion) {
  6051. // $oldVersion = [
  6052. // 'url' => $role->url,
  6053. // 'description' => $role->pic_prompt,
  6054. // ];
  6055. // // 旧版本添加到数组末尾
  6056. // $versions[] = $oldVersion;
  6057. // }
  6058. // // 构建新版本(变更后)
  6059. // $newVersion = [
  6060. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6061. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6062. // ];
  6063. // // 检查新版本是否已存在于历史版本中
  6064. // $existingIndex = -1;
  6065. // foreach ($versions as $index => $version) {
  6066. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6067. // $existingIndex = $index;
  6068. // break;
  6069. // }
  6070. // }
  6071. // if ($existingIndex !== -1) {
  6072. // // 如果已存在,移除旧的位置
  6073. // array_splice($versions, $existingIndex, 1);
  6074. // }
  6075. // // 新版本添加到数组开头(最新的在前)
  6076. // array_unshift($versions, $newVersion);
  6077. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6078. // // if (count($versions) > 10) {
  6079. // // $versions = array_slice($versions, 0, 10);
  6080. // // }
  6081. // $updateData['versions'] = json_encode($versions, 256);
  6082. // }
  6083. if ($versions) {
  6084. $updateData['versions'] = json_encode($versions, 256);
  6085. }
  6086. if (!empty($updateData)) {
  6087. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6088. }
  6089. // 更新资产并保存剧本资产关联关系(同一事务)
  6090. DB::beginTransaction();
  6091. try {
  6092. $updated = true;
  6093. if (!empty($updateData)) {
  6094. $updated = DB::table('mp_products')
  6095. ->where('cpid', $cpid)
  6096. ->where('id', $id)
  6097. ->update($updateData);
  6098. }
  6099. // 保存剧本资产关联关系
  6100. if ($script_id) {
  6101. $this->saveProductScriptMapping($id, $script_id, $episode_number);
  6102. }
  6103. DB::commit();
  6104. } catch (\Exception $e) {
  6105. DB::rollback();
  6106. throw $e;
  6107. }
  6108. return $updated;
  6109. }
  6110. /**
  6111. * 保存单一资产与剧本剧集的关联关系
  6112. *
  6113. * @param int $product_id 资产ID
  6114. * @param int $script_id 剧本ID
  6115. * @param string $episode_number_str 剧集序号,多个序号用英文逗号隔开(序号从1开始)
  6116. * @return int 新增关联数量
  6117. */
  6118. private function saveProductScriptMapping($product_id, $script_id, $episode_number_str) {
  6119. // 验证剧本是否存在
  6120. $script = DB::table('mp_scripts')
  6121. ->where('id', $script_id)
  6122. ->where('is_deleted', 0)
  6123. ->first();
  6124. if (!$script) {
  6125. Utils::throwError('20003:剧本不存在');
  6126. }
  6127. // 使用 splitContent 拆分剧本内容获取总集数
  6128. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6129. // 解析剧集序号(英文逗号分隔)
  6130. $episodes = [];
  6131. foreach (explode(',', $episode_number_str) as $item) {
  6132. $item = trim($item);
  6133. if ($item === '' || !is_numeric($item)) {
  6134. Utils::throwError('20003:剧集序号格式不正确,多个序号请用英文逗号隔开');
  6135. }
  6136. $episodes[] = (int)$item;
  6137. }
  6138. // 去重并校验序号范围(序号从1开始)
  6139. $episodes = array_values(array_unique($episodes));
  6140. if (empty($episodes)) {
  6141. Utils::throwError('20003:剧集序号不能为空');
  6142. }
  6143. foreach ($episodes as $episode) {
  6144. if ($episode < 1 || $episode > $totalEpisodes) {
  6145. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6146. }
  6147. }
  6148. $now = now();
  6149. // 过滤已存在的关联,避免重复
  6150. $existingEpisodes = DB::table('mp_script_product_mappings')
  6151. ->where('script_id', $script_id)
  6152. ->where('product_id', $product_id)
  6153. ->whereIn('episode_number', $episodes)
  6154. ->pluck('episode_number')
  6155. ->all();
  6156. $mappingRecords = [];
  6157. foreach ($episodes as $episode) {
  6158. if (in_array($episode, $existingEpisodes)) {
  6159. continue;
  6160. }
  6161. $mappingRecords[] = [
  6162. 'script_id' => $script_id,
  6163. 'product_id' => $product_id,
  6164. 'episode_number' => $episode,
  6165. 'created_at' => $now,
  6166. 'updated_at' => $now,
  6167. ];
  6168. }
  6169. $insertedCount = 0;
  6170. if (!empty($mappingRecords)) {
  6171. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6172. }
  6173. return $insertedCount;
  6174. }
  6175. /**
  6176. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6177. *
  6178. * @param object $script 剧本记录
  6179. * @return int 总集数
  6180. */
  6181. private function getScriptTotalEpisodeCount($script) {
  6182. if (empty($script->content)) {
  6183. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6184. }
  6185. $totalEpisodes = count(splitContent($script->content));
  6186. if ($totalEpisodes < 1) {
  6187. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6188. }
  6189. return $totalEpisodes;
  6190. }
  6191. /**
  6192. * 获取剧本总集数
  6193. *
  6194. * @param array $data 包含 script_id(剧本ID)
  6195. * @return array
  6196. */
  6197. public function getScriptTotalEpisodes($data) {
  6198. $script_id = (int)getProp($data, 'script_id', 0);
  6199. if (!$script_id) {
  6200. Utils::throwError('20003:请提供剧本ID');
  6201. }
  6202. // 验证剧本是否存在
  6203. $script = DB::table('mp_scripts')
  6204. ->where('id', $script_id)
  6205. ->where('is_deleted', 0)
  6206. ->first();
  6207. if (!$script) {
  6208. Utils::throwError('20003:剧本不存在');
  6209. }
  6210. return [
  6211. 'script_id' => $script_id,
  6212. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6213. 'total_episodes' => $this->getScriptTotalEpisodeCount($script),
  6214. ];
  6215. }
  6216. /**
  6217. * 获取角色版本历史
  6218. * @param array $data 包含 id(角色ID)
  6219. * @return array 返回版本历史列表
  6220. */
  6221. public function getProductVersions($data) {
  6222. $cpid = Site::getCpid();
  6223. $id = getProp($data, 'id');
  6224. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6225. $role = DB::table('mp_products')
  6226. ->where('id', $id)
  6227. ->where('cpid', $cpid)
  6228. ->where('type', 1)
  6229. ->first();
  6230. if (!$role) Utils::throwError('20003:角色不存在');
  6231. // 获取版本历史
  6232. $versions = json_decode($role->versions, true) ?: [];
  6233. // 添加当前版本作为最新版本
  6234. $currentVersion = [
  6235. 'version' => 0, // 0 表示当前版本
  6236. 'url' => $role->url,
  6237. 'pic_prompt' => $role->pic_prompt,
  6238. 'updated_at' => $role->updated_at,
  6239. 'is_current' => true
  6240. ];
  6241. array_unshift($versions, $currentVersion);
  6242. return $versions;
  6243. }
  6244. /**
  6245. * 恢复到指定版本
  6246. * @param array $data 包含 id(角色ID)、version(版本号)
  6247. * @return bool
  6248. */
  6249. public function restoreProductVersion($data) {
  6250. $uid = Site::getUid();
  6251. $cpid = Site::getCpid();
  6252. $id = getProp($data, 'id');
  6253. $version = getProp($data, 'version');
  6254. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6255. if (!$version) Utils::throwError('20003:版本号不能为空');
  6256. $role = DB::table('mp_products')
  6257. ->where('id', $id)
  6258. ->where('cpid', $cpid)
  6259. ->where('type', 1)
  6260. ->first();
  6261. if (!$role) Utils::throwError('20003:角色不存在');
  6262. // 获取版本历史
  6263. $versions = json_decode($role->versions, true) ?: [];
  6264. // 查找指定版本
  6265. $targetVersion = null;
  6266. foreach ($versions as $v) {
  6267. if ($v['version'] == $version) {
  6268. $targetVersion = $v;
  6269. break;
  6270. }
  6271. }
  6272. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6273. // 先将当前版本保存到历史
  6274. $newVersion = [
  6275. 'version' => count($versions) + 1,
  6276. 'url' => $role->url,
  6277. 'pic_prompt' => $role->pic_prompt,
  6278. 'updated_at' => date('Y-m-d H:i:s'),
  6279. 'updated_by' => $uid
  6280. ];
  6281. array_unshift($versions, $newVersion);
  6282. // 限制版本数量
  6283. if (count($versions) > 10) {
  6284. $versions = array_slice($versions, 0, 10);
  6285. }
  6286. // 恢复到指定版本
  6287. return DB::table('mp_products')
  6288. ->where('id', $id)
  6289. ->where('cpid', $cpid)
  6290. ->update([
  6291. 'url' => $targetVersion['url'],
  6292. 'pic_prompt' => $targetVersion['pic_prompt'],
  6293. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6294. 'updated_at' => date('Y-m-d H:i:s')
  6295. ]);
  6296. }
  6297. public function deleteProduct($data) {
  6298. $uid = Site::getUid();
  6299. $cpid = Site::getCpid();
  6300. $role = Site::getRole();
  6301. $id = getProp($data, 'id');
  6302. if (!$id) Utils::throwError('20003:ID不能为空');
  6303. $ids = explode(',', $id);
  6304. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6305. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6306. $query_uid = $is_public ? 0 : $uid;
  6307. // 如果是公共库操作,需要admin权限
  6308. if ($is_public && $role !== 'admin') {
  6309. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6310. }
  6311. // 检查是否存在且属于当前用户或公共库
  6312. $role = DB::table('mp_products')
  6313. ->whereIn('id', $ids)
  6314. ->where('cpid', $cpid)
  6315. ->where('user_id', $query_uid)
  6316. ->get();
  6317. if (!$role) Utils::throwError('20003:记录不存在');
  6318. return DB::table('mp_products')
  6319. ->where('cpid', $cpid)
  6320. ->where('user_id', $query_uid)
  6321. ->whereIn('id', $ids)
  6322. ->update([
  6323. 'is_deleted' => 1,
  6324. 'updated_at' => date('Y-m-d H:i:s')
  6325. ]);
  6326. }
  6327. public function generateThreeView($data) {
  6328. $uid = Site::getUid();
  6329. $cpid = Site::getCpid();
  6330. $role = Site::getRole();
  6331. $id = getProp($data, 'id');
  6332. if (!$id) Utils::throwError('20003:ID不能为空');
  6333. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6334. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6335. $query_uid = $is_public ? 0 : $uid;
  6336. // 如果是公共库操作,需要admin权限
  6337. if ($is_public && $role !== 'admin') {
  6338. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6339. }
  6340. // 检查是否存在且属于当前用户或公共库
  6341. $product = DB::table('mp_products')
  6342. ->where('id', $id)
  6343. ->where('cpid', $cpid)
  6344. ->where('user_id', $query_uid)
  6345. ->where('type', 1)->first();
  6346. if (!$product) Utils::throwError('20003:资产不存在');
  6347. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6348. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6349. if (!$ref_img_url) {
  6350. // 如果没有传入参考图,使用角色表中的图片
  6351. $ref_img_url = $product->url ?? '';
  6352. if (!$ref_img_url) {
  6353. Utils::throwError('20003:参考图不能为空');
  6354. }
  6355. }
  6356. $pic_prompt = getProp($product, 'pic_prompt');
  6357. if ($pic_prompt) {
  6358. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6359. }
  6360. // 检查参考图是否是正确的图片格式
  6361. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6362. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6363. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6364. if (!in_array($extension, $allowedExtensions)) {
  6365. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6366. }
  6367. // 处理图片模型
  6368. $model = getProp($data, 'model');
  6369. if (!$model) {
  6370. // 使用默认模型
  6371. $model = 'doubao-seedream-5-0-lite-260128';
  6372. }
  6373. // 验证模型是否在可用模型表中
  6374. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6375. Utils::throwError('20003:该模型已不可用,请更换!');
  6376. }
  6377. $ratio = getProp($data, 'ratio', '16:9');
  6378. $resolution = getProp($data, 'resolution', '2k');
  6379. // 定义分辨率和宽高比对应的尺寸映射表
  6380. $sizeMap = [
  6381. '2k' => [
  6382. '1:1' => ['width' => 2048, 'height' => 2048],
  6383. '4:3' => ['width' => 2304, 'height' => 1728],
  6384. '3:4' => ['width' => 1728, 'height' => 2304],
  6385. '16:9' => ['width' => 2848, 'height' => 1600],
  6386. '9:16' => ['width' => 1600, 'height' => 2848],
  6387. '3:2' => ['width' => 2496, 'height' => 1664],
  6388. '2:3' => ['width' => 1664, 'height' => 2496],
  6389. '21:9' => ['width' => 3136, 'height' => 1344],
  6390. ],
  6391. '3k' => [
  6392. '1:1' => ['width' => 3072, 'height' => 3072],
  6393. '4:3' => ['width' => 3456, 'height' => 2592],
  6394. '3:4' => ['width' => 2592, 'height' => 3456],
  6395. '16:9' => ['width' => 4096, 'height' => 2304],
  6396. '9:16' => ['width' => 2304, 'height' => 4096],
  6397. '2:3' => ['width' => 2496, 'height' => 3744],
  6398. '3:2' => ['width' => 3744, 'height' => 2496],
  6399. '21:9' => ['width' => 4704, 'height' => 2016],
  6400. ],
  6401. '4k' => [
  6402. '1:1' => ['width' => 4096, 'height' => 4096],
  6403. '3:4' => ['width' => 3520, 'height' => 4704],
  6404. '4:3' => ['width' => 4704, 'height' => 3520],
  6405. '16:9' => ['width' => 5504, 'height' => 3040],
  6406. '9:16' => ['width' => 3040, 'height' => 5504],
  6407. '2:3' => ['width' => 3328, 'height' => 4992],
  6408. '3:2' => ['width' => 4992, 'height' => 3328],
  6409. '21:9' => ['width' => 6240, 'height' => 2656],
  6410. ],
  6411. ];
  6412. // 参数验证
  6413. $resolution = strtolower($resolution);
  6414. if (!isset($sizeMap[$resolution])) {
  6415. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6416. }
  6417. if (!isset($sizeMap[$resolution][$ratio])) {
  6418. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6419. }
  6420. // 根据 ratio 和 resolution 确定宽高
  6421. $width = $sizeMap[$resolution][$ratio]['width'];
  6422. $height = $sizeMap[$resolution][$ratio]['height'];
  6423. try {
  6424. // 创建图片生成任务
  6425. $params = [
  6426. 'prompt' => $prompt,
  6427. 'model' => $model,
  6428. 'ref_img_urls' => [$ref_img_url],
  6429. 'width' => $width,
  6430. 'height' => $height
  6431. ];
  6432. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6433. $task_id = $task->id;
  6434. if (!$task_id) {
  6435. Utils::throwError('20003:创建图片生成任务失败');
  6436. }
  6437. // 轮询获取结果
  6438. // 只查询数据库,不调用API,不更新任务表
  6439. $start_time = time();
  6440. $timeout = 1800;
  6441. $img_url = '';
  6442. while (time() - $start_time < $timeout) {
  6443. sleep(5);
  6444. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6445. $task = DB::table('mp_generate_pic_tasks')
  6446. ->where('id', $task_id)
  6447. ->first();
  6448. if (!$task) {
  6449. Utils::throwError('20003:任务不存在');
  6450. }
  6451. if ($task->status === 'success' && $task->result_url) {
  6452. $result_urls = is_string($task->result_url)
  6453. ? json_decode($task->result_url, true)
  6454. : $task->result_url;
  6455. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6456. break;
  6457. } elseif ($task->status === 'failed') {
  6458. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6459. }
  6460. // 其他状态继续轮询
  6461. }
  6462. if (empty($img_url)) {
  6463. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6464. }
  6465. // 更新 mp_products 表(不是任务表)
  6466. DB::table('mp_products')
  6467. ->where('id', $id)
  6468. ->where('cpid', $cpid)
  6469. ->update([
  6470. 'three_view_image_url' => $img_url,
  6471. 'updated_at' => date('Y-m-d H:i:s')
  6472. ]);
  6473. return ['three_view_image_url' => $img_url];
  6474. } catch (\Exception $e) {
  6475. dLog('anime')->error('生成三视图失败', [
  6476. 'error' => $e->getMessage()
  6477. ]);
  6478. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6479. Utils::throwError('20003:' . $e->getMessage());
  6480. }
  6481. }
  6482. /**
  6483. * 推送(复制)资产或文件夹到目标位置
  6484. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6485. * @return array 返回推送结果
  6486. */
  6487. public function pushProductOrFolder($data) {
  6488. $uid = Site::getUid();
  6489. $cpid = Site::getCpid();
  6490. $role = Site::getRole();
  6491. $product_id = getProp($data, 'product_id');
  6492. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6493. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6494. if (!$product_id) {
  6495. Utils::throwError('20003:请选择要推送的项目');
  6496. }
  6497. // 查询源项目(只通过cpid查询,不限制user_id)
  6498. $sourceItem = DB::table('mp_products')
  6499. ->where('id', $product_id)
  6500. ->where('cpid', $cpid)
  6501. ->where('is_deleted', 0)
  6502. ->first();
  6503. if (!$sourceItem) {
  6504. Utils::throwError('20003:要推送的项目不存在');
  6505. }
  6506. // 通过user_id判断源是公共库还是个人库
  6507. $source_uid = $sourceItem->user_id;
  6508. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6509. // 验证目标文件夹并确定目标是公共库还是个人库
  6510. $target_level = 0;
  6511. $target_uid = $uid; // 默认推送到个人库
  6512. $target_is_public = 0;
  6513. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6514. if ($target_parent_id > 0) {
  6515. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6516. $targetParent = DB::table('mp_products')
  6517. ->where('id', $target_parent_id)
  6518. ->where('cpid', $cpid)
  6519. ->where('type', 2)
  6520. ->where('is_deleted', 0)
  6521. ->first();
  6522. if (!$targetParent) {
  6523. Utils::throwError('20003:目标文件夹不存在');
  6524. }
  6525. // 通过user_id判断目标是公共库还是个人库
  6526. $target_level = $targetParent->level;
  6527. $target_uid = $targetParent->user_id;
  6528. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6529. // 使用目标文件夹的 product 类型
  6530. $final_product_type = $targetParent->product;
  6531. }
  6532. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6533. else {
  6534. $push_to_public = getProp($data, 'push_to_public');
  6535. if ($push_to_public === '') {
  6536. Utils::throwError('20003:请选择是否推送到公共库');
  6537. }
  6538. if ($push_to_public) {
  6539. $target_uid = 0;
  6540. $target_is_public = 1;
  6541. }
  6542. // 推送到根目录时,必须指定 product 类型
  6543. if ($target_product === null || $target_product === '') {
  6544. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6545. }
  6546. $final_product_type = $target_product;
  6547. }
  6548. // 如果目标是公共库,需要admin权限
  6549. if ($target_is_public && $role !== 'admin') {
  6550. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6551. }
  6552. // 权限验证:验证是否符合允许的推送规则
  6553. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6554. try {
  6555. DB::beginTransaction();
  6556. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6557. if ($sourceItem->type == 1) {
  6558. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6559. DB::commit();
  6560. return [
  6561. 'product_id' => $newId,
  6562. ];
  6563. }
  6564. // 如果是文件夹,递归复制(支持跨类型推送)
  6565. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6566. DB::commit();
  6567. return [
  6568. 'product_id' => $newFolderId,
  6569. ];
  6570. } catch (\Exception $e) {
  6571. DB::rollBack();
  6572. dLog('anime')->error('推送失败', [
  6573. 'error' => $e->getMessage(),
  6574. 'product_id' => $product_id
  6575. ]);
  6576. Utils::throwError('20003:' . $e->getMessage());
  6577. }
  6578. }
  6579. /**
  6580. * 验证推送权限
  6581. * 允许的推送规则:
  6582. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6583. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6584. * 3. 公共库推送给公共库(公共库 → 公共库)
  6585. *
  6586. * @param int $source_uid 源的user_id
  6587. * @param int $target_uid 目标的user_id
  6588. * @param int $current_uid 当前用户ID
  6589. * @throws \Exception
  6590. */
  6591. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6592. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6593. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6594. return; // 允许
  6595. }
  6596. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6597. if ($source_uid == 0 && $target_uid == $current_uid) {
  6598. return; // 允许
  6599. }
  6600. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6601. if ($source_uid == 0 && $target_uid == 0) {
  6602. return; // 允许
  6603. }
  6604. // 其他情况都不允许
  6605. if ($source_uid != 0 && $source_uid != $current_uid) {
  6606. // 源是别人的个人库
  6607. Utils::throwError('20003:无权限访问该资产');
  6608. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6609. // 个人库推送给公共库(不允许)
  6610. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6611. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6612. // 不同用户的个人库之间推送(不允许)
  6613. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6614. } else {
  6615. // 其他未知情况
  6616. Utils::throwError('20003:不允许的推送操作');
  6617. }
  6618. }
  6619. /**
  6620. * 复制单个资产
  6621. * @param object $sourceProduct 源资产对象
  6622. * @param int $targetParentId 目标父文件夹ID
  6623. * @param int $targetLevel 目标层级
  6624. * @param int $cpid 公司ID
  6625. * @param int $targetUid 目标用户ID
  6626. * @return int 返回新资产ID
  6627. */
  6628. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6629. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6630. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6631. $newProductData = [
  6632. 'user_id' => $targetUid,
  6633. 'cpid' => $cpid,
  6634. 'type' => 1,
  6635. 'parent_id' => $targetParentId,
  6636. 'level' => $targetLevel,
  6637. 'product_name' => $sourceProduct->product_name,
  6638. 'url' => $sourceProduct->url,
  6639. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6640. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6641. 'product' => $finalProductType,
  6642. 'versions' => $sourceProduct->versions ?? '',
  6643. 'sort_order' => time(),
  6644. 'is_deleted' => 0,
  6645. 'created_at' => date('Y-m-d H:i:s'),
  6646. 'updated_at' => date('Y-m-d H:i:s')
  6647. ];
  6648. return DB::table('mp_products')->insertGetId($newProductData);
  6649. }
  6650. /**
  6651. * 递归复制文件夹及其子项
  6652. * @param object $sourceFolder 源文件夹对象
  6653. * @param int $targetParentId 目标父文件夹ID
  6654. * @param int $targetLevel 目标层级
  6655. * @param int $cpid 公司ID
  6656. * @param int $targetUid 目标用户ID
  6657. * @param int $sourceUid 源用户ID
  6658. * @return int 返回新文件夹ID
  6659. */
  6660. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6661. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6662. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6663. // 创建新文件夹
  6664. $newFolderData = [
  6665. 'user_id' => $targetUid,
  6666. 'cpid' => $cpid,
  6667. 'type' => 2,
  6668. 'parent_id' => $targetParentId,
  6669. 'level' => $targetLevel,
  6670. 'product_name' => $sourceFolder->product_name,
  6671. 'product' => $finalProductType,
  6672. 'sort_order' => time(),
  6673. 'is_deleted' => 0,
  6674. 'created_at' => date('Y-m-d H:i:s'),
  6675. 'updated_at' => date('Y-m-d H:i:s')
  6676. ];
  6677. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6678. // 获取源文件夹下的所有子项
  6679. $children = DB::table('mp_products')
  6680. ->where('parent_id', $sourceFolder->id)
  6681. ->where('cpid', $cpid)
  6682. ->where('user_id', $sourceUid)
  6683. ->where('is_deleted', 0)
  6684. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6685. ->get();
  6686. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6687. foreach ($children as $child) {
  6688. if ($child->type == 1) {
  6689. // 资产
  6690. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6691. } else {
  6692. // 文件夹
  6693. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6694. }
  6695. }
  6696. return $newFolderId;
  6697. }
  6698. /**
  6699. * 保存剧本资产关联关系
  6700. * @param array $data 请求参数
  6701. * @return bool
  6702. */
  6703. public function saveScriptProducts($data) {
  6704. $uid = Site::getUid();
  6705. $cpid = Site::getCpid();
  6706. $script_id = getProp($data, 'script_id');
  6707. $products = getProp($data, 'products', []);
  6708. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6709. if (!$script_id) {
  6710. Utils::throwError('20003:请提供剧本ID');
  6711. }
  6712. // 验证剧本是否存在
  6713. $script = DB::table('mp_scripts')
  6714. ->where('id', $script_id)
  6715. ->where('is_deleted', 0)
  6716. ->first();
  6717. if (!$script) {
  6718. Utils::throwError('20003:剧本不存在');
  6719. }
  6720. // 处理图片模型
  6721. $model = getProp($data, 'model');
  6722. if (!$model) {
  6723. // 使用默认模型
  6724. $model = 'doubao-seedream-5-0-lite-260128';
  6725. }
  6726. // 验证模型是否在可用模型表中
  6727. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6728. Utils::throwError('20003:该模型已不可用,请更换!');
  6729. }
  6730. $ratio = getProp($data, 'ratio', '9:16');
  6731. $resolution = getProp($data, 'resolution', '2k');
  6732. // 定义分辨率和宽高比对应的尺寸映射表
  6733. $sizeMap = [
  6734. '2k' => [
  6735. '1:1' => ['width' => 2048, 'height' => 2048],
  6736. '4:3' => ['width' => 2304, 'height' => 1728],
  6737. '3:4' => ['width' => 1728, 'height' => 2304],
  6738. '16:9' => ['width' => 2848, 'height' => 1600],
  6739. '9:16' => ['width' => 1600, 'height' => 2848],
  6740. '3:2' => ['width' => 2496, 'height' => 1664],
  6741. '2:3' => ['width' => 1664, 'height' => 2496],
  6742. '21:9' => ['width' => 3136, 'height' => 1344],
  6743. ],
  6744. '3k' => [
  6745. '1:1' => ['width' => 3072, 'height' => 3072],
  6746. '4:3' => ['width' => 3456, 'height' => 2592],
  6747. '3:4' => ['width' => 2592, 'height' => 3456],
  6748. '16:9' => ['width' => 4096, 'height' => 2304],
  6749. '9:16' => ['width' => 2304, 'height' => 4096],
  6750. '2:3' => ['width' => 2496, 'height' => 3744],
  6751. '3:2' => ['width' => 3744, 'height' => 2496],
  6752. '21:9' => ['width' => 4704, 'height' => 2016],
  6753. ],
  6754. '4k' => [
  6755. '1:1' => ['width' => 4096, 'height' => 4096],
  6756. '3:4' => ['width' => 3520, 'height' => 4704],
  6757. '4:3' => ['width' => 4704, 'height' => 3520],
  6758. '16:9' => ['width' => 5504, 'height' => 3040],
  6759. '9:16' => ['width' => 3040, 'height' => 5504],
  6760. '2:3' => ['width' => 3328, 'height' => 4992],
  6761. '3:2' => ['width' => 4992, 'height' => 3328],
  6762. '21:9' => ['width' => 6240, 'height' => 2656],
  6763. ],
  6764. ];
  6765. // 参数验证
  6766. $resolution = strtolower($resolution);
  6767. if (!isset($sizeMap[$resolution])) {
  6768. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6769. }
  6770. if (!isset($sizeMap[$resolution][$ratio])) {
  6771. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6772. }
  6773. // 根据 ratio 和 resolution 确定宽高
  6774. $width = $sizeMap[$resolution][$ratio]['width'];
  6775. $height = $sizeMap[$resolution][$ratio]['height'];
  6776. $script_name = $script->script_name ?? 'script_' . $script_id;
  6777. // 检查是否已经有该剧本的资产数据
  6778. $existingMappings = DB::table('mp_script_product_mappings')
  6779. ->where('script_id', $script_id)
  6780. ->get();
  6781. if ($existingMappings->isNotEmpty()) {
  6782. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6783. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6784. // 查询这些资产的图片生成任务状态
  6785. $productsWithTasks = DB::table('mp_products')
  6786. ->whereIn('id', $productIds)
  6787. ->where('is_deleted', 0)
  6788. ->get();
  6789. $productTaskMap = [];
  6790. $typeFolderIds = [];
  6791. $hasAllTasks = true;
  6792. foreach ($productsWithTasks as $product) {
  6793. // 收集类型文件夹ID
  6794. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6795. $parentFolder = DB::table('mp_products')
  6796. ->where('id', $product->parent_id)
  6797. ->where('type', 2)
  6798. ->first();
  6799. if ($parentFolder) {
  6800. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6801. }
  6802. }
  6803. // 检查是否有图片生成任务
  6804. if (!empty($product->pic_task_id)) {
  6805. $productTaskMap[$product->id] = $product->pic_task_id;
  6806. } else if($product->url && $product->pic_task_status == '生成成功') {
  6807. continue;
  6808. } else {
  6809. // 有资产没有图片任务
  6810. $hasAllTasks = false;
  6811. }
  6812. }
  6813. // 如果所有资产都有任务ID,直接轮询返回结果
  6814. if ($hasAllTasks && !empty($productTaskMap)) {
  6815. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6816. 'script_id' => $script_id,
  6817. 'script_name' => $script_name,
  6818. 'product_count' => count($productTaskMap)
  6819. ]);
  6820. // 直接返回 SSE 流轮询结果
  6821. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6822. }
  6823. // 如果部分资产没有任务ID,只为这些资产创建任务
  6824. if (!$hasAllTasks && $auto_generate_images) {
  6825. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6826. 'script_id' => $script_id,
  6827. 'script_name' => $script_name
  6828. ]);
  6829. // 开启事务
  6830. DB::beginTransaction();
  6831. try {
  6832. foreach ($productsWithTasks as $product) {
  6833. // 跳过已有任务的资产
  6834. if (!empty($product->pic_task_id)) {
  6835. continue;
  6836. }
  6837. // 跳过没有提示词的资产
  6838. if (empty($product->pic_prompt)) {
  6839. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6840. 'product_id' => $product->id,
  6841. 'product_name' => $product->product_name
  6842. ]);
  6843. continue;
  6844. }
  6845. try {
  6846. // 创建图片生成任务
  6847. $params = [
  6848. 'prompt' => $product->pic_prompt,
  6849. 'model' => $model,
  6850. 'ref_img_urls' => [],
  6851. 'width' => $width,
  6852. 'height' => $height
  6853. ];
  6854. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6855. $task_id = $task->id;
  6856. if ($task_id) {
  6857. $productTaskMap[$product->id] = $task_id;
  6858. // 在事务中更新资产表的任务ID和状态
  6859. DB::table('mp_products')
  6860. ->where('id', $product->id)
  6861. ->update([
  6862. 'pic_task_id' => $task_id,
  6863. 'pic_task_status' => '生成中',
  6864. 'updated_at' => now()
  6865. ]);
  6866. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6867. 'product_id' => $product->id,
  6868. 'task_id' => $task_id
  6869. ]);
  6870. }
  6871. } catch (\Exception $e) {
  6872. dLog('anime')->error('创建资产图片生成任务失败', [
  6873. 'product_id' => $product->id,
  6874. 'error' => $e->getMessage()
  6875. ]);
  6876. // 标记为失败(仍在事务中)
  6877. DB::table('mp_products')
  6878. ->where('id', $product->id)
  6879. ->update([
  6880. 'pic_task_status' => '生成失败',
  6881. 'updated_at' => now()
  6882. ]);
  6883. }
  6884. }
  6885. // 提交事务
  6886. DB::commit();
  6887. // 如果有新创建的任务,返回 SSE 流
  6888. if (!empty($productTaskMap)) {
  6889. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6890. }
  6891. } catch (\Exception $e) {
  6892. // 回滚事务
  6893. DB::rollback();
  6894. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6895. 'script_id' => $script_id,
  6896. 'error' => $e->getMessage()
  6897. ]);
  6898. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6899. }
  6900. }
  6901. // 如果不需要生成图片,返回已存在的信息
  6902. return [
  6903. 'success' => true,
  6904. 'message' => '剧本资产已存在',
  6905. 'script_id' => $script_id,
  6906. 'script_name' => $script_name,
  6907. 'type_folder_ids' => $typeFolderIds,
  6908. 'existing_products' => count($productIds),
  6909. 'tasks_count' => count($productTaskMap)
  6910. ];
  6911. }
  6912. // 解析 products(可能是 JSON 字符串或数组)
  6913. if (is_string($products)) {
  6914. $products = json_decode($products, true);
  6915. if (json_last_error() !== JSON_ERROR_NONE) {
  6916. Utils::throwError('20003:产品数据格式错误');
  6917. }
  6918. }
  6919. if (!is_array($products) || empty($products)) {
  6920. Utils::throwError('20003:产品数据不能为空');
  6921. }
  6922. // 以下是原有的创建逻辑...
  6923. // 开启事务
  6924. DB::beginTransaction();
  6925. try {
  6926. $now = now();
  6927. $mappingRecords = [];
  6928. $createdProductIds = []; // 记录所有创建的资产ID
  6929. // 获取剧本名称
  6930. $script_name = $script->script_name ?? 'script_' . $script_id;
  6931. // 存储每个类型的根文件夹ID
  6932. $typeFolderIds = [];
  6933. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6934. foreach ($products as $productGroup) {
  6935. $type = getProp($productGroup, 'type');
  6936. $title = getProp($productGroup, 'title', '');
  6937. $content = getProp($productGroup, 'content', []);
  6938. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6939. continue;
  6940. }
  6941. // 为当前类型创建根文件夹(如果还未创建)
  6942. if (!isset($typeFolderIds[$type])) {
  6943. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6944. 'user_id' => $uid,
  6945. 'cpid' => $cpid,
  6946. 'type' => 2, // 1.资产 2文件夹
  6947. 'product' => $type, // 1.主体 2.场景 3.道具
  6948. 'parent_id' => 0, // 根文件夹,parent_id=0
  6949. 'level' => 1, // 第一层级
  6950. 'product_name' => $script_name,
  6951. 'sort_order' => time() + $type,
  6952. 'is_deleted' => 0,
  6953. 'created_at' => $now,
  6954. 'updated_at' => $now
  6955. ]);
  6956. }
  6957. $folder_id = $typeFolderIds[$type];
  6958. // 获取表头(第一行)并查找关键列的位置
  6959. $headers = $content[0];
  6960. $nameColumnIndex = -1; // 资产名称列索引
  6961. $sequenceColumnIndex = -1; // 使用范围列索引
  6962. $promptColumnIndex = -1; // 参考提示词列索引
  6963. foreach ($headers as $index => $header) {
  6964. // 查找"资产名称"列
  6965. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6966. $nameColumnIndex = $index;
  6967. }
  6968. // 查找"使用范围"列
  6969. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6970. $sequenceColumnIndex = $index;
  6971. }
  6972. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6973. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6974. $promptColumnIndex = $index;
  6975. }
  6976. }
  6977. // 验证必要的列是否都找到了
  6978. if ($nameColumnIndex === -1) {
  6979. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6980. continue;
  6981. }
  6982. if ($sequenceColumnIndex === -1) {
  6983. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6984. continue;
  6985. }
  6986. // 跳过表头,解析每一行数据
  6987. for ($i = 1; $i < count($content); $i++) {
  6988. $row = $content[$i];
  6989. // 确保行数据有效
  6990. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6991. continue;
  6992. }
  6993. // 根据动态查找的列索引提取数据
  6994. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  6995. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6996. $pic_prompt = '';
  6997. // 提取参考提示词(如果找到了该列)
  6998. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6999. $pic_prompt = trim($row[$promptColumnIndex]);
  7000. }
  7001. // 解析使用范围(逗号分隔的序号)
  7002. $sequences = [];
  7003. if (!empty($sequence_str)) {
  7004. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7005. foreach ($sequenceParts as $part) {
  7006. if (is_numeric($part)) {
  7007. $sequences[] = (int)$part;
  7008. }
  7009. }
  7010. }
  7011. if (empty($product_name)) {
  7012. continue;
  7013. }
  7014. // 处理product_name两边的符号
  7015. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7016. // 如果名称不存在或仅剩占位符号,则跳过
  7017. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7018. dLog('anime')->warning('资产名称无效,跳过保存', [
  7019. 'script_id' => $script_id,
  7020. 'type' => $type,
  7021. 'product_name' => $product_name
  7022. ]);
  7023. continue;
  7024. }
  7025. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7026. $product_id = DB::table('mp_products')->insertGetId([
  7027. 'product_name' => $product_name,
  7028. 'type' => 1, // 1=资产 2.文件夹
  7029. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7030. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7031. 'level' => 2, // 第二层级
  7032. 'pic_prompt' => $pic_prompt,
  7033. 'user_id' => $uid,
  7034. 'cpid' => $cpid,
  7035. 'sort_order' => time(),
  7036. 'is_deleted' => 0,
  7037. 'created_at' => $now,
  7038. 'updated_at' => $now,
  7039. ]);
  7040. // 记录创建的资产ID
  7041. $createdProductIds[] = $product_id;
  7042. // 为每个序号创建映射记录
  7043. if (!empty($sequences)) {
  7044. foreach ($sequences as $sequence) {
  7045. $mappingRecords[] = [
  7046. 'script_id' => $script_id,
  7047. 'product_id' => $product_id,
  7048. 'episode_number' => $sequence,
  7049. 'created_at' => $now,
  7050. 'updated_at' => $now,
  7051. ];
  7052. }
  7053. } else {
  7054. // 如果没有指定序号,创建一个默认映射(序号为0)
  7055. $mappingRecords[] = [
  7056. 'script_id' => $script_id,
  7057. 'product_id' => $product_id,
  7058. 'episode_number' => 0,
  7059. 'created_at' => $now,
  7060. 'updated_at' => $now,
  7061. ];
  7062. }
  7063. }
  7064. }
  7065. if (empty($mappingRecords)) {
  7066. Utils::throwError('20003:没有有效的产品数据');
  7067. }
  7068. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7069. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7070. // 剧本已有资产,同步更新is_products标记
  7071. DB::table('mp_scripts')->where('id', $script_id)->update([
  7072. 'is_products' => 1,
  7073. 'updated_at' => $now
  7074. ]);
  7075. // 如果需要自动生成图片,在事务中创建图片生成任务
  7076. $productTaskMap = [];
  7077. if ($auto_generate_images && !empty($createdProductIds)) {
  7078. // 查询所有创建的资产
  7079. $productsToGenerate = DB::table('mp_products')
  7080. ->whereIn('id', $createdProductIds)
  7081. ->where('is_deleted', 0)
  7082. ->get();
  7083. foreach ($productsToGenerate as $product) {
  7084. if (empty($product->pic_prompt)) {
  7085. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7086. 'product_id' => $product->id,
  7087. 'product_name' => $product->product_name
  7088. ]);
  7089. continue;
  7090. }
  7091. try {
  7092. // 创建图片生成任务
  7093. $params = [
  7094. 'prompt' => $product->pic_prompt,
  7095. 'model' => $model,
  7096. 'ref_img_urls' => [],
  7097. 'width' => $width,
  7098. 'height' => $height
  7099. ];
  7100. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7101. $task_id = $task->id;
  7102. if ($task_id) {
  7103. $productTaskMap[$product->id] = $task_id;
  7104. // 在事务中更新资产表的任务ID和状态
  7105. DB::table('mp_products')
  7106. ->where('id', $product->id)
  7107. ->update([
  7108. 'pic_task_id' => $task_id,
  7109. 'pic_task_status' => '生成中',
  7110. 'updated_at' => now()
  7111. ]);
  7112. dLog('anime')->info('创建资产图片生成任务', [
  7113. 'product_id' => $product->id,
  7114. 'task_id' => $task_id
  7115. ]);
  7116. }
  7117. } catch (\Exception $e) {
  7118. dLog('anime')->error('创建资产图片生成任务失败', [
  7119. 'product_id' => $product->id,
  7120. 'error' => $e->getMessage()
  7121. ]);
  7122. // 标记为失败(仍在事务中)
  7123. DB::table('mp_products')
  7124. ->where('id', $product->id)
  7125. ->update([
  7126. 'pic_task_status' => '生成失败',
  7127. 'updated_at' => now()
  7128. ]);
  7129. }
  7130. }
  7131. }
  7132. // 提交事务
  7133. DB::commit();
  7134. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7135. if ($auto_generate_images && !empty($productTaskMap)) {
  7136. // 返回 SSE 流(事务外轮询)
  7137. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7138. }
  7139. // 如果不需要生成图片,返回普通结果
  7140. return [
  7141. 'success' => true,
  7142. 'type_folder_ids' => $typeFolderIds,
  7143. 'inserted_count' => $insertedCount,
  7144. 'total_records' => count($mappingRecords),
  7145. 'created_products' => count($createdProductIds),
  7146. 'image_tasks_created' => count($productTaskMap)
  7147. ];
  7148. } catch (\Exception $e) {
  7149. // 回滚事务
  7150. DB::rollback();
  7151. // 记录错误日志
  7152. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7153. 'script_id' => $script_id,
  7154. 'error' => $e->getMessage(),
  7155. 'trace' => $e->getTraceAsString()
  7156. ]);
  7157. // 统一使用 Utils::throwError 抛出错误
  7158. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7159. }
  7160. }
  7161. /**
  7162. * 批量为剧本资产生成图片
  7163. *
  7164. * @param array $data 请求参数
  7165. * @return \Generator 返回 SSE 流
  7166. */
  7167. public function batchGenerateProductImages($data) {
  7168. $script_id = getProp($data, 'script_id');
  7169. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7170. if (!$script_id) {
  7171. Utils::throwError('20003:请提供剧本ID');
  7172. }
  7173. // 验证剧本是否存在
  7174. $script = DB::table('mp_scripts')
  7175. ->where('id', $script_id)
  7176. ->where('is_deleted', 0)
  7177. ->first();
  7178. if (!$script) {
  7179. Utils::throwError('20003:剧本不存在');
  7180. }
  7181. $script_name = $script->script_name ?? 'script_' . $script_id;
  7182. // 获取需要生成图片的所有资产
  7183. $products = DB::table('mp_products')
  7184. ->whereIn('parent_id', array_values($type_folder_ids))
  7185. ->where('is_deleted', 0)
  7186. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7187. ->get();
  7188. if ($products->isEmpty()) {
  7189. Utils::throwError('20003:没有找到需要生成图片的资产');
  7190. }
  7191. // 默认参数
  7192. $model = 'doubao-seedream-5-0-lite-260128';
  7193. $width = 1600;
  7194. $height = 2848;
  7195. // 开始为每个资产创建图片生成任务
  7196. $taskIds = [];
  7197. $productTaskMap = []; // 资产ID到任务ID的映射
  7198. foreach ($products as $product) {
  7199. if (empty($product->pic_prompt)) {
  7200. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7201. continue;
  7202. }
  7203. try {
  7204. // 创建图片生成任务
  7205. $params = [
  7206. 'prompt' => $product->pic_prompt,
  7207. 'model' => $model,
  7208. 'ref_img_urls' => [],
  7209. 'width' => $width,
  7210. 'height' => $height
  7211. ];
  7212. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7213. $task_id = $task->id;
  7214. if ($task_id) {
  7215. $taskIds[] = $task_id;
  7216. $productTaskMap[$product->id] = $task_id;
  7217. // 更新资产表的任务ID和状态
  7218. DB::table('mp_products')
  7219. ->where('id', $product->id)
  7220. ->update([
  7221. 'pic_task_id' => $task_id,
  7222. 'pic_task_status' => '生成中',
  7223. 'updated_at' => now()
  7224. ]);
  7225. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7226. }
  7227. } catch (\Exception $e) {
  7228. dLog('anime')->error('创建资产图片生成任务失败', [
  7229. 'product_id' => $product->id,
  7230. 'error' => $e->getMessage()
  7231. ]);
  7232. // 标记为失败
  7233. DB::table('mp_products')
  7234. ->where('id', $product->id)
  7235. ->update([
  7236. 'pic_task_status' => '生成失败',
  7237. 'updated_at' => now()
  7238. ]);
  7239. }
  7240. }
  7241. if (empty($taskIds)) {
  7242. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7243. }
  7244. // 返回 SSE 流
  7245. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7246. }
  7247. /**
  7248. * 轮询资产图片生成任务状态(SSE流式返回)
  7249. * 只通过查询数据库获取任务状态,不主动调用API
  7250. *
  7251. * @param int $script_id 剧本ID
  7252. * @param string $script_name 剧本名称
  7253. * @param array $productTaskMap 资产ID到任务ID的映射
  7254. * @param array $type_folder_ids 类型文件夹ID映射
  7255. * @return \Generator
  7256. */
  7257. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7258. $startTime = time();
  7259. $timeout = 1800; // 30分钟超时
  7260. $pollInterval = 10; // 10秒轮询一次
  7261. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7262. // 定义类型名称映射
  7263. $typeNames = [
  7264. 1 => 'roles', // 角色
  7265. 2 => 'scenes', // 场景
  7266. 3 => 'props' // 道具
  7267. ];
  7268. while (time() - $startTime < $timeout) {
  7269. sleep($pollInterval);
  7270. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7271. $mappings = DB::table('mp_script_product_mappings')
  7272. ->where('script_id', $script_id)
  7273. ->pluck('product_id')
  7274. ->unique()
  7275. ->toArray();
  7276. if (empty($mappings)) {
  7277. dLog('anime')->warning('该剧本没有关联的资产', [
  7278. 'script_id' => $script_id,
  7279. 'script_name' => $script_name
  7280. ]);
  7281. break;
  7282. }
  7283. // 查询所有资产的当前状态
  7284. $products = DB::table('mp_products')
  7285. ->whereIn('id', $mappings)
  7286. ->where('is_deleted', 0)
  7287. ->get();
  7288. // 统计各类型的状态(使用类型名称作为键名)
  7289. $stats = [
  7290. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7291. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7292. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7293. ];
  7294. $allCompleted = true;
  7295. $hasStatusChange = false;
  7296. foreach ($products as $product) {
  7297. $type = $product->product;
  7298. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7299. // 如果类型名称不在 stats 中,初始化
  7300. if (!isset($stats[$typeName])) {
  7301. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7302. }
  7303. $stats[$typeName]['total']++;
  7304. $task_id = $product->pic_task_id;
  7305. $currentStatus = $product->pic_task_status;
  7306. // 检查状态是否有变化
  7307. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7308. $hasStatusChange = true;
  7309. $lastStatus[$product->id] = $currentStatus;
  7310. }
  7311. // 如果是生成中,查询任务表状态
  7312. if ($currentStatus === '生成中' && $task_id) {
  7313. // 只查询数据库,不调用API
  7314. $task = DB::table('mp_generate_pic_tasks')
  7315. ->where('id', $task_id)
  7316. ->first();
  7317. if ($task) {
  7318. // 检查任务状态
  7319. if ($task->status === 'success' && $task->result_url) {
  7320. // 解析图片URL
  7321. $result_urls = $task->result_url;
  7322. if (is_string($result_urls)) {
  7323. $result_urls = json_decode($result_urls, true);
  7324. }
  7325. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7326. // 更新资产表状态
  7327. DB::table('mp_products')
  7328. ->where('id', $product->id)
  7329. ->update([
  7330. 'pic_task_status' => '生成成功',
  7331. 'url' => $img_url,
  7332. 'updated_at' => now()
  7333. ]);
  7334. $stats[$typeName]['success']++;
  7335. $stats[$typeName]['completed']++;
  7336. $hasStatusChange = true;
  7337. dLog('anime')->info('资产图片生成成功', [
  7338. 'product_id' => $product->id,
  7339. 'task_id' => $task_id,
  7340. 'img_url' => $img_url
  7341. ]);
  7342. } elseif ($task->status === 'failed') {
  7343. // 更新资产表状态
  7344. DB::table('mp_products')
  7345. ->where('id', $product->id)
  7346. ->update([
  7347. 'pic_task_status' => '生成失败',
  7348. 'updated_at' => now()
  7349. ]);
  7350. $stats[$typeName]['completed']++;
  7351. $hasStatusChange = true;
  7352. dLog('anime')->warning('资产图片生成失败', [
  7353. 'product_id' => $product->id,
  7354. 'task_id' => $task_id,
  7355. 'error' => $task->error_message ?? '未知错误'
  7356. ]);
  7357. } else {
  7358. // 任务还在处理中
  7359. $allCompleted = false;
  7360. }
  7361. } else {
  7362. // 任务不存在,标记为失败
  7363. DB::table('mp_products')
  7364. ->where('id', $product->id)
  7365. ->update([
  7366. 'pic_task_status' => '生成失败',
  7367. 'updated_at' => now()
  7368. ]);
  7369. $stats[$type]['completed']++;
  7370. $hasStatusChange = true;
  7371. dLog('anime')->error('图片生成任务不存在', [
  7372. 'product_id' => $product->id,
  7373. 'task_id' => $task_id
  7374. ]);
  7375. }
  7376. } elseif ($currentStatus === '生成成功') {
  7377. $stats[$typeName]['success']++;
  7378. $stats[$typeName]['completed']++;
  7379. } elseif ($currentStatus === '生成失败') {
  7380. $stats[$typeName]['completed']++;
  7381. } else {
  7382. // 其他状态也认为未完成
  7383. $allCompleted = false;
  7384. }
  7385. }
  7386. // 移除没有数据的类型(total=0)
  7387. foreach ($stats as $typeName => $stat) {
  7388. if ($stat['total'] === 0) {
  7389. unset($stats[$typeName]);
  7390. }
  7391. }
  7392. // 如果有状态变化,发送 SSE 更新
  7393. if ($hasStatusChange) {
  7394. $eventType = $allCompleted ? 'complete' : 'update';
  7395. $response = [
  7396. 'type' => $eventType,
  7397. 'script_id' => $script_id,
  7398. 'script_name' => $script_name,
  7399. 'stats' => $stats,
  7400. 'timestamp' => date('Y-m-d H:i:s')
  7401. ];
  7402. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7403. dLog('anime')->info('SSE更新', [
  7404. 'event_type' => $eventType,
  7405. 'script_id' => $script_id,
  7406. 'script_name' => $script_name,
  7407. 'stats' => $stats
  7408. ]);
  7409. if ($allCompleted) {
  7410. dLog('anime')->info('所有资产图片生成任务已完成', [
  7411. 'script_id' => $script_id,
  7412. 'script_name' => $script_name,
  7413. 'stats' => $stats
  7414. ]);
  7415. break;
  7416. }
  7417. }
  7418. }
  7419. // 超时处理
  7420. if (time() - $startTime >= $timeout && !$allCompleted) {
  7421. $response = [
  7422. 'type' => 'timeout',
  7423. 'message' => '部分任务超时,请稍后查看结果',
  7424. 'script_id' => $script_id,
  7425. 'script_name' => $script_name,
  7426. 'timestamp' => date('Y-m-d H:i:s')
  7427. ];
  7428. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7429. dLog('anime')->warning('资产图片生成任务超时', [
  7430. 'script_id' => $script_id,
  7431. 'script_name' => $script_name,
  7432. 'timeout' => $timeout
  7433. ]);
  7434. }
  7435. }
  7436. /**
  7437. * 获取剧本关联的资产列表
  7438. * @param array $data 请求参数
  7439. * @return array
  7440. */
  7441. public function getScriptProducts($data) {
  7442. $uid = Site::getUid();
  7443. $cpid = Site::getCpid();
  7444. $script_id = getProp($data, 'script_id');
  7445. $episode_number = getProp($data, 'episode_number');
  7446. if (!$script_id) {
  7447. Utils::throwError('20003:请提供剧本ID');
  7448. }
  7449. // 验证剧本是否存在
  7450. $script = DB::table('mp_scripts')
  7451. ->where('id', $script_id)
  7452. ->where('is_deleted', 0)
  7453. ->first();
  7454. if (!$script) {
  7455. Utils::throwError('20003:剧本不存在');
  7456. }
  7457. // 联表查询资产信息
  7458. $query = DB::table('mp_script_product_mappings as mapping')
  7459. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7460. ->where('mapping.script_id', $script_id)
  7461. ->where('product.cpid', $cpid)
  7462. ->where('product.is_deleted', 0);
  7463. // 如果提供了 episode_number,则过滤指定集数
  7464. if ($episode_number !== null && $episode_number !== '') {
  7465. $query->where('mapping.episode_number', $episode_number);
  7466. }
  7467. $mappings = $query->select(
  7468. 'mapping.script_id',
  7469. 'mapping.product_id',
  7470. 'mapping.episode_number',
  7471. 'product.product_name',
  7472. 'product.type',
  7473. 'product.product',
  7474. 'product.pic_prompt',
  7475. 'product.url',
  7476. 'product.pic_task_id',
  7477. 'product.pic_task_status',
  7478. 'product.three_view_image_url',
  7479. 'mapping.created_at'
  7480. )
  7481. ->orderBy('mapping.product_id', 'asc')
  7482. ->orderBy('mapping.episode_number', 'asc')
  7483. ->get();
  7484. // 按 product_id 分组,合并 episode_number
  7485. $productMap = [];
  7486. foreach ($mappings as $item) {
  7487. $product_id = $item->product_id;
  7488. if (!isset($productMap[$product_id])) {
  7489. $productMap[$product_id] = [
  7490. 'product_id' => $product_id,
  7491. 'product_name' => $item->product_name,
  7492. 'type' => (int)$item->type,
  7493. 'product' => (int)$item->product,
  7494. 'pic_prompt' => $item->pic_prompt,
  7495. 'url' => $item->url,
  7496. 'pic_task_id' => $item->pic_task_id,
  7497. 'pic_task_status' => $item->pic_task_status,
  7498. 'episode_numbers' => [],
  7499. 'created_at' => $item->created_at,
  7500. ];
  7501. }
  7502. // 添加 episode_number(去重)
  7503. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7504. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7505. }
  7506. }
  7507. // 按类型分组
  7508. $roles = []; // type=1 角色/主体
  7509. $scenes = []; // type=2 场景
  7510. $props = []; // type=3 道具
  7511. foreach ($productMap as $product) {
  7512. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7513. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7514. // 构造返回数据
  7515. $productData = [
  7516. 'product_id' => $product['product_id'],
  7517. 'product_name' => $product['product_name'],
  7518. 'product' => $product['product'],
  7519. 'pic_prompt' => $product['pic_prompt'],
  7520. 'url' => $product['url'],
  7521. 'pic_task_id' => $product['pic_task_id'],
  7522. 'pic_task_status' => $product['pic_task_status'],
  7523. 'episode_numbers' => $episodeNumbersStr,
  7524. 'created_at' => $product['created_at'],
  7525. ];
  7526. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7527. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7528. switch ($product['product']) {
  7529. case 1:
  7530. $roles[] = $productData;
  7531. break;
  7532. case 2:
  7533. $scenes[] = $productData;
  7534. break;
  7535. case 3:
  7536. $props[] = $productData;
  7537. break;
  7538. }
  7539. }
  7540. return [
  7541. 'script_id' => $script_id,
  7542. 'script_name' => $script->script_name ?? '',
  7543. 'roles' => $roles, // 主体
  7544. 'scenes' => $scenes, // 场景
  7545. 'props' => $props, // 道具
  7546. ];
  7547. }
  7548. /**
  7549. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7550. * @param string $actContent 原始内容
  7551. * @param array $products 产品数组(包含product_name和url)
  7552. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7553. */
  7554. public function processActContentWithProducts($actContent, $products) {
  7555. if (empty($actContent) || empty($products)) {
  7556. return [
  7557. 'content' => $actContent,
  7558. 'reference_images' => []
  7559. ];
  7560. }
  7561. // 构建产品名称到产品信息的映射
  7562. $product_dict = [];
  7563. foreach ($products as $product) {
  7564. $product_name = getProp($product, 'product_name');
  7565. if ($product_name) {
  7566. $product_dict[$product_name] = [
  7567. 'url' => getProp($product, 'url'),
  7568. 'voice_prompt' => getProp($product, 'voice_prompt')
  7569. ];
  7570. }
  7571. }
  7572. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7573. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7574. $reference_images = [];
  7575. $product_index_map = []; // 产品名称 => 图片序号的映射
  7576. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7577. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7578. $current_index = 1;
  7579. if (!empty($matches[1])) {
  7580. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7581. $seen_products = []; // 用于去重
  7582. foreach ($matches[1] as $product_name) {
  7583. // 跳过已处理的产品
  7584. if (isset($seen_products[$product_name])) {
  7585. continue;
  7586. }
  7587. $seen_products[$product_name] = true;
  7588. // 检查产品是否在字典中
  7589. if (isset($product_dict[$product_name])) {
  7590. $url = $product_dict[$product_name]['url'];
  7591. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7592. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7593. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7594. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7595. }
  7596. // 只有URL非空才分配序号和添加到参考图片
  7597. if (!empty($url)) {
  7598. // 检查URL是否已经在reference_images中(去重)
  7599. if (!in_array($url, $reference_images)) {
  7600. $reference_images[] = $url;
  7601. $product_index_map[$product_name] = $current_index;
  7602. $current_index++;
  7603. } else {
  7604. // URL重复,找到已有的序号
  7605. $existing_index = array_search($url, $reference_images) + 1;
  7606. $product_index_map[$product_name] = $existing_index;
  7607. }
  7608. } else {
  7609. // URL为空,不分配序号(后续直接去掉{})
  7610. $product_index_map[$product_name] = 0;
  7611. }
  7612. } else {
  7613. // 产品不在字典中,不分配序号
  7614. $product_index_map[$product_name] = 0;
  7615. }
  7616. }
  7617. }
  7618. // 第二步:替换内容中的 {产品名称}
  7619. $processedContent = $actContent;
  7620. foreach ($product_index_map as $product_name => $index) {
  7621. $escaped_name = preg_quote($product_name, '/');
  7622. if ($index > 0) {
  7623. // 有图片,替换为:产品名称(图X)
  7624. $replacement = $product_name . '<图片' . $index . '>';
  7625. } else {
  7626. // 无图片,只保留产品名称
  7627. $replacement = $product_name;
  7628. }
  7629. // 替换所有 {产品名称} 为处理后的格式
  7630. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7631. }
  7632. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7633. foreach ($products as $product) {
  7634. $product_name = getProp($product, 'product_name');
  7635. $voice_prompt = getProp($product, 'voice_prompt');
  7636. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7637. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7638. break; // 找到旁白后退出循环
  7639. }
  7640. }
  7641. // 第四步:将voice_prompt信息添加到内容最前面
  7642. $voice_prompt_prefix = '';
  7643. if (!empty($voice_prompts)) {
  7644. $voice_prompt_prefix .= implode('', $voice_prompts);
  7645. }
  7646. // 旁白的voice_prompt放在最后
  7647. if (!empty($narrator_voice_prompt)) {
  7648. $voice_prompt_prefix .= $narrator_voice_prompt;
  7649. }
  7650. // 如果有voice_prompt信息,添加到内容开头
  7651. if (!empty($voice_prompt_prefix)) {
  7652. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7653. }
  7654. return [
  7655. 'content' => $processedContent,
  7656. 'reference_images' => $reference_images
  7657. ];
  7658. }
  7659. public function saveActVideoGenerateParams($data) {
  7660. $episode_id = getProp($data, 'episode_id');
  7661. $model = getProp($data, 'video_model');
  7662. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7663. Utils::throwError('20003:该模型不可用');
  7664. }
  7665. if (!$model) {
  7666. // 使用默认模型
  7667. $model = 'zhizhen-20';
  7668. }
  7669. // 验证模型是否在可用模型表中
  7670. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7671. Utils::throwError('20003:该模型已不可用,请更换!');
  7672. }
  7673. $video_resolution = getProp($data, 'video_resolution', '720p');
  7674. $ratio = getProp($data, 'ratio');
  7675. if (!$ratio) $ratio = '9:16';
  7676. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  7677. if (!$episode) {
  7678. Utils::throwError('20003:分集不存在');
  7679. }
  7680. try {
  7681. DB::beginTransaction();
  7682. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7683. 'video_model' => $model,
  7684. 'video_resolution' => $video_resolution,
  7685. 'ratio' => $ratio,
  7686. 'updated_at' => date('Y-m-d H:i:s')
  7687. ]);
  7688. if ($result === false) {
  7689. Utils::throwError('20003:分集视频参数保存失败');
  7690. }
  7691. // 同步更新mp_animes表
  7692. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  7693. 'video_model' => $model,
  7694. 'video_resolution' => $video_resolution,
  7695. 'video_ratio' => $ratio,
  7696. 'updated_at' => date('Y-m-d H:i:s')
  7697. ]);
  7698. if ($anime_result === false) {
  7699. Utils::throwError('20003:动漫视频参数保存失败');
  7700. }
  7701. } catch (\Exception $e) {
  7702. DB::rollBack();
  7703. Utils::throwError('20003:'.$e->getMessage());
  7704. }
  7705. DB::commit();
  7706. return $result;
  7707. }
  7708. public function confirmActs($data) {
  7709. $episode_id = getProp($data, 'episode_id');
  7710. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7711. if (!$episode) {
  7712. Utils::throwError('20003:分集不存在');
  7713. }
  7714. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7715. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7716. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7717. // 获取所有片段数据
  7718. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7719. // 收集所有资产名称(角色、场景、道具)
  7720. $product_names = [];
  7721. // 收集角色名称
  7722. foreach ($roles as $role) {
  7723. $role_name = getProp($role, 'role');
  7724. if ($role_name && $role_name != '旁白') {
  7725. $product_names[] = $role_name;
  7726. }
  7727. }
  7728. // 收集场景名称
  7729. foreach ($scenes as $scene) {
  7730. $scene_name = getProp($scene, 'scene');
  7731. if ($scene_name) {
  7732. $product_names[] = $scene_name;
  7733. }
  7734. }
  7735. // 收集道具名称
  7736. foreach ($props as $prop) {
  7737. $prop_name = getProp($prop, 'prop');
  7738. if ($prop_name) {
  7739. $product_names[] = $prop_name;
  7740. }
  7741. }
  7742. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7743. $product_names = array_unique($product_names);
  7744. usort($product_names, function($a, $b) {
  7745. return mb_strlen($b) - mb_strlen($a);
  7746. });
  7747. try {
  7748. DB::beginTransaction();
  7749. // 处理每个片段
  7750. foreach ($acts as $act) {
  7751. $act_content = getProp($act, 'act_content');
  7752. if (!$act_content) continue;
  7753. $processed_content = $act_content;
  7754. // 统一替换所有资产名称为 {资产名} 格式
  7755. // 使用占位符避免嵌套替换问题
  7756. $placeholder_map = [];
  7757. $placeholder_index = 0;
  7758. foreach ($product_names as $product_name) {
  7759. // 转义特殊字符
  7760. $escaped_product = preg_quote($product_name, '/');
  7761. // 检查是否匹配且未被 {} 包裹
  7762. $processed_content = preg_replace_callback(
  7763. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7764. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7765. // 使用唯一占位符
  7766. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7767. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7768. $placeholder_index++;
  7769. return $placeholder;
  7770. },
  7771. $processed_content
  7772. );
  7773. }
  7774. // 将所有占位符替换回实际内容
  7775. foreach ($placeholder_map as $placeholder => $replacement) {
  7776. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7777. }
  7778. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7779. $shot_counter = 0;
  7780. $processed_content = preg_replace_callback(
  7781. '/【(?:镜头|分镜)(\d+)】/u',
  7782. function($matches) use (&$shot_counter) {
  7783. $shot_counter++;
  7784. return '【镜头' . $shot_counter . '】';
  7785. },
  7786. $processed_content
  7787. );
  7788. // 更新数据库
  7789. $boolen = DB::table('mp_episode_segments')
  7790. ->where('id', $act->id)
  7791. ->update([
  7792. 'act_show_content' => $processed_content,
  7793. 'updated_at' => date('Y-m-d H:i:s')
  7794. ]);
  7795. if (!$boolen) {
  7796. Utils::throwError('20003:片段处理失败');
  7797. }
  7798. }
  7799. }catch (\Exception $e) {
  7800. DB::rollBack();
  7801. Utils::throwError('20003:'.$e->getMessage());
  7802. }
  7803. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7804. 'is_generated' => 1,
  7805. 'updated_at' => date('Y-m-d H:i:s')
  7806. ]);
  7807. if (!$boolen1) {
  7808. DB::rollBack();
  7809. Utils::throwError('20003:分集处理失败!');
  7810. }
  7811. DB::commit();
  7812. // 重新查询更新后的片段数据
  7813. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7814. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7815. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7816. $products = [];
  7817. // 先处理角色数组
  7818. foreach ($roles as $role) {
  7819. $product = $role;
  7820. // 将role字段重命名为product_name
  7821. if (isset($product['role'])) {
  7822. $product['product_name'] = $product['role'];
  7823. unset($product['role']);
  7824. $product['product'] = 1; // 标记类型为角色
  7825. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7826. }
  7827. }
  7828. // 处理场景数组
  7829. foreach ($scenes as $scene) {
  7830. $product = $scene;
  7831. // 将scene字段重命名为product_name
  7832. if (isset($product['scene'])) {
  7833. $product['product_name'] = $product['scene'];
  7834. unset($product['scene']);
  7835. $product['product'] = 2; // 标记类型为场景
  7836. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7837. }
  7838. }
  7839. // 处理道具数组(逻辑与场景一致)
  7840. foreach ($props as $prop) {
  7841. $product = $prop;
  7842. // 将prop字段重命名为product_name
  7843. if (isset($product['prop'])) {
  7844. $product['product_name'] = $product['prop'];
  7845. unset($product['prop']);
  7846. $product['product'] = 3; // 标记类型为道具
  7847. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7848. }
  7849. }
  7850. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7851. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7852. foreach ($extra_products as $extra_product) {
  7853. $product_name = getProp($extra_product, 'product_name');
  7854. if ($product_name) {
  7855. $products[$product_name] = $extra_product; // 覆盖同名数据
  7856. }
  7857. }
  7858. // 重新索引数组(去除key)
  7859. $products = array_values($products);
  7860. // 构建返回的acts数组
  7861. $return_acts = [];
  7862. foreach ($acts as $act) {
  7863. $return_acts[] = [
  7864. 'act_id' => getProp($act, 'id'),
  7865. 'act_number' => getProp($act, 'act_number'),
  7866. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7867. 'act_show_content' => getProp($act, 'act_show_content'),
  7868. 'video_url' => getProp($act, 'video_url'),
  7869. 'video_duration' => getProp($act, 'video_duration'),
  7870. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7871. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7872. ];
  7873. }
  7874. return [
  7875. 'anime_id' => getProp($episode, 'anime_id'),
  7876. 'episode_id' => $episode_id,
  7877. 'title' => getProp($episode, 'title'),
  7878. 'episode_number' => getProp($episode, 'episode_number'),
  7879. 'is_generated' => getProp($episode, 'is_generated'),
  7880. 'video_params' => [
  7881. 'video_model' => getProp($episode, 'video_model'),
  7882. 'video_resolution' => getProp($episode, 'video_resolution'),
  7883. 'ratio' => getProp($episode, 'ratio'),
  7884. ],
  7885. 'products' => $products,
  7886. 'acts' => $return_acts
  7887. ];
  7888. }
  7889. }