AnimeService.php 505 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Exceptions\ApiException;
  6. use App\Facade\Site;
  7. use App\Libs\Utils;
  8. use App\Models\MpGeneratePicTask;
  9. use App\Models\MpTaskCenter;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\DeepSeek\DeepSeekService;
  13. use App\Services\PointsService;
  14. use App\Services\TaskCenterService;
  15. use Dflydev\DotAccessData\Util;
  16. use GuzzleHttp\Client;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Log;
  19. use Illuminate\Support\Facades\Redis;
  20. use OSS\Core\OssException;
  21. use OSS\OssClient;
  22. use PhpOffice\PhpSpreadsheet\IOFactory;
  23. class AnimeService
  24. {
  25. protected $aiImageGenerationService;
  26. protected $aiVideoGenerationService;
  27. protected $DeepSeekService;
  28. protected $pointsService;
  29. protected $taskCenterService;
  30. private $url;
  31. private $api_key;
  32. private $headers;
  33. public function __construct(
  34. AIImageGenerationService $aiImageGenerationService,
  35. AIVideoGenerationService $aiVideoGenerationService,
  36. DeepSeekService $DeepSeekService,
  37. PointsService $pointsService,
  38. TaskCenterService $taskCenterService
  39. ) {
  40. $this->aiImageGenerationService = $aiImageGenerationService;
  41. $this->aiVideoGenerationService = $aiVideoGenerationService;
  42. $this->DeepSeekService = $DeepSeekService;
  43. $this->pointsService = $pointsService;
  44. $this->taskCenterService = $taskCenterService;
  45. $this->url = 'https://api.deepseek.com/chat/completions';
  46. $this->api_key = env('DEEPSEEK_API_KEY');
  47. $this->headers = [
  48. 'Authorization' => 'Bearer '.$this->api_key,
  49. 'Content-Type' => 'application/json; charset=UTF-8'
  50. ];
  51. }
  52. /**
  53. * 构建统一的分镜数据结构(episodeInfo格式)
  54. * @param array $segments 分镜数据数组
  55. * @return array 返回包含acts和total_duration的数组
  56. */
  57. public function buildEpisodeSegmentsStructure($segments) {
  58. $acts = [];
  59. $totalDuration = 0; // 初始化总时长
  60. foreach($segments as $segment) {
  61. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  62. $videoDuration = getProp($segment, 'video_duration');
  63. $audioDuration = getProp($segment, 'audio_duration');
  64. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  65. $totalDuration += floatval($videoDuration);
  66. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  67. $totalDuration += floatval($audioDuration);
  68. } else {
  69. $totalDuration += 5; // 默认5秒
  70. }
  71. $segment_content = getProp($segment, 'segment_content');
  72. // 判断是否有尾帧描述,如果有则去掉这部分内容
  73. if (strpos($segment_content, '尾帧') !== false) {
  74. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  75. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  76. }
  77. // 构建分镜信息
  78. $segmentInfo = [
  79. 'segment_id' => getProp($segment, 'segment_id'),
  80. 'segment_number' => getProp($segment, 'segment_number'),
  81. 'segment_content' => $segment_content,
  82. 'description' => getProp($segment, 'description'),
  83. 'composition' => getProp($segment, 'composition'),
  84. 'camera_movement' => getProp($segment, 'camera_movement'),
  85. 'voice_actor' => getProp($segment, 'voice_actor'),
  86. 'dialogue' => getProp($segment, 'dialogue'),
  87. 'frame_type' => getProp($segment, 'frame_type'),
  88. 'scene' => getProp($segment, 'scene'),
  89. 'characters' => getProp($segment, 'characters'),
  90. 'tail_frame' => getProp($segment, 'tail_frame'),
  91. 'emotion' => getProp($segment, 'emotion'),
  92. 'emotion_type' => getProp($segment, 'emotion_type'),
  93. 'gender' => getProp($segment, 'gender'),
  94. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  95. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  96. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  97. 'pitch' => getProp($segment, 'pitch'),
  98. 'voice_name' => getProp($segment, 'voice_name'),
  99. 'voice_type' => getProp($segment, 'voice_type'),
  100. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  101. 'img_url' => getProp($segment, 'img_url'),
  102. 'audio_url' => getProp($segment, 'audio_url'),
  103. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  104. 'video_url' => getProp($segment, 'video_url'),
  105. 'video_duration' => getProp($segment, 'video_duration', 0),
  106. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  107. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  108. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  109. 'current_type' => getProp($segment, 'current_type'),
  110. ];
  111. $actNumber = getProp($segment, 'act_number');
  112. if (isset($acts[$actNumber])) {
  113. $acts[$actNumber]['segments'][] = $segmentInfo;
  114. } else {
  115. $acts[$actNumber] = [
  116. 'act_number' => $actNumber,
  117. 'act_title' => getProp($segment, 'act_title'),
  118. 'act_duration' => getProp($segment, 'act_duration'),
  119. 'segments' => [$segmentInfo]
  120. ];
  121. }
  122. }
  123. return [
  124. 'acts' => array_values($acts),
  125. 'total_duration' => intval(round($totalDuration))
  126. ];
  127. }
  128. /**
  129. * 构建统一的分段数据结构(episodeInfoForAce格式)
  130. * @param array $segments 分段数据数组
  131. * @return array 返回包含acts和total_duration的数组
  132. */
  133. public function buildEpisodeActsStructureForAce($segments) {
  134. $acts = [];
  135. $totalDuration = 0; // 初始化总时长
  136. foreach($segments as $segment) {
  137. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  138. $videoDuration = getProp($segment, 'video_duration');
  139. $actDuration = getProp($segment, 'act_duration');
  140. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  141. $totalDuration += floatval($videoDuration);
  142. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  143. $totalDuration += floatval($actDuration);
  144. } else {
  145. $totalDuration += 5; // 默认5秒
  146. }
  147. // 构建分镜信息
  148. $segmentInfo = [
  149. 'act_id' => getProp($segment, 'id'),
  150. 'act_number' => getProp($segment, 'act_number'),
  151. 'act_title' => getProp($segment, 'act_title'),
  152. 'act_duration' => getProp($segment, 'act_duration'),
  153. 'act_content' => getProp($segment, 'act_content'),
  154. 'video_url' => getProp($segment, 'video_url'),
  155. 'video_duration' => getProp($segment, 'video_duration', 0),
  156. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  157. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  158. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  159. 'current_type' => getProp($segment, 'current_type'),
  160. ];
  161. $acts[] = $segmentInfo;
  162. }
  163. return [
  164. 'acts' => array_values($acts),
  165. 'total_duration' => intval(round($totalDuration))
  166. ];
  167. }
  168. /**
  169. * 验证画面比例是否有效
  170. * @param string $ratio 画面比例
  171. * @return bool
  172. */
  173. public function validateRatio($ratio) {
  174. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  175. }
  176. /**
  177. * 获取画面比例对应的宽高
  178. * @param string $ratio 画面比例
  179. * @return array ['width' => int, 'height' => int]
  180. * @throws \Exception
  181. */
  182. private function getRatioDimensions($ratio) {
  183. if ($ratio && !$this->validateRatio($ratio)) {
  184. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  185. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  186. }
  187. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  188. }
  189. public function createAnime($data) {
  190. $uid = Site::getUid();
  191. $cpid = Site::getCpid();
  192. $input_art_style = getProp($data, 'art_style');
  193. $file = getProp($data, 'file');
  194. $content = getProp($data, 'content', '');
  195. $bid = getProp($data, 'bid', 0);
  196. $script_id = getProp($data, 'script_id', 0);
  197. $ace_mode = getProp($data, 'ace_mode', 0);
  198. $extra_products = getProp($data, 'products', []);
  199. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  200. if (!is_array($extra_products)) {
  201. Utils::throwError('20003:传入的资产格式不正确');
  202. }
  203. // 替换美术风格
  204. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  205. // 提取文件内容
  206. if ($file) {
  207. $content = $this->DeepSeekService->extractFileContent($file);
  208. if (!$content) {
  209. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  210. }
  211. } elseif ($script_id) {
  212. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  213. if (!$content) {
  214. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  215. }
  216. } elseif ($bid) {
  217. $content = $this->DeepSeekService->getContentByBid($bid);
  218. if (!$content) {
  219. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  220. }
  221. } elseif ($content) {
  222. $content = filterContent($content);
  223. }else {
  224. $content = '';
  225. }
  226. $anime_data = [
  227. 'user_id' => $uid,
  228. 'cpid' => $cpid,
  229. 'anime_name' => '新剧本策划',
  230. 'is_multi' => getProp($data, 'is_multi', 1),
  231. 'content' => $content,
  232. 'art_style_type' => $input_art_style,
  233. 'ace_mode' => $ace_mode,
  234. 'script_id' => $script_id,
  235. 'extra_products' => json_encode($extra_products, 256),
  236. 'created_at' => date('Y-m-d H:i:s'),
  237. 'updated_at' => date('Y-m-d H:i:s'),
  238. ];
  239. // 处理文本模型
  240. $model = getProp($data, 'model');
  241. if (!$model) {
  242. // 用户没有输入,使用默认值
  243. $model = 'deepseek-v4-pro';
  244. }
  245. // 验证模型是否在可用模型表中
  246. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  247. $model = 'deepseek-v4-pro';
  248. }
  249. $anime_data['model'] = $model;
  250. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  251. return DB::table('mp_animes')->insertGetId($anime_data);
  252. }
  253. public function chatList($data) {
  254. $uid = Site::getUid();
  255. $anime_name = getProp($data, 'anime_name');
  256. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  257. if ($anime_name) {
  258. $query->where('anime_name', 'like', "%$anime_name%");
  259. }
  260. return $query->orderBy('id', 'desc')->paginate();
  261. }
  262. public function chatHistory($data) {
  263. $anime_id = getProp($data, 'anime_id');
  264. $sequence = getProp($data, 'sequence', 0);
  265. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  266. $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)
  267. ->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');
  268. return $query->orderBy('ar.id')->get()->map(function ($value) {
  269. $value = (array)$value;
  270. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  271. $value['created_at'] = transDate($value['created_at']);
  272. $value['episode_created_at'] = transDate($value['episode_created_at']);
  273. return $value;
  274. })->toArray();
  275. }
  276. public function batchSetRoleImg($data) {
  277. $episode_id = getProp($data, 'episode_id');
  278. if (!$episode_id) Utils::throwError('1002:请选择分集');
  279. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  280. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  281. $art_style = getProp($episode, 'art_style');
  282. $anime_id = getProp($episode, 'anime_id');
  283. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  284. $art_style_type = getProp($anime, 'art_style_type');
  285. $character_prefix = '';
  286. $scene_prefix = '';
  287. if ($art_style_type) {
  288. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  289. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  290. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  291. }
  292. foreach ($roles as &$role) {
  293. $role_name = getProp($role, 'role');
  294. if ($role_name == '旁白') continue;
  295. // 优先使用 pic_prompt,如果没有则使用 description
  296. $pic_prompt = getProp($role, 'pic_prompt');
  297. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  298. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  299. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  300. // 参考图地址
  301. $ref_img_url = getProp($role, 'url');
  302. if ($ref_img_url) continue; // 已有图片则跳过
  303. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  304. try {
  305. $params = [
  306. 'prompt' => $description,
  307. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  308. ];
  309. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  310. $task_id = $task->id;
  311. if (!$task_id) {
  312. Utils::throwError("20003:角色({$role_name})生成图片失败");
  313. }
  314. $role['task_id'] = $task_id;
  315. $role['task_status'] = 'processing';
  316. } catch (\Exception $e) {
  317. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  318. Utils::throwError("20003:" . $e->getMessage());
  319. }
  320. }
  321. // 保存角色信息
  322. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  323. 'roles' => json_encode($roles, 256),
  324. 'generate_status' => '执行中',
  325. 'generate_at' => date('Y-m-d H:i:s'),
  326. 'updated_at' => date('Y-m-d H:i:s')
  327. ]);
  328. if (!$boolen) {
  329. Utils::throwError('20003:保存角色信息失败');
  330. }
  331. return $boolen;
  332. }
  333. public function batchSetSceneImg($data) {
  334. $episode_id = getProp($data, 'episode_id');
  335. if (!$episode_id) Utils::throwError('1002:请选择分集');
  336. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  337. $scenes = json_decode(getProp($episode, 'scenes'), true);
  338. $art_style = getProp($episode, 'art_style');
  339. $target_scene = getProp($data, 'target_scene');
  340. $anime_id = getProp($episode, 'anime_id');
  341. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  342. $art_style_type = getProp($anime, 'art_style_type');
  343. $character_prefix = '';
  344. $scene_prefix = '';
  345. if ($art_style_type) {
  346. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  347. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  348. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  349. }
  350. foreach ($scenes as &$scene) {
  351. $scene_name = getProp($scene, 'scene');
  352. if ($scene_name != $target_scene) continue;
  353. // 优先使用 pic_prompt,如果没有则使用 description
  354. $pic_prompt = getProp($scene, 'pic_prompt');
  355. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  356. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  357. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  358. // 参考图地址
  359. $ref_img_url = getProp($scene, 'url');
  360. if ($ref_img_url) continue; // 已有图片则跳过
  361. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  362. try {
  363. $params = [
  364. 'prompt' => $description,
  365. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  366. ];
  367. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  368. $task_id = $task->id;
  369. if (!$task_id) {
  370. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  371. }
  372. $scene['task_id'] = $task_id;
  373. $scene['task_status'] = 'processing';
  374. } catch (\Exception $e) {
  375. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  376. Utils::throwError("20003:" . $e->getMessage());
  377. }
  378. }
  379. // 保存场景信息
  380. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  381. 'scenes' => json_encode($scenes, 256),
  382. 'generate_status' => '执行中',
  383. 'generate_at' => date('Y-m-d H:i:s'),
  384. 'updated_at' => date('Y-m-d H:i:s')
  385. ]);
  386. if (!$boolen) {
  387. Utils::throwError('20003:保存角色信息失败');
  388. }
  389. return $boolen;
  390. }
  391. public function editAnime($data) {
  392. $anime_id = getProp($data, 'anime_id');
  393. $anime_name = trim(getProp($data, 'anime_name'));
  394. // 确认对话名称唯一性
  395. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  396. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  397. }
  398. if (!$anime_id || !$anime_name) {
  399. Utils::throwError('20003:参数异常');
  400. }
  401. return DB::table('mp_animes')->where('id', $anime_id)->update([
  402. 'anime_name' => $anime_name,
  403. 'updated_at' => date('Y-m-d H:i:s')
  404. ]);
  405. // $script_arr =getProp($data, 'script', []);
  406. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  407. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  408. // $anime_id = getProp($data, 'anime_id');
  409. // try {
  410. // DB::beginTransaction();
  411. // $table_data = [
  412. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  413. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  414. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  415. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  416. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  417. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  418. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  419. // 'status' => 3,
  420. // 'start_episode_sequence' => $start_episode_sequence,
  421. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  422. // 'episode_num' => count($script_arr['episodes']),
  423. // 'updated_at' => date('Y-m-d H:i:s')
  424. // ];
  425. // // 保存剧本内容
  426. // if (!empty($anime_id)) {
  427. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  428. // if (!$boolen) {
  429. // dLog('anime')->info('对话保存失败', $table_data);
  430. // Utils::throwError('20003:对话保存失败');
  431. // }
  432. // }else {
  433. // $table['created_at'] = $table_data['updated_at'];
  434. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  435. // if (!$anime_id) {
  436. // dLog('anime')->info('对话保存失败', $table_data);
  437. // Utils::throwError('20003:对话保存失败');
  438. // }
  439. // }
  440. // // 保存分集内容
  441. // // 删除历史分集内容
  442. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  443. // $episodes = [];
  444. // $sequence = 1;
  445. // foreach ($script_arr['episodes'] as $episode) {
  446. // $segment_number = 1;
  447. // foreach($episode['segments'] as $segment) {
  448. // $episodes[] = [
  449. // 'anime_id' => $anime_id,
  450. // 'episode_number' => $episode['episode_number'],
  451. // 'title' => $episode['title'],
  452. // // 'content' => $episode['content'],
  453. // 'content' => '',
  454. // 'segment_number' => $segment_number,
  455. // 'segment_content' => $segment['segment_content'],
  456. // 'sequence' => $sequence,
  457. // 'created_at' => date('Y-m-d H:i:s'),
  458. // 'updated_at' => date('Y-m-d H:i:s')
  459. // ];
  460. // $sequence++;
  461. // $segment_number++;
  462. // }
  463. // }
  464. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  465. // if (!$boolen2) {
  466. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  467. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  468. // Utils::throwError('20003:分集内容保存失败');
  469. // }
  470. // } catch (\Exception $e) {
  471. // DB::rollBack();
  472. // Utils::throwError('20003:'.$e->getMessage());
  473. // }
  474. // DB::commit();
  475. // return true;
  476. }
  477. public function delAnime($data) {
  478. $anime_id = getProp($data, 'anime_id');
  479. if (!$anime_id) {
  480. Utils::throwError('20003:请选择剧本');
  481. }
  482. return DB::table('mp_animes')->where('id', $anime_id)->update([
  483. 'is_deleted' => 1,
  484. 'updated_at' => date('Y-m-d H:i:s')
  485. ]);
  486. }
  487. public function animeDetail($data) {
  488. $uid = Site::getUid();
  489. $anime_id = getProp($data, 'anime_id');
  490. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  491. ->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();
  492. if (!$anime) Utils::throwError('20003:权限不足');
  493. $anime = (array)$anime;
  494. $anime['roles'] = json_decode($anime['roles']);
  495. $anime['scenes'] = json_decode($anime['scenes']);
  496. // 获取分集信息
  497. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  498. ->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"))
  499. ->orderBy('episode_number')->get()->map(function ($value) {
  500. return (array)$value;
  501. })->toArray();
  502. $anime['episodes'] = $episodes;
  503. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  504. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  505. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  506. ->where('anime_id', $anime_id)
  507. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  508. ->orderBy('episode_number')
  509. ->get()
  510. ->map(function ($task) use ($episodeNumbers) {
  511. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  512. return null;
  513. }
  514. return [
  515. 'episode_number' => (int)$task->episode_number,
  516. 'status' => $task->status,
  517. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  518. ];
  519. })
  520. ->filter()
  521. ->values()
  522. ->toArray();
  523. $anime['episode_tasks'] = $episodeTasks;
  524. return $anime;
  525. }
  526. public function episodeInfo($data) {
  527. $uid = Site::getUid();
  528. $anime_id = getProp($data, 'anime_id');
  529. $episode_id = getProp($data, 'episode_id');
  530. if (!$anime_id || !$episode_id) {
  531. Utils::throwError('1002:请选择剧集');
  532. }
  533. // 验证用户权限
  534. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  535. if (!$anime) Utils::throwError('20003:权限不足');
  536. $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();
  537. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  538. $episode = (array)$episode;
  539. $episode['roles'] = json_decode($episode['roles'], true);
  540. // foreach($episode['roles'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  542. // }
  543. $episode['scenes'] = json_decode($episode['scenes'], true);
  544. // foreach($episode['scenes'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  546. // }
  547. // 获取分镜信息
  548. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  549. ->select('*')->get()->map(function ($value) {
  550. return (array)$value;
  551. })->toArray();
  552. // 使用公共方法构建分镜结构
  553. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  554. $episode['acts'] = $segmentsStructure['acts'];
  555. $episode['total_duration'] = $segmentsStructure['total_duration'];
  556. return $episode;
  557. }
  558. public function episodeInfoForAce($data) {
  559. $anime_id = getProp($data, 'anime_id');
  560. $episode_id = getProp($data, 'episode_id');
  561. if (!$anime_id || !$episode_id) {
  562. Utils::throwError('1002:请选择剧集');
  563. }
  564. $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();
  565. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  566. $episode = (array)$episode;
  567. $episode['roles'] = json_decode($episode['roles'], true);
  568. // foreach($episode['roles'] as &$item) {
  569. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  570. // }
  571. $episode['scenes'] = json_decode($episode['scenes'], true);
  572. // foreach($episode['scenes'] as &$item) {
  573. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  574. // }
  575. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  576. // 获取分镜信息
  577. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  578. ->select('*')->get()->map(function ($value) {
  579. return (array)$value;
  580. })->toArray();
  581. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  582. $episode['acts'] = $segmentsStructure['acts'];
  583. $episode['total_duration'] = $segmentsStructure['total_duration'];
  584. // 获取mp_animes表中的视频参数
  585. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  586. $episode['video_params'] = [
  587. 'video_model' => getProp($anime, 'video_model'),
  588. 'video_resolution' => getProp($anime, 'video_resolution'),
  589. 'ratio' => getProp($anime, 'video_ratio'),
  590. ];
  591. return $episode;
  592. }
  593. public function segmentInfo($data) {
  594. $uid = Site::getUid();
  595. $segment_id = getProp($data, 'segment_id');
  596. if (!$segment_id) {
  597. Utils::throwError('1002:请选择分镜');
  598. }
  599. // 获取分镜信息
  600. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  601. // 验证用户权限
  602. if ($segment) {
  603. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  604. if (!$anime) Utils::throwError('20003:权限不足');
  605. }
  606. $result = [
  607. 'segment_id' => getProp($segment, 'segment_id'),
  608. 'segment_number' => getProp($segment, 'segment_number'),
  609. 'segment_content' => getProp($segment, 'segment_content'),
  610. 'description' => getProp($segment, 'description'),
  611. 'composition' => getProp($segment, 'composition'),
  612. 'camera_movement' => getProp($segment, 'camera_movement'),
  613. 'voice_actor' => getProp($segment, 'voice_actor'),
  614. 'dialogue' => getProp($segment, 'dialogue'),
  615. 'frame_type' => getProp($segment, 'frame_type'),
  616. 'scene' => getProp($segment, 'scene'),
  617. 'characters' => getProp($segment, 'characters'),
  618. 'tail_frame' => getProp($segment, 'tail_frame'),
  619. 'emotion' => getProp($segment, 'emotion'),
  620. 'emotion_type' => getProp($segment, 'emotion_type'),
  621. 'gender' => getProp($segment, 'gender'),
  622. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  623. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  624. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  625. 'pitch' => getProp($segment, 'pitch'),
  626. 'voice_name' => getProp($segment, 'voice_name'),
  627. 'voice_type' => getProp($segment, 'voice_type'),
  628. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  629. 'img_url' => getProp($segment, 'img_url'),
  630. 'video_url' => getProp($segment, 'video_url'),
  631. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  632. ];
  633. return $result;
  634. }
  635. public function copyEpisodeVersion($data) {
  636. $episode_id = getProp($data, 'episode_id');
  637. $uid = Site::getUid();
  638. $cpid = Site::getCpid();
  639. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  640. if (!$episode) Utils::throwError('20003:该剧集不存在');
  641. $episode = (array)$episode;
  642. $anime_id = $episode['anime_id'];
  643. $episode_number = $episode['episode_number'];
  644. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  645. $sequence = $count + 1;
  646. unset($episode['id']);
  647. $now = date('Y-m-d H:i:s');
  648. $episode['created_at'] = $now;
  649. $episode['updated_at'] = $now;
  650. $episode['is_default'] = 1;
  651. // 获取版本中含有"(副本"字样的个数
  652. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  653. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  654. $episode['sequence'] = $sequence;
  655. $episode['is_generated'] = 0;
  656. $episode['cpid'] = $cpid;
  657. // 获取ace_mode
  658. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  659. try {
  660. DB::beginTransaction();
  661. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  662. // 新增副本
  663. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  664. if (!$new_episode_id) {
  665. Utils::throwError('20003:创建副本失败!');
  666. }
  667. // 获取分镜数据并准备插入
  668. $segments_for_insert = DB::table('mp_episode_segments')
  669. ->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')
  670. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  671. $item = (array)$item;
  672. $item['episode_id'] = $new_episode_id;
  673. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  674. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  675. return $item;
  676. })->toArray();
  677. // 写入分镜数据
  678. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  679. if (!$boolen2) {
  680. Utils::throwError('20003:写入分镜数据失败!');
  681. }
  682. // 写入对话历史
  683. $records = [
  684. [
  685. 'uid' => $uid,
  686. 'anime_id' => $anime_id,
  687. 'role' => 'user',
  688. 'content' => '创建副本',
  689. 'sequence' => $episode_number,
  690. 'episode_id' => $new_episode_id,
  691. 'created_at' => $now,
  692. 'updated_at' => $now
  693. ],
  694. [
  695. 'uid' => $uid,
  696. 'anime_id' => $anime_id,
  697. 'role' => 'assistant',
  698. 'content' => '好的,已为您创建副本',
  699. 'sequence' => $episode_number,
  700. 'episode_id' => $new_episode_id,
  701. 'created_at' => $now,
  702. 'updated_at' => $now
  703. ]
  704. ];
  705. $boolen3 = DB::table('mp_anime_records')->insert($records);
  706. if (!$boolen3) {
  707. Utils::throwError('20003:对话记录保存失败');
  708. }
  709. }catch (\Exception $e) {
  710. DB::rollBack();
  711. Utils::throwError('20003:'.$e->getMessage());
  712. }
  713. DB::commit();
  714. // 构建与 episodeInfo 方法一致的返回数据结构
  715. $result = [
  716. 'episode_id' => $new_episode_id,
  717. 'anime_id' => $anime_id,
  718. 'episode_number' => $episode_number,
  719. 'title' => $episode['title'],
  720. 'intro' => $episode['intro'],
  721. 'art_style' => $episode['art_style'],
  722. 'roles' => json_decode($episode['roles'], true),
  723. 'scenes' => json_decode($episode['scenes'], true),
  724. 'is_generated' => (int)$episode['is_generated']
  725. ];
  726. if ((int)$ace_mode === 1) {
  727. // 获取分镜信息
  728. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  729. ->select('*')->get()->map(function ($value) {
  730. return (array)$value;
  731. })->toArray();
  732. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  733. }else {
  734. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  735. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  736. }
  737. $result['acts'] = $segmentsStructure['acts'];
  738. $result['total_duration'] = $segmentsStructure['total_duration'];
  739. return $result;
  740. }
  741. public function episodeVersions($data) {
  742. $anime_id = getProp($data, 'anime_id');
  743. $episode_id = getProp($data, 'episode_id');
  744. if (!$anime_id || !$episode_id) {
  745. Utils::throwError('1002:请选择剧集');
  746. }
  747. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  748. $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) {
  749. return (array)$value;
  750. })->toArray();
  751. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  752. foreach($episodes as &$episode) {
  753. $episode['version'] = 'V'.$episode['sequence'];
  754. $episode['roles'] = json_decode($episode['roles'], true);
  755. $episode['scenes'] = json_decode($episode['scenes'], true);
  756. // 获取分镜信息
  757. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  758. ->select('*')->get()->map(function ($value) {
  759. return (array)$value;
  760. })->toArray();
  761. // 使用公共方法构建分镜结构
  762. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  763. $episode['acts'] = $segmentsStructure['acts'];
  764. $episode['total_duration'] = $segmentsStructure['total_duration'];
  765. }
  766. return $episodes;
  767. }
  768. public function bindEpisodeVersion($data) {
  769. $episode_id = getProp($data, 'episode_id');
  770. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  771. if (!$episode) Utils::throwError('20003:该剧集不存在');
  772. $episode = (array)$episode;
  773. if ((int)$episode['is_default'] === 1) return true;
  774. try {
  775. DB::beginTransaction();
  776. // 移除is_default标志
  777. $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')]);
  778. if (!$boolen) {
  779. Utils::throwError('20003:更新失败!');
  780. }
  781. // 绑定副本
  782. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  783. if (!$boolen2) {
  784. Utils::throwError('20003:绑定失败!');
  785. }
  786. }catch (\Exception $e) {
  787. DB::rollBack();
  788. Utils::throwError('20003:'.$e->getMessage());
  789. }
  790. DB::commit();
  791. return true;
  792. }
  793. public function chatChangeImg($data) {
  794. $segment_id = getProp($data, 'segment_id');
  795. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  796. $prompt = getProp($data, 'prompt');
  797. if (!$prompt || !$segment_id) {
  798. Utils::throwError('1002:请输入提示词,并且选择分镜');
  799. }
  800. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  801. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  802. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  803. else $ref_img_url = '';
  804. // $ref_img_url = '';
  805. if (empty($prompt)) {
  806. if (empty($ref_img_url)) {
  807. $prompt = getProp($segment, 'segment_content');
  808. }else {
  809. $prompt = '请根据图片生成';
  810. }
  811. }
  812. $anime_id = getProp($segment, 'anime_id');
  813. $episode_id = getProp($segment, 'episode_id');
  814. $episode_number = getProp($segment, 'episode_number');
  815. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  816. $ratio = getProp($data, 'ratio');
  817. if (!$ratio) {
  818. $ratio = getProp($episode, 'ratio');
  819. if (!$ratio) $ratio = '9:16';
  820. }
  821. $art_style = getProp($episode, 'art_style');
  822. if ($art_style) {
  823. $prompt = "美术风格:{$art_style}\n{$prompt}";
  824. }
  825. $dimensions = $this->getRatioDimensions($ratio);
  826. $width = $dimensions['width'];
  827. $height = $dimensions['height'];
  828. try {
  829. $params = [
  830. 'alias_segment_id' => $segment_id,
  831. 'prompt' => $prompt,
  832. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  833. 'width' => $width,
  834. 'height' => $height
  835. ];
  836. // 优化提示词(不要生成字幕)
  837. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  838. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  839. $task_id = $task->id;
  840. if (!$task_id) {
  841. Utils::throwError("20003:生成图片失败");
  842. }
  843. // 更新任务ID
  844. $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')]);
  845. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  846. } catch (\Exception $e) {
  847. Utils::throwError("20003:" . $e->getMessage());
  848. }
  849. // 创建任务之后先暂停10s等待异步任务完成
  850. sleep(10);
  851. $img_url = $this->loopGetPicTaskResult($task_id);
  852. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  853. // 图片生成后新增对话记录
  854. try {
  855. $uid = Site::getUid();
  856. $now = date('Y-m-d H:i:s');
  857. // 使用AI反推图片提示词
  858. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  859. // 保存对话记录
  860. $records = [
  861. [
  862. 'uid' => $uid,
  863. 'anime_id' => $anime_id,
  864. 'sequence' => $episode_number,
  865. 'role' => 'user',
  866. 'content' => $prompt,
  867. 'segment_id' => $segment_id,
  868. 'pic_task_id' => $task_id,
  869. 'image_url' => '',
  870. 'created_at' => $now,
  871. 'updated_at' => $now
  872. ],
  873. [
  874. 'uid' => $uid,
  875. 'anime_id' => $anime_id,
  876. 'sequence' => $episode_number,
  877. 'role' => 'assistant',
  878. 'content' => $pic_prompt,
  879. 'segment_id' => $segment_id,
  880. 'pic_task_id' => $task_id,
  881. 'image_url' => $img_url,
  882. 'created_at' => $now,
  883. 'updated_at' => $now
  884. ]
  885. ];
  886. DB::table('mp_anime_records')->insert($records);
  887. } catch (\Exception $e) {
  888. // 记录日志但不影响主流程
  889. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  890. 'segment_id' => $segment_id,
  891. 'img_url' => $img_url
  892. ]);
  893. logDB('anime', 'error', '保存对话记录失败', [
  894. 'segment_id' => $segment_id,
  895. 'img_url' => $img_url,
  896. 'error' => $e->getMessage()
  897. ]);
  898. }
  899. return $img_url;
  900. }
  901. public function segmentChatHistory($data) {
  902. $segment_id = getProp($data, 'segment_id');
  903. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  904. $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');
  905. $chat = $query->orderBy('id')->get()->map(function ($value) {
  906. $value = (array)$value;
  907. $value['created_at'] = transDate($value['created_at']);
  908. return $value;
  909. })->toArray();
  910. // 获取历史图片
  911. $url = [];
  912. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  913. foreach($pic_history as $task) {
  914. $result_url = getProp($task, 'result_url');
  915. if (is_json($result_url)) {
  916. $url = array_merge($url, json_decode($result_url, true));
  917. }else {
  918. $url[] = $result_url;
  919. }
  920. }
  921. // 获取历史视频
  922. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  923. foreach($video_history as $task) {
  924. $result_url = getProp($task, 'compressed_url');
  925. if (is_json($result_url)) {
  926. $url = array_merge($url, json_decode($result_url, true));
  927. }else {
  928. $url[] = $result_url;
  929. }
  930. }
  931. return compact('chat', 'url');
  932. }
  933. public function changeEpisodeRoles($data) {
  934. $anime_id = getProp($data, 'anime_id');
  935. $episode_id = getProp($data, 'episode_id');
  936. $target_roles = getProp($data, 'roles');
  937. // 删除标志位于角色对象内部(roles.is_deleted),不在最外层
  938. $is_deleted = getProp($target_roles, 'is_deleted', 0);
  939. // 控制字段不随角色内容写入分集roles存储
  940. if (is_array($target_roles)) {
  941. unset($target_roles['is_deleted']);
  942. }
  943. // 参数验证
  944. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  945. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  946. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  947. // 验证剧集是否存在
  948. $episode = DB::table('mp_anime_episodes')
  949. ->where('anime_id', $anime_id)
  950. ->where('id', $episode_id)
  951. ->first();
  952. if (!$episode) Utils::throwError('20003:该剧集不存在');
  953. $roles = json_decode(getProp($episode, 'roles'), true);
  954. // 获取anime信息,检查是否有关联的script_id
  955. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  956. if (!$anime) Utils::throwError('20003:动漫不存在');
  957. $script_id = getProp($anime, 'script_id');
  958. $episode_number = getProp($episode, 'episode_number', 1);
  959. $uid = Site::getUid();
  960. $cpid = Site::getCpid();
  961. try {
  962. $target_role_name = getProp($target_roles, 'role');
  963. if (empty($target_role_name)) {
  964. Utils::throwError('20003:角色名称不能为空');
  965. }
  966. // 如果是删除操作
  967. if ($is_deleted == 1) {
  968. // 从角色列表中移除该角色
  969. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  970. return getProp($role, 'role') !== $target_role_name;
  971. }));
  972. // 更新角色列表
  973. $result = DB::table('mp_anime_episodes')
  974. ->where('anime_id', $anime_id)
  975. ->where('id', $episode_id)
  976. ->update([
  977. 'roles' => json_encode($roles, 256),
  978. 'updated_at' => date('Y-m-d H:i:s')
  979. ]);
  980. if ($result === false) {
  981. Utils::throwError('20003:删除角色失败');
  982. }
  983. } else {
  984. // 新增或更新操作
  985. $role_found = false;
  986. $is_new_role = false;
  987. // 查找并更新已存在的角色
  988. foreach($roles as &$role) {
  989. if (getProp($role, 'role') === $target_role_name) {
  990. $role = $target_roles;
  991. $role_found = true;
  992. break;
  993. }
  994. }
  995. // 如果角色不存在,则新增
  996. if (!$role_found) {
  997. $roles[] = $target_roles;
  998. $is_new_role = true;
  999. }
  1000. // 更新角色列表
  1001. $result = DB::table('mp_anime_episodes')
  1002. ->where('anime_id', $anime_id)
  1003. ->where('id', $episode_id)
  1004. ->update([
  1005. 'roles' => json_encode($roles, 256),
  1006. 'updated_at' => date('Y-m-d H:i:s')
  1007. ]);
  1008. if ($result === false) {
  1009. Utils::throwError('20003:更新角色列表失败');
  1010. }
  1011. // 同步更新分镜表中对应主体的音色信息
  1012. $voice_name = getProp($target_roles, 'voice_name');
  1013. $voice_type = getProp($target_roles, 'voice_type');
  1014. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1015. DB::table('mp_episode_segments')
  1016. ->where('anime_id', $anime_id)
  1017. ->where('episode_id', $episode_id)
  1018. ->where('voice_actor', $target_role_name)
  1019. ->update([
  1020. 'voice_name' => $voice_name,
  1021. 'voice_type' => $voice_type,
  1022. 'voice_audio_url' => $voice_audio_url,
  1023. 'updated_at' => date('Y-m-d H:i:s')
  1024. ]);
  1025. // 如果有关联的script_id,则同步到mp_products表
  1026. if ($script_id) {
  1027. // 查询剧本信息
  1028. $script = DB::table('mp_scripts')
  1029. ->where('id', $script_id)
  1030. ->where('is_deleted', 0)
  1031. ->first();
  1032. if ($script) {
  1033. $script_name = $script->script_name ?? 'script_' . $script_id;
  1034. $product_name = getProp($target_roles, 'role');
  1035. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1036. $url = getProp($target_roles, 'url', '');
  1037. $product_type = 1; // 1=角色
  1038. // 查找或创建以script_name命名的文件夹
  1039. $folder = DB::table('mp_products')
  1040. ->where('cpid', $cpid)
  1041. ->where('type', 2) // 文件夹类型
  1042. ->where('product', $product_type) // 角色类型
  1043. ->where('product_name', $script_name)
  1044. ->where('parent_id', 0)
  1045. ->where('is_deleted', 0)
  1046. ->first();
  1047. if (!$folder) {
  1048. // 创建文件夹
  1049. $folder_id = DB::table('mp_products')->insertGetId([
  1050. 'user_id' => $uid,
  1051. 'cpid' => $cpid,
  1052. 'type' => 2, // 文件夹
  1053. 'product' => $product_type, // 角色类型
  1054. 'parent_id' => 0,
  1055. 'level' => 1,
  1056. 'product_name' => $script_name,
  1057. 'sort_order' => time(),
  1058. 'is_deleted' => 0,
  1059. 'created_at' => date('Y-m-d H:i:s'),
  1060. 'updated_at' => date('Y-m-d H:i:s')
  1061. ]);
  1062. } else {
  1063. $folder_id = $folder->id;
  1064. }
  1065. // 查找该文件夹下是否已存在同名资产
  1066. $existing_product = DB::table('mp_products')
  1067. ->where('cpid', $cpid)
  1068. ->where('type', 1) // 资产类型
  1069. ->where('product', $product_type)
  1070. ->where('parent_id', $folder_id)
  1071. ->where('product_name', $product_name)
  1072. ->where('is_deleted', 0)
  1073. ->first();
  1074. if ($existing_product) {
  1075. // 更新已存在的资产
  1076. $updateData = [
  1077. 'pic_task_status' => '生成成功',
  1078. ];
  1079. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1080. if ($url) $updateData['url'] = $url;
  1081. // 处理versions字段
  1082. $versions = getProp($target_roles, 'versions', []);
  1083. if ($versions && is_array($versions)) {
  1084. $updateData['versions'] = json_encode($versions, 256);
  1085. }
  1086. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1087. DB::table('mp_products')
  1088. ->where('id', $existing_product->id)
  1089. ->update($updateData);
  1090. $product_id = $existing_product->id;
  1091. } else {
  1092. // 创建新资产
  1093. $versions = getProp($target_roles, 'versions', []);
  1094. $product_id = DB::table('mp_products')->insertGetId([
  1095. 'user_id' => $uid,
  1096. 'cpid' => $cpid,
  1097. 'type' => 1, // 资产
  1098. 'product' => $product_type, // 角色
  1099. 'parent_id' => $folder_id,
  1100. 'level' => 2,
  1101. 'product_name' => $product_name,
  1102. 'url' => $url,
  1103. 'pic_prompt' => $pic_prompt,
  1104. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1105. 'sort_order' => time(),
  1106. 'is_deleted' => 0,
  1107. 'pic_task_status' => '生成成功',
  1108. 'created_at' => date('Y-m-d H:i:s'),
  1109. 'updated_at' => date('Y-m-d H:i:s')
  1110. ]);
  1111. }
  1112. // 建立或更新绑定关系
  1113. $existing_mapping = DB::table('mp_script_product_mappings')
  1114. ->where('script_id', $script_id)
  1115. ->where('product_id', $product_id)
  1116. ->where('episode_number', $episode_number)
  1117. ->first();
  1118. if (!$existing_mapping) {
  1119. // 创建绑定关系
  1120. DB::table('mp_script_product_mappings')->insert([
  1121. 'script_id' => $script_id,
  1122. 'product_id' => $product_id,
  1123. 'episode_number' => $episode_number,
  1124. 'created_at' => date('Y-m-d H:i:s'),
  1125. 'updated_at' => date('Y-m-d H:i:s')
  1126. ]);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. } catch (\Exception $e) {
  1132. dLog('anime')->error('更新剧集角色失败', [
  1133. 'anime_id' => $anime_id,
  1134. 'episode_id' => $episode_id,
  1135. 'error' => $e->getMessage()
  1136. ]);
  1137. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1138. }
  1139. return true;
  1140. }
  1141. public function changeEpisodeScenes($data) {
  1142. $anime_id = getProp($data, 'anime_id');
  1143. $episode_id = getProp($data, 'episode_id');
  1144. $target_scenes = getProp($data, 'scenes');
  1145. // 删除标志位于场景对象内部(scenes.is_deleted),不在最外层
  1146. $is_deleted = getProp($target_scenes, 'is_deleted', 0);
  1147. // 控制字段不随场景内容写入分集scenes存储
  1148. if (is_array($target_scenes)) {
  1149. unset($target_scenes['is_deleted']);
  1150. }
  1151. // 参数验证
  1152. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1153. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1154. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1155. // 验证剧集是否存在
  1156. $episode = DB::table('mp_anime_episodes')
  1157. ->where('anime_id', $anime_id)
  1158. ->where('id', $episode_id)
  1159. ->first();
  1160. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1161. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1162. // 获取anime信息,检查是否有关联的script_id
  1163. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1164. if (!$anime) Utils::throwError('20003:动漫不存在');
  1165. $script_id = getProp($anime, 'script_id');
  1166. $episode_number = getProp($episode, 'episode_number', 1);
  1167. $uid = Site::getUid();
  1168. $cpid = Site::getCpid();
  1169. try {
  1170. $target_scene_name = getProp($target_scenes, 'scene');
  1171. if (empty($target_scene_name)) {
  1172. Utils::throwError('20003:场景名称不能为空');
  1173. }
  1174. // 如果是删除操作
  1175. if ($is_deleted == 1) {
  1176. // 从场景列表中移除该场景
  1177. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1178. return getProp($scene, 'scene') !== $target_scene_name;
  1179. }));
  1180. // 更新场景列表
  1181. $result = DB::table('mp_anime_episodes')
  1182. ->where('anime_id', $anime_id)
  1183. ->where('id', $episode_id)
  1184. ->update([
  1185. 'scenes' => json_encode($scenes, 256),
  1186. 'updated_at' => date('Y-m-d H:i:s')
  1187. ]);
  1188. if ($result === false) {
  1189. Utils::throwError('20003:删除场景失败');
  1190. }
  1191. } else {
  1192. // 新增或更新操作
  1193. $scene_found = false;
  1194. $is_new_scene = false;
  1195. // 查找并更新已存在的场景
  1196. foreach($scenes as &$scene) {
  1197. if (getProp($scene, 'scene') === $target_scene_name) {
  1198. $scene = $target_scenes;
  1199. $scene_found = true;
  1200. break;
  1201. }
  1202. }
  1203. // 如果场景不存在,则新增
  1204. if (!$scene_found) {
  1205. $scenes[] = $target_scenes;
  1206. $is_new_scene = true;
  1207. }
  1208. // 更新场景列表
  1209. $result = DB::table('mp_anime_episodes')
  1210. ->where('anime_id', $anime_id)
  1211. ->where('id', $episode_id)
  1212. ->update([
  1213. 'scenes' => json_encode($scenes, 256),
  1214. 'updated_at' => date('Y-m-d H:i:s')
  1215. ]);
  1216. if ($result === false) {
  1217. Utils::throwError('20003:更新场景列表失败');
  1218. }
  1219. // 如果有关联的script_id,则同步到mp_products表
  1220. if ($script_id) {
  1221. // 查询剧本信息
  1222. $script = DB::table('mp_scripts')
  1223. ->where('id', $script_id)
  1224. ->where('is_deleted', 0)
  1225. ->first();
  1226. if ($script) {
  1227. $script_name = $script->script_name ?? 'script_' . $script_id;
  1228. $product_name = getProp($target_scenes, 'scene');
  1229. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1230. $url = getProp($target_scenes, 'url', '');
  1231. $product_type = 2; // 2=场景
  1232. // 查找或创建以script_name命名的文件夹
  1233. $folder = DB::table('mp_products')
  1234. ->where('cpid', $cpid)
  1235. ->where('type', 2) // 文件夹类型
  1236. ->where('product', $product_type) // 场景类型
  1237. ->where('product_name', $script_name)
  1238. ->where('parent_id', 0)
  1239. ->where('is_deleted', 0)
  1240. ->first();
  1241. if (!$folder) {
  1242. // 创建文件夹
  1243. $folder_id = DB::table('mp_products')->insertGetId([
  1244. 'user_id' => $uid,
  1245. 'cpid' => $cpid,
  1246. 'type' => 2, // 文件夹
  1247. 'product' => $product_type, // 场景类型
  1248. 'parent_id' => 0,
  1249. 'level' => 1,
  1250. 'product_name' => $script_name,
  1251. 'sort_order' => time(),
  1252. 'is_deleted' => 0,
  1253. 'created_at' => date('Y-m-d H:i:s'),
  1254. 'updated_at' => date('Y-m-d H:i:s')
  1255. ]);
  1256. } else {
  1257. $folder_id = $folder->id;
  1258. }
  1259. // 查找该文件夹下是否已存在同名资产
  1260. $existing_product = DB::table('mp_products')
  1261. ->where('cpid', $cpid)
  1262. ->where('type', 1) // 资产类型
  1263. ->where('product', $product_type)
  1264. ->where('parent_id', $folder_id)
  1265. ->where('product_name', $product_name)
  1266. ->where('is_deleted', 0)
  1267. ->first();
  1268. if ($existing_product) {
  1269. // 更新已存在的资产
  1270. $updateData = [
  1271. 'pic_task_status' => '生成成功'
  1272. ];
  1273. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1274. if ($url) $updateData['url'] = $url;
  1275. // 处理versions字段
  1276. $versions = getProp($target_scenes, 'versions', []);
  1277. if ($versions && is_array($versions)) {
  1278. $updateData['versions'] = json_encode($versions, 256);
  1279. }
  1280. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1281. DB::table('mp_products')
  1282. ->where('id', $existing_product->id)
  1283. ->update($updateData);
  1284. $product_id = $existing_product->id;
  1285. } else {
  1286. // 创建新资产
  1287. $versions = getProp($target_scenes, 'versions', []);
  1288. $product_id = DB::table('mp_products')->insertGetId([
  1289. 'user_id' => $uid,
  1290. 'cpid' => $cpid,
  1291. 'type' => 1, // 资产
  1292. 'product' => $product_type, // 场景
  1293. 'parent_id' => $folder_id,
  1294. 'level' => 2,
  1295. 'product_name' => $product_name,
  1296. 'url' => $url,
  1297. 'pic_prompt' => $pic_prompt,
  1298. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1299. 'sort_order' => time(),
  1300. 'is_deleted' => 0,
  1301. 'pic_task_status' => '生成成功',
  1302. 'created_at' => date('Y-m-d H:i:s'),
  1303. 'updated_at' => date('Y-m-d H:i:s')
  1304. ]);
  1305. }
  1306. // 建立或更新绑定关系
  1307. $existing_mapping = DB::table('mp_script_product_mappings')
  1308. ->where('script_id', $script_id)
  1309. ->where('product_id', $product_id)
  1310. ->where('episode_number', $episode_number)
  1311. ->first();
  1312. if (!$existing_mapping) {
  1313. // 创建绑定关系
  1314. DB::table('mp_script_product_mappings')->insert([
  1315. 'script_id' => $script_id,
  1316. 'product_id' => $product_id,
  1317. 'episode_number' => $episode_number,
  1318. 'created_at' => date('Y-m-d H:i:s'),
  1319. 'updated_at' => date('Y-m-d H:i:s')
  1320. ]);
  1321. }
  1322. }
  1323. }
  1324. }
  1325. } catch (\Exception $e) {
  1326. dLog('anime')->error('更新剧集场景失败', [
  1327. 'anime_id' => $anime_id,
  1328. 'episode_id' => $episode_id,
  1329. 'error' => $e->getMessage()
  1330. ]);
  1331. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1332. }
  1333. return true;
  1334. }
  1335. public function changeEpisodeProps($data) {
  1336. $anime_id = getProp($data, 'anime_id');
  1337. $episode_id = getProp($data, 'episode_id');
  1338. $target_props = getProp($data, 'props');
  1339. // 删除标志位于道具对象内部(props.is_deleted),不在最外层
  1340. $is_deleted = getProp($target_props, 'is_deleted', 0);
  1341. // 控制字段不随道具内容写入分集props存储
  1342. if (is_array($target_props)) {
  1343. unset($target_props['is_deleted']);
  1344. }
  1345. // 参数验证
  1346. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1347. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1348. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1349. // 验证剧集是否存在
  1350. $episode = DB::table('mp_anime_episodes')
  1351. ->where('anime_id', $anime_id)
  1352. ->where('id', $episode_id)
  1353. ->first();
  1354. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1355. $props = json_decode(getProp($episode, 'props'), true);
  1356. // 获取anime信息,检查是否有关联的script_id
  1357. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1358. if (!$anime) Utils::throwError('20003:动漫不存在');
  1359. $script_id = getProp($anime, 'script_id');
  1360. $episode_number = getProp($episode, 'episode_number', 1);
  1361. $uid = Site::getUid();
  1362. $cpid = Site::getCpid();
  1363. try {
  1364. $target_prop_name = getProp($target_props, 'prop');
  1365. if (empty($target_prop_name)) {
  1366. Utils::throwError('20003:道具名称不能为空');
  1367. }
  1368. // 如果是删除操作
  1369. if ($is_deleted == 1) {
  1370. // 从道具列表中移除该道具
  1371. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1372. return getProp($prop, 'prop') !== $target_prop_name;
  1373. }));
  1374. // 更新道具列表
  1375. $result = DB::table('mp_anime_episodes')
  1376. ->where('anime_id', $anime_id)
  1377. ->where('id', $episode_id)
  1378. ->update([
  1379. 'props' => json_encode($props, 256),
  1380. 'updated_at' => date('Y-m-d H:i:s')
  1381. ]);
  1382. if ($result === false) {
  1383. Utils::throwError('20003:删除道具失败');
  1384. }
  1385. } else {
  1386. // 新增或更新操作
  1387. $prop_found = false;
  1388. $is_new_prop = false;
  1389. // 查找并更新已存在的道具
  1390. foreach($props as &$prop) {
  1391. if (getProp($prop, 'prop') === $target_prop_name) {
  1392. $prop = $target_props;
  1393. $prop_found = true;
  1394. break;
  1395. }
  1396. }
  1397. // 如果道具不存在,则新增
  1398. if (!$prop_found) {
  1399. $props[] = $target_props;
  1400. $is_new_prop = true;
  1401. }
  1402. // 更新道具列表
  1403. $result = DB::table('mp_anime_episodes')
  1404. ->where('anime_id', $anime_id)
  1405. ->where('id', $episode_id)
  1406. ->update([
  1407. 'props' => json_encode($props, 256),
  1408. 'updated_at' => date('Y-m-d H:i:s')
  1409. ]);
  1410. if ($result === false) {
  1411. Utils::throwError('20003:更新道具列表失败');
  1412. }
  1413. // 如果有关联的script_id,则同步到mp_products表
  1414. if ($script_id) {
  1415. // 查询剧本信息
  1416. $script = DB::table('mp_scripts')
  1417. ->where('id', $script_id)
  1418. ->where('is_deleted', 0)
  1419. ->first();
  1420. if ($script) {
  1421. $script_name = $script->script_name ?? 'script_' . $script_id;
  1422. $product_name = getProp($target_props, 'prop');
  1423. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1424. $url = getProp($target_props, 'url', '');
  1425. $product_type = 3; // 3=道具
  1426. // 查找或创建以script_name命名的文件夹
  1427. $folder = DB::table('mp_products')
  1428. ->where('cpid', $cpid)
  1429. ->where('type', 2) // 文件夹类型
  1430. ->where('product', $product_type) // 道具类型
  1431. ->where('product_name', $script_name)
  1432. ->where('parent_id', 0)
  1433. ->where('is_deleted', 0)
  1434. ->first();
  1435. if (!$folder) {
  1436. // 创建文件夹
  1437. $folder_id = DB::table('mp_products')->insertGetId([
  1438. 'user_id' => $uid,
  1439. 'cpid' => $cpid,
  1440. 'type' => 2, // 文件夹
  1441. 'product' => $product_type, // 道具类型
  1442. 'parent_id' => 0,
  1443. 'level' => 1,
  1444. 'product_name' => $script_name,
  1445. 'sort_order' => time(),
  1446. 'is_deleted' => 0,
  1447. 'created_at' => date('Y-m-d H:i:s'),
  1448. 'updated_at' => date('Y-m-d H:i:s')
  1449. ]);
  1450. } else {
  1451. $folder_id = $folder->id;
  1452. }
  1453. // 查找该文件夹下是否已存在同名资产
  1454. $existing_product = DB::table('mp_products')
  1455. ->where('cpid', $cpid)
  1456. ->where('type', 1) // 资产类型
  1457. ->where('product', $product_type)
  1458. ->where('parent_id', $folder_id)
  1459. ->where('product_name', $product_name)
  1460. ->where('is_deleted', 0)
  1461. ->first();
  1462. if ($existing_product) {
  1463. // 更新已存在的资产
  1464. $updateData = [
  1465. 'pic_task_status' => '生成成功'
  1466. ];
  1467. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1468. if ($url) $updateData['url'] = $url;
  1469. // 处理versions字段
  1470. $versions = getProp($target_props, 'versions', []);
  1471. if ($versions && is_array($versions)) {
  1472. $updateData['versions'] = json_encode($versions, 256);
  1473. }
  1474. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1475. DB::table('mp_products')
  1476. ->where('id', $existing_product->id)
  1477. ->update($updateData);
  1478. $product_id = $existing_product->id;
  1479. } else {
  1480. // 创建新资产
  1481. $versions = getProp($target_props, 'versions', []);
  1482. $product_id = DB::table('mp_products')->insertGetId([
  1483. 'user_id' => $uid,
  1484. 'cpid' => $cpid,
  1485. 'type' => 1, // 资产
  1486. 'product' => $product_type, // 道具
  1487. 'parent_id' => $folder_id,
  1488. 'level' => 2,
  1489. 'product_name' => $product_name,
  1490. 'url' => $url,
  1491. 'pic_prompt' => $pic_prompt,
  1492. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1493. 'sort_order' => time(),
  1494. 'is_deleted' => 0,
  1495. 'pic_task_status' => '生成成功',
  1496. 'created_at' => date('Y-m-d H:i:s'),
  1497. 'updated_at' => date('Y-m-d H:i:s')
  1498. ]);
  1499. }
  1500. // 建立或更新绑定关系
  1501. $existing_mapping = DB::table('mp_script_product_mappings')
  1502. ->where('script_id', $script_id)
  1503. ->where('product_id', $product_id)
  1504. ->where('episode_number', $episode_number)
  1505. ->first();
  1506. if (!$existing_mapping) {
  1507. // 创建绑定关系
  1508. DB::table('mp_script_product_mappings')->insert([
  1509. 'script_id' => $script_id,
  1510. 'product_id' => $product_id,
  1511. 'episode_number' => $episode_number,
  1512. 'created_at' => date('Y-m-d H:i:s'),
  1513. 'updated_at' => date('Y-m-d H:i:s')
  1514. ]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. } catch (\Exception $e) {
  1520. dLog('anime')->error('更新剧集道具失败', [
  1521. 'anime_id' => $anime_id,
  1522. 'episode_id' => $episode_id,
  1523. 'error' => $e->getMessage()
  1524. ]);
  1525. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1526. }
  1527. return true;
  1528. }
  1529. public function editSegment($data) {
  1530. $segment_id = getProp($data, 'segment_id');
  1531. $segment_content = getProp($data, 'segment_content');
  1532. $image_url = getProp($data, 'image_url');
  1533. $video_url = getProp($data, 'video_url');
  1534. // 参数验证
  1535. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1536. // 验证分镜是否存在
  1537. $segment = DB::table('mp_episode_segments')
  1538. ->where('segment_id', $segment_id)
  1539. ->first();
  1540. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1541. $dubTaskId = 0;
  1542. try {
  1543. DB::beginTransaction();
  1544. // 准备更新数据
  1545. $update_data = [
  1546. 'updated_at' => date('Y-m-d H:i:s')
  1547. ];
  1548. if ($segment_content) {
  1549. // 先将segment_content赋值到update_data
  1550. $update_data['segment_content'] = $segment_content;
  1551. // 使用现有方法分析segment_content,提取各个字段
  1552. $this->handleSegmentContent($update_data);
  1553. // 如果有对话内容,创建视频配音合成任务
  1554. $dialogue = getProp($update_data, 'dialogue');
  1555. if (!empty($dialogue)) {
  1556. $now = date('Y-m-d H:i:s');
  1557. $generate_json = [
  1558. 'text' => $dialogue,
  1559. 'role' => getProp($update_data, 'voice_actor'),
  1560. 'voice_type' => getProp($update_data, 'voice_type'),
  1561. 'voice_name' => getProp($update_data, 'voice_name'),
  1562. 'emotion' => getProp($update_data, 'emotion'),
  1563. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1564. 'gender' => getProp($update_data, 'gender'),
  1565. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1566. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1567. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1568. 'pitch' => getProp($update_data, 'pitch', 0),
  1569. ];
  1570. // 插入视频配音合成任务
  1571. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1572. 'alias_segment_id' => $segment_id,
  1573. 'generate_status' => '执行中',
  1574. 'audio_url' => '',
  1575. 'generate_json' => json_encode($generate_json, 256),
  1576. 'created_at' => $now,
  1577. 'updated_at' => $now,
  1578. ]);
  1579. if (!$dubTaskId) {
  1580. Utils::throwError('20003:创建配音任务失败!');
  1581. }
  1582. $update_data['audio_url'] = '';
  1583. } else {
  1584. // dialogue为空时,直接写入默认音频信息
  1585. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1586. $update_data['audio_duration'] = 2.0;
  1587. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1588. }
  1589. }
  1590. if ($image_url) {
  1591. $update_data['img_url'] = $image_url;
  1592. // 同时写入一个简单的图片生成任务
  1593. $pic_task = [
  1594. 'alias_segment_id' => $segment_id,
  1595. 'ref_img_url' => json_encode([]),
  1596. 'status' => 'success',
  1597. 'result_url' => json_encode([$image_url], 256),
  1598. 'model' => '',
  1599. 'created_at' => date('Y-m-d H:i:s'),
  1600. 'updated_at' => date('Y-m-d H:i:s'),
  1601. ];
  1602. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1603. }
  1604. if ($video_url) {
  1605. $update_data['origin_video_url'] = $video_url;
  1606. $compressed_video_url = compressVideo($video_url);
  1607. $update_data['current_type'] = 2;
  1608. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1609. // 同时写入一个简单的视频生成任务
  1610. $video_task = [
  1611. 'alias_segment_id' => $segment_id,
  1612. 'status' => 'success',
  1613. 'result_url' => $update_data['origin_video_url'],
  1614. 'compressed_url' => $update_data['video_url'],
  1615. 'created_at' => date('Y-m-d H:i:s'),
  1616. 'updated_at' => date('Y-m-d H:i:s'),
  1617. ];
  1618. DB::table('mp_generate_video_tasks')->insert($video_task);
  1619. }
  1620. // 更新分镜信息
  1621. $result = DB::table('mp_episode_segments')
  1622. ->where('segment_id', $segment_id)
  1623. ->update($update_data);
  1624. if ($result === false) {
  1625. Utils::throwError('20003:更新分镜剧本失败');
  1626. }
  1627. DB::commit();
  1628. // 如果有创建音频生成任务则调用API
  1629. if ($dubTaskId) {
  1630. // 请求远程服务器执行生成
  1631. $client = new Client(['timeout' => 300, 'verify' => false]);
  1632. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1633. $response = $result->getBody()->getContents();
  1634. $response_arr = json_decode($response, true);
  1635. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1636. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1637. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1638. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1639. Utils::throwError('20003:火山生成音频失败');
  1640. }
  1641. }
  1642. return true;
  1643. } catch (\Exception $e) {
  1644. DB::rollBack();
  1645. dLog('anime')->error('更新分镜剧本失败', [
  1646. 'segment_id' => $segment_id,
  1647. 'error' => $e->getMessage()
  1648. ]);
  1649. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1650. }
  1651. }
  1652. public function batchSetSegmentPics($data) {
  1653. $anime_id = getProp($data, 'anime_id');
  1654. $episode_id = getProp($data, 'episode_id');
  1655. $ratio = getProp($data, 'ratio');
  1656. $dimensions = $this->getRatioDimensions($ratio);
  1657. $width = $dimensions['width'];
  1658. $height = $dimensions['height'];
  1659. if (!$anime_id || !$episode_id) {
  1660. Utils::throwError('1002:请选择剧集');
  1661. }
  1662. // 获取剧集信息
  1663. $episode = DB::table('mp_anime_episodes')
  1664. ->where('anime_id', $anime_id)
  1665. ->where('id', $episode_id)
  1666. ->where('is_default', 1)
  1667. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1668. ->first();
  1669. if (!$episode) {
  1670. Utils::throwError('20003:该剧集不存在');
  1671. }
  1672. $model = getProp($data, 'model');
  1673. if (!$model) {
  1674. $model = getProp($episode, 'image_model');
  1675. if (!$model) {
  1676. // episode表也没有,使用默认值
  1677. $model = 'doubao-seedream-5-0-lite-260128';
  1678. }
  1679. }
  1680. // 验证模型是否在可用模型表中
  1681. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1682. $model = 'doubao-seedream-5-0-lite-260128';
  1683. }
  1684. $roles = json_decode(getProp($episode, 'roles'), true);
  1685. if (!$roles) {
  1686. Utils::throwError('20003:角色信息格式错误');
  1687. }
  1688. // 构建角色名称到参考图的映射
  1689. $role_map = [];
  1690. foreach ($roles as $role) {
  1691. $role_name = getProp($role, 'role');
  1692. $role_url = getProp($role, 'url');
  1693. if (!empty($role_name) && !empty($role_url)) {
  1694. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1695. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1696. // $role_map[$base_name] = $role_url;
  1697. // 同时保存完整名称的映射
  1698. $role_map[$role_name] = $role_url;
  1699. }
  1700. }
  1701. $scenes = json_decode(getProp($episode, 'roles'), true);
  1702. if (!$scenes) {
  1703. Utils::throwError('20003:场景信息格式错误');
  1704. }
  1705. // 构建角色名称到参考图的映射
  1706. $scene_map = [];
  1707. foreach ($scenes as $scene) {
  1708. $scene_name = getProp($scene, 'scene');
  1709. $scene_url = getProp($scene, 'url');
  1710. if (!empty($scene_name) && !empty($scene_url)) {
  1711. $scene_map[$scene_name] = $scene_url;
  1712. }
  1713. }
  1714. // 获取所有分镜信息
  1715. $segments = DB::table('mp_episode_segments')
  1716. ->where('anime_id', $anime_id)
  1717. ->where('episode_id', $episode_id)
  1718. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1719. ->orderBy('segment_number')
  1720. ->get()
  1721. ->toArray();
  1722. if (empty($segments)) {
  1723. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1724. }
  1725. // 保存图片比例
  1726. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1727. $updated_segments = [];
  1728. $failed_segments = [];
  1729. // 批量为每个分镜生成图片任务
  1730. foreach ($segments as $segment) {
  1731. $segment_id = $segment->segment_id;
  1732. $segment_content = $segment->segment_content;
  1733. if (empty($segment_content)) {
  1734. $failed_segments[] = [
  1735. 'segment_id' => $segment_id,
  1736. 'error' => '分镜内容为空'
  1737. ];
  1738. continue;
  1739. }
  1740. try {
  1741. $dubTaskId = 0;
  1742. // 解析分镜内容,提取画面描述作为主要提示词
  1743. $prompt = $segment_content;
  1744. $ref_img_urls = [];
  1745. // 分镜场景
  1746. $scene = getProp($segment, 'scene');
  1747. $matched_scene = '';
  1748. if (isset($scene_map[$scene])) {
  1749. $img_index = count($ref_img_urls) + 1;
  1750. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1751. $ref_img_urls[] = $scene_map[$scene];
  1752. $matched_scene = $scene;
  1753. }
  1754. // 分镜角色
  1755. $characters = getProp($segment, 'characters');
  1756. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1757. $roles = explode(',', $characters);
  1758. // 从分镜内容中提取涉及的角色
  1759. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1760. // 获取匹配角色的参考图
  1761. foreach ($segment_characters as $character) {
  1762. if (isset($role_map[$character])) {
  1763. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1764. $img_index = count($ref_img_urls) + 1;
  1765. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1766. $ref_img_urls[] = $role_map[$character];
  1767. }
  1768. }
  1769. // 如果没有找到匹配的角色参考图,不使用参考图
  1770. if (empty($ref_img_urls)) {
  1771. $ref_img_urls = [];
  1772. }
  1773. // 准备生成任务参数
  1774. $params = [
  1775. 'model' => $model,
  1776. 'alias_segment_id' => $segment_id,
  1777. 'prompt' => $prompt,
  1778. 'ref_img_urls' => $ref_img_urls,
  1779. 'width' => $width,
  1780. 'height' => $height,
  1781. ];
  1782. // 优化提示词(不要生成字幕)
  1783. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1784. // $task_id = mt_rand(100000, 999999);
  1785. // 调用AI图片生成服务
  1786. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1787. $task_id = $task->id;
  1788. if (!$task_id) {
  1789. $failed_segments[] = [
  1790. 'segment_id' => $segment_id,
  1791. 'error' => '创建生成任务失败'
  1792. ];
  1793. continue;
  1794. }
  1795. $update_data = [
  1796. 'pic_task_id' => $task_id,
  1797. 'pic_task_status' => '生成中',
  1798. 'audio_url' => '',
  1799. 'updated_at' => date('Y-m-d H:i:s')
  1800. ];
  1801. // 如果有对话内容,创建视频配音合成任务
  1802. $dialogue = getProp($segment, 'dialogue');
  1803. if (!empty($dialogue)) {
  1804. $now = date('Y-m-d H:i:s');
  1805. $generate_json = [
  1806. 'text' => $dialogue,
  1807. 'role' => getProp($segment, 'voice_actor'),
  1808. 'voice_type' => getProp($segment, 'voice_type'),
  1809. 'voice_name' => getProp($segment, 'voice_name'),
  1810. 'emotion' => getProp($segment, 'emotion'),
  1811. 'emotion_type' => getProp($segment, 'emotion_type'),
  1812. 'gender' => getProp($segment, 'gender'),
  1813. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1814. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1815. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1816. 'pitch' => getProp($segment, 'pitch', 0),
  1817. ];
  1818. // 插入视频配音合成任务
  1819. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1820. 'alias_segment_id' => $segment_id,
  1821. 'generate_status' => '执行中',
  1822. 'audio_url' => '',
  1823. 'generate_json' => json_encode($generate_json, 256),
  1824. 'created_at' => $now,
  1825. 'updated_at' => $now,
  1826. ]);
  1827. if (!$dubTaskId) {
  1828. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1829. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1830. // Utils::throwError('20003:创建配音任务失败!');
  1831. }
  1832. } else {
  1833. // dialogue为空时,直接写入默认音频信息到分镜表
  1834. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1835. $update_data['audio_duration'] = 2.0;
  1836. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1837. }
  1838. // 更新分镜的任务信息
  1839. $update_result = DB::table('mp_episode_segments')
  1840. ->where('segment_id', $segment_id)
  1841. ->update($update_data);
  1842. // 如果是第一集的首帧图片,则存入待更新数组
  1843. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1844. Redis::sadd('anime_first_frame_urls', $segment_id);
  1845. }
  1846. if ($update_result) {
  1847. $updated_segments[] = [
  1848. 'segment_id' => $segment_id,
  1849. 'task_id' => $task_id,
  1850. 'status' => '生成中',
  1851. 'matched_scenes' => $matched_scene,
  1852. 'matched_roles' => $segment_characters,
  1853. 'ref_urls_count' => count($ref_img_urls)
  1854. ];
  1855. } else {
  1856. $failed_segments[] = [
  1857. 'segment_id' => $segment_id,
  1858. 'error' => '更新分镜任务状态失败'
  1859. ];
  1860. }
  1861. if ($dubTaskId) {
  1862. sleep(1);
  1863. // 请求远程服务器执行生成
  1864. $client = new Client(['timeout' => 300, 'verify' => false]);
  1865. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1866. $response = $result->getBody()->getContents();
  1867. $response_arr = json_decode($response, true);
  1868. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1869. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1870. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1871. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1872. }
  1873. }
  1874. } catch (\Exception $e) {
  1875. $failed_segments[] = [
  1876. 'segment_id' => $segment_id,
  1877. 'error' => $e->getMessage()
  1878. ];
  1879. }
  1880. }
  1881. // 更新剧集生成状态
  1882. if (!empty($updated_segments)) {
  1883. DB::table('mp_anime_episodes')
  1884. ->where('id', $episode_id)
  1885. ->update([
  1886. 'is_generated' => 1,
  1887. 'updated_at' => date('Y-m-d H:i:s')
  1888. ]);
  1889. }
  1890. return [
  1891. 'success_count' => count($updated_segments),
  1892. 'failed_count' => count($failed_segments),
  1893. 'success_segments' => $updated_segments,
  1894. 'failed_segments' => $failed_segments,
  1895. 'total_segments' => count($segments)
  1896. ];
  1897. }
  1898. public function reGenerateSegment($data) {
  1899. $segment_id = getProp($data, 'segment_id');
  1900. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1901. $anime_id = getProp($segment, 'anime_id');
  1902. $episode_id = getProp($segment, 'episode_id');
  1903. $episode_number = getProp($segment, 'episode_number');
  1904. $segment_content = getProp($data, 'segment_content');
  1905. $ratio = getProp($data, 'ratio');
  1906. if (!$ratio) {
  1907. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1908. if (!$ratio) $ratio = '9:16';
  1909. }
  1910. $dimensions = $this->getRatioDimensions($ratio);
  1911. $width = $dimensions['width'];
  1912. $height = $dimensions['height'];
  1913. if (!$anime_id || !$episode_id) {
  1914. Utils::throwError('1002:请选择分镜');
  1915. }
  1916. // 使用文生文模型重新解析segment_content
  1917. if (!empty($segment_content)) {
  1918. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1919. }
  1920. // 获取动漫的角色信息(包含参考图)
  1921. $anime = DB::table('mp_animes')
  1922. ->where('id', $anime_id)
  1923. ->select('roles', 'scenes')
  1924. ->first();
  1925. if (!$anime || !$anime->roles) {
  1926. Utils::throwError('20003:未找到角色信息');
  1927. }
  1928. $roles = json_decode($anime->roles, true);
  1929. if (!$roles) {
  1930. Utils::throwError('20003:角色信息格式错误');
  1931. }
  1932. // 构建角色名称到参考图的映射
  1933. $role_map = [];
  1934. foreach ($roles as $role) {
  1935. $role_name = getProp($role, 'role');
  1936. $role_url = getProp($role, 'url');
  1937. if (!empty($role_name) && !empty($role_url)) {
  1938. $role_map[$role_name] = $role_url;
  1939. }
  1940. }
  1941. $scenes = json_decode($anime->scenes, true);
  1942. if (!$scenes) {
  1943. Utils::throwError('20003:角色信息格式错误');
  1944. }
  1945. // 构建角色名称到参考图的映射
  1946. $scene_map = [];
  1947. foreach ($scenes as $scene) {
  1948. $scene_name = getProp($scene, 'scene');
  1949. $scene_url = getProp($scene, 'url');
  1950. if (!empty($scene_name) && !empty($scene_url)) {
  1951. $scene_map[$scene_name] = $scene_url;
  1952. }
  1953. }
  1954. $segment_id = $segment->segment_id;
  1955. $original_segment_content = $segment->segment_content;
  1956. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1957. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1958. if (empty($final_segment_content)) {
  1959. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1960. }
  1961. try {
  1962. $dubTaskId = 0;
  1963. // 分镜剧本数组
  1964. $update_data = [
  1965. 'segment_content' => $final_segment_content,
  1966. 'pic_task_status' => '生成中',
  1967. 'updated_at' => date('Y-m-d H:i:s')
  1968. ];
  1969. // 解析分镜内容,提取画面描述作为主要提示词
  1970. $prompt = $final_segment_content;
  1971. $ref_img_urls = [];
  1972. // 分镜场景
  1973. $scene = getProp($data, 'scene');
  1974. if ($scene) {
  1975. $matched_scene = '';
  1976. if (isset($scene_map[$scene])) {
  1977. $img_index = count($ref_img_urls) + 1;
  1978. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1979. $ref_img_urls[] = $scene_map[$scene];
  1980. $matched_scene = $scene;
  1981. }
  1982. $update_data['scene'] = $scene;
  1983. }
  1984. // 分镜角色
  1985. $characters = getProp($data, 'characters');
  1986. if ($characters) {
  1987. $update_data['characters'] = $characters;
  1988. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1989. $characters = explode(',', $characters);
  1990. // 从分镜内容中提取涉及的角色
  1991. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1992. // 获取匹配角色的参考图
  1993. foreach ($segment_characters as $character) {
  1994. if (isset($role_map[$character])) {
  1995. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1996. $img_index = count($ref_img_urls) + 1;
  1997. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1998. $ref_img_urls[] = $role_map[$character];
  1999. }
  2000. }
  2001. }
  2002. // 如果没有找到匹配的角色参考图,不使用参考图
  2003. if (empty($ref_img_urls)) {
  2004. $ref_img_urls = [];
  2005. }
  2006. // 准备生成任务参数
  2007. $params = [
  2008. 'alias_segment_id' => $segment_id,
  2009. 'prompt' => $prompt,
  2010. 'ref_img_urls' => $ref_img_urls,
  2011. 'width' => $width,
  2012. 'height' => $height,
  2013. ];
  2014. // 优化提示词(不要生成字幕)
  2015. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2016. // 调用AI图片生成服务
  2017. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2018. $task_id = $task->id;
  2019. if (!$task_id) {
  2020. Utils::throwError('20003:创建生成任务失败!');
  2021. }
  2022. $update_data['pic_task_id'] = $task_id;
  2023. // 更新分镜剧本信息
  2024. $this->handleSegmentContent($update_data);
  2025. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2026. if ($segment_content) {
  2027. $dialogue = getProp($update_data, 'dialogue');
  2028. if (!empty($dialogue)) {
  2029. $now = date('Y-m-d H:i:s');
  2030. $generate_json = [
  2031. 'text' => $dialogue,
  2032. 'role' => getProp($update_data, 'voice_actor'),
  2033. 'voice_type' => getProp($update_data, 'voice_type'),
  2034. 'voice_name' => getProp($update_data, 'voice_name'),
  2035. 'emotion' => getProp($update_data, 'emotion'),
  2036. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2037. 'gender' => getProp($update_data, 'gender'),
  2038. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2039. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2040. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2041. 'pitch' => getProp($update_data, 'pitch', 0),
  2042. ];
  2043. // 插入视频配音合成任务
  2044. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2045. 'alias_segment_id' => $segment_id,
  2046. 'generate_status' => '执行中',
  2047. 'audio_url' => '',
  2048. 'generate_json' => json_encode($generate_json, 256),
  2049. 'created_at' => date('Y-m-d H:i:s'),
  2050. 'updated_at' => date('Y-m-d H:i:s'),
  2051. ]);
  2052. if (!$dubTaskId) {
  2053. Utils::throwError('20003:创建配音任务失败!');
  2054. }
  2055. $update_data['audio_url'] = '';
  2056. } else {
  2057. // dialogue为空时,直接写入默认音频信息
  2058. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2059. $update_data['audio_duration'] = 2.0;
  2060. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2061. }
  2062. }
  2063. $boolen = DB::table('mp_episode_segments')
  2064. ->where('segment_id', $segment_id)
  2065. ->update($update_data);
  2066. // 如果是第一集的首帧图片,则存入待更新数组
  2067. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2068. Redis::sadd('anime_first_frame_urls', $segment_id);
  2069. }
  2070. if ($dubTaskId) {
  2071. // 请求远程服务器执行生成
  2072. $client = new Client(['timeout' => 300, 'verify' => false]);
  2073. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2074. $response = $result->getBody()->getContents();
  2075. $response_arr = json_decode($response, true);
  2076. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2077. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2078. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2079. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2080. Utils::throwError('20003:火山生成音频失败');
  2081. }
  2082. }
  2083. } catch (\Exception $e) {
  2084. $failed_segments[] = [
  2085. 'segment_id' => $segment_id,
  2086. 'error' => $e->getMessage()
  2087. ];
  2088. }
  2089. // 创建任务之后先暂停10s等待异步任务完成
  2090. sleep(10);
  2091. $img_url = $this->loopGetPicTaskResult($task_id);
  2092. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2093. // 图片生成后新增对话记录
  2094. try {
  2095. $uid = Site::getUid();
  2096. $now = date('Y-m-d H:i:s');
  2097. // 使用AI反推图片提示词
  2098. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2099. // 保存对话记录
  2100. $records = [
  2101. [
  2102. 'uid' => $uid,
  2103. 'anime_id' => $anime_id,
  2104. 'sequence' => $episode_number,
  2105. 'role' => 'user',
  2106. 'content' => '重新生成',
  2107. 'segment_id' => $segment_id,
  2108. 'pic_task_id' => $task_id,
  2109. 'image_url' => '',
  2110. 'created_at' => $now,
  2111. 'updated_at' => $now
  2112. ],
  2113. [
  2114. 'uid' => $uid,
  2115. 'anime_id' => $anime_id,
  2116. 'sequence' => $episode_number,
  2117. 'role' => 'assistant',
  2118. 'content' => $pic_prompt,
  2119. 'segment_id' => $segment_id,
  2120. 'pic_task_id' => $task_id,
  2121. 'image_url' => $img_url,
  2122. 'created_at' => $now,
  2123. 'updated_at' => $now
  2124. ]
  2125. ];
  2126. DB::table('mp_anime_records')->insert($records);
  2127. } catch (\Exception $e) {
  2128. // 记录日志但不影响主流程
  2129. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2130. 'segment_id' => $segment_id,
  2131. 'img_url' => $img_url
  2132. ]);
  2133. }
  2134. return $img_url;
  2135. }
  2136. public function addSegment($data) {
  2137. $prev_segment_id = getProp($data, 'prev_segment_id');
  2138. $img_url = getProp($data, 'img_url');
  2139. $video_url = getProp($data, 'video_url');
  2140. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2141. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2142. $anime_id = getProp($segment, 'anime_id');
  2143. $episode_id = getProp($segment, 'episode_id');
  2144. $episode_number = getProp($segment, 'episode_number');
  2145. $segment_number = getProp($segment, 'segment_number');
  2146. $new_segment_number = $segment_number + 1;
  2147. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2148. // 分镜剧本数组
  2149. $insert_data = [
  2150. 'anime_id' => $anime_id,
  2151. 'episode_id' => $episode_id,
  2152. 'episode_number' => $episode_number,
  2153. 'act_number' => getProp($segment, 'act_number'),
  2154. 'act_title' => getProp($segment, 'act_title'),
  2155. 'segment_id' => $segment_id,
  2156. 'segment_number' => $new_segment_number,
  2157. 'segment_content' => '',
  2158. 'img_url' => '',
  2159. 'video_url' => '',
  2160. 'created_at' => date('Y-m-d H:i:s'),
  2161. 'updated_at' => date('Y-m-d H:i:s')
  2162. ];
  2163. if ($img_url) $insert_data['img_url'] = $img_url;
  2164. if ($video_url) {
  2165. $insert_data['origin_video_url'] = $video_url;
  2166. $insert_data['current_type'] = 2;
  2167. $compressed_video_url = compressVideo($video_url);
  2168. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2169. }
  2170. try {
  2171. DB::beginTransaction();
  2172. // 先更新序号
  2173. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2174. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2175. if (!$id) {
  2176. Utils::throwError('20003:新增分镜失败!');
  2177. }
  2178. }catch (\Exception $e) {
  2179. DB::rollBack();
  2180. Utils::throwError('20003:'.$e->getMessage());
  2181. }
  2182. DB::commit();
  2183. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2184. $segment = $segment ? (array)$segment : [];
  2185. return $segment;
  2186. // 以下代码暂弃用
  2187. $anime_id = getProp($segment, 'anime_id');
  2188. $episode_id = getProp($segment, 'episode_id');
  2189. $episode_number = getProp($segment, 'episode_number');
  2190. $segment_number = getProp($segment, 'segment_number');
  2191. $segment_content = getProp($data, 'segment_content');
  2192. $img_url = getProp($data, 'img_url');
  2193. $video_url = getProp($data, 'video_url');
  2194. $ratio = getProp($data, 'ratio');
  2195. $dimensions = $this->getRatioDimensions($ratio);
  2196. $width = $dimensions['width'];
  2197. $height = $dimensions['height'];
  2198. if (!$anime_id || !$episode_id) {
  2199. Utils::throwError('1002:请选择分镜');
  2200. }
  2201. // 使用文生文模型重新解析segment_content
  2202. if (!empty($segment_content)) {
  2203. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2204. }
  2205. // 获取动漫的角色信息(包含参考图)
  2206. $anime = DB::table('mp_animes')
  2207. ->where('id', $anime_id)
  2208. ->select('roles', 'scenes')
  2209. ->first();
  2210. if (!$anime || !$anime->roles) {
  2211. Utils::throwError('20003:未找到角色信息');
  2212. }
  2213. $roles = json_decode($anime->roles, true);
  2214. if (!$roles) {
  2215. Utils::throwError('20003:角色信息格式错误');
  2216. }
  2217. // 构建角色名称到参考图的映射
  2218. $role_map = [];
  2219. foreach ($roles as $role) {
  2220. $role_name = getProp($role, 'role');
  2221. $role_url = getProp($role, 'url');
  2222. if (!empty($role_name) && !empty($role_url)) {
  2223. $role_map[$role_name] = $role_url;
  2224. }
  2225. }
  2226. $scenes = json_decode($anime->scenes, true);
  2227. if (!$scenes) {
  2228. Utils::throwError('20003:角色信息格式错误');
  2229. }
  2230. // 构建角色名称到参考图的映射
  2231. $scene_map = [];
  2232. foreach ($scenes as $scene) {
  2233. $scene_name = getProp($scene, 'scene');
  2234. $scene_url = getProp($scene, 'url');
  2235. if (!empty($scene_name) && !empty($scene_url)) {
  2236. $scene_map[$scene_name] = $scene_url;
  2237. }
  2238. }
  2239. $segment_id = $segment->segment_id;
  2240. $original_segment_content = $segment->segment_content;
  2241. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2242. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2243. if (empty($final_segment_content)) {
  2244. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2245. }
  2246. try {
  2247. $dubTaskId = 0;
  2248. DB::beginTransaction();
  2249. $new_segment_number = $segment_number + 1;
  2250. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2251. // 分镜剧本数组
  2252. $insert_data = [
  2253. 'anime_id' => $anime_id,
  2254. 'episode_id' => $episode_id,
  2255. 'episode_number' => $episode_number,
  2256. 'act_number' => getProp($segment, 'act_number'),
  2257. 'act_title' => getProp($segment, 'act_title'),
  2258. 'segment_id' => $segment_id,
  2259. 'segment_number' => $new_segment_number,
  2260. 'segment_content' => $final_segment_content,
  2261. 'img_url' => $img_url,
  2262. 'video_url' => $video_url,
  2263. 'created_at' => date('Y-m-d H:i:s'),
  2264. 'updated_at' => date('Y-m-d H:i:s')
  2265. ];
  2266. // 更新分镜剧本信息
  2267. $this->handleSegmentContent($insert_data);
  2268. // 如果有对话内容,创建视频配音合成任务
  2269. $dialogue = getProp($insert_data, 'dialogue');
  2270. if (!empty($dialogue)) {
  2271. $now = date('Y-m-d H:i:s');
  2272. $generate_json = [
  2273. 'text' => $dialogue,
  2274. 'role' => getProp($insert_data, 'voice_actor'),
  2275. 'voice_type' => getProp($insert_data, 'voice_type'),
  2276. 'voice_name' => getProp($insert_data, 'voice_name'),
  2277. 'emotion' => getProp($insert_data, 'emotion'),
  2278. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2279. 'gender' => getProp($insert_data, 'gender'),
  2280. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2281. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2282. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2283. 'pitch' => getProp($insert_data, 'pitch', 0),
  2284. ];
  2285. // 插入视频配音合成任务
  2286. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2287. 'alias_segment_id' => $segment_id,
  2288. 'generate_status' => '执行中',
  2289. 'audio_url' => '',
  2290. 'generate_json' => json_encode($generate_json, 256),
  2291. 'created_at' => $now,
  2292. 'updated_at' => $now,
  2293. ]);
  2294. if (!$dubTaskId) {
  2295. Utils::throwError('20003:创建配音任务失败!');
  2296. }
  2297. $insert_data['audio_url'] = '';
  2298. } else {
  2299. // dialogue为空时,直接写入默认音频信息
  2300. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2301. $insert_data['audio_duration'] = 2.0;
  2302. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2303. }
  2304. // 如果没有上传图片则使用当前描述进行生成
  2305. if (!$img_url) {
  2306. // 解析分镜内容,提取画面描述作为主要提示词
  2307. $prompt = $final_segment_content;
  2308. $ref_img_urls = [];
  2309. // 分镜场景
  2310. $scene = getProp($insert_data, 'scene');
  2311. if ($scene) {
  2312. $matched_scene = '';
  2313. if (isset($scene_map[$scene])) {
  2314. $img_index = count($ref_img_urls) + 1;
  2315. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2316. $ref_img_urls[] = $scene_map[$scene];
  2317. $matched_scene = $scene;
  2318. }
  2319. $update_data['scene'] = $scene;
  2320. }
  2321. // 分镜角色
  2322. $characters = getProp($insert_data, 'characters');
  2323. if ($characters) {
  2324. $update_data['characters'] = $characters;
  2325. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2326. $characters = explode(',', $characters);
  2327. // 从分镜内容中提取涉及的角色
  2328. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2329. // 获取匹配角色的参考图
  2330. foreach ($segment_characters as $character) {
  2331. if (isset($role_map[$character])) {
  2332. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2333. $img_index = count($ref_img_urls) + 1;
  2334. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2335. $ref_img_urls[] = $role_map[$character];
  2336. }
  2337. }
  2338. }
  2339. // 如果没有找到匹配的角色参考图,不使用参考图
  2340. if (empty($ref_img_urls)) {
  2341. $ref_img_urls = [];
  2342. }
  2343. // 准备生成任务参数
  2344. $params = [
  2345. 'alias_segment_id' => $segment_id,
  2346. 'prompt' => $prompt,
  2347. 'ref_img_urls' => $ref_img_urls,
  2348. 'width' => $width,
  2349. 'height' => $height,
  2350. ];
  2351. // 调用AI图片生成服务
  2352. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2353. $task_id = $task->id;
  2354. // $task_id = 'whatever';
  2355. if (!$task_id) {
  2356. Utils::throwError('20003:创建生成任务失败!');
  2357. }
  2358. $insert_data['pic_task_status'] = '生成中';
  2359. $insert_data['pic_task_id'] = $task_id;
  2360. }
  2361. // 先更新序号
  2362. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2363. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2364. if (!$boolen) {
  2365. Utils::throwError('20003:新增分镜失败!');
  2366. }
  2367. // 如果是第一集的首帧图片,则存入待更新数组
  2368. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2369. Redis::sadd('anime_first_frame_urls', $segment_id);
  2370. }
  2371. if ($dubTaskId) {
  2372. // 请求远程服务器执行生成
  2373. $client = new Client(['timeout' => 300, 'verify' => false]);
  2374. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2375. $response = $result->getBody()->getContents();
  2376. $response_arr = json_decode($response, true);
  2377. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2378. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2379. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2380. Utils::throwError('20003:火山生成音频失败');
  2381. }
  2382. }
  2383. } catch (\Exception $e) {
  2384. DB::rollBack();
  2385. Utils::throwError('20003:'.$e->getMessage());
  2386. }
  2387. DB::commit();
  2388. // 创建任务之后先暂停10s等待异步任务完成
  2389. sleep(10);
  2390. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2391. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2392. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2393. $segment = $segment ? (array)$segment : [];
  2394. return $segment;
  2395. }
  2396. public function copySegment($data) {
  2397. $segment_id = getProp($data, 'segment_id');
  2398. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2399. if (!$segment) Utils::throwError('20003:请选择分镜');
  2400. $anime_id = getProp($segment, 'anime_id');
  2401. $episode_id = getProp($segment, 'episode_id');
  2402. $episode_number = getProp($segment, 'episode_number');
  2403. $segment_number = getProp($segment, 'segment_number');
  2404. $new_segment_id = 0;
  2405. try {
  2406. DB::beginTransaction();
  2407. $segment = (array)$segment;
  2408. unset($segment['id']);
  2409. $segment['segment_number'] += 1;
  2410. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2411. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2412. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2413. // 更新其他分镜序号
  2414. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2415. // 复制分镜
  2416. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2417. if (!$id) {
  2418. Utils::throwError('20003:复制分镜失败');
  2419. }
  2420. }catch (\Exception $e) {
  2421. DB::rollBack();
  2422. Utils::throwError('20003:'.$e->getMessage());
  2423. }
  2424. DB::commit();
  2425. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2426. $segment = $segment ? (array)$segment : [];
  2427. return $segment;
  2428. }
  2429. public function moveSegment($data) {
  2430. $segment_id = getProp($data, 'segment_id');
  2431. $target_segment_id = getProp($data, 'target_segment_id');
  2432. // 获取源分镜信息
  2433. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2434. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2435. // 获取目标分镜信息
  2436. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2437. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2438. $anime_id = getProp($source_segment, 'anime_id');
  2439. $episode_id = getProp($source_segment, 'episode_id');
  2440. $episode_number = getProp($source_segment, 'episode_number');
  2441. $source_segment_number = getProp($source_segment, 'segment_number');
  2442. $target_segment_number = getProp($target_segment, 'segment_number');
  2443. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2444. $target_anime_id = getProp($target_segment, 'anime_id');
  2445. $target_episode_number = getProp($target_segment, 'episode_number');
  2446. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2447. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2448. }
  2449. // 如果源分镜和目标分镜相同,无需移动
  2450. if ($source_segment_number == $target_segment_number) {
  2451. return true;
  2452. }
  2453. try {
  2454. DB::beginTransaction();
  2455. if ($source_segment_number < $target_segment_number) {
  2456. // 向后移动:源分镜移动到目标分镜之后
  2457. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2458. DB::table('mp_episode_segments')
  2459. ->where('anime_id', $anime_id)
  2460. ->where('episode_id', $episode_id)
  2461. ->where('segment_number', '>', $source_segment_number)
  2462. ->where('segment_number', '<=', $target_segment_number)
  2463. ->decrement('segment_number');
  2464. // 2. 将源分镜移动到目标分镜之后
  2465. $new_segment_number = $target_segment_number;
  2466. } else {
  2467. // 向前移动:源分镜移动到目标分镜之后
  2468. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2469. DB::table('mp_episode_segments')
  2470. ->where('anime_id', $anime_id)
  2471. ->where('episode_id', $episode_id)
  2472. ->where('segment_number', '>', $target_segment_number)
  2473. ->where('segment_number', '<', $source_segment_number)
  2474. ->increment('segment_number');
  2475. // 2. 将源分镜移动到目标分镜之后
  2476. $new_segment_number = $target_segment_number + 1;
  2477. }
  2478. // 3. 更新源分镜的序号
  2479. $update_result = DB::table('mp_episode_segments')
  2480. ->where('segment_id', $segment_id)
  2481. ->update([
  2482. 'segment_number' => $new_segment_number,
  2483. 'updated_at' => date('Y-m-d H:i:s')
  2484. ]);
  2485. if (!$update_result) {
  2486. Utils::throwError('20003:更新分镜序号失败');
  2487. }
  2488. DB::commit();
  2489. return true;
  2490. } catch (\Exception $e) {
  2491. DB::rollBack();
  2492. Utils::throwError('20003:' . $e->getMessage());
  2493. }
  2494. }
  2495. public function delSegment($data) {
  2496. $segment_id = getProp($data, 'segment_id');
  2497. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2498. if (!$segment) Utils::throwError('20003:请选择分镜');
  2499. $anime_id = getProp($segment, 'anime_id');
  2500. $episode_id = getProp($segment, 'episode_id');
  2501. $episode_number = getProp($segment, 'episode_number');
  2502. $segment_number = getProp($segment, 'segment_number');
  2503. try {
  2504. DB::beginTransaction();
  2505. // 删除分镜
  2506. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2507. if (!$boolen) {
  2508. Utils::throwError('20003:删除分镜失败');
  2509. }
  2510. // 更新其他分镜序号
  2511. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2512. }catch (\Exception $e) {
  2513. DB::rollBack();
  2514. Utils::throwError('20003:'.$e->getMessage());
  2515. }
  2516. DB::commit();
  2517. return true;
  2518. }
  2519. public function applySegment($data) {
  2520. $segment_id = getProp($data, 'segment_id');
  2521. $url = getProp($data, 'url');
  2522. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2523. if (!$url) Utils::throwError('20003:URL不能为空');
  2524. // 获取URL的文件扩展名
  2525. $urlPath = parse_url($url, PHP_URL_PATH);
  2526. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2527. // 定义图片和视频的扩展名
  2528. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2529. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2530. // 判断是图片还是视频
  2531. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2532. if (in_array($extension, $imageExtensions)) {
  2533. // 图片类型
  2534. $updateData['img_url'] = $url;
  2535. $updateData['current_type'] = 1;
  2536. } elseif (in_array($extension, $videoExtensions)) {
  2537. // 视频类型
  2538. $updateData['video_url'] = $url;
  2539. $updateData['current_type'] = 2;
  2540. } else {
  2541. Utils::throwError('20003:不支持的文件类型');
  2542. }
  2543. // 更新分镜表
  2544. $result = DB::table('mp_episode_segments')
  2545. ->where('segment_id', $segment_id)
  2546. ->update($updateData);
  2547. if (!$result) {
  2548. Utils::throwError('20003:更新分镜失败');
  2549. }
  2550. return true;
  2551. }
  2552. public function segmentHistory($data) {
  2553. $segment_id = getProp($data, 'segment_id');
  2554. // 获取历史图片
  2555. $pics = [];
  2556. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2557. foreach($pic_history as $task) {
  2558. $result_url = getProp($task, 'result_url');
  2559. if (is_json($result_url)) {
  2560. $pics = array_merge($pics, json_decode($result_url, true));
  2561. }else {
  2562. $pics[] = $result_url;
  2563. }
  2564. }
  2565. // 获取历史视频
  2566. $videos = [];
  2567. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2568. foreach($video_history as $task) {
  2569. $result_url = getProp($task, 'result_url');
  2570. if (is_json($result_url)) {
  2571. $videos = array_merge($videos, json_decode($result_url, true));
  2572. }else {
  2573. $videos[] = $result_url;
  2574. }
  2575. }
  2576. return compact('pics', 'videos');
  2577. }
  2578. public function addAct($data) {
  2579. $prev_act_id = getProp($data, 'prev_act_id');
  2580. $act_title = getProp($data, 'act_title', '');
  2581. $act_content = getProp($data, 'act_content', '');
  2582. $act_duration = getProp($data, 'act_duration', 5);
  2583. $video_url = getProp($data, 'video_url');
  2584. // 根据prev_act_id获取记录
  2585. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2586. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2587. $anime_id = getProp($prev_segment, 'anime_id');
  2588. $episode_id = getProp($prev_segment, 'episode_id');
  2589. $episode_number = getProp($prev_segment, 'episode_number');
  2590. $prev_act_number = getProp($prev_segment, 'act_number');
  2591. // 获取新的act_number
  2592. $new_act_number = $prev_act_number + 1;
  2593. try {
  2594. DB::beginTransaction();
  2595. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2596. DB::table('mp_episode_segments')
  2597. ->where('anime_id', $anime_id)
  2598. ->where('episode_id', $episode_id)
  2599. ->where('act_number', '>', $prev_act_number)
  2600. ->increment('act_number');
  2601. // 插入新片段记录
  2602. $insert_data = [
  2603. 'anime_id' => $anime_id,
  2604. 'episode_id' => $episode_id,
  2605. 'episode_number' => $episode_number,
  2606. 'act_number' => $new_act_number,
  2607. 'created_at' => date('Y-m-d H:i:s'),
  2608. 'updated_at' => date('Y-m-d H:i:s')
  2609. ];
  2610. if ($act_title) {
  2611. $insert_data['act_title'] = $act_title;
  2612. }
  2613. if ($act_content) {
  2614. $insert_data['act_content'] = $act_content;
  2615. }
  2616. if ($act_duration) {
  2617. $insert_data['act_duration'] = $act_duration;
  2618. }
  2619. if ($video_url) {
  2620. $insert_data['origin_video_url'] = $video_url;
  2621. $insert_data['current_type'] = 2;
  2622. $compressed_video_url = compressVideo($video_url);
  2623. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2624. }
  2625. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2626. if (!$id) {
  2627. Utils::throwError('20003:新增片段失败!');
  2628. }
  2629. DB::commit();
  2630. }catch (\Exception $e) {
  2631. DB::rollBack();
  2632. Utils::throwError('20003:'.$e->getMessage());
  2633. }
  2634. $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();
  2635. $segment = $segment ? (array)$segment : [];
  2636. return $segment;
  2637. }
  2638. public function editAct($data) {
  2639. $act_id = getProp($data, 'act_id');
  2640. $act_content = getProp($data, 'act_content');
  2641. $act_duration = getProp($data, 'act_duration');
  2642. $act_title = getProp($data, 'act_title');
  2643. $image_url = getProp($data, 'image_url');
  2644. $video_url = getProp($data, 'video_url');
  2645. // 参数验证
  2646. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2647. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2648. $segment = DB::table('mp_episode_segments')
  2649. ->where('id', $act_id)
  2650. ->first();
  2651. if (!$segment) Utils::throwError('20003:该片段不存在');
  2652. try {
  2653. DB::beginTransaction();
  2654. // 准备更新数据
  2655. $update_data = [
  2656. 'updated_at' => date('Y-m-d H:i:s')
  2657. ];
  2658. // 更新act相关字段
  2659. if (!empty($act_content)) {
  2660. $update_data['act_show_content'] = $act_content;
  2661. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2662. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2663. $shot_counter = 0;
  2664. $update_data['act_show_content'] = preg_replace_callback(
  2665. '/【(?:镜头|分镜)(\d+)】/u',
  2666. function($matches) use (&$shot_counter) {
  2667. $shot_counter++;
  2668. return '【镜头' . $shot_counter . '】';
  2669. },
  2670. $update_data['act_show_content']
  2671. );
  2672. }
  2673. if (!empty($act_duration)) {
  2674. $update_data['act_duration'] = $act_duration;
  2675. }
  2676. if (!empty($act_title)) {
  2677. $update_data['act_title'] = $act_title;
  2678. }
  2679. // 处理图片上传
  2680. if ($image_url) {
  2681. $update_data['img_url'] = $image_url;
  2682. $update_data['current_type'] = 1;
  2683. // 同时写入一个图片生成任务记录
  2684. if ($act_id) {
  2685. $pic_task = [
  2686. 'alias_act_id' => $act_id,
  2687. 'ref_img_url' => json_encode([]),
  2688. 'status' => 'success',
  2689. 'result_url' => json_encode([$image_url], 256),
  2690. 'model' => '',
  2691. 'created_at' => date('Y-m-d H:i:s'),
  2692. 'updated_at' => date('Y-m-d H:i:s'),
  2693. ];
  2694. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2695. }
  2696. }
  2697. // 处理视频上传
  2698. if ($video_url) {
  2699. $update_data['origin_video_url'] = $video_url;
  2700. $compressed_video_url = compressVideo($video_url);
  2701. $update_data['current_type'] = 2;
  2702. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2703. // 同时写入一个视频生成任务记录
  2704. if ($act_id) {
  2705. $video_task = [
  2706. 'alias_act_id' => $act_id,
  2707. 'status' => 'success',
  2708. 'result_url' => $update_data['origin_video_url'],
  2709. 'compressed_url' => $update_data['video_url'],
  2710. 'created_at' => date('Y-m-d H:i:s'),
  2711. 'updated_at' => date('Y-m-d H:i:s'),
  2712. ];
  2713. DB::table('mp_generate_video_tasks')->insert($video_task);
  2714. }
  2715. }
  2716. // 更新片段信息
  2717. $result = DB::table('mp_episode_segments')
  2718. ->where('id', $act_id)
  2719. ->update($update_data);
  2720. if ($result === false) {
  2721. Utils::throwError('20003:更新片段失败');
  2722. }
  2723. DB::commit();
  2724. // 返回新复制的记录
  2725. $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();
  2726. $new_segment = (array)$new_segment;
  2727. return $new_segment;
  2728. } catch (\Exception $e) {
  2729. DB::rollBack();
  2730. dLog('anime')->error('更新片段失败', [
  2731. 'act_id' => $act_id,
  2732. 'error' => $e->getMessage()
  2733. ]);
  2734. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2735. }
  2736. }
  2737. public function copyAct($data) {
  2738. $act_id = getProp($data, 'act_id');
  2739. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2740. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2741. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2742. $anime_id = getProp($source_segment, 'anime_id');
  2743. $episode_id = getProp($source_segment, 'episode_id');
  2744. $episode_number = getProp($source_segment, 'episode_number');
  2745. $act_number = getProp($source_segment, 'act_number');
  2746. try {
  2747. DB::beginTransaction();
  2748. // 新act的编号
  2749. $new_act_number = $act_number + 1;
  2750. // 更新后续所有act的act_number
  2751. DB::table('mp_episode_segments')
  2752. ->where('anime_id', $anime_id)
  2753. ->where('episode_id', $episode_id)
  2754. ->where('act_number', '>', $act_number)
  2755. ->increment('act_number');
  2756. // 复制该片段记录
  2757. $segment_data = (array)$source_segment;
  2758. unset($segment_data['id']);
  2759. $segment_data['video_url'] = '';
  2760. $segment_data['video_task_id'] = '';
  2761. $segment_data['video_task_status'] = '';
  2762. $segment_data['act_number'] = $new_act_number;
  2763. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2764. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2765. if (!$id) {
  2766. Utils::throwError('20003:复制片段失败');
  2767. }
  2768. DB::commit();
  2769. }catch (\Exception $e) {
  2770. DB::rollBack();
  2771. Utils::throwError('20003:'.$e->getMessage());
  2772. }
  2773. // 返回新复制的记录
  2774. $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();
  2775. $new_segment = $new_segment ? (array)$new_segment : [];
  2776. $new_segment['act_id'] = $id;
  2777. return $new_segment;
  2778. }
  2779. public function moveAct($data) {
  2780. $act_id = getProp($data, 'act_id');
  2781. $target_act_id = getProp($data, 'target_act_id');
  2782. // 获取源片段信息
  2783. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2784. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2785. // 获取目标片段信息
  2786. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2787. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2788. $anime_id = getProp($source_segment, 'anime_id');
  2789. $episode_id = getProp($source_segment, 'episode_id');
  2790. $source_act_number = getProp($source_segment, 'act_number');
  2791. $target_act_number = getProp($target_segment, 'act_number');
  2792. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2793. $target_anime_id = getProp($target_segment, 'anime_id');
  2794. $target_episode_id = getProp($target_segment, 'episode_id');
  2795. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2796. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2797. }
  2798. // 如果源片段和目标片段相同,无需移动
  2799. if ($source_act_number == $target_act_number) {
  2800. return true;
  2801. }
  2802. try {
  2803. DB::beginTransaction();
  2804. if ($source_act_number < $target_act_number) {
  2805. // 向后移动:源片段移动到目标片段之后
  2806. // 1. 将源片段和目标片段之间的所有片段编号减1
  2807. DB::table('mp_episode_segments')
  2808. ->where('anime_id', $anime_id)
  2809. ->where('episode_id', $episode_id)
  2810. ->where('act_number', '>', $source_act_number)
  2811. ->where('act_number', '<=', $target_act_number)
  2812. ->decrement('act_number');
  2813. // 2. 将源片段移动到目标片段之后
  2814. $new_act_number = $target_act_number;
  2815. } else {
  2816. // 向前移动:源片段移动到目标片段之后
  2817. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2818. DB::table('mp_episode_segments')
  2819. ->where('anime_id', $anime_id)
  2820. ->where('episode_id', $episode_id)
  2821. ->where('act_number', '>', $target_act_number)
  2822. ->where('act_number', '<', $source_act_number)
  2823. ->increment('act_number');
  2824. // 2. 将源片段移动到目标片段之后
  2825. $new_act_number = $target_act_number + 1;
  2826. }
  2827. // 3. 更新源片段的编号
  2828. $update_result = DB::table('mp_episode_segments')
  2829. ->where('id', $act_id)
  2830. ->update([
  2831. 'act_number' => $new_act_number,
  2832. 'updated_at' => date('Y-m-d H:i:s')
  2833. ]);
  2834. if (!$update_result) {
  2835. Utils::throwError('20003:更新片段编号失败');
  2836. }
  2837. DB::commit();
  2838. return true;
  2839. } catch (\Exception $e) {
  2840. DB::rollBack();
  2841. Utils::throwError('20003:' . $e->getMessage());
  2842. }
  2843. }
  2844. public function delAct($data) {
  2845. $act_id = getProp($data, 'act_id');
  2846. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2847. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2848. if (!$segment) Utils::throwError('20003:请选择片段');
  2849. $anime_id = getProp($segment, 'anime_id');
  2850. $episode_id = getProp($segment, 'episode_id');
  2851. $act_number = getProp($segment, 'act_number');
  2852. try {
  2853. DB::beginTransaction();
  2854. // 删除该片段记录
  2855. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2856. if (!$deleted) {
  2857. Utils::throwError('20003:删除片段失败');
  2858. }
  2859. // 更新后续act的编号
  2860. DB::table('mp_episode_segments')
  2861. ->where('anime_id', $anime_id)
  2862. ->where('episode_id', $episode_id)
  2863. ->where('act_number', '>', $act_number)
  2864. ->decrement('act_number');
  2865. DB::commit();
  2866. }catch (\Exception $e) {
  2867. DB::rollBack();
  2868. Utils::throwError('20003:'.$e->getMessage());
  2869. }
  2870. return true;
  2871. }
  2872. public function applyAct($data) {
  2873. $act_id = getProp($data, 'act_id');
  2874. $url = getProp($data, 'url');
  2875. if (!$act_id) Utils::throwError('20003:请选择片段');
  2876. if (!$url) Utils::throwError('20003:URL不能为空');
  2877. // 获取URL的文件扩展名
  2878. $urlPath = parse_url($url, PHP_URL_PATH);
  2879. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2880. // 定义图片和视频的扩展名
  2881. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2882. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2883. // 判断是图片还是视频
  2884. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2885. if (in_array($extension, $imageExtensions)) {
  2886. // 图片类型
  2887. $updateData['img_url'] = $url;
  2888. $updateData['current_type'] = 1;
  2889. } elseif (in_array($extension, $videoExtensions)) {
  2890. // 视频类型
  2891. $updateData['video_url'] = $url;
  2892. $updateData['current_type'] = 2;
  2893. } else {
  2894. Utils::throwError('20003:不支持的文件类型');
  2895. }
  2896. // 更新片段记录(全能模式下每个act只有一条记录)
  2897. $result = DB::table('mp_episode_segments')
  2898. ->where('id', $act_id)
  2899. ->update($updateData);
  2900. if (!$result) {
  2901. Utils::throwError('20003:更新片段失败');
  2902. }
  2903. return true;
  2904. }
  2905. public function actChatHistory($data) {
  2906. $act_id = getProp($data, 'act_id');
  2907. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2908. $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');
  2909. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2910. $value = (array)$value;
  2911. $value['created_at'] = transDate($value['created_at']);
  2912. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2913. else $value['reference_images'] = [];
  2914. return $value;
  2915. })->toArray();
  2916. // 获取历史图片
  2917. $url = [];
  2918. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2919. foreach($pic_history as $task) {
  2920. $result_url = getProp($task, 'result_url');
  2921. if (is_json($result_url)) {
  2922. $url = array_merge($url, json_decode($result_url, true));
  2923. }else {
  2924. $url[] = $result_url;
  2925. }
  2926. }
  2927. // 获取历史视频
  2928. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2929. foreach($video_history as $task) {
  2930. $result_url = getProp($task, 'result_url');
  2931. if (is_json($result_url)) {
  2932. $url = array_merge($url, json_decode($result_url, true));
  2933. }else {
  2934. $url[] = $result_url;
  2935. }
  2936. }
  2937. // 获取资产库
  2938. $products = [];
  2939. // 通过act_id查询片段信息获取episode_id
  2940. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2941. if ($segment) {
  2942. $episode_id = getProp($segment, 'episode_id');
  2943. // 查询剧集信息获取roles、scenes和extra_products
  2944. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2945. if ($episode) {
  2946. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2947. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2948. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2949. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2950. // 先合并roles、scenes和props
  2951. // 处理角色数组
  2952. foreach ($roles as $role) {
  2953. $product = $role;
  2954. // 将role字段重命名为product_name
  2955. if (is_array($product) && !empty($product['role'] ?? null)) {
  2956. $product['product_name'] = $product['role'];
  2957. unset($product['role']);
  2958. $product['product'] = 1; // 标记类型为角色
  2959. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2960. }
  2961. }
  2962. // 处理场景数组
  2963. foreach ($scenes as $scene) {
  2964. $product = $scene;
  2965. // 将scene字段重命名为product_name
  2966. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2967. $product['product_name'] = $product['scene'];
  2968. unset($product['scene']);
  2969. $product['product'] = 2; // 标记类型为场景
  2970. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2971. }
  2972. }
  2973. // 处理道具数组
  2974. foreach ($props as $prop) {
  2975. $product = $prop;
  2976. // 将prop字段重命名为product_name
  2977. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2978. $product['product_name'] = $product['prop'];
  2979. unset($product['prop']);
  2980. $product['product'] = 3; // 标记类型为道具
  2981. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2982. }
  2983. }
  2984. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2985. foreach ($extra_products as $extra_product) {
  2986. $product_name = getProp($extra_product, 'product_name');
  2987. if ($product_name) {
  2988. $products[$product_name] = $extra_product; // 覆盖同名数据
  2989. }
  2990. }
  2991. // 重新索引数组(去除key)
  2992. $products = array_values($products);
  2993. }
  2994. }
  2995. // 获取执行中的任务
  2996. $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) {
  2997. $value = (array)$value;
  2998. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2999. else $value['ref_image_url'] = [];
  3000. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3001. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3002. if (!empty($value['prompt'])) {
  3003. $prompt = $value['prompt'];
  3004. // 查找第一个【镜头】的位置
  3005. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3006. // 从【镜头】开始截取
  3007. $prompt = substr($prompt, $matches[0][1]);
  3008. }
  3009. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3010. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3011. $value['prompt'] = $prompt;
  3012. }
  3013. return $value;
  3014. })->toArray();
  3015. return compact('chat', 'url', 'products', 'tasks');
  3016. }
  3017. public function applyAudioData($data) {
  3018. $segment_id = getProp($data, 'segment_id');
  3019. $global_data = getProp($data, 'global_data');
  3020. $segment_data = getProp($data, 'segment_data');
  3021. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3022. $global_data = is_array($global_data) ? $global_data : [];
  3023. $segment_data = is_array($segment_data) ? $segment_data : [];
  3024. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3025. $dialogue_item = null;
  3026. foreach ($global_data as $key => $item) {
  3027. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3028. $dialogue_item = $item;
  3029. unset($global_data[$key]);
  3030. break;
  3031. }
  3032. }
  3033. if ($dialogue_item) {
  3034. $segment_data[] = $dialogue_item;
  3035. }
  3036. // 特殊参数: audio_url,audio_duration,subtitle_info
  3037. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3038. // 如果不是全部存在,则仍需创建音频任务
  3039. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3040. $special_update_data = [];
  3041. $has_all_special_params = false;
  3042. // 从segment_data中提取特殊参数
  3043. $filtered_segment_data = [];
  3044. foreach ($segment_data as $item) {
  3045. $field_name = trim((string)getProp($item, 'name'));
  3046. if (in_array($field_name, $special_fields)) {
  3047. $special_update_data[$field_name] = getProp($item, 'value');
  3048. } else {
  3049. // 非特殊参数保留,继续后续处理
  3050. $filtered_segment_data[] = $item;
  3051. }
  3052. }
  3053. // 检查是否三个特殊参数都存在
  3054. if (count($special_update_data) === 3 &&
  3055. isset($special_update_data['audio_url']) &&
  3056. isset($special_update_data['audio_duration']) &&
  3057. isset($special_update_data['subtitle_info'])) {
  3058. $has_all_special_params = true;
  3059. // 立即更新到当前分镜
  3060. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3061. DB::table('mp_episode_segments')
  3062. ->where('segment_id', $segment_id)
  3063. ->update($special_update_data);
  3064. }
  3065. // 使用过滤后的segment_data继续处理其他参数
  3066. $segment_data = $filtered_segment_data;
  3067. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3068. $global_update_data = [];
  3069. $segment_update_data = [];
  3070. $global_voice_type = '';
  3071. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3072. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3073. $episode_id = getProp($target_segment, 'episode_id');
  3074. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3075. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3076. if (!$episode) Utils::throwError('20003:分集不存在');
  3077. foreach ($global_data as $item) {
  3078. $field_name = trim((string)getProp($item, 'name'));
  3079. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3080. continue;
  3081. }
  3082. $global_update_data[$field_name] = getProp($item, 'value');
  3083. if ($field_name === 'voice_type') {
  3084. $global_voice_type = trim((string)getProp($item, 'value'));
  3085. }
  3086. }
  3087. foreach ($segment_data as $item) {
  3088. $field_name = trim((string)getProp($item, 'name'));
  3089. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3090. continue;
  3091. }
  3092. $segment_update_data[$field_name] = getProp($item, 'value');
  3093. }
  3094. if ($global_voice_type) {
  3095. $timbre_info = DB::table('mp_timbres')
  3096. ->where('timbre_type', $global_voice_type)
  3097. ->select('audio_url', 'timbre_name')
  3098. ->first();
  3099. if ($timbre_info) {
  3100. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3101. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3102. }
  3103. }
  3104. try {
  3105. DB::beginTransaction();
  3106. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3107. $segment_ids_to_create_task = [];
  3108. $segments_data = [];
  3109. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3110. if (!empty($global_update_data)) {
  3111. // 如果角色不存在,则只更新当前分镜
  3112. if (!$target_voice_actor) {
  3113. // 只处理当前分镜
  3114. $affected_segments = DB::table('mp_episode_segments')
  3115. ->where('segment_id', $segment_id)
  3116. ->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')
  3117. ->get();
  3118. } else {
  3119. // 获取该角色的所有分镜
  3120. $affected_segments = DB::table('mp_episode_segments')
  3121. ->where('episode_id', $episode_id)
  3122. ->where('voice_actor', $target_voice_actor)
  3123. ->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')
  3124. ->get();
  3125. }
  3126. foreach ($affected_segments as $seg) {
  3127. $seg = (array)$seg;
  3128. $sid = getProp($seg, 'segment_id');
  3129. // 检查参数是否发生变化
  3130. $has_changed = false;
  3131. foreach ($global_update_data as $field => $new_value) {
  3132. $old_value = getProp($seg, $field);
  3133. if ($old_value != $new_value) {
  3134. $has_changed = true;
  3135. break;
  3136. }
  3137. }
  3138. if ($has_changed) {
  3139. $segment_ids_to_create_task[] = $sid;
  3140. $segments_data[$sid] = $seg;
  3141. }
  3142. }
  3143. // 只有在有变化的分镜时才更新
  3144. if (!empty($segment_ids_to_create_task)) {
  3145. $global_segment_update_data = $global_update_data;
  3146. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3147. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3148. DB::table('mp_episode_segments')
  3149. ->where('episode_id', $episode_id)
  3150. ->where('voice_actor', $target_voice_actor)
  3151. ->whereIn('segment_id', $segment_ids_to_create_task)
  3152. ->update($global_segment_update_data);
  3153. }
  3154. if ($global_voice_type) {
  3155. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3156. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3157. $roles_updated = false;
  3158. foreach ($episode_roles as &$role) {
  3159. // 通过 role 字段匹配角色名,而不是 voice_name
  3160. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3161. continue;
  3162. }
  3163. $role['voice_type'] = $global_voice_type;
  3164. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3165. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3166. $roles_updated = true;
  3167. }
  3168. unset($role);
  3169. if ($roles_updated) {
  3170. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3171. 'roles' => json_encode($episode_roles, 256),
  3172. 'updated_at' => date('Y-m-d H:i:s'),
  3173. ]);
  3174. }
  3175. }
  3176. }
  3177. // 如果有单个分镜更新,检查是否有变化
  3178. if (!empty($segment_update_data)) {
  3179. // 获取当前分镜数据
  3180. $current_segment = DB::table('mp_episode_segments')
  3181. ->where('segment_id', $segment_id)
  3182. ->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')
  3183. ->first();
  3184. if ($current_segment) {
  3185. $current_segment = (array)$current_segment;
  3186. // 检查参数是否发生变化
  3187. $has_changed = false;
  3188. foreach ($segment_update_data as $field => $new_value) {
  3189. $old_value = getProp($current_segment, $field);
  3190. if ($old_value != $new_value) {
  3191. $has_changed = true;
  3192. break;
  3193. }
  3194. }
  3195. if ($has_changed) {
  3196. // 如果该分镜还未在列表中,添加进去
  3197. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3198. $segment_ids_to_create_task[] = $segment_id;
  3199. $segments_data[$segment_id] = $current_segment;
  3200. }
  3201. // 更新分镜数据并清空音频URL
  3202. $segment_update_data['audio_url'] = '';
  3203. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3204. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3205. }
  3206. }
  3207. }
  3208. // 为所有有变化的分镜创建音频合成任务
  3209. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3210. if (!empty($segment_ids_to_create_task)) {
  3211. foreach ($segment_ids_to_create_task as $sid) {
  3212. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3213. if ($sid === $segment_id && $has_all_special_params) {
  3214. continue;
  3215. }
  3216. // 重新获取更新后的分镜数据
  3217. $updated_segment = DB::table('mp_episode_segments')
  3218. ->where('segment_id', $sid)
  3219. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3220. ->first();
  3221. if (!$updated_segment) continue;
  3222. $updated_segment = (array)$updated_segment;
  3223. // 检查dialogue是否为空
  3224. $dialogue = getProp($updated_segment, 'dialogue');
  3225. if (empty($dialogue)) {
  3226. // dialogue为空时,直接写入默认音频信息
  3227. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3228. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3229. 'audio_duration' => 2.0,
  3230. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3231. 'updated_at' => date('Y-m-d H:i:s')
  3232. ]);
  3233. continue;
  3234. }
  3235. $generate_json = [
  3236. 'text' => $dialogue,
  3237. 'role' => getProp($updated_segment, 'voice_actor'),
  3238. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3239. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3240. 'emotion' => getProp($updated_segment, 'emotion'),
  3241. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3242. 'gender' => getProp($updated_segment, 'gender'),
  3243. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3244. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3245. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3246. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3247. ];
  3248. // 插入视频配音合成任务
  3249. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3250. 'alias_segment_id' => $sid,
  3251. 'generate_status' => '执行中',
  3252. 'audio_url' => '',
  3253. 'generate_json' => json_encode($generate_json, 256),
  3254. 'created_at' => date('Y-m-d H:i:s'),
  3255. 'updated_at' => date('Y-m-d H:i:s'),
  3256. ]);
  3257. if (!$dubTaskId) {
  3258. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3259. continue;
  3260. }
  3261. // 将任务ID添加到Redis列表中
  3262. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3263. // 请求远程服务器执行生成
  3264. try {
  3265. sleep(1);
  3266. $client = new Client(['timeout' => 300, 'verify' => false]);
  3267. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3268. $response = $result->getBody()->getContents();
  3269. $response_arr = json_decode($response, true);
  3270. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3271. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3272. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3273. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3274. }
  3275. } catch (\Exception $e) {
  3276. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3277. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3278. }
  3279. }
  3280. }
  3281. DB::commit();
  3282. } catch (\Exception $e) {
  3283. DB::rollBack();
  3284. Utils::throwError('20003:'.$e->getMessage());
  3285. }
  3286. return true;
  3287. }
  3288. public function episodePicsInfo($data) {
  3289. $anime_id = getProp($data, 'anime_id');
  3290. $episode_id = getProp($data, 'episode_id');
  3291. // 参数验证
  3292. if (!$anime_id && !$episode_id) {
  3293. Utils::throwError('20003:请提供动漫ID或分集ID');
  3294. }
  3295. // 根据参数获取数据源
  3296. if ($episode_id) {
  3297. // 从剧集表获取
  3298. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3299. if (!$source) Utils::throwError('20003:该剧集不存在');
  3300. $table_name = 'mp_anime_episodes';
  3301. $id_field = 'id';
  3302. $id_value = $episode_id;
  3303. // 获取剧集的anime_id用于继承全局数据
  3304. $anime_id = getProp($source, 'anime_id');
  3305. } else {
  3306. // 从动漫表获取
  3307. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3308. if (!$source) Utils::throwError('20003:该动漫不存在');
  3309. $table_name = 'mp_animes';
  3310. $id_field = 'id';
  3311. $id_value = $anime_id;
  3312. }
  3313. $source = (array)$source;
  3314. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3315. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3316. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3317. // 如果是分集数据,需要处理继承和任务创建逻辑
  3318. if ($episode_id) {
  3319. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3320. }
  3321. // 返回生成器函数,用于 SSE 流式输出
  3322. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3323. $startTime = time();
  3324. $maxDuration = 600; // 10分钟超时
  3325. $checkInterval = 3; // 每3秒检查一次
  3326. // Redis 缓存键
  3327. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3328. // 生成当前数据的哈希值用于比较
  3329. $generateHash = function($roles, $scenes, $props) {
  3330. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3331. };
  3332. // 发送初始数据
  3333. $currentHash = $generateHash($roles, $scenes, $props);
  3334. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3335. echo "data: " . json_encode([
  3336. 'type' => 'init',
  3337. 'data' => [
  3338. 'roles' => $roles,
  3339. 'scenes' => $scenes,
  3340. 'props' => $props,
  3341. 'start_time' => $startTime
  3342. ]
  3343. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3344. if (ob_get_level() > 0) {
  3345. ob_flush();
  3346. }
  3347. flush();
  3348. // 持续轮询任务状态
  3349. while (time() - $startTime < $maxDuration) {
  3350. $hasProcessing = false;
  3351. $updated = false;
  3352. // 检查角色任务状态
  3353. foreach ($roles as $index => &$role) {
  3354. $task_id = getProp($role, 'task_id');
  3355. $task_status = getProp($role, 'task_status');
  3356. $existing_url = getProp($role, 'url');
  3357. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3358. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3359. $hasProcessing = ($task_status === 'processing');
  3360. // 查询任务状态
  3361. $task = DB::table('mp_generate_pic_tasks')
  3362. ->where('id', $task_id)
  3363. ->select('id', 'status', 'result_url', 'error_message')
  3364. ->first();
  3365. if ($task) {
  3366. $task = (array)$task;
  3367. $status = getProp($task, 'status');
  3368. // 如果任务完成或失败
  3369. if (in_array($status, ['success', 'failed'])) {
  3370. $role['task_status'] = $status;
  3371. if ($status === 'success') {
  3372. $result_url = getProp($task, 'result_url');
  3373. if ($result_url) {
  3374. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3375. if (is_array($result_urls) && !empty($result_urls[0])) {
  3376. $role['url'] = $result_urls[0];
  3377. }
  3378. }
  3379. }
  3380. $updated = true;
  3381. } else if ($status === 'processing') {
  3382. $hasProcessing = true;
  3383. }
  3384. }
  3385. }
  3386. }
  3387. // 检查场景任务状态
  3388. foreach ($scenes as $index => &$scene) {
  3389. $task_id = getProp($scene, 'task_id');
  3390. $task_status = getProp($scene, 'task_status');
  3391. $existing_url = getProp($scene, 'url');
  3392. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3393. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3394. $hasProcessing = ($task_status === 'processing');
  3395. // 查询任务状态
  3396. $task = DB::table('mp_generate_pic_tasks')
  3397. ->where('id', $task_id)
  3398. ->select('id', 'status', 'result_url', 'error_message')
  3399. ->first();
  3400. if ($task) {
  3401. $task = (array)$task;
  3402. $status = getProp($task, 'status');
  3403. // 如果任务完成或失败
  3404. if (in_array($status, ['success', 'failed'])) {
  3405. $scene['task_status'] = $status;
  3406. if ($status === 'success') {
  3407. $result_url = getProp($task, 'result_url');
  3408. if ($result_url) {
  3409. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3410. if (is_array($result_urls) && !empty($result_urls[0])) {
  3411. $scene['url'] = $result_urls[0];
  3412. }
  3413. }
  3414. }
  3415. $updated = true;
  3416. } else if ($status === 'processing') {
  3417. $hasProcessing = true;
  3418. }
  3419. }
  3420. }
  3421. }
  3422. // 检查道具任务状态
  3423. foreach ($props as $index => &$prop) {
  3424. $task_id = getProp($prop, 'task_id');
  3425. $task_status = getProp($prop, 'task_status');
  3426. $existing_url = getProp($prop, 'url');
  3427. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3428. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3429. $hasProcessing = ($task_status === 'processing');
  3430. // 查询任务状态
  3431. $task = DB::table('mp_generate_pic_tasks')
  3432. ->where('id', $task_id)
  3433. ->select('id', 'status', 'result_url', 'error_message')
  3434. ->first();
  3435. if ($task) {
  3436. $task = (array)$task;
  3437. $status = getProp($task, 'status');
  3438. // 如果任务完成或失败
  3439. if (in_array($status, ['success', 'failed'])) {
  3440. $prop['task_status'] = $status;
  3441. if ($status === 'success') {
  3442. $result_url = getProp($task, 'result_url');
  3443. if ($result_url) {
  3444. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3445. if (is_array($result_urls) && !empty($result_urls[0])) {
  3446. $prop['url'] = $result_urls[0];
  3447. }
  3448. }
  3449. }
  3450. $updated = true;
  3451. } else if ($status === 'processing') {
  3452. $hasProcessing = true;
  3453. }
  3454. }
  3455. }
  3456. }
  3457. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3458. if ($updated) {
  3459. $newHash = $generateHash($roles, $scenes, $props);
  3460. $cachedHash = Redis::get($cacheKey);
  3461. // 只有当数据真正变化时才更新数据库和发送事件
  3462. if ($newHash !== $cachedHash) {
  3463. try {
  3464. // 更新数据库
  3465. DB::table($table_name)->where($id_field, $id_value)->update([
  3466. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3467. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3468. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3469. 'updated_at' => date('Y-m-d H:i:s')
  3470. ]);
  3471. // 更新缓存
  3472. Redis::setex($cacheKey, 600, $newHash);
  3473. // 发送更新事件
  3474. echo "data: " . json_encode([
  3475. 'type' => 'update',
  3476. 'data' => [
  3477. 'roles' => $roles,
  3478. 'scenes' => $scenes,
  3479. 'props' => $props,
  3480. 'elapsed_time' => time() - $startTime
  3481. ]
  3482. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3483. if (ob_get_level() > 0) {
  3484. ob_flush();
  3485. }
  3486. flush();
  3487. } catch (\Exception $e) {
  3488. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3489. }
  3490. } else {
  3491. // 即使哈希相同,如果有URL更新也要发送事件
  3492. $hasUrlUpdate = false;
  3493. foreach ($roles as $role) {
  3494. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3495. $hasUrlUpdate = true;
  3496. break;
  3497. }
  3498. }
  3499. if (!$hasUrlUpdate) {
  3500. foreach ($scenes as $scene) {
  3501. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3502. $hasUrlUpdate = true;
  3503. break;
  3504. }
  3505. }
  3506. }
  3507. if (!$hasUrlUpdate) {
  3508. foreach ($props as $prop) {
  3509. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3510. $hasUrlUpdate = true;
  3511. break;
  3512. }
  3513. }
  3514. }
  3515. if ($hasUrlUpdate) {
  3516. // 强制更新数据库和发送事件
  3517. try {
  3518. DB::table($table_name)->where($id_field, $id_value)->update([
  3519. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3520. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3521. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3522. 'updated_at' => date('Y-m-d H:i:s')
  3523. ]);
  3524. // 更新缓存
  3525. Redis::setex($cacheKey, 600, $newHash);
  3526. // 发送更新事件
  3527. echo "data: " . json_encode([
  3528. 'type' => 'update',
  3529. 'data' => [
  3530. 'roles' => $roles,
  3531. 'scenes' => $scenes,
  3532. 'props' => $props,
  3533. 'elapsed_time' => time() - $startTime
  3534. ]
  3535. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3536. if (ob_get_level() > 0) {
  3537. ob_flush();
  3538. }
  3539. flush();
  3540. } catch (\Exception $e) {
  3541. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3542. }
  3543. }
  3544. }
  3545. }
  3546. // 如果所有任务都已完成,发送完成事件并退出
  3547. if (!$hasProcessing) {
  3548. // 查询数据库中的最终数据,确保返回最新的完整数据
  3549. try {
  3550. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3551. if ($finalSource) {
  3552. $finalSource = (array)$finalSource;
  3553. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3554. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3555. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3556. // 使用数据库中的最终数据
  3557. $roles = $finalRoles;
  3558. $scenes = $finalScenes;
  3559. $props = $finalProps;
  3560. }
  3561. } catch (\Exception $e) {
  3562. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3563. // 如果查询失败,继续使用内存中的数据
  3564. }
  3565. // 清理缓存
  3566. Redis::del($cacheKey);
  3567. echo "data: " . json_encode([
  3568. 'type' => 'completed',
  3569. 'data' => [
  3570. 'roles' => $roles,
  3571. 'scenes' => $scenes,
  3572. 'props' => $props,
  3573. 'total_time' => time() - $startTime
  3574. ]
  3575. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3576. if (ob_get_level() > 0) {
  3577. ob_flush();
  3578. }
  3579. flush();
  3580. break;
  3581. }
  3582. // 等待下次检查
  3583. sleep($checkInterval);
  3584. }
  3585. // 超时处理
  3586. if (time() - $startTime >= $maxDuration) {
  3587. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3588. try {
  3589. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3590. if ($finalSource) {
  3591. $finalSource = (array)$finalSource;
  3592. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3593. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3594. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3595. // 使用数据库中的最终数据
  3596. $roles = $finalRoles;
  3597. $scenes = $finalScenes;
  3598. $props = $finalProps;
  3599. }
  3600. } catch (\Exception $e) {
  3601. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3602. // 如果查询失败,继续使用内存中的数据
  3603. }
  3604. // 清理缓存
  3605. Redis::del($cacheKey);
  3606. echo "data: " . json_encode([
  3607. 'type' => 'timeout',
  3608. 'message' => '轮询超时,请刷新页面查看最新状态',
  3609. 'data' => [
  3610. 'roles' => $roles,
  3611. 'scenes' => $scenes,
  3612. 'props' => $props
  3613. ]
  3614. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3615. if (ob_get_level() > 0) {
  3616. ob_flush();
  3617. }
  3618. flush();
  3619. }
  3620. };
  3621. }
  3622. public function clipSegmentVideo($data) {
  3623. $segment_id = getProp($data, 'segment_id');
  3624. $video_time_point_start = getProp($data, 'video_time_point_start');
  3625. $video_time_point_end = getProp($data, 'video_time_point_end');
  3626. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3627. Utils::throwError('20003:参数异常');
  3628. }
  3629. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3630. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3631. }
  3632. $video_duration = $video_time_point_end - $video_time_point_start;
  3633. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3634. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3635. 'video_duration' => $video_duration,
  3636. 'video_time_point_start' => $video_time_point_start,
  3637. 'video_time_point_end' => $video_time_point_end,
  3638. 'updated_at' => date('Y-m-d H:i:s')
  3639. ]);
  3640. }
  3641. // 轮训获取图片任务结果
  3642. private function loopGetPicTaskResult($task_id) {
  3643. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3644. if (!$task) {
  3645. return '';
  3646. }
  3647. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3648. $model = getProp($task, 'model');
  3649. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3650. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3651. $isSyncModel = $isVolcModel || $isGptModel;
  3652. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3653. $start_count = 0;
  3654. $img_url = '';
  3655. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3656. sleep(3);
  3657. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3658. // 如果任务已经完成,直接返回结果
  3659. if ($task->status === 'success' && $task->result_url) {
  3660. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3661. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3662. }
  3663. // 如果任务已失败,返回空
  3664. if ($task->status === 'failed') {
  3665. return '';
  3666. }
  3667. if ($isSyncModel) continue;
  3668. // 查询任务状态
  3669. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3670. if ($statusInfo['status'] === 'success') {
  3671. $task->updateStatus('success', [
  3672. 'result_url' => $statusInfo['result_url'],
  3673. 'result_json' => $statusInfo['result_json'] ?? []
  3674. ]);
  3675. // 同步调整分镜图片状态和结果
  3676. if (getProp($task, 'alias_segment_id')) {
  3677. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3678. 'img_url' => $statusInfo['result_url'][0],
  3679. 'pic_task_status' => '已完成',
  3680. ]);
  3681. }
  3682. $img_url = $statusInfo['result_url'][0];
  3683. break;
  3684. } elseif ($statusInfo['status'] === 'failed') {
  3685. $task->updateStatus('failed', [
  3686. 'error_message' => $statusInfo['error_message'],
  3687. 'result_json' => $statusInfo['result_json'] ?? []
  3688. ]);
  3689. if (getProp($task, 'alias_segment_id')) {
  3690. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3691. 'pic_task_status' => '失败',
  3692. ]);
  3693. }
  3694. break;
  3695. }
  3696. $start_count++;
  3697. }
  3698. return $img_url;
  3699. }
  3700. /**
  3701. * 从分镜内容中提取涉及的角色
  3702. */
  3703. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3704. $found_characters = [];
  3705. foreach ($available_characters as $character) {
  3706. // 检查角色名称是否在分镜内容中出现
  3707. if (strpos($segment_content, $character) !== false) {
  3708. $found_characters[] = $character;
  3709. }
  3710. }
  3711. if (!$found_characters) {
  3712. foreach ($roles as $character) {
  3713. // 检查角色名称是否在分镜内容中出现
  3714. if (strpos($segment_content, $character) !== false) {
  3715. $found_characters[] = $character;
  3716. }
  3717. }
  3718. }
  3719. return array_unique($found_characters);
  3720. }
  3721. // 从分镜剧本中提取关键字段
  3722. private function handleSegmentContent(&$data) {
  3723. $segmentContent = getProp($data, 'segment_content');
  3724. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3725. $segmentData = [
  3726. 'description' => '',
  3727. 'composition' => '',
  3728. 'camera_movement' => '',
  3729. 'voice_actor' => '',
  3730. 'dialogue' => '',
  3731. 'frame_type' => '',
  3732. 'scene' => '', // 场景
  3733. 'characters' => '', // 出镜角色
  3734. 'tail_frame' => '', // 尾帧描述
  3735. 'emotion' => '中性', // 情感
  3736. 'gender' => '0', // 性别(0未知,1男,2女)
  3737. 'speed_ratio' => 0, // 语速
  3738. 'loudness_ratio' => 0, // 音量
  3739. 'emotion_scale' => 4, // 情感强度
  3740. 'pitch' => 0, // 音调
  3741. ];
  3742. // 用于存储需要从 segment_content 中移除的匹配项
  3743. $replaceEmptyArr = [];
  3744. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3745. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3746. $segmentData['description'] = trim($descMatch[1]);
  3747. $data['description'] = trim($descMatch[1]);
  3748. }
  3749. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3750. $segmentData['composition'] = trim($compMatch[1]);
  3751. $data['composition'] = trim($compMatch[1]);
  3752. }
  3753. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3754. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3755. $data['camera_movement'] = trim($cameraMatch[1]);
  3756. }
  3757. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3758. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3759. $data['voice_actor'] = trim($voiceMatch[1]);
  3760. }
  3761. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3762. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3763. $data['dialogue'] = trim($dialogueMatch[1]);
  3764. }
  3765. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3766. $segmentData['frame_type'] = trim($frameMatch[1]);
  3767. $data['frame_type'] = trim($frameMatch[1]);
  3768. }
  3769. // 场景字段
  3770. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3771. $segmentData['scene'] = trim($sceneMatch[1]);
  3772. $data['scene'] = trim($sceneMatch[1]);
  3773. }
  3774. // 出镜角色字段
  3775. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3776. $segmentData['characters'] = trim($charactersMatch[1]);
  3777. $data['characters'] = trim($charactersMatch[1]);
  3778. }
  3779. // 尾帧描述字段
  3780. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3781. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3782. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3783. }
  3784. // 情感字段
  3785. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3786. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3787. $segmentData['emotion'] = trim($emotionMatch[1]);
  3788. $data['emotion'] = trim($emotionMatch[1]);
  3789. }
  3790. // 性别字段
  3791. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3792. $replaceEmptyArr[] = trim($genderMatch[0]);
  3793. $genderStr = trim($genderMatch[1]);
  3794. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3795. $segmentData['gender'] = '1';
  3796. $data['gender'] = '1';
  3797. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3798. $segmentData['gender'] = '2';
  3799. $data['gender'] = '2';
  3800. } else {
  3801. $segmentData['gender'] = '0';
  3802. $data['gender'] = '0';
  3803. }
  3804. }
  3805. // 语速字段
  3806. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3807. $replaceEmptyArr[] = trim($speedMatch[0]);
  3808. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3809. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3810. }
  3811. // 音量字段
  3812. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3813. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3814. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3815. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3816. }
  3817. // 情感强度字段
  3818. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3819. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3820. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3821. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3822. }
  3823. // 音调字段
  3824. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3825. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3826. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3827. $data['pitch'] = (int)trim($pitchMatch[1]);
  3828. }
  3829. // 从 segment_content 中移除已提取的配音参数字段
  3830. if (!empty($replaceEmptyArr)) {
  3831. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3832. }
  3833. // 如果有配音角色,查询音色信息并验证情感
  3834. $voice_actor = $segmentData['voice_actor'];
  3835. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3836. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3837. $anime_id = getProp($data, 'anime_id');
  3838. $episode_id = getProp($data, 'episode_id');
  3839. // 优先从剧集的角色列表中查找
  3840. $roles = [];
  3841. if ($episode_id) {
  3842. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3843. if ($episode && getProp($episode, 'roles')) {
  3844. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3845. }
  3846. }
  3847. // 如果剧集中没有,从动漫的角色列表中查找
  3848. if (empty($roles) && $anime_id) {
  3849. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3850. if ($anime && getProp($anime, 'roles')) {
  3851. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3852. }
  3853. }
  3854. // 查找匹配的角色音色信息
  3855. $timbre_info = null;
  3856. foreach ($roles as $role) {
  3857. if (getProp($role, 'role') === $voice_actor) {
  3858. $timbre_info = $role;
  3859. break;
  3860. }
  3861. }
  3862. // 如果找到音色信息,添加到数据中
  3863. if ($timbre_info) {
  3864. $voice_type = getProp($timbre_info, 'voice_type');
  3865. $voice_name = getProp($timbre_info, 'voice_name');
  3866. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3867. if ($voice_type) {
  3868. $data['voice_type'] = $voice_type;
  3869. $segmentData['voice_type'] = $voice_type;
  3870. }
  3871. if ($voice_name) {
  3872. $data['voice_name'] = $voice_name;
  3873. $segmentData['voice_name'] = $voice_name;
  3874. }
  3875. if ($voice_audio_url) {
  3876. $data['voice_audio_url'] = $voice_audio_url;
  3877. $segmentData['voice_audio_url'] = $voice_audio_url;
  3878. }
  3879. // 验证情感是否在音色支持的情感列表中
  3880. if ($voice_type) {
  3881. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3882. if ($timbre_emotion) {
  3883. $timbre_emotion = explode(',', $timbre_emotion);
  3884. } else {
  3885. $timbre_emotion = [];
  3886. }
  3887. $emotion = getProp($segmentData, 'emotion', '中性');
  3888. if (!in_array($emotion, $timbre_emotion)) {
  3889. $emotion = '中性';
  3890. }
  3891. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3892. $emotion_list = array_flip($emotion_list);
  3893. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3894. $data['emotion_type'] = $emotion_type;
  3895. $segmentData['emotion_type'] = $emotion_type;
  3896. }
  3897. }
  3898. }
  3899. return $segmentData;
  3900. }
  3901. public function createSegmentVideoTask($data) {
  3902. $segment_id = getProp($data, 'segment_id');
  3903. $tail_frame = getProp($data, 'tail_frame');
  3904. $first_frame_url = getProp($data, 'first_frame_url');
  3905. $tail_frame_url = getProp($data, 'tail_frame_url');
  3906. $generate_audio = getProp($data, 'generate_audio', 0);
  3907. if (!$segment_id) {
  3908. Utils::throwError('1002:分镜ID不能为空');
  3909. }
  3910. // 获取分镜信息
  3911. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3912. if (!$segment) {
  3913. Utils::throwError('20003:分镜不存在');
  3914. }
  3915. $segment = (array)$segment;
  3916. $episode_id = getProp($segment, 'episode_id');
  3917. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3918. if (!$ratio) $ratio = '9:16';
  3919. // 获取分镜内容
  3920. $segmentContent = getProp($segment, 'segment_content', '');
  3921. // 检查 $segmentContent 中是否已有尾帧描述
  3922. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3923. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3924. $finalTailFrame = '';
  3925. if ($tail_frame) {
  3926. // 用户输入了尾帧描述,优先使用
  3927. $finalTailFrame = $tail_frame;
  3928. // 如果 segmentContent 中已有尾帧描述,需要替换
  3929. if ($contentHasTailFrame) {
  3930. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3931. }
  3932. } elseif ($contentHasTailFrame) {
  3933. // segmentContent 中有尾帧描述,使用它
  3934. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3935. } else {
  3936. // 两者都没有,使用分镜表中的尾帧描述
  3937. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3938. }
  3939. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3940. $hasDialogue = false;
  3941. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3942. $dialogue = trim($dialogueMatch[1]);
  3943. // 如果台词不为空且不是"无"
  3944. if (!empty($dialogue) && $dialogue !== '无') {
  3945. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3946. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3947. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3948. $hasDialogue = true;
  3949. }
  3950. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3951. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3952. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3953. if (!preg_match('/^[“]/', $dialogue)) {
  3954. $dialogue = '“' . $dialogue;
  3955. }
  3956. if (!preg_match('/[”]$/', $dialogue)) {
  3957. $dialogue .= '”';
  3958. }
  3959. // 将修改后的台词替换回 $segmentContent
  3960. $originalDialogue = $dialogueMatch[1];
  3961. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3962. }
  3963. }
  3964. // 构建完整的提示词
  3965. $fullPrompt = $segmentContent;
  3966. if ($finalTailFrame && !$contentHasTailFrame) {
  3967. // 只有当 segmentContent 中没有尾帧描述时才追加
  3968. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3969. }
  3970. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3971. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3972. $fullPrompt = trim($fullPrompt);
  3973. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3974. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3975. // 智能选择视频时长
  3976. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3977. $videoDuration = -1;
  3978. // 处理视频模型
  3979. $model = getProp($data, 'model');
  3980. if (!$model) {
  3981. // 用户没有输入,从episode表获取
  3982. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3983. $model = getProp($episode, 'video_model');
  3984. if (!$model) {
  3985. // episode表也没有,使用默认值
  3986. $model = 'doubao-seedance-1-5-pro-251215';
  3987. }
  3988. }
  3989. // 验证模型是否在可用模型表中
  3990. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3991. $model = 'doubao-seedance-1-5-pro-251215';
  3992. }
  3993. // 保存到episode表
  3994. $episode_id = getProp($segment, 'episode_id');
  3995. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3996. 'video_model' => $model,
  3997. 'updated_at' => date('Y-m-d H:i:s')
  3998. ]);
  3999. // 构建视频生成参数
  4000. $videoParams = [
  4001. 'model' => $model,
  4002. 'alias_segment_id' => $segment_id,
  4003. 'prompt' => trim($fullPrompt),
  4004. 'video_duration' => $videoDuration,
  4005. 'video_resolution' => '720P',
  4006. 'seed' => -1,
  4007. 'ratio' => $ratio,
  4008. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4009. 'draft' => false,
  4010. 'watermark' => false,
  4011. 'camera_fixed' => false,
  4012. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4013. ];
  4014. // 如果分镜有图片,作为首帧
  4015. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4016. $hasVideo = !empty(getProp($segment, 'video_url'));
  4017. if ($hasImage) {
  4018. if ($first_frame_url) {
  4019. $videoParams['first_frame_url'] = $first_frame_url;
  4020. }else {
  4021. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4022. }
  4023. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4024. }
  4025. // 构建content数组
  4026. $videoParams['content'] = [
  4027. [
  4028. 'type' => 'text',
  4029. 'text' => $videoParams['prompt'],
  4030. ]
  4031. ];
  4032. // 如果有首帧图片,添加到content中
  4033. if ($hasImage) {
  4034. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4035. $videoParams['content'][] = [
  4036. 'type' => 'image_url',
  4037. 'image_url' => [
  4038. 'url' => $videoParams['first_frame_url'],
  4039. ],
  4040. 'role' => 'reference_image',
  4041. ];
  4042. if (isset($videoParams['tail_frame_url'])) {
  4043. $videoParams['content'][] = [
  4044. 'type' => 'image_url',
  4045. 'image_url' => [
  4046. 'url' => $videoParams['tail_frame_url'],
  4047. ],
  4048. 'role' => 'reference_image',
  4049. ];
  4050. }
  4051. }else {
  4052. $videoParams['content'][] = [
  4053. 'type' => 'image_url',
  4054. 'image_url' => [
  4055. 'url' => $videoParams['first_frame_url'],
  4056. ],
  4057. 'role' => 'first_frame',
  4058. ];
  4059. if (isset($videoParams['tail_frame_url'])) {
  4060. $videoParams['content'][] = [
  4061. 'type' => 'image_url',
  4062. 'image_url' => [
  4063. 'url' => $videoParams['tail_frame_url'],
  4064. ],
  4065. 'role' => 'last_frame',
  4066. ];
  4067. }
  4068. }
  4069. }
  4070. // 获取配音音频URL
  4071. $audioUrl = getProp($segment, 'audio_url');
  4072. $audioDuration = getProp($segment, 'audio_duration');
  4073. // 音频传入的前提:必须有至少一张图片或一个视频
  4074. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4075. // 余额预检:按预估时长计算所需积分,不足直接报错
  4076. $chargeDuration = (int)ceil((float)$audioDuration);
  4077. if ($chargeDuration <= 0) {
  4078. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4079. }
  4080. $this->pointsService->checkUserPointsEnough(
  4081. $this->pointsService->getVideoChargePoints([
  4082. 'model' => $model,
  4083. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4084. 'video_duration' => $chargeDuration,
  4085. 'ratio' => $ratio,
  4086. 'generate_audio' => $current_generate_audio,
  4087. ])
  4088. );
  4089. // dd($videoParams);
  4090. // 根据模型选择不同的视频生成方法
  4091. if (strpos($model, 'jimeng') !== false) {
  4092. // 即梦模型参数调整
  4093. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4094. unset($videoParams['content']); // 即梦不使用content格式
  4095. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4096. } elseif (strpos($model, 'kling') !== false) {
  4097. // Keling模型参数调整
  4098. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4099. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4100. unset($videoParams['ratio']);
  4101. unset($videoParams['content']); // Keling不使用content格式
  4102. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4103. } elseif (strpos($model, 'zhizhen') !== false) {
  4104. // 智帧20等新模型使用统一API
  4105. // 构建统一API参数
  4106. $unifiedParams = [
  4107. 'model_code' => $model,
  4108. 'alias_segment_id' => $segment_id,
  4109. 'prompt' => trim($fullPrompt),
  4110. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4111. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4112. 'video_ratio' => $ratio,
  4113. 'seed' => -1,
  4114. ];
  4115. // 构建parameters参数
  4116. $parameters = [
  4117. 'seconds' => $unifiedParams['video_duration'],
  4118. 'resolution' => $unifiedParams['video_resolution'],
  4119. 'ratio' => $ratio,
  4120. // 'video_mode' => 'multi_image',
  4121. // 'mode' => 'multi_image',
  4122. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4123. ];
  4124. $hasImage = false;
  4125. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4126. if ($hasImage) {
  4127. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4128. if (isset($videoParams['tail_frame_url'])) {
  4129. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4130. }
  4131. // 只有在有图片的情况下才能添加参考音频
  4132. if ($audioUrl) {
  4133. // $parameters['reference_audios'] = [$audioUrl];
  4134. }
  4135. } else {
  4136. // 没有图片时,记录错误日志
  4137. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4138. 'segment_id' => $segment_id,
  4139. 'model' => $model
  4140. ]);
  4141. }
  4142. $unifiedParams['parameters'] = $parameters;
  4143. // 调用统一API创建任务
  4144. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4145. } else {
  4146. // Seedance模型(默认)
  4147. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4148. if ($this->isKuaikuaiSeedanceModel($model)) {
  4149. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4150. if ($canUseAudio && $audioUrl) {
  4151. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4152. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4153. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4154. // 优化提示词,增加音频相关描述
  4155. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4156. $videoParams['prompt'] = $audioPrompt;
  4157. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4158. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4159. }
  4160. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4161. } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4162. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4163. // 添加配音音频到content中
  4164. $videoParams['content'][] = [
  4165. 'type' => 'audio_url',
  4166. 'audio_url' => [
  4167. 'url' => $audioUrl,
  4168. ],
  4169. 'role' => 'reference_audio',
  4170. ];
  4171. // 优化提示词,增加音频相关描述
  4172. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4173. $videoParams['prompt'] = $audioPrompt;
  4174. $videoParams['content'][0]['text'] = $audioPrompt;
  4175. } else {
  4176. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4177. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4178. }
  4179. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4180. }
  4181. }
  4182. // 更新分镜表的视频任务信息
  4183. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4184. 'video_task_id' => $task->id,
  4185. 'video_task_status' => '生成中',
  4186. 'generate_audio' => $generate_audio,
  4187. 'updated_at' => date('Y-m-d H:i:s')
  4188. ]);
  4189. return [
  4190. 'task_id' => $task->id,
  4191. 'status' => $task->status,
  4192. 'segment_id' => $segment_id,
  4193. 'video_duration' => $videoDuration
  4194. ];
  4195. }
  4196. /**
  4197. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4198. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4199. *
  4200. * @param string $model
  4201. * @return bool
  4202. */
  4203. public function isKuaikuaiSeedanceModel(string $model): bool
  4204. {
  4205. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4206. }
  4207. /**
  4208. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4209. *
  4210. * @param string $model
  4211. * @return bool
  4212. */
  4213. public function isBaiduSeedanceModel(string $model): bool
  4214. {
  4215. return in_array($model, [
  4216. 'baidu-doubao-seedance-2-0-260128',
  4217. 'baidu-doubao-seedance-2-0-fast-260128',
  4218. 'baidu-doubao-seedance-2-0-mini-260615',
  4219. 'baidu-doubao-seedance-2-5-260628',
  4220. ], true);
  4221. }
  4222. /**
  4223. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4224. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4225. *
  4226. * @param string $model
  4227. * @return bool
  4228. */
  4229. public function isOverseasBaiduSeedanceModel(string $model): bool
  4230. {
  4231. return in_array($model, [
  4232. 'baidu-dreamina-seedance-2-0-260128',
  4233. 'baidu-dreamina-seedance-2-0-fast-260128',
  4234. 'baidu-dreamina-seedance-2-0-mini-260615',
  4235. 'baidu-dreamina-seedance-2-5-260628',
  4236. ], true);
  4237. }
  4238. /**
  4239. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4240. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4241. *
  4242. * @param string $model
  4243. * @return bool
  4244. */
  4245. public function isSeedance20SeriesModel(string $model): bool
  4246. {
  4247. return strpos($model, 'doubao-seedance-2.0') !== false
  4248. || $this->isKuaikuaiSeedanceModel($model)
  4249. || $this->isBaiduSeedanceModel($model)
  4250. || $this->isOverseasBaiduSeedanceModel($model);
  4251. }
  4252. public function createActVideoTask($data) {
  4253. $act_id = getProp($data, 'act_id');
  4254. $first_frame_url = getProp($data, 'first_frame_url');
  4255. $tail_frame_url = getProp($data, 'tail_frame_url');
  4256. $generate_audio = getProp($data, 'generate_audio', 1);
  4257. $video_duration = getProp($data, 'video_duration');
  4258. $video_resolution = getProp($data, 'video_resolution');
  4259. $ratio = getProp($data, 'ratio');
  4260. $products = getProp($data, 'products', []);
  4261. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4262. if (!is_array($reference_images) || !is_array($products)) {
  4263. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4264. }
  4265. if (!$act_id) {
  4266. Utils::throwError('1002:片段ID不能为空');
  4267. }
  4268. // 获取片段信息
  4269. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4270. if (!$act) {
  4271. Utils::throwError('20003:片段不存在');
  4272. }
  4273. $act = (array)$act;
  4274. $anime_id = getProp($act, 'anime_id');
  4275. $episode_id = getProp($act, 'episode_id');
  4276. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4277. $ace_mode = getProp($anime, 'ace_mode');
  4278. $art_style_type = getProp($anime, 'art_style_type');
  4279. $art_style = getProp($anime, 'art_style');
  4280. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4281. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4282. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4283. // 将资产中新出现的资产放到extra_products中
  4284. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4285. if (!empty($products) && $episode) {
  4286. // 获取剧集中的角色、场景和道具列表
  4287. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4288. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4289. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4290. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4291. // 构建角色名称列表
  4292. $role_names = array_column($roles, 'role');
  4293. // 构建场景名称列表
  4294. $scene_names = array_column($scenes, 'scene');
  4295. // 构建道具名称列表
  4296. $prop_names = array_column($props, 'prop');
  4297. // 遍历传入的products
  4298. foreach ($products as $product) {
  4299. $product_name = getProp($product, 'product_name');
  4300. // 如果product_name不在roles、scenes和props中
  4301. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4302. // 查找是否在extra_products中存在同名的
  4303. $found = false;
  4304. foreach ($extra_products as $key => $extra_product) {
  4305. if (getProp($extra_product, 'product_name') === $product_name) {
  4306. // 有同名的则覆盖
  4307. $extra_products[$key] = $product;
  4308. $found = true;
  4309. break;
  4310. }
  4311. }
  4312. // 没有则新增
  4313. if (!$found) {
  4314. $extra_products[] = $product;
  4315. }
  4316. }
  4317. }
  4318. if ($extra_products) {
  4319. // 保存到数据库
  4320. DB::table('mp_anime_episodes')
  4321. ->where('id', $episode_id)
  4322. ->update([
  4323. 'extra_products' => json_encode($extra_products, 256),
  4324. 'updated_at' => date('Y-m-d H:i:s')
  4325. ]);
  4326. }
  4327. }
  4328. // 获取分镜内容
  4329. $actContent = getProp($act, 'act_show_content', '');
  4330. // 音效同出(默认使用)
  4331. $current_generate_audio = $generate_audio ? 1 : 0;
  4332. // 构建完整的提示词
  4333. $processResult = $this->processActContentWithProducts($actContent, $products);
  4334. $fullPrompt = $processResult['content'];
  4335. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4336. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4337. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4338. // 处理视频模型
  4339. $model = getProp($data, 'model');
  4340. if (!$model) {
  4341. $model = getProp($episode, 'video_model');
  4342. if (!$model) {
  4343. // episode表也没有,使用默认值
  4344. $model = 'seed-2';
  4345. }
  4346. }
  4347. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4348. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4349. if (!in_array($model, $valid_models)) {
  4350. $model = 'seed-2';
  4351. }
  4352. // 保存到episode表(仅在专用方法中更新模型)
  4353. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4354. // 'video_model' => $model,
  4355. // 'updated_at' => date('Y-m-d H:i:s')
  4356. // ]);
  4357. // 余额预检:按预估时长计算所需积分,不足直接报错
  4358. $chargeDuration = (int)$videoDuration;
  4359. if ($chargeDuration <= 0) {
  4360. $chargeDuration = 5; // 无时长时按默认5秒预估
  4361. }
  4362. $this->pointsService->checkUserPointsEnough(
  4363. $this->pointsService->getVideoChargePoints([
  4364. 'model' => $model,
  4365. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4366. 'video_duration' => $chargeDuration,
  4367. 'ratio' => $ratio,
  4368. 'generate_audio' => $current_generate_audio,
  4369. ])
  4370. );
  4371. // 构建视频生成参数
  4372. $videoParams = [
  4373. 'model' => $model,
  4374. 'alias_act_id' => $act_id,
  4375. 'prompt' => trim($fullPrompt),
  4376. 'video_duration' => $videoDuration,
  4377. 'video_resolution' => $video_resolution,
  4378. 'seed' => -1,
  4379. 'ratio' => $ratio,
  4380. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4381. 'draft' => false,
  4382. 'watermark' => false,
  4383. 'camera_fixed' => false,
  4384. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4385. ];
  4386. // 如果分镜有图片,作为首帧
  4387. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4388. $hasVideo = !empty(getProp($act, 'video_url'));
  4389. if ($hasImage) {
  4390. if ($first_frame_url) {
  4391. $videoParams['first_frame_url'] = $first_frame_url;
  4392. }else {
  4393. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4394. }
  4395. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4396. }
  4397. // 构建content数组
  4398. $videoParams['content'] = [
  4399. [
  4400. 'type' => 'text',
  4401. 'text' => $videoParams['prompt'],
  4402. ]
  4403. ];
  4404. // 如果有首帧图片,添加到content中
  4405. if ($hasImage) {
  4406. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4407. $videoParams['content'][] = [
  4408. 'type' => 'image_url',
  4409. 'image_url' => [
  4410. 'url' => $videoParams['first_frame_url'],
  4411. ],
  4412. 'role' => 'reference_image',
  4413. ];
  4414. if (isset($videoParams['tail_frame_url'])) {
  4415. $videoParams['content'][] = [
  4416. 'type' => 'image_url',
  4417. 'image_url' => [
  4418. 'url' => $videoParams['tail_frame_url'],
  4419. ],
  4420. 'role' => 'reference_image',
  4421. ];
  4422. }
  4423. }else {
  4424. $videoParams['content'][] = [
  4425. 'type' => 'image_url',
  4426. 'image_url' => [
  4427. 'url' => $videoParams['first_frame_url'],
  4428. ],
  4429. 'role' => 'first_frame',
  4430. ];
  4431. if (isset($videoParams['tail_frame_url'])) {
  4432. $videoParams['content'][] = [
  4433. 'type' => 'image_url',
  4434. 'image_url' => [
  4435. 'url' => $videoParams['tail_frame_url'],
  4436. ],
  4437. 'role' => 'last_frame',
  4438. ];
  4439. }
  4440. }
  4441. }
  4442. // dd($videoParams);
  4443. // 根据模型选择不同的视频生成方法
  4444. try {
  4445. if (strpos($model, 'jimeng') !== false) {
  4446. // 即梦模型参数调整
  4447. unset($videoParams['content']); // 即梦不使用content格式
  4448. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4449. } elseif (strpos($model, 'kling') !== false) {
  4450. // Keling模型参数调整
  4451. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4452. unset($videoParams['ratio']);
  4453. unset($videoParams['content']); // Keling不使用content格式
  4454. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4455. } elseif (strpos($model, 'zhizhen') !== false) {
  4456. // 智帧20等新模型使用统一API
  4457. // 构建统一API参数
  4458. $unifiedParams = [
  4459. 'model_code' => $model,
  4460. 'alias_act_id' => $act_id,
  4461. 'prompt' => trim($fullPrompt),
  4462. 'video_duration' => $videoDuration,
  4463. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4464. 'video_ratio' => $ratio,
  4465. 'seed' => -1,
  4466. ];
  4467. // 构建parameters参数
  4468. $parameters = [
  4469. 'seconds' => $unifiedParams['video_duration'],
  4470. 'resolution' => $unifiedParams['video_resolution'],
  4471. 'ratio' => $ratio,
  4472. // 'video_mode' => 'multi_image',
  4473. // 'mode' => 'multi_image',
  4474. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4475. ];
  4476. $hasImage = false;
  4477. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4478. if ($hasImage) {
  4479. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4480. if (isset($videoParams['tail_frame_url'])) {
  4481. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4482. }
  4483. } else {
  4484. // 没有图片时,记录错误日志
  4485. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4486. 'act_id' => $act_id,
  4487. 'model' => $model
  4488. ]);
  4489. }
  4490. if ($reference_images) {
  4491. // 限制只传入9张参考图
  4492. $reference_images = array_slice($reference_images, 0, 9);
  4493. // 在处理之前先保存原始reference_images到任务参数中
  4494. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4495. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4496. $parameters['reference_images'] = $reference_images;
  4497. $parameters['video_mode'] = 'multi_image';
  4498. $parameters['mode'] = 'multi_image';
  4499. }
  4500. $unifiedParams['parameters'] = $parameters;
  4501. // 调用统一API创建任务
  4502. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4503. } elseif ($this->isSeedance20SeriesModel($model)) {
  4504. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4505. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4506. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4507. // 保存原始参考图用于任务记录
  4508. $videoParams['reference_images'] = $reference_images;
  4509. if ($reference_images) {
  4510. // 限制只传入9张参考图
  4511. $reference_images = array_slice($reference_images, 0, 9);
  4512. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4513. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4514. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4515. $reference_image_assets = $isKuaikuai
  4516. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4517. : ($isDreamina
  4518. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4519. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4520. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4521. $videoParams['prompt'] = trim($fullPrompt);
  4522. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4523. $videoParams['reference_image_assets'] = $reference_image_assets;
  4524. }
  4525. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4526. if ($isKuaikuai) {
  4527. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4528. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4529. } else {
  4530. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4531. }
  4532. } else {
  4533. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4534. }
  4535. } catch (ApiException $e) {
  4536. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4537. if ($e->getCode() === 1001) {
  4538. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4539. }
  4540. throw $e;
  4541. } catch (\Exception $e) {
  4542. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4543. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4544. }
  4545. // 更新分镜表的视频任务信息
  4546. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4547. 'video_task_id' => $task->id,
  4548. 'video_task_status' => '生成中',
  4549. 'generate_audio' => $generate_audio,
  4550. 'updated_at' => date('Y-m-d H:i:s')
  4551. ]);
  4552. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4553. $episode_number = getProp($act, 'episode_number');
  4554. $act_number = getProp($act, 'act_number');
  4555. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4556. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4557. }
  4558. $result = [
  4559. 'task_id' => $task->id,
  4560. 'status' => $task->status,
  4561. 'act_id' => $act_id,
  4562. 'video_duration' => $videoDuration
  4563. ];
  4564. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4565. if ($task->status === 'failed' && !empty($task->error_message)) {
  4566. $result['error_message'] = mapErrorMessage($task->error_message);
  4567. }
  4568. return $result;
  4569. }
  4570. /**
  4571. * 文生视频通用方法
  4572. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4573. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4574. *
  4575. * @param array $data 请求参数
  4576. * @return array
  4577. */
  4578. public function generateVideo($data) {
  4579. $prompt = getProp($data, 'prompt');
  4580. if (empty($prompt)) {
  4581. Utils::throwError('20003:提示词不能为空');
  4582. }
  4583. $model = getProp($data, 'model');
  4584. if (!$model) {
  4585. $model = 'seed-2';
  4586. }
  4587. // 验证模型是否在可用模型表中
  4588. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4589. Utils::throwError('20003:该模型已不可用,请更换!');
  4590. }
  4591. $video_duration = getProp($data, 'video_duration', 5);
  4592. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4593. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4594. $ratio = getProp($data, 'ratio', '9:16');
  4595. $generate_audio = getProp($data, 'generate_audio', 1);
  4596. $seed = getProp($data, 'seed', -1);
  4597. $first_frame_url = getProp($data, 'first_frame_url');
  4598. $tail_frame_url = getProp($data, 'tail_frame_url');
  4599. // 参考图(支持数组或JSON字符串,最多9张)
  4600. $reference_images = getProp($data, 'reference_images', []);
  4601. if (is_string($reference_images)) {
  4602. $reference_images = json_decode($reference_images, true) ?: [];
  4603. }
  4604. if (!is_array($reference_images)) {
  4605. Utils::throwError('20003:参考图格式不正确');
  4606. }
  4607. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4608. $reference_images = array_slice($reference_images, 0, 9);
  4609. // 参考视频(支持数组或JSON字符串,最多3个)
  4610. $reference_videos = getProp($data, 'reference_videos', []);
  4611. if (is_string($reference_videos)) {
  4612. $reference_videos = json_decode($reference_videos, true) ?: [];
  4613. }
  4614. if (!is_array($reference_videos)) {
  4615. Utils::throwError('20003:参考视频格式不正确');
  4616. }
  4617. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4618. if (count($reference_videos) > 3) {
  4619. Utils::throwError('20003:参考视频最多选择3个');
  4620. }
  4621. $reference_videos = array_slice($reference_videos, 0, 3);
  4622. // 参考音频(支持数组或JSON字符串,最多3个)
  4623. $reference_audios = getProp($data, 'reference_audios', []);
  4624. if (is_string($reference_audios)) {
  4625. $reference_audios = json_decode($reference_audios, true) ?: [];
  4626. }
  4627. if (!is_array($reference_audios)) {
  4628. Utils::throwError('20003:参考音频格式不正确');
  4629. }
  4630. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4631. if (count($reference_audios) > 3) {
  4632. Utils::throwError('20003:参考音频最多选择3个');
  4633. }
  4634. $reference_audios = array_slice($reference_audios, 0, 3);
  4635. // 余额预检:按预估时长计算所需积分,不足直接报错
  4636. $chargeDuration = (int)ceil((float)$video_duration);
  4637. if ($chargeDuration <= 0) {
  4638. $chargeDuration = 5; // 无时长时按默认5秒预估
  4639. }
  4640. $this->pointsService->checkUserPointsEnough(
  4641. $this->pointsService->getVideoChargePoints([
  4642. 'model' => $model,
  4643. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4644. 'video_duration' => $chargeDuration,
  4645. 'ratio' => $ratio,
  4646. 'generate_audio' => (int)$generate_audio,
  4647. ])
  4648. );
  4649. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4650. $videoParams = [
  4651. 'model' => $model,
  4652. 'prompt' => $prompt,
  4653. 'video_duration' => $video_duration,
  4654. 'video_resolution' => $video_resolution,
  4655. 'seed' => $seed,
  4656. 'ratio' => $ratio,
  4657. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4658. 'draft' => getProp($data, 'draft', false),
  4659. 'watermark' => getProp($data, 'watermark', false),
  4660. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4661. ];
  4662. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4663. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4664. // 构建content数组
  4665. $videoParams['content'] = [
  4666. [
  4667. 'type' => 'text',
  4668. 'text' => $prompt,
  4669. ]
  4670. ];
  4671. // 根据模型选择不同的视频生成方法
  4672. if (strpos($model, 'jimeng') !== false) {
  4673. // 即梦模型参数调整
  4674. unset($videoParams['content']); // 即梦不使用content格式
  4675. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4676. } elseif (strpos($model, 'kling') !== false) {
  4677. // 可灵模型参数调整
  4678. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4679. unset($videoParams['ratio']);
  4680. unset($videoParams['content']); // 可灵不使用content格式
  4681. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4682. } elseif (strpos($model, 'zhizhen') !== false) {
  4683. // 智帧等新模型使用统一API
  4684. $unifiedParams = [
  4685. 'model_code' => $model,
  4686. 'prompt' => $prompt,
  4687. 'video_duration' => $video_duration,
  4688. 'video_resolution' => strtolower($video_resolution),
  4689. 'video_ratio' => $ratio,
  4690. 'seed' => $seed,
  4691. ];
  4692. // 构建parameters参数
  4693. $parameters = [
  4694. 'seconds' => $unifiedParams['video_duration'],
  4695. 'resolution' => $unifiedParams['video_resolution'],
  4696. 'ratio' => $ratio,
  4697. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4698. ];
  4699. // 首帧和尾帧
  4700. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4701. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4702. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4703. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4704. if ($refImageUrls) {
  4705. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4706. }
  4707. // 参考图处理
  4708. if ($reference_images) {
  4709. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4710. $parameters['reference_images'] = $reference_images;
  4711. $parameters['video_mode'] = 'multi_image';
  4712. $parameters['mode'] = 'multi_image';
  4713. }
  4714. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4715. if ($reference_videos) {
  4716. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4717. $parameters['reference_videos'] = $reference_videos;
  4718. }
  4719. if ($reference_audios) {
  4720. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4721. $parameters['reference_audios'] = $reference_audios;
  4722. }
  4723. $unifiedParams['parameters'] = $parameters;
  4724. // 调用统一API创建任务
  4725. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4726. } elseif ($this->isSeedance20SeriesModel($model)) {
  4727. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4728. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4729. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4730. $videoParams['reference_images'] = $reference_images;
  4731. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4732. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4733. if ($refImageUrls) {
  4734. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4735. }
  4736. if ($reference_images) {
  4737. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4738. $reference_image_assets = $isKuaikuai
  4739. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4740. : ($isDreamina
  4741. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4742. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4743. $videoParams['reference_image_assets'] = $reference_image_assets;
  4744. }
  4745. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4746. if ($reference_videos) {
  4747. $reference_video_assets = $isKuaikuai
  4748. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4749. : ($isDreamina
  4750. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4751. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4752. $videoParams['reference_video_assets'] = $reference_video_assets;
  4753. }
  4754. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4755. if ($reference_audios) {
  4756. $reference_audio_assets = $isKuaikuai
  4757. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4758. : ($isDreamina
  4759. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4760. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4761. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4762. }
  4763. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4764. if ($reference_images || $reference_videos || $reference_audios) {
  4765. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4766. }
  4767. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4768. if ($isKuaikuai) {
  4769. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4770. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4771. } else {
  4772. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4773. }
  4774. } else {
  4775. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4776. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4777. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4778. if ($refImageUrls) {
  4779. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4780. }
  4781. if ($reference_videos) {
  4782. foreach ($reference_videos as $videoUrl) {
  4783. $videoParams['content'][] = [
  4784. 'type' => 'video_url',
  4785. 'video_url' => [
  4786. 'url' => $videoUrl,
  4787. ],
  4788. 'role' => 'reference_video',
  4789. ];
  4790. }
  4791. }
  4792. if ($reference_audios) {
  4793. foreach ($reference_audios as $audioUrl) {
  4794. $videoParams['content'][] = [
  4795. 'type' => 'audio_url',
  4796. 'audio_url' => [
  4797. 'url' => $audioUrl,
  4798. ],
  4799. 'role' => 'reference_audio',
  4800. ];
  4801. }
  4802. }
  4803. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4804. }
  4805. return [
  4806. 'task_id' => $task->id,
  4807. 'status' => $task->status,
  4808. 'model' => $model,
  4809. 'video_duration' => $video_duration,
  4810. 'video_resolution' => $video_resolution,
  4811. 'ratio' => $ratio
  4812. ];
  4813. }
  4814. /**
  4815. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4816. *
  4817. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4818. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4819. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4820. *
  4821. * @param array $data
  4822. * @return array
  4823. */
  4824. public function previewCharge(array $data): array
  4825. {
  4826. $mode = (string)getProp($data, 'mode', '');
  4827. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4828. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4829. }
  4830. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4831. $scene = (string)getProp($data, 'scene', 'video_generation');
  4832. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4833. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4834. $scene = 'video_to_video';
  4835. }
  4836. $items = [];
  4837. $model = '';
  4838. $resolution = '';
  4839. if ($mode === 'video') {
  4840. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4841. $model = (string)getProp($data, 'model', '');
  4842. if (!$model) {
  4843. Utils::throwError('1002:model参数不能为空');
  4844. }
  4845. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4846. $duration = (int)getProp($data, 'video_duration', 5);
  4847. if ($duration <= 0) {
  4848. $duration = 5;
  4849. }
  4850. $count = max(1, (int)getProp($data, 'count', 1));
  4851. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4852. 'model' => $model,
  4853. 'video_resolution' => $resolution,
  4854. 'video_duration' => $duration,
  4855. 'mode' => $scene,
  4856. ]);
  4857. $points = $pointsPerVideo * $count;
  4858. $items[] = [
  4859. 'type' => 'video',
  4860. 'model' => $model,
  4861. 'video_resolution' => $resolution,
  4862. 'video_duration' => $duration,
  4863. 'count' => $count,
  4864. 'points' => $points,
  4865. ];
  4866. } elseif ($mode === 'image') {
  4867. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4868. $model = (string)getProp($data, 'model', '');
  4869. if (!$model) {
  4870. Utils::throwError('1002:model参数不能为空');
  4871. }
  4872. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4873. if (!$resolution) {
  4874. $width = (int)getProp($data, 'width', 0);
  4875. $height = (int)getProp($data, 'height', 0);
  4876. if ($width <= 0 || $height <= 0) {
  4877. $width = 1600;
  4878. $height = 2848;
  4879. }
  4880. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4881. }
  4882. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4883. $points = $this->pointsService->getImageChargePoints([
  4884. 'model' => $model,
  4885. 'resolution' => $resolution,
  4886. ]) * $imageNum;
  4887. $items[] = [
  4888. 'type' => 'image',
  4889. 'model' => $model,
  4890. 'resolution' => $resolution,
  4891. 'image_num' => $imageNum,
  4892. 'points' => $points,
  4893. ];
  4894. } else {
  4895. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4896. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4897. $priceType = (string)getProp($data, 'price_type', 'special');
  4898. if (!in_array($priceType, ['special', 'normal'], true)) {
  4899. Utils::throwError('1003:price_type参数仅支持special或normal');
  4900. }
  4901. $count = max(1, (int)getProp($data, 'count', 1));
  4902. $animeId = getProp($data, 'anime_id');
  4903. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4904. if ($animeId && $generateEpisodes > 0) {
  4905. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4906. $priceType = 'special';
  4907. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4908. ->where('anime_id', $animeId)
  4909. ->where('is_default', 1)
  4910. ->max('episode_number');
  4911. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4912. $startEpisodeNumber = $currentMaxEpisode + 1;
  4913. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4914. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4915. ->where('anime_id', $animeId)
  4916. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4917. ->whereIn('status', ['pending', 'processing', 'completed'])
  4918. ->count();
  4919. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4920. if ($count < 0) {
  4921. $count = 0;
  4922. }
  4923. }
  4924. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4925. $items[] = [
  4926. 'type' => 'chat',
  4927. 'count' => $count,
  4928. 'price_type' => $priceType,
  4929. 'points' => $points,
  4930. ];
  4931. }
  4932. $totalPoints = 0;
  4933. foreach ($items as $item) {
  4934. $totalPoints += $item['points'];
  4935. }
  4936. return [
  4937. 'mode' => $mode,
  4938. 'total_points' => $totalPoints,
  4939. 'items' => $items,
  4940. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4941. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4942. ];
  4943. }
  4944. /**
  4945. * 根据提示词内容智能计算最优视频时长
  4946. *
  4947. * @param string $segmentContent 分镜内容
  4948. * @param string $tailFrame 尾帧描述
  4949. * @return int 视频时长(2-12秒)
  4950. */
  4951. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4952. // 合并所有文本内容
  4953. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4954. // 如果没有内容,返回默认时长
  4955. if (empty($fullText)) {
  4956. return 5;
  4957. }
  4958. // 计算文本长度(中文字符按2个字符计算)
  4959. $textLength = mb_strlen($fullText, 'UTF-8');
  4960. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4961. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4962. // 分析内容复杂度
  4963. $complexityScore = $this->analyzeContentComplexity($fullText);
  4964. // 基础时长计算(根据文本长度)
  4965. $baseDuration = 3; // 默认2秒
  4966. // if ($adjustedLength <= 20) {
  4967. // $baseDuration = 3;
  4968. // } elseif ($adjustedLength <= 40) {
  4969. // $baseDuration = 4;
  4970. // } elseif ($adjustedLength <= 60) {
  4971. // $baseDuration = 5;
  4972. // } elseif ($adjustedLength <= 80) {
  4973. // $baseDuration = 6;
  4974. // } elseif ($adjustedLength <= 100) {
  4975. // $baseDuration = 7;
  4976. // } elseif ($adjustedLength <= 120) {
  4977. // $baseDuration = 8;
  4978. // } else {
  4979. // $baseDuration = 9;
  4980. // }
  4981. // 根据内容复杂度调整时长
  4982. $finalDuration = $baseDuration + $complexityScore;
  4983. // 确保时长在2-12秒范围内
  4984. return max(4, min(12, $finalDuration));
  4985. }
  4986. /**
  4987. * 分析内容复杂度,返回时长调整值
  4988. *
  4989. * @param string $text 文本内容
  4990. * @return int 调整值(-2到+3)
  4991. */
  4992. private function analyzeContentComplexity($text) {
  4993. $score = 0;
  4994. // 动作关键词(需要更长时间展现)
  4995. $actionKeywords = [
  4996. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4997. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4998. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4999. ];
  5000. // 静态关键词(可以用较短时间)
  5001. $staticKeywords = [
  5002. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5003. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5004. ];
  5005. // 复杂场景关键词(需要更长时间)
  5006. $complexSceneKeywords = [
  5007. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5008. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5009. ];
  5010. // 情感关键词(需要适中时间表现)
  5011. $emotionKeywords = [
  5012. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5013. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5014. ];
  5015. // 检查动作关键词
  5016. foreach ($actionKeywords as $keyword) {
  5017. if (strpos($text, $keyword) !== false) {
  5018. $score += 1;
  5019. break; // 避免重复加分
  5020. }
  5021. }
  5022. // 检查静态关键词
  5023. foreach ($staticKeywords as $keyword) {
  5024. if (strpos($text, $keyword) !== false) {
  5025. $score -= 1;
  5026. break;
  5027. }
  5028. }
  5029. // 检查复杂场景关键词
  5030. foreach ($complexSceneKeywords as $keyword) {
  5031. if (strpos($text, $keyword) !== false) {
  5032. $score += 1;
  5033. break;
  5034. }
  5035. }
  5036. // 检查情感关键词
  5037. foreach ($emotionKeywords as $keyword) {
  5038. if (strpos($text, $keyword) !== false) {
  5039. $score += 1;
  5040. break;
  5041. }
  5042. }
  5043. // 检查时间相关词汇
  5044. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5045. $score += 1;
  5046. }
  5047. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5048. $score -= 1;
  5049. }
  5050. // 检查转场词汇
  5051. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5052. $score += 1;
  5053. }
  5054. // 检查环境描述(复杂环境需要更多时间)
  5055. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5056. $score += 1;
  5057. }
  5058. // 检查对话内容(对话需要更多时间)
  5059. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5060. $score += 1;
  5061. }
  5062. // 限制调整范围
  5063. return max(-1, min(4, $score));
  5064. }
  5065. /**
  5066. * 创建完整视频合成任务
  5067. *
  5068. * @param array $data
  5069. * @return array
  5070. */
  5071. public function createCompleteVideoTask($data)
  5072. {
  5073. $animeId = getProp($data, 'anime_id');
  5074. $episodeId = getProp($data, 'episode_id');
  5075. // 验证参数
  5076. if (!$animeId || !$episodeId) {
  5077. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5078. }
  5079. // 检查是否已存在处理中的任务
  5080. $existingTask = DB::table('mp_complete_video_tasks')
  5081. ->where('anime_id', $animeId)
  5082. ->where('episode_id', $episodeId)
  5083. ->whereIn('generate_status', ['执行中'])
  5084. ->first();
  5085. if ($existingTask) {
  5086. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5087. }
  5088. // 获取全能模式状态
  5089. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5090. if ((int)$ace_mode === 1) {
  5091. // 获取所有片段的配音视频,按 act_number 排序
  5092. $segments = DB::table('mp_episode_segments')
  5093. ->where('anime_id', $animeId)
  5094. ->where('episode_id', $episodeId)
  5095. ->orderBy('segment_number')
  5096. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5097. ->get();
  5098. // 检查是否所有片段都有视频
  5099. $missingVideos = $segments->filter(function($segment) {
  5100. return empty($segment->video_url);
  5101. });
  5102. if ($missingVideos->isNotEmpty()) {
  5103. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5104. }
  5105. }else {
  5106. // 获取所有分镜的配音视频,按 segment_number 排序
  5107. $segments = DB::table('mp_episode_segments')
  5108. ->where('anime_id', $animeId)
  5109. ->where('episode_id', $episodeId)
  5110. ->orderBy('segment_number')
  5111. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5112. ->get();
  5113. // 检查是否所有分镜都有配音和视频
  5114. $missingVideos = $segments->filter(function($segment) {
  5115. return empty($segment->audio_url) || empty($segment->video_url);
  5116. });
  5117. if ($missingVideos->isNotEmpty()) {
  5118. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5119. }
  5120. }
  5121. if ($segments->isEmpty()) {
  5122. Utils::throwError('20003:未找到该剧集的分镜数据');
  5123. }
  5124. // 获取当前完整视频url
  5125. $completeVideoUrl = DB::table('mp_anime_episodes')
  5126. ->where('anime_id', $animeId)
  5127. ->where('id', $episodeId)
  5128. ->value('complete_video_url');
  5129. // 构建 generate_json
  5130. $generateJson = [];
  5131. $sequence = 1;
  5132. foreach ($segments as $segment) {
  5133. if ((int)$ace_mode === 1) {
  5134. $generateJson[] = [
  5135. 'sequence' => $sequence++,
  5136. 'video_url' => $segment->video_url,
  5137. 'video_time_point_start' => $segment->video_time_point_start,
  5138. 'video_time_point_end' => $segment->video_time_point_end
  5139. ];
  5140. }else {
  5141. $generateJson[] = [
  5142. 'sequence' => $sequence++,
  5143. 'video_url' => $segment->video_url,
  5144. 'audio_url' => $segment->audio_url,
  5145. 'video_time_point_start' => $segment->video_time_point_start,
  5146. 'video_time_point_end' => $segment->video_time_point_end
  5147. ];
  5148. }
  5149. }
  5150. // 创建任务
  5151. $now = date('Y-m-d H:i:s');
  5152. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5153. 'anime_id' => $animeId,
  5154. 'episode_id' => $episodeId,
  5155. 'generate_json' => json_encode($generateJson, 256),
  5156. 'generate_status' => '执行中',
  5157. 'complete_video_url' => '',
  5158. 'created_at' => $now,
  5159. 'updated_at' => $now
  5160. ]);
  5161. if (!$taskId) {
  5162. Utils::throwError('20003:创建任务失败');
  5163. }
  5164. // 更新剧集表的任务ID和状态
  5165. $boolen = DB::table('mp_anime_episodes')
  5166. ->where('anime_id', $animeId)
  5167. ->where('id', $episodeId)
  5168. ->update([
  5169. 'complete_video_task_id' => $taskId,
  5170. 'complete_video_task_status' => '执行中',
  5171. 'updated_at' => $now
  5172. ]);
  5173. if (!$boolen) {
  5174. Utils::throwError('20003:更新剧集表失败');
  5175. }
  5176. dLog('anime')->info('创建完整视频合成任务', [
  5177. 'task_id' => $taskId,
  5178. 'anime_id' => $animeId,
  5179. 'episode_id' => $episodeId,
  5180. 'segment_count' => count($generateJson)
  5181. ]);
  5182. // 请求远程服务器执行生成
  5183. $client = new Client(['timeout' => 600, 'verify' => false]);
  5184. try {
  5185. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5186. $response = $result->getBody()->getContents();
  5187. $response_arr = json_decode($response, true);
  5188. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5189. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5190. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5191. // // 更新任务状态为失败
  5192. // DB::table('mp_complete_video_tasks')
  5193. // ->where('id', $taskId)
  5194. // ->update([
  5195. // 'generate_status' => '执行失败',
  5196. // 'error_message' => $error_msg,
  5197. // 'updated_at' => date('Y-m-d H:i:s')
  5198. // ]);
  5199. // // 同步更新剧集表状态
  5200. // DB::table('mp_anime_episodes')
  5201. // ->where('complete_video_task_id', $taskId)
  5202. // ->update([
  5203. // 'complete_video_task_status' => '执行失败',
  5204. // 'updated_at' => date('Y-m-d H:i:s')
  5205. // ]);
  5206. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5207. }
  5208. } catch (\Exception $e) {
  5209. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5210. // 更新任务状态为失败
  5211. DB::table('mp_complete_video_tasks')
  5212. ->where('id', $taskId)
  5213. ->update([
  5214. 'generate_status' => '执行失败',
  5215. 'error_message' => $e->getMessage(),
  5216. 'updated_at' => date('Y-m-d H:i:s')
  5217. ]);
  5218. // 同步更新剧集表状态
  5219. DB::table('mp_anime_episodes')
  5220. ->where('complete_video_task_id', $taskId)
  5221. ->update([
  5222. 'complete_video_task_status' => '执行失败',
  5223. 'updated_at' => date('Y-m-d H:i:s')
  5224. ]);
  5225. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5226. }
  5227. // 开始轮询任务状态
  5228. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5229. $pollInterval = 5; // 每5秒轮询一次
  5230. $attempt = 0;
  5231. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5232. while ($attempt < $maxAttempts) {
  5233. sleep($pollInterval);
  5234. $attempt++;
  5235. // 查询任务状态
  5236. $task = DB::table('mp_complete_video_tasks')
  5237. ->where('id', $taskId)
  5238. ->first();
  5239. if (!$task) {
  5240. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5241. Utils::throwError('20003:任务不存在');
  5242. }
  5243. dLog('anime')->info('轮询任务状态', [
  5244. 'task_id' => $taskId,
  5245. 'attempt' => $attempt,
  5246. 'status' => $task->generate_status
  5247. ]);
  5248. // 检查任务是否完成
  5249. if ($task->generate_status === '执行成功') {
  5250. // 同步更新剧集表状态
  5251. $boolen3 = DB::table('mp_anime_episodes')
  5252. ->where('anime_id', $animeId)
  5253. ->where('id', $episodeId)
  5254. ->update([
  5255. 'complete_video_url' => $task->complete_video_url,
  5256. 'complete_video_task_status' => '执行成功',
  5257. 'updated_at' => date('Y-m-d H:i:s')
  5258. ]);
  5259. dLog('anime')->info('视频合成任务完成', [
  5260. 'task_id' => $taskId,
  5261. 'video_url' => $task->complete_video_url,
  5262. 'attempts' => $attempt
  5263. ]);
  5264. // 如果更新成功则远程删除之前的文件
  5265. if ($boolen3 && $completeVideoUrl) {
  5266. $encode_url = urlencode($completeVideoUrl);
  5267. $client = new Client(['timeout' => 300, 'verify' => false]);
  5268. // 根据ID通过API通知合成音频
  5269. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5270. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5271. $response = $result->getBody()->getContents();
  5272. $response_arr = json_decode($response, true);
  5273. Log::info('火山删除音频返回: '.$response);
  5274. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5275. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5276. Log::info('火山删除音频失败: '.$error_msg);
  5277. // Utils::throwError('20003:火山删除音频失败');
  5278. }
  5279. }
  5280. return [
  5281. 'task_id' => $taskId,
  5282. 'anime_id' => $animeId,
  5283. 'episode_id' => $episodeId,
  5284. 'segment_count' => count($generateJson),
  5285. 'generate_status' => '执行成功',
  5286. 'complete_video_url' => $task->complete_video_url,
  5287. ];
  5288. }
  5289. // 检查任务是否失败
  5290. if ($task->generate_status === '执行失败') {
  5291. // 同步更新剧集表状态
  5292. DB::table('mp_anime_episodes')
  5293. ->where('anime_id', $animeId)
  5294. ->where('id', $episodeId)
  5295. ->update([
  5296. 'complete_video_task_status' => '执行失败',
  5297. 'updated_at' => date('Y-m-d H:i:s')
  5298. ]);
  5299. $errorMessage = $task->error_message ?? '未知错误';
  5300. dLog('anime')->error('视频合成任务失败', [
  5301. 'task_id' => $taskId,
  5302. 'error' => $errorMessage,
  5303. 'attempts' => $attempt
  5304. ]);
  5305. return [
  5306. 'task_id' => $taskId,
  5307. 'anime_id' => $animeId,
  5308. 'episode_id' => $episodeId,
  5309. 'segment_count' => count($generateJson),
  5310. 'generate_status' => '执行失败',
  5311. 'error_message' => $errorMessage
  5312. ];
  5313. }
  5314. }
  5315. // 超时处理
  5316. dLog('anime')->warning('视频合成任务超时', [
  5317. 'task_id' => $taskId,
  5318. 'max_attempts' => $maxAttempts,
  5319. 'timeout_seconds' => $maxAttempts * $pollInterval
  5320. ]);
  5321. // 更新任务状态为超时
  5322. DB::table('mp_complete_video_tasks')
  5323. ->where('id', $taskId)
  5324. ->update([
  5325. 'generate_status' => '超时',
  5326. 'error_message' => '任务执行超时(5分钟)',
  5327. 'updated_at' => date('Y-m-d H:i:s')
  5328. ]);
  5329. return [
  5330. 'task_id' => $taskId,
  5331. 'anime_id' => $animeId,
  5332. 'episode_id' => $episodeId,
  5333. 'segment_count' => count($generateJson),
  5334. 'generate_status' => '超时',
  5335. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5336. ];
  5337. }
  5338. /**
  5339. * 根据 inner_prompt_type 附加内置提示词
  5340. *
  5341. * @param string $prompt 用户提示词
  5342. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5343. * @return string 合并后的提示词
  5344. */
  5345. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5346. {
  5347. $innerPromptMap = [
  5348. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5349. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5350. ];
  5351. if (!isset($innerPromptMap[$innerPromptType])) {
  5352. return $prompt;
  5353. }
  5354. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5355. }
  5356. /**
  5357. * 根据 inner_prompt_type 获取生成图片数量
  5358. *
  5359. * @param int $innerPromptType 内置提示词类型
  5360. * @param int $imageNum 传入的图片张数
  5361. * @return int 图片数量
  5362. */
  5363. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5364. {
  5365. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5366. }
  5367. /**
  5368. * 提取图片生成结果URL
  5369. *
  5370. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5371. * @param int $innerPromptType 内置提示词类型
  5372. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5373. */
  5374. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5375. {
  5376. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5377. if (is_array($resultUrls) && !empty($resultUrls)) {
  5378. $resultUrls = array_values($resultUrls);
  5379. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5380. }
  5381. if (!empty($resultUrl)) {
  5382. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5383. }
  5384. return (int)$innerPromptType === 2 ? [] : '';
  5385. }
  5386. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5387. $prompt = getProp($data, 'prompt');
  5388. $episode_id = getProp($data, 'episode_id');
  5389. $ref_img_urls = getProp($data, 'ref_img_urls');
  5390. $ratio = getProp($data, 'ratio', '9:16');
  5391. $resolution = getProp($data, 'resolution', '2k');
  5392. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5393. $imageNum = (int)getProp($data, 'image_num', 1);
  5394. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5395. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5396. // 参数验证
  5397. $resolution = strtolower($resolution);
  5398. if (!isset($sizeMap[$resolution])) {
  5399. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5400. }
  5401. if (!isset($sizeMap[$resolution][$ratio])) {
  5402. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5403. }
  5404. // 根据 ratio 和 resolution 确定宽高
  5405. $width = $sizeMap[$resolution][$ratio]['width'];
  5406. $height = $sizeMap[$resolution][$ratio]['height'];
  5407. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5408. if (is_json($ref_img_urls)) {
  5409. $ref_img_urls = json_decode($ref_img_urls, true);
  5410. }else {
  5411. $ref_img_urls = explode(',', $ref_img_urls);
  5412. }
  5413. }
  5414. // 处理图片模型
  5415. $model = getProp($data, 'model');
  5416. if (!$model) {
  5417. // 用户没有输入,从episode表获取
  5418. if ($episode_id) {
  5419. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5420. $model = getProp($episode, 'image_model');
  5421. }
  5422. if (!$model) {
  5423. // episode表也没有,使用默认值
  5424. $model = 'doubao-seedream-5-0-lite-260128';
  5425. }
  5426. }
  5427. // 验证模型是否在可用模型表中
  5428. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5429. // $model = 'doubao-seedream-5-0-lite-260128';
  5430. Utils::throwError('20003:该模型已不可用,请更换!');
  5431. }
  5432. // 保存到episode表
  5433. if ($episode_id) {
  5434. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5435. 'image_model' => $model,
  5436. 'updated_at' => date('Y-m-d H:i:s')
  5437. ]);
  5438. }
  5439. // 参数验证
  5440. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5441. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5442. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5443. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5444. try {
  5445. // 创建图片生成任务
  5446. $params = [
  5447. 'prompt' => $prompt,
  5448. 'model' => $model,
  5449. 'ref_img_urls' => '',
  5450. 'width' => $width,
  5451. 'height' => $height,
  5452. 'image_num' => $imageNum
  5453. ];
  5454. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5455. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5456. $task_id = $task->id;
  5457. if (!$task_id) {
  5458. Utils::throwError('20003:创建图片生成任务失败');
  5459. }
  5460. // 创建任务中心记录并关联图片任务ID
  5461. $taskCenter = $this->taskCenterService->createTask('image', [
  5462. 'title' => '文生图',
  5463. 'ref_task_id' => $task_id,
  5464. // 'prompt' => $prompt,
  5465. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5466. ]);
  5467. $taskCenterId = $taskCenter->id;
  5468. // 组装本次任务信息(用于init消息,类似generateVideo)
  5469. $taskInfo = [
  5470. 'task_id' => $task_id,
  5471. 'status' => getProp($task, 'status', 'processing'),
  5472. 'model' => $model,
  5473. 'ratio' => $ratio,
  5474. 'resolution' => $resolution,
  5475. 'image_num' => $imageNum,
  5476. ];
  5477. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5478. if (is_callable($onTaskCreated)) {
  5479. $onTaskCreated($taskCenterId, $taskInfo);
  5480. }
  5481. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5482. $model = getProp($task, 'model');
  5483. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5484. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5485. $isSyncModel = $isVolcModel || $isGptModel;
  5486. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5487. $start_time = time();
  5488. $timeout = 900; // 15分钟
  5489. $img_url = '';
  5490. $img_urls = [];
  5491. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5492. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5493. while (time() - $start_time < $timeout) {
  5494. sleep(3);
  5495. // 每分钟发送一次队列状态消息(仅流式模式)
  5496. if (is_callable($onPoll)) {
  5497. $currentTime = time();
  5498. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5499. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5500. $lastQueueMessageTime = $currentTime;
  5501. }
  5502. }
  5503. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5504. if ($isSyncModel) {
  5505. // 刷新任务状态
  5506. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5507. if ($task->status === 'success' && $task->result_url) {
  5508. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5509. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5510. if (!empty($resultUrls)) {
  5511. $img_urls = $resultUrls;
  5512. $img_url = $resultUrls[0];
  5513. } else {
  5514. $img_url = (string)$task->result_url;
  5515. }
  5516. break;
  5517. } elseif ($task->status === 'failed') {
  5518. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5519. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5520. }
  5521. // // 如果还在处理中,提示用户稍后查看
  5522. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5523. }else {
  5524. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5525. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5526. if ($statusInfo['status'] === 'success') {
  5527. $task->updateStatus('success', [
  5528. 'result_url' => $statusInfo['result_url'],
  5529. 'result_json' => $statusInfo['result_json'] ?? []
  5530. ]);
  5531. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5532. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5533. if (!empty($resultUrls)) {
  5534. $img_urls = $resultUrls;
  5535. $img_url = $resultUrls[0];
  5536. } else {
  5537. $img_url = (string)$statusInfo['result_url'];
  5538. }
  5539. break;
  5540. } elseif ($statusInfo['status'] === 'failed') {
  5541. $task->updateStatus('failed', [
  5542. 'error_message' => $statusInfo['error_message'],
  5543. 'result_json' => $statusInfo['result_json'] ?? []
  5544. ]);
  5545. dLog('anime')->error('图片生成失败,', [
  5546. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5547. ]);
  5548. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5549. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5550. }
  5551. }
  5552. }
  5553. if (empty($img_url)) {
  5554. Utils::throwError('20003:图片生成超时,请稍后重试');
  5555. }
  5556. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5557. if (count($img_urls) > 1) {
  5558. return [
  5559. 'img_url' => $img_url,
  5560. 'image_urls' => $img_urls,
  5561. 'task_id' => $taskCenterId,
  5562. ];
  5563. }
  5564. return [
  5565. 'img_url' => $img_url,
  5566. 'task_id' => $taskCenterId,
  5567. ];
  5568. } catch (\Exception $e) {
  5569. dLog('anime')->error('更新角色或场景失败', [
  5570. 'error' => $e->getMessage()
  5571. ]);
  5572. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5573. Utils::throwError('20003:' . $e->getMessage());
  5574. }
  5575. }
  5576. /**
  5577. * 使用文生文模型解析分镜内容
  5578. */
  5579. private function parseSegmentContentWithAI($segment_content) {
  5580. try {
  5581. // 使用DeepSeek服务的公开方法解析分镜内容
  5582. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5583. } catch (\Exception $e) {
  5584. // 如果AI解析失败,记录日志并返回原内容
  5585. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5586. return $segment_content;
  5587. }
  5588. }
  5589. /**
  5590. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5591. *
  5592. * @param int $episode_id 分集ID
  5593. * @param int $anime_id 动漫ID
  5594. * @param array $roles 分集角色数组(引用传递)
  5595. * @param array $scenes 分集场景数组(引用传递)
  5596. * @param array $episode 分集数据
  5597. */
  5598. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5599. // 获取全局动漫的角色和场景数据
  5600. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5601. if (!$anime) return;
  5602. $art_style_type = getProp($anime, 'art_style_type');
  5603. $character_prefix = '';
  5604. $scene_prefix = '';
  5605. if ($art_style_type) {
  5606. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5607. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5608. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5609. }
  5610. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5611. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5612. $roles_updated = false;
  5613. $scenes_updated = false;
  5614. // 处理角色
  5615. foreach ($roles as &$role) {
  5616. $role_name = getProp($role, 'role');
  5617. $role_description = getProp($role, 'description');
  5618. $role_pic_prompt = getProp($role, 'pic_prompt');
  5619. $role_url = getProp($role, 'url');
  5620. $role_task_id = getProp($role, 'task_id');
  5621. // 如果已有URL或已有任务ID,跳过
  5622. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5623. continue;
  5624. }
  5625. $url_inherited = false;
  5626. // 尝试从全局数据中继承
  5627. foreach ($global_roles as $global_role) {
  5628. $global_role_name = getProp($global_role, 'role');
  5629. $global_role_description = getProp($global_role, 'description');
  5630. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5631. $global_role_url = getProp($global_role, 'url');
  5632. $global_role_task_id = getProp($global_role, 'task_id');
  5633. $global_role_task_status = getProp($global_role, 'task_status');
  5634. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5635. if ($role_name === $global_role_name
  5636. && $role_description === $global_role_description
  5637. && $role_pic_prompt === $global_role_pic_prompt
  5638. && !empty($global_role_url)) {
  5639. // 继承 task_id、task_status 和 url
  5640. $role['task_id'] = $global_role_task_id;
  5641. $role['task_status'] = $global_role_task_status;
  5642. $role['url'] = $global_role_url;
  5643. $roles_updated = true;
  5644. $url_inherited = true;
  5645. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5646. break;
  5647. }
  5648. }
  5649. // 如果无法继承且没有任务ID,创建新任务
  5650. if (!$url_inherited && empty($role_task_id)) {
  5651. try {
  5652. $art_style = getProp($episode, 'art_style');
  5653. // 优先使用 pic_prompt,如果没有则使用 description
  5654. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5655. // if ($art_style) {
  5656. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5657. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5658. // }
  5659. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5660. $params = [
  5661. 'prompt' => $description,
  5662. 'ref_img_urls' => []
  5663. ];
  5664. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5665. $task_id = $task->id;
  5666. if ($task_id) {
  5667. $role['task_id'] = $task_id;
  5668. $role['task_status'] = 'processing';
  5669. $roles_updated = true;
  5670. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5671. }
  5672. } catch (\Exception $e) {
  5673. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5674. }
  5675. }
  5676. }
  5677. // 处理场景
  5678. foreach ($scenes as &$scene) {
  5679. $scene_name = getProp($scene, 'scene');
  5680. $scene_description = getProp($scene, 'description');
  5681. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5682. $scene_url = getProp($scene, 'url');
  5683. $scene_task_id = getProp($scene, 'task_id');
  5684. // 如果已有URL或已有任务ID,跳过
  5685. if (!empty($scene_url) || !empty($scene_task_id)) {
  5686. continue;
  5687. }
  5688. $url_inherited = false;
  5689. // 尝试从全局数据中继承
  5690. foreach ($global_scenes as $global_scene) {
  5691. $global_scene_name = getProp($global_scene, 'scene');
  5692. $global_scene_description = getProp($global_scene, 'description');
  5693. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5694. $global_scene_url = getProp($global_scene, 'url');
  5695. $global_scene_task_id = getProp($global_scene, 'task_id');
  5696. $global_scene_task_status = getProp($global_scene, 'task_status');
  5697. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5698. if ($scene_name === $global_scene_name
  5699. && $scene_description === $global_scene_description
  5700. && $scene_pic_prompt === $global_scene_pic_prompt
  5701. && !empty($global_scene_url)) {
  5702. // 继承 task_id、task_status 和 url
  5703. $scene['task_id'] = $global_scene_task_id;
  5704. $scene['task_status'] = $global_scene_task_status;
  5705. $scene['url'] = $global_scene_url;
  5706. $scenes_updated = true;
  5707. $url_inherited = true;
  5708. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5709. break;
  5710. }
  5711. }
  5712. // 如果无法继承且没有任务ID,创建新任务
  5713. if (!$url_inherited && empty($scene_task_id)) {
  5714. try {
  5715. $art_style = getProp($episode, 'art_style');
  5716. // 优先使用 pic_prompt,如果没有则使用 description
  5717. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5718. // if ($art_style) {
  5719. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5720. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5721. // }
  5722. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5723. $params = [
  5724. 'prompt' => $description,
  5725. 'ref_img_urls' => []
  5726. ];
  5727. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5728. $task_id = $task->id;
  5729. if ($task_id) {
  5730. $scene['task_id'] = $task_id;
  5731. $scene['task_status'] = 'processing';
  5732. $scenes_updated = true;
  5733. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5734. }
  5735. } catch (\Exception $e) {
  5736. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5737. }
  5738. }
  5739. }
  5740. // 如果有更新,保存到数据库
  5741. if ($roles_updated || $scenes_updated) {
  5742. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5743. if ($roles_updated) {
  5744. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5745. }
  5746. if ($scenes_updated) {
  5747. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5748. }
  5749. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5750. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5751. }
  5752. }
  5753. /**
  5754. * 根据图片URL使用AI反推图片提示词
  5755. *
  5756. * @param string $img_url 图片URL
  5757. * @return string 反推的提示词
  5758. */
  5759. private function generateImagePromptFromUrl($img_url) {
  5760. try {
  5761. // 获取默认模型
  5762. $model = 'doubao-seed-2-0-mini-260215';
  5763. // 构建messages参数
  5764. $messages = [
  5765. [
  5766. 'role' => 'user',
  5767. 'content' => [
  5768. [
  5769. 'type' => 'text',
  5770. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5771. ],
  5772. [
  5773. 'type' => 'image_url',
  5774. 'image_url' => [
  5775. 'url' => $img_url
  5776. ]
  5777. ]
  5778. ]
  5779. ]
  5780. ];
  5781. // 构建请求参数
  5782. $params = [
  5783. 'model' => $model,
  5784. 'messages' => $messages,
  5785. 'stream' => false,
  5786. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5787. ];
  5788. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5789. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5790. // 仅记录 token 使用明细(不扣积分)
  5791. $uid = 0;
  5792. try {
  5793. $uid = (int)Site::getUid();
  5794. } catch (\Throwable $e) {
  5795. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5796. }
  5797. $this->pointsService->recordTokenOnlyDetail(
  5798. $uid,
  5799. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5800. [
  5801. 'model' => $model,
  5802. 'img_url' => $img_url,
  5803. 'source' => 'generateImagePromptFromUrl',
  5804. ],
  5805. 'chat',
  5806. $model,
  5807. ''
  5808. );
  5809. // 返回生成的内容
  5810. return getProp($result, 'fullContent', '图片描述生成失败');
  5811. } catch (\Exception $e) {
  5812. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5813. 'img_url' => $img_url
  5814. ]);
  5815. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5816. 'error' => $e->getMessage(),
  5817. 'img_url' => $img_url
  5818. ]);
  5819. return '图片描述生成失败: ' . $e->getMessage();
  5820. }
  5821. }
  5822. /**
  5823. * 音频试听接口
  5824. * 创建音频任务并轮询获取结果
  5825. *
  5826. * @param array $data 参数数组
  5827. * @return array 返回音频URL或错误信息
  5828. */
  5829. public function previewAudio($data) {
  5830. $dialogue = getProp($data, 'dialogue');
  5831. // 必填参数验证
  5832. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5833. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5834. $voice_type = getProp($data, 'voice_type');
  5835. $voice_name = getProp($data, 'voice_name');
  5836. $voice_actor = getProp($data, 'voice_actor');
  5837. $emotion_type = getProp($data, 'emotion_type');
  5838. $gender = getProp($data, 'gender', 0);
  5839. $emotion = getProp($data, 'emotion');
  5840. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5841. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5842. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5843. $pitch = getProp($data, 'pitch', 0);
  5844. try {
  5845. $now = date('Y-m-d H:i:s');
  5846. // 构建生成参数
  5847. $generate_json = json_encode([
  5848. 'text' => $dialogue,
  5849. 'role' => $voice_actor,
  5850. 'voice_type' => $voice_type,
  5851. 'voice_name' => $voice_name,
  5852. 'emotion' => $emotion,
  5853. 'emotion_type' => $emotion_type,
  5854. 'gender' => $gender,
  5855. 'speed_ratio' => $speed_ratio,
  5856. 'loudness_ratio' => $loudness_ratio,
  5857. 'emotion_scale' => $emotion_scale,
  5858. 'pitch' => $pitch,
  5859. ], 256);
  5860. // 请求远程服务器执行生成
  5861. $client = new Client(['timeout' => 600, 'verify' => false]);
  5862. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5863. $response = $result->getBody()->getContents();
  5864. $response_arr = json_decode($response, true);
  5865. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5866. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5867. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5868. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5869. }
  5870. $arr = $response_arr['data'];
  5871. $subtitle_info = $arr['subtitle_info'];
  5872. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5873. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5874. return [
  5875. 'audio_url' => $arr['url'],
  5876. 'subtitle_info' => $subtitle_info,
  5877. 'audio_duration' => round($audio_duration, 2)
  5878. ];
  5879. } catch (\Exception $e) {
  5880. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5881. Utils::throwError('20003:' . $e->getMessage());
  5882. }
  5883. }
  5884. /**
  5885. * 获取角色库列表(支持文件夹递归查询)
  5886. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5887. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5888. */
  5889. public function globalProducts($data) {
  5890. $uid = Site::getUid();
  5891. $cpid = Site::getCpid();
  5892. $role = Site::getRole();
  5893. $id = getProp($data, 'id', 0);
  5894. $parent_id = getProp($data, 'parent_id', 0);
  5895. $product_name = getProp($data, 'product_name');
  5896. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5897. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5898. if (!$product) {
  5899. Utils::throwError('20003:请选择产品类型');
  5900. }
  5901. // 根据角色和is_public参数确定查询范围
  5902. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5903. // user角色:根据is_public参数筛选
  5904. $query_user_ids = [];
  5905. if ($role === 'admin') {
  5906. // admin获取所有个人库和公共库
  5907. $query_user_ids = [$uid, 0];
  5908. } else {
  5909. // user角色根据is_public参数筛选
  5910. if ($is_public == 2) {
  5911. // 个人库+公共库
  5912. $query_user_ids = [$uid, 0];
  5913. } elseif ($is_public == 0) {
  5914. // 仅个人库
  5915. $query_user_ids = [$uid];
  5916. } elseif ($is_public == 1) {
  5917. // 仅公共库
  5918. $query_user_ids = [0];
  5919. }
  5920. }
  5921. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5922. if ($id || $product_name) {
  5923. $query = DB::table('mp_products')
  5924. ->where('cpid', $cpid)
  5925. ->whereIn('user_id', $query_user_ids)
  5926. ->where('is_deleted', 0);
  5927. // 如果指定了 id,按 id 精确查询
  5928. if ($id) {
  5929. $query->where('id', $id);
  5930. }
  5931. // 如果指定了 product_name,按名称模糊查询
  5932. if ($product_name) {
  5933. $query->where('product_name', 'like', "%{$product_name}%");
  5934. }
  5935. // 如果指定了 product,添加筛选条件
  5936. if ($product) {
  5937. $query->where('product', $product);
  5938. }
  5939. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5940. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5941. ->get()
  5942. ->map(function($value) {
  5943. $value = (array)$value;
  5944. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5945. $value['type'] = (int)$value['type'];
  5946. $value['parent_id'] = (int)$value['parent_id'];
  5947. $value['level'] = (int)$value['level'];
  5948. $value['product'] = (int)($value['product'] ?? 1);
  5949. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5950. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5951. unset($value['user_id']);
  5952. return $value;
  5953. })
  5954. ->toArray();
  5955. return $result;
  5956. }
  5957. // 递归获取所有子目录和角色
  5958. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5959. }
  5960. /**
  5961. * 递归获取指定目录下的所有子目录和角色
  5962. * @param int $cpid 公司ID
  5963. * @param int $parent_id 父目录ID
  5964. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5965. * @param array $query_user_ids 用户ID数组(支持多个)
  5966. * @param int $current_uid 当前用户ID(用于排序)
  5967. * @return array
  5968. */
  5969. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5970. // 查询当前层级的所有项(文件夹和角色)
  5971. $query = DB::table('mp_products')
  5972. ->where('cpid', $cpid)
  5973. ->where('is_deleted', 0)
  5974. ->where('parent_id', $parent_id);
  5975. // 添加用户ID验证(支持多个user_id)
  5976. if (!empty($query_user_ids)) {
  5977. $query->whereIn('user_id', $query_user_ids);
  5978. }
  5979. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5980. if ($product) {
  5981. $query->where('product', $product);
  5982. }
  5983. // 排序规则:
  5984. // 1. 文件夹在前(type DESC)
  5985. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5986. // 3. 其他排序规则
  5987. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5988. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5989. ->get();
  5990. $result = [];
  5991. foreach ($items as $item) {
  5992. $itemArray = [
  5993. 'id' => $item->id,
  5994. 'type' => (int)$item->type,
  5995. 'parent_id' => (int)$item->parent_id,
  5996. 'level' => (int)$item->level,
  5997. 'product_name' => $item->product_name,
  5998. 'url' => $item->url,
  5999. 'pic_prompt' => $item->pic_prompt ?? '',
  6000. 'three_view_image_url' => $item->three_view_image_url,
  6001. 'product' => (int)($item->product ?? 1),
  6002. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6003. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6004. ];
  6005. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6006. // 如果是文件夹,递归获取其子项
  6007. if ($item->type == 2) {
  6008. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6009. if (!empty($children)) {
  6010. $itemArray['children'] = $children;
  6011. }
  6012. }
  6013. $result[] = $itemArray;
  6014. }
  6015. return $result;
  6016. }
  6017. /**
  6018. * 创建文件夹
  6019. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6020. * @return int 返回新建文件夹ID
  6021. */
  6022. public function createFolder($data) {
  6023. $uid = Site::getUid();
  6024. $cpid = Site::getCpid();
  6025. $role = Site::getRole();
  6026. $parent_id = getProp($data, 'parent_id', 0);
  6027. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6028. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6029. // 如果是公共库操作,需要admin权限
  6030. if ($is_public && $role !== 'admin') {
  6031. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6032. }
  6033. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6034. $store_uid = $is_public ? 0 : $uid;
  6035. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6036. $product = getProp($data, 'product');
  6037. if (!in_array($product, [1, 2, 3])) {
  6038. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6039. }
  6040. // 验证父文件夹
  6041. $parent_level = 0;
  6042. if ($parent_id > 0) {
  6043. $parent = DB::table('mp_products')
  6044. ->where('id', $parent_id)
  6045. ->where('cpid', $cpid)
  6046. ->where('user_id', $store_uid)
  6047. ->where('type', 2)
  6048. ->where('is_deleted', 0)
  6049. ->first();
  6050. if (!$parent) {
  6051. Utils::throwError('20003:父文件夹不存在');
  6052. }
  6053. // 检查父文件夹的 product 类型是否一致
  6054. if ($parent->product != $product) {
  6055. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6056. }
  6057. $parent_level = $parent->level;
  6058. // 检查层级限制(最多3层)
  6059. if ($parent_level >= 3) {
  6060. Utils::throwError('20003:文件夹层级不能超过3层');
  6061. }
  6062. }
  6063. // 检查当前目录下是否已存在空白文件夹
  6064. $empty_folder_exists = DB::table('mp_products')
  6065. ->where('parent_id', $parent_id)
  6066. ->where('cpid', $cpid)
  6067. ->where('user_id', $store_uid)
  6068. ->where('type', 2)
  6069. ->where('product', $product)
  6070. ->where('product_name', '新建文件夹')
  6071. ->where('is_deleted', 0)
  6072. ->exists();
  6073. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6074. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6075. }
  6076. // 创建文件夹
  6077. $folder_id = DB::table('mp_products')->insertGetId([
  6078. 'user_id' => $store_uid,
  6079. 'cpid' => $cpid,
  6080. 'type' => 2,
  6081. 'parent_id' => $parent_id,
  6082. 'level' => $parent_level + 1,
  6083. 'product_name' => $folder_name,
  6084. 'product' => $product,
  6085. 'sort_order' => time(), // 使用时间戳作为排序权重
  6086. 'is_deleted' => 0,
  6087. 'created_at' => date('Y-m-d H:i:s'),
  6088. 'updated_at' => date('Y-m-d H:i:s')
  6089. ]);
  6090. return [
  6091. 'id' => $folder_id,
  6092. 'type' => 2,
  6093. 'parent_id' => $parent_id,
  6094. 'level' => $parent_level + 1,
  6095. 'product_name' => $folder_name,
  6096. 'product' => $product,
  6097. ];
  6098. }
  6099. /**
  6100. * 重命名文件夹或角色
  6101. * @param array $data 包含 id、product_name(新名称)
  6102. * @return bool
  6103. */
  6104. public function renameFolder($data) {
  6105. $uid = Site::getUid();
  6106. $cpid = Site::getCpid();
  6107. $role = Site::getRole();
  6108. $id = getProp($data, 'id');
  6109. $new_name = getProp($data, 'product_name');
  6110. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6111. if (!$id || !$new_name) {
  6112. Utils::throwError('20003:参数不完整');
  6113. }
  6114. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6115. $query_uid = $is_public ? 0 : $uid;
  6116. // 如果是公共库操作,需要admin权限
  6117. if ($is_public && $role !== 'admin') {
  6118. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6119. }
  6120. // 检查是否存在
  6121. $item = DB::table('mp_products')
  6122. ->where('id', $id)
  6123. ->where('cpid', $cpid)
  6124. ->where('user_id', $query_uid)
  6125. ->where('is_deleted', 0)
  6126. ->first();
  6127. if (!$item) {
  6128. Utils::throwError('20003:项目不存在');
  6129. }
  6130. return DB::table('mp_products')
  6131. ->where('id', $id)
  6132. ->where('cpid', $cpid)
  6133. ->where('user_id', $query_uid)
  6134. ->update([
  6135. 'product_name' => $new_name,
  6136. 'updated_at' => date('Y-m-d H:i:s')
  6137. ]);
  6138. }
  6139. /**
  6140. * 移动角色或文件夹到指定文件夹
  6141. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6142. * @return bool
  6143. */
  6144. public function moveProductOrFolder($data) {
  6145. $uid = Site::getUid();
  6146. $cpid = Site::getCpid();
  6147. $role = Site::getRole();
  6148. $id = getProp($data, 'id');
  6149. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6150. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6151. if (!$id) {
  6152. Utils::throwError('20003:请选择要移动的项目');
  6153. }
  6154. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6155. $query_uid = $is_public ? 0 : $uid;
  6156. // 如果是公共库操作,需要admin权限
  6157. if ($is_public && $role !== 'admin') {
  6158. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6159. }
  6160. // 检查要移动的项目
  6161. $item = DB::table('mp_products')
  6162. ->where('id', $id)
  6163. ->where('cpid', $cpid)
  6164. ->where('user_id', $query_uid)
  6165. ->where('is_deleted', 0)
  6166. ->first();
  6167. if (!$item) {
  6168. Utils::throwError('20003:项目不存在');
  6169. }
  6170. // 验证目标文件夹
  6171. $target_level = 0;
  6172. $target_product = $item->product; // 默认使用当前项目的 product
  6173. if ($target_parent_id > 0) {
  6174. $target_parent = DB::table('mp_products')
  6175. ->where('id', $target_parent_id)
  6176. ->where('cpid', $cpid)
  6177. ->where('user_id', $query_uid)
  6178. ->where('type', 2)
  6179. ->where('is_deleted', 0)
  6180. ->first();
  6181. if (!$target_parent) {
  6182. Utils::throwError('20003:目标文件夹不存在');
  6183. }
  6184. // 检查 product 类型是否一致
  6185. if ($target_parent->product != $item->product) {
  6186. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6187. }
  6188. $target_level = $target_parent->level;
  6189. $target_product = $target_parent->product;
  6190. // 如果移动的是文件夹,需要检查层级
  6191. if ($item->type == 2) {
  6192. // 计算移动后的最大层级
  6193. $max_child_level = $this->getMaxChildLevel($id);
  6194. $depth = $max_child_level - $item->level;
  6195. if ($target_level + 1 + $depth > 3) {
  6196. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6197. }
  6198. // 不能移动到自己或自己的子文件夹下
  6199. if ($this->isDescendant($target_parent_id, $id)) {
  6200. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6201. }
  6202. }
  6203. }
  6204. // 更新父文件夹和层级
  6205. $new_level = $target_level + 1;
  6206. DB::table('mp_products')
  6207. ->where('id', $id)
  6208. ->update([
  6209. 'parent_id' => $target_parent_id,
  6210. 'level' => $new_level,
  6211. 'updated_at' => date('Y-m-d H:i:s')
  6212. ]);
  6213. // 如果是文件夹,需要递归更新所有子项的层级
  6214. if ($item->type == 2) {
  6215. $this->updateChildrenLevel($id, $new_level);
  6216. }
  6217. return true;
  6218. }
  6219. /**
  6220. * 获取文件夹下最大子层级
  6221. * @param int $folder_id
  6222. * @return int
  6223. */
  6224. private function getMaxChildLevel($folder_id) {
  6225. $max_level = DB::table('mp_products')
  6226. ->where('parent_id', $folder_id)
  6227. ->where('is_deleted', 0)
  6228. ->max('level');
  6229. if (!$max_level) {
  6230. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6231. }
  6232. // 递归查找子文件夹
  6233. $children = DB::table('mp_products')
  6234. ->where('parent_id', $folder_id)
  6235. ->where('type', 2)
  6236. ->where('is_deleted', 0)
  6237. ->pluck('id');
  6238. foreach ($children as $child_id) {
  6239. $child_max = $this->getMaxChildLevel($child_id);
  6240. if ($child_max > $max_level) {
  6241. $max_level = $child_max;
  6242. }
  6243. }
  6244. return $max_level;
  6245. }
  6246. /**
  6247. * 检查 target_id 是否是 folder_id 的后代
  6248. * @param int $target_id
  6249. * @param int $folder_id
  6250. * @return bool
  6251. */
  6252. private function isDescendant($target_id, $folder_id) {
  6253. if ($target_id == $folder_id) {
  6254. return true;
  6255. }
  6256. $parent = DB::table('mp_products')
  6257. ->where('id', $target_id)
  6258. ->where('is_deleted', 0)
  6259. ->first();
  6260. if (!$parent || $parent->parent_id == 0) {
  6261. return false;
  6262. }
  6263. return $this->isDescendant($parent->parent_id, $folder_id);
  6264. }
  6265. /**
  6266. * 递归更新子项层级
  6267. * @param int $parent_id
  6268. * @param int $parent_level
  6269. */
  6270. private function updateChildrenLevel($parent_id, $parent_level) {
  6271. $children = DB::table('mp_products')
  6272. ->where('parent_id', $parent_id)
  6273. ->where('is_deleted', 0)
  6274. ->get();
  6275. foreach ($children as $child) {
  6276. $new_level = $parent_level + 1;
  6277. DB::table('mp_products')
  6278. ->where('id', $child->id)
  6279. ->update([
  6280. 'level' => $new_level,
  6281. 'updated_at' => date('Y-m-d H:i:s')
  6282. ]);
  6283. // 如果是文件夹,继续递归
  6284. if ($child->type == 2) {
  6285. $this->updateChildrenLevel($child->id, $new_level);
  6286. }
  6287. }
  6288. }
  6289. /**
  6290. * 获取文件夹路径(面包屑导航)
  6291. * @param array $data 包含 folder_id
  6292. * @return array 返回路径数组
  6293. */
  6294. public function getFolderPath($data) {
  6295. $uid = Site::getUid();
  6296. $cpid = Site::getCpid();
  6297. $folder_id = getProp($data, 'id', 0);
  6298. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6299. if ($folder_id == 0) {
  6300. return [
  6301. ['id' => 0, 'name' => '根目录']
  6302. ];
  6303. }
  6304. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6305. $query_uid = $is_public ? 0 : $uid;
  6306. $path = [];
  6307. $current_id = $folder_id;
  6308. while ($current_id > 0) {
  6309. $folder = DB::table('mp_products')
  6310. ->where('id', $current_id)
  6311. ->where('cpid', $cpid)
  6312. ->where('user_id', $query_uid)
  6313. ->where('type', 2)
  6314. ->where('is_deleted', 0)
  6315. ->first();
  6316. if (!$folder) {
  6317. break;
  6318. }
  6319. array_unshift($path, [
  6320. 'id' => $folder->id,
  6321. 'name' => $folder->product_name
  6322. ]);
  6323. $current_id = $folder->parent_id;
  6324. }
  6325. // 添加根目录
  6326. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6327. return $path;
  6328. }
  6329. public function createProduct($data) {
  6330. $uid = Site::getUid();
  6331. $cpid = Site::getCpid();
  6332. $role = Site::getRole();
  6333. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6334. // 如果是公共库操作,需要admin权限
  6335. if ($is_public && $role !== 'admin') {
  6336. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6337. }
  6338. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6339. $store_uid = $is_public ? 0 : $uid;
  6340. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6341. $script_id = (int)getProp($data, 'script_id', 0);
  6342. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6343. if ($script_id && empty($episode_numbers)) {
  6344. Utils::throwError('20003:剧集序号不能为空');
  6345. }
  6346. if (!$script_id && !empty($episode_numbers)) {
  6347. Utils::throwError('20003:请提供剧本ID');
  6348. }
  6349. $product_name = trim(getProp($data, 'product_name'));
  6350. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6351. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6352. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6353. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6354. $url = trim(getProp($data, 'url'));
  6355. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6356. $versions = getProp($data, 'versions');
  6357. // 检查是否是正确的图片格式
  6358. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6359. $urlPath = parse_url($url, PHP_URL_PATH);
  6360. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6361. if (!in_array($extension, $allowedExtensions)) {
  6362. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6363. }
  6364. // 选填三视图图片地址,格式校验与 url 一致
  6365. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6366. if ($three_view_image_url) {
  6367. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6368. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6369. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6370. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6371. }
  6372. }
  6373. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6374. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6375. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6376. $product = getProp($data, 'product');
  6377. if (!in_array($product, [1, 2, 3])) {
  6378. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6379. }
  6380. // 获取父文件夹ID和层级
  6381. $parent_id = getProp($data, 'parent_id', 0);
  6382. $parent_level = 0;
  6383. if ($parent_id > 0) {
  6384. $parent = DB::table('mp_products')
  6385. ->where('id', $parent_id)
  6386. ->where('cpid', $cpid)
  6387. ->where('user_id', $store_uid)
  6388. ->where('type', 2)
  6389. ->where('is_deleted', 0)
  6390. ->first();
  6391. if (!$parent) {
  6392. Utils::throwError('20003:父文件夹不存在');
  6393. }
  6394. $parent_level = $parent->level;
  6395. }
  6396. // 创建资产并保存剧本资产关联关系(同一事务)
  6397. DB::beginTransaction();
  6398. try {
  6399. $id = DB::table('mp_products')->insertGetId([
  6400. 'user_id' => $store_uid,
  6401. 'cpid' => $cpid,
  6402. 'type' => 1, // 1=角色图片
  6403. 'parent_id' => $parent_id,
  6404. 'level' => $parent_level + 1,
  6405. 'product_name' => $product_name,
  6406. 'url' => $url,
  6407. 'three_view_image_url' => $three_view_image_url,
  6408. 'pic_prompt' => $pic_prompt,
  6409. 'product' => $product,
  6410. 'versions' => json_encode($versions, 256),
  6411. 'sort_order' => time(), // 使用时间戳作为排序权重
  6412. 'created_at' => date('Y-m-d H:i:s'),
  6413. 'updated_at' => date('Y-m-d H:i:s')
  6414. ]);
  6415. if (!$id) Utils::throwError('20003:创建失败');
  6416. // 保存剧本资产关联关系
  6417. if ($script_id) {
  6418. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6419. }
  6420. DB::commit();
  6421. } catch (\Exception $e) {
  6422. DB::rollback();
  6423. throw $e;
  6424. }
  6425. return [
  6426. 'id' => $id,
  6427. 'type' => 1,
  6428. 'parent_id' => $parent_id,
  6429. 'level' => $parent_level + 1,
  6430. 'product_name' => $product_name,
  6431. 'url' => $url,
  6432. 'three_view_image_url' => $three_view_image_url,
  6433. 'pic_prompt' => $pic_prompt,
  6434. 'product' => $product,
  6435. 'versions' => $versions
  6436. ];
  6437. }
  6438. public function editProduct($data) {
  6439. $uid = Site::getUid();
  6440. $cpid = Site::getCpid();
  6441. $role = Site::getRole();
  6442. $id = getProp($data, 'id');
  6443. if (!$id) Utils::throwError('20003:ID不能为空');
  6444. $versions = getProp($data, 'versions');
  6445. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6446. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6447. $script_id = (int)getProp($data, 'script_id', 0);
  6448. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6449. if ($script_id && empty($episode_numbers)) {
  6450. Utils::throwError('20003:剧集序号不能为空');
  6451. }
  6452. if (!$script_id && !empty($episode_numbers)) {
  6453. Utils::throwError('20003:请提供剧本ID');
  6454. }
  6455. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6456. $query_uid = $is_public ? 0 : $uid;
  6457. // 如果是公共库操作,需要admin权限
  6458. if ($is_public && $role !== 'admin') {
  6459. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6460. }
  6461. // 检查是否存在且属于当前用户或公共库
  6462. $role = DB::table('mp_products')
  6463. ->where('id', $id)
  6464. ->where('cpid', $cpid)
  6465. ->where('user_id', $query_uid)
  6466. ->where('type', 1)->first();
  6467. if (!$role) Utils::throwError('20003:记录不存在');
  6468. $updateData = [];
  6469. // $needVersionRecord = false; // 是否需要记录版本
  6470. // 名称
  6471. $product_name = trim(getProp($data, 'product_name'));
  6472. if ($product_name) {
  6473. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6474. $updateData['product_name'] = $product_name;
  6475. }
  6476. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6477. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6478. // 图片地址
  6479. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6480. $url = trim(getProp($data, 'url'));
  6481. if ($url) {
  6482. // 检查是否是正确的图片格式
  6483. $urlPath = parse_url($url, PHP_URL_PATH);
  6484. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6485. if (!in_array($extension, $allowedExtensions)) {
  6486. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6487. }
  6488. // // 如果 url 有变更,记录版本
  6489. // if ($url !== $role->url) {
  6490. // $needVersionRecord = true;
  6491. // }
  6492. $updateData['url'] = $url;
  6493. }
  6494. // 三视图图片地址(选填),格式校验与 url 一致
  6495. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6496. if ($three_view_image_url) {
  6497. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6498. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6499. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6500. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6501. }
  6502. $updateData['three_view_image_url'] = $three_view_image_url;
  6503. }
  6504. // 提示词
  6505. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6506. if ($pic_prompt) {
  6507. // // 如果 pic_prompt 有变更,记录版本
  6508. // if ($pic_prompt !== $role->pic_prompt) {
  6509. // $needVersionRecord = true;
  6510. // }
  6511. $updateData['pic_prompt'] = $pic_prompt;
  6512. }
  6513. if (empty($updateData) && !$script_id) {
  6514. Utils::throwError('20003:没有需要更新的数据');
  6515. }
  6516. // // 如果需要记录版本,将数据添加到 versions 数组
  6517. // if ($needVersionRecord) {
  6518. // // 获取现有的 versions 数据
  6519. // $versions = json_decode($role->versions, true) ?: [];
  6520. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6521. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6522. // if ($isFirstVersion) {
  6523. // $oldVersion = [
  6524. // 'url' => $role->url,
  6525. // 'description' => $role->pic_prompt,
  6526. // ];
  6527. // // 旧版本添加到数组末尾
  6528. // $versions[] = $oldVersion;
  6529. // }
  6530. // // 构建新版本(变更后)
  6531. // $newVersion = [
  6532. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6533. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6534. // ];
  6535. // // 检查新版本是否已存在于历史版本中
  6536. // $existingIndex = -1;
  6537. // foreach ($versions as $index => $version) {
  6538. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6539. // $existingIndex = $index;
  6540. // break;
  6541. // }
  6542. // }
  6543. // if ($existingIndex !== -1) {
  6544. // // 如果已存在,移除旧的位置
  6545. // array_splice($versions, $existingIndex, 1);
  6546. // }
  6547. // // 新版本添加到数组开头(最新的在前)
  6548. // array_unshift($versions, $newVersion);
  6549. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6550. // // if (count($versions) > 10) {
  6551. // // $versions = array_slice($versions, 0, 10);
  6552. // // }
  6553. // $updateData['versions'] = json_encode($versions, 256);
  6554. // }
  6555. if ($versions) {
  6556. $updateData['versions'] = json_encode($versions, 256);
  6557. }
  6558. if (!empty($updateData)) {
  6559. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6560. }
  6561. // 更新资产并保存剧本资产关联关系(同一事务)
  6562. DB::beginTransaction();
  6563. try {
  6564. $updated = true;
  6565. if (!empty($updateData)) {
  6566. $updated = DB::table('mp_products')
  6567. ->where('cpid', $cpid)
  6568. ->where('id', $id)
  6569. ->update($updateData);
  6570. }
  6571. // 保存剧本资产关联关系
  6572. if ($script_id) {
  6573. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6574. }
  6575. DB::commit();
  6576. } catch (\Exception $e) {
  6577. DB::rollback();
  6578. throw $e;
  6579. }
  6580. return $updated;
  6581. }
  6582. /**
  6583. * 保存单一资产与剧本剧集的关联关系
  6584. *
  6585. * @param int $product_id 资产ID
  6586. * @param int $script_id 剧本ID
  6587. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6588. * @return int 新增关联数量
  6589. */
  6590. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6591. $uid = Site::getUid();
  6592. // 验证剧本是否存在
  6593. $script = DB::table('mp_scripts')
  6594. ->where('id', $script_id)
  6595. ->where('is_deleted', 0)
  6596. ->first();
  6597. if (!$script) {
  6598. Utils::throwError('20003:剧本不存在');
  6599. }
  6600. // 验证剧本归属:只能关联自己的剧本
  6601. if ((int)$script->user_id !== (int)$uid) {
  6602. Utils::throwError('20003:只能添加到自己的剧本');
  6603. }
  6604. // 使用 splitContent 拆分剧本内容获取总集数
  6605. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6606. // 解析剧集序号(数组)
  6607. $episodes = [];
  6608. foreach ($episode_numbers as $item) {
  6609. if (is_array($item)) {
  6610. continue;
  6611. }
  6612. $item = trim((string)$item);
  6613. if ($item === '' || !is_numeric($item)) {
  6614. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6615. }
  6616. $episodes[] = (int)$item;
  6617. }
  6618. // 去重并校验序号范围(序号从1开始)
  6619. $episodes = array_values(array_unique($episodes));
  6620. if (empty($episodes)) {
  6621. Utils::throwError('20003:剧集序号不能为空');
  6622. }
  6623. foreach ($episodes as $episode) {
  6624. if ($episode < 1 || $episode > $totalEpisodes) {
  6625. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6626. }
  6627. }
  6628. $now = now();
  6629. // 过滤已存在的关联,避免重复
  6630. $existingEpisodes = DB::table('mp_script_product_mappings')
  6631. ->where('script_id', $script_id)
  6632. ->where('product_id', $product_id)
  6633. ->whereIn('episode_number', $episodes)
  6634. ->pluck('episode_number')
  6635. ->all();
  6636. $mappingRecords = [];
  6637. foreach ($episodes as $episode) {
  6638. if (in_array($episode, $existingEpisodes)) {
  6639. continue;
  6640. }
  6641. $mappingRecords[] = [
  6642. 'script_id' => $script_id,
  6643. 'product_id' => $product_id,
  6644. 'episode_number' => $episode,
  6645. 'created_at' => $now,
  6646. 'updated_at' => $now,
  6647. ];
  6648. }
  6649. $insertedCount = 0;
  6650. if (!empty($mappingRecords)) {
  6651. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6652. }
  6653. return $insertedCount;
  6654. }
  6655. /**
  6656. * 规范化剧集序号参数,统一为数组
  6657. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6658. *
  6659. * @param mixed $episode_number 剧集序号参数
  6660. * @return array
  6661. */
  6662. private function normalizeEpisodeNumbers($episode_number) {
  6663. if (!is_array($episode_number)) {
  6664. $episode_number = explode(',', (string)$episode_number);
  6665. }
  6666. $items = [];
  6667. foreach ($episode_number as $item) {
  6668. if (is_array($item)) {
  6669. continue;
  6670. }
  6671. foreach (explode(',', (string)$item) as $part) {
  6672. $part = trim($part);
  6673. if ($part !== '') {
  6674. $items[] = $part;
  6675. }
  6676. }
  6677. }
  6678. return $items;
  6679. }
  6680. /**
  6681. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6682. *
  6683. * @param object $script 剧本记录
  6684. * @return int 总集数
  6685. */
  6686. private function getScriptTotalEpisodeCount($script) {
  6687. if (empty($script->content)) {
  6688. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6689. }
  6690. $totalEpisodes = count(splitContent($script->content));
  6691. if ($totalEpisodes < 1) {
  6692. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6693. }
  6694. return $totalEpisodes;
  6695. }
  6696. /**
  6697. * 获取剧本总集数
  6698. *
  6699. * @param array $data 包含 script_id(剧本ID)
  6700. * @return array
  6701. */
  6702. public function getScriptTotalEpisodes($data) {
  6703. $script_id = (int)getProp($data, 'script_id', 0);
  6704. if (!$script_id) {
  6705. Utils::throwError('20003:请提供剧本ID');
  6706. }
  6707. // 验证剧本是否存在
  6708. $script = DB::table('mp_scripts')
  6709. ->where('id', $script_id)
  6710. ->where('is_deleted', 0)
  6711. ->first();
  6712. if (!$script) {
  6713. Utils::throwError('20003:剧本不存在');
  6714. }
  6715. return [
  6716. 'script_id' => $script_id,
  6717. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6718. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6719. ];
  6720. }
  6721. /**
  6722. * 获取角色版本历史
  6723. * @param array $data 包含 id(角色ID)
  6724. * @return array 返回版本历史列表
  6725. */
  6726. public function getProductVersions($data) {
  6727. $cpid = Site::getCpid();
  6728. $id = getProp($data, 'id');
  6729. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6730. $role = DB::table('mp_products')
  6731. ->where('id', $id)
  6732. ->where('cpid', $cpid)
  6733. ->where('type', 1)
  6734. ->first();
  6735. if (!$role) Utils::throwError('20003:角色不存在');
  6736. // 获取版本历史
  6737. $versions = json_decode($role->versions, true) ?: [];
  6738. // 添加当前版本作为最新版本
  6739. $currentVersion = [
  6740. 'version' => 0, // 0 表示当前版本
  6741. 'url' => $role->url,
  6742. 'pic_prompt' => $role->pic_prompt,
  6743. 'updated_at' => $role->updated_at,
  6744. 'is_current' => true
  6745. ];
  6746. array_unshift($versions, $currentVersion);
  6747. return $versions;
  6748. }
  6749. /**
  6750. * 恢复到指定版本
  6751. * @param array $data 包含 id(角色ID)、version(版本号)
  6752. * @return bool
  6753. */
  6754. public function restoreProductVersion($data) {
  6755. $uid = Site::getUid();
  6756. $cpid = Site::getCpid();
  6757. $id = getProp($data, 'id');
  6758. $version = getProp($data, 'version');
  6759. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6760. if (!$version) Utils::throwError('20003:版本号不能为空');
  6761. $role = DB::table('mp_products')
  6762. ->where('id', $id)
  6763. ->where('cpid', $cpid)
  6764. ->where('type', 1)
  6765. ->first();
  6766. if (!$role) Utils::throwError('20003:角色不存在');
  6767. // 获取版本历史
  6768. $versions = json_decode($role->versions, true) ?: [];
  6769. // 查找指定版本
  6770. $targetVersion = null;
  6771. foreach ($versions as $v) {
  6772. if ($v['version'] == $version) {
  6773. $targetVersion = $v;
  6774. break;
  6775. }
  6776. }
  6777. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6778. // 先将当前版本保存到历史
  6779. $newVersion = [
  6780. 'version' => count($versions) + 1,
  6781. 'url' => $role->url,
  6782. 'pic_prompt' => $role->pic_prompt,
  6783. 'updated_at' => date('Y-m-d H:i:s'),
  6784. 'updated_by' => $uid
  6785. ];
  6786. array_unshift($versions, $newVersion);
  6787. // 限制版本数量
  6788. if (count($versions) > 10) {
  6789. $versions = array_slice($versions, 0, 10);
  6790. }
  6791. // 恢复到指定版本
  6792. return DB::table('mp_products')
  6793. ->where('id', $id)
  6794. ->where('cpid', $cpid)
  6795. ->update([
  6796. 'url' => $targetVersion['url'],
  6797. 'pic_prompt' => $targetVersion['pic_prompt'],
  6798. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6799. 'updated_at' => date('Y-m-d H:i:s')
  6800. ]);
  6801. }
  6802. public function deleteProduct($data) {
  6803. $uid = Site::getUid();
  6804. $cpid = Site::getCpid();
  6805. $role = Site::getRole();
  6806. $id = getProp($data, 'id');
  6807. if (!$id) Utils::throwError('20003:ID不能为空');
  6808. $ids = explode(',', $id);
  6809. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6810. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6811. $query_uid = $is_public ? 0 : $uid;
  6812. // 如果是公共库操作,需要admin权限
  6813. if ($is_public && $role !== 'admin') {
  6814. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6815. }
  6816. // 检查是否存在且属于当前用户或公共库
  6817. $role = DB::table('mp_products')
  6818. ->whereIn('id', $ids)
  6819. ->where('cpid', $cpid)
  6820. ->where('user_id', $query_uid)
  6821. ->get();
  6822. if (!$role) Utils::throwError('20003:记录不存在');
  6823. return DB::table('mp_products')
  6824. ->where('cpid', $cpid)
  6825. ->where('user_id', $query_uid)
  6826. ->whereIn('id', $ids)
  6827. ->update([
  6828. 'is_deleted' => 1,
  6829. 'updated_at' => date('Y-m-d H:i:s')
  6830. ]);
  6831. }
  6832. public function generateThreeView($data) {
  6833. $uid = Site::getUid();
  6834. $cpid = Site::getCpid();
  6835. $role = Site::getRole();
  6836. $id = getProp($data, 'id');
  6837. if (!$id) Utils::throwError('20003:ID不能为空');
  6838. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6839. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6840. $query_uid = $is_public ? 0 : $uid;
  6841. // 如果是公共库操作,需要admin权限
  6842. if ($is_public && $role !== 'admin') {
  6843. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6844. }
  6845. // 检查是否存在且属于当前用户或公共库
  6846. $product = DB::table('mp_products')
  6847. ->where('id', $id)
  6848. ->where('cpid', $cpid)
  6849. ->where('user_id', $query_uid)
  6850. ->where('type', 1)->first();
  6851. if (!$product) Utils::throwError('20003:资产不存在');
  6852. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6853. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6854. if (!$ref_img_url) {
  6855. // 如果没有传入参考图,使用角色表中的图片
  6856. $ref_img_url = $product->url ?? '';
  6857. if (!$ref_img_url) {
  6858. Utils::throwError('20003:参考图不能为空');
  6859. }
  6860. }
  6861. $pic_prompt = getProp($product, 'pic_prompt');
  6862. if ($pic_prompt) {
  6863. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6864. }
  6865. // 检查参考图是否是正确的图片格式
  6866. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6867. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6868. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6869. if (!in_array($extension, $allowedExtensions)) {
  6870. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6871. }
  6872. // 处理图片模型
  6873. $model = getProp($data, 'model');
  6874. if (!$model) {
  6875. // 使用默认模型
  6876. $model = 'doubao-seedream-5-0-lite-260128';
  6877. }
  6878. // 验证模型是否在可用模型表中
  6879. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6880. Utils::throwError('20003:该模型已不可用,请更换!');
  6881. }
  6882. $ratio = getProp($data, 'ratio', '16:9');
  6883. $resolution = getProp($data, 'resolution', '2k');
  6884. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  6885. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  6886. // 参数验证
  6887. $resolution = strtolower($resolution);
  6888. if (!isset($sizeMap[$resolution])) {
  6889. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6890. }
  6891. if (!isset($sizeMap[$resolution][$ratio])) {
  6892. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6893. }
  6894. // 根据 ratio 和 resolution 确定宽高
  6895. $width = $sizeMap[$resolution][$ratio]['width'];
  6896. $height = $sizeMap[$resolution][$ratio]['height'];
  6897. try {
  6898. // 创建图片生成任务
  6899. $params = [
  6900. 'prompt' => $prompt,
  6901. 'model' => $model,
  6902. 'ref_img_urls' => [$ref_img_url],
  6903. 'width' => $width,
  6904. 'height' => $height
  6905. ];
  6906. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6907. $task_id = $task->id;
  6908. if (!$task_id) {
  6909. Utils::throwError('20003:创建图片生成任务失败');
  6910. }
  6911. // 轮询获取结果
  6912. // 只查询数据库,不调用API,不更新任务表
  6913. $start_time = time();
  6914. $timeout = 1800;
  6915. $img_url = '';
  6916. while (time() - $start_time < $timeout) {
  6917. sleep(5);
  6918. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6919. $task = DB::table('mp_generate_pic_tasks')
  6920. ->where('id', $task_id)
  6921. ->first();
  6922. if (!$task) {
  6923. Utils::throwError('20003:任务不存在');
  6924. }
  6925. if ($task->status === 'success' && $task->result_url) {
  6926. $result_urls = is_string($task->result_url)
  6927. ? json_decode($task->result_url, true)
  6928. : $task->result_url;
  6929. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6930. break;
  6931. } elseif ($task->status === 'failed') {
  6932. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6933. }
  6934. // 其他状态继续轮询
  6935. }
  6936. if (empty($img_url)) {
  6937. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6938. }
  6939. // 更新 mp_products 表(不是任务表)
  6940. DB::table('mp_products')
  6941. ->where('id', $id)
  6942. ->where('cpid', $cpid)
  6943. ->update([
  6944. 'three_view_image_url' => $img_url,
  6945. 'updated_at' => date('Y-m-d H:i:s')
  6946. ]);
  6947. return ['three_view_image_url' => $img_url];
  6948. } catch (\Exception $e) {
  6949. dLog('anime')->error('生成三视图失败', [
  6950. 'error' => $e->getMessage()
  6951. ]);
  6952. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6953. Utils::throwError('20003:' . $e->getMessage());
  6954. }
  6955. }
  6956. /**
  6957. * 推送(复制)资产或文件夹到目标位置
  6958. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6959. * @return array 返回推送结果
  6960. */
  6961. public function pushProductOrFolder($data) {
  6962. $uid = Site::getUid();
  6963. $cpid = Site::getCpid();
  6964. $role = Site::getRole();
  6965. $product_id = getProp($data, 'product_id');
  6966. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6967. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6968. if (!$product_id) {
  6969. Utils::throwError('20003:请选择要推送的项目');
  6970. }
  6971. // 查询源项目(只通过cpid查询,不限制user_id)
  6972. $sourceItem = DB::table('mp_products')
  6973. ->where('id', $product_id)
  6974. ->where('cpid', $cpid)
  6975. ->where('is_deleted', 0)
  6976. ->first();
  6977. if (!$sourceItem) {
  6978. Utils::throwError('20003:要推送的项目不存在');
  6979. }
  6980. // 通过user_id判断源是公共库还是个人库
  6981. $source_uid = $sourceItem->user_id;
  6982. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6983. // 验证目标文件夹并确定目标是公共库还是个人库
  6984. $target_level = 0;
  6985. $target_uid = $uid; // 默认推送到个人库
  6986. $target_is_public = 0;
  6987. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6988. if ($target_parent_id > 0) {
  6989. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6990. $targetParent = DB::table('mp_products')
  6991. ->where('id', $target_parent_id)
  6992. ->where('cpid', $cpid)
  6993. ->where('type', 2)
  6994. ->where('is_deleted', 0)
  6995. ->first();
  6996. if (!$targetParent) {
  6997. Utils::throwError('20003:目标文件夹不存在');
  6998. }
  6999. // 通过user_id判断目标是公共库还是个人库
  7000. $target_level = $targetParent->level;
  7001. $target_uid = $targetParent->user_id;
  7002. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7003. // 使用目标文件夹的 product 类型
  7004. $final_product_type = $targetParent->product;
  7005. }
  7006. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7007. else {
  7008. $push_to_public = getProp($data, 'push_to_public');
  7009. if ($push_to_public === '') {
  7010. Utils::throwError('20003:请选择是否推送到公共库');
  7011. }
  7012. if ($push_to_public) {
  7013. $target_uid = 0;
  7014. $target_is_public = 1;
  7015. }
  7016. // 推送到根目录时,必须指定 product 类型
  7017. if ($target_product === null || $target_product === '') {
  7018. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7019. }
  7020. $final_product_type = $target_product;
  7021. }
  7022. // 如果目标是公共库,需要admin权限
  7023. if ($target_is_public && $role !== 'admin') {
  7024. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7025. }
  7026. // 权限验证:验证是否符合允许的推送规则
  7027. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7028. try {
  7029. DB::beginTransaction();
  7030. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7031. if ($sourceItem->type == 1) {
  7032. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7033. DB::commit();
  7034. return [
  7035. 'product_id' => $newId,
  7036. ];
  7037. }
  7038. // 如果是文件夹,递归复制(支持跨类型推送)
  7039. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7040. DB::commit();
  7041. return [
  7042. 'product_id' => $newFolderId,
  7043. ];
  7044. } catch (\Exception $e) {
  7045. DB::rollBack();
  7046. dLog('anime')->error('推送失败', [
  7047. 'error' => $e->getMessage(),
  7048. 'product_id' => $product_id
  7049. ]);
  7050. Utils::throwError('20003:' . $e->getMessage());
  7051. }
  7052. }
  7053. /**
  7054. * 验证推送权限
  7055. * 允许的推送规则:
  7056. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7057. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7058. * 3. 公共库推送给公共库(公共库 → 公共库)
  7059. *
  7060. * @param int $source_uid 源的user_id
  7061. * @param int $target_uid 目标的user_id
  7062. * @param int $current_uid 当前用户ID
  7063. * @throws \Exception
  7064. */
  7065. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7066. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7067. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7068. return; // 允许
  7069. }
  7070. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7071. if ($source_uid == 0 && $target_uid == $current_uid) {
  7072. return; // 允许
  7073. }
  7074. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7075. if ($source_uid == 0 && $target_uid == 0) {
  7076. return; // 允许
  7077. }
  7078. // 其他情况都不允许
  7079. if ($source_uid != 0 && $source_uid != $current_uid) {
  7080. // 源是别人的个人库
  7081. Utils::throwError('20003:无权限访问该资产');
  7082. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7083. // 个人库推送给公共库(不允许)
  7084. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7085. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7086. // 不同用户的个人库之间推送(不允许)
  7087. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7088. } else {
  7089. // 其他未知情况
  7090. Utils::throwError('20003:不允许的推送操作');
  7091. }
  7092. }
  7093. /**
  7094. * 复制单个资产
  7095. * @param object $sourceProduct 源资产对象
  7096. * @param int $targetParentId 目标父文件夹ID
  7097. * @param int $targetLevel 目标层级
  7098. * @param int $cpid 公司ID
  7099. * @param int $targetUid 目标用户ID
  7100. * @return int 返回新资产ID
  7101. */
  7102. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7103. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7104. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7105. $newProductData = [
  7106. 'user_id' => $targetUid,
  7107. 'cpid' => $cpid,
  7108. 'type' => 1,
  7109. 'parent_id' => $targetParentId,
  7110. 'level' => $targetLevel,
  7111. 'product_name' => $sourceProduct->product_name,
  7112. 'url' => $sourceProduct->url,
  7113. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7114. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7115. 'product' => $finalProductType,
  7116. 'versions' => $sourceProduct->versions ?? '',
  7117. 'sort_order' => time(),
  7118. 'is_deleted' => 0,
  7119. 'created_at' => date('Y-m-d H:i:s'),
  7120. 'updated_at' => date('Y-m-d H:i:s')
  7121. ];
  7122. return DB::table('mp_products')->insertGetId($newProductData);
  7123. }
  7124. /**
  7125. * 递归复制文件夹及其子项
  7126. * @param object $sourceFolder 源文件夹对象
  7127. * @param int $targetParentId 目标父文件夹ID
  7128. * @param int $targetLevel 目标层级
  7129. * @param int $cpid 公司ID
  7130. * @param int $targetUid 目标用户ID
  7131. * @param int $sourceUid 源用户ID
  7132. * @return int 返回新文件夹ID
  7133. */
  7134. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7135. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7136. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7137. // 创建新文件夹
  7138. $newFolderData = [
  7139. 'user_id' => $targetUid,
  7140. 'cpid' => $cpid,
  7141. 'type' => 2,
  7142. 'parent_id' => $targetParentId,
  7143. 'level' => $targetLevel,
  7144. 'product_name' => $sourceFolder->product_name,
  7145. 'product' => $finalProductType,
  7146. 'sort_order' => time(),
  7147. 'is_deleted' => 0,
  7148. 'created_at' => date('Y-m-d H:i:s'),
  7149. 'updated_at' => date('Y-m-d H:i:s')
  7150. ];
  7151. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7152. // 获取源文件夹下的所有子项
  7153. $children = DB::table('mp_products')
  7154. ->where('parent_id', $sourceFolder->id)
  7155. ->where('cpid', $cpid)
  7156. ->where('user_id', $sourceUid)
  7157. ->where('is_deleted', 0)
  7158. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7159. ->get();
  7160. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7161. foreach ($children as $child) {
  7162. if ($child->type == 1) {
  7163. // 资产
  7164. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7165. } else {
  7166. // 文件夹
  7167. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7168. }
  7169. }
  7170. return $newFolderId;
  7171. }
  7172. /**
  7173. * 转让剧本归属(剧本及其关联资产)
  7174. *
  7175. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7176. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7177. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7178. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7179. *
  7180. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7181. * @return array
  7182. */
  7183. public function transferScriptOwner($data) {
  7184. $operatorRole = Site::getRole();
  7185. $operatorCpid = Site::getCpid();
  7186. // 1.权限校验:仅管理员和超管可操作
  7187. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7188. Utils::throwError(ErrorConst::NOT_ACCESS);
  7189. }
  7190. // 2.目标用户校验:必须存在且角色为 user(组员)
  7191. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7192. if ($targetUserId < 1) {
  7193. Utils::throwError('1002:请选择转让的目标用户');
  7194. }
  7195. $targetUser = DB::table('mp_manage_users')
  7196. ->where('id', $targetUserId)
  7197. ->where('is_deleted', 0)
  7198. ->first();
  7199. if (!$targetUser) {
  7200. Utils::throwError('20003:目标用户不存在');
  7201. }
  7202. if ((string)getProp($targetUser, 'role') !== 'user') {
  7203. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7204. }
  7205. $targetCpid = (int)getProp($targetUser, 'cpid');
  7206. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7207. $rawScriptIds = getProp($data, 'script_ids');
  7208. if (empty($rawScriptIds)) {
  7209. $rawScriptIds = getProp($data, 'script_id');
  7210. }
  7211. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7212. if (empty($scriptIds)) {
  7213. Utils::throwError('20003:请提供剧本ID');
  7214. }
  7215. // 预取剧本名称,便于失败结果中回显
  7216. $scriptNameMap = DB::table('mp_scripts')
  7217. ->whereIn('id', $scriptIds)
  7218. ->pluck('script_name', 'id')
  7219. ->all();
  7220. $successList = [];
  7221. $failedList = [];
  7222. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7223. foreach ($scriptIds as $scriptId) {
  7224. DB::beginTransaction();
  7225. try {
  7226. $successList[] = $this->transferSingleScriptOwner(
  7227. $scriptId,
  7228. $targetUserId,
  7229. $targetCpid,
  7230. $operatorRole,
  7231. $operatorCpid,
  7232. Site::getUid()
  7233. );
  7234. DB::commit();
  7235. } catch (\Throwable $e) {
  7236. DB::rollBack();
  7237. $failedList[] = [
  7238. 'script_id' => (int)$scriptId,
  7239. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7240. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7241. ];
  7242. dLog('anime')->error('剧本归属转让失败', [
  7243. 'script_id' => $scriptId,
  7244. 'target_user_id' => $targetUserId,
  7245. 'operator_uid' => Site::getUid(),
  7246. 'error' => $e->getMessage(),
  7247. ]);
  7248. }
  7249. }
  7250. return [
  7251. 'target_user_id' => $targetUserId,
  7252. 'success_count' => count($successList),
  7253. 'failed_count' => count($failedList),
  7254. 'success_list' => $successList,
  7255. 'failed_list' => $failedList,
  7256. ];
  7257. }
  7258. /**
  7259. * 单个剧本的归属转让(需在事务中调用)
  7260. *
  7261. * @param int $scriptId 剧本ID
  7262. * @param int $targetUserId 目标用户ID
  7263. * @param int $targetCpid 目标用户所属公司ID
  7264. * @param string $operatorRole 操作人角色
  7265. * @param int $operatorCpid 操作人所属公司ID
  7266. * @param int $operatorUid 操作人用户ID
  7267. * @return array
  7268. */
  7269. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7270. $script = DB::table('mp_scripts')
  7271. ->where('id', $scriptId)
  7272. ->where('is_deleted', 0)
  7273. ->first();
  7274. if (!$script) {
  7275. Utils::throwError('20003:剧本不存在');
  7276. }
  7277. $scriptCpid = (int)getProp($script, 'cpid');
  7278. $fromUserId = (int)getProp($script, 'user_id');
  7279. // 管理员仅可操作本组剧本
  7280. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7281. Utils::throwError(ErrorConst::NOT_ACCESS);
  7282. }
  7283. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7284. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7285. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7286. }
  7287. // 禁止跨组转让:目标用户必须与剧本同组
  7288. if ($targetCpid !== $scriptCpid) {
  7289. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7290. }
  7291. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7292. $productIds = $this->normalizeIdList(
  7293. DB::table('mp_script_product_mappings')
  7294. ->where('script_id', $scriptId)
  7295. ->pluck('product_id')
  7296. ->all()
  7297. );
  7298. $folderIds = [];
  7299. if (!empty($productIds)) {
  7300. $products = DB::table('mp_products')
  7301. ->whereIn('id', $productIds)
  7302. ->select('id', 'cpid', 'parent_id', 'user_id')
  7303. ->get();
  7304. // 关联资产必须全部存在,否则视为数据异常,不提交
  7305. if ($products->count() !== count($productIds)) {
  7306. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7307. }
  7308. foreach ($products as $product) {
  7309. // 关联资产必须与剧本同组,避免误转让跨组资产
  7310. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7311. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7312. }
  7313. $parentId = (int)getProp($product, 'parent_id', 0);
  7314. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7315. $folderIds[] = $parentId;
  7316. }
  7317. }
  7318. // 仅转让归属于原剧本所有者的资产
  7319. $folderIds = DB::table('mp_products')
  7320. ->whereIn('id', $folderIds)
  7321. ->where('type', 2)
  7322. ->where('cpid', $scriptCpid)
  7323. ->where('user_id', $fromUserId)
  7324. ->pluck('id')
  7325. ->map('intval')
  7326. ->all();
  7327. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7328. if ($operatorRole !== 'superadmin') {
  7329. foreach ($products as $product) {
  7330. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7331. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7332. }
  7333. }
  7334. foreach ($products as $product) {
  7335. $parentId = (int)getProp($product, 'parent_id', 0);
  7336. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7337. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7338. }
  7339. }
  7340. }
  7341. }
  7342. $now = now();
  7343. // 5.更新剧本归属
  7344. DB::table('mp_scripts')
  7345. ->where('id', $scriptId)
  7346. ->update([
  7347. 'user_id' => $targetUserId,
  7348. 'updated_at' => $now,
  7349. ]);
  7350. // 6.更新关联资产归属
  7351. if (!empty($productIds)) {
  7352. DB::table('mp_products')
  7353. ->whereIn('id', $productIds)
  7354. ->update([
  7355. 'user_id' => $targetUserId,
  7356. 'updated_at' => $now,
  7357. ]);
  7358. }
  7359. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7360. if (!empty($folderIds)) {
  7361. DB::table('mp_products')
  7362. ->whereIn('id', $folderIds)
  7363. ->update([
  7364. 'user_id' => $targetUserId,
  7365. 'updated_at' => $now,
  7366. ]);
  7367. }
  7368. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7369. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7370. if ($scriptOwner !== $targetUserId) {
  7371. Utils::throwError('20003:剧本归属更新失败');
  7372. }
  7373. if (!empty($productIds)) {
  7374. $updatedProductCount = DB::table('mp_products')
  7375. ->whereIn('id', $productIds)
  7376. ->where('user_id', $targetUserId)
  7377. ->count();
  7378. if ($updatedProductCount !== count($productIds)) {
  7379. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7380. }
  7381. }
  7382. if (!empty($folderIds)) {
  7383. $updatedFolderCount = DB::table('mp_products')
  7384. ->whereIn('id', $folderIds)
  7385. ->where('user_id', $targetUserId)
  7386. ->count();
  7387. if ($updatedFolderCount !== count($folderIds)) {
  7388. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7389. }
  7390. }
  7391. return [
  7392. 'script_id' => (int)$scriptId,
  7393. 'script_name' => (string)getProp($script, 'script_name', ''),
  7394. 'from_user_id' => $fromUserId,
  7395. 'to_user_id' => $targetUserId,
  7396. 'product_count' => count($productIds),
  7397. 'folder_count' => count($folderIds),
  7398. ];
  7399. }
  7400. /**
  7401. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7402. *
  7403. * @param mixed $ids 待处理的ID集合
  7404. * @return array 去重后的正整数ID数组
  7405. */
  7406. private function normalizeIdList($ids) {
  7407. if (!is_array($ids)) {
  7408. $ids = explode(',', (string)$ids);
  7409. }
  7410. $result = [];
  7411. foreach ($ids as $item) {
  7412. if (is_array($item)) {
  7413. continue;
  7414. }
  7415. foreach (explode(',', (string)$item) as $part) {
  7416. $part = trim($part);
  7417. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7418. $result[] = (int)$part;
  7419. }
  7420. }
  7421. }
  7422. return array_values(array_unique($result));
  7423. }
  7424. /**
  7425. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7426. *
  7427. * 流程:
  7428. * 1. 校验剧本存在且属于当前用户
  7429. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7430. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7431. * 4. 事务内创建类型文件夹、资产与剧本映射
  7432. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7433. *
  7434. * @param array $data 请求参数
  7435. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7436. * @return array|\Generator
  7437. */
  7438. public function importScriptProductsByExcel($data, $file) {
  7439. $uid = Site::getUid();
  7440. $cpid = Site::getCpid();
  7441. $script_id = (int)getProp($data, 'script_id', 0);
  7442. if (!$script_id) {
  7443. Utils::throwError('20003:请提供剧本ID');
  7444. }
  7445. // 验证剧本是否存在,且只能导入自己创建的剧本
  7446. $script = DB::table('mp_scripts')
  7447. ->where('id', $script_id)
  7448. ->where('is_deleted', 0)
  7449. ->where('user_id', $uid)
  7450. ->first();
  7451. if (!$script) {
  7452. Utils::throwError('20003:剧本不存在或无权限操作');
  7453. }
  7454. $script_name = $script->script_name ?? 'script_' . $script_id;
  7455. // 校验上传文件
  7456. if (!$file) {
  7457. Utils::throwError('20003:请上传Excel文件');
  7458. }
  7459. $extension = strtolower($file->getClientOriginalExtension());
  7460. if (!in_array($extension, ['xlsx', 'xls'])) {
  7461. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7462. }
  7463. if ($file->getSize() > 10 * 1024 * 1024) {
  7464. Utils::throwError('20003:文件大小不能超过10M');
  7465. }
  7466. // 解析 Excel(第一行为表头)
  7467. $rows = $this->readImportExcelRows($file);
  7468. if (empty($rows)) {
  7469. Utils::throwError('20003:Excel内容为空');
  7470. }
  7471. $headers = array_shift($rows);
  7472. // 定位强制列
  7473. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7474. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7475. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7476. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7477. $missingColumns = [];
  7478. if ($typeColumnIndex < 0) {
  7479. $missingColumns[] = '资产类型';
  7480. }
  7481. if ($nameColumnIndex < 0) {
  7482. $missingColumns[] = '资产名称';
  7483. }
  7484. if ($rangeColumnIndex < 0) {
  7485. $missingColumns[] = '使用范围';
  7486. }
  7487. if ($promptColumnIndex < 0) {
  7488. $missingColumns[] = '参考提示词';
  7489. }
  7490. if (!empty($missingColumns)) {
  7491. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7492. }
  7493. // 先整体校验 Excel 数据,所有异常行一次性返回
  7494. $validation = $this->validateImportExcelRows(
  7495. $rows,
  7496. $typeColumnIndex,
  7497. $nameColumnIndex,
  7498. $rangeColumnIndex,
  7499. $promptColumnIndex
  7500. );
  7501. $errors = $validation['errors'];
  7502. $checkedRows = $validation['checked_rows'];
  7503. if (empty($checkedRows)) {
  7504. $errors[] = 'Excel中没有有效的数据行';
  7505. }
  7506. if (!empty($errors)) {
  7507. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7508. }
  7509. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7510. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7511. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7512. $validRows = $dedupResult['valid_rows'];
  7513. $skipped = $dedupResult['skipped'];
  7514. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7515. $model = getProp($data, 'model');
  7516. if (!$model) {
  7517. $model = 'doubao-seedream-5-0-lite-260128';
  7518. }
  7519. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7520. Utils::throwError('20003:该模型已不可用,请更换!');
  7521. }
  7522. $ratio = getProp($data, 'ratio', '9:16');
  7523. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7524. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7525. if (!isset($sizeMap[$resolution])) {
  7526. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7527. }
  7528. if (!isset($sizeMap[$resolution][$ratio])) {
  7529. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7530. }
  7531. $width = $sizeMap[$resolution][$ratio]['width'];
  7532. $height = $sizeMap[$resolution][$ratio]['height'];
  7533. $autoRaw = getProp($data, 'auto_generate_images', true);
  7534. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7535. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7536. $taskCenterId = $this->createScriptProductTaskCenter(
  7537. $uid,
  7538. $cpid,
  7539. $script_id,
  7540. $validRows,
  7541. $model,
  7542. $ratio,
  7543. $resolution,
  7544. $auto_generate_images
  7545. );
  7546. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7547. if (empty($validRows)) {
  7548. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7549. $script_id,
  7550. $model,
  7551. $width,
  7552. $height,
  7553. $auto_generate_images
  7554. );
  7555. $productTaskMap = $existingTaskInfo['product_task_map'];
  7556. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7557. if (!empty($productTaskMap)) {
  7558. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7559. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7560. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7561. } else {
  7562. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7563. }
  7564. $resultData = [
  7565. 'success' => true,
  7566. 'message' => $message,
  7567. 'script_id' => $script_id,
  7568. 'script_name' => $script_name,
  7569. 'imported_count' => 0,
  7570. 'existing_products' => $existingTaskInfo['product_count'],
  7571. 'skipped_count' => count($skipped),
  7572. 'skipped' => $skipped,
  7573. 'created_products' => [],
  7574. 'type_folder_ids' => $typeFolderIds,
  7575. 'pending_tasks_count' => count($productTaskMap),
  7576. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7577. 'task_center_id' => $taskCenterId,
  7578. ];
  7579. // 有需要轮询的任务(已有任务或本次补建):走 SSE 返回结果
  7580. if (!empty($productTaskMap)) {
  7581. return $this->pollProductImageTasks(
  7582. $script_id,
  7583. $script_name,
  7584. $productTaskMap,
  7585. $typeFolderIds,
  7586. $taskCenterId,
  7587. ['import_result' => $resultData]
  7588. );
  7589. }
  7590. // 资产图片已全部生成完成或无法生成:直接返回结果
  7591. if ($taskCenterId) {
  7592. $this->taskCenterService->updateTask($taskCenterId, [
  7593. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7594. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7595. 'error_message' => null,
  7596. ]);
  7597. }
  7598. return $resultData;
  7599. }
  7600. // 事务内创建资产、类型文件夹与剧本映射
  7601. $typeFolderIds = [];
  7602. $createdProducts = [];
  7603. $mappingRecords = [];
  7604. $now = now();
  7605. DB::beginTransaction();
  7606. try {
  7607. foreach ($validRows as $row) {
  7608. $type = $row['type'];
  7609. if (!isset($typeFolderIds[$type])) {
  7610. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7611. $folder = DB::table('mp_products')
  7612. ->where('cpid', $cpid)
  7613. ->where('type', 2)
  7614. ->where('product', $type)
  7615. ->where('product_name', $script_name)
  7616. ->where('parent_id', 0)
  7617. ->where('is_deleted', 0)
  7618. ->first();
  7619. if ($folder) {
  7620. $typeFolderIds[$type] = $folder->id;
  7621. } else {
  7622. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7623. 'user_id' => $uid,
  7624. 'cpid' => $cpid,
  7625. 'type' => 2, // 文件夹
  7626. 'product' => $type, // 1=角色 2=场景 3=道具
  7627. 'parent_id' => 0,
  7628. 'level' => 1,
  7629. 'product_name' => $script_name,
  7630. 'sort_order' => time() + $type,
  7631. 'is_deleted' => 0,
  7632. 'created_at' => $now,
  7633. 'updated_at' => $now,
  7634. ]);
  7635. }
  7636. }
  7637. $folder_id = $typeFolderIds[$type];
  7638. $product_id = DB::table('mp_products')->insertGetId([
  7639. 'user_id' => $uid,
  7640. 'cpid' => $cpid,
  7641. 'type' => 1, // 资产
  7642. 'product' => $type,
  7643. 'parent_id' => $folder_id,
  7644. 'level' => 2,
  7645. 'product_name' => $row['product_name'],
  7646. 'pic_prompt' => $row['pic_prompt'],
  7647. 'sort_order' => time(),
  7648. 'is_deleted' => 0,
  7649. 'created_at' => $now,
  7650. 'updated_at' => $now,
  7651. ]);
  7652. $createdProducts[] = [
  7653. 'id' => $product_id,
  7654. 'type' => $type,
  7655. 'product_name' => $row['product_name'],
  7656. 'pic_prompt' => $row['pic_prompt'],
  7657. ];
  7658. // 为每个使用范围(集数)创建映射记录
  7659. foreach ($row['episode_numbers'] as $episodeNumber) {
  7660. $mappingRecords[] = [
  7661. 'script_id' => $script_id,
  7662. 'product_id' => $product_id,
  7663. 'episode_number' => $episodeNumber,
  7664. 'created_at' => $now,
  7665. 'updated_at' => $now,
  7666. ];
  7667. }
  7668. }
  7669. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7670. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7671. // 剧本已有资产,同步更新is_products标记
  7672. DB::table('mp_scripts')->where('id', $script_id)->update([
  7673. 'is_products' => 1,
  7674. 'updated_at' => $now,
  7675. ]);
  7676. DB::commit();
  7677. } catch (\Exception $e) {
  7678. DB::rollback();
  7679. if ($taskCenterId) {
  7680. $this->taskCenterService->updateTask($taskCenterId, [
  7681. 'status' => MpTaskCenter::STATUS_FAILED,
  7682. 'error_message' => $e->getMessage(),
  7683. ]);
  7684. }
  7685. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7686. 'script_id' => $script_id,
  7687. 'error' => $e->getMessage(),
  7688. 'trace' => $e->getTraceAsString(),
  7689. ]);
  7690. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7691. }
  7692. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7693. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7694. $script_id,
  7695. $model,
  7696. $width,
  7697. $height,
  7698. $auto_generate_images
  7699. );
  7700. $productTaskMap = $existingTaskInfo['product_task_map'];
  7701. $resultData = [
  7702. 'success' => true,
  7703. 'message' => '导入完成',
  7704. 'script_id' => $script_id,
  7705. 'script_name' => $script_name,
  7706. 'imported_count' => count($createdProducts),
  7707. 'skipped_count' => count($skipped),
  7708. 'skipped' => $skipped,
  7709. 'created_products' => array_map(function ($item) {
  7710. return [
  7711. 'id' => $item['id'],
  7712. 'type' => $item['type'],
  7713. 'product_name' => $item['product_name'],
  7714. ];
  7715. }, $createdProducts),
  7716. 'type_folder_ids' => $typeFolderIds,
  7717. 'pending_tasks_count' => count($productTaskMap),
  7718. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7719. 'task_center_id' => $taskCenterId,
  7720. ];
  7721. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计放在 init 事件中)
  7722. if (!empty($productTaskMap)) {
  7723. return $this->pollProductImageTasks(
  7724. $script_id,
  7725. $script_name,
  7726. $productTaskMap,
  7727. $typeFolderIds,
  7728. $taskCenterId,
  7729. ['import_result' => $resultData]
  7730. );
  7731. }
  7732. // 所有资产都已有图片或未开启生成:直接返回结果
  7733. if ($taskCenterId) {
  7734. $this->taskCenterService->updateTask($taskCenterId, [
  7735. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7736. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7737. 'error_message' => null,
  7738. ]);
  7739. }
  7740. return $resultData;
  7741. }
  7742. /**
  7743. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7744. *
  7745. * @param array $rows
  7746. * @param int $typeColumnIndex
  7747. * @param int $nameColumnIndex
  7748. * @param int $rangeColumnIndex
  7749. * @param int $promptColumnIndex
  7750. * @return array ['errors' => [], 'checked_rows' => []]
  7751. */
  7752. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7753. $errors = [];
  7754. $checkedRows = [];
  7755. foreach ($rows as $rowIndex => $row) {
  7756. // 数据从第2行开始(表头占第1行)
  7757. $excelRowNo = $rowIndex + 2;
  7758. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7759. continue;
  7760. }
  7761. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7762. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7763. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7764. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7765. $missingFields = [];
  7766. if ($typeRaw === '') {
  7767. $missingFields[] = '资产类型';
  7768. }
  7769. if ($nameRaw === '') {
  7770. $missingFields[] = '资产名称';
  7771. }
  7772. if ($rangeRaw === '') {
  7773. $missingFields[] = '使用范围';
  7774. }
  7775. if ($promptRaw === '') {
  7776. $missingFields[] = '参考提示词';
  7777. }
  7778. if (!empty($missingFields)) {
  7779. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7780. continue;
  7781. }
  7782. // 资产类型校验
  7783. $productType = $this->resolveImportProductType($typeRaw);
  7784. if (!$productType) {
  7785. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7786. continue;
  7787. }
  7788. // 资产名称去除两边特殊符号
  7789. $productName = $this->normalizeImportProductName($nameRaw);
  7790. if ($productName === '') {
  7791. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7792. continue;
  7793. }
  7794. if (mb_strlen($productName, 'UTF-8') > 64) {
  7795. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7796. continue;
  7797. }
  7798. // 解析使用范围(逗号分隔的集数)
  7799. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7800. if (empty($episodeNumbers)) {
  7801. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7802. continue;
  7803. }
  7804. $checkedRows[] = [
  7805. 'row' => $excelRowNo,
  7806. 'type' => $productType,
  7807. 'product_name' => $productName,
  7808. 'episode_numbers' => $episodeNumbers,
  7809. 'pic_prompt' => $promptRaw,
  7810. ];
  7811. }
  7812. return [
  7813. 'errors' => $errors,
  7814. 'checked_rows' => $checkedRows,
  7815. ];
  7816. }
  7817. /**
  7818. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7819. *
  7820. * @param array $checkedRows
  7821. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  7822. * @return array ['valid_rows' => [], 'skipped' => []]
  7823. */
  7824. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  7825. $seenNames = [];
  7826. $validRows = [];
  7827. $skipped = [];
  7828. foreach ($checkedRows as $row) {
  7829. $nameKey = $row['product_name'];
  7830. $typeText = $this->getImportProductTypeText($row['type']);
  7831. if (isset($seenNames[$nameKey])) {
  7832. $skipped[] = [
  7833. 'row' => $row['row'],
  7834. 'type' => $typeText,
  7835. 'product_name' => $row['product_name'],
  7836. 'reason' => 'Excel中资产名称重复',
  7837. ];
  7838. continue;
  7839. }
  7840. if (isset($existingNames[$nameKey])) {
  7841. $skipped[] = [
  7842. 'row' => $row['row'],
  7843. 'type' => $typeText,
  7844. 'product_name' => $row['product_name'],
  7845. 'reason' => '剧本中已存在同名资产',
  7846. ];
  7847. continue;
  7848. }
  7849. $seenNames[$nameKey] = true;
  7850. $validRows[] = $row;
  7851. }
  7852. return [
  7853. 'valid_rows' => $validRows,
  7854. 'skipped' => $skipped,
  7855. ];
  7856. }
  7857. /**
  7858. * 读取 Excel 文件为二维数组(第一行为表头)
  7859. *
  7860. * @param \Illuminate\Http\UploadedFile $file
  7861. * @return array
  7862. */
  7863. private function readImportExcelRows($file) {
  7864. try {
  7865. $reader = IOFactory::createReaderForFile($file->getRealPath());
  7866. $reader->setReadDataOnly(true);
  7867. $spreadsheet = $reader->load($file->getRealPath());
  7868. $sheet = $spreadsheet->getSheet(0);
  7869. $rows = $sheet->toArray(null, true, true, false);
  7870. $spreadsheet->disconnectWorksheets();
  7871. unset($spreadsheet);
  7872. return $rows;
  7873. } catch (\Exception $e) {
  7874. dLog('anime')->error('Excel文件解析失败', [
  7875. 'error' => $e->getMessage(),
  7876. ]);
  7877. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  7878. }
  7879. }
  7880. /**
  7881. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  7882. *
  7883. * @param array $headers
  7884. * @param array $exactKeywords
  7885. * @param array $fuzzyKeywords
  7886. * @return int
  7887. */
  7888. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  7889. foreach ($headers as $index => $header) {
  7890. $header = trim((string)$header);
  7891. if ($header === '') {
  7892. continue;
  7893. }
  7894. foreach ($exactKeywords as $keyword) {
  7895. if ($header === $keyword) {
  7896. return $index;
  7897. }
  7898. }
  7899. }
  7900. foreach ($headers as $index => $header) {
  7901. $header = trim((string)$header);
  7902. if ($header === '') {
  7903. continue;
  7904. }
  7905. foreach ($fuzzyKeywords as $keyword) {
  7906. if (mb_strpos($header, $keyword) !== false) {
  7907. return $index;
  7908. }
  7909. }
  7910. }
  7911. return -1;
  7912. }
  7913. /**
  7914. * 判断 Excel 行是否为空行
  7915. *
  7916. * @param array $row
  7917. * @return bool
  7918. */
  7919. private function isImportExcelRowEmpty(array $row) {
  7920. foreach ($row as $cell) {
  7921. if (trim((string)$cell) !== '') {
  7922. return false;
  7923. }
  7924. }
  7925. return true;
  7926. }
  7927. /**
  7928. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  7929. *
  7930. * @param string $name
  7931. * @return string
  7932. */
  7933. private function normalizeImportProductName($name) {
  7934. $name = trim((string)$name);
  7935. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  7936. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  7937. return '';
  7938. }
  7939. return $name;
  7940. }
  7941. /**
  7942. * 解析 Excel 中的资产类型
  7943. *
  7944. * @param string $value
  7945. * @return int|null 1=角色 2=场景 3=道具
  7946. */
  7947. private function resolveImportProductType($value) {
  7948. $value = trim((string)$value);
  7949. $map = [
  7950. '角色' => 1,
  7951. '主体' => 1,
  7952. '人物' => 1,
  7953. '1' => 1,
  7954. '场景' => 2,
  7955. '2' => 2,
  7956. '道具' => 3,
  7957. '3' => 3,
  7958. ];
  7959. return isset($map[$value]) ? $map[$value] : null;
  7960. }
  7961. /**
  7962. * 资产类型文案
  7963. *
  7964. * @param int $type
  7965. * @return string
  7966. */
  7967. private function getImportProductTypeText($type) {
  7968. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  7969. return isset($map[$type]) ? $map[$type] : (string)$type;
  7970. }
  7971. /**
  7972. * 解析使用范围(逗号分隔的集数)
  7973. *
  7974. * @param string $value
  7975. * @return array
  7976. */
  7977. private function parseImportEpisodeNumbers($value) {
  7978. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  7979. $episodeNumbers = [];
  7980. foreach ($parts as $part) {
  7981. if ($part === '') {
  7982. continue;
  7983. }
  7984. if (!is_numeric($part)) {
  7985. return [];
  7986. }
  7987. $episodeNumbers[] = (int)$part;
  7988. }
  7989. $episodeNumbers = array_values(array_unique($episodeNumbers));
  7990. sort($episodeNumbers);
  7991. return $episodeNumbers;
  7992. }
  7993. /**
  7994. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  7995. *
  7996. * @param int $script_id
  7997. * @param int $cpid
  7998. * @return array
  7999. */
  8000. private function getScriptProductNames($script_id, $cpid) {
  8001. $products = DB::table('mp_script_product_mappings as m')
  8002. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8003. ->where('m.script_id', $script_id)
  8004. ->where('p.cpid', $cpid)
  8005. ->where('p.type', 1)
  8006. ->where('p.is_deleted', 0)
  8007. ->get(['p.product_name']);
  8008. $names = [];
  8009. foreach ($products as $product) {
  8010. $name = $this->normalizeImportProductName($product->product_name);
  8011. if ($name !== '') {
  8012. $names[$name] = true;
  8013. }
  8014. }
  8015. return $names;
  8016. }
  8017. /**
  8018. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8019. *
  8020. * - 已有图片任务的资产:收集任务ID,交给轮询
  8021. * - 已有图片且生成成功的资产:跳过
  8022. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8023. *
  8024. * @param int $script_id
  8025. * @param string $model
  8026. * @param int $width
  8027. * @param int $height
  8028. * @param bool $auto_generate_images
  8029. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8030. */
  8031. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8032. $productTaskMap = [];
  8033. $typeFolderIds = [];
  8034. $hasAllTasks = true;
  8035. $createdCount = 0;
  8036. $existingMappings = DB::table('mp_script_product_mappings')
  8037. ->where('script_id', $script_id)
  8038. ->get();
  8039. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8040. $productsWithTasks = DB::table('mp_products')
  8041. ->whereIn('id', $productIds)
  8042. ->where('is_deleted', 0)
  8043. ->get();
  8044. foreach ($productsWithTasks as $product) {
  8045. // 收集类型文件夹ID
  8046. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8047. $parentFolder = DB::table('mp_products')
  8048. ->where('id', $product->parent_id)
  8049. ->where('type', 2)
  8050. ->first();
  8051. if ($parentFolder) {
  8052. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8053. }
  8054. }
  8055. // 检查是否有图片生成任务
  8056. if (!empty($product->pic_task_id)) {
  8057. $productTaskMap[$product->id] = $product->pic_task_id;
  8058. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8059. continue;
  8060. } else {
  8061. // 有资产没有图片
  8062. $hasAllTasks = false;
  8063. }
  8064. }
  8065. // 为没有图片的资产补建图片生成任务
  8066. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8067. DB::beginTransaction();
  8068. try {
  8069. foreach ($productsWithTasks as $product) {
  8070. // 跳过已有任务的资产
  8071. if (!empty($product->pic_task_id)) {
  8072. continue;
  8073. }
  8074. // 跳过没有提示词的资产
  8075. if (empty($product->pic_prompt)) {
  8076. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8077. 'product_id' => $product->id,
  8078. 'product_name' => $product->product_name,
  8079. ]);
  8080. continue;
  8081. }
  8082. try {
  8083. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8084. 'prompt' => $product->pic_prompt,
  8085. 'model' => $model,
  8086. 'ref_img_urls' => [],
  8087. 'width' => $width,
  8088. 'height' => $height,
  8089. ]);
  8090. $task_id = $task->id;
  8091. if ($task_id) {
  8092. $productTaskMap[$product->id] = $task_id;
  8093. $createdCount++;
  8094. DB::table('mp_products')
  8095. ->where('id', $product->id)
  8096. ->update([
  8097. 'pic_task_id' => $task_id,
  8098. 'pic_task_status' => '生成中',
  8099. 'updated_at' => now(),
  8100. ]);
  8101. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8102. 'product_id' => $product->id,
  8103. 'task_id' => $task_id,
  8104. ]);
  8105. }
  8106. } catch (\Exception $e) {
  8107. dLog('anime')->error('创建资产图片生成任务失败', [
  8108. 'product_id' => $product->id,
  8109. 'error' => $e->getMessage(),
  8110. ]);
  8111. DB::table('mp_products')
  8112. ->where('id', $product->id)
  8113. ->update([
  8114. 'pic_task_status' => '生成失败',
  8115. 'updated_at' => now(),
  8116. ]);
  8117. }
  8118. }
  8119. DB::commit();
  8120. } catch (\Exception $e) {
  8121. DB::rollback();
  8122. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8123. 'script_id' => $script_id,
  8124. 'error' => $e->getMessage(),
  8125. ]);
  8126. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8127. }
  8128. }
  8129. return [
  8130. 'product_task_map' => $productTaskMap,
  8131. 'type_folder_ids' => $typeFolderIds,
  8132. 'has_all_tasks' => $hasAllTasks,
  8133. 'product_count' => count($productIds),
  8134. 'created_count' => $createdCount,
  8135. ];
  8136. }
  8137. /**
  8138. * 保存剧本资产关联关系
  8139. * @param array $data 请求参数
  8140. * @return bool
  8141. */
  8142. public function saveScriptProducts($data) {
  8143. $uid = Site::getUid();
  8144. $cpid = Site::getCpid();
  8145. $script_id = getProp($data, 'script_id');
  8146. $products = getProp($data, 'products', []);
  8147. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8148. if (!$script_id) {
  8149. Utils::throwError('20003:请提供剧本ID');
  8150. }
  8151. // 验证剧本是否存在
  8152. $script = DB::table('mp_scripts')
  8153. ->where('id', $script_id)
  8154. ->where('is_deleted', 0)
  8155. ->first();
  8156. if (!$script) {
  8157. Utils::throwError('20003:剧本不存在');
  8158. }
  8159. // 处理图片模型
  8160. $model = getProp($data, 'model');
  8161. if (!$model) {
  8162. // 使用默认模型
  8163. $model = 'doubao-seedream-5-0-lite-260128';
  8164. }
  8165. // 验证模型是否在可用模型表中
  8166. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8167. Utils::throwError('20003:该模型已不可用,请更换!');
  8168. }
  8169. $ratio = getProp($data, 'ratio', '9:16');
  8170. $resolution = getProp($data, 'resolution', '2k');
  8171. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8172. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8173. // 参数验证
  8174. $resolution = strtolower($resolution);
  8175. if (!isset($sizeMap[$resolution])) {
  8176. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8177. }
  8178. if (!isset($sizeMap[$resolution][$ratio])) {
  8179. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8180. }
  8181. // 根据 ratio 和 resolution 确定宽高
  8182. $width = $sizeMap[$resolution][$ratio]['width'];
  8183. $height = $sizeMap[$resolution][$ratio]['height'];
  8184. $script_name = $script->script_name ?? 'script_' . $script_id;
  8185. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8186. $taskCenterId = $this->createScriptProductTaskCenter(
  8187. $uid,
  8188. $cpid,
  8189. $script_id,
  8190. $products,
  8191. $model,
  8192. $ratio,
  8193. $resolution,
  8194. $auto_generate_images
  8195. );
  8196. // 检查是否已经有该剧本的资产数据
  8197. $existingMappings = DB::table('mp_script_product_mappings')
  8198. ->where('script_id', $script_id)
  8199. ->get();
  8200. if ($existingMappings->isNotEmpty()) {
  8201. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8202. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8203. // 查询这些资产的图片生成任务状态
  8204. $productsWithTasks = DB::table('mp_products')
  8205. ->whereIn('id', $productIds)
  8206. ->where('is_deleted', 0)
  8207. ->get();
  8208. $productTaskMap = [];
  8209. $typeFolderIds = [];
  8210. $hasAllTasks = true;
  8211. foreach ($productsWithTasks as $product) {
  8212. // 收集类型文件夹ID
  8213. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8214. $parentFolder = DB::table('mp_products')
  8215. ->where('id', $product->parent_id)
  8216. ->where('type', 2)
  8217. ->first();
  8218. if ($parentFolder) {
  8219. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8220. }
  8221. }
  8222. // 检查是否有图片生成任务
  8223. if (!empty($product->pic_task_id)) {
  8224. $productTaskMap[$product->id] = $product->pic_task_id;
  8225. } else if($product->url && $product->pic_task_status == '生成成功') {
  8226. continue;
  8227. } else {
  8228. // 有资产没有图片任务
  8229. $hasAllTasks = false;
  8230. }
  8231. }
  8232. // 如果所有资产都有任务ID,直接轮询返回结果
  8233. if ($hasAllTasks && !empty($productTaskMap)) {
  8234. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8235. 'script_id' => $script_id,
  8236. 'script_name' => $script_name,
  8237. 'product_count' => count($productTaskMap)
  8238. ]);
  8239. // 直接返回 SSE 流轮询结果
  8240. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8241. }
  8242. // 如果部分资产没有任务ID,只为这些资产创建任务
  8243. if (!$hasAllTasks && $auto_generate_images) {
  8244. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8245. 'script_id' => $script_id,
  8246. 'script_name' => $script_name
  8247. ]);
  8248. // 开启事务
  8249. DB::beginTransaction();
  8250. try {
  8251. foreach ($productsWithTasks as $product) {
  8252. // 跳过已有任务的资产
  8253. if (!empty($product->pic_task_id)) {
  8254. continue;
  8255. }
  8256. // 跳过没有提示词的资产
  8257. if (empty($product->pic_prompt)) {
  8258. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8259. 'product_id' => $product->id,
  8260. 'product_name' => $product->product_name
  8261. ]);
  8262. continue;
  8263. }
  8264. try {
  8265. // 创建图片生成任务
  8266. $params = [
  8267. 'prompt' => $product->pic_prompt,
  8268. 'model' => $model,
  8269. 'ref_img_urls' => [],
  8270. 'width' => $width,
  8271. 'height' => $height
  8272. ];
  8273. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8274. $task_id = $task->id;
  8275. if ($task_id) {
  8276. $productTaskMap[$product->id] = $task_id;
  8277. // 在事务中更新资产表的任务ID和状态
  8278. DB::table('mp_products')
  8279. ->where('id', $product->id)
  8280. ->update([
  8281. 'pic_task_id' => $task_id,
  8282. 'pic_task_status' => '生成中',
  8283. 'updated_at' => now()
  8284. ]);
  8285. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8286. 'product_id' => $product->id,
  8287. 'task_id' => $task_id
  8288. ]);
  8289. }
  8290. } catch (\Exception $e) {
  8291. dLog('anime')->error('创建资产图片生成任务失败', [
  8292. 'product_id' => $product->id,
  8293. 'error' => $e->getMessage()
  8294. ]);
  8295. // 标记为失败(仍在事务中)
  8296. DB::table('mp_products')
  8297. ->where('id', $product->id)
  8298. ->update([
  8299. 'pic_task_status' => '生成失败',
  8300. 'updated_at' => now()
  8301. ]);
  8302. }
  8303. }
  8304. // 提交事务
  8305. DB::commit();
  8306. // 如果有新创建的任务,返回 SSE 流
  8307. if (!empty($productTaskMap)) {
  8308. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8309. }
  8310. } catch (\Exception $e) {
  8311. // 回滚事务
  8312. DB::rollback();
  8313. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8314. 'script_id' => $script_id,
  8315. 'error' => $e->getMessage()
  8316. ]);
  8317. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8318. }
  8319. }
  8320. // 如果不需要生成图片,返回已存在的信息
  8321. $resultData = [
  8322. 'success' => true,
  8323. 'message' => '剧本资产已存在',
  8324. 'script_id' => $script_id,
  8325. 'script_name' => $script_name,
  8326. 'type_folder_ids' => $typeFolderIds,
  8327. 'existing_products' => count($productIds),
  8328. 'tasks_count' => count($productTaskMap),
  8329. 'task_center_id' => $taskCenterId
  8330. ];
  8331. // 接口已正常完成,更新任务中心状态和结果
  8332. if ($taskCenterId) {
  8333. $this->taskCenterService->updateTask($taskCenterId, [
  8334. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8335. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8336. 'error_message' => null
  8337. ]);
  8338. }
  8339. return $resultData;
  8340. }
  8341. // 解析 products(可能是 JSON 字符串或数组)
  8342. if (is_string($products)) {
  8343. $products = json_decode($products, true);
  8344. if (json_last_error() !== JSON_ERROR_NONE) {
  8345. Utils::throwError('20003:产品数据格式错误');
  8346. }
  8347. }
  8348. if (!is_array($products) || empty($products)) {
  8349. Utils::throwError('20003:产品数据不能为空');
  8350. }
  8351. // 以下是原有的创建逻辑...
  8352. // 开启事务
  8353. DB::beginTransaction();
  8354. try {
  8355. $now = now();
  8356. $mappingRecords = [];
  8357. $createdProductIds = []; // 记录所有创建的资产ID
  8358. // 获取剧本名称
  8359. $script_name = $script->script_name ?? 'script_' . $script_id;
  8360. // 存储每个类型的根文件夹ID
  8361. $typeFolderIds = [];
  8362. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8363. foreach ($products as $productGroup) {
  8364. $type = getProp($productGroup, 'type');
  8365. $title = getProp($productGroup, 'title', '');
  8366. $content = getProp($productGroup, 'content', []);
  8367. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8368. continue;
  8369. }
  8370. // 为当前类型创建根文件夹(如果还未创建)
  8371. if (!isset($typeFolderIds[$type])) {
  8372. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8373. 'user_id' => $uid,
  8374. 'cpid' => $cpid,
  8375. 'type' => 2, // 1.资产 2文件夹
  8376. 'product' => $type, // 1.主体 2.场景 3.道具
  8377. 'parent_id' => 0, // 根文件夹,parent_id=0
  8378. 'level' => 1, // 第一层级
  8379. 'product_name' => $script_name,
  8380. 'sort_order' => time() + $type,
  8381. 'is_deleted' => 0,
  8382. 'created_at' => $now,
  8383. 'updated_at' => $now
  8384. ]);
  8385. }
  8386. $folder_id = $typeFolderIds[$type];
  8387. // 获取表头(第一行)并查找关键列的位置
  8388. $headers = $content[0];
  8389. $nameColumnIndex = -1; // 资产名称列索引
  8390. $sequenceColumnIndex = -1; // 使用范围列索引
  8391. $promptColumnIndex = -1; // 参考提示词列索引
  8392. foreach ($headers as $index => $header) {
  8393. // 查找"资产名称"列
  8394. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8395. $nameColumnIndex = $index;
  8396. }
  8397. // 查找"使用范围"列
  8398. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8399. $sequenceColumnIndex = $index;
  8400. }
  8401. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8402. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8403. $promptColumnIndex = $index;
  8404. }
  8405. }
  8406. // 验证必要的列是否都找到了
  8407. if ($nameColumnIndex === -1) {
  8408. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8409. continue;
  8410. }
  8411. if ($sequenceColumnIndex === -1) {
  8412. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8413. continue;
  8414. }
  8415. // 跳过表头,解析每一行数据
  8416. for ($i = 1; $i < count($content); $i++) {
  8417. $row = $content[$i];
  8418. // 确保行数据有效
  8419. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8420. continue;
  8421. }
  8422. // 根据动态查找的列索引提取数据
  8423. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8424. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8425. $pic_prompt = '';
  8426. // 提取参考提示词(如果找到了该列)
  8427. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8428. $pic_prompt = trim($row[$promptColumnIndex]);
  8429. }
  8430. // 解析使用范围(逗号分隔的序号)
  8431. $sequences = [];
  8432. if (!empty($sequence_str)) {
  8433. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8434. foreach ($sequenceParts as $part) {
  8435. if (is_numeric($part)) {
  8436. $sequences[] = (int)$part;
  8437. }
  8438. }
  8439. }
  8440. if (empty($product_name)) {
  8441. continue;
  8442. }
  8443. // 处理product_name两边的符号
  8444. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8445. // 如果名称不存在或仅剩占位符号,则跳过
  8446. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8447. dLog('anime')->warning('资产名称无效,跳过保存', [
  8448. 'script_id' => $script_id,
  8449. 'type' => $type,
  8450. 'product_name' => $product_name
  8451. ]);
  8452. continue;
  8453. }
  8454. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8455. $product_id = DB::table('mp_products')->insertGetId([
  8456. 'product_name' => $product_name,
  8457. 'type' => 1, // 1=资产 2.文件夹
  8458. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8459. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8460. 'level' => 2, // 第二层级
  8461. 'pic_prompt' => $pic_prompt,
  8462. 'user_id' => $uid,
  8463. 'cpid' => $cpid,
  8464. 'sort_order' => time(),
  8465. 'is_deleted' => 0,
  8466. 'created_at' => $now,
  8467. 'updated_at' => $now,
  8468. ]);
  8469. // 记录创建的资产ID
  8470. $createdProductIds[] = $product_id;
  8471. // 为每个序号创建映射记录
  8472. if (!empty($sequences)) {
  8473. foreach ($sequences as $sequence) {
  8474. $mappingRecords[] = [
  8475. 'script_id' => $script_id,
  8476. 'product_id' => $product_id,
  8477. 'episode_number' => $sequence,
  8478. 'created_at' => $now,
  8479. 'updated_at' => $now,
  8480. ];
  8481. }
  8482. } else {
  8483. // 如果没有指定序号,创建一个默认映射(序号为0)
  8484. $mappingRecords[] = [
  8485. 'script_id' => $script_id,
  8486. 'product_id' => $product_id,
  8487. 'episode_number' => 0,
  8488. 'created_at' => $now,
  8489. 'updated_at' => $now,
  8490. ];
  8491. }
  8492. }
  8493. }
  8494. if (empty($mappingRecords)) {
  8495. Utils::throwError('20003:没有有效的产品数据');
  8496. }
  8497. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8498. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8499. // 剧本已有资产,同步更新is_products标记
  8500. DB::table('mp_scripts')->where('id', $script_id)->update([
  8501. 'is_products' => 1,
  8502. 'updated_at' => $now
  8503. ]);
  8504. // 如果需要自动生成图片,在事务中创建图片生成任务
  8505. $productTaskMap = [];
  8506. if ($auto_generate_images && !empty($createdProductIds)) {
  8507. // 查询所有创建的资产
  8508. $productsToGenerate = DB::table('mp_products')
  8509. ->whereIn('id', $createdProductIds)
  8510. ->where('is_deleted', 0)
  8511. ->get();
  8512. foreach ($productsToGenerate as $product) {
  8513. if (empty($product->pic_prompt)) {
  8514. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8515. 'product_id' => $product->id,
  8516. 'product_name' => $product->product_name
  8517. ]);
  8518. continue;
  8519. }
  8520. try {
  8521. // 创建图片生成任务
  8522. $params = [
  8523. 'prompt' => $product->pic_prompt,
  8524. 'model' => $model,
  8525. 'ref_img_urls' => [],
  8526. 'width' => $width,
  8527. 'height' => $height
  8528. ];
  8529. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8530. $task_id = $task->id;
  8531. if ($task_id) {
  8532. $productTaskMap[$product->id] = $task_id;
  8533. // 在事务中更新资产表的任务ID和状态
  8534. DB::table('mp_products')
  8535. ->where('id', $product->id)
  8536. ->update([
  8537. 'pic_task_id' => $task_id,
  8538. 'pic_task_status' => '生成中',
  8539. 'updated_at' => now()
  8540. ]);
  8541. dLog('anime')->info('创建资产图片生成任务', [
  8542. 'product_id' => $product->id,
  8543. 'task_id' => $task_id
  8544. ]);
  8545. }
  8546. } catch (\Exception $e) {
  8547. dLog('anime')->error('创建资产图片生成任务失败', [
  8548. 'product_id' => $product->id,
  8549. 'error' => $e->getMessage()
  8550. ]);
  8551. // 标记为失败(仍在事务中)
  8552. DB::table('mp_products')
  8553. ->where('id', $product->id)
  8554. ->update([
  8555. 'pic_task_status' => '生成失败',
  8556. 'updated_at' => now()
  8557. ]);
  8558. }
  8559. }
  8560. }
  8561. // 提交事务
  8562. DB::commit();
  8563. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  8564. if ($auto_generate_images && !empty($productTaskMap)) {
  8565. // 返回 SSE 流(事务外轮询)
  8566. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8567. }
  8568. // 如果不需要生成图片,返回普通结果
  8569. $resultData = [
  8570. 'success' => true,
  8571. 'type_folder_ids' => $typeFolderIds,
  8572. 'inserted_count' => $insertedCount,
  8573. 'total_records' => count($mappingRecords),
  8574. 'created_products' => count($createdProductIds),
  8575. 'image_tasks_created' => count($productTaskMap),
  8576. 'task_center_id' => $taskCenterId
  8577. ];
  8578. // 接口已正常完成,更新任务中心状态和结果
  8579. if ($taskCenterId) {
  8580. $this->taskCenterService->updateTask($taskCenterId, [
  8581. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8582. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8583. 'error_message' => null
  8584. ]);
  8585. }
  8586. return $resultData;
  8587. } catch (\Exception $e) {
  8588. // 回滚事务
  8589. DB::rollback();
  8590. // 更新任务中心状态为失败
  8591. if (!empty($taskCenterId)) {
  8592. $this->taskCenterService->updateTask($taskCenterId, [
  8593. 'status' => MpTaskCenter::STATUS_FAILED,
  8594. 'error_message' => $e->getMessage()
  8595. ]);
  8596. }
  8597. // 记录错误日志
  8598. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8599. 'script_id' => $script_id,
  8600. 'error' => $e->getMessage(),
  8601. 'trace' => $e->getTraceAsString()
  8602. ]);
  8603. // 统一使用 Utils::throwError 抛出错误
  8604. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8605. }
  8606. }
  8607. /**
  8608. * 根据入参创建或复用任务中心记录
  8609. *
  8610. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8611. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8612. * 避免生成重复任务。
  8613. *
  8614. * @param int|string $uid
  8615. * @param int|string $cpid
  8616. * @param int|string $script_id
  8617. * @param mixed $products
  8618. * @param string $model
  8619. * @param string $ratio
  8620. * @param string $resolution
  8621. * @param mixed $auto_generate_images
  8622. * @return int 任务中心ID
  8623. */
  8624. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8625. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8626. if (is_string($products)) {
  8627. $decoded = json_decode($products, true);
  8628. if (json_last_error() === JSON_ERROR_NONE) {
  8629. $products = $decoded;
  8630. }
  8631. }
  8632. $params = [
  8633. 'script_id' => (int)$script_id,
  8634. 'products' => $products,
  8635. 'model' => $model,
  8636. 'ratio' => $ratio,
  8637. 'resolution' => $resolution,
  8638. 'auto_generate_images' => (bool)$auto_generate_images,
  8639. ];
  8640. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  8641. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  8642. $existing = DB::table('mp_task_center')
  8643. ->where('uid', (int)$uid)
  8644. ->where('cpid', (int)$cpid)
  8645. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8646. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8647. ->where('params_md5', $paramsMd5)
  8648. ->orderBy('id', 'desc')
  8649. ->first();
  8650. if ($existing) {
  8651. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  8652. 'script_id' => $script_id,
  8653. 'task_center_id' => $existing->id,
  8654. 'params_md5' => $paramsMd5,
  8655. ]);
  8656. return (int)$existing->id;
  8657. }
  8658. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  8659. $now = date('Y-m-d H:i:s');
  8660. DB::table('mp_task_center')->insertOrIgnore([
  8661. 'uid' => (int)$uid,
  8662. 'cpid' => (int)$cpid,
  8663. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  8664. 'title' => '剧本资产图片生成',
  8665. 'ref_task_id' => 0,
  8666. 'status' => MpTaskCenter::STATUS_PROCESSING,
  8667. 'result' => null,
  8668. 'error_message' => null,
  8669. 'prompt' => null,
  8670. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  8671. 'params_md5' => $paramsMd5,
  8672. 'created_at' => $now,
  8673. 'updated_at' => $now,
  8674. ]);
  8675. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  8676. $taskId = (int)DB::table('mp_task_center')
  8677. ->where('uid', (int)$uid)
  8678. ->where('cpid', (int)$cpid)
  8679. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8680. ->where('params_md5', $paramsMd5)
  8681. ->orderBy('id', 'desc')
  8682. ->value('id');
  8683. dLog('anime')->info('创建任务中心记录', [
  8684. 'script_id' => $script_id,
  8685. 'task_center_id' => $taskId,
  8686. 'params_md5' => $paramsMd5,
  8687. ]);
  8688. return $taskId;
  8689. }
  8690. /**
  8691. * 任务结束时更新任务中心记录的状态和结果
  8692. *
  8693. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  8694. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  8695. *
  8696. * @param int|null $taskCenterId
  8697. * @param array $resultData 接口返回结果数组
  8698. * @param bool $timeout 是否超时未完成
  8699. */
  8700. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  8701. if (!$taskCenterId) {
  8702. return;
  8703. }
  8704. $stats = $resultData['stats'] ?? [];
  8705. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  8706. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  8707. $failedCount = $completedCount - $successCount;
  8708. // 与接口返回给客户端的结果保持一致
  8709. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  8710. if ($timeout) {
  8711. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8712. 'status' => MpTaskCenter::STATUS_FAILED,
  8713. 'result' => $result,
  8714. 'error_message' => '部分任务超时,请稍后查看结果',
  8715. ]);
  8716. return;
  8717. }
  8718. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8719. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  8720. 'result' => $result,
  8721. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  8722. ]);
  8723. }
  8724. /**
  8725. * 批量为剧本资产生成图片
  8726. *
  8727. * @param array $data 请求参数
  8728. * @return \Generator 返回 SSE 流
  8729. */
  8730. public function batchGenerateProductImages($data) {
  8731. $script_id = getProp($data, 'script_id');
  8732. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  8733. if (!$script_id) {
  8734. Utils::throwError('20003:请提供剧本ID');
  8735. }
  8736. // 验证剧本是否存在
  8737. $script = DB::table('mp_scripts')
  8738. ->where('id', $script_id)
  8739. ->where('is_deleted', 0)
  8740. ->first();
  8741. if (!$script) {
  8742. Utils::throwError('20003:剧本不存在');
  8743. }
  8744. $script_name = $script->script_name ?? 'script_' . $script_id;
  8745. // 获取需要生成图片的所有资产
  8746. $products = DB::table('mp_products')
  8747. ->whereIn('parent_id', array_values($type_folder_ids))
  8748. ->where('is_deleted', 0)
  8749. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  8750. ->get();
  8751. if ($products->isEmpty()) {
  8752. Utils::throwError('20003:没有找到需要生成图片的资产');
  8753. }
  8754. // 默认参数
  8755. $model = 'doubao-seedream-5-0-lite-260128';
  8756. $width = 1600;
  8757. $height = 2848;
  8758. // 开始为每个资产创建图片生成任务
  8759. $taskIds = [];
  8760. $productTaskMap = []; // 资产ID到任务ID的映射
  8761. foreach ($products as $product) {
  8762. if (empty($product->pic_prompt)) {
  8763. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  8764. continue;
  8765. }
  8766. try {
  8767. // 创建图片生成任务
  8768. $params = [
  8769. 'prompt' => $product->pic_prompt,
  8770. 'model' => $model,
  8771. 'ref_img_urls' => [],
  8772. 'width' => $width,
  8773. 'height' => $height
  8774. ];
  8775. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8776. $task_id = $task->id;
  8777. if ($task_id) {
  8778. $taskIds[] = $task_id;
  8779. $productTaskMap[$product->id] = $task_id;
  8780. // 更新资产表的任务ID和状态
  8781. DB::table('mp_products')
  8782. ->where('id', $product->id)
  8783. ->update([
  8784. 'pic_task_id' => $task_id,
  8785. 'pic_task_status' => '生成中',
  8786. 'updated_at' => now()
  8787. ]);
  8788. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  8789. }
  8790. } catch (\Exception $e) {
  8791. dLog('anime')->error('创建资产图片生成任务失败', [
  8792. 'product_id' => $product->id,
  8793. 'error' => $e->getMessage()
  8794. ]);
  8795. // 标记为失败
  8796. DB::table('mp_products')
  8797. ->where('id', $product->id)
  8798. ->update([
  8799. 'pic_task_status' => '生成失败',
  8800. 'updated_at' => now()
  8801. ]);
  8802. }
  8803. }
  8804. if (empty($taskIds)) {
  8805. Utils::throwError('20003:没有成功创建任何图片生成任务');
  8806. }
  8807. // 返回 SSE 流
  8808. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  8809. }
  8810. /**
  8811. * 轮询资产图片生成任务状态(SSE流式返回)
  8812. * 只通过查询数据库获取任务状态,不主动调用API
  8813. *
  8814. * @param int $script_id 剧本ID
  8815. * @param string $script_name 剧本名称
  8816. * @param array $productTaskMap 资产ID到任务ID的映射
  8817. * @param array $type_folder_ids 类型文件夹ID映射
  8818. * @param int|null $taskCenterId 任务中心ID
  8819. * @param array $initExtra 追加到 init 事件中的额外数据
  8820. * @return \Generator
  8821. */
  8822. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = []) {
  8823. $startTime = time();
  8824. $timeout = 1800; // 30分钟超时
  8825. $pollInterval = 10; // 10秒轮询一次
  8826. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  8827. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  8828. if ($taskCenterId) {
  8829. $initResponse = array_merge([
  8830. 'type' => 'init',
  8831. 'script_id' => $script_id,
  8832. 'script_name' => $script_name,
  8833. 'timestamp' => date('Y-m-d H:i:s'),
  8834. 'task_center_id' => (int)$taskCenterId,
  8835. ], $initExtra);
  8836. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  8837. }
  8838. // 定义类型名称映射
  8839. $typeNames = [
  8840. 1 => 'roles', // 角色
  8841. 2 => 'scenes', // 场景
  8842. 3 => 'props' // 道具
  8843. ];
  8844. while (time() - $startTime < $timeout) {
  8845. sleep($pollInterval);
  8846. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  8847. $mappings = DB::table('mp_script_product_mappings')
  8848. ->where('script_id', $script_id)
  8849. ->pluck('product_id')
  8850. ->unique()
  8851. ->toArray();
  8852. if (empty($mappings)) {
  8853. dLog('anime')->warning('该剧本没有关联的资产', [
  8854. 'script_id' => $script_id,
  8855. 'script_name' => $script_name
  8856. ]);
  8857. break;
  8858. }
  8859. // 查询所有资产的当前状态
  8860. $products = DB::table('mp_products')
  8861. ->whereIn('id', $mappings)
  8862. ->where('is_deleted', 0)
  8863. ->get();
  8864. // 统计各类型的状态(使用类型名称作为键名)
  8865. $stats = [
  8866. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  8867. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  8868. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  8869. ];
  8870. $allCompleted = true;
  8871. $hasStatusChange = false;
  8872. foreach ($products as $product) {
  8873. $type = $product->product;
  8874. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  8875. // 如果类型名称不在 stats 中,初始化
  8876. if (!isset($stats[$typeName])) {
  8877. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8878. }
  8879. $stats[$typeName]['total']++;
  8880. $task_id = $product->pic_task_id;
  8881. $currentStatus = $product->pic_task_status;
  8882. // 检查状态是否有变化
  8883. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  8884. $hasStatusChange = true;
  8885. $lastStatus[$product->id] = $currentStatus;
  8886. }
  8887. // 如果是生成中,查询任务表状态
  8888. if ($currentStatus === '生成中' && $task_id) {
  8889. // 只查询数据库,不调用API
  8890. $task = DB::table('mp_generate_pic_tasks')
  8891. ->where('id', $task_id)
  8892. ->first();
  8893. if ($task) {
  8894. // 检查任务状态
  8895. if ($task->status === 'success' && $task->result_url) {
  8896. // 解析图片URL
  8897. $result_urls = $task->result_url;
  8898. if (is_string($result_urls)) {
  8899. $result_urls = json_decode($result_urls, true);
  8900. }
  8901. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  8902. // 更新资产表状态
  8903. DB::table('mp_products')
  8904. ->where('id', $product->id)
  8905. ->update([
  8906. 'pic_task_status' => '生成成功',
  8907. 'url' => $img_url,
  8908. 'updated_at' => now()
  8909. ]);
  8910. $stats[$typeName]['success']++;
  8911. $stats[$typeName]['completed']++;
  8912. $hasStatusChange = true;
  8913. dLog('anime')->info('资产图片生成成功', [
  8914. 'product_id' => $product->id,
  8915. 'task_id' => $task_id,
  8916. 'img_url' => $img_url
  8917. ]);
  8918. } elseif ($task->status === 'failed') {
  8919. // 更新资产表状态
  8920. DB::table('mp_products')
  8921. ->where('id', $product->id)
  8922. ->update([
  8923. 'pic_task_status' => '生成失败',
  8924. 'updated_at' => now()
  8925. ]);
  8926. $stats[$typeName]['completed']++;
  8927. $hasStatusChange = true;
  8928. dLog('anime')->warning('资产图片生成失败', [
  8929. 'product_id' => $product->id,
  8930. 'task_id' => $task_id,
  8931. 'error' => $task->error_message ?? '未知错误'
  8932. ]);
  8933. } else {
  8934. // 任务还在处理中
  8935. $allCompleted = false;
  8936. }
  8937. } else {
  8938. // 任务不存在,标记为失败
  8939. DB::table('mp_products')
  8940. ->where('id', $product->id)
  8941. ->update([
  8942. 'pic_task_status' => '生成失败',
  8943. 'updated_at' => now()
  8944. ]);
  8945. $stats[$typeName]['completed']++;
  8946. $hasStatusChange = true;
  8947. dLog('anime')->error('图片生成任务不存在', [
  8948. 'product_id' => $product->id,
  8949. 'task_id' => $task_id
  8950. ]);
  8951. }
  8952. } elseif ($currentStatus === '生成成功') {
  8953. $stats[$typeName]['success']++;
  8954. $stats[$typeName]['completed']++;
  8955. } elseif ($currentStatus === '生成失败') {
  8956. $stats[$typeName]['completed']++;
  8957. } else {
  8958. // 其他状态也认为未完成
  8959. $allCompleted = false;
  8960. }
  8961. }
  8962. // 移除没有数据的类型(total=0)
  8963. foreach ($stats as $typeName => $stat) {
  8964. if ($stat['total'] === 0) {
  8965. unset($stats[$typeName]);
  8966. }
  8967. }
  8968. // 如果有状态变化,发送 SSE 更新
  8969. if ($hasStatusChange) {
  8970. $eventType = $allCompleted ? 'complete' : 'update';
  8971. $response = [
  8972. 'type' => $eventType,
  8973. 'script_id' => $script_id,
  8974. 'script_name' => $script_name,
  8975. 'stats' => $stats,
  8976. 'timestamp' => date('Y-m-d H:i:s')
  8977. ];
  8978. if ($taskCenterId) {
  8979. $response['task_center_id'] = $taskCenterId;
  8980. }
  8981. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8982. dLog('anime')->info('SSE更新', [
  8983. 'event_type' => $eventType,
  8984. 'script_id' => $script_id,
  8985. 'script_name' => $script_name,
  8986. 'stats' => $stats
  8987. ]);
  8988. if ($allCompleted) {
  8989. dLog('anime')->info('所有资产图片生成任务已完成', [
  8990. 'script_id' => $script_id,
  8991. 'script_name' => $script_name,
  8992. 'stats' => $stats
  8993. ]);
  8994. // 全部任务完成,更新任务中心状态和结果
  8995. $this->finishScriptProductTask($taskCenterId, $response);
  8996. break;
  8997. }
  8998. }
  8999. }
  9000. // 超时处理
  9001. if (time() - $startTime >= $timeout && !$allCompleted) {
  9002. $response = [
  9003. 'type' => 'timeout',
  9004. 'message' => '部分任务超时,请稍后查看结果',
  9005. 'script_id' => $script_id,
  9006. 'script_name' => $script_name,
  9007. 'timestamp' => date('Y-m-d H:i:s')
  9008. ];
  9009. if ($taskCenterId) {
  9010. $response['task_center_id'] = $taskCenterId;
  9011. }
  9012. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9013. dLog('anime')->warning('资产图片生成任务超时', [
  9014. 'script_id' => $script_id,
  9015. 'script_name' => $script_name,
  9016. 'timeout' => $timeout
  9017. ]);
  9018. // 超时未完成,更新任务中心状态和结果
  9019. $this->finishScriptProductTask($taskCenterId, $response, true);
  9020. }
  9021. }
  9022. /**
  9023. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9024. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9025. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9026. *
  9027. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9028. */
  9029. public function checkProductPicTasks() {
  9030. // 查询所有生成中的产品图片任务
  9031. $products = DB::table('mp_products')
  9032. ->whereNotNull('pic_task_id')
  9033. ->where('pic_task_status', '生成中')
  9034. ->where('is_deleted', 0)
  9035. ->get();
  9036. $stats = [
  9037. 'total' => $products->count(),
  9038. 'success' => 0,
  9039. 'failed' => 0,
  9040. 'pending' => 0,
  9041. ];
  9042. foreach ($products as $product) {
  9043. try {
  9044. $task_id = $product->pic_task_id;
  9045. // 通过 pic_task_id 查询图片生成任务结果
  9046. $task = DB::table('mp_generate_pic_tasks')
  9047. ->where('id', $task_id)
  9048. ->first();
  9049. if ($task) {
  9050. if ($task->status === 'success' && $task->result_url) {
  9051. // 解析图片URL
  9052. $result_urls = $task->result_url;
  9053. if (is_string($result_urls)) {
  9054. $result_urls = json_decode($result_urls, true);
  9055. }
  9056. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9057. // 更新资产表状态
  9058. DB::table('mp_products')
  9059. ->where('id', $product->id)
  9060. ->update([
  9061. 'pic_task_status' => '生成成功',
  9062. 'url' => $img_url,
  9063. 'updated_at' => now()
  9064. ]);
  9065. $stats['success']++;
  9066. dLog('anime')->info('资产图片生成成功', [
  9067. 'product_id' => $product->id,
  9068. 'task_id' => $task_id,
  9069. 'img_url' => $img_url
  9070. ]);
  9071. } elseif ($task->status === 'failed') {
  9072. // 更新资产表状态
  9073. DB::table('mp_products')
  9074. ->where('id', $product->id)
  9075. ->update([
  9076. 'pic_task_status' => '生成失败',
  9077. 'updated_at' => now()
  9078. ]);
  9079. $stats['failed']++;
  9080. dLog('anime')->warning('资产图片生成失败', [
  9081. 'product_id' => $product->id,
  9082. 'task_id' => $task_id,
  9083. 'error' => $task->error_message ?? '未知错误'
  9084. ]);
  9085. } else {
  9086. // 任务还在处理中
  9087. $stats['pending']++;
  9088. }
  9089. } else {
  9090. // 任务不存在,标记为失败
  9091. DB::table('mp_products')
  9092. ->where('id', $product->id)
  9093. ->update([
  9094. 'pic_task_status' => '生成失败',
  9095. 'updated_at' => now()
  9096. ]);
  9097. $stats['failed']++;
  9098. dLog('anime')->error('图片生成任务不存在', [
  9099. 'product_id' => $product->id,
  9100. 'task_id' => $task_id
  9101. ]);
  9102. }
  9103. } catch (\Exception $e) {
  9104. dLog('anime')->error('检查产品图片生成任务异常', [
  9105. 'product_id' => $product->id,
  9106. 'task_id' => $product->pic_task_id ?? null,
  9107. 'error' => $e->getMessage()
  9108. ]);
  9109. }
  9110. }
  9111. return $stats;
  9112. }
  9113. /**
  9114. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9115. *
  9116. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9117. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9118. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9119. *
  9120. * @return int 更新的任务中心记录数
  9121. */
  9122. public function checkSaveScriptProductTaskCenters() {
  9123. $updated = 0;
  9124. // 只扫描尚未结束的 saveScriptProducts 任务
  9125. $tasks = DB::table('mp_task_center')
  9126. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9127. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9128. ->orderBy('id', 'desc')
  9129. ->limit(500)
  9130. ->get();
  9131. // 与 pollProductImageTasks 保持一致的类型名称映射
  9132. $typeNames = [
  9133. 1 => 'roles', // 角色
  9134. 2 => 'scenes', // 场景
  9135. 3 => 'props', // 道具
  9136. ];
  9137. foreach ($tasks as $task) {
  9138. try {
  9139. $taskParams = json_decode((string)$task->params, true);
  9140. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9141. if (!$script_id) {
  9142. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9143. 'task_center_id' => $task->id,
  9144. ]);
  9145. continue;
  9146. }
  9147. // 获取该剧本关联的全部资产ID
  9148. $productIds = DB::table('mp_script_product_mappings')
  9149. ->where('script_id', $script_id)
  9150. ->pluck('product_id')
  9151. ->unique()
  9152. ->toArray();
  9153. if (empty($productIds)) {
  9154. // 剧本没有关联资产,不视为完成,等待下一次检查
  9155. continue;
  9156. }
  9157. $products = DB::table('mp_products')
  9158. ->whereIn('id', $productIds)
  9159. ->where('is_deleted', 0)
  9160. ->get();
  9161. $stats = [];
  9162. $allCompleted = true;
  9163. foreach ($products as $product) {
  9164. $typeName = $typeNames[$product->product] ?? 'unknown';
  9165. if (!isset($stats[$typeName])) {
  9166. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9167. }
  9168. $stats[$typeName]['total']++;
  9169. if ($product->pic_task_status === '生成成功') {
  9170. $stats[$typeName]['success']++;
  9171. $stats[$typeName]['completed']++;
  9172. } elseif ($product->pic_task_status === '生成失败') {
  9173. $stats[$typeName]['completed']++;
  9174. } else {
  9175. // 仍有资产在生成中或未生成,任务未完成
  9176. $allCompleted = false;
  9177. }
  9178. }
  9179. if (!$allCompleted) {
  9180. continue;
  9181. }
  9182. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9183. $script = DB::table('mp_scripts')
  9184. ->where('id', $script_id)
  9185. ->where('is_deleted', 0)
  9186. ->first();
  9187. $script_name = $script->script_name ?? 'script_' . $script_id;
  9188. $this->finishScriptProductTask($task->id, [
  9189. 'type' => 'complete',
  9190. 'script_id' => $script_id,
  9191. 'script_name' => $script_name,
  9192. 'stats' => $stats,
  9193. 'timestamp' => date('Y-m-d H:i:s'),
  9194. 'task_center_id' => (int)$task->id,
  9195. ]);
  9196. $updated++;
  9197. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9198. 'task_center_id' => $task->id,
  9199. 'script_id' => $script_id,
  9200. 'stats' => $stats,
  9201. ]);
  9202. } catch (\Exception $e) {
  9203. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9204. 'task_center_id' => $task->id,
  9205. 'error' => $e->getMessage(),
  9206. ]);
  9207. }
  9208. }
  9209. return $updated;
  9210. }
  9211. /**
  9212. * 获取剧本关联的资产列表
  9213. * @param array $data 请求参数
  9214. * @return array
  9215. */
  9216. public function getScriptProducts($data) {
  9217. $uid = Site::getUid();
  9218. $cpid = Site::getCpid();
  9219. $script_id = getProp($data, 'script_id');
  9220. $episode_number = getProp($data, 'episode_number');
  9221. if (!$script_id) {
  9222. Utils::throwError('20003:请提供剧本ID');
  9223. }
  9224. // 验证剧本是否存在
  9225. $script = DB::table('mp_scripts')
  9226. ->where('id', $script_id)
  9227. ->where('is_deleted', 0)
  9228. ->first();
  9229. if (!$script) {
  9230. Utils::throwError('20003:剧本不存在');
  9231. }
  9232. // 联表查询资产信息
  9233. $query = DB::table('mp_script_product_mappings as mapping')
  9234. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9235. ->where('mapping.script_id', $script_id)
  9236. ->where('product.cpid', $cpid)
  9237. ->where('product.is_deleted', 0);
  9238. // 如果提供了 episode_number,则过滤指定集数
  9239. if ($episode_number !== null && $episode_number !== '') {
  9240. $query->where('mapping.episode_number', $episode_number);
  9241. }
  9242. $mappings = $query->select(
  9243. 'mapping.script_id',
  9244. 'mapping.product_id',
  9245. 'mapping.episode_number',
  9246. 'product.product_name',
  9247. 'product.type',
  9248. 'product.product',
  9249. 'product.pic_prompt',
  9250. 'product.url',
  9251. 'product.pic_task_id',
  9252. 'product.pic_task_status',
  9253. 'product.three_view_image_url',
  9254. 'mapping.created_at'
  9255. )
  9256. ->orderBy('mapping.product_id', 'asc')
  9257. ->orderBy('mapping.episode_number', 'asc')
  9258. ->get();
  9259. // 按 product_id 分组,合并 episode_number
  9260. $productMap = [];
  9261. foreach ($mappings as $item) {
  9262. $product_id = $item->product_id;
  9263. if (!isset($productMap[$product_id])) {
  9264. $productMap[$product_id] = [
  9265. 'product_id' => $product_id,
  9266. 'product_name' => $item->product_name,
  9267. 'type' => (int)$item->type,
  9268. 'product' => (int)$item->product,
  9269. 'pic_prompt' => $item->pic_prompt,
  9270. 'url' => $item->url,
  9271. 'pic_task_id' => $item->pic_task_id,
  9272. 'pic_task_status' => $item->pic_task_status,
  9273. 'episode_numbers' => [],
  9274. 'created_at' => $item->created_at,
  9275. ];
  9276. }
  9277. // 添加 episode_number(去重)
  9278. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9279. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9280. }
  9281. }
  9282. // 按类型分组
  9283. $roles = []; // type=1 角色/主体
  9284. $scenes = []; // type=2 场景
  9285. $props = []; // type=3 道具
  9286. foreach ($productMap as $product) {
  9287. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9288. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9289. // 构造返回数据
  9290. $productData = [
  9291. 'product_id' => $product['product_id'],
  9292. 'product_name' => $product['product_name'],
  9293. 'product' => $product['product'],
  9294. 'pic_prompt' => $product['pic_prompt'],
  9295. 'url' => $product['url'],
  9296. 'pic_task_id' => $product['pic_task_id'],
  9297. 'pic_task_status' => $product['pic_task_status'],
  9298. 'episode_numbers' => $episodeNumbersStr,
  9299. 'created_at' => $product['created_at'],
  9300. ];
  9301. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9302. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9303. switch ($product['product']) {
  9304. case 1:
  9305. $roles[] = $productData;
  9306. break;
  9307. case 2:
  9308. $scenes[] = $productData;
  9309. break;
  9310. case 3:
  9311. $props[] = $productData;
  9312. break;
  9313. }
  9314. }
  9315. return [
  9316. 'script_id' => $script_id,
  9317. 'script_name' => $script->script_name ?? '',
  9318. 'roles' => $roles, // 主体
  9319. 'scenes' => $scenes, // 场景
  9320. 'props' => $props, // 道具
  9321. ];
  9322. }
  9323. /**
  9324. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9325. * @param string $actContent 原始内容
  9326. * @param array $products 产品数组(包含product_name和url)
  9327. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9328. */
  9329. public function processActContentWithProducts($actContent, $products) {
  9330. if (empty($actContent) || empty($products)) {
  9331. return [
  9332. 'content' => $actContent,
  9333. 'reference_images' => []
  9334. ];
  9335. }
  9336. // 构建产品名称到产品信息的映射
  9337. $product_dict = [];
  9338. foreach ($products as $product) {
  9339. $product_name = getProp($product, 'product_name');
  9340. if ($product_name) {
  9341. $product_dict[$product_name] = [
  9342. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9343. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9344. 'voice_prompt' => getProp($product, 'voice_prompt')
  9345. ];
  9346. }
  9347. }
  9348. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9349. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9350. $reference_images = [];
  9351. $product_index_map = []; // 产品名称 => 图片序号的映射
  9352. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9353. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9354. $current_index = 1;
  9355. if (!empty($matches[1])) {
  9356. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9357. $seen_products = []; // 用于去重
  9358. foreach ($matches[1] as $product_name) {
  9359. // 跳过已处理的产品
  9360. if (isset($seen_products[$product_name])) {
  9361. continue;
  9362. }
  9363. $seen_products[$product_name] = true;
  9364. // 检查产品是否在字典中
  9365. if (isset($product_dict[$product_name])) {
  9366. $url = $product_dict[$product_name]['url'];
  9367. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9368. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  9369. if (!empty($voice_prompt) && $product_name !== '旁白') {
  9370. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9371. }
  9372. // 只有URL非空才分配序号和添加到参考图片
  9373. if (!empty($url)) {
  9374. // 检查URL是否已经在reference_images中(去重)
  9375. if (!in_array($url, $reference_images)) {
  9376. $reference_images[] = $url;
  9377. $product_index_map[$product_name] = $current_index;
  9378. $current_index++;
  9379. } else {
  9380. // URL重复,找到已有的序号
  9381. $existing_index = array_search($url, $reference_images) + 1;
  9382. $product_index_map[$product_name] = $existing_index;
  9383. }
  9384. } else {
  9385. // URL为空,不分配序号(后续直接去掉{})
  9386. $product_index_map[$product_name] = 0;
  9387. }
  9388. } else {
  9389. // 产品不在字典中,不分配序号
  9390. $product_index_map[$product_name] = 0;
  9391. }
  9392. }
  9393. }
  9394. // 第二步:替换内容中的 {产品名称}
  9395. $processedContent = $actContent;
  9396. foreach ($product_index_map as $product_name => $index) {
  9397. $escaped_name = preg_quote($product_name, '/');
  9398. if ($index > 0) {
  9399. // 有图片,替换为:产品名称(图X)
  9400. $replacement = $product_name . '<图片' . $index . '>';
  9401. } else {
  9402. // 无图片,只保留产品名称
  9403. $replacement = $product_name;
  9404. }
  9405. // 替换所有 {产品名称} 为处理后的格式
  9406. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9407. }
  9408. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9409. foreach ($products as $product) {
  9410. $product_name = getProp($product, 'product_name');
  9411. $voice_prompt = getProp($product, 'voice_prompt');
  9412. if ($product_name === '旁白' && !empty($voice_prompt)) {
  9413. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9414. break; // 找到旁白后退出循环
  9415. }
  9416. }
  9417. // 第四步:将voice_prompt信息添加到内容最前面
  9418. $voice_prompt_prefix = '';
  9419. if (!empty($voice_prompts)) {
  9420. $voice_prompt_prefix .= implode('', $voice_prompts);
  9421. }
  9422. // 旁白的voice_prompt放在最后
  9423. if (!empty($narrator_voice_prompt)) {
  9424. $voice_prompt_prefix .= $narrator_voice_prompt;
  9425. }
  9426. // 如果有voice_prompt信息,添加到内容开头
  9427. if (!empty($voice_prompt_prefix)) {
  9428. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9429. }
  9430. return [
  9431. 'content' => $processedContent,
  9432. 'reference_images' => $reference_images
  9433. ];
  9434. }
  9435. public function saveActVideoGenerateParams($data) {
  9436. $episode_id = getProp($data, 'episode_id');
  9437. $model = getProp($data, 'video_model');
  9438. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  9439. if (!in_array($model, $valid_models)) {
  9440. Utils::throwError('20003:该模型不可用');
  9441. }
  9442. // 验证模型是否在可用模型表中
  9443. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9444. Utils::throwError('20003:该模型已不可用,请更换!');
  9445. }
  9446. $video_resolution = getProp($data, 'video_resolution', '720p');
  9447. $ratio = getProp($data, 'ratio');
  9448. if (!$ratio) $ratio = '9:16';
  9449. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  9450. if (!$episode) {
  9451. Utils::throwError('20003:分集不存在');
  9452. }
  9453. dLog('anime')->info('保存分集视频参数', $data);
  9454. try {
  9455. DB::beginTransaction();
  9456. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9457. 'video_model' => $model,
  9458. 'video_resolution' => $video_resolution,
  9459. 'ratio' => $ratio,
  9460. 'updated_at' => date('Y-m-d H:i:s')
  9461. ]);
  9462. if ($result === false) {
  9463. Utils::throwError('20003:分集视频参数保存失败');
  9464. }
  9465. // 同步更新mp_animes表
  9466. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  9467. 'video_model' => $model,
  9468. 'video_resolution' => $video_resolution,
  9469. 'video_ratio' => $ratio,
  9470. 'updated_at' => date('Y-m-d H:i:s')
  9471. ]);
  9472. if ($anime_result === false) {
  9473. Utils::throwError('20003:动漫视频参数保存失败');
  9474. }
  9475. } catch (\Exception $e) {
  9476. DB::rollBack();
  9477. Utils::throwError('20003:'.$e->getMessage());
  9478. }
  9479. DB::commit();
  9480. return $result;
  9481. }
  9482. public function confirmActs($data) {
  9483. $episode_id = getProp($data, 'episode_id');
  9484. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9485. if (!$episode) {
  9486. Utils::throwError('20003:分集不存在');
  9487. }
  9488. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9489. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9490. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9491. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  9492. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  9493. // 获取所有片段数据
  9494. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9495. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  9496. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  9497. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  9498. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  9499. $products = [];
  9500. // 先处理角色数组
  9501. foreach ($roles as $role) {
  9502. $product = $role;
  9503. // 将role字段重命名为product_name
  9504. if (isset($product['role'])) {
  9505. $product['product_name'] = $product['role'];
  9506. unset($product['role']);
  9507. $product['product'] = 1; // 标记类型为角色
  9508. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9509. }
  9510. }
  9511. // 处理场景数组
  9512. foreach ($scenes as $scene) {
  9513. $product = $scene;
  9514. // 将scene字段重命名为product_name
  9515. if (isset($product['scene'])) {
  9516. $product['product_name'] = $product['scene'];
  9517. unset($product['scene']);
  9518. $product['product'] = 2; // 标记类型为场景
  9519. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9520. }
  9521. }
  9522. // 处理道具数组(逻辑与场景一致)
  9523. foreach ($props as $prop) {
  9524. $product = $prop;
  9525. // 将prop字段重命名为product_name
  9526. if (isset($product['prop'])) {
  9527. $product['product_name'] = $product['prop'];
  9528. unset($product['prop']);
  9529. $product['product'] = 3; // 标记类型为道具
  9530. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9531. }
  9532. }
  9533. // extra_products优先级更高,直接覆盖同名的roles和scenes
  9534. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  9535. foreach ($extra_products as $extra_product) {
  9536. $product_name = getProp($extra_product, 'product_name');
  9537. if ($product_name) {
  9538. $products[$product_name] = $extra_product; // 覆盖同名数据
  9539. }
  9540. }
  9541. // mp_script_product_mappings 信息优先级更高:
  9542. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  9543. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  9544. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  9545. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  9546. if ($script_id && !empty($products)) {
  9547. $currentProductNames = array_keys($products);
  9548. $normalizeName = function($name) {
  9549. return trim(preg_replace(
  9550. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  9551. '',
  9552. trim((string)$name)
  9553. ));
  9554. };
  9555. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9556. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9557. ->where('mapping.script_id', $script_id)
  9558. ->where('product.is_deleted', 0)
  9559. ->whereIn('product.product_name', $currentProductNames)
  9560. ->select(
  9561. 'mapping.product_id',
  9562. 'product.product_name',
  9563. 'product.product',
  9564. 'product.pic_prompt',
  9565. 'product.url',
  9566. 'product.three_view_image_url',
  9567. )
  9568. ->get();
  9569. $mappingByName = [];
  9570. foreach ($mappingItems as $mappingItem) {
  9571. $normalizedName = $normalizeName($mappingItem->product_name);
  9572. if (!$normalizedName) continue;
  9573. $mappingByName[$normalizedName] = [
  9574. 'product_id' => (int)$mappingItem->product_id,
  9575. 'product_name' => $mappingItem->product_name,
  9576. 'product' => (int)$mappingItem->product,
  9577. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  9578. 'url' => $mappingItem->url ?? '',
  9579. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  9580. ];
  9581. }
  9582. foreach ($products as $key => &$product) {
  9583. $normalizedKey = $normalizeName($key);
  9584. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  9585. $product = array_merge($product, $mappingByName[$normalizedKey]);
  9586. }
  9587. }
  9588. unset($product);
  9589. }
  9590. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  9591. foreach ($products as &$product) {
  9592. if (!isset($product['three_view_image_url'])) {
  9593. $product['three_view_image_url'] = '';
  9594. }
  9595. }
  9596. unset($product);
  9597. // 重新索引数组(去除key)
  9598. $products = array_values($products);
  9599. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  9600. $product_names = [];
  9601. foreach ($products as $product) {
  9602. $product_name = getProp($product, 'product_name');
  9603. if ($product_name && $product_name !== '旁白') {
  9604. $product_names[] = $product_name;
  9605. }
  9606. }
  9607. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9608. $product_names = array_unique($product_names);
  9609. usort($product_names, function($a, $b) {
  9610. return mb_strlen($b) - mb_strlen($a);
  9611. });
  9612. try {
  9613. DB::beginTransaction();
  9614. // 处理每个片段
  9615. foreach ($acts as $act) {
  9616. $act_content = getProp($act, 'act_content');
  9617. if (!$act_content) continue;
  9618. $processed_content = $act_content;
  9619. // 统一替换所有资产名称为 {资产名} 格式
  9620. // 使用占位符避免嵌套替换问题
  9621. $placeholder_map = [];
  9622. $placeholder_index = 0;
  9623. foreach ($product_names as $product_name) {
  9624. // 转义特殊字符
  9625. $escaped_product = preg_quote($product_name, '/');
  9626. // 检查是否匹配且未被 {} 包裹
  9627. $processed_content = preg_replace_callback(
  9628. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9629. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9630. // 使用唯一占位符
  9631. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9632. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9633. $placeholder_index++;
  9634. return $placeholder;
  9635. },
  9636. $processed_content
  9637. );
  9638. }
  9639. // 将所有占位符替换回实际内容
  9640. foreach ($placeholder_map as $placeholder => $replacement) {
  9641. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9642. }
  9643. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9644. $shot_counter = 0;
  9645. $processed_content = preg_replace_callback(
  9646. '/【(?:镜头|分镜)(\d+)】/u',
  9647. function($matches) use (&$shot_counter) {
  9648. $shot_counter++;
  9649. return '【镜头' . $shot_counter . '】';
  9650. },
  9651. $processed_content
  9652. );
  9653. // 更新数据库
  9654. $boolen = DB::table('mp_episode_segments')
  9655. ->where('id', $act->id)
  9656. ->update([
  9657. 'act_show_content' => $processed_content,
  9658. 'updated_at' => date('Y-m-d H:i:s')
  9659. ]);
  9660. if (!$boolen) {
  9661. Utils::throwError('20003:片段处理失败');
  9662. }
  9663. }
  9664. }catch (\Exception $e) {
  9665. DB::rollBack();
  9666. Utils::throwError('20003:'.$e->getMessage());
  9667. }
  9668. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9669. 'is_generated' => 1,
  9670. 'updated_at' => date('Y-m-d H:i:s')
  9671. ]);
  9672. if (!$boolen1) {
  9673. DB::rollBack();
  9674. Utils::throwError('20003:分集处理失败!');
  9675. }
  9676. DB::commit();
  9677. // 重新查询更新后的片段数据
  9678. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9679. // 构建返回的acts数组
  9680. $return_acts = [];
  9681. foreach ($acts as $act) {
  9682. $return_acts[] = [
  9683. 'act_id' => getProp($act, 'id'),
  9684. 'act_number' => getProp($act, 'act_number'),
  9685. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  9686. 'act_show_content' => getProp($act, 'act_show_content'),
  9687. 'video_url' => getProp($act, 'video_url'),
  9688. 'video_duration' => getProp($act, 'video_duration'),
  9689. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  9690. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  9691. ];
  9692. }
  9693. return [
  9694. 'anime_id' => getProp($episode, 'anime_id'),
  9695. 'episode_id' => $episode_id,
  9696. 'title' => getProp($episode, 'title'),
  9697. 'episode_number' => getProp($episode, 'episode_number'),
  9698. 'is_generated' => getProp($episode, 'is_generated'),
  9699. 'video_params' => [
  9700. 'video_model' => getProp($episode, 'video_model'),
  9701. 'video_resolution' => getProp($episode, 'video_resolution'),
  9702. 'ratio' => getProp($episode, 'ratio'),
  9703. ],
  9704. 'products' => $products,
  9705. 'acts' => $return_acts
  9706. ];
  9707. }
  9708. /**
  9709. * 参照 episodePicsInfo 的更新与监控逻辑:
  9710. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  9711. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  9712. */
  9713. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  9714. $pollInterval = 5; // 每5秒查询一次
  9715. $maxWaitSeconds = 60; // 最多持续1分钟
  9716. $startTime = time();
  9717. while (true) {
  9718. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  9719. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9720. if (!$episode) {
  9721. Utils::throwError('20003:分集不存在');
  9722. }
  9723. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9724. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9725. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9726. $updated = false;
  9727. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  9728. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  9729. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  9730. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  9731. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  9732. // 有图片任务结果更新时写回分集表
  9733. if ($updated) {
  9734. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9735. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  9736. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  9737. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  9738. 'updated_at' => date('Y-m-d H:i:s')
  9739. ]);
  9740. }
  9741. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  9742. if (empty($waitingAssets) && empty($missingAssets)) {
  9743. return;
  9744. }
  9745. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  9746. if (empty($waitingAssets)) {
  9747. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  9748. }
  9749. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  9750. if (time() - $startTime >= $maxWaitSeconds) {
  9751. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  9752. }
  9753. sleep($pollInterval);
  9754. }
  9755. }
  9756. /**
  9757. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  9758. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  9759. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  9760. */
  9761. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  9762. foreach ($assets as &$asset) {
  9763. $assetName = getProp($asset, $nameKey);
  9764. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  9765. continue;
  9766. }
  9767. // 已有图片URL的资产视为已生成
  9768. if (getProp($asset, 'url')) {
  9769. continue;
  9770. }
  9771. $task_id = getProp($asset, 'task_id');
  9772. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  9773. if (!$task_id) {
  9774. $missingAssets[] = $assetName;
  9775. continue;
  9776. }
  9777. $task = DB::table('mp_generate_pic_tasks')
  9778. ->where('id', $task_id)
  9779. ->select('status', 'result_url')
  9780. ->first();
  9781. // 任务不存在:同样记录为缺失项,不在此处直接报错
  9782. if (!$task) {
  9783. $missingAssets[] = $assetName;
  9784. continue;
  9785. }
  9786. if ($task->status === 'success') {
  9787. $result_url = getProp($task, 'result_url');
  9788. if ($result_url) {
  9789. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  9790. if (is_array($result_urls) && !empty($result_urls[0])) {
  9791. $asset['url'] = $result_urls[0];
  9792. $asset['task_status'] = 'success';
  9793. $updated = true;
  9794. continue;
  9795. }
  9796. }
  9797. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  9798. $waitingAssets[] = $assetName;
  9799. } elseif ($task->status === 'failed') {
  9800. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  9801. $missingAssets[] = $assetName;
  9802. } else {
  9803. // 任务仍在生成中,等待下一次轮询
  9804. $waitingAssets[] = $assetName;
  9805. }
  9806. }
  9807. unset($asset);
  9808. }
  9809. /**
  9810. * 导出动漫剧本为PDF(参照示例PDF版式)
  9811. * @param int $animeId 动漫ID
  9812. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  9813. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  9814. * @return string|null
  9815. */
  9816. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  9817. // 图片下载与转换可能占用较多内存
  9818. ini_set('memory_limit', '512M');
  9819. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  9820. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  9821. $anime = (array)$anime;
  9822. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  9823. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  9824. // 获取分集(默认展示版本,按集数升序)
  9825. $episodeQuery = DB::table('mp_anime_episodes')
  9826. ->where('anime_id', $animeId)
  9827. ->where('is_default', 1)
  9828. ->orderBy('episode_number')
  9829. ->orderBy('id');
  9830. if ($episodeCount > 0) {
  9831. $episodeQuery->limit($episodeCount);
  9832. }
  9833. $episodes = $episodeQuery->get()->map(function ($value) {
  9834. return (array)$value;
  9835. })->toArray();
  9836. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  9837. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  9838. $roles = $this->mergeEpisodeItems($episodes, 'role');
  9839. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  9840. $props = $this->mergeEpisodeItems($episodes, 'prop');
  9841. // 组装分集剧本数据
  9842. $episodeScripts = [];
  9843. foreach ($episodes as $episode) {
  9844. $segments = DB::table('mp_episode_segments')
  9845. ->where('anime_id', $animeId)
  9846. ->where('episode_id', $episode['id'])
  9847. ->get();
  9848. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  9849. $acts = [];
  9850. foreach ($segments as $segment) {
  9851. $segment = (array)$segment;
  9852. $actNumber = (int)getProp($segment, 'act_number', 0);
  9853. if ($actNumber <= 0) continue;
  9854. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  9855. $acts[$actNumber] = [
  9856. 'id' => (int)$segment['id'],
  9857. 'act_number' => $actNumber,
  9858. 'duration' => getProp($segment, 'act_duration', ''),
  9859. 'content' => getProp($segment, 'act_content', ''),
  9860. ];
  9861. }
  9862. }
  9863. ksort($acts);
  9864. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  9865. $segmentCounter = 0;
  9866. foreach ($acts as &$act) {
  9867. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  9868. }
  9869. unset($act);
  9870. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  9871. $narratorVoice = '';
  9872. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  9873. foreach ($episodeRoles as $role) {
  9874. if (getProp($role, 'role') === '旁白') {
  9875. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  9876. break;
  9877. }
  9878. }
  9879. if ($narratorVoice === '') {
  9880. foreach ($acts as $act) {
  9881. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  9882. $narratorVoice = trim($match[1]);
  9883. break;
  9884. }
  9885. }
  9886. }
  9887. $episodeScripts[] = [
  9888. 'episode_number' => getProp($episode, 'episode_number'),
  9889. 'title' => getProp($episode, 'title', ''),
  9890. 'act_count' => count($acts),
  9891. 'narrator_voice' => $narratorVoice,
  9892. 'acts' => array_values($acts),
  9893. ];
  9894. }
  9895. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  9896. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  9897. // 构建PDF
  9898. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  9899. // 图片已嵌入PDF,清理临时文件
  9900. foreach ($imageCache as $imgFile) {
  9901. @unlink($imgFile);
  9902. }
  9903. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  9904. if ($savePath) {
  9905. $pdf->Output($savePath, 'F');
  9906. return $savePath;
  9907. }
  9908. // 直接下载输出
  9909. header('Content-Type: application/pdf');
  9910. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  9911. $pdf->Output($filename . '.pdf', 'D');
  9912. exit();
  9913. }
  9914. /**
  9915. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  9916. * @param array $episodes 分集数据
  9917. * @param string $nameKey role|scene|prop
  9918. * @return array
  9919. */
  9920. private function mergeEpisodeItems(array $episodes, $nameKey) {
  9921. $fieldMap = [
  9922. 'role' => 'roles',
  9923. 'scene' => 'scenes',
  9924. 'prop' => 'props',
  9925. ];
  9926. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  9927. $items = [];
  9928. foreach ($episodes as $episode) {
  9929. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  9930. foreach ($list as $item) {
  9931. if (!is_array($item)) continue;
  9932. $name = trim((string)getProp($item, $nameKey, ''));
  9933. if ($name === '') continue;
  9934. // 旁白不进入主体列表(仅作为旁白音色来源)
  9935. if ($nameKey === 'role' && $name === '旁白') continue;
  9936. if (!isset($items[$name])) {
  9937. $items[$name] = $item;
  9938. }
  9939. }
  9940. }
  9941. return array_values($items);
  9942. }
  9943. /**
  9944. * 构建动漫剧本PDF
  9945. * @param array $anime 动漫信息
  9946. * @param array $roles 主体列表
  9947. * @param array $scenes 场景列表
  9948. * @param array $props 道具列表
  9949. * @param array $episodeScripts 分集剧本数据
  9950. * @param array $imageCache 图片缓存(url => 临时文件路径)
  9951. * @return \TCPDF
  9952. */
  9953. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  9954. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  9955. $pdf->SetCreator('动漫剧本导出系统');
  9956. $pdf->SetAuthor('系统');
  9957. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  9958. $pdf->SetSubject('动漫剧本导出');
  9959. $pdf->SetMargins(15, 15, 15);
  9960. $pdf->SetAutoPageBreak(true, 15);
  9961. // 剧本名
  9962. $pdf->AddPage();
  9963. $pdf->SetFont('simsun', 'B', 20);
  9964. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  9965. $pdf->Ln(5);
  9966. // 故事梗概
  9967. $intro = trim((string)getProp($anime, 'intro', ''));
  9968. if ($intro !== '') {
  9969. $this->pdfSectionTitle($pdf, '故事梗概');
  9970. $this->pdfBody($pdf, $intro);
  9971. }
  9972. // 美术风格
  9973. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  9974. if ($artStyle !== '') {
  9975. $this->pdfSectionTitle($pdf, '美术风格');
  9976. $this->pdfBody($pdf, $artStyle);
  9977. }
  9978. // 主体列表(文字+图片)
  9979. $this->pdfSectionTitle($pdf, '主体列表');
  9980. foreach ($roles as $index => $role) {
  9981. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  9982. }
  9983. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  9984. // 场景列表(文字+图片)
  9985. $this->pdfSectionTitle($pdf, '场景列表');
  9986. foreach ($scenes as $index => $scene) {
  9987. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  9988. }
  9989. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  9990. // 道具列表(文字+图片)
  9991. $this->pdfSectionTitle($pdf, '道具列表');
  9992. foreach ($props as $index => $prop) {
  9993. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  9994. }
  9995. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  9996. // 分镜剧本
  9997. $this->pdfSectionTitle($pdf, '分镜剧本');
  9998. foreach ($episodeScripts as $episodeScript) {
  9999. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  10000. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  10001. if ($episodeTitleRaw !== '') {
  10002. // title 字段可能已带"第N集"前缀,避免重复
  10003. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  10004. $episodeTitle = $episodeTitleRaw;
  10005. } else {
  10006. $episodeTitle .= ':' . $episodeTitleRaw;
  10007. }
  10008. }
  10009. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  10010. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  10011. if (getProp($episodeScript, 'narrator_voice') !== '') {
  10012. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  10013. }
  10014. foreach (getProp($episodeScript, 'acts', []) as $act) {
  10015. $actTitle = '片段' . getProp($act, 'act_number');
  10016. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  10017. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  10018. }
  10019. $this->pdfSubTitle($pdf, $actTitle, 12);
  10020. if (getProp($act, 'content') !== '') {
  10021. $this->pdfBody($pdf, getProp($act, 'content'));
  10022. }
  10023. }
  10024. }
  10025. return $pdf;
  10026. }
  10027. /**
  10028. * PDF章节标题(带分隔线)
  10029. */
  10030. private function pdfSectionTitle($pdf, $title) {
  10031. if ($pdf->GetY() > 230) {
  10032. $pdf->AddPage();
  10033. }
  10034. $pdf->SetFont('simsun', 'B', 15);
  10035. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  10036. $y = $pdf->GetY();
  10037. $pdf->SetLineWidth(0.4);
  10038. $pdf->Line(15, $y, 195, $y);
  10039. $pdf->Ln(4);
  10040. }
  10041. /**
  10042. * PDF子标题(集数/片段标题)
  10043. */
  10044. private function pdfSubTitle($pdf, $title, $size = 13) {
  10045. if ($pdf->GetY() > 240) {
  10046. $pdf->AddPage();
  10047. }
  10048. $pdf->SetFont('simsun', 'B', $size);
  10049. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  10050. $pdf->Ln(1);
  10051. }
  10052. /**
  10053. * PDF正文段落
  10054. */
  10055. private function pdfBody($pdf, $text) {
  10056. $pdf->SetFont('simsun', '', 11);
  10057. $pdf->MultiCell(0, 6, $text, 0, 'L');
  10058. $pdf->Ln(2);
  10059. }
  10060. /**
  10061. * 输出列表项图片(每张图单独一页,图下标注名称)
  10062. * @param \TCPDF $pdf
  10063. * @param array $items 列表项
  10064. * @param string $nameKey role|scene|prop
  10065. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10066. */
  10067. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  10068. foreach ($items as $item) {
  10069. $url = trim((string)getProp($item, 'url', ''));
  10070. $name = trim((string)getProp($item, $nameKey, ''));
  10071. if ($url === '' || !isset($imageCache[$url])) continue;
  10072. $imgPath = $imageCache[$url];
  10073. $size = @getimagesize($imgPath);
  10074. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  10075. continue;
  10076. }
  10077. $pdf->AddPage();
  10078. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  10079. $maxW = 160;
  10080. $maxH = 170;
  10081. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  10082. $drawW = $size[0] * $ratio;
  10083. $drawH = $size[1] * $ratio;
  10084. $x = (210 - $drawW) / 2;
  10085. $y = max(15, (297 - $drawH) / 2 - 10);
  10086. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  10087. // 图下标注名称
  10088. $pdf->SetFont('simsun', 'B', 13);
  10089. $pdf->SetY(297 - 28);
  10090. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  10091. }
  10092. }
  10093. /**
  10094. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  10095. * @param array $items 包含url字段的列表项
  10096. * @return array url => 临时文件路径
  10097. */
  10098. private function downloadImagesConcurrently(array $items) {
  10099. // 收集唯一的图片URL
  10100. $urls = [];
  10101. foreach ($items as $item) {
  10102. $url = trim((string)getProp($item, 'url', ''));
  10103. if ($url !== '') $urls[$url] = true;
  10104. }
  10105. if (!$urls) return [];
  10106. $urls = array_keys($urls);
  10107. $tmpDir = sys_get_temp_dir();
  10108. $rawFiles = [];
  10109. foreach ($urls as $url) {
  10110. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  10111. $rawFiles[$url] = $rawFile;
  10112. }
  10113. $client = new Client(['timeout' => 180, 'verify' => false]);
  10114. // 低并发下载,sink写入文件避免大图占用内存
  10115. $generator = (function () use ($urls, $client, $rawFiles) {
  10116. foreach ($urls as $url) {
  10117. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  10118. }
  10119. })();
  10120. $errors = [];
  10121. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  10122. 'concurrency' => 4,
  10123. 'rejected' => function ($reason, $url) use (&$errors) {
  10124. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  10125. },
  10126. ]);
  10127. $each->promise()->wait();
  10128. // 失败的图片串行重试一次(独占带宽,提高成功率)
  10129. foreach ($urls as $url) {
  10130. if (!isset($errors[$url])) continue;
  10131. try {
  10132. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  10133. unset($errors[$url]);
  10134. } catch (\Throwable $e) {
  10135. // 重试仍失败
  10136. }
  10137. }
  10138. $cache = [];
  10139. foreach ($urls as $url) {
  10140. $rawFile = $rawFiles[$url];
  10141. if (isset($errors[$url])) {
  10142. dLog('anime')->error('导出PDF图片下载失败', [
  10143. 'url' => $url,
  10144. 'error' => $errors[$url],
  10145. ]);
  10146. @unlink($rawFile);
  10147. continue;
  10148. }
  10149. $converted = $this->convertImageFile($rawFile, $url);
  10150. if ($converted !== null) {
  10151. $cache[$url] = $converted;
  10152. } else {
  10153. @unlink($rawFile);
  10154. }
  10155. }
  10156. return $cache;
  10157. }
  10158. /**
  10159. * 将已下载的图片文件缩放并转为JPEG
  10160. * @param string $rawFile 原始图片临时文件
  10161. * @param string $url 图片地址(用于命名)
  10162. * @return string|null 转换后的文件路径,转换失败返回null
  10163. */
  10164. private function convertImageFile($rawFile, $url) {
  10165. $content = @file_get_contents($rawFile);
  10166. if ($content === false || $content === '') return null;
  10167. if (!function_exists('imagecreatefromstring')) return null;
  10168. $image = @imagecreatefromstring($content);
  10169. if ($image === false) return null;
  10170. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  10171. imagedestroy($image);
  10172. if ($jpeg !== null) {
  10173. @unlink($rawFile);
  10174. }
  10175. return $jpeg;
  10176. }
  10177. /**
  10178. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  10179. * @param resource $srcImage GD图片资源
  10180. * @param string $rawFile 原始图片临时文件
  10181. * @param string $url 图片地址(用于命名)
  10182. * @return string|null 压缩后的JPEG文件路径
  10183. */
  10184. private function compressImageForPdf($srcImage, $rawFile, $url) {
  10185. $maxBytes = 2 * 1024 * 1024; // 2MB
  10186. $sizes = [2048, 1600, 1280, 1024, 800];
  10187. $qualities = [85, 70, 55, 40];
  10188. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  10189. foreach ($sizes as $size) {
  10190. $resized = $this->copyAndResize($srcImage, $size);
  10191. $flat = $this->flattenToWhite($resized);
  10192. imagedestroy($resized);
  10193. foreach ($qualities as $quality) {
  10194. ob_start();
  10195. $saved = imagejpeg($flat, null, $quality);
  10196. $data = ob_get_clean();
  10197. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  10198. file_put_contents($jpeg, $data);
  10199. imagedestroy($flat);
  10200. dLog('anime')->info('导出PDF图片压缩完成', [
  10201. 'url' => $url,
  10202. 'size' => filesize($jpeg),
  10203. 'edge' => $size,
  10204. 'quality' => $quality,
  10205. ]);
  10206. return $jpeg;
  10207. }
  10208. }
  10209. imagedestroy($flat);
  10210. }
  10211. // 兜底:最小尺寸、最低质量强制输出
  10212. $resized = $this->copyAndResize($srcImage, 800);
  10213. $flat = $this->flattenToWhite($resized);
  10214. imagedestroy($resized);
  10215. $saved = imagejpeg($flat, $jpeg, 30);
  10216. imagedestroy($flat);
  10217. if (!$saved) return null;
  10218. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  10219. 'url' => $url,
  10220. 'size' => filesize($jpeg),
  10221. ]);
  10222. return $jpeg;
  10223. }
  10224. /**
  10225. * 等比缩放图片副本(不销毁原图)
  10226. * @param resource $srcImage GD图片资源
  10227. * @param int $maxEdge 最大边长
  10228. * @return resource
  10229. */
  10230. private function copyAndResize($srcImage, $maxEdge) {
  10231. $width = imagesx($srcImage);
  10232. $height = imagesy($srcImage);
  10233. $max = max($width, $height);
  10234. if ($max <= $maxEdge) {
  10235. $copy = imagecreatetruecolor($width, $height);
  10236. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  10237. return $copy;
  10238. }
  10239. $ratio = $maxEdge / $max;
  10240. $newWidth = max(1, (int)round($width * $ratio));
  10241. $newHeight = max(1, (int)round($height * $ratio));
  10242. $resized = imagecreatetruecolor($newWidth, $newHeight);
  10243. imagealphablending($resized, false);
  10244. imagesavealpha($resized, true);
  10245. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  10246. return $resized;
  10247. }
  10248. /**
  10249. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  10250. * @param resource $image GD图片资源
  10251. * @return resource
  10252. */
  10253. private function flattenToWhite($image) {
  10254. $width = imagesx($image);
  10255. $height = imagesy($image);
  10256. $flat = imagecreatetruecolor($width, $height);
  10257. $white = imagecolorallocate($flat, 255, 255, 255);
  10258. imagefill($flat, 0, 0, $white);
  10259. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  10260. return $flat;
  10261. }
  10262. /**
  10263. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  10264. * @param string $content 片段内容
  10265. * @param int $counter 当前已编号数量(引用传递,整集累计)
  10266. * @return string
  10267. */
  10268. private function renumberSegmentBlocks($content, &$counter) {
  10269. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  10270. $counter++;
  10271. return '【' . $match[1] . $counter . '】';
  10272. }, $content);
  10273. }
  10274. }