AnimeService.php 541 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670
  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. 'anime_id' => $anime_id,
  310. 'episode_id' => $episode_id,
  311. 'episode_number' => getProp($episode, 'episode_number'),
  312. ];
  313. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  314. $task_id = $task->id;
  315. if (!$task_id) {
  316. Utils::throwError("20003:角色({$role_name})生成图片失败");
  317. }
  318. $role['task_id'] = $task_id;
  319. $role['task_status'] = 'processing';
  320. } catch (\Exception $e) {
  321. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  322. Utils::throwError("20003:" . $e->getMessage());
  323. }
  324. }
  325. // 保存角色信息
  326. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  327. 'roles' => json_encode($roles, 256),
  328. 'generate_status' => '执行中',
  329. 'generate_at' => date('Y-m-d H:i:s'),
  330. 'updated_at' => date('Y-m-d H:i:s')
  331. ]);
  332. if (!$boolen) {
  333. Utils::throwError('20003:保存角色信息失败');
  334. }
  335. return $boolen;
  336. }
  337. public function batchSetSceneImg($data) {
  338. $episode_id = getProp($data, 'episode_id');
  339. if (!$episode_id) Utils::throwError('1002:请选择分集');
  340. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  341. $scenes = json_decode(getProp($episode, 'scenes'), true);
  342. $art_style = getProp($episode, 'art_style');
  343. $target_scene = getProp($data, 'target_scene');
  344. $anime_id = getProp($episode, 'anime_id');
  345. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  346. $art_style_type = getProp($anime, 'art_style_type');
  347. $character_prefix = '';
  348. $scene_prefix = '';
  349. if ($art_style_type) {
  350. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  351. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  352. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  353. }
  354. foreach ($scenes as &$scene) {
  355. $scene_name = getProp($scene, 'scene');
  356. if ($scene_name != $target_scene) continue;
  357. // 优先使用 pic_prompt,如果没有则使用 description
  358. $pic_prompt = getProp($scene, 'pic_prompt');
  359. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  360. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  361. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  362. // 参考图地址
  363. $ref_img_url = getProp($scene, 'url');
  364. if ($ref_img_url) continue; // 已有图片则跳过
  365. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  366. try {
  367. $params = [
  368. 'prompt' => $description,
  369. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  370. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  371. 'anime_id' => $anime_id,
  372. 'episode_id' => $episode_id,
  373. 'episode_number' => getProp($episode, 'episode_number'),
  374. ];
  375. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  376. $task_id = $task->id;
  377. if (!$task_id) {
  378. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  379. }
  380. $scene['task_id'] = $task_id;
  381. $scene['task_status'] = 'processing';
  382. } catch (\Exception $e) {
  383. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  384. Utils::throwError("20003:" . $e->getMessage());
  385. }
  386. }
  387. // 保存场景信息
  388. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  389. 'scenes' => json_encode($scenes, 256),
  390. 'generate_status' => '执行中',
  391. 'generate_at' => date('Y-m-d H:i:s'),
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. if (!$boolen) {
  395. Utils::throwError('20003:保存角色信息失败');
  396. }
  397. return $boolen;
  398. }
  399. public function editAnime($data) {
  400. $anime_id = getProp($data, 'anime_id');
  401. $anime_name = trim(getProp($data, 'anime_name'));
  402. // 确认对话名称唯一性
  403. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  404. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  405. }
  406. if (!$anime_id || !$anime_name) {
  407. Utils::throwError('20003:参数异常');
  408. }
  409. return DB::table('mp_animes')->where('id', $anime_id)->update([
  410. 'anime_name' => $anime_name,
  411. 'updated_at' => date('Y-m-d H:i:s')
  412. ]);
  413. // $script_arr =getProp($data, 'script', []);
  414. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  415. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  416. // $anime_id = getProp($data, 'anime_id');
  417. // try {
  418. // DB::beginTransaction();
  419. // $table_data = [
  420. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  421. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  422. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  423. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  424. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  425. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  426. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  427. // 'status' => 3,
  428. // 'start_episode_sequence' => $start_episode_sequence,
  429. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  430. // 'episode_num' => count($script_arr['episodes']),
  431. // 'updated_at' => date('Y-m-d H:i:s')
  432. // ];
  433. // // 保存剧本内容
  434. // if (!empty($anime_id)) {
  435. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  436. // if (!$boolen) {
  437. // dLog('anime')->info('对话保存失败', $table_data);
  438. // Utils::throwError('20003:对话保存失败');
  439. // }
  440. // }else {
  441. // $table['created_at'] = $table_data['updated_at'];
  442. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  443. // if (!$anime_id) {
  444. // dLog('anime')->info('对话保存失败', $table_data);
  445. // Utils::throwError('20003:对话保存失败');
  446. // }
  447. // }
  448. // // 保存分集内容
  449. // // 删除历史分集内容
  450. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  451. // $episodes = [];
  452. // $sequence = 1;
  453. // foreach ($script_arr['episodes'] as $episode) {
  454. // $segment_number = 1;
  455. // foreach($episode['segments'] as $segment) {
  456. // $episodes[] = [
  457. // 'anime_id' => $anime_id,
  458. // 'episode_number' => $episode['episode_number'],
  459. // 'title' => $episode['title'],
  460. // // 'content' => $episode['content'],
  461. // 'content' => '',
  462. // 'segment_number' => $segment_number,
  463. // 'segment_content' => $segment['segment_content'],
  464. // 'sequence' => $sequence,
  465. // 'created_at' => date('Y-m-d H:i:s'),
  466. // 'updated_at' => date('Y-m-d H:i:s')
  467. // ];
  468. // $sequence++;
  469. // $segment_number++;
  470. // }
  471. // }
  472. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  473. // if (!$boolen2) {
  474. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  475. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  476. // Utils::throwError('20003:分集内容保存失败');
  477. // }
  478. // } catch (\Exception $e) {
  479. // DB::rollBack();
  480. // Utils::throwError('20003:'.$e->getMessage());
  481. // }
  482. // DB::commit();
  483. // return true;
  484. }
  485. public function delAnime($data) {
  486. $anime_id = getProp($data, 'anime_id');
  487. if (!$anime_id) {
  488. Utils::throwError('20003:请选择剧本');
  489. }
  490. return DB::table('mp_animes')->where('id', $anime_id)->update([
  491. 'is_deleted' => 1,
  492. 'updated_at' => date('Y-m-d H:i:s')
  493. ]);
  494. }
  495. public function animeDetail($data) {
  496. $uid = Site::getUid();
  497. $anime_id = getProp($data, 'anime_id');
  498. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  499. ->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();
  500. if (!$anime) Utils::throwError('20003:权限不足');
  501. $anime = (array)$anime;
  502. $anime['roles'] = json_decode($anime['roles']);
  503. $anime['scenes'] = json_decode($anime['scenes']);
  504. // 获取分集信息
  505. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  506. ->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"))
  507. ->orderBy('episode_number')->get()->map(function ($value) {
  508. return (array)$value;
  509. })->toArray();
  510. $anime['episodes'] = $episodes;
  511. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  512. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  513. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  514. ->where('anime_id', $anime_id)
  515. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  516. ->orderBy('episode_number')
  517. ->get()
  518. ->map(function ($task) use ($episodeNumbers) {
  519. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  520. return null;
  521. }
  522. return [
  523. 'episode_number' => (int)$task->episode_number,
  524. 'status' => $task->status,
  525. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  526. ];
  527. })
  528. ->filter()
  529. ->values()
  530. ->toArray();
  531. $anime['episode_tasks'] = $episodeTasks;
  532. return $anime;
  533. }
  534. public function episodeInfo($data) {
  535. $uid = Site::getUid();
  536. $anime_id = getProp($data, 'anime_id');
  537. $episode_id = getProp($data, 'episode_id');
  538. if (!$anime_id || !$episode_id) {
  539. Utils::throwError('1002:请选择剧集');
  540. }
  541. // 验证用户权限
  542. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  543. if (!$anime) Utils::throwError('20003:权限不足');
  544. $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();
  545. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  546. $episode = (array)$episode;
  547. $episode['roles'] = json_decode($episode['roles'], true);
  548. // foreach($episode['roles'] as &$item) {
  549. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  550. // }
  551. $episode['scenes'] = json_decode($episode['scenes'], true);
  552. // foreach($episode['scenes'] as &$item) {
  553. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  554. // }
  555. // 获取分镜信息
  556. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  557. ->select('*')->get()->map(function ($value) {
  558. return (array)$value;
  559. })->toArray();
  560. // 使用公共方法构建分镜结构
  561. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  562. $episode['acts'] = $segmentsStructure['acts'];
  563. $episode['total_duration'] = $segmentsStructure['total_duration'];
  564. return $episode;
  565. }
  566. public function episodeInfoForAce($data) {
  567. $anime_id = getProp($data, 'anime_id');
  568. $episode_id = getProp($data, 'episode_id');
  569. if (!$anime_id || !$episode_id) {
  570. Utils::throwError('1002:请选择剧集');
  571. }
  572. $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();
  573. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  574. $episode = (array)$episode;
  575. $episode['roles'] = json_decode($episode['roles'], true);
  576. // foreach($episode['roles'] as &$item) {
  577. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  578. // }
  579. $episode['scenes'] = json_decode($episode['scenes'], true);
  580. // foreach($episode['scenes'] as &$item) {
  581. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  582. // }
  583. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  584. // 获取分镜信息
  585. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  586. ->select('*')->get()->map(function ($value) {
  587. return (array)$value;
  588. })->toArray();
  589. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  590. $episode['acts'] = $segmentsStructure['acts'];
  591. $episode['total_duration'] = $segmentsStructure['total_duration'];
  592. // 获取mp_animes表中的视频参数
  593. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  594. $episode['video_params'] = [
  595. 'video_model' => getProp($anime, 'video_model'),
  596. 'video_resolution' => getProp($anime, 'video_resolution'),
  597. 'ratio' => getProp($anime, 'video_ratio'),
  598. ];
  599. return $episode;
  600. }
  601. public function segmentInfo($data) {
  602. $uid = Site::getUid();
  603. $segment_id = getProp($data, 'segment_id');
  604. if (!$segment_id) {
  605. Utils::throwError('1002:请选择分镜');
  606. }
  607. // 获取分镜信息
  608. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  609. // 验证用户权限
  610. if ($segment) {
  611. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  612. if (!$anime) Utils::throwError('20003:权限不足');
  613. }
  614. $result = [
  615. 'segment_id' => getProp($segment, 'segment_id'),
  616. 'segment_number' => getProp($segment, 'segment_number'),
  617. 'segment_content' => getProp($segment, 'segment_content'),
  618. 'description' => getProp($segment, 'description'),
  619. 'composition' => getProp($segment, 'composition'),
  620. 'camera_movement' => getProp($segment, 'camera_movement'),
  621. 'voice_actor' => getProp($segment, 'voice_actor'),
  622. 'dialogue' => getProp($segment, 'dialogue'),
  623. 'frame_type' => getProp($segment, 'frame_type'),
  624. 'scene' => getProp($segment, 'scene'),
  625. 'characters' => getProp($segment, 'characters'),
  626. 'tail_frame' => getProp($segment, 'tail_frame'),
  627. 'emotion' => getProp($segment, 'emotion'),
  628. 'emotion_type' => getProp($segment, 'emotion_type'),
  629. 'gender' => getProp($segment, 'gender'),
  630. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  631. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  632. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  633. 'pitch' => getProp($segment, 'pitch'),
  634. 'voice_name' => getProp($segment, 'voice_name'),
  635. 'voice_type' => getProp($segment, 'voice_type'),
  636. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  637. 'img_url' => getProp($segment, 'img_url'),
  638. 'video_url' => getProp($segment, 'video_url'),
  639. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  640. ];
  641. return $result;
  642. }
  643. public function copyEpisodeVersion($data) {
  644. $episode_id = getProp($data, 'episode_id');
  645. $uid = Site::getUid();
  646. $cpid = Site::getCpid();
  647. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  648. if (!$episode) Utils::throwError('20003:该剧集不存在');
  649. $episode = (array)$episode;
  650. $anime_id = $episode['anime_id'];
  651. $episode_number = $episode['episode_number'];
  652. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  653. $sequence = $count + 1;
  654. unset($episode['id']);
  655. $now = date('Y-m-d H:i:s');
  656. $episode['created_at'] = $now;
  657. $episode['updated_at'] = $now;
  658. $episode['is_default'] = 1;
  659. // 获取版本中含有"(副本"字样的个数
  660. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  661. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  662. $episode['sequence'] = $sequence;
  663. $episode['is_generated'] = 0;
  664. $episode['cpid'] = $cpid;
  665. // 获取ace_mode
  666. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  667. try {
  668. DB::beginTransaction();
  669. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  670. // 新增副本
  671. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  672. if (!$new_episode_id) {
  673. Utils::throwError('20003:创建副本失败!');
  674. }
  675. // 获取分镜数据并准备插入
  676. $segments_for_insert = DB::table('mp_episode_segments')
  677. ->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')
  678. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  679. $item = (array)$item;
  680. $item['episode_id'] = $new_episode_id;
  681. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  682. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  683. return $item;
  684. })->toArray();
  685. // 写入分镜数据
  686. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  687. if (!$boolen2) {
  688. Utils::throwError('20003:写入分镜数据失败!');
  689. }
  690. // 写入对话历史
  691. $records = [
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'user',
  696. 'content' => '创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ],
  702. [
  703. 'uid' => $uid,
  704. 'anime_id' => $anime_id,
  705. 'role' => 'assistant',
  706. 'content' => '好的,已为您创建副本',
  707. 'sequence' => $episode_number,
  708. 'episode_id' => $new_episode_id,
  709. 'created_at' => $now,
  710. 'updated_at' => $now
  711. ]
  712. ];
  713. $boolen3 = DB::table('mp_anime_records')->insert($records);
  714. if (!$boolen3) {
  715. Utils::throwError('20003:对话记录保存失败');
  716. }
  717. }catch (\Exception $e) {
  718. DB::rollBack();
  719. Utils::throwError('20003:'.$e->getMessage());
  720. }
  721. DB::commit();
  722. // 构建与 episodeInfo 方法一致的返回数据结构
  723. $result = [
  724. 'episode_id' => $new_episode_id,
  725. 'anime_id' => $anime_id,
  726. 'episode_number' => $episode_number,
  727. 'title' => $episode['title'],
  728. 'intro' => $episode['intro'],
  729. 'art_style' => $episode['art_style'],
  730. 'roles' => json_decode($episode['roles'], true),
  731. 'scenes' => json_decode($episode['scenes'], true),
  732. 'is_generated' => (int)$episode['is_generated']
  733. ];
  734. if ((int)$ace_mode === 1) {
  735. // 获取分镜信息
  736. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  737. ->select('*')->get()->map(function ($value) {
  738. return (array)$value;
  739. })->toArray();
  740. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  741. }else {
  742. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  743. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  744. }
  745. $result['acts'] = $segmentsStructure['acts'];
  746. $result['total_duration'] = $segmentsStructure['total_duration'];
  747. return $result;
  748. }
  749. public function episodeVersions($data) {
  750. $anime_id = getProp($data, 'anime_id');
  751. $episode_id = getProp($data, 'episode_id');
  752. if (!$anime_id || !$episode_id) {
  753. Utils::throwError('1002:请选择剧集');
  754. }
  755. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  756. $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) {
  757. return (array)$value;
  758. })->toArray();
  759. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  760. foreach($episodes as &$episode) {
  761. $episode['version'] = 'V'.$episode['sequence'];
  762. $episode['roles'] = json_decode($episode['roles'], true);
  763. $episode['scenes'] = json_decode($episode['scenes'], true);
  764. // 获取分镜信息
  765. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  766. ->select('*')->get()->map(function ($value) {
  767. return (array)$value;
  768. })->toArray();
  769. // 使用公共方法构建分镜结构
  770. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  771. $episode['acts'] = $segmentsStructure['acts'];
  772. $episode['total_duration'] = $segmentsStructure['total_duration'];
  773. }
  774. return $episodes;
  775. }
  776. public function bindEpisodeVersion($data) {
  777. $episode_id = getProp($data, 'episode_id');
  778. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  779. if (!$episode) Utils::throwError('20003:该剧集不存在');
  780. $episode = (array)$episode;
  781. if ((int)$episode['is_default'] === 1) return true;
  782. try {
  783. DB::beginTransaction();
  784. // 移除is_default标志
  785. $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')]);
  786. if (!$boolen) {
  787. Utils::throwError('20003:更新失败!');
  788. }
  789. // 绑定副本
  790. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  791. if (!$boolen2) {
  792. Utils::throwError('20003:绑定失败!');
  793. }
  794. }catch (\Exception $e) {
  795. DB::rollBack();
  796. Utils::throwError('20003:'.$e->getMessage());
  797. }
  798. DB::commit();
  799. return true;
  800. }
  801. public function chatChangeImg($data) {
  802. $segment_id = getProp($data, 'segment_id');
  803. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  804. $prompt = getProp($data, 'prompt');
  805. if (!$prompt || !$segment_id) {
  806. Utils::throwError('1002:请输入提示词,并且选择分镜');
  807. }
  808. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  809. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  810. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  811. else $ref_img_url = '';
  812. // $ref_img_url = '';
  813. if (empty($prompt)) {
  814. if (empty($ref_img_url)) {
  815. $prompt = getProp($segment, 'segment_content');
  816. }else {
  817. $prompt = '请根据图片生成';
  818. }
  819. }
  820. $anime_id = getProp($segment, 'anime_id');
  821. $episode_id = getProp($segment, 'episode_id');
  822. $episode_number = getProp($segment, 'episode_number');
  823. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  824. $ratio = getProp($data, 'ratio');
  825. if (!$ratio) {
  826. $ratio = getProp($episode, 'ratio');
  827. if (!$ratio) $ratio = '9:16';
  828. }
  829. $art_style = getProp($episode, 'art_style');
  830. if ($art_style) {
  831. $prompt = "美术风格:{$art_style}\n{$prompt}";
  832. }
  833. $dimensions = $this->getRatioDimensions($ratio);
  834. $width = $dimensions['width'];
  835. $height = $dimensions['height'];
  836. try {
  837. $params = [
  838. 'alias_segment_id' => $segment_id,
  839. 'prompt' => $prompt,
  840. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  841. 'width' => $width,
  842. 'height' => $height
  843. ];
  844. // 优化提示词(不要生成字幕)
  845. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  846. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  847. $task_id = $task->id;
  848. if (!$task_id) {
  849. Utils::throwError("20003:生成图片失败");
  850. }
  851. // 更新任务ID
  852. $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')]);
  853. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  854. } catch (\Exception $e) {
  855. Utils::throwError("20003:" . $e->getMessage());
  856. }
  857. // 创建任务之后先暂停10s等待异步任务完成
  858. sleep(10);
  859. $img_url = $this->loopGetPicTaskResult($task_id);
  860. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  861. // 图片生成后新增对话记录
  862. try {
  863. $uid = Site::getUid();
  864. $now = date('Y-m-d H:i:s');
  865. // 使用AI反推图片提示词
  866. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  867. // 保存对话记录
  868. $records = [
  869. [
  870. 'uid' => $uid,
  871. 'anime_id' => $anime_id,
  872. 'sequence' => $episode_number,
  873. 'role' => 'user',
  874. 'content' => $prompt,
  875. 'segment_id' => $segment_id,
  876. 'pic_task_id' => $task_id,
  877. 'image_url' => '',
  878. 'created_at' => $now,
  879. 'updated_at' => $now
  880. ],
  881. [
  882. 'uid' => $uid,
  883. 'anime_id' => $anime_id,
  884. 'sequence' => $episode_number,
  885. 'role' => 'assistant',
  886. 'content' => $pic_prompt,
  887. 'segment_id' => $segment_id,
  888. 'pic_task_id' => $task_id,
  889. 'image_url' => $img_url,
  890. 'created_at' => $now,
  891. 'updated_at' => $now
  892. ]
  893. ];
  894. DB::table('mp_anime_records')->insert($records);
  895. } catch (\Exception $e) {
  896. // 记录日志但不影响主流程
  897. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  898. 'segment_id' => $segment_id,
  899. 'img_url' => $img_url
  900. ]);
  901. logDB('anime', 'error', '保存对话记录失败', [
  902. 'segment_id' => $segment_id,
  903. 'img_url' => $img_url,
  904. 'error' => $e->getMessage()
  905. ]);
  906. }
  907. return $img_url;
  908. }
  909. public function segmentChatHistory($data) {
  910. $segment_id = getProp($data, 'segment_id');
  911. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  912. $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');
  913. $chat = $query->orderBy('id')->get()->map(function ($value) {
  914. $value = (array)$value;
  915. $value['created_at'] = transDate($value['created_at']);
  916. return $value;
  917. })->toArray();
  918. // 获取历史图片
  919. $url = [];
  920. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($pic_history as $task) {
  922. $result_url = getProp($task, 'result_url');
  923. if (is_json($result_url)) {
  924. $url = array_merge($url, json_decode($result_url, true));
  925. }else {
  926. $url[] = $result_url;
  927. }
  928. }
  929. // 获取历史视频
  930. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  931. foreach($video_history as $task) {
  932. $result_url = getProp($task, 'compressed_url');
  933. if (is_json($result_url)) {
  934. $url = array_merge($url, json_decode($result_url, true));
  935. }else {
  936. $url[] = $result_url;
  937. }
  938. }
  939. return compact('chat', 'url');
  940. }
  941. public function changeEpisodeRoles($data) {
  942. $anime_id = getProp($data, 'anime_id');
  943. $episode_id = getProp($data, 'episode_id');
  944. $target_roles = getProp($data, 'roles');
  945. // 删除标志优先取最外层入参 is_deleted,兼容角色对象内部(roles.is_deleted)的传参
  946. $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
  947. // 控制字段不随角色内容写入分集roles存储
  948. if (is_array($target_roles)) {
  949. unset($target_roles['is_deleted']);
  950. }
  951. // 参数验证
  952. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  953. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  954. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  955. // 验证剧集是否存在
  956. $episode = DB::table('mp_anime_episodes')
  957. ->where('anime_id', $anime_id)
  958. ->where('id', $episode_id)
  959. ->first();
  960. if (!$episode) Utils::throwError('20003:该剧集不存在');
  961. $roles = json_decode(getProp($episode, 'roles'), true);
  962. // 获取anime信息,检查是否有关联的script_id
  963. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  964. if (!$anime) Utils::throwError('20003:动漫不存在');
  965. $script_id = getProp($anime, 'script_id');
  966. $episode_number = getProp($episode, 'episode_number', 1);
  967. $uid = Site::getUid();
  968. $cpid = Site::getCpid();
  969. try {
  970. $target_role_name = getProp($target_roles, 'role');
  971. if (empty($target_role_name)) {
  972. Utils::throwError('20003:角色名称不能为空');
  973. }
  974. // 如果是删除操作
  975. if ($is_deleted == 1) {
  976. // 从角色列表中移除该角色
  977. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  978. return getProp($role, 'role') !== $target_role_name;
  979. }));
  980. // 更新角色列表
  981. $result = DB::table('mp_anime_episodes')
  982. ->where('anime_id', $anime_id)
  983. ->where('id', $episode_id)
  984. ->update([
  985. 'roles' => json_encode($roles, 256),
  986. 'updated_at' => date('Y-m-d H:i:s')
  987. ]);
  988. if ($result === false) {
  989. Utils::throwError('20003:删除角色失败');
  990. }
  991. } else {
  992. // 新增或更新操作
  993. $role_found = false;
  994. $is_new_role = false;
  995. // 查找并更新已存在的角色
  996. foreach($roles as &$role) {
  997. if (getProp($role, 'role') === $target_role_name) {
  998. $role = $target_roles;
  999. $role_found = true;
  1000. break;
  1001. }
  1002. }
  1003. // 如果角色不存在,则新增
  1004. if (!$role_found) {
  1005. $roles[] = $target_roles;
  1006. $is_new_role = true;
  1007. }
  1008. // 更新角色列表
  1009. $result = DB::table('mp_anime_episodes')
  1010. ->where('anime_id', $anime_id)
  1011. ->where('id', $episode_id)
  1012. ->update([
  1013. 'roles' => json_encode($roles, 256),
  1014. 'updated_at' => date('Y-m-d H:i:s')
  1015. ]);
  1016. if ($result === false) {
  1017. Utils::throwError('20003:更新角色列表失败');
  1018. }
  1019. // 同步更新分镜表中对应主体的音色信息
  1020. $voice_name = getProp($target_roles, 'voice_name');
  1021. $voice_type = getProp($target_roles, 'voice_type');
  1022. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1023. DB::table('mp_episode_segments')
  1024. ->where('anime_id', $anime_id)
  1025. ->where('episode_id', $episode_id)
  1026. ->where('voice_actor', $target_role_name)
  1027. ->update([
  1028. 'voice_name' => $voice_name,
  1029. 'voice_type' => $voice_type,
  1030. 'voice_audio_url' => $voice_audio_url,
  1031. 'updated_at' => date('Y-m-d H:i:s')
  1032. ]);
  1033. // 如果有关联的script_id,则同步到mp_products表
  1034. if ($script_id) {
  1035. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1036. $script = DB::table('mp_scripts')
  1037. ->where('id', $script_id)
  1038. ->where('user_id', $uid)
  1039. ->where('is_deleted', 0)
  1040. ->first();
  1041. if ($script) {
  1042. $script_name = $script->script_name ?? 'script_' . $script_id;
  1043. $product_name = getProp($target_roles, 'role');
  1044. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1045. $url = getProp($target_roles, 'url', '');
  1046. $three_view_image_url = trim(getProp($target_roles, 'three_view_image_url', ''));
  1047. // 兼容 versions 传入数组或 JSON 字符串
  1048. $versions = getProp($target_roles, 'versions', null);
  1049. if (is_string($versions) && $versions !== '') {
  1050. $decoded_versions = json_decode($versions, true);
  1051. if (is_array($decoded_versions)) {
  1052. $versions = $decoded_versions;
  1053. }
  1054. }
  1055. $product_type = 1; // 1=角色
  1056. // 查找或创建以script_name命名的文件夹
  1057. $folder = DB::table('mp_products')
  1058. ->where('cpid', $cpid)
  1059. ->where('type', 2) // 文件夹类型
  1060. ->where('product', $product_type) // 角色类型
  1061. ->where('product_name', $script_name)
  1062. ->where('parent_id', 0)
  1063. ->where('is_deleted', 0)
  1064. ->first();
  1065. if (!$folder) {
  1066. // 创建文件夹
  1067. $folder_id = DB::table('mp_products')->insertGetId([
  1068. 'user_id' => $uid,
  1069. 'cpid' => $cpid,
  1070. 'type' => 2, // 文件夹
  1071. 'product' => $product_type, // 角色类型
  1072. 'parent_id' => 0,
  1073. 'level' => 1,
  1074. 'product_name' => $script_name,
  1075. 'sort_order' => time(),
  1076. 'is_deleted' => 0,
  1077. 'created_at' => date('Y-m-d H:i:s'),
  1078. 'updated_at' => date('Y-m-d H:i:s')
  1079. ]);
  1080. } else {
  1081. $folder_id = $folder->id;
  1082. }
  1083. // 查找该文件夹下是否已存在同名资产
  1084. $existing_product = DB::table('mp_products')
  1085. ->where('cpid', $cpid)
  1086. ->where('type', 1) // 资产类型
  1087. ->where('product', $product_type)
  1088. ->where('parent_id', $folder_id)
  1089. ->where('product_name', $product_name)
  1090. ->where('is_deleted', 0)
  1091. ->first();
  1092. if ($existing_product) {
  1093. // 更新已存在的资产
  1094. $updateData = [
  1095. 'pic_task_status' => '生成成功',
  1096. ];
  1097. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1098. if ($url) $updateData['url'] = $url;
  1099. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1100. if (is_array($target_roles) && array_key_exists('three_view_image_url', $target_roles)) {
  1101. $updateData['three_view_image_url'] = trim(getProp($target_roles, 'three_view_image_url', ''));
  1102. }
  1103. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1104. if (is_array($versions)) {
  1105. $updateData['versions'] = json_encode($versions, 256);
  1106. }
  1107. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1108. DB::table('mp_products')
  1109. ->where('id', $existing_product->id)
  1110. ->update($updateData);
  1111. $product_id = $existing_product->id;
  1112. } else {
  1113. // 创建新资产
  1114. $product_id = DB::table('mp_products')->insertGetId([
  1115. 'user_id' => $uid,
  1116. 'cpid' => $cpid,
  1117. 'type' => 1, // 资产
  1118. 'product' => $product_type, // 角色
  1119. 'parent_id' => $folder_id,
  1120. 'level' => 2,
  1121. 'product_name' => $product_name,
  1122. 'url' => $url,
  1123. 'three_view_image_url' => $three_view_image_url,
  1124. 'pic_prompt' => $pic_prompt,
  1125. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1126. 'sort_order' => time(),
  1127. 'is_deleted' => 0,
  1128. 'pic_task_status' => '生成成功',
  1129. 'created_at' => date('Y-m-d H:i:s'),
  1130. 'updated_at' => date('Y-m-d H:i:s')
  1131. ]);
  1132. }
  1133. // 建立或更新绑定关系
  1134. $existing_mapping = DB::table('mp_script_product_mappings')
  1135. ->where('script_id', $script_id)
  1136. ->where('product_id', $product_id)
  1137. ->where('episode_number', $episode_number)
  1138. ->first();
  1139. if (!$existing_mapping) {
  1140. // 创建绑定关系
  1141. DB::table('mp_script_product_mappings')->insert([
  1142. 'script_id' => $script_id,
  1143. 'product_id' => $product_id,
  1144. 'episode_number' => $episode_number,
  1145. 'created_at' => date('Y-m-d H:i:s'),
  1146. 'updated_at' => date('Y-m-d H:i:s')
  1147. ]);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. } catch (\Exception $e) {
  1153. dLog('anime')->error('更新剧集角色失败', [
  1154. 'anime_id' => $anime_id,
  1155. 'episode_id' => $episode_id,
  1156. 'error' => $e->getMessage()
  1157. ]);
  1158. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1159. }
  1160. return true;
  1161. }
  1162. public function changeEpisodeScenes($data) {
  1163. $anime_id = getProp($data, 'anime_id');
  1164. $episode_id = getProp($data, 'episode_id');
  1165. $target_scenes = getProp($data, 'scenes');
  1166. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1167. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1168. // 控制字段不随场景内容写入分集scenes存储
  1169. if (is_array($target_scenes)) {
  1170. unset($target_scenes['is_deleted']);
  1171. }
  1172. // 参数验证
  1173. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1174. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1175. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1176. // 验证剧集是否存在
  1177. $episode = DB::table('mp_anime_episodes')
  1178. ->where('anime_id', $anime_id)
  1179. ->where('id', $episode_id)
  1180. ->first();
  1181. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1182. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1183. // 获取anime信息,检查是否有关联的script_id
  1184. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1185. if (!$anime) Utils::throwError('20003:动漫不存在');
  1186. $script_id = getProp($anime, 'script_id');
  1187. $episode_number = getProp($episode, 'episode_number', 1);
  1188. $uid = Site::getUid();
  1189. $cpid = Site::getCpid();
  1190. try {
  1191. $target_scene_name = getProp($target_scenes, 'scene');
  1192. if (empty($target_scene_name)) {
  1193. Utils::throwError('20003:场景名称不能为空');
  1194. }
  1195. // 如果是删除操作
  1196. if ($is_deleted == 1) {
  1197. // 从场景列表中移除该场景
  1198. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1199. return getProp($scene, 'scene') !== $target_scene_name;
  1200. }));
  1201. // 更新场景列表
  1202. $result = DB::table('mp_anime_episodes')
  1203. ->where('anime_id', $anime_id)
  1204. ->where('id', $episode_id)
  1205. ->update([
  1206. 'scenes' => json_encode($scenes, 256),
  1207. 'updated_at' => date('Y-m-d H:i:s')
  1208. ]);
  1209. if ($result === false) {
  1210. Utils::throwError('20003:删除场景失败');
  1211. }
  1212. } else {
  1213. // 新增或更新操作
  1214. $scene_found = false;
  1215. $is_new_scene = false;
  1216. // 查找并更新已存在的场景
  1217. foreach($scenes as &$scene) {
  1218. if (getProp($scene, 'scene') === $target_scene_name) {
  1219. $scene = $target_scenes;
  1220. $scene_found = true;
  1221. break;
  1222. }
  1223. }
  1224. // 如果场景不存在,则新增
  1225. if (!$scene_found) {
  1226. $scenes[] = $target_scenes;
  1227. $is_new_scene = true;
  1228. }
  1229. // 更新场景列表
  1230. $result = DB::table('mp_anime_episodes')
  1231. ->where('anime_id', $anime_id)
  1232. ->where('id', $episode_id)
  1233. ->update([
  1234. 'scenes' => json_encode($scenes, 256),
  1235. 'updated_at' => date('Y-m-d H:i:s')
  1236. ]);
  1237. if ($result === false) {
  1238. Utils::throwError('20003:更新场景列表失败');
  1239. }
  1240. // 如果有关联的script_id,则同步到mp_products表
  1241. if ($script_id) {
  1242. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1243. $script = DB::table('mp_scripts')
  1244. ->where('id', $script_id)
  1245. ->where('user_id', $uid)
  1246. ->where('is_deleted', 0)
  1247. ->first();
  1248. if ($script) {
  1249. $script_name = $script->script_name ?? 'script_' . $script_id;
  1250. $product_name = getProp($target_scenes, 'scene');
  1251. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1252. $url = getProp($target_scenes, 'url', '');
  1253. $three_view_image_url = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1254. // 兼容 versions 传入数组或 JSON 字符串
  1255. $versions = getProp($target_scenes, 'versions', null);
  1256. if (is_string($versions) && $versions !== '') {
  1257. $decoded_versions = json_decode($versions, true);
  1258. if (is_array($decoded_versions)) {
  1259. $versions = $decoded_versions;
  1260. }
  1261. }
  1262. $product_type = 2; // 2=场景
  1263. // 查找或创建以script_name命名的文件夹
  1264. $folder = DB::table('mp_products')
  1265. ->where('cpid', $cpid)
  1266. ->where('type', 2) // 文件夹类型
  1267. ->where('product', $product_type) // 场景类型
  1268. ->where('product_name', $script_name)
  1269. ->where('parent_id', 0)
  1270. ->where('is_deleted', 0)
  1271. ->first();
  1272. if (!$folder) {
  1273. // 创建文件夹
  1274. $folder_id = DB::table('mp_products')->insertGetId([
  1275. 'user_id' => $uid,
  1276. 'cpid' => $cpid,
  1277. 'type' => 2, // 文件夹
  1278. 'product' => $product_type, // 场景类型
  1279. 'parent_id' => 0,
  1280. 'level' => 1,
  1281. 'product_name' => $script_name,
  1282. 'sort_order' => time(),
  1283. 'is_deleted' => 0,
  1284. 'created_at' => date('Y-m-d H:i:s'),
  1285. 'updated_at' => date('Y-m-d H:i:s')
  1286. ]);
  1287. } else {
  1288. $folder_id = $folder->id;
  1289. }
  1290. // 查找该文件夹下是否已存在同名资产
  1291. $existing_product = DB::table('mp_products')
  1292. ->where('cpid', $cpid)
  1293. ->where('type', 1) // 资产类型
  1294. ->where('product', $product_type)
  1295. ->where('parent_id', $folder_id)
  1296. ->where('product_name', $product_name)
  1297. ->where('is_deleted', 0)
  1298. ->first();
  1299. if ($existing_product) {
  1300. // 更新已存在的资产
  1301. $updateData = [
  1302. 'pic_task_status' => '生成成功'
  1303. ];
  1304. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1305. if ($url) $updateData['url'] = $url;
  1306. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1307. if (is_array($target_scenes) && array_key_exists('three_view_image_url', $target_scenes)) {
  1308. $updateData['three_view_image_url'] = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1309. }
  1310. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1311. if (is_array($versions)) {
  1312. $updateData['versions'] = json_encode($versions, 256);
  1313. }
  1314. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1315. DB::table('mp_products')
  1316. ->where('id', $existing_product->id)
  1317. ->update($updateData);
  1318. $product_id = $existing_product->id;
  1319. } else {
  1320. // 创建新资产
  1321. $product_id = DB::table('mp_products')->insertGetId([
  1322. 'user_id' => $uid,
  1323. 'cpid' => $cpid,
  1324. 'type' => 1, // 资产
  1325. 'product' => $product_type, // 场景
  1326. 'parent_id' => $folder_id,
  1327. 'level' => 2,
  1328. 'product_name' => $product_name,
  1329. 'url' => $url,
  1330. 'three_view_image_url' => $three_view_image_url,
  1331. 'pic_prompt' => $pic_prompt,
  1332. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1333. 'sort_order' => time(),
  1334. 'is_deleted' => 0,
  1335. 'pic_task_status' => '生成成功',
  1336. 'created_at' => date('Y-m-d H:i:s'),
  1337. 'updated_at' => date('Y-m-d H:i:s')
  1338. ]);
  1339. }
  1340. // 建立或更新绑定关系
  1341. $existing_mapping = DB::table('mp_script_product_mappings')
  1342. ->where('script_id', $script_id)
  1343. ->where('product_id', $product_id)
  1344. ->where('episode_number', $episode_number)
  1345. ->first();
  1346. if (!$existing_mapping) {
  1347. // 创建绑定关系
  1348. DB::table('mp_script_product_mappings')->insert([
  1349. 'script_id' => $script_id,
  1350. 'product_id' => $product_id,
  1351. 'episode_number' => $episode_number,
  1352. 'created_at' => date('Y-m-d H:i:s'),
  1353. 'updated_at' => date('Y-m-d H:i:s')
  1354. ]);
  1355. }
  1356. }
  1357. }
  1358. }
  1359. } catch (\Exception $e) {
  1360. dLog('anime')->error('更新剧集场景失败', [
  1361. 'anime_id' => $anime_id,
  1362. 'episode_id' => $episode_id,
  1363. 'error' => $e->getMessage()
  1364. ]);
  1365. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1366. }
  1367. return true;
  1368. }
  1369. public function changeEpisodeProps($data) {
  1370. $anime_id = getProp($data, 'anime_id');
  1371. $episode_id = getProp($data, 'episode_id');
  1372. $target_props = getProp($data, 'props');
  1373. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1374. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1375. // 控制字段不随道具内容写入分集props存储
  1376. if (is_array($target_props)) {
  1377. unset($target_props['is_deleted']);
  1378. }
  1379. // 参数验证
  1380. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1381. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1382. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1383. // 验证剧集是否存在
  1384. $episode = DB::table('mp_anime_episodes')
  1385. ->where('anime_id', $anime_id)
  1386. ->where('id', $episode_id)
  1387. ->first();
  1388. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1389. $props = json_decode(getProp($episode, 'props'), true);
  1390. // 获取anime信息,检查是否有关联的script_id
  1391. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1392. if (!$anime) Utils::throwError('20003:动漫不存在');
  1393. $script_id = getProp($anime, 'script_id');
  1394. $episode_number = getProp($episode, 'episode_number', 1);
  1395. $uid = Site::getUid();
  1396. $cpid = Site::getCpid();
  1397. try {
  1398. $target_prop_name = getProp($target_props, 'prop');
  1399. if (empty($target_prop_name)) {
  1400. Utils::throwError('20003:道具名称不能为空');
  1401. }
  1402. // 如果是删除操作
  1403. if ($is_deleted == 1) {
  1404. // 从道具列表中移除该道具
  1405. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1406. return getProp($prop, 'prop') !== $target_prop_name;
  1407. }));
  1408. // 更新道具列表
  1409. $result = DB::table('mp_anime_episodes')
  1410. ->where('anime_id', $anime_id)
  1411. ->where('id', $episode_id)
  1412. ->update([
  1413. 'props' => json_encode($props, 256),
  1414. 'updated_at' => date('Y-m-d H:i:s')
  1415. ]);
  1416. if ($result === false) {
  1417. Utils::throwError('20003:删除道具失败');
  1418. }
  1419. } else {
  1420. // 新增或更新操作
  1421. $prop_found = false;
  1422. $is_new_prop = false;
  1423. // 查找并更新已存在的道具
  1424. foreach($props as &$prop) {
  1425. if (getProp($prop, 'prop') === $target_prop_name) {
  1426. $prop = $target_props;
  1427. $prop_found = true;
  1428. break;
  1429. }
  1430. }
  1431. // 如果道具不存在,则新增
  1432. if (!$prop_found) {
  1433. $props[] = $target_props;
  1434. $is_new_prop = true;
  1435. }
  1436. // 更新道具列表
  1437. $result = DB::table('mp_anime_episodes')
  1438. ->where('anime_id', $anime_id)
  1439. ->where('id', $episode_id)
  1440. ->update([
  1441. 'props' => json_encode($props, 256),
  1442. 'updated_at' => date('Y-m-d H:i:s')
  1443. ]);
  1444. if ($result === false) {
  1445. Utils::throwError('20003:更新道具列表失败');
  1446. }
  1447. // 如果有关联的script_id,则同步到mp_products表
  1448. if ($script_id) {
  1449. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1450. $script = DB::table('mp_scripts')
  1451. ->where('id', $script_id)
  1452. ->where('user_id', $uid)
  1453. ->where('is_deleted', 0)
  1454. ->first();
  1455. if ($script) {
  1456. $script_name = $script->script_name ?? 'script_' . $script_id;
  1457. $product_name = getProp($target_props, 'prop');
  1458. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1459. $url = getProp($target_props, 'url', '');
  1460. $three_view_image_url = trim(getProp($target_props, 'three_view_image_url', ''));
  1461. // 兼容 versions 传入数组或 JSON 字符串
  1462. $versions = getProp($target_props, 'versions', null);
  1463. if (is_string($versions) && $versions !== '') {
  1464. $decoded_versions = json_decode($versions, true);
  1465. if (is_array($decoded_versions)) {
  1466. $versions = $decoded_versions;
  1467. }
  1468. }
  1469. $product_type = 3; // 3=道具
  1470. // 查找或创建以script_name命名的文件夹
  1471. $folder = DB::table('mp_products')
  1472. ->where('cpid', $cpid)
  1473. ->where('type', 2) // 文件夹类型
  1474. ->where('product', $product_type) // 道具类型
  1475. ->where('product_name', $script_name)
  1476. ->where('parent_id', 0)
  1477. ->where('is_deleted', 0)
  1478. ->first();
  1479. if (!$folder) {
  1480. // 创建文件夹
  1481. $folder_id = DB::table('mp_products')->insertGetId([
  1482. 'user_id' => $uid,
  1483. 'cpid' => $cpid,
  1484. 'type' => 2, // 文件夹
  1485. 'product' => $product_type, // 道具类型
  1486. 'parent_id' => 0,
  1487. 'level' => 1,
  1488. 'product_name' => $script_name,
  1489. 'sort_order' => time(),
  1490. 'is_deleted' => 0,
  1491. 'created_at' => date('Y-m-d H:i:s'),
  1492. 'updated_at' => date('Y-m-d H:i:s')
  1493. ]);
  1494. } else {
  1495. $folder_id = $folder->id;
  1496. }
  1497. // 查找该文件夹下是否已存在同名资产
  1498. $existing_product = DB::table('mp_products')
  1499. ->where('cpid', $cpid)
  1500. ->where('type', 1) // 资产类型
  1501. ->where('product', $product_type)
  1502. ->where('parent_id', $folder_id)
  1503. ->where('product_name', $product_name)
  1504. ->where('is_deleted', 0)
  1505. ->first();
  1506. if ($existing_product) {
  1507. // 更新已存在的资产
  1508. $updateData = [
  1509. 'pic_task_status' => '生成成功'
  1510. ];
  1511. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1512. if ($url) $updateData['url'] = $url;
  1513. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1514. if (is_array($target_props) && array_key_exists('three_view_image_url', $target_props)) {
  1515. $updateData['three_view_image_url'] = trim(getProp($target_props, 'three_view_image_url', ''));
  1516. }
  1517. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1518. if (is_array($versions)) {
  1519. $updateData['versions'] = json_encode($versions, 256);
  1520. }
  1521. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1522. DB::table('mp_products')
  1523. ->where('id', $existing_product->id)
  1524. ->update($updateData);
  1525. $product_id = $existing_product->id;
  1526. } else {
  1527. // 创建新资产
  1528. $product_id = DB::table('mp_products')->insertGetId([
  1529. 'user_id' => $uid,
  1530. 'cpid' => $cpid,
  1531. 'type' => 1, // 资产
  1532. 'product' => $product_type, // 道具
  1533. 'parent_id' => $folder_id,
  1534. 'level' => 2,
  1535. 'product_name' => $product_name,
  1536. 'url' => $url,
  1537. 'three_view_image_url' => $three_view_image_url,
  1538. 'pic_prompt' => $pic_prompt,
  1539. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1540. 'sort_order' => time(),
  1541. 'is_deleted' => 0,
  1542. 'pic_task_status' => '生成成功',
  1543. 'created_at' => date('Y-m-d H:i:s'),
  1544. 'updated_at' => date('Y-m-d H:i:s')
  1545. ]);
  1546. }
  1547. // 建立或更新绑定关系
  1548. $existing_mapping = DB::table('mp_script_product_mappings')
  1549. ->where('script_id', $script_id)
  1550. ->where('product_id', $product_id)
  1551. ->where('episode_number', $episode_number)
  1552. ->first();
  1553. if (!$existing_mapping) {
  1554. // 创建绑定关系
  1555. DB::table('mp_script_product_mappings')->insert([
  1556. 'script_id' => $script_id,
  1557. 'product_id' => $product_id,
  1558. 'episode_number' => $episode_number,
  1559. 'created_at' => date('Y-m-d H:i:s'),
  1560. 'updated_at' => date('Y-m-d H:i:s')
  1561. ]);
  1562. }
  1563. }
  1564. }
  1565. }
  1566. } catch (\Exception $e) {
  1567. dLog('anime')->error('更新剧集道具失败', [
  1568. 'anime_id' => $anime_id,
  1569. 'episode_id' => $episode_id,
  1570. 'error' => $e->getMessage()
  1571. ]);
  1572. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1573. }
  1574. return true;
  1575. }
  1576. public function editSegment($data) {
  1577. $segment_id = getProp($data, 'segment_id');
  1578. $segment_content = getProp($data, 'segment_content');
  1579. $image_url = getProp($data, 'image_url');
  1580. $video_url = getProp($data, 'video_url');
  1581. // 参数验证
  1582. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1583. // 验证分镜是否存在
  1584. $segment = DB::table('mp_episode_segments')
  1585. ->where('segment_id', $segment_id)
  1586. ->first();
  1587. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1588. $dubTaskId = 0;
  1589. try {
  1590. DB::beginTransaction();
  1591. // 准备更新数据
  1592. $update_data = [
  1593. 'updated_at' => date('Y-m-d H:i:s')
  1594. ];
  1595. if ($segment_content) {
  1596. // 先将segment_content赋值到update_data
  1597. $update_data['segment_content'] = $segment_content;
  1598. // 使用现有方法分析segment_content,提取各个字段
  1599. $this->handleSegmentContent($update_data);
  1600. // 如果有对话内容,创建视频配音合成任务
  1601. $dialogue = getProp($update_data, 'dialogue');
  1602. if (!empty($dialogue)) {
  1603. $now = date('Y-m-d H:i:s');
  1604. $generate_json = [
  1605. 'text' => $dialogue,
  1606. 'role' => getProp($update_data, 'voice_actor'),
  1607. 'voice_type' => getProp($update_data, 'voice_type'),
  1608. 'voice_name' => getProp($update_data, 'voice_name'),
  1609. 'emotion' => getProp($update_data, 'emotion'),
  1610. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1611. 'gender' => getProp($update_data, 'gender'),
  1612. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1613. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1614. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1615. 'pitch' => getProp($update_data, 'pitch', 0),
  1616. ];
  1617. // 插入视频配音合成任务
  1618. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1619. 'alias_segment_id' => $segment_id,
  1620. 'generate_status' => '执行中',
  1621. 'audio_url' => '',
  1622. 'generate_json' => json_encode($generate_json, 256),
  1623. 'created_at' => $now,
  1624. 'updated_at' => $now,
  1625. ]);
  1626. if (!$dubTaskId) {
  1627. Utils::throwError('20003:创建配音任务失败!');
  1628. }
  1629. $update_data['audio_url'] = '';
  1630. } else {
  1631. // dialogue为空时,直接写入默认音频信息
  1632. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1633. $update_data['audio_duration'] = 2.0;
  1634. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1635. }
  1636. }
  1637. if ($image_url) {
  1638. $update_data['img_url'] = $image_url;
  1639. // 同时写入一个简单的图片生成任务
  1640. $pic_task = [
  1641. 'alias_segment_id' => $segment_id,
  1642. 'ref_img_url' => json_encode([]),
  1643. 'status' => 'success',
  1644. 'result_url' => json_encode([$image_url], 256),
  1645. 'model' => '',
  1646. 'created_at' => date('Y-m-d H:i:s'),
  1647. 'updated_at' => date('Y-m-d H:i:s'),
  1648. ];
  1649. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1650. }
  1651. if ($video_url) {
  1652. $update_data['origin_video_url'] = $video_url;
  1653. $compressed_video_url = compressVideo($video_url);
  1654. $update_data['current_type'] = 2;
  1655. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1656. // 同时写入一个简单的视频生成任务
  1657. $video_task = [
  1658. 'alias_segment_id' => $segment_id,
  1659. 'status' => 'success',
  1660. 'result_url' => $update_data['origin_video_url'],
  1661. 'compressed_url' => $update_data['video_url'],
  1662. 'created_at' => date('Y-m-d H:i:s'),
  1663. 'updated_at' => date('Y-m-d H:i:s'),
  1664. ];
  1665. DB::table('mp_generate_video_tasks')->insert($video_task);
  1666. }
  1667. // 更新分镜信息
  1668. $result = DB::table('mp_episode_segments')
  1669. ->where('segment_id', $segment_id)
  1670. ->update($update_data);
  1671. if ($result === false) {
  1672. Utils::throwError('20003:更新分镜剧本失败');
  1673. }
  1674. DB::commit();
  1675. // 如果有创建音频生成任务则调用API
  1676. if ($dubTaskId) {
  1677. // 请求远程服务器执行生成
  1678. $client = new Client(['timeout' => 300, 'verify' => false]);
  1679. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1680. $response = $result->getBody()->getContents();
  1681. $response_arr = json_decode($response, true);
  1682. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1683. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1684. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1685. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1686. Utils::throwError('20003:火山生成音频失败');
  1687. }
  1688. }
  1689. return true;
  1690. } catch (\Exception $e) {
  1691. DB::rollBack();
  1692. dLog('anime')->error('更新分镜剧本失败', [
  1693. 'segment_id' => $segment_id,
  1694. 'error' => $e->getMessage()
  1695. ]);
  1696. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1697. }
  1698. }
  1699. public function batchSetSegmentPics($data) {
  1700. $anime_id = getProp($data, 'anime_id');
  1701. $episode_id = getProp($data, 'episode_id');
  1702. $ratio = getProp($data, 'ratio');
  1703. $dimensions = $this->getRatioDimensions($ratio);
  1704. $width = $dimensions['width'];
  1705. $height = $dimensions['height'];
  1706. if (!$anime_id || !$episode_id) {
  1707. Utils::throwError('1002:请选择剧集');
  1708. }
  1709. // 获取剧集信息
  1710. $episode = DB::table('mp_anime_episodes')
  1711. ->where('anime_id', $anime_id)
  1712. ->where('id', $episode_id)
  1713. ->where('is_default', 1)
  1714. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1715. ->first();
  1716. if (!$episode) {
  1717. Utils::throwError('20003:该剧集不存在');
  1718. }
  1719. $model = getProp($data, 'model');
  1720. if (!$model) {
  1721. $model = getProp($episode, 'image_model');
  1722. if (!$model) {
  1723. // episode表也没有,使用默认值
  1724. $model = 'gpt-image-2';
  1725. }
  1726. }
  1727. // 验证模型是否在可用模型表中
  1728. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1729. $model = 'gpt-image-2';
  1730. }
  1731. $roles = json_decode(getProp($episode, 'roles'), true);
  1732. if (!$roles) {
  1733. Utils::throwError('20003:角色信息格式错误');
  1734. }
  1735. // 构建角色名称到参考图的映射
  1736. $role_map = [];
  1737. foreach ($roles as $role) {
  1738. $role_name = getProp($role, 'role');
  1739. $role_url = getProp($role, 'url');
  1740. if (!empty($role_name) && !empty($role_url)) {
  1741. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1742. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1743. // $role_map[$base_name] = $role_url;
  1744. // 同时保存完整名称的映射
  1745. $role_map[$role_name] = $role_url;
  1746. }
  1747. }
  1748. $scenes = json_decode(getProp($episode, 'roles'), true);
  1749. if (!$scenes) {
  1750. Utils::throwError('20003:场景信息格式错误');
  1751. }
  1752. // 构建角色名称到参考图的映射
  1753. $scene_map = [];
  1754. foreach ($scenes as $scene) {
  1755. $scene_name = getProp($scene, 'scene');
  1756. $scene_url = getProp($scene, 'url');
  1757. if (!empty($scene_name) && !empty($scene_url)) {
  1758. $scene_map[$scene_name] = $scene_url;
  1759. }
  1760. }
  1761. // 获取所有分镜信息
  1762. $segments = DB::table('mp_episode_segments')
  1763. ->where('anime_id', $anime_id)
  1764. ->where('episode_id', $episode_id)
  1765. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1766. ->orderBy('segment_number')
  1767. ->get()
  1768. ->toArray();
  1769. if (empty($segments)) {
  1770. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1771. }
  1772. // 保存图片比例
  1773. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1774. $updated_segments = [];
  1775. $failed_segments = [];
  1776. // 批量为每个分镜生成图片任务
  1777. foreach ($segments as $segment) {
  1778. $segment_id = $segment->segment_id;
  1779. $segment_content = $segment->segment_content;
  1780. if (empty($segment_content)) {
  1781. $failed_segments[] = [
  1782. 'segment_id' => $segment_id,
  1783. 'error' => '分镜内容为空'
  1784. ];
  1785. continue;
  1786. }
  1787. try {
  1788. $dubTaskId = 0;
  1789. // 解析分镜内容,提取画面描述作为主要提示词
  1790. $prompt = $segment_content;
  1791. $ref_img_urls = [];
  1792. // 分镜场景
  1793. $scene = getProp($segment, 'scene');
  1794. $matched_scene = '';
  1795. if (isset($scene_map[$scene])) {
  1796. $img_index = count($ref_img_urls) + 1;
  1797. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1798. $ref_img_urls[] = $scene_map[$scene];
  1799. $matched_scene = $scene;
  1800. }
  1801. // 分镜角色
  1802. $characters = getProp($segment, 'characters');
  1803. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1804. $roles = explode(',', $characters);
  1805. // 从分镜内容中提取涉及的角色
  1806. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1807. // 获取匹配角色的参考图
  1808. foreach ($segment_characters as $character) {
  1809. if (isset($role_map[$character])) {
  1810. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1811. $img_index = count($ref_img_urls) + 1;
  1812. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1813. $ref_img_urls[] = $role_map[$character];
  1814. }
  1815. }
  1816. // 如果没有找到匹配的角色参考图,不使用参考图
  1817. if (empty($ref_img_urls)) {
  1818. $ref_img_urls = [];
  1819. }
  1820. // 准备生成任务参数
  1821. $params = [
  1822. 'model' => $model,
  1823. 'alias_segment_id' => $segment_id,
  1824. 'prompt' => $prompt,
  1825. 'ref_img_urls' => $ref_img_urls,
  1826. 'width' => $width,
  1827. 'height' => $height,
  1828. ];
  1829. // 优化提示词(不要生成字幕)
  1830. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1831. // $task_id = mt_rand(100000, 999999);
  1832. // 调用AI图片生成服务
  1833. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1834. $task_id = $task->id;
  1835. if (!$task_id) {
  1836. $failed_segments[] = [
  1837. 'segment_id' => $segment_id,
  1838. 'error' => '创建生成任务失败'
  1839. ];
  1840. continue;
  1841. }
  1842. $update_data = [
  1843. 'pic_task_id' => $task_id,
  1844. 'pic_task_status' => '生成中',
  1845. 'audio_url' => '',
  1846. 'updated_at' => date('Y-m-d H:i:s')
  1847. ];
  1848. // 如果有对话内容,创建视频配音合成任务
  1849. $dialogue = getProp($segment, 'dialogue');
  1850. if (!empty($dialogue)) {
  1851. $now = date('Y-m-d H:i:s');
  1852. $generate_json = [
  1853. 'text' => $dialogue,
  1854. 'role' => getProp($segment, 'voice_actor'),
  1855. 'voice_type' => getProp($segment, 'voice_type'),
  1856. 'voice_name' => getProp($segment, 'voice_name'),
  1857. 'emotion' => getProp($segment, 'emotion'),
  1858. 'emotion_type' => getProp($segment, 'emotion_type'),
  1859. 'gender' => getProp($segment, 'gender'),
  1860. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1861. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1862. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1863. 'pitch' => getProp($segment, 'pitch', 0),
  1864. ];
  1865. // 插入视频配音合成任务
  1866. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1867. 'alias_segment_id' => $segment_id,
  1868. 'generate_status' => '执行中',
  1869. 'audio_url' => '',
  1870. 'generate_json' => json_encode($generate_json, 256),
  1871. 'created_at' => $now,
  1872. 'updated_at' => $now,
  1873. ]);
  1874. if (!$dubTaskId) {
  1875. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1876. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1877. // Utils::throwError('20003:创建配音任务失败!');
  1878. }
  1879. } else {
  1880. // dialogue为空时,直接写入默认音频信息到分镜表
  1881. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1882. $update_data['audio_duration'] = 2.0;
  1883. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1884. }
  1885. // 更新分镜的任务信息
  1886. $update_result = DB::table('mp_episode_segments')
  1887. ->where('segment_id', $segment_id)
  1888. ->update($update_data);
  1889. // 如果是第一集的首帧图片,则存入待更新数组
  1890. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1891. Redis::sadd('anime_first_frame_urls', $segment_id);
  1892. }
  1893. if ($update_result) {
  1894. $updated_segments[] = [
  1895. 'segment_id' => $segment_id,
  1896. 'task_id' => $task_id,
  1897. 'status' => '生成中',
  1898. 'matched_scenes' => $matched_scene,
  1899. 'matched_roles' => $segment_characters,
  1900. 'ref_urls_count' => count($ref_img_urls)
  1901. ];
  1902. } else {
  1903. $failed_segments[] = [
  1904. 'segment_id' => $segment_id,
  1905. 'error' => '更新分镜任务状态失败'
  1906. ];
  1907. }
  1908. if ($dubTaskId) {
  1909. sleep(1);
  1910. // 请求远程服务器执行生成
  1911. $client = new Client(['timeout' => 300, 'verify' => false]);
  1912. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1913. $response = $result->getBody()->getContents();
  1914. $response_arr = json_decode($response, true);
  1915. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1916. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1917. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1918. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1919. }
  1920. }
  1921. } catch (\Exception $e) {
  1922. $failed_segments[] = [
  1923. 'segment_id' => $segment_id,
  1924. 'error' => $e->getMessage()
  1925. ];
  1926. }
  1927. }
  1928. // 更新剧集生成状态
  1929. if (!empty($updated_segments)) {
  1930. DB::table('mp_anime_episodes')
  1931. ->where('id', $episode_id)
  1932. ->update([
  1933. 'is_generated' => 1,
  1934. 'updated_at' => date('Y-m-d H:i:s')
  1935. ]);
  1936. }
  1937. return [
  1938. 'success_count' => count($updated_segments),
  1939. 'failed_count' => count($failed_segments),
  1940. 'success_segments' => $updated_segments,
  1941. 'failed_segments' => $failed_segments,
  1942. 'total_segments' => count($segments)
  1943. ];
  1944. }
  1945. public function reGenerateSegment($data) {
  1946. $segment_id = getProp($data, 'segment_id');
  1947. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1948. $anime_id = getProp($segment, 'anime_id');
  1949. $episode_id = getProp($segment, 'episode_id');
  1950. $episode_number = getProp($segment, 'episode_number');
  1951. $segment_content = getProp($data, 'segment_content');
  1952. $ratio = getProp($data, 'ratio');
  1953. if (!$ratio) {
  1954. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1955. if (!$ratio) $ratio = '9:16';
  1956. }
  1957. $dimensions = $this->getRatioDimensions($ratio);
  1958. $width = $dimensions['width'];
  1959. $height = $dimensions['height'];
  1960. if (!$anime_id || !$episode_id) {
  1961. Utils::throwError('1002:请选择分镜');
  1962. }
  1963. // 使用文生文模型重新解析segment_content
  1964. if (!empty($segment_content)) {
  1965. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1966. }
  1967. // 获取动漫的角色信息(包含参考图)
  1968. $anime = DB::table('mp_animes')
  1969. ->where('id', $anime_id)
  1970. ->select('roles', 'scenes')
  1971. ->first();
  1972. if (!$anime || !$anime->roles) {
  1973. Utils::throwError('20003:未找到角色信息');
  1974. }
  1975. $roles = json_decode($anime->roles, true);
  1976. if (!$roles) {
  1977. Utils::throwError('20003:角色信息格式错误');
  1978. }
  1979. // 构建角色名称到参考图的映射
  1980. $role_map = [];
  1981. foreach ($roles as $role) {
  1982. $role_name = getProp($role, 'role');
  1983. $role_url = getProp($role, 'url');
  1984. if (!empty($role_name) && !empty($role_url)) {
  1985. $role_map[$role_name] = $role_url;
  1986. }
  1987. }
  1988. $scenes = json_decode($anime->scenes, true);
  1989. if (!$scenes) {
  1990. Utils::throwError('20003:角色信息格式错误');
  1991. }
  1992. // 构建角色名称到参考图的映射
  1993. $scene_map = [];
  1994. foreach ($scenes as $scene) {
  1995. $scene_name = getProp($scene, 'scene');
  1996. $scene_url = getProp($scene, 'url');
  1997. if (!empty($scene_name) && !empty($scene_url)) {
  1998. $scene_map[$scene_name] = $scene_url;
  1999. }
  2000. }
  2001. $segment_id = $segment->segment_id;
  2002. $original_segment_content = $segment->segment_content;
  2003. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2004. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2005. if (empty($final_segment_content)) {
  2006. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2007. }
  2008. try {
  2009. $dubTaskId = 0;
  2010. // 分镜剧本数组
  2011. $update_data = [
  2012. 'segment_content' => $final_segment_content,
  2013. 'pic_task_status' => '生成中',
  2014. 'updated_at' => date('Y-m-d H:i:s')
  2015. ];
  2016. // 解析分镜内容,提取画面描述作为主要提示词
  2017. $prompt = $final_segment_content;
  2018. $ref_img_urls = [];
  2019. // 分镜场景
  2020. $scene = getProp($data, 'scene');
  2021. if ($scene) {
  2022. $matched_scene = '';
  2023. if (isset($scene_map[$scene])) {
  2024. $img_index = count($ref_img_urls) + 1;
  2025. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2026. $ref_img_urls[] = $scene_map[$scene];
  2027. $matched_scene = $scene;
  2028. }
  2029. $update_data['scene'] = $scene;
  2030. }
  2031. // 分镜角色
  2032. $characters = getProp($data, 'characters');
  2033. if ($characters) {
  2034. $update_data['characters'] = $characters;
  2035. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2036. $characters = explode(',', $characters);
  2037. // 从分镜内容中提取涉及的角色
  2038. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2039. // 获取匹配角色的参考图
  2040. foreach ($segment_characters as $character) {
  2041. if (isset($role_map[$character])) {
  2042. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2043. $img_index = count($ref_img_urls) + 1;
  2044. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2045. $ref_img_urls[] = $role_map[$character];
  2046. }
  2047. }
  2048. }
  2049. // 如果没有找到匹配的角色参考图,不使用参考图
  2050. if (empty($ref_img_urls)) {
  2051. $ref_img_urls = [];
  2052. }
  2053. // 准备生成任务参数
  2054. $params = [
  2055. 'alias_segment_id' => $segment_id,
  2056. 'prompt' => $prompt,
  2057. 'ref_img_urls' => $ref_img_urls,
  2058. 'width' => $width,
  2059. 'height' => $height,
  2060. ];
  2061. // 优化提示词(不要生成字幕)
  2062. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2063. // 调用AI图片生成服务
  2064. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2065. $task_id = $task->id;
  2066. if (!$task_id) {
  2067. Utils::throwError('20003:创建生成任务失败!');
  2068. }
  2069. $update_data['pic_task_id'] = $task_id;
  2070. // 更新分镜剧本信息
  2071. $this->handleSegmentContent($update_data);
  2072. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2073. if ($segment_content) {
  2074. $dialogue = getProp($update_data, 'dialogue');
  2075. if (!empty($dialogue)) {
  2076. $now = date('Y-m-d H:i:s');
  2077. $generate_json = [
  2078. 'text' => $dialogue,
  2079. 'role' => getProp($update_data, 'voice_actor'),
  2080. 'voice_type' => getProp($update_data, 'voice_type'),
  2081. 'voice_name' => getProp($update_data, 'voice_name'),
  2082. 'emotion' => getProp($update_data, 'emotion'),
  2083. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2084. 'gender' => getProp($update_data, 'gender'),
  2085. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2086. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2087. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2088. 'pitch' => getProp($update_data, 'pitch', 0),
  2089. ];
  2090. // 插入视频配音合成任务
  2091. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2092. 'alias_segment_id' => $segment_id,
  2093. 'generate_status' => '执行中',
  2094. 'audio_url' => '',
  2095. 'generate_json' => json_encode($generate_json, 256),
  2096. 'created_at' => date('Y-m-d H:i:s'),
  2097. 'updated_at' => date('Y-m-d H:i:s'),
  2098. ]);
  2099. if (!$dubTaskId) {
  2100. Utils::throwError('20003:创建配音任务失败!');
  2101. }
  2102. $update_data['audio_url'] = '';
  2103. } else {
  2104. // dialogue为空时,直接写入默认音频信息
  2105. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2106. $update_data['audio_duration'] = 2.0;
  2107. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2108. }
  2109. }
  2110. $boolen = DB::table('mp_episode_segments')
  2111. ->where('segment_id', $segment_id)
  2112. ->update($update_data);
  2113. // 如果是第一集的首帧图片,则存入待更新数组
  2114. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2115. Redis::sadd('anime_first_frame_urls', $segment_id);
  2116. }
  2117. if ($dubTaskId) {
  2118. // 请求远程服务器执行生成
  2119. $client = new Client(['timeout' => 300, 'verify' => false]);
  2120. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2121. $response = $result->getBody()->getContents();
  2122. $response_arr = json_decode($response, true);
  2123. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2124. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2125. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2126. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2127. Utils::throwError('20003:火山生成音频失败');
  2128. }
  2129. }
  2130. } catch (\Exception $e) {
  2131. $failed_segments[] = [
  2132. 'segment_id' => $segment_id,
  2133. 'error' => $e->getMessage()
  2134. ];
  2135. }
  2136. // 创建任务之后先暂停10s等待异步任务完成
  2137. sleep(10);
  2138. $img_url = $this->loopGetPicTaskResult($task_id);
  2139. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2140. // 图片生成后新增对话记录
  2141. try {
  2142. $uid = Site::getUid();
  2143. $now = date('Y-m-d H:i:s');
  2144. // 使用AI反推图片提示词
  2145. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2146. // 保存对话记录
  2147. $records = [
  2148. [
  2149. 'uid' => $uid,
  2150. 'anime_id' => $anime_id,
  2151. 'sequence' => $episode_number,
  2152. 'role' => 'user',
  2153. 'content' => '重新生成',
  2154. 'segment_id' => $segment_id,
  2155. 'pic_task_id' => $task_id,
  2156. 'image_url' => '',
  2157. 'created_at' => $now,
  2158. 'updated_at' => $now
  2159. ],
  2160. [
  2161. 'uid' => $uid,
  2162. 'anime_id' => $anime_id,
  2163. 'sequence' => $episode_number,
  2164. 'role' => 'assistant',
  2165. 'content' => $pic_prompt,
  2166. 'segment_id' => $segment_id,
  2167. 'pic_task_id' => $task_id,
  2168. 'image_url' => $img_url,
  2169. 'created_at' => $now,
  2170. 'updated_at' => $now
  2171. ]
  2172. ];
  2173. DB::table('mp_anime_records')->insert($records);
  2174. } catch (\Exception $e) {
  2175. // 记录日志但不影响主流程
  2176. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2177. 'segment_id' => $segment_id,
  2178. 'img_url' => $img_url
  2179. ]);
  2180. }
  2181. return $img_url;
  2182. }
  2183. public function addSegment($data) {
  2184. $prev_segment_id = getProp($data, 'prev_segment_id');
  2185. $img_url = getProp($data, 'img_url');
  2186. $video_url = getProp($data, 'video_url');
  2187. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2188. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2189. $anime_id = getProp($segment, 'anime_id');
  2190. $episode_id = getProp($segment, 'episode_id');
  2191. $episode_number = getProp($segment, 'episode_number');
  2192. $segment_number = getProp($segment, 'segment_number');
  2193. $new_segment_number = $segment_number + 1;
  2194. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2195. // 分镜剧本数组
  2196. $insert_data = [
  2197. 'anime_id' => $anime_id,
  2198. 'episode_id' => $episode_id,
  2199. 'episode_number' => $episode_number,
  2200. 'act_number' => getProp($segment, 'act_number'),
  2201. 'act_title' => getProp($segment, 'act_title'),
  2202. 'segment_id' => $segment_id,
  2203. 'segment_number' => $new_segment_number,
  2204. 'segment_content' => '',
  2205. 'img_url' => '',
  2206. 'video_url' => '',
  2207. 'created_at' => date('Y-m-d H:i:s'),
  2208. 'updated_at' => date('Y-m-d H:i:s')
  2209. ];
  2210. if ($img_url) $insert_data['img_url'] = $img_url;
  2211. if ($video_url) {
  2212. $insert_data['origin_video_url'] = $video_url;
  2213. $insert_data['current_type'] = 2;
  2214. $compressed_video_url = compressVideo($video_url);
  2215. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2216. }
  2217. try {
  2218. DB::beginTransaction();
  2219. // 先更新序号
  2220. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2221. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2222. if (!$id) {
  2223. Utils::throwError('20003:新增分镜失败!');
  2224. }
  2225. }catch (\Exception $e) {
  2226. DB::rollBack();
  2227. Utils::throwError('20003:'.$e->getMessage());
  2228. }
  2229. DB::commit();
  2230. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2231. $segment = $segment ? (array)$segment : [];
  2232. return $segment;
  2233. // 以下代码暂弃用
  2234. $anime_id = getProp($segment, 'anime_id');
  2235. $episode_id = getProp($segment, 'episode_id');
  2236. $episode_number = getProp($segment, 'episode_number');
  2237. $segment_number = getProp($segment, 'segment_number');
  2238. $segment_content = getProp($data, 'segment_content');
  2239. $img_url = getProp($data, 'img_url');
  2240. $video_url = getProp($data, 'video_url');
  2241. $ratio = getProp($data, 'ratio');
  2242. $dimensions = $this->getRatioDimensions($ratio);
  2243. $width = $dimensions['width'];
  2244. $height = $dimensions['height'];
  2245. if (!$anime_id || !$episode_id) {
  2246. Utils::throwError('1002:请选择分镜');
  2247. }
  2248. // 使用文生文模型重新解析segment_content
  2249. if (!empty($segment_content)) {
  2250. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2251. }
  2252. // 获取动漫的角色信息(包含参考图)
  2253. $anime = DB::table('mp_animes')
  2254. ->where('id', $anime_id)
  2255. ->select('roles', 'scenes')
  2256. ->first();
  2257. if (!$anime || !$anime->roles) {
  2258. Utils::throwError('20003:未找到角色信息');
  2259. }
  2260. $roles = json_decode($anime->roles, true);
  2261. if (!$roles) {
  2262. Utils::throwError('20003:角色信息格式错误');
  2263. }
  2264. // 构建角色名称到参考图的映射
  2265. $role_map = [];
  2266. foreach ($roles as $role) {
  2267. $role_name = getProp($role, 'role');
  2268. $role_url = getProp($role, 'url');
  2269. if (!empty($role_name) && !empty($role_url)) {
  2270. $role_map[$role_name] = $role_url;
  2271. }
  2272. }
  2273. $scenes = json_decode($anime->scenes, true);
  2274. if (!$scenes) {
  2275. Utils::throwError('20003:角色信息格式错误');
  2276. }
  2277. // 构建角色名称到参考图的映射
  2278. $scene_map = [];
  2279. foreach ($scenes as $scene) {
  2280. $scene_name = getProp($scene, 'scene');
  2281. $scene_url = getProp($scene, 'url');
  2282. if (!empty($scene_name) && !empty($scene_url)) {
  2283. $scene_map[$scene_name] = $scene_url;
  2284. }
  2285. }
  2286. $segment_id = $segment->segment_id;
  2287. $original_segment_content = $segment->segment_content;
  2288. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2289. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2290. if (empty($final_segment_content)) {
  2291. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2292. }
  2293. try {
  2294. $dubTaskId = 0;
  2295. DB::beginTransaction();
  2296. $new_segment_number = $segment_number + 1;
  2297. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2298. // 分镜剧本数组
  2299. $insert_data = [
  2300. 'anime_id' => $anime_id,
  2301. 'episode_id' => $episode_id,
  2302. 'episode_number' => $episode_number,
  2303. 'act_number' => getProp($segment, 'act_number'),
  2304. 'act_title' => getProp($segment, 'act_title'),
  2305. 'segment_id' => $segment_id,
  2306. 'segment_number' => $new_segment_number,
  2307. 'segment_content' => $final_segment_content,
  2308. 'img_url' => $img_url,
  2309. 'video_url' => $video_url,
  2310. 'created_at' => date('Y-m-d H:i:s'),
  2311. 'updated_at' => date('Y-m-d H:i:s')
  2312. ];
  2313. // 更新分镜剧本信息
  2314. $this->handleSegmentContent($insert_data);
  2315. // 如果有对话内容,创建视频配音合成任务
  2316. $dialogue = getProp($insert_data, 'dialogue');
  2317. if (!empty($dialogue)) {
  2318. $now = date('Y-m-d H:i:s');
  2319. $generate_json = [
  2320. 'text' => $dialogue,
  2321. 'role' => getProp($insert_data, 'voice_actor'),
  2322. 'voice_type' => getProp($insert_data, 'voice_type'),
  2323. 'voice_name' => getProp($insert_data, 'voice_name'),
  2324. 'emotion' => getProp($insert_data, 'emotion'),
  2325. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2326. 'gender' => getProp($insert_data, 'gender'),
  2327. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2328. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2329. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2330. 'pitch' => getProp($insert_data, 'pitch', 0),
  2331. ];
  2332. // 插入视频配音合成任务
  2333. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2334. 'alias_segment_id' => $segment_id,
  2335. 'generate_status' => '执行中',
  2336. 'audio_url' => '',
  2337. 'generate_json' => json_encode($generate_json, 256),
  2338. 'created_at' => $now,
  2339. 'updated_at' => $now,
  2340. ]);
  2341. if (!$dubTaskId) {
  2342. Utils::throwError('20003:创建配音任务失败!');
  2343. }
  2344. $insert_data['audio_url'] = '';
  2345. } else {
  2346. // dialogue为空时,直接写入默认音频信息
  2347. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2348. $insert_data['audio_duration'] = 2.0;
  2349. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2350. }
  2351. // 如果没有上传图片则使用当前描述进行生成
  2352. if (!$img_url) {
  2353. // 解析分镜内容,提取画面描述作为主要提示词
  2354. $prompt = $final_segment_content;
  2355. $ref_img_urls = [];
  2356. // 分镜场景
  2357. $scene = getProp($insert_data, 'scene');
  2358. if ($scene) {
  2359. $matched_scene = '';
  2360. if (isset($scene_map[$scene])) {
  2361. $img_index = count($ref_img_urls) + 1;
  2362. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2363. $ref_img_urls[] = $scene_map[$scene];
  2364. $matched_scene = $scene;
  2365. }
  2366. $update_data['scene'] = $scene;
  2367. }
  2368. // 分镜角色
  2369. $characters = getProp($insert_data, 'characters');
  2370. if ($characters) {
  2371. $update_data['characters'] = $characters;
  2372. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2373. $characters = explode(',', $characters);
  2374. // 从分镜内容中提取涉及的角色
  2375. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2376. // 获取匹配角色的参考图
  2377. foreach ($segment_characters as $character) {
  2378. if (isset($role_map[$character])) {
  2379. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2380. $img_index = count($ref_img_urls) + 1;
  2381. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2382. $ref_img_urls[] = $role_map[$character];
  2383. }
  2384. }
  2385. }
  2386. // 如果没有找到匹配的角色参考图,不使用参考图
  2387. if (empty($ref_img_urls)) {
  2388. $ref_img_urls = [];
  2389. }
  2390. // 准备生成任务参数
  2391. $params = [
  2392. 'alias_segment_id' => $segment_id,
  2393. 'prompt' => $prompt,
  2394. 'ref_img_urls' => $ref_img_urls,
  2395. 'width' => $width,
  2396. 'height' => $height,
  2397. ];
  2398. // 调用AI图片生成服务
  2399. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2400. $task_id = $task->id;
  2401. // $task_id = 'whatever';
  2402. if (!$task_id) {
  2403. Utils::throwError('20003:创建生成任务失败!');
  2404. }
  2405. $insert_data['pic_task_status'] = '生成中';
  2406. $insert_data['pic_task_id'] = $task_id;
  2407. }
  2408. // 先更新序号
  2409. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2410. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2411. if (!$boolen) {
  2412. Utils::throwError('20003:新增分镜失败!');
  2413. }
  2414. // 如果是第一集的首帧图片,则存入待更新数组
  2415. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2416. Redis::sadd('anime_first_frame_urls', $segment_id);
  2417. }
  2418. if ($dubTaskId) {
  2419. // 请求远程服务器执行生成
  2420. $client = new Client(['timeout' => 300, 'verify' => false]);
  2421. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2422. $response = $result->getBody()->getContents();
  2423. $response_arr = json_decode($response, true);
  2424. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2425. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2426. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2427. Utils::throwError('20003:火山生成音频失败');
  2428. }
  2429. }
  2430. } catch (\Exception $e) {
  2431. DB::rollBack();
  2432. Utils::throwError('20003:'.$e->getMessage());
  2433. }
  2434. DB::commit();
  2435. // 创建任务之后先暂停10s等待异步任务完成
  2436. sleep(10);
  2437. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2438. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2439. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2440. $segment = $segment ? (array)$segment : [];
  2441. return $segment;
  2442. }
  2443. public function copySegment($data) {
  2444. $segment_id = getProp($data, 'segment_id');
  2445. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2446. if (!$segment) Utils::throwError('20003:请选择分镜');
  2447. $anime_id = getProp($segment, 'anime_id');
  2448. $episode_id = getProp($segment, 'episode_id');
  2449. $episode_number = getProp($segment, 'episode_number');
  2450. $segment_number = getProp($segment, 'segment_number');
  2451. $new_segment_id = 0;
  2452. try {
  2453. DB::beginTransaction();
  2454. $segment = (array)$segment;
  2455. unset($segment['id']);
  2456. $segment['segment_number'] += 1;
  2457. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2458. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2459. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2460. // 更新其他分镜序号
  2461. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2462. // 复制分镜
  2463. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2464. if (!$id) {
  2465. Utils::throwError('20003:复制分镜失败');
  2466. }
  2467. }catch (\Exception $e) {
  2468. DB::rollBack();
  2469. Utils::throwError('20003:'.$e->getMessage());
  2470. }
  2471. DB::commit();
  2472. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2473. $segment = $segment ? (array)$segment : [];
  2474. return $segment;
  2475. }
  2476. public function moveSegment($data) {
  2477. $segment_id = getProp($data, 'segment_id');
  2478. $target_segment_id = getProp($data, 'target_segment_id');
  2479. // 获取源分镜信息
  2480. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2481. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2482. // 获取目标分镜信息
  2483. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2484. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2485. $anime_id = getProp($source_segment, 'anime_id');
  2486. $episode_id = getProp($source_segment, 'episode_id');
  2487. $episode_number = getProp($source_segment, 'episode_number');
  2488. $source_segment_number = getProp($source_segment, 'segment_number');
  2489. $target_segment_number = getProp($target_segment, 'segment_number');
  2490. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2491. $target_anime_id = getProp($target_segment, 'anime_id');
  2492. $target_episode_number = getProp($target_segment, 'episode_number');
  2493. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2494. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2495. }
  2496. // 如果源分镜和目标分镜相同,无需移动
  2497. if ($source_segment_number == $target_segment_number) {
  2498. return true;
  2499. }
  2500. try {
  2501. DB::beginTransaction();
  2502. if ($source_segment_number < $target_segment_number) {
  2503. // 向后移动:源分镜移动到目标分镜之后
  2504. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2505. DB::table('mp_episode_segments')
  2506. ->where('anime_id', $anime_id)
  2507. ->where('episode_id', $episode_id)
  2508. ->where('segment_number', '>', $source_segment_number)
  2509. ->where('segment_number', '<=', $target_segment_number)
  2510. ->decrement('segment_number');
  2511. // 2. 将源分镜移动到目标分镜之后
  2512. $new_segment_number = $target_segment_number;
  2513. } else {
  2514. // 向前移动:源分镜移动到目标分镜之后
  2515. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2516. DB::table('mp_episode_segments')
  2517. ->where('anime_id', $anime_id)
  2518. ->where('episode_id', $episode_id)
  2519. ->where('segment_number', '>', $target_segment_number)
  2520. ->where('segment_number', '<', $source_segment_number)
  2521. ->increment('segment_number');
  2522. // 2. 将源分镜移动到目标分镜之后
  2523. $new_segment_number = $target_segment_number + 1;
  2524. }
  2525. // 3. 更新源分镜的序号
  2526. $update_result = DB::table('mp_episode_segments')
  2527. ->where('segment_id', $segment_id)
  2528. ->update([
  2529. 'segment_number' => $new_segment_number,
  2530. 'updated_at' => date('Y-m-d H:i:s')
  2531. ]);
  2532. if (!$update_result) {
  2533. Utils::throwError('20003:更新分镜序号失败');
  2534. }
  2535. DB::commit();
  2536. return true;
  2537. } catch (\Exception $e) {
  2538. DB::rollBack();
  2539. Utils::throwError('20003:' . $e->getMessage());
  2540. }
  2541. }
  2542. public function delSegment($data) {
  2543. $segment_id = getProp($data, 'segment_id');
  2544. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2545. if (!$segment) Utils::throwError('20003:请选择分镜');
  2546. $anime_id = getProp($segment, 'anime_id');
  2547. $episode_id = getProp($segment, 'episode_id');
  2548. $episode_number = getProp($segment, 'episode_number');
  2549. $segment_number = getProp($segment, 'segment_number');
  2550. try {
  2551. DB::beginTransaction();
  2552. // 删除分镜
  2553. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2554. if (!$boolen) {
  2555. Utils::throwError('20003:删除分镜失败');
  2556. }
  2557. // 更新其他分镜序号
  2558. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2559. }catch (\Exception $e) {
  2560. DB::rollBack();
  2561. Utils::throwError('20003:'.$e->getMessage());
  2562. }
  2563. DB::commit();
  2564. return true;
  2565. }
  2566. public function applySegment($data) {
  2567. $segment_id = getProp($data, 'segment_id');
  2568. $url = getProp($data, 'url');
  2569. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2570. if (!$url) Utils::throwError('20003:URL不能为空');
  2571. // 获取URL的文件扩展名
  2572. $urlPath = parse_url($url, PHP_URL_PATH);
  2573. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2574. // 定义图片和视频的扩展名
  2575. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2576. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2577. // 判断是图片还是视频
  2578. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2579. if (in_array($extension, $imageExtensions)) {
  2580. // 图片类型
  2581. $updateData['img_url'] = $url;
  2582. $updateData['current_type'] = 1;
  2583. } elseif (in_array($extension, $videoExtensions)) {
  2584. // 视频类型
  2585. $updateData['video_url'] = $url;
  2586. $updateData['current_type'] = 2;
  2587. } else {
  2588. Utils::throwError('20003:不支持的文件类型');
  2589. }
  2590. // 更新分镜表
  2591. $result = DB::table('mp_episode_segments')
  2592. ->where('segment_id', $segment_id)
  2593. ->update($updateData);
  2594. if (!$result) {
  2595. Utils::throwError('20003:更新分镜失败');
  2596. }
  2597. return true;
  2598. }
  2599. public function segmentHistory($data) {
  2600. $segment_id = getProp($data, 'segment_id');
  2601. // 获取历史图片
  2602. $pics = [];
  2603. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2604. foreach($pic_history as $task) {
  2605. $result_url = getProp($task, 'result_url');
  2606. if (is_json($result_url)) {
  2607. $pics = array_merge($pics, json_decode($result_url, true));
  2608. }else {
  2609. $pics[] = $result_url;
  2610. }
  2611. }
  2612. // 获取历史视频
  2613. $videos = [];
  2614. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2615. foreach($video_history as $task) {
  2616. $result_url = getProp($task, 'result_url');
  2617. if (is_json($result_url)) {
  2618. $videos = array_merge($videos, json_decode($result_url, true));
  2619. }else {
  2620. $videos[] = $result_url;
  2621. }
  2622. }
  2623. return compact('pics', 'videos');
  2624. }
  2625. public function addAct($data) {
  2626. $prev_act_id = getProp($data, 'prev_act_id');
  2627. $act_title = getProp($data, 'act_title', '');
  2628. $act_content = getProp($data, 'act_content', '');
  2629. $act_duration = getProp($data, 'act_duration', 5);
  2630. $video_url = getProp($data, 'video_url');
  2631. // 根据prev_act_id获取记录
  2632. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2633. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2634. $anime_id = getProp($prev_segment, 'anime_id');
  2635. $episode_id = getProp($prev_segment, 'episode_id');
  2636. $episode_number = getProp($prev_segment, 'episode_number');
  2637. $prev_act_number = getProp($prev_segment, 'act_number');
  2638. // 获取新的act_number
  2639. $new_act_number = $prev_act_number + 1;
  2640. try {
  2641. DB::beginTransaction();
  2642. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2643. DB::table('mp_episode_segments')
  2644. ->where('anime_id', $anime_id)
  2645. ->where('episode_id', $episode_id)
  2646. ->where('act_number', '>', $prev_act_number)
  2647. ->increment('act_number');
  2648. // 插入新片段记录
  2649. $insert_data = [
  2650. 'anime_id' => $anime_id,
  2651. 'episode_id' => $episode_id,
  2652. 'episode_number' => $episode_number,
  2653. 'act_number' => $new_act_number,
  2654. 'created_at' => date('Y-m-d H:i:s'),
  2655. 'updated_at' => date('Y-m-d H:i:s')
  2656. ];
  2657. if ($act_title) {
  2658. $insert_data['act_title'] = $act_title;
  2659. }
  2660. if ($act_content) {
  2661. $insert_data['act_content'] = $act_content;
  2662. }
  2663. if ($act_duration) {
  2664. $insert_data['act_duration'] = $act_duration;
  2665. }
  2666. if ($video_url) {
  2667. $insert_data['origin_video_url'] = $video_url;
  2668. $insert_data['current_type'] = 2;
  2669. $compressed_video_url = compressVideo($video_url);
  2670. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2671. }
  2672. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2673. if (!$id) {
  2674. Utils::throwError('20003:新增片段失败!');
  2675. }
  2676. DB::commit();
  2677. }catch (\Exception $e) {
  2678. DB::rollBack();
  2679. Utils::throwError('20003:'.$e->getMessage());
  2680. }
  2681. $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();
  2682. $segment = $segment ? (array)$segment : [];
  2683. return $segment;
  2684. }
  2685. public function editAct($data) {
  2686. $act_id = getProp($data, 'act_id');
  2687. $act_content = getProp($data, 'act_content');
  2688. $act_duration = getProp($data, 'act_duration');
  2689. $act_title = getProp($data, 'act_title');
  2690. $image_url = getProp($data, 'image_url');
  2691. $video_url = getProp($data, 'video_url');
  2692. // 参数验证
  2693. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2694. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2695. $segment = DB::table('mp_episode_segments')
  2696. ->where('id', $act_id)
  2697. ->first();
  2698. if (!$segment) Utils::throwError('20003:该片段不存在');
  2699. try {
  2700. DB::beginTransaction();
  2701. // 准备更新数据
  2702. $update_data = [
  2703. 'updated_at' => date('Y-m-d H:i:s')
  2704. ];
  2705. // 更新act相关字段
  2706. if (!empty($act_content)) {
  2707. $update_data['act_show_content'] = $act_content;
  2708. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2709. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2710. $shot_counter = 0;
  2711. $update_data['act_show_content'] = preg_replace_callback(
  2712. '/【(?:镜头|分镜)(\d+)】/u',
  2713. function($matches) use (&$shot_counter) {
  2714. $shot_counter++;
  2715. return '【镜头' . $shot_counter . '】';
  2716. },
  2717. $update_data['act_show_content']
  2718. );
  2719. }
  2720. if (!empty($act_duration)) {
  2721. $update_data['act_duration'] = $act_duration;
  2722. }
  2723. if (!empty($act_title)) {
  2724. $update_data['act_title'] = $act_title;
  2725. }
  2726. // 处理图片上传
  2727. if ($image_url) {
  2728. $update_data['img_url'] = $image_url;
  2729. $update_data['current_type'] = 1;
  2730. // 同时写入一个图片生成任务记录
  2731. if ($act_id) {
  2732. $pic_task = [
  2733. 'alias_act_id' => $act_id,
  2734. 'ref_img_url' => json_encode([]),
  2735. 'status' => 'success',
  2736. 'result_url' => json_encode([$image_url], 256),
  2737. 'model' => '',
  2738. 'created_at' => date('Y-m-d H:i:s'),
  2739. 'updated_at' => date('Y-m-d H:i:s'),
  2740. ];
  2741. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2742. }
  2743. }
  2744. // 处理视频上传
  2745. if ($video_url) {
  2746. $update_data['origin_video_url'] = $video_url;
  2747. $compressed_video_url = compressVideo($video_url);
  2748. $update_data['current_type'] = 2;
  2749. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2750. // 同时写入一个视频生成任务记录
  2751. if ($act_id) {
  2752. $video_task = [
  2753. 'alias_act_id' => $act_id,
  2754. 'status' => 'success',
  2755. 'result_url' => $update_data['origin_video_url'],
  2756. 'compressed_url' => $update_data['video_url'],
  2757. 'created_at' => date('Y-m-d H:i:s'),
  2758. 'updated_at' => date('Y-m-d H:i:s'),
  2759. ];
  2760. DB::table('mp_generate_video_tasks')->insert($video_task);
  2761. }
  2762. }
  2763. // 更新片段信息
  2764. $result = DB::table('mp_episode_segments')
  2765. ->where('id', $act_id)
  2766. ->update($update_data);
  2767. if ($result === false) {
  2768. Utils::throwError('20003:更新片段失败');
  2769. }
  2770. DB::commit();
  2771. // 返回新复制的记录
  2772. $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();
  2773. $new_segment = (array)$new_segment;
  2774. return $new_segment;
  2775. } catch (\Exception $e) {
  2776. DB::rollBack();
  2777. dLog('anime')->error('更新片段失败', [
  2778. 'act_id' => $act_id,
  2779. 'error' => $e->getMessage()
  2780. ]);
  2781. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2782. }
  2783. }
  2784. public function copyAct($data) {
  2785. $act_id = getProp($data, 'act_id');
  2786. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2787. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2788. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2789. $anime_id = getProp($source_segment, 'anime_id');
  2790. $episode_id = getProp($source_segment, 'episode_id');
  2791. $episode_number = getProp($source_segment, 'episode_number');
  2792. $act_number = getProp($source_segment, 'act_number');
  2793. try {
  2794. DB::beginTransaction();
  2795. // 新act的编号
  2796. $new_act_number = $act_number + 1;
  2797. // 更新后续所有act的act_number
  2798. DB::table('mp_episode_segments')
  2799. ->where('anime_id', $anime_id)
  2800. ->where('episode_id', $episode_id)
  2801. ->where('act_number', '>', $act_number)
  2802. ->increment('act_number');
  2803. // 复制该片段记录
  2804. $segment_data = (array)$source_segment;
  2805. unset($segment_data['id']);
  2806. $segment_data['video_url'] = '';
  2807. $segment_data['video_task_id'] = '';
  2808. $segment_data['video_task_status'] = '';
  2809. $segment_data['act_number'] = $new_act_number;
  2810. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2811. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2812. if (!$id) {
  2813. Utils::throwError('20003:复制片段失败');
  2814. }
  2815. DB::commit();
  2816. }catch (\Exception $e) {
  2817. DB::rollBack();
  2818. Utils::throwError('20003:'.$e->getMessage());
  2819. }
  2820. // 返回新复制的记录
  2821. $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();
  2822. $new_segment = $new_segment ? (array)$new_segment : [];
  2823. $new_segment['act_id'] = $id;
  2824. return $new_segment;
  2825. }
  2826. public function moveAct($data) {
  2827. $act_id = getProp($data, 'act_id');
  2828. $target_act_id = getProp($data, 'target_act_id');
  2829. // 获取源片段信息
  2830. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2831. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2832. // 获取目标片段信息
  2833. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2834. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2835. $anime_id = getProp($source_segment, 'anime_id');
  2836. $episode_id = getProp($source_segment, 'episode_id');
  2837. $source_act_number = getProp($source_segment, 'act_number');
  2838. $target_act_number = getProp($target_segment, 'act_number');
  2839. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2840. $target_anime_id = getProp($target_segment, 'anime_id');
  2841. $target_episode_id = getProp($target_segment, 'episode_id');
  2842. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2843. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2844. }
  2845. // 如果源片段和目标片段相同,无需移动
  2846. if ($source_act_number == $target_act_number) {
  2847. return true;
  2848. }
  2849. try {
  2850. DB::beginTransaction();
  2851. if ($source_act_number < $target_act_number) {
  2852. // 向后移动:源片段移动到目标片段之后
  2853. // 1. 将源片段和目标片段之间的所有片段编号减1
  2854. DB::table('mp_episode_segments')
  2855. ->where('anime_id', $anime_id)
  2856. ->where('episode_id', $episode_id)
  2857. ->where('act_number', '>', $source_act_number)
  2858. ->where('act_number', '<=', $target_act_number)
  2859. ->decrement('act_number');
  2860. // 2. 将源片段移动到目标片段之后
  2861. $new_act_number = $target_act_number;
  2862. } else {
  2863. // 向前移动:源片段移动到目标片段之后
  2864. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2865. DB::table('mp_episode_segments')
  2866. ->where('anime_id', $anime_id)
  2867. ->where('episode_id', $episode_id)
  2868. ->where('act_number', '>', $target_act_number)
  2869. ->where('act_number', '<', $source_act_number)
  2870. ->increment('act_number');
  2871. // 2. 将源片段移动到目标片段之后
  2872. $new_act_number = $target_act_number + 1;
  2873. }
  2874. // 3. 更新源片段的编号
  2875. $update_result = DB::table('mp_episode_segments')
  2876. ->where('id', $act_id)
  2877. ->update([
  2878. 'act_number' => $new_act_number,
  2879. 'updated_at' => date('Y-m-d H:i:s')
  2880. ]);
  2881. if (!$update_result) {
  2882. Utils::throwError('20003:更新片段编号失败');
  2883. }
  2884. DB::commit();
  2885. return true;
  2886. } catch (\Exception $e) {
  2887. DB::rollBack();
  2888. Utils::throwError('20003:' . $e->getMessage());
  2889. }
  2890. }
  2891. public function delAct($data) {
  2892. $act_id = getProp($data, 'act_id');
  2893. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2894. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2895. if (!$segment) Utils::throwError('20003:请选择片段');
  2896. $anime_id = getProp($segment, 'anime_id');
  2897. $episode_id = getProp($segment, 'episode_id');
  2898. $act_number = getProp($segment, 'act_number');
  2899. try {
  2900. DB::beginTransaction();
  2901. // 删除该片段记录
  2902. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2903. if (!$deleted) {
  2904. Utils::throwError('20003:删除片段失败');
  2905. }
  2906. // 更新后续act的编号
  2907. DB::table('mp_episode_segments')
  2908. ->where('anime_id', $anime_id)
  2909. ->where('episode_id', $episode_id)
  2910. ->where('act_number', '>', $act_number)
  2911. ->decrement('act_number');
  2912. DB::commit();
  2913. }catch (\Exception $e) {
  2914. DB::rollBack();
  2915. Utils::throwError('20003:'.$e->getMessage());
  2916. }
  2917. return true;
  2918. }
  2919. public function applyAct($data) {
  2920. $act_id = getProp($data, 'act_id');
  2921. $url = getProp($data, 'url');
  2922. if (!$act_id) Utils::throwError('20003:请选择片段');
  2923. if (!$url) Utils::throwError('20003:URL不能为空');
  2924. // 获取URL的文件扩展名
  2925. $urlPath = parse_url($url, PHP_URL_PATH);
  2926. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2927. // 定义图片和视频的扩展名
  2928. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2929. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2930. // 判断是图片还是视频
  2931. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2932. if (in_array($extension, $imageExtensions)) {
  2933. // 图片类型
  2934. $updateData['img_url'] = $url;
  2935. $updateData['current_type'] = 1;
  2936. } elseif (in_array($extension, $videoExtensions)) {
  2937. // 视频类型
  2938. $updateData['video_url'] = $url;
  2939. $updateData['current_type'] = 2;
  2940. } else {
  2941. Utils::throwError('20003:不支持的文件类型');
  2942. }
  2943. // 更新片段记录(全能模式下每个act只有一条记录)
  2944. $result = DB::table('mp_episode_segments')
  2945. ->where('id', $act_id)
  2946. ->update($updateData);
  2947. if (!$result) {
  2948. Utils::throwError('20003:更新片段失败');
  2949. }
  2950. return true;
  2951. }
  2952. public function actChatHistory($data) {
  2953. $act_id = getProp($data, 'act_id');
  2954. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2955. $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');
  2956. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2957. $value = (array)$value;
  2958. $value['created_at'] = transDate($value['created_at']);
  2959. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2960. else $value['reference_images'] = [];
  2961. return $value;
  2962. })->toArray();
  2963. // 获取历史图片
  2964. $url = [];
  2965. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2966. foreach($pic_history as $task) {
  2967. $result_url = getProp($task, 'result_url');
  2968. if (is_json($result_url)) {
  2969. $url = array_merge($url, json_decode($result_url, true));
  2970. }else {
  2971. $url[] = $result_url;
  2972. }
  2973. }
  2974. // 获取历史视频
  2975. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2976. foreach($video_history as $task) {
  2977. $result_url = getProp($task, 'result_url');
  2978. if (is_json($result_url)) {
  2979. $url = array_merge($url, json_decode($result_url, true));
  2980. }else {
  2981. $url[] = $result_url;
  2982. }
  2983. }
  2984. // 获取资产库
  2985. $products = [];
  2986. // 通过act_id查询片段信息获取episode_id
  2987. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2988. if ($segment) {
  2989. $episode_id = getProp($segment, 'episode_id');
  2990. // 查询剧集信息获取roles、scenes和extra_products
  2991. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2992. if ($episode) {
  2993. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2994. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2995. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2996. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2997. // 先合并roles、scenes和props
  2998. // 处理角色数组
  2999. foreach ($roles as $role) {
  3000. $product = $role;
  3001. // 将role字段重命名为product_name
  3002. if (is_array($product) && !empty($product['role'] ?? null)) {
  3003. $product['product_name'] = $product['role'];
  3004. unset($product['role']);
  3005. $product['product'] = 1; // 标记类型为角色
  3006. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3007. }
  3008. }
  3009. // 处理场景数组
  3010. foreach ($scenes as $scene) {
  3011. $product = $scene;
  3012. // 将scene字段重命名为product_name
  3013. if (is_array($product) && !empty($product['scene'] ?? null)) {
  3014. $product['product_name'] = $product['scene'];
  3015. unset($product['scene']);
  3016. $product['product'] = 2; // 标记类型为场景
  3017. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3018. }
  3019. }
  3020. // 处理道具数组
  3021. foreach ($props as $prop) {
  3022. $product = $prop;
  3023. // 将prop字段重命名为product_name
  3024. if (is_array($product) && !empty($product['prop'] ?? null)) {
  3025. $product['product_name'] = $product['prop'];
  3026. unset($product['prop']);
  3027. $product['product'] = 3; // 标记类型为道具
  3028. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3029. }
  3030. }
  3031. // extra_products优先级更高,直接覆盖同名的roles和scenes
  3032. foreach ($extra_products as $extra_product) {
  3033. $product_name = getProp($extra_product, 'product_name');
  3034. if ($product_name) {
  3035. $products[$product_name] = $extra_product; // 覆盖同名数据
  3036. }
  3037. }
  3038. // 重新索引数组(去除key)
  3039. $products = array_values($products);
  3040. }
  3041. }
  3042. // 获取执行中的任务
  3043. $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) {
  3044. $value = (array)$value;
  3045. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  3046. else $value['ref_image_url'] = [];
  3047. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3048. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3049. if (!empty($value['prompt'])) {
  3050. $prompt = $value['prompt'];
  3051. // 查找第一个【镜头】的位置
  3052. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3053. // 从【镜头】开始截取
  3054. $prompt = substr($prompt, $matches[0][1]);
  3055. }
  3056. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3057. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3058. $value['prompt'] = $prompt;
  3059. }
  3060. return $value;
  3061. })->toArray();
  3062. return compact('chat', 'url', 'products', 'tasks');
  3063. }
  3064. public function applyAudioData($data) {
  3065. $segment_id = getProp($data, 'segment_id');
  3066. $global_data = getProp($data, 'global_data');
  3067. $segment_data = getProp($data, 'segment_data');
  3068. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3069. $global_data = is_array($global_data) ? $global_data : [];
  3070. $segment_data = is_array($segment_data) ? $segment_data : [];
  3071. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3072. $dialogue_item = null;
  3073. foreach ($global_data as $key => $item) {
  3074. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3075. $dialogue_item = $item;
  3076. unset($global_data[$key]);
  3077. break;
  3078. }
  3079. }
  3080. if ($dialogue_item) {
  3081. $segment_data[] = $dialogue_item;
  3082. }
  3083. // 特殊参数: audio_url,audio_duration,subtitle_info
  3084. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3085. // 如果不是全部存在,则仍需创建音频任务
  3086. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3087. $special_update_data = [];
  3088. $has_all_special_params = false;
  3089. // 从segment_data中提取特殊参数
  3090. $filtered_segment_data = [];
  3091. foreach ($segment_data as $item) {
  3092. $field_name = trim((string)getProp($item, 'name'));
  3093. if (in_array($field_name, $special_fields)) {
  3094. $special_update_data[$field_name] = getProp($item, 'value');
  3095. } else {
  3096. // 非特殊参数保留,继续后续处理
  3097. $filtered_segment_data[] = $item;
  3098. }
  3099. }
  3100. // 检查是否三个特殊参数都存在
  3101. if (count($special_update_data) === 3 &&
  3102. isset($special_update_data['audio_url']) &&
  3103. isset($special_update_data['audio_duration']) &&
  3104. isset($special_update_data['subtitle_info'])) {
  3105. $has_all_special_params = true;
  3106. // 立即更新到当前分镜
  3107. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3108. DB::table('mp_episode_segments')
  3109. ->where('segment_id', $segment_id)
  3110. ->update($special_update_data);
  3111. }
  3112. // 使用过滤后的segment_data继续处理其他参数
  3113. $segment_data = $filtered_segment_data;
  3114. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3115. $global_update_data = [];
  3116. $segment_update_data = [];
  3117. $global_voice_type = '';
  3118. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3119. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3120. $episode_id = getProp($target_segment, 'episode_id');
  3121. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3122. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3123. if (!$episode) Utils::throwError('20003:分集不存在');
  3124. foreach ($global_data as $item) {
  3125. $field_name = trim((string)getProp($item, 'name'));
  3126. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3127. continue;
  3128. }
  3129. $global_update_data[$field_name] = getProp($item, 'value');
  3130. if ($field_name === 'voice_type') {
  3131. $global_voice_type = trim((string)getProp($item, 'value'));
  3132. }
  3133. }
  3134. foreach ($segment_data as $item) {
  3135. $field_name = trim((string)getProp($item, 'name'));
  3136. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3137. continue;
  3138. }
  3139. $segment_update_data[$field_name] = getProp($item, 'value');
  3140. }
  3141. if ($global_voice_type) {
  3142. $timbre_info = DB::table('mp_timbres')
  3143. ->where('timbre_type', $global_voice_type)
  3144. ->select('audio_url', 'timbre_name')
  3145. ->first();
  3146. if ($timbre_info) {
  3147. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3148. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3149. }
  3150. }
  3151. try {
  3152. DB::beginTransaction();
  3153. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3154. $segment_ids_to_create_task = [];
  3155. $segments_data = [];
  3156. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3157. if (!empty($global_update_data)) {
  3158. // 如果角色不存在,则只更新当前分镜
  3159. if (!$target_voice_actor) {
  3160. // 只处理当前分镜
  3161. $affected_segments = DB::table('mp_episode_segments')
  3162. ->where('segment_id', $segment_id)
  3163. ->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')
  3164. ->get();
  3165. } else {
  3166. // 获取该角色的所有分镜
  3167. $affected_segments = DB::table('mp_episode_segments')
  3168. ->where('episode_id', $episode_id)
  3169. ->where('voice_actor', $target_voice_actor)
  3170. ->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')
  3171. ->get();
  3172. }
  3173. foreach ($affected_segments as $seg) {
  3174. $seg = (array)$seg;
  3175. $sid = getProp($seg, 'segment_id');
  3176. // 检查参数是否发生变化
  3177. $has_changed = false;
  3178. foreach ($global_update_data as $field => $new_value) {
  3179. $old_value = getProp($seg, $field);
  3180. if ($old_value != $new_value) {
  3181. $has_changed = true;
  3182. break;
  3183. }
  3184. }
  3185. if ($has_changed) {
  3186. $segment_ids_to_create_task[] = $sid;
  3187. $segments_data[$sid] = $seg;
  3188. }
  3189. }
  3190. // 只有在有变化的分镜时才更新
  3191. if (!empty($segment_ids_to_create_task)) {
  3192. $global_segment_update_data = $global_update_data;
  3193. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3194. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3195. DB::table('mp_episode_segments')
  3196. ->where('episode_id', $episode_id)
  3197. ->where('voice_actor', $target_voice_actor)
  3198. ->whereIn('segment_id', $segment_ids_to_create_task)
  3199. ->update($global_segment_update_data);
  3200. }
  3201. if ($global_voice_type) {
  3202. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3203. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3204. $roles_updated = false;
  3205. foreach ($episode_roles as &$role) {
  3206. // 通过 role 字段匹配角色名,而不是 voice_name
  3207. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3208. continue;
  3209. }
  3210. $role['voice_type'] = $global_voice_type;
  3211. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3212. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3213. $roles_updated = true;
  3214. }
  3215. unset($role);
  3216. if ($roles_updated) {
  3217. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3218. 'roles' => json_encode($episode_roles, 256),
  3219. 'updated_at' => date('Y-m-d H:i:s'),
  3220. ]);
  3221. }
  3222. }
  3223. }
  3224. // 如果有单个分镜更新,检查是否有变化
  3225. if (!empty($segment_update_data)) {
  3226. // 获取当前分镜数据
  3227. $current_segment = DB::table('mp_episode_segments')
  3228. ->where('segment_id', $segment_id)
  3229. ->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')
  3230. ->first();
  3231. if ($current_segment) {
  3232. $current_segment = (array)$current_segment;
  3233. // 检查参数是否发生变化
  3234. $has_changed = false;
  3235. foreach ($segment_update_data as $field => $new_value) {
  3236. $old_value = getProp($current_segment, $field);
  3237. if ($old_value != $new_value) {
  3238. $has_changed = true;
  3239. break;
  3240. }
  3241. }
  3242. if ($has_changed) {
  3243. // 如果该分镜还未在列表中,添加进去
  3244. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3245. $segment_ids_to_create_task[] = $segment_id;
  3246. $segments_data[$segment_id] = $current_segment;
  3247. }
  3248. // 更新分镜数据并清空音频URL
  3249. $segment_update_data['audio_url'] = '';
  3250. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3251. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3252. }
  3253. }
  3254. }
  3255. // 为所有有变化的分镜创建音频合成任务
  3256. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3257. if (!empty($segment_ids_to_create_task)) {
  3258. foreach ($segment_ids_to_create_task as $sid) {
  3259. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3260. if ($sid === $segment_id && $has_all_special_params) {
  3261. continue;
  3262. }
  3263. // 重新获取更新后的分镜数据
  3264. $updated_segment = DB::table('mp_episode_segments')
  3265. ->where('segment_id', $sid)
  3266. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3267. ->first();
  3268. if (!$updated_segment) continue;
  3269. $updated_segment = (array)$updated_segment;
  3270. // 检查dialogue是否为空
  3271. $dialogue = getProp($updated_segment, 'dialogue');
  3272. if (empty($dialogue)) {
  3273. // dialogue为空时,直接写入默认音频信息
  3274. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3275. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3276. 'audio_duration' => 2.0,
  3277. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3278. 'updated_at' => date('Y-m-d H:i:s')
  3279. ]);
  3280. continue;
  3281. }
  3282. $generate_json = [
  3283. 'text' => $dialogue,
  3284. 'role' => getProp($updated_segment, 'voice_actor'),
  3285. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3286. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3287. 'emotion' => getProp($updated_segment, 'emotion'),
  3288. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3289. 'gender' => getProp($updated_segment, 'gender'),
  3290. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3291. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3292. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3293. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3294. ];
  3295. // 插入视频配音合成任务
  3296. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3297. 'alias_segment_id' => $sid,
  3298. 'generate_status' => '执行中',
  3299. 'audio_url' => '',
  3300. 'generate_json' => json_encode($generate_json, 256),
  3301. 'created_at' => date('Y-m-d H:i:s'),
  3302. 'updated_at' => date('Y-m-d H:i:s'),
  3303. ]);
  3304. if (!$dubTaskId) {
  3305. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3306. continue;
  3307. }
  3308. // 将任务ID添加到Redis列表中
  3309. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3310. // 请求远程服务器执行生成
  3311. try {
  3312. sleep(1);
  3313. $client = new Client(['timeout' => 300, 'verify' => false]);
  3314. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3315. $response = $result->getBody()->getContents();
  3316. $response_arr = json_decode($response, true);
  3317. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3318. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3319. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3320. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3321. }
  3322. } catch (\Exception $e) {
  3323. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3324. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3325. }
  3326. }
  3327. }
  3328. DB::commit();
  3329. } catch (\Exception $e) {
  3330. DB::rollBack();
  3331. Utils::throwError('20003:'.$e->getMessage());
  3332. }
  3333. return true;
  3334. }
  3335. public function episodePicsInfo($data) {
  3336. $anime_id = getProp($data, 'anime_id');
  3337. $episode_id = getProp($data, 'episode_id');
  3338. // 参数验证
  3339. if (!$anime_id && !$episode_id) {
  3340. Utils::throwError('20003:请提供动漫ID或分集ID');
  3341. }
  3342. // 根据参数获取数据源
  3343. if ($episode_id) {
  3344. // 从剧集表获取
  3345. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3346. if (!$source) Utils::throwError('20003:该剧集不存在');
  3347. $table_name = 'mp_anime_episodes';
  3348. $id_field = 'id';
  3349. $id_value = $episode_id;
  3350. // 获取剧集的anime_id用于继承全局数据
  3351. $anime_id = getProp($source, 'anime_id');
  3352. } else {
  3353. // 从动漫表获取
  3354. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3355. if (!$source) Utils::throwError('20003:该动漫不存在');
  3356. $table_name = 'mp_animes';
  3357. $id_field = 'id';
  3358. $id_value = $anime_id;
  3359. }
  3360. $source = (array)$source;
  3361. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3362. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3363. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3364. // 如果是分集数据,需要处理继承和任务创建逻辑
  3365. if ($episode_id) {
  3366. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3367. }
  3368. // 返回生成器函数,用于 SSE 流式输出
  3369. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3370. $startTime = time();
  3371. $maxDuration = 600; // 10分钟超时
  3372. $checkInterval = 3; // 每3秒检查一次
  3373. // Redis 缓存键
  3374. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3375. // 生成当前数据的哈希值用于比较
  3376. $generateHash = function($roles, $scenes, $props) {
  3377. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3378. };
  3379. // 发送初始数据
  3380. $currentHash = $generateHash($roles, $scenes, $props);
  3381. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3382. echo "data: " . json_encode([
  3383. 'type' => 'init',
  3384. 'data' => [
  3385. 'roles' => $roles,
  3386. 'scenes' => $scenes,
  3387. 'props' => $props,
  3388. 'start_time' => $startTime
  3389. ]
  3390. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3391. if (ob_get_level() > 0) {
  3392. ob_flush();
  3393. }
  3394. flush();
  3395. // 持续轮询任务状态
  3396. while (time() - $startTime < $maxDuration) {
  3397. $hasProcessing = false;
  3398. $updated = false;
  3399. // 检查角色任务状态
  3400. foreach ($roles as $index => &$role) {
  3401. $task_id = getProp($role, 'task_id');
  3402. $task_status = getProp($role, 'task_status');
  3403. $existing_url = getProp($role, 'url');
  3404. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3405. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3406. $hasProcessing = ($task_status === 'processing');
  3407. // 查询任务状态
  3408. $task = DB::table('mp_generate_pic_tasks')
  3409. ->where('id', $task_id)
  3410. ->select('id', 'status', 'result_url', 'error_message')
  3411. ->first();
  3412. if ($task) {
  3413. $task = (array)$task;
  3414. $status = getProp($task, 'status');
  3415. // 如果任务完成或失败
  3416. if (in_array($status, ['success', 'failed'])) {
  3417. $role['task_status'] = $status;
  3418. if ($status === 'success') {
  3419. $result_url = getProp($task, 'result_url');
  3420. if ($result_url) {
  3421. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3422. if (is_array($result_urls) && !empty($result_urls[0])) {
  3423. $role['url'] = $result_urls[0];
  3424. }
  3425. }
  3426. }
  3427. $updated = true;
  3428. } else if ($status === 'processing') {
  3429. $hasProcessing = true;
  3430. }
  3431. }
  3432. }
  3433. }
  3434. // 检查场景任务状态
  3435. foreach ($scenes as $index => &$scene) {
  3436. $task_id = getProp($scene, 'task_id');
  3437. $task_status = getProp($scene, 'task_status');
  3438. $existing_url = getProp($scene, 'url');
  3439. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3440. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3441. $hasProcessing = ($task_status === 'processing');
  3442. // 查询任务状态
  3443. $task = DB::table('mp_generate_pic_tasks')
  3444. ->where('id', $task_id)
  3445. ->select('id', 'status', 'result_url', 'error_message')
  3446. ->first();
  3447. if ($task) {
  3448. $task = (array)$task;
  3449. $status = getProp($task, 'status');
  3450. // 如果任务完成或失败
  3451. if (in_array($status, ['success', 'failed'])) {
  3452. $scene['task_status'] = $status;
  3453. if ($status === 'success') {
  3454. $result_url = getProp($task, 'result_url');
  3455. if ($result_url) {
  3456. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3457. if (is_array($result_urls) && !empty($result_urls[0])) {
  3458. $scene['url'] = $result_urls[0];
  3459. }
  3460. }
  3461. }
  3462. $updated = true;
  3463. } else if ($status === 'processing') {
  3464. $hasProcessing = true;
  3465. }
  3466. }
  3467. }
  3468. }
  3469. // 检查道具任务状态
  3470. foreach ($props as $index => &$prop) {
  3471. $task_id = getProp($prop, 'task_id');
  3472. $task_status = getProp($prop, 'task_status');
  3473. $existing_url = getProp($prop, 'url');
  3474. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3475. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3476. $hasProcessing = ($task_status === 'processing');
  3477. // 查询任务状态
  3478. $task = DB::table('mp_generate_pic_tasks')
  3479. ->where('id', $task_id)
  3480. ->select('id', 'status', 'result_url', 'error_message')
  3481. ->first();
  3482. if ($task) {
  3483. $task = (array)$task;
  3484. $status = getProp($task, 'status');
  3485. // 如果任务完成或失败
  3486. if (in_array($status, ['success', 'failed'])) {
  3487. $prop['task_status'] = $status;
  3488. if ($status === 'success') {
  3489. $result_url = getProp($task, 'result_url');
  3490. if ($result_url) {
  3491. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3492. if (is_array($result_urls) && !empty($result_urls[0])) {
  3493. $prop['url'] = $result_urls[0];
  3494. }
  3495. }
  3496. }
  3497. $updated = true;
  3498. } else if ($status === 'processing') {
  3499. $hasProcessing = true;
  3500. }
  3501. }
  3502. }
  3503. }
  3504. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3505. if ($updated) {
  3506. $newHash = $generateHash($roles, $scenes, $props);
  3507. $cachedHash = Redis::get($cacheKey);
  3508. // 只有当数据真正变化时才更新数据库和发送事件
  3509. if ($newHash !== $cachedHash) {
  3510. try {
  3511. // 更新数据库
  3512. DB::table($table_name)->where($id_field, $id_value)->update([
  3513. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3514. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3515. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3516. 'updated_at' => date('Y-m-d H:i:s')
  3517. ]);
  3518. // 更新缓存
  3519. Redis::setex($cacheKey, 600, $newHash);
  3520. // 发送更新事件
  3521. echo "data: " . json_encode([
  3522. 'type' => 'update',
  3523. 'data' => [
  3524. 'roles' => $roles,
  3525. 'scenes' => $scenes,
  3526. 'props' => $props,
  3527. 'elapsed_time' => time() - $startTime
  3528. ]
  3529. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3530. if (ob_get_level() > 0) {
  3531. ob_flush();
  3532. }
  3533. flush();
  3534. } catch (\Exception $e) {
  3535. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3536. }
  3537. } else {
  3538. // 即使哈希相同,如果有URL更新也要发送事件
  3539. $hasUrlUpdate = false;
  3540. foreach ($roles as $role) {
  3541. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3542. $hasUrlUpdate = true;
  3543. break;
  3544. }
  3545. }
  3546. if (!$hasUrlUpdate) {
  3547. foreach ($scenes as $scene) {
  3548. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3549. $hasUrlUpdate = true;
  3550. break;
  3551. }
  3552. }
  3553. }
  3554. if (!$hasUrlUpdate) {
  3555. foreach ($props as $prop) {
  3556. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3557. $hasUrlUpdate = true;
  3558. break;
  3559. }
  3560. }
  3561. }
  3562. if ($hasUrlUpdate) {
  3563. // 强制更新数据库和发送事件
  3564. try {
  3565. DB::table($table_name)->where($id_field, $id_value)->update([
  3566. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3567. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3568. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3569. 'updated_at' => date('Y-m-d H:i:s')
  3570. ]);
  3571. // 更新缓存
  3572. Redis::setex($cacheKey, 600, $newHash);
  3573. // 发送更新事件
  3574. echo "data: " . json_encode([
  3575. 'type' => 'update',
  3576. 'data' => [
  3577. 'roles' => $roles,
  3578. 'scenes' => $scenes,
  3579. 'props' => $props,
  3580. 'elapsed_time' => time() - $startTime
  3581. ]
  3582. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3583. if (ob_get_level() > 0) {
  3584. ob_flush();
  3585. }
  3586. flush();
  3587. } catch (\Exception $e) {
  3588. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3589. }
  3590. }
  3591. }
  3592. }
  3593. // 如果所有任务都已完成,发送完成事件并退出
  3594. if (!$hasProcessing) {
  3595. // 查询数据库中的最终数据,确保返回最新的完整数据
  3596. try {
  3597. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3598. if ($finalSource) {
  3599. $finalSource = (array)$finalSource;
  3600. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3601. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3602. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3603. // 使用数据库中的最终数据
  3604. $roles = $finalRoles;
  3605. $scenes = $finalScenes;
  3606. $props = $finalProps;
  3607. }
  3608. } catch (\Exception $e) {
  3609. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3610. // 如果查询失败,继续使用内存中的数据
  3611. }
  3612. // 清理缓存
  3613. Redis::del($cacheKey);
  3614. echo "data: " . json_encode([
  3615. 'type' => 'completed',
  3616. 'data' => [
  3617. 'roles' => $roles,
  3618. 'scenes' => $scenes,
  3619. 'props' => $props,
  3620. 'total_time' => time() - $startTime
  3621. ]
  3622. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3623. if (ob_get_level() > 0) {
  3624. ob_flush();
  3625. }
  3626. flush();
  3627. break;
  3628. }
  3629. // 等待下次检查
  3630. sleep($checkInterval);
  3631. }
  3632. // 超时处理
  3633. if (time() - $startTime >= $maxDuration) {
  3634. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3635. try {
  3636. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3637. if ($finalSource) {
  3638. $finalSource = (array)$finalSource;
  3639. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3640. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3641. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3642. // 使用数据库中的最终数据
  3643. $roles = $finalRoles;
  3644. $scenes = $finalScenes;
  3645. $props = $finalProps;
  3646. }
  3647. } catch (\Exception $e) {
  3648. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3649. // 如果查询失败,继续使用内存中的数据
  3650. }
  3651. // 清理缓存
  3652. Redis::del($cacheKey);
  3653. echo "data: " . json_encode([
  3654. 'type' => 'timeout',
  3655. 'message' => '轮询超时,请刷新页面查看最新状态',
  3656. 'data' => [
  3657. 'roles' => $roles,
  3658. 'scenes' => $scenes,
  3659. 'props' => $props
  3660. ]
  3661. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3662. if (ob_get_level() > 0) {
  3663. ob_flush();
  3664. }
  3665. flush();
  3666. }
  3667. };
  3668. }
  3669. public function clipSegmentVideo($data) {
  3670. $segment_id = getProp($data, 'segment_id');
  3671. $video_time_point_start = getProp($data, 'video_time_point_start');
  3672. $video_time_point_end = getProp($data, 'video_time_point_end');
  3673. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3674. Utils::throwError('20003:参数异常');
  3675. }
  3676. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3677. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3678. }
  3679. $video_duration = $video_time_point_end - $video_time_point_start;
  3680. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3681. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3682. 'video_duration' => $video_duration,
  3683. 'video_time_point_start' => $video_time_point_start,
  3684. 'video_time_point_end' => $video_time_point_end,
  3685. 'updated_at' => date('Y-m-d H:i:s')
  3686. ]);
  3687. }
  3688. // 轮训获取图片任务结果
  3689. private function loopGetPicTaskResult($task_id) {
  3690. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3691. if (!$task) {
  3692. return '';
  3693. }
  3694. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3695. $model = getProp($task, 'model');
  3696. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3697. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3698. $isSyncModel = $isVolcModel || $isGptModel;
  3699. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3700. $start_count = 0;
  3701. $img_url = '';
  3702. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3703. sleep(3);
  3704. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3705. // 如果任务已经完成,直接返回结果
  3706. if ($task->status === 'success' && $task->result_url) {
  3707. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3708. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3709. }
  3710. // 如果任务已失败,返回空
  3711. if ($task->status === 'failed') {
  3712. return '';
  3713. }
  3714. if ($isSyncModel) continue;
  3715. // 查询任务状态
  3716. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3717. if ($statusInfo['status'] === 'success') {
  3718. $task->updateStatus('success', [
  3719. 'result_url' => $statusInfo['result_url'],
  3720. 'result_json' => $statusInfo['result_json'] ?? []
  3721. ]);
  3722. // 同步调整分镜图片状态和结果
  3723. if (getProp($task, 'alias_segment_id')) {
  3724. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3725. 'img_url' => $statusInfo['result_url'][0],
  3726. 'pic_task_status' => '已完成',
  3727. ]);
  3728. }
  3729. $img_url = $statusInfo['result_url'][0];
  3730. break;
  3731. } elseif ($statusInfo['status'] === 'failed') {
  3732. $task->updateStatus('failed', [
  3733. 'error_message' => $statusInfo['error_message'],
  3734. 'result_json' => $statusInfo['result_json'] ?? []
  3735. ]);
  3736. if (getProp($task, 'alias_segment_id')) {
  3737. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3738. 'pic_task_status' => '失败',
  3739. ]);
  3740. }
  3741. break;
  3742. }
  3743. $start_count++;
  3744. }
  3745. return $img_url;
  3746. }
  3747. /**
  3748. * 从分镜内容中提取涉及的角色
  3749. */
  3750. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3751. $found_characters = [];
  3752. foreach ($available_characters as $character) {
  3753. // 检查角色名称是否在分镜内容中出现
  3754. if (strpos($segment_content, $character) !== false) {
  3755. $found_characters[] = $character;
  3756. }
  3757. }
  3758. if (!$found_characters) {
  3759. foreach ($roles as $character) {
  3760. // 检查角色名称是否在分镜内容中出现
  3761. if (strpos($segment_content, $character) !== false) {
  3762. $found_characters[] = $character;
  3763. }
  3764. }
  3765. }
  3766. return array_unique($found_characters);
  3767. }
  3768. // 从分镜剧本中提取关键字段
  3769. private function handleSegmentContent(&$data) {
  3770. $segmentContent = getProp($data, 'segment_content');
  3771. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3772. $segmentData = [
  3773. 'description' => '',
  3774. 'composition' => '',
  3775. 'camera_movement' => '',
  3776. 'voice_actor' => '',
  3777. 'dialogue' => '',
  3778. 'frame_type' => '',
  3779. 'scene' => '', // 场景
  3780. 'characters' => '', // 出镜角色
  3781. 'tail_frame' => '', // 尾帧描述
  3782. 'emotion' => '中性', // 情感
  3783. 'gender' => '0', // 性别(0未知,1男,2女)
  3784. 'speed_ratio' => 0, // 语速
  3785. 'loudness_ratio' => 0, // 音量
  3786. 'emotion_scale' => 4, // 情感强度
  3787. 'pitch' => 0, // 音调
  3788. ];
  3789. // 用于存储需要从 segment_content 中移除的匹配项
  3790. $replaceEmptyArr = [];
  3791. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3792. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3793. $segmentData['description'] = trim($descMatch[1]);
  3794. $data['description'] = trim($descMatch[1]);
  3795. }
  3796. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3797. $segmentData['composition'] = trim($compMatch[1]);
  3798. $data['composition'] = trim($compMatch[1]);
  3799. }
  3800. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3801. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3802. $data['camera_movement'] = trim($cameraMatch[1]);
  3803. }
  3804. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3805. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3806. $data['voice_actor'] = trim($voiceMatch[1]);
  3807. }
  3808. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3809. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3810. $data['dialogue'] = trim($dialogueMatch[1]);
  3811. }
  3812. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3813. $segmentData['frame_type'] = trim($frameMatch[1]);
  3814. $data['frame_type'] = trim($frameMatch[1]);
  3815. }
  3816. // 场景字段
  3817. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3818. $segmentData['scene'] = trim($sceneMatch[1]);
  3819. $data['scene'] = trim($sceneMatch[1]);
  3820. }
  3821. // 出镜角色字段
  3822. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3823. $segmentData['characters'] = trim($charactersMatch[1]);
  3824. $data['characters'] = trim($charactersMatch[1]);
  3825. }
  3826. // 尾帧描述字段
  3827. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3828. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3829. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3830. }
  3831. // 情感字段
  3832. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3833. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3834. $segmentData['emotion'] = trim($emotionMatch[1]);
  3835. $data['emotion'] = trim($emotionMatch[1]);
  3836. }
  3837. // 性别字段
  3838. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3839. $replaceEmptyArr[] = trim($genderMatch[0]);
  3840. $genderStr = trim($genderMatch[1]);
  3841. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3842. $segmentData['gender'] = '1';
  3843. $data['gender'] = '1';
  3844. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3845. $segmentData['gender'] = '2';
  3846. $data['gender'] = '2';
  3847. } else {
  3848. $segmentData['gender'] = '0';
  3849. $data['gender'] = '0';
  3850. }
  3851. }
  3852. // 语速字段
  3853. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3854. $replaceEmptyArr[] = trim($speedMatch[0]);
  3855. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3856. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3857. }
  3858. // 音量字段
  3859. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3860. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3861. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3862. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3863. }
  3864. // 情感强度字段
  3865. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3866. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3867. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3868. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3869. }
  3870. // 音调字段
  3871. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3872. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3873. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3874. $data['pitch'] = (int)trim($pitchMatch[1]);
  3875. }
  3876. // 从 segment_content 中移除已提取的配音参数字段
  3877. if (!empty($replaceEmptyArr)) {
  3878. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3879. }
  3880. // 如果有配音角色,查询音色信息并验证情感
  3881. $voice_actor = $segmentData['voice_actor'];
  3882. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3883. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3884. $anime_id = getProp($data, 'anime_id');
  3885. $episode_id = getProp($data, 'episode_id');
  3886. // 优先从剧集的角色列表中查找
  3887. $roles = [];
  3888. if ($episode_id) {
  3889. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3890. if ($episode && getProp($episode, 'roles')) {
  3891. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3892. }
  3893. }
  3894. // 如果剧集中没有,从动漫的角色列表中查找
  3895. if (empty($roles) && $anime_id) {
  3896. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3897. if ($anime && getProp($anime, 'roles')) {
  3898. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3899. }
  3900. }
  3901. // 查找匹配的角色音色信息
  3902. $timbre_info = null;
  3903. foreach ($roles as $role) {
  3904. if (getProp($role, 'role') === $voice_actor) {
  3905. $timbre_info = $role;
  3906. break;
  3907. }
  3908. }
  3909. // 如果找到音色信息,添加到数据中
  3910. if ($timbre_info) {
  3911. $voice_type = getProp($timbre_info, 'voice_type');
  3912. $voice_name = getProp($timbre_info, 'voice_name');
  3913. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3914. if ($voice_type) {
  3915. $data['voice_type'] = $voice_type;
  3916. $segmentData['voice_type'] = $voice_type;
  3917. }
  3918. if ($voice_name) {
  3919. $data['voice_name'] = $voice_name;
  3920. $segmentData['voice_name'] = $voice_name;
  3921. }
  3922. if ($voice_audio_url) {
  3923. $data['voice_audio_url'] = $voice_audio_url;
  3924. $segmentData['voice_audio_url'] = $voice_audio_url;
  3925. }
  3926. // 验证情感是否在音色支持的情感列表中
  3927. if ($voice_type) {
  3928. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3929. if ($timbre_emotion) {
  3930. $timbre_emotion = explode(',', $timbre_emotion);
  3931. } else {
  3932. $timbre_emotion = [];
  3933. }
  3934. $emotion = getProp($segmentData, 'emotion', '中性');
  3935. if (!in_array($emotion, $timbre_emotion)) {
  3936. $emotion = '中性';
  3937. }
  3938. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3939. $emotion_list = array_flip($emotion_list);
  3940. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3941. $data['emotion_type'] = $emotion_type;
  3942. $segmentData['emotion_type'] = $emotion_type;
  3943. }
  3944. }
  3945. }
  3946. return $segmentData;
  3947. }
  3948. public function createSegmentVideoTask($data) {
  3949. $segment_id = getProp($data, 'segment_id');
  3950. $tail_frame = getProp($data, 'tail_frame');
  3951. $first_frame_url = getProp($data, 'first_frame_url');
  3952. $tail_frame_url = getProp($data, 'tail_frame_url');
  3953. $generate_audio = getProp($data, 'generate_audio', 0);
  3954. if (!$segment_id) {
  3955. Utils::throwError('1002:分镜ID不能为空');
  3956. }
  3957. // 获取分镜信息
  3958. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3959. if (!$segment) {
  3960. Utils::throwError('20003:分镜不存在');
  3961. }
  3962. $segment = (array)$segment;
  3963. $episode_id = getProp($segment, 'episode_id');
  3964. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3965. if (!$ratio) $ratio = '9:16';
  3966. // 获取分镜内容
  3967. $segmentContent = getProp($segment, 'segment_content', '');
  3968. // 检查 $segmentContent 中是否已有尾帧描述
  3969. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3970. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3971. $finalTailFrame = '';
  3972. if ($tail_frame) {
  3973. // 用户输入了尾帧描述,优先使用
  3974. $finalTailFrame = $tail_frame;
  3975. // 如果 segmentContent 中已有尾帧描述,需要替换
  3976. if ($contentHasTailFrame) {
  3977. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3978. }
  3979. } elseif ($contentHasTailFrame) {
  3980. // segmentContent 中有尾帧描述,使用它
  3981. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3982. } else {
  3983. // 两者都没有,使用分镜表中的尾帧描述
  3984. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3985. }
  3986. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3987. $hasDialogue = false;
  3988. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3989. $dialogue = trim($dialogueMatch[1]);
  3990. // 如果台词不为空且不是"无"
  3991. if (!empty($dialogue) && $dialogue !== '无') {
  3992. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3993. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3994. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3995. $hasDialogue = true;
  3996. }
  3997. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3998. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3999. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  4000. if (!preg_match('/^[“]/', $dialogue)) {
  4001. $dialogue = '“' . $dialogue;
  4002. }
  4003. if (!preg_match('/[”]$/', $dialogue)) {
  4004. $dialogue .= '”';
  4005. }
  4006. // 将修改后的台词替换回 $segmentContent
  4007. $originalDialogue = $dialogueMatch[1];
  4008. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  4009. }
  4010. }
  4011. // 构建完整的提示词
  4012. $fullPrompt = $segmentContent;
  4013. if ($finalTailFrame && !$contentHasTailFrame) {
  4014. // 只有当 segmentContent 中没有尾帧描述时才追加
  4015. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  4016. }
  4017. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  4018. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  4019. $fullPrompt = trim($fullPrompt);
  4020. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  4021. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  4022. // 智能选择视频时长
  4023. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  4024. $videoDuration = -1;
  4025. // 处理视频模型
  4026. $model = getProp($data, 'model');
  4027. if (!$model) {
  4028. // 用户没有输入,从episode表获取
  4029. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  4030. $model = getProp($episode, 'video_model');
  4031. if (!$model) {
  4032. // episode表也没有,使用默认值
  4033. $model = 'doubao-seedance-1-5-pro-251215';
  4034. }
  4035. }
  4036. // 验证模型是否在可用模型表中
  4037. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4038. $model = 'doubao-seedance-1-5-pro-251215';
  4039. }
  4040. // 保存到episode表
  4041. $episode_id = getProp($segment, 'episode_id');
  4042. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4043. 'video_model' => $model,
  4044. 'updated_at' => date('Y-m-d H:i:s')
  4045. ]);
  4046. // 构建视频生成参数
  4047. $videoParams = [
  4048. 'model' => $model,
  4049. 'alias_segment_id' => $segment_id,
  4050. 'prompt' => trim($fullPrompt),
  4051. 'video_duration' => $videoDuration,
  4052. 'video_resolution' => '720P',
  4053. 'seed' => -1,
  4054. 'ratio' => $ratio,
  4055. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4056. 'draft' => false,
  4057. 'watermark' => false,
  4058. 'camera_fixed' => false,
  4059. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4060. ];
  4061. // 如果分镜有图片,作为首帧
  4062. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4063. $hasVideo = !empty(getProp($segment, 'video_url'));
  4064. if ($hasImage) {
  4065. if ($first_frame_url) {
  4066. $videoParams['first_frame_url'] = $first_frame_url;
  4067. }else {
  4068. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4069. }
  4070. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4071. }
  4072. // 构建content数组
  4073. $videoParams['content'] = [
  4074. [
  4075. 'type' => 'text',
  4076. 'text' => $videoParams['prompt'],
  4077. ]
  4078. ];
  4079. // 如果有首帧图片,添加到content中
  4080. if ($hasImage) {
  4081. 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'])) {
  4082. $videoParams['content'][] = [
  4083. 'type' => 'image_url',
  4084. 'image_url' => [
  4085. 'url' => $videoParams['first_frame_url'],
  4086. ],
  4087. 'role' => 'reference_image',
  4088. ];
  4089. if (isset($videoParams['tail_frame_url'])) {
  4090. $videoParams['content'][] = [
  4091. 'type' => 'image_url',
  4092. 'image_url' => [
  4093. 'url' => $videoParams['tail_frame_url'],
  4094. ],
  4095. 'role' => 'reference_image',
  4096. ];
  4097. }
  4098. }else {
  4099. $videoParams['content'][] = [
  4100. 'type' => 'image_url',
  4101. 'image_url' => [
  4102. 'url' => $videoParams['first_frame_url'],
  4103. ],
  4104. 'role' => 'first_frame',
  4105. ];
  4106. if (isset($videoParams['tail_frame_url'])) {
  4107. $videoParams['content'][] = [
  4108. 'type' => 'image_url',
  4109. 'image_url' => [
  4110. 'url' => $videoParams['tail_frame_url'],
  4111. ],
  4112. 'role' => 'last_frame',
  4113. ];
  4114. }
  4115. }
  4116. }
  4117. // 获取配音音频URL
  4118. $audioUrl = getProp($segment, 'audio_url');
  4119. $audioDuration = getProp($segment, 'audio_duration');
  4120. // 音频传入的前提:必须有至少一张图片或一个视频
  4121. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4122. // 余额预检:按预估时长计算所需积分,不足直接报错
  4123. $chargeDuration = (int)ceil((float)$audioDuration);
  4124. if ($chargeDuration <= 0) {
  4125. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4126. }
  4127. $this->pointsService->checkUserPointsEnough(
  4128. $this->pointsService->getVideoChargePoints([
  4129. 'model' => $model,
  4130. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4131. 'video_duration' => $chargeDuration,
  4132. 'ratio' => $ratio,
  4133. 'generate_audio' => $current_generate_audio,
  4134. ])
  4135. );
  4136. // dd($videoParams);
  4137. // 根据模型选择不同的视频生成方法
  4138. if (strpos($model, 'jimeng') !== false) {
  4139. // 即梦模型参数调整
  4140. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4141. unset($videoParams['content']); // 即梦不使用content格式
  4142. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4143. } elseif (strpos($model, 'kling') !== false) {
  4144. // Keling模型参数调整
  4145. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4146. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4147. unset($videoParams['ratio']);
  4148. unset($videoParams['content']); // Keling不使用content格式
  4149. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4150. } elseif (strpos($model, 'zhizhen') !== false) {
  4151. // 智帧20等新模型使用统一API
  4152. // 构建统一API参数
  4153. $unifiedParams = [
  4154. 'model_code' => $model,
  4155. 'alias_segment_id' => $segment_id,
  4156. 'prompt' => trim($fullPrompt),
  4157. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4158. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4159. 'video_ratio' => $ratio,
  4160. 'seed' => -1,
  4161. ];
  4162. // 构建parameters参数
  4163. $parameters = [
  4164. 'seconds' => $unifiedParams['video_duration'],
  4165. 'resolution' => $unifiedParams['video_resolution'],
  4166. 'ratio' => $ratio,
  4167. // 'video_mode' => 'multi_image',
  4168. // 'mode' => 'multi_image',
  4169. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4170. ];
  4171. $hasImage = false;
  4172. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4173. if ($hasImage) {
  4174. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4175. if (isset($videoParams['tail_frame_url'])) {
  4176. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4177. }
  4178. // 只有在有图片的情况下才能添加参考音频
  4179. if ($audioUrl) {
  4180. // $parameters['reference_audios'] = [$audioUrl];
  4181. }
  4182. } else {
  4183. // 没有图片时,记录错误日志
  4184. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4185. 'segment_id' => $segment_id,
  4186. 'model' => $model
  4187. ]);
  4188. }
  4189. $unifiedParams['parameters'] = $parameters;
  4190. // 调用统一API创建任务
  4191. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4192. } else {
  4193. // Seedance模型(默认)
  4194. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4195. if ($this->isKuaikuaiSeedanceModel($model)) {
  4196. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4197. if ($canUseAudio && $audioUrl) {
  4198. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4199. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4200. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4201. // 优化提示词,增加音频相关描述
  4202. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4203. $videoParams['prompt'] = $audioPrompt;
  4204. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4205. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4206. }
  4207. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4208. } 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'])) {
  4209. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4210. // 添加配音音频到content中
  4211. $videoParams['content'][] = [
  4212. 'type' => 'audio_url',
  4213. 'audio_url' => [
  4214. 'url' => $audioUrl,
  4215. ],
  4216. 'role' => 'reference_audio',
  4217. ];
  4218. // 优化提示词,增加音频相关描述
  4219. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4220. $videoParams['prompt'] = $audioPrompt;
  4221. $videoParams['content'][0]['text'] = $audioPrompt;
  4222. } else {
  4223. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4224. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4225. }
  4226. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4227. }
  4228. }
  4229. // 更新分镜表的视频任务信息
  4230. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4231. 'video_task_id' => $task->id,
  4232. 'video_task_status' => '生成中',
  4233. 'generate_audio' => $generate_audio,
  4234. 'updated_at' => date('Y-m-d H:i:s')
  4235. ]);
  4236. return [
  4237. 'task_id' => $task->id,
  4238. 'status' => $task->status,
  4239. 'segment_id' => $segment_id,
  4240. 'video_duration' => $videoDuration
  4241. ];
  4242. }
  4243. /**
  4244. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4245. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4246. *
  4247. * @param string $model
  4248. * @return bool
  4249. */
  4250. public function isKuaikuaiSeedanceModel(string $model): bool
  4251. {
  4252. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4253. }
  4254. /**
  4255. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4256. *
  4257. * @param string $model
  4258. * @return bool
  4259. */
  4260. public function isBaiduSeedanceModel(string $model): bool
  4261. {
  4262. return in_array($model, [
  4263. 'baidu-doubao-seedance-2-0-260128',
  4264. 'baidu-doubao-seedance-2-0-fast-260128',
  4265. 'baidu-doubao-seedance-2-0-mini-260615',
  4266. 'baidu-doubao-seedance-2-5-260628',
  4267. ], true);
  4268. }
  4269. /**
  4270. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4271. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4272. *
  4273. * @param string $model
  4274. * @return bool
  4275. */
  4276. public function isOverseasBaiduSeedanceModel(string $model): bool
  4277. {
  4278. return in_array($model, [
  4279. 'baidu-dreamina-seedance-2-0-260128',
  4280. 'baidu-dreamina-seedance-2-0-fast-260128',
  4281. 'baidu-dreamina-seedance-2-0-mini-260615',
  4282. 'baidu-dreamina-seedance-2-5-260628',
  4283. ], true);
  4284. }
  4285. /**
  4286. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4287. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4288. *
  4289. * @param string $model
  4290. * @return bool
  4291. */
  4292. public function isSeedance20SeriesModel(string $model): bool
  4293. {
  4294. return strpos($model, 'doubao-seedance-2.0') !== false
  4295. || $this->isKuaikuaiSeedanceModel($model)
  4296. || $this->isBaiduSeedanceModel($model)
  4297. || $this->isOverseasBaiduSeedanceModel($model);
  4298. }
  4299. public function createActVideoTask($data) {
  4300. $act_id = getProp($data, 'act_id');
  4301. $first_frame_url = getProp($data, 'first_frame_url');
  4302. $tail_frame_url = getProp($data, 'tail_frame_url');
  4303. $generate_audio = getProp($data, 'generate_audio', 1);
  4304. $video_duration = getProp($data, 'video_duration');
  4305. $video_resolution = getProp($data, 'video_resolution');
  4306. $ratio = getProp($data, 'ratio');
  4307. $products = getProp($data, 'products', []);
  4308. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4309. if (!is_array($reference_images) || !is_array($products)) {
  4310. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4311. }
  4312. if (!$act_id) {
  4313. Utils::throwError('1002:片段ID不能为空');
  4314. }
  4315. // 获取片段信息
  4316. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4317. if (!$act) {
  4318. Utils::throwError('20003:片段不存在');
  4319. }
  4320. $act = (array)$act;
  4321. $anime_id = getProp($act, 'anime_id');
  4322. $episode_id = getProp($act, 'episode_id');
  4323. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4324. $ace_mode = getProp($anime, 'ace_mode');
  4325. $art_style_type = getProp($anime, 'art_style_type');
  4326. $art_style = getProp($anime, 'art_style');
  4327. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4328. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4329. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4330. // 将资产中新出现的资产放到extra_products中
  4331. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4332. if (!empty($products) && $episode) {
  4333. // 获取剧集中的角色、场景和道具列表
  4334. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4335. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4336. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4337. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4338. // 构建角色名称列表
  4339. $role_names = array_column($roles, 'role');
  4340. // 构建场景名称列表
  4341. $scene_names = array_column($scenes, 'scene');
  4342. // 构建道具名称列表
  4343. $prop_names = array_column($props, 'prop');
  4344. // 遍历传入的products
  4345. foreach ($products as $product) {
  4346. $product_name = getProp($product, 'product_name');
  4347. // 如果product_name不在roles、scenes和props中
  4348. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4349. // 查找是否在extra_products中存在同名的
  4350. $found = false;
  4351. foreach ($extra_products as $key => $extra_product) {
  4352. if (getProp($extra_product, 'product_name') === $product_name) {
  4353. // 有同名的则覆盖
  4354. $extra_products[$key] = $product;
  4355. $found = true;
  4356. break;
  4357. }
  4358. }
  4359. // 没有则新增
  4360. if (!$found) {
  4361. $extra_products[] = $product;
  4362. }
  4363. }
  4364. }
  4365. if ($extra_products) {
  4366. // 保存到数据库
  4367. DB::table('mp_anime_episodes')
  4368. ->where('id', $episode_id)
  4369. ->update([
  4370. 'extra_products' => json_encode($extra_products, 256),
  4371. 'updated_at' => date('Y-m-d H:i:s')
  4372. ]);
  4373. }
  4374. }
  4375. // 获取分镜内容
  4376. $actContent = getProp($act, 'act_show_content', '');
  4377. // 音效同出(默认使用)
  4378. $current_generate_audio = $generate_audio ? 1 : 0;
  4379. // 处理视频模型(需在构建提示词之前解析:决定角色音色是否使用参考音频)
  4380. $model = getProp($data, 'model');
  4381. if (!$model) {
  4382. $model = getProp($episode, 'video_model');
  4383. if (!$model) {
  4384. // episode表也没有,使用默认值
  4385. $model = 'seed-2';
  4386. }
  4387. }
  4388. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4389. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4390. if (!in_array($model, $valid_models)) {
  4391. $model = 'seed-2';
  4392. }
  4393. // 构建完整的提示词
  4394. $supportAudioReference = $this->isActReferenceAudioSupported($model);
  4395. $processResult = $this->processActContentWithProducts($actContent, $products, $supportAudioReference);
  4396. $fullPrompt = $processResult['content'];
  4397. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4398. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4399. // 角色音色参考音频(顺序与提示词中的<音频N>标记一一对应)
  4400. $reference_audios = $supportAudioReference ? ($processResult['reference_audios'] ?? []) : [];
  4401. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4402. // 保存到episode表(仅在专用方法中更新模型)
  4403. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4404. // 'video_model' => $model,
  4405. // 'updated_at' => date('Y-m-d H:i:s')
  4406. // ]);
  4407. // 余额预检:按预估时长计算所需积分,不足直接报错
  4408. $chargeDuration = (int)$videoDuration;
  4409. if ($chargeDuration <= 0) {
  4410. $chargeDuration = 5; // 无时长时按默认5秒预估
  4411. }
  4412. $this->pointsService->checkUserPointsEnough(
  4413. $this->pointsService->getVideoChargePoints([
  4414. 'model' => $model,
  4415. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4416. 'video_duration' => $chargeDuration,
  4417. 'ratio' => $ratio,
  4418. 'generate_audio' => $current_generate_audio,
  4419. ])
  4420. );
  4421. // 构建视频生成参数
  4422. $videoParams = [
  4423. 'model' => $model,
  4424. 'alias_act_id' => $act_id,
  4425. 'prompt' => trim($fullPrompt),
  4426. 'video_duration' => $videoDuration,
  4427. 'video_resolution' => $video_resolution,
  4428. 'seed' => -1,
  4429. 'ratio' => $ratio,
  4430. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4431. 'draft' => false,
  4432. 'watermark' => false,
  4433. 'camera_fixed' => false,
  4434. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4435. ];
  4436. // 如果分镜有图片,作为首帧
  4437. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4438. $hasVideo = !empty(getProp($act, 'video_url'));
  4439. if ($hasImage) {
  4440. if ($first_frame_url) {
  4441. $videoParams['first_frame_url'] = $first_frame_url;
  4442. }else {
  4443. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4444. }
  4445. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4446. }
  4447. // 构建content数组
  4448. $videoParams['content'] = [
  4449. [
  4450. 'type' => 'text',
  4451. 'text' => $videoParams['prompt'],
  4452. ]
  4453. ];
  4454. // 如果有首帧图片,添加到content中
  4455. if ($hasImage) {
  4456. 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'])) {
  4457. $videoParams['content'][] = [
  4458. 'type' => 'image_url',
  4459. 'image_url' => [
  4460. 'url' => $videoParams['first_frame_url'],
  4461. ],
  4462. 'role' => 'reference_image',
  4463. ];
  4464. if (isset($videoParams['tail_frame_url'])) {
  4465. $videoParams['content'][] = [
  4466. 'type' => 'image_url',
  4467. 'image_url' => [
  4468. 'url' => $videoParams['tail_frame_url'],
  4469. ],
  4470. 'role' => 'reference_image',
  4471. ];
  4472. }
  4473. }else {
  4474. $videoParams['content'][] = [
  4475. 'type' => 'image_url',
  4476. 'image_url' => [
  4477. 'url' => $videoParams['first_frame_url'],
  4478. ],
  4479. 'role' => 'first_frame',
  4480. ];
  4481. if (isset($videoParams['tail_frame_url'])) {
  4482. $videoParams['content'][] = [
  4483. 'type' => 'image_url',
  4484. 'image_url' => [
  4485. 'url' => $videoParams['tail_frame_url'],
  4486. ],
  4487. 'role' => 'last_frame',
  4488. ];
  4489. }
  4490. }
  4491. }
  4492. // dd($videoParams);
  4493. // 根据模型选择不同的视频生成方法
  4494. try {
  4495. if (strpos($model, 'jimeng') !== false) {
  4496. // 即梦模型参数调整
  4497. unset($videoParams['content']); // 即梦不使用content格式
  4498. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4499. } elseif (strpos($model, 'kling') !== false) {
  4500. // Keling模型参数调整
  4501. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4502. unset($videoParams['ratio']);
  4503. unset($videoParams['content']); // Keling不使用content格式
  4504. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4505. } elseif (strpos($model, 'zhizhen') !== false) {
  4506. // 智帧20等新模型使用统一API
  4507. // 构建统一API参数
  4508. $unifiedParams = [
  4509. 'model_code' => $model,
  4510. 'alias_act_id' => $act_id,
  4511. 'prompt' => trim($fullPrompt),
  4512. 'video_duration' => $videoDuration,
  4513. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4514. 'video_ratio' => $ratio,
  4515. 'seed' => -1,
  4516. ];
  4517. // 构建parameters参数
  4518. $parameters = [
  4519. 'seconds' => $unifiedParams['video_duration'],
  4520. 'resolution' => $unifiedParams['video_resolution'],
  4521. 'ratio' => $ratio,
  4522. // 'video_mode' => 'multi_image',
  4523. // 'mode' => 'multi_image',
  4524. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4525. ];
  4526. $hasImage = false;
  4527. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4528. if ($hasImage) {
  4529. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4530. if (isset($videoParams['tail_frame_url'])) {
  4531. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4532. }
  4533. } else {
  4534. // 没有图片时,记录错误日志
  4535. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4536. 'act_id' => $act_id,
  4537. 'model' => $model
  4538. ]);
  4539. }
  4540. if ($reference_images) {
  4541. // 限制只传入9张参考图
  4542. $reference_images = array_slice($reference_images, 0, 9);
  4543. // 在处理之前先保存原始reference_images到任务参数中
  4544. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4545. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4546. $parameters['reference_images'] = $reference_images;
  4547. $parameters['video_mode'] = 'multi_image';
  4548. $parameters['mode'] = 'multi_image';
  4549. }
  4550. // 角色音色参考音频:上传为素材并传入统一API(上传失败时清理提示词中的<音频N>标记)
  4551. if ($reference_audios) {
  4552. $unifiedParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4553. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $unifiedParams['prompt']);
  4554. $parameters['reference_audios'] = $reference_audio_assets;
  4555. // 音频素材上传失败的角色回退到音色提示词
  4556. $unifiedParams['prompt'] = $this->applyAudioVoiceFallbacks($unifiedParams['prompt'], $processResult['audio_voice_fallbacks'] ?? []);
  4557. $unifiedParams['prompt'] = trim($unifiedParams['prompt']);
  4558. }
  4559. $unifiedParams['parameters'] = $parameters;
  4560. // 调用统一API创建任务
  4561. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4562. } elseif ($this->isSeedance20SeriesModel($model)) {
  4563. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4564. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4565. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4566. // 保存原始参考图用于任务记录
  4567. $videoParams['reference_images'] = $reference_images;
  4568. if ($reference_images) {
  4569. // 限制只传入9张参考图
  4570. $reference_images = array_slice($reference_images, 0, 9);
  4571. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4572. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4573. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4574. $reference_image_assets = $isKuaikuai
  4575. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4576. : ($isDreamina
  4577. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4578. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4579. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4580. $videoParams['prompt'] = trim($fullPrompt);
  4581. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4582. $videoParams['reference_image_assets'] = $reference_image_assets;
  4583. }
  4584. // 角色音色参考音频:上传为素材并传入网关(上传失败时清理提示词中的<音频N>标记)
  4585. if ($reference_audios) {
  4586. $videoParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4587. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $fullPrompt);
  4588. // 音频素材上传失败的角色回退到音色提示词
  4589. $fullPrompt = $this->applyAudioVoiceFallbacks($fullPrompt, $processResult['audio_voice_fallbacks'] ?? []);
  4590. $videoParams['prompt'] = trim($fullPrompt);
  4591. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4592. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4593. }
  4594. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4595. if ($isKuaikuai) {
  4596. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4597. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4598. } else {
  4599. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4600. }
  4601. } else {
  4602. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4603. }
  4604. } catch (ApiException $e) {
  4605. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4606. if ($e->getCode() === 1001) {
  4607. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4608. }
  4609. throw $e;
  4610. } catch (\Exception $e) {
  4611. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4612. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4613. }
  4614. // 更新分镜表的视频任务信息
  4615. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4616. 'video_task_id' => $task->id,
  4617. 'video_task_status' => '生成中',
  4618. 'generate_audio' => $generate_audio,
  4619. 'updated_at' => date('Y-m-d H:i:s')
  4620. ]);
  4621. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4622. $episode_number = getProp($act, 'episode_number');
  4623. $act_number = getProp($act, 'act_number');
  4624. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4625. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4626. }
  4627. $result = [
  4628. 'task_id' => $task->id,
  4629. 'status' => $task->status,
  4630. 'act_id' => $act_id,
  4631. 'video_duration' => $videoDuration
  4632. ];
  4633. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4634. if ($task->status === 'failed' && !empty($task->error_message)) {
  4635. $result['error_message'] = mapErrorMessage($task->error_message);
  4636. }
  4637. return $result;
  4638. }
  4639. /**
  4640. * 文生视频通用方法
  4641. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4642. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4643. *
  4644. * @param array $data 请求参数
  4645. * @return array
  4646. */
  4647. public function generateVideo($data) {
  4648. $prompt = getProp($data, 'prompt');
  4649. if (empty($prompt)) {
  4650. Utils::throwError('20003:提示词不能为空');
  4651. }
  4652. $model = getProp($data, 'model');
  4653. if (!$model) {
  4654. $model = 'seed-2';
  4655. }
  4656. // 验证模型是否在可用模型表中
  4657. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4658. Utils::throwError('20003:该模型已不可用,请更换!');
  4659. }
  4660. $video_duration = getProp($data, 'video_duration', 5);
  4661. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4662. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4663. $ratio = getProp($data, 'ratio', '9:16');
  4664. $generate_audio = getProp($data, 'generate_audio', 1);
  4665. $seed = getProp($data, 'seed', -1);
  4666. $first_frame_url = getProp($data, 'first_frame_url');
  4667. $tail_frame_url = getProp($data, 'tail_frame_url');
  4668. // 参考图(支持数组或JSON字符串,最多9张)
  4669. $reference_images = getProp($data, 'reference_images', []);
  4670. if (is_string($reference_images)) {
  4671. $reference_images = json_decode($reference_images, true) ?: [];
  4672. }
  4673. if (!is_array($reference_images)) {
  4674. Utils::throwError('20003:参考图格式不正确');
  4675. }
  4676. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4677. $reference_images = array_slice($reference_images, 0, 9);
  4678. // 参考视频(支持数组或JSON字符串,最多3个)
  4679. $reference_videos = getProp($data, 'reference_videos', []);
  4680. if (is_string($reference_videos)) {
  4681. $reference_videos = json_decode($reference_videos, true) ?: [];
  4682. }
  4683. if (!is_array($reference_videos)) {
  4684. Utils::throwError('20003:参考视频格式不正确');
  4685. }
  4686. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4687. if (count($reference_videos) > 3) {
  4688. Utils::throwError('20003:参考视频最多选择3个');
  4689. }
  4690. $reference_videos = array_slice($reference_videos, 0, 3);
  4691. // 参考音频(支持数组或JSON字符串,最多3个)
  4692. $reference_audios = getProp($data, 'reference_audios', []);
  4693. if (is_string($reference_audios)) {
  4694. $reference_audios = json_decode($reference_audios, true) ?: [];
  4695. }
  4696. if (!is_array($reference_audios)) {
  4697. Utils::throwError('20003:参考音频格式不正确');
  4698. }
  4699. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4700. if (count($reference_audios) > 3) {
  4701. Utils::throwError('20003:参考音频最多选择3个');
  4702. }
  4703. $reference_audios = array_slice($reference_audios, 0, 3);
  4704. // 余额预检:按预估时长计算所需积分,不足直接报错
  4705. $chargeDuration = (int)ceil((float)$video_duration);
  4706. if ($chargeDuration <= 0) {
  4707. $chargeDuration = 5; // 无时长时按默认5秒预估
  4708. }
  4709. $this->pointsService->checkUserPointsEnough(
  4710. $this->pointsService->getVideoChargePoints([
  4711. 'model' => $model,
  4712. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4713. 'video_duration' => $chargeDuration,
  4714. 'ratio' => $ratio,
  4715. 'generate_audio' => (int)$generate_audio,
  4716. ])
  4717. );
  4718. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4719. $videoParams = [
  4720. 'model' => $model,
  4721. 'prompt' => $prompt,
  4722. 'video_duration' => $video_duration,
  4723. 'video_resolution' => $video_resolution,
  4724. 'seed' => $seed,
  4725. 'ratio' => $ratio,
  4726. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4727. 'draft' => getProp($data, 'draft', false),
  4728. 'watermark' => getProp($data, 'watermark', false),
  4729. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4730. ];
  4731. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4732. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4733. // 构建content数组
  4734. $videoParams['content'] = [
  4735. [
  4736. 'type' => 'text',
  4737. 'text' => $prompt,
  4738. ]
  4739. ];
  4740. // 根据模型选择不同的视频生成方法
  4741. if (strpos($model, 'jimeng') !== false) {
  4742. // 即梦模型参数调整
  4743. unset($videoParams['content']); // 即梦不使用content格式
  4744. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4745. } elseif (strpos($model, 'kling') !== false) {
  4746. // 可灵模型参数调整
  4747. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4748. unset($videoParams['ratio']);
  4749. unset($videoParams['content']); // 可灵不使用content格式
  4750. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4751. } elseif (strpos($model, 'zhizhen') !== false) {
  4752. // 智帧等新模型使用统一API
  4753. $unifiedParams = [
  4754. 'model_code' => $model,
  4755. 'prompt' => $prompt,
  4756. 'video_duration' => $video_duration,
  4757. 'video_resolution' => strtolower($video_resolution),
  4758. 'video_ratio' => $ratio,
  4759. 'seed' => $seed,
  4760. ];
  4761. // 构建parameters参数
  4762. $parameters = [
  4763. 'seconds' => $unifiedParams['video_duration'],
  4764. 'resolution' => $unifiedParams['video_resolution'],
  4765. 'ratio' => $ratio,
  4766. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4767. ];
  4768. // 首帧和尾帧
  4769. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4770. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4771. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4772. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4773. if ($refImageUrls) {
  4774. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4775. }
  4776. // 参考图处理
  4777. if ($reference_images) {
  4778. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4779. $parameters['reference_images'] = $reference_images;
  4780. $parameters['video_mode'] = 'multi_image';
  4781. $parameters['mode'] = 'multi_image';
  4782. }
  4783. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4784. if ($reference_videos) {
  4785. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4786. $parameters['reference_videos'] = $reference_videos;
  4787. }
  4788. if ($reference_audios) {
  4789. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4790. $parameters['reference_audios'] = $reference_audios;
  4791. }
  4792. $unifiedParams['parameters'] = $parameters;
  4793. // 调用统一API创建任务
  4794. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4795. } elseif ($this->isSeedance20SeriesModel($model)) {
  4796. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4797. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4798. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4799. $videoParams['reference_images'] = $reference_images;
  4800. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4801. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4802. if ($refImageUrls) {
  4803. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4804. }
  4805. if ($reference_images) {
  4806. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4807. $reference_image_assets = $isKuaikuai
  4808. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4809. : ($isDreamina
  4810. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4811. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4812. $videoParams['reference_image_assets'] = $reference_image_assets;
  4813. }
  4814. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4815. if ($reference_videos) {
  4816. $reference_video_assets = $isKuaikuai
  4817. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4818. : ($isDreamina
  4819. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4820. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4821. $videoParams['reference_video_assets'] = $reference_video_assets;
  4822. }
  4823. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4824. if ($reference_audios) {
  4825. $reference_audio_assets = $isKuaikuai
  4826. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4827. : ($isDreamina
  4828. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4829. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4830. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4831. }
  4832. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4833. if ($reference_images || $reference_videos || $reference_audios) {
  4834. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4835. }
  4836. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4837. if ($isKuaikuai) {
  4838. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4839. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4840. } else {
  4841. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4842. }
  4843. } else {
  4844. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4845. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4846. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4847. if ($refImageUrls) {
  4848. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4849. }
  4850. if ($reference_videos) {
  4851. foreach ($reference_videos as $videoUrl) {
  4852. $videoParams['content'][] = [
  4853. 'type' => 'video_url',
  4854. 'video_url' => [
  4855. 'url' => $videoUrl,
  4856. ],
  4857. 'role' => 'reference_video',
  4858. ];
  4859. }
  4860. }
  4861. if ($reference_audios) {
  4862. foreach ($reference_audios as $audioUrl) {
  4863. $videoParams['content'][] = [
  4864. 'type' => 'audio_url',
  4865. 'audio_url' => [
  4866. 'url' => $audioUrl,
  4867. ],
  4868. 'role' => 'reference_audio',
  4869. ];
  4870. }
  4871. }
  4872. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4873. }
  4874. return [
  4875. 'task_id' => $task->id,
  4876. 'status' => $task->status,
  4877. 'model' => $model,
  4878. 'video_duration' => $video_duration,
  4879. 'video_resolution' => $video_resolution,
  4880. 'ratio' => $ratio
  4881. ];
  4882. }
  4883. /**
  4884. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4885. *
  4886. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4887. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4888. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4889. *
  4890. * @param array $data
  4891. * @return array
  4892. */
  4893. public function previewCharge(array $data): array
  4894. {
  4895. $mode = (string)getProp($data, 'mode', '');
  4896. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4897. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4898. }
  4899. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4900. $scene = (string)getProp($data, 'scene', 'video_generation');
  4901. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4902. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4903. $scene = 'video_to_video';
  4904. }
  4905. $items = [];
  4906. $model = '';
  4907. $resolution = '';
  4908. if ($mode === 'video') {
  4909. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4910. $model = (string)getProp($data, 'model', '');
  4911. if (!$model) {
  4912. Utils::throwError('1002:model参数不能为空');
  4913. }
  4914. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4915. $duration = (int)getProp($data, 'video_duration', 5);
  4916. if ($duration <= 0) {
  4917. $duration = 5;
  4918. }
  4919. $count = max(1, (int)getProp($data, 'count', 1));
  4920. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4921. 'model' => $model,
  4922. 'video_resolution' => $resolution,
  4923. 'video_duration' => $duration,
  4924. 'mode' => $scene,
  4925. ]);
  4926. $points = $pointsPerVideo * $count;
  4927. $items[] = [
  4928. 'type' => 'video',
  4929. 'model' => $model,
  4930. 'video_resolution' => $resolution,
  4931. 'video_duration' => $duration,
  4932. 'count' => $count,
  4933. 'points' => $points,
  4934. ];
  4935. } elseif ($mode === 'image') {
  4936. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4937. $model = (string)getProp($data, 'model', '');
  4938. if (!$model) {
  4939. Utils::throwError('1002:model参数不能为空');
  4940. }
  4941. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4942. if (!$resolution) {
  4943. $width = (int)getProp($data, 'width', 0);
  4944. $height = (int)getProp($data, 'height', 0);
  4945. if ($width <= 0 || $height <= 0) {
  4946. $width = 1600;
  4947. $height = 2848;
  4948. }
  4949. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4950. }
  4951. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4952. $points = $this->pointsService->getImageChargePoints([
  4953. 'model' => $model,
  4954. 'resolution' => $resolution,
  4955. ]) * $imageNum;
  4956. $items[] = [
  4957. 'type' => 'image',
  4958. 'model' => $model,
  4959. 'resolution' => $resolution,
  4960. 'image_num' => $imageNum,
  4961. 'points' => $points,
  4962. ];
  4963. } else {
  4964. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4965. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4966. $priceType = (string)getProp($data, 'price_type', 'special');
  4967. if (!in_array($priceType, ['special', 'normal'], true)) {
  4968. Utils::throwError('1003:price_type参数仅支持special或normal');
  4969. }
  4970. $count = max(1, (int)getProp($data, 'count', 1));
  4971. $animeId = getProp($data, 'anime_id');
  4972. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4973. if ($animeId && $generateEpisodes > 0) {
  4974. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4975. $priceType = 'special';
  4976. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4977. ->where('anime_id', $animeId)
  4978. ->where('is_default', 1)
  4979. ->max('episode_number');
  4980. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4981. $startEpisodeNumber = $currentMaxEpisode + 1;
  4982. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4983. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4984. ->where('anime_id', $animeId)
  4985. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4986. ->whereIn('status', ['pending', 'processing', 'completed'])
  4987. ->count();
  4988. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4989. if ($count < 0) {
  4990. $count = 0;
  4991. }
  4992. }
  4993. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4994. $items[] = [
  4995. 'type' => 'chat',
  4996. 'count' => $count,
  4997. 'price_type' => $priceType,
  4998. 'points' => $points,
  4999. ];
  5000. }
  5001. $totalPoints = 0;
  5002. foreach ($items as $item) {
  5003. $totalPoints += $item['points'];
  5004. }
  5005. return [
  5006. 'mode' => $mode,
  5007. 'total_points' => $totalPoints,
  5008. 'items' => $items,
  5009. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  5010. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  5011. ];
  5012. }
  5013. /**
  5014. * 根据提示词内容智能计算最优视频时长
  5015. *
  5016. * @param string $segmentContent 分镜内容
  5017. * @param string $tailFrame 尾帧描述
  5018. * @return int 视频时长(2-12秒)
  5019. */
  5020. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  5021. // 合并所有文本内容
  5022. $fullText = trim($segmentContent . ' ' . $tailFrame);
  5023. // 如果没有内容,返回默认时长
  5024. if (empty($fullText)) {
  5025. return 5;
  5026. }
  5027. // 计算文本长度(中文字符按2个字符计算)
  5028. $textLength = mb_strlen($fullText, 'UTF-8');
  5029. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  5030. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  5031. // 分析内容复杂度
  5032. $complexityScore = $this->analyzeContentComplexity($fullText);
  5033. // 基础时长计算(根据文本长度)
  5034. $baseDuration = 3; // 默认2秒
  5035. // if ($adjustedLength <= 20) {
  5036. // $baseDuration = 3;
  5037. // } elseif ($adjustedLength <= 40) {
  5038. // $baseDuration = 4;
  5039. // } elseif ($adjustedLength <= 60) {
  5040. // $baseDuration = 5;
  5041. // } elseif ($adjustedLength <= 80) {
  5042. // $baseDuration = 6;
  5043. // } elseif ($adjustedLength <= 100) {
  5044. // $baseDuration = 7;
  5045. // } elseif ($adjustedLength <= 120) {
  5046. // $baseDuration = 8;
  5047. // } else {
  5048. // $baseDuration = 9;
  5049. // }
  5050. // 根据内容复杂度调整时长
  5051. $finalDuration = $baseDuration + $complexityScore;
  5052. // 确保时长在2-12秒范围内
  5053. return max(4, min(12, $finalDuration));
  5054. }
  5055. /**
  5056. * 分析内容复杂度,返回时长调整值
  5057. *
  5058. * @param string $text 文本内容
  5059. * @return int 调整值(-2到+3)
  5060. */
  5061. private function analyzeContentComplexity($text) {
  5062. $score = 0;
  5063. // 动作关键词(需要更长时间展现)
  5064. $actionKeywords = [
  5065. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  5066. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  5067. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  5068. ];
  5069. // 静态关键词(可以用较短时间)
  5070. $staticKeywords = [
  5071. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5072. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5073. ];
  5074. // 复杂场景关键词(需要更长时间)
  5075. $complexSceneKeywords = [
  5076. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5077. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5078. ];
  5079. // 情感关键词(需要适中时间表现)
  5080. $emotionKeywords = [
  5081. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5082. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5083. ];
  5084. // 检查动作关键词
  5085. foreach ($actionKeywords as $keyword) {
  5086. if (strpos($text, $keyword) !== false) {
  5087. $score += 1;
  5088. break; // 避免重复加分
  5089. }
  5090. }
  5091. // 检查静态关键词
  5092. foreach ($staticKeywords as $keyword) {
  5093. if (strpos($text, $keyword) !== false) {
  5094. $score -= 1;
  5095. break;
  5096. }
  5097. }
  5098. // 检查复杂场景关键词
  5099. foreach ($complexSceneKeywords as $keyword) {
  5100. if (strpos($text, $keyword) !== false) {
  5101. $score += 1;
  5102. break;
  5103. }
  5104. }
  5105. // 检查情感关键词
  5106. foreach ($emotionKeywords as $keyword) {
  5107. if (strpos($text, $keyword) !== false) {
  5108. $score += 1;
  5109. break;
  5110. }
  5111. }
  5112. // 检查时间相关词汇
  5113. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5114. $score += 1;
  5115. }
  5116. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5117. $score -= 1;
  5118. }
  5119. // 检查转场词汇
  5120. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5121. $score += 1;
  5122. }
  5123. // 检查环境描述(复杂环境需要更多时间)
  5124. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5125. $score += 1;
  5126. }
  5127. // 检查对话内容(对话需要更多时间)
  5128. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5129. $score += 1;
  5130. }
  5131. // 限制调整范围
  5132. return max(-1, min(4, $score));
  5133. }
  5134. /**
  5135. * 创建完整视频合成任务
  5136. *
  5137. * @param array $data
  5138. * @return array
  5139. */
  5140. public function createCompleteVideoTask($data)
  5141. {
  5142. $animeId = getProp($data, 'anime_id');
  5143. $episodeId = getProp($data, 'episode_id');
  5144. // 验证参数
  5145. if (!$animeId || !$episodeId) {
  5146. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5147. }
  5148. // 检查是否已存在处理中的任务
  5149. $existingTask = DB::table('mp_complete_video_tasks')
  5150. ->where('anime_id', $animeId)
  5151. ->where('episode_id', $episodeId)
  5152. ->whereIn('generate_status', ['执行中'])
  5153. ->first();
  5154. if ($existingTask) {
  5155. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5156. }
  5157. // 获取全能模式状态
  5158. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5159. if ((int)$ace_mode === 1) {
  5160. // 获取所有片段的配音视频,按 act_number 排序
  5161. $segments = DB::table('mp_episode_segments')
  5162. ->where('anime_id', $animeId)
  5163. ->where('episode_id', $episodeId)
  5164. ->orderBy('segment_number')
  5165. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5166. ->get();
  5167. // 检查是否所有片段都有视频
  5168. $missingVideos = $segments->filter(function($segment) {
  5169. return empty($segment->video_url);
  5170. });
  5171. if ($missingVideos->isNotEmpty()) {
  5172. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5173. }
  5174. }else {
  5175. // 获取所有分镜的配音视频,按 segment_number 排序
  5176. $segments = DB::table('mp_episode_segments')
  5177. ->where('anime_id', $animeId)
  5178. ->where('episode_id', $episodeId)
  5179. ->orderBy('segment_number')
  5180. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5181. ->get();
  5182. // 检查是否所有分镜都有配音和视频
  5183. $missingVideos = $segments->filter(function($segment) {
  5184. return empty($segment->audio_url) || empty($segment->video_url);
  5185. });
  5186. if ($missingVideos->isNotEmpty()) {
  5187. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5188. }
  5189. }
  5190. if ($segments->isEmpty()) {
  5191. Utils::throwError('20003:未找到该剧集的分镜数据');
  5192. }
  5193. // 获取当前完整视频url
  5194. $completeVideoUrl = DB::table('mp_anime_episodes')
  5195. ->where('anime_id', $animeId)
  5196. ->where('id', $episodeId)
  5197. ->value('complete_video_url');
  5198. // 构建 generate_json
  5199. $generateJson = [];
  5200. $sequence = 1;
  5201. foreach ($segments as $segment) {
  5202. if ((int)$ace_mode === 1) {
  5203. $generateJson[] = [
  5204. 'sequence' => $sequence++,
  5205. 'video_url' => $segment->video_url,
  5206. 'video_time_point_start' => $segment->video_time_point_start,
  5207. 'video_time_point_end' => $segment->video_time_point_end
  5208. ];
  5209. }else {
  5210. $generateJson[] = [
  5211. 'sequence' => $sequence++,
  5212. 'video_url' => $segment->video_url,
  5213. 'audio_url' => $segment->audio_url,
  5214. 'video_time_point_start' => $segment->video_time_point_start,
  5215. 'video_time_point_end' => $segment->video_time_point_end
  5216. ];
  5217. }
  5218. }
  5219. // 创建任务
  5220. $now = date('Y-m-d H:i:s');
  5221. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5222. 'anime_id' => $animeId,
  5223. 'episode_id' => $episodeId,
  5224. 'generate_json' => json_encode($generateJson, 256),
  5225. 'generate_status' => '执行中',
  5226. 'complete_video_url' => '',
  5227. 'created_at' => $now,
  5228. 'updated_at' => $now
  5229. ]);
  5230. if (!$taskId) {
  5231. Utils::throwError('20003:创建任务失败');
  5232. }
  5233. // 更新剧集表的任务ID和状态
  5234. $boolen = DB::table('mp_anime_episodes')
  5235. ->where('anime_id', $animeId)
  5236. ->where('id', $episodeId)
  5237. ->update([
  5238. 'complete_video_task_id' => $taskId,
  5239. 'complete_video_task_status' => '执行中',
  5240. 'updated_at' => $now
  5241. ]);
  5242. if (!$boolen) {
  5243. Utils::throwError('20003:更新剧集表失败');
  5244. }
  5245. dLog('anime')->info('创建完整视频合成任务', [
  5246. 'task_id' => $taskId,
  5247. 'anime_id' => $animeId,
  5248. 'episode_id' => $episodeId,
  5249. 'segment_count' => count($generateJson)
  5250. ]);
  5251. // 请求远程服务器执行生成
  5252. $client = new Client(['timeout' => 600, 'verify' => false]);
  5253. try {
  5254. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5255. $response = $result->getBody()->getContents();
  5256. $response_arr = json_decode($response, true);
  5257. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5258. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5259. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5260. // // 更新任务状态为失败
  5261. // DB::table('mp_complete_video_tasks')
  5262. // ->where('id', $taskId)
  5263. // ->update([
  5264. // 'generate_status' => '执行失败',
  5265. // 'error_message' => $error_msg,
  5266. // 'updated_at' => date('Y-m-d H:i:s')
  5267. // ]);
  5268. // // 同步更新剧集表状态
  5269. // DB::table('mp_anime_episodes')
  5270. // ->where('complete_video_task_id', $taskId)
  5271. // ->update([
  5272. // 'complete_video_task_status' => '执行失败',
  5273. // 'updated_at' => date('Y-m-d H:i:s')
  5274. // ]);
  5275. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5276. }
  5277. } catch (\Exception $e) {
  5278. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5279. // 更新任务状态为失败
  5280. DB::table('mp_complete_video_tasks')
  5281. ->where('id', $taskId)
  5282. ->update([
  5283. 'generate_status' => '执行失败',
  5284. 'error_message' => $e->getMessage(),
  5285. 'updated_at' => date('Y-m-d H:i:s')
  5286. ]);
  5287. // 同步更新剧集表状态
  5288. DB::table('mp_anime_episodes')
  5289. ->where('complete_video_task_id', $taskId)
  5290. ->update([
  5291. 'complete_video_task_status' => '执行失败',
  5292. 'updated_at' => date('Y-m-d H:i:s')
  5293. ]);
  5294. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5295. }
  5296. // 开始轮询任务状态
  5297. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5298. $pollInterval = 5; // 每5秒轮询一次
  5299. $attempt = 0;
  5300. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5301. while ($attempt < $maxAttempts) {
  5302. sleep($pollInterval);
  5303. $attempt++;
  5304. // 查询任务状态
  5305. $task = DB::table('mp_complete_video_tasks')
  5306. ->where('id', $taskId)
  5307. ->first();
  5308. if (!$task) {
  5309. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5310. Utils::throwError('20003:任务不存在');
  5311. }
  5312. dLog('anime')->info('轮询任务状态', [
  5313. 'task_id' => $taskId,
  5314. 'attempt' => $attempt,
  5315. 'status' => $task->generate_status
  5316. ]);
  5317. // 检查任务是否完成
  5318. if ($task->generate_status === '执行成功') {
  5319. // 同步更新剧集表状态
  5320. $boolen3 = DB::table('mp_anime_episodes')
  5321. ->where('anime_id', $animeId)
  5322. ->where('id', $episodeId)
  5323. ->update([
  5324. 'complete_video_url' => $task->complete_video_url,
  5325. 'complete_video_task_status' => '执行成功',
  5326. 'updated_at' => date('Y-m-d H:i:s')
  5327. ]);
  5328. dLog('anime')->info('视频合成任务完成', [
  5329. 'task_id' => $taskId,
  5330. 'video_url' => $task->complete_video_url,
  5331. 'attempts' => $attempt
  5332. ]);
  5333. // 如果更新成功则远程删除之前的文件
  5334. if ($boolen3 && $completeVideoUrl) {
  5335. $encode_url = urlencode($completeVideoUrl);
  5336. $client = new Client(['timeout' => 300, 'verify' => false]);
  5337. // 根据ID通过API通知合成音频
  5338. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5339. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5340. $response = $result->getBody()->getContents();
  5341. $response_arr = json_decode($response, true);
  5342. Log::info('火山删除音频返回: '.$response);
  5343. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5344. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5345. Log::info('火山删除音频失败: '.$error_msg);
  5346. // Utils::throwError('20003:火山删除音频失败');
  5347. }
  5348. }
  5349. return [
  5350. 'task_id' => $taskId,
  5351. 'anime_id' => $animeId,
  5352. 'episode_id' => $episodeId,
  5353. 'segment_count' => count($generateJson),
  5354. 'generate_status' => '执行成功',
  5355. 'complete_video_url' => $task->complete_video_url,
  5356. ];
  5357. }
  5358. // 检查任务是否失败
  5359. if ($task->generate_status === '执行失败') {
  5360. // 同步更新剧集表状态
  5361. DB::table('mp_anime_episodes')
  5362. ->where('anime_id', $animeId)
  5363. ->where('id', $episodeId)
  5364. ->update([
  5365. 'complete_video_task_status' => '执行失败',
  5366. 'updated_at' => date('Y-m-d H:i:s')
  5367. ]);
  5368. $errorMessage = $task->error_message ?? '未知错误';
  5369. dLog('anime')->error('视频合成任务失败', [
  5370. 'task_id' => $taskId,
  5371. 'error' => $errorMessage,
  5372. 'attempts' => $attempt
  5373. ]);
  5374. return [
  5375. 'task_id' => $taskId,
  5376. 'anime_id' => $animeId,
  5377. 'episode_id' => $episodeId,
  5378. 'segment_count' => count($generateJson),
  5379. 'generate_status' => '执行失败',
  5380. 'error_message' => $errorMessage
  5381. ];
  5382. }
  5383. }
  5384. // 超时处理
  5385. dLog('anime')->warning('视频合成任务超时', [
  5386. 'task_id' => $taskId,
  5387. 'max_attempts' => $maxAttempts,
  5388. 'timeout_seconds' => $maxAttempts * $pollInterval
  5389. ]);
  5390. // 更新任务状态为超时
  5391. DB::table('mp_complete_video_tasks')
  5392. ->where('id', $taskId)
  5393. ->update([
  5394. 'generate_status' => '超时',
  5395. 'error_message' => '任务执行超时(5分钟)',
  5396. 'updated_at' => date('Y-m-d H:i:s')
  5397. ]);
  5398. return [
  5399. 'task_id' => $taskId,
  5400. 'anime_id' => $animeId,
  5401. 'episode_id' => $episodeId,
  5402. 'segment_count' => count($generateJson),
  5403. 'generate_status' => '超时',
  5404. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5405. ];
  5406. }
  5407. /**
  5408. * 根据 inner_prompt_type 附加内置提示词
  5409. *
  5410. * @param string $prompt 用户提示词
  5411. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5412. * @return string 合并后的提示词
  5413. */
  5414. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5415. {
  5416. $innerPromptMap = [
  5417. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5418. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5419. ];
  5420. if (!isset($innerPromptMap[$innerPromptType])) {
  5421. return $prompt;
  5422. }
  5423. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5424. }
  5425. /**
  5426. * 根据 inner_prompt_type 获取生成图片数量
  5427. *
  5428. * @param int $innerPromptType 内置提示词类型
  5429. * @param int $imageNum 传入的图片张数
  5430. * @return int 图片数量
  5431. */
  5432. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5433. {
  5434. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5435. }
  5436. /**
  5437. * 提取图片生成结果URL
  5438. *
  5439. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5440. * @param int $innerPromptType 内置提示词类型
  5441. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5442. */
  5443. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5444. {
  5445. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5446. if (is_array($resultUrls) && !empty($resultUrls)) {
  5447. $resultUrls = array_values($resultUrls);
  5448. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5449. }
  5450. if (!empty($resultUrl)) {
  5451. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5452. }
  5453. return (int)$innerPromptType === 2 ? [] : '';
  5454. }
  5455. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5456. $prompt = getProp($data, 'prompt');
  5457. $episode_id = getProp($data, 'episode_id');
  5458. $ref_img_urls = getProp($data, 'ref_img_urls');
  5459. $ratio = getProp($data, 'ratio', '9:16');
  5460. $resolution = getProp($data, 'resolution', '2k');
  5461. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5462. $imageNum = (int)getProp($data, 'image_num', 1);
  5463. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5464. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5465. // 参数验证
  5466. $resolution = strtolower($resolution);
  5467. if (!isset($sizeMap[$resolution])) {
  5468. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5469. }
  5470. if (!isset($sizeMap[$resolution][$ratio])) {
  5471. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5472. }
  5473. // 根据 ratio 和 resolution 确定宽高
  5474. $width = $sizeMap[$resolution][$ratio]['width'];
  5475. $height = $sizeMap[$resolution][$ratio]['height'];
  5476. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5477. if (is_json($ref_img_urls)) {
  5478. $ref_img_urls = json_decode($ref_img_urls, true);
  5479. }else {
  5480. $ref_img_urls = explode(',', $ref_img_urls);
  5481. }
  5482. }
  5483. // 处理图片模型
  5484. $model = getProp($data, 'model');
  5485. if (!$model) {
  5486. // 用户没有输入,从episode表获取
  5487. if ($episode_id) {
  5488. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5489. $model = getProp($episode, 'image_model');
  5490. }
  5491. if (!$model) {
  5492. // episode表也没有,使用默认值
  5493. $model = 'gpt-image-2';
  5494. }
  5495. }
  5496. // 验证模型是否在可用模型表中
  5497. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5498. // $model = 'gpt-image-2';
  5499. Utils::throwError('20003:该模型已不可用,请更换!');
  5500. }
  5501. // 保存到episode表
  5502. if ($episode_id) {
  5503. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5504. 'image_model' => $model,
  5505. 'updated_at' => date('Y-m-d H:i:s')
  5506. ]);
  5507. }
  5508. // 参数验证
  5509. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5510. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5511. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5512. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5513. try {
  5514. // 创建图片生成任务
  5515. $params = [
  5516. 'prompt' => $prompt,
  5517. 'model' => $model,
  5518. 'ref_img_urls' => '',
  5519. 'width' => $width,
  5520. 'height' => $height,
  5521. 'image_num' => $imageNum,
  5522. // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
  5523. 'anime_id' => getProp($data, 'anime_id'),
  5524. 'episode_id' => $episode_id,
  5525. ];
  5526. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5527. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5528. $task_id = $task->id;
  5529. if (!$task_id) {
  5530. Utils::throwError('20003:创建图片生成任务失败');
  5531. }
  5532. // 创建任务中心记录并关联图片任务ID
  5533. $taskCenter = $this->taskCenterService->createTask('image', [
  5534. 'title' => '文生图',
  5535. 'ref_task_id' => $task_id,
  5536. // 'prompt' => $prompt,
  5537. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5538. ]);
  5539. $taskCenterId = $taskCenter->id;
  5540. // 组装本次任务信息(用于init消息,类似generateVideo)
  5541. $taskInfo = [
  5542. 'task_id' => $task_id,
  5543. 'status' => getProp($task, 'status', 'processing'),
  5544. 'model' => $model,
  5545. 'ratio' => $ratio,
  5546. 'resolution' => $resolution,
  5547. 'image_num' => $imageNum,
  5548. ];
  5549. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5550. if (is_callable($onTaskCreated)) {
  5551. $onTaskCreated($taskCenterId, $taskInfo);
  5552. }
  5553. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5554. $model = getProp($task, 'model');
  5555. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5556. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5557. $isSyncModel = $isVolcModel || $isGptModel;
  5558. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5559. $start_time = time();
  5560. $timeout = 900; // 15分钟
  5561. $img_url = '';
  5562. $img_urls = [];
  5563. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5564. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5565. while (time() - $start_time < $timeout) {
  5566. sleep(3);
  5567. // 每分钟发送一次队列状态消息(仅流式模式)
  5568. if (is_callable($onPoll)) {
  5569. $currentTime = time();
  5570. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5571. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5572. $lastQueueMessageTime = $currentTime;
  5573. }
  5574. }
  5575. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5576. if ($isSyncModel) {
  5577. // 刷新任务状态
  5578. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5579. if ($task->status === 'success' && $task->result_url) {
  5580. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5581. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5582. if (!empty($resultUrls)) {
  5583. $img_urls = $resultUrls;
  5584. $img_url = $resultUrls[0];
  5585. } else {
  5586. $img_url = (string)$task->result_url;
  5587. }
  5588. break;
  5589. } elseif ($task->status === 'failed') {
  5590. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5591. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5592. }
  5593. // // 如果还在处理中,提示用户稍后查看
  5594. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5595. }else {
  5596. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5597. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5598. if ($statusInfo['status'] === 'success') {
  5599. $task->updateStatus('success', [
  5600. 'result_url' => $statusInfo['result_url'],
  5601. 'result_json' => $statusInfo['result_json'] ?? []
  5602. ]);
  5603. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5604. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5605. if (!empty($resultUrls)) {
  5606. $img_urls = $resultUrls;
  5607. $img_url = $resultUrls[0];
  5608. } else {
  5609. $img_url = (string)$statusInfo['result_url'];
  5610. }
  5611. break;
  5612. } elseif ($statusInfo['status'] === 'failed') {
  5613. $task->updateStatus('failed', [
  5614. 'error_message' => $statusInfo['error_message'],
  5615. 'result_json' => $statusInfo['result_json'] ?? []
  5616. ]);
  5617. dLog('anime')->error('图片生成失败,', [
  5618. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5619. ]);
  5620. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5621. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5622. }
  5623. }
  5624. }
  5625. if (empty($img_url)) {
  5626. Utils::throwError('20003:图片生成超时,请稍后重试');
  5627. }
  5628. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5629. if (count($img_urls) > 1) {
  5630. return [
  5631. 'img_url' => $img_url,
  5632. 'image_urls' => $img_urls,
  5633. 'task_id' => $taskCenterId,
  5634. ];
  5635. }
  5636. return [
  5637. 'img_url' => $img_url,
  5638. 'task_id' => $taskCenterId,
  5639. ];
  5640. } catch (\Exception $e) {
  5641. dLog('anime')->error('更新角色或场景失败', [
  5642. 'error' => $e->getMessage()
  5643. ]);
  5644. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5645. Utils::throwError('20003:' . $e->getMessage());
  5646. }
  5647. }
  5648. /**
  5649. * 使用文生文模型解析分镜内容
  5650. */
  5651. private function parseSegmentContentWithAI($segment_content) {
  5652. try {
  5653. // 使用DeepSeek服务的公开方法解析分镜内容
  5654. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5655. } catch (\Exception $e) {
  5656. // 如果AI解析失败,记录日志并返回原内容
  5657. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5658. return $segment_content;
  5659. }
  5660. }
  5661. /**
  5662. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5663. *
  5664. * @param int $episode_id 分集ID
  5665. * @param int $anime_id 动漫ID
  5666. * @param array $roles 分集角色数组(引用传递)
  5667. * @param array $scenes 分集场景数组(引用传递)
  5668. * @param array $episode 分集数据
  5669. */
  5670. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5671. // 获取全局动漫的角色和场景数据
  5672. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5673. if (!$anime) return;
  5674. $art_style_type = getProp($anime, 'art_style_type');
  5675. $character_prefix = '';
  5676. $scene_prefix = '';
  5677. if ($art_style_type) {
  5678. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5679. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5680. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5681. }
  5682. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5683. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5684. $roles_updated = false;
  5685. $scenes_updated = false;
  5686. // 处理角色
  5687. foreach ($roles as &$role) {
  5688. $role_name = getProp($role, 'role');
  5689. $role_description = getProp($role, 'description');
  5690. $role_pic_prompt = getProp($role, 'pic_prompt');
  5691. $role_url = getProp($role, 'url');
  5692. $role_task_id = getProp($role, 'task_id');
  5693. // 如果已有URL或已有任务ID,跳过
  5694. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5695. continue;
  5696. }
  5697. $url_inherited = false;
  5698. // 尝试从全局数据中继承
  5699. foreach ($global_roles as $global_role) {
  5700. $global_role_name = getProp($global_role, 'role');
  5701. $global_role_description = getProp($global_role, 'description');
  5702. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5703. $global_role_url = getProp($global_role, 'url');
  5704. $global_role_task_id = getProp($global_role, 'task_id');
  5705. $global_role_task_status = getProp($global_role, 'task_status');
  5706. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5707. if ($role_name === $global_role_name
  5708. && $role_description === $global_role_description
  5709. && $role_pic_prompt === $global_role_pic_prompt
  5710. && !empty($global_role_url)) {
  5711. // 继承 task_id、task_status 和 url
  5712. $role['task_id'] = $global_role_task_id;
  5713. $role['task_status'] = $global_role_task_status;
  5714. $role['url'] = $global_role_url;
  5715. $roles_updated = true;
  5716. $url_inherited = true;
  5717. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5718. break;
  5719. }
  5720. }
  5721. // 如果无法继承且没有任务ID,创建新任务
  5722. if (!$url_inherited && empty($role_task_id)) {
  5723. try {
  5724. $art_style = getProp($episode, 'art_style');
  5725. // 优先使用 pic_prompt,如果没有则使用 description
  5726. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5727. // if ($art_style) {
  5728. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5729. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5730. // }
  5731. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5732. $params = [
  5733. 'prompt' => $description,
  5734. 'ref_img_urls' => [],
  5735. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5736. 'anime_id' => $anime_id,
  5737. 'episode_id' => $episode_id,
  5738. 'episode_number' => getProp($episode, 'episode_number'),
  5739. ];
  5740. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5741. $task_id = $task->id;
  5742. if ($task_id) {
  5743. $role['task_id'] = $task_id;
  5744. $role['task_status'] = 'processing';
  5745. $roles_updated = true;
  5746. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5747. }
  5748. } catch (\Exception $e) {
  5749. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5750. }
  5751. }
  5752. }
  5753. // 处理场景
  5754. foreach ($scenes as &$scene) {
  5755. $scene_name = getProp($scene, 'scene');
  5756. $scene_description = getProp($scene, 'description');
  5757. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5758. $scene_url = getProp($scene, 'url');
  5759. $scene_task_id = getProp($scene, 'task_id');
  5760. // 如果已有URL或已有任务ID,跳过
  5761. if (!empty($scene_url) || !empty($scene_task_id)) {
  5762. continue;
  5763. }
  5764. $url_inherited = false;
  5765. // 尝试从全局数据中继承
  5766. foreach ($global_scenes as $global_scene) {
  5767. $global_scene_name = getProp($global_scene, 'scene');
  5768. $global_scene_description = getProp($global_scene, 'description');
  5769. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5770. $global_scene_url = getProp($global_scene, 'url');
  5771. $global_scene_task_id = getProp($global_scene, 'task_id');
  5772. $global_scene_task_status = getProp($global_scene, 'task_status');
  5773. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5774. if ($scene_name === $global_scene_name
  5775. && $scene_description === $global_scene_description
  5776. && $scene_pic_prompt === $global_scene_pic_prompt
  5777. && !empty($global_scene_url)) {
  5778. // 继承 task_id、task_status 和 url
  5779. $scene['task_id'] = $global_scene_task_id;
  5780. $scene['task_status'] = $global_scene_task_status;
  5781. $scene['url'] = $global_scene_url;
  5782. $scenes_updated = true;
  5783. $url_inherited = true;
  5784. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5785. break;
  5786. }
  5787. }
  5788. // 如果无法继承且没有任务ID,创建新任务
  5789. if (!$url_inherited && empty($scene_task_id)) {
  5790. try {
  5791. $art_style = getProp($episode, 'art_style');
  5792. // 优先使用 pic_prompt,如果没有则使用 description
  5793. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5794. // if ($art_style) {
  5795. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5796. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5797. // }
  5798. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5799. $params = [
  5800. 'prompt' => $description,
  5801. 'ref_img_urls' => [],
  5802. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5803. 'anime_id' => $anime_id,
  5804. 'episode_id' => $episode_id,
  5805. 'episode_number' => getProp($episode, 'episode_number'),
  5806. ];
  5807. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5808. $task_id = $task->id;
  5809. if ($task_id) {
  5810. $scene['task_id'] = $task_id;
  5811. $scene['task_status'] = 'processing';
  5812. $scenes_updated = true;
  5813. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5814. }
  5815. } catch (\Exception $e) {
  5816. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5817. }
  5818. }
  5819. }
  5820. // 如果有更新,保存到数据库
  5821. if ($roles_updated || $scenes_updated) {
  5822. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5823. if ($roles_updated) {
  5824. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5825. }
  5826. if ($scenes_updated) {
  5827. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5828. }
  5829. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5830. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5831. }
  5832. }
  5833. /**
  5834. * 根据图片URL使用AI反推图片提示词
  5835. *
  5836. * @param string $img_url 图片URL
  5837. * @return string 反推的提示词
  5838. */
  5839. private function generateImagePromptFromUrl($img_url) {
  5840. try {
  5841. // 获取默认模型
  5842. $model = 'doubao-seed-2-0-mini-260215';
  5843. // 构建messages参数
  5844. $messages = [
  5845. [
  5846. 'role' => 'user',
  5847. 'content' => [
  5848. [
  5849. 'type' => 'text',
  5850. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5851. ],
  5852. [
  5853. 'type' => 'image_url',
  5854. 'image_url' => [
  5855. 'url' => $img_url
  5856. ]
  5857. ]
  5858. ]
  5859. ]
  5860. ];
  5861. // 构建请求参数
  5862. $params = [
  5863. 'model' => $model,
  5864. 'messages' => $messages,
  5865. 'stream' => false,
  5866. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5867. ];
  5868. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5869. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5870. // 仅记录 token 使用明细(不扣积分)
  5871. $uid = 0;
  5872. try {
  5873. $uid = (int)Site::getUid();
  5874. } catch (\Throwable $e) {
  5875. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5876. }
  5877. $this->pointsService->recordTokenOnlyDetail(
  5878. $uid,
  5879. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5880. [
  5881. 'model' => $model,
  5882. 'img_url' => $img_url,
  5883. 'source' => 'generateImagePromptFromUrl',
  5884. ],
  5885. 'chat',
  5886. $model,
  5887. ''
  5888. );
  5889. // 返回生成的内容
  5890. return getProp($result, 'fullContent', '图片描述生成失败');
  5891. } catch (\Exception $e) {
  5892. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5893. 'img_url' => $img_url
  5894. ]);
  5895. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5896. 'error' => $e->getMessage(),
  5897. 'img_url' => $img_url
  5898. ]);
  5899. return '图片描述生成失败: ' . $e->getMessage();
  5900. }
  5901. }
  5902. /**
  5903. * 音频试听接口
  5904. * 创建音频任务并轮询获取结果
  5905. *
  5906. * @param array $data 参数数组
  5907. * @return array 返回音频URL或错误信息
  5908. */
  5909. public function previewAudio($data) {
  5910. $dialogue = getProp($data, 'dialogue');
  5911. // 必填参数验证
  5912. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5913. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5914. $voice_type = getProp($data, 'voice_type');
  5915. $voice_name = getProp($data, 'voice_name');
  5916. $voice_actor = getProp($data, 'voice_actor');
  5917. $emotion_type = getProp($data, 'emotion_type');
  5918. $gender = getProp($data, 'gender', 0);
  5919. $emotion = getProp($data, 'emotion');
  5920. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5921. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5922. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5923. $pitch = getProp($data, 'pitch', 0);
  5924. try {
  5925. $now = date('Y-m-d H:i:s');
  5926. // 构建生成参数
  5927. $generate_json = json_encode([
  5928. 'text' => $dialogue,
  5929. 'role' => $voice_actor,
  5930. 'voice_type' => $voice_type,
  5931. 'voice_name' => $voice_name,
  5932. 'emotion' => $emotion,
  5933. 'emotion_type' => $emotion_type,
  5934. 'gender' => $gender,
  5935. 'speed_ratio' => $speed_ratio,
  5936. 'loudness_ratio' => $loudness_ratio,
  5937. 'emotion_scale' => $emotion_scale,
  5938. 'pitch' => $pitch,
  5939. ], 256);
  5940. // 请求远程服务器执行生成
  5941. $client = new Client(['timeout' => 600, 'verify' => false]);
  5942. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5943. $response = $result->getBody()->getContents();
  5944. $response_arr = json_decode($response, true);
  5945. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5946. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5947. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5948. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5949. }
  5950. $arr = $response_arr['data'];
  5951. $subtitle_info = $arr['subtitle_info'];
  5952. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5953. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5954. return [
  5955. 'audio_url' => $arr['url'],
  5956. 'subtitle_info' => $subtitle_info,
  5957. 'audio_duration' => round($audio_duration, 2)
  5958. ];
  5959. } catch (\Exception $e) {
  5960. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5961. Utils::throwError('20003:' . $e->getMessage());
  5962. }
  5963. }
  5964. /**
  5965. * 获取角色库列表(支持文件夹递归查询)
  5966. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5967. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5968. */
  5969. public function globalProducts($data) {
  5970. $uid = Site::getUid();
  5971. $cpid = Site::getCpid();
  5972. $role = Site::getRole();
  5973. $id = getProp($data, 'id', 0);
  5974. $parent_id = getProp($data, 'parent_id', 0);
  5975. $product_name = getProp($data, 'product_name');
  5976. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5977. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5978. if (!$product) {
  5979. Utils::throwError('20003:请选择产品类型');
  5980. }
  5981. // 根据角色和is_public参数确定查询范围
  5982. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5983. // user角色:根据is_public参数筛选
  5984. $query_user_ids = [];
  5985. if ($role === 'admin') {
  5986. // admin获取所有个人库和公共库
  5987. $query_user_ids = [$uid, 0];
  5988. } else {
  5989. // user角色根据is_public参数筛选
  5990. if ($is_public == 2) {
  5991. // 个人库+公共库
  5992. $query_user_ids = [$uid, 0];
  5993. } elseif ($is_public == 0) {
  5994. // 仅个人库
  5995. $query_user_ids = [$uid];
  5996. } elseif ($is_public == 1) {
  5997. // 仅公共库
  5998. $query_user_ids = [0];
  5999. }
  6000. }
  6001. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  6002. if ($id || $product_name) {
  6003. $query = DB::table('mp_products')
  6004. ->where('cpid', $cpid)
  6005. ->whereIn('user_id', $query_user_ids)
  6006. ->where('is_deleted', 0);
  6007. // 如果指定了 id,按 id 精确查询
  6008. if ($id) {
  6009. $query->where('id', $id);
  6010. }
  6011. // 如果指定了 product_name,按名称模糊查询
  6012. if ($product_name) {
  6013. $query->where('product_name', 'like', "%{$product_name}%");
  6014. }
  6015. // 如果指定了 product,添加筛选条件
  6016. if ($product) {
  6017. $query->where('product', $product);
  6018. }
  6019. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  6020. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6021. ->get()
  6022. ->map(function($value) {
  6023. $value = (array)$value;
  6024. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  6025. $value['type'] = (int)$value['type'];
  6026. $value['parent_id'] = (int)$value['parent_id'];
  6027. $value['level'] = (int)$value['level'];
  6028. $value['product'] = (int)($value['product'] ?? 1);
  6029. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  6030. $value['timbre_url'] = $value['timbre_url'] ?? '';
  6031. $value['versions'] = json_decode($value['versions'], true) ?: [];
  6032. unset($value['user_id']);
  6033. return $value;
  6034. })
  6035. ->toArray();
  6036. return $result;
  6037. }
  6038. // 递归获取所有子目录和角色
  6039. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  6040. }
  6041. /**
  6042. * 递归获取指定目录下的所有子目录和角色
  6043. * @param int $cpid 公司ID
  6044. * @param int $parent_id 父目录ID
  6045. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  6046. * @param array $query_user_ids 用户ID数组(支持多个)
  6047. * @param int $current_uid 当前用户ID(用于排序)
  6048. * @return array
  6049. */
  6050. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  6051. // 查询当前层级的所有项(文件夹和角色)
  6052. $query = DB::table('mp_products')
  6053. ->where('cpid', $cpid)
  6054. ->where('is_deleted', 0)
  6055. ->where('parent_id', $parent_id);
  6056. // 添加用户ID验证(支持多个user_id)
  6057. if (!empty($query_user_ids)) {
  6058. $query->whereIn('user_id', $query_user_ids);
  6059. }
  6060. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  6061. if ($product) {
  6062. $query->where('product', $product);
  6063. }
  6064. // 排序规则:
  6065. // 1. 文件夹在前(type DESC)
  6066. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  6067. // 3. 其他排序规则
  6068. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  6069. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6070. ->get();
  6071. $result = [];
  6072. foreach ($items as $item) {
  6073. $itemArray = [
  6074. 'id' => $item->id,
  6075. 'type' => (int)$item->type,
  6076. 'parent_id' => (int)$item->parent_id,
  6077. 'level' => (int)$item->level,
  6078. 'product_name' => $item->product_name,
  6079. 'url' => $item->url,
  6080. 'pic_prompt' => $item->pic_prompt ?? '',
  6081. 'three_view_image_url' => $item->three_view_image_url,
  6082. 'timbre_url' => $item->timbre_url ?? '',
  6083. 'product' => (int)($item->product ?? 1),
  6084. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6085. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6086. ];
  6087. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6088. // 如果是文件夹,递归获取其子项
  6089. if ($item->type == 2) {
  6090. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6091. if (!empty($children)) {
  6092. $itemArray['children'] = $children;
  6093. }
  6094. }
  6095. $result[] = $itemArray;
  6096. }
  6097. return $result;
  6098. }
  6099. /**
  6100. * 创建文件夹
  6101. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6102. * @return int 返回新建文件夹ID
  6103. */
  6104. public function createFolder($data) {
  6105. $uid = Site::getUid();
  6106. $cpid = Site::getCpid();
  6107. $role = Site::getRole();
  6108. $parent_id = getProp($data, 'parent_id', 0);
  6109. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6110. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6111. // 如果是公共库操作,需要admin权限
  6112. if ($is_public && $role !== 'admin') {
  6113. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6114. }
  6115. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6116. $store_uid = $is_public ? 0 : $uid;
  6117. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6118. $product = getProp($data, 'product');
  6119. if (!in_array($product, [1, 2, 3])) {
  6120. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6121. }
  6122. // 验证父文件夹
  6123. $parent_level = 0;
  6124. if ($parent_id > 0) {
  6125. $parent = DB::table('mp_products')
  6126. ->where('id', $parent_id)
  6127. ->where('cpid', $cpid)
  6128. ->where('user_id', $store_uid)
  6129. ->where('type', 2)
  6130. ->where('is_deleted', 0)
  6131. ->first();
  6132. if (!$parent) {
  6133. Utils::throwError('20003:父文件夹不存在');
  6134. }
  6135. // 检查父文件夹的 product 类型是否一致
  6136. if ($parent->product != $product) {
  6137. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6138. }
  6139. $parent_level = $parent->level;
  6140. // 检查层级限制(最多3层)
  6141. if ($parent_level >= 3) {
  6142. Utils::throwError('20003:文件夹层级不能超过3层');
  6143. }
  6144. }
  6145. // 检查当前目录下是否已存在空白文件夹
  6146. $empty_folder_exists = DB::table('mp_products')
  6147. ->where('parent_id', $parent_id)
  6148. ->where('cpid', $cpid)
  6149. ->where('user_id', $store_uid)
  6150. ->where('type', 2)
  6151. ->where('product', $product)
  6152. ->where('product_name', '新建文件夹')
  6153. ->where('is_deleted', 0)
  6154. ->exists();
  6155. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6156. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6157. }
  6158. // 创建文件夹
  6159. $folder_id = DB::table('mp_products')->insertGetId([
  6160. 'user_id' => $store_uid,
  6161. 'cpid' => $cpid,
  6162. 'type' => 2,
  6163. 'parent_id' => $parent_id,
  6164. 'level' => $parent_level + 1,
  6165. 'product_name' => $folder_name,
  6166. 'product' => $product,
  6167. 'sort_order' => time(), // 使用时间戳作为排序权重
  6168. 'is_deleted' => 0,
  6169. 'created_at' => date('Y-m-d H:i:s'),
  6170. 'updated_at' => date('Y-m-d H:i:s')
  6171. ]);
  6172. return [
  6173. 'id' => $folder_id,
  6174. 'type' => 2,
  6175. 'parent_id' => $parent_id,
  6176. 'level' => $parent_level + 1,
  6177. 'product_name' => $folder_name,
  6178. 'product' => $product,
  6179. ];
  6180. }
  6181. /**
  6182. * 重命名文件夹或角色
  6183. * @param array $data 包含 id、product_name(新名称)
  6184. * @return bool
  6185. */
  6186. public function renameFolder($data) {
  6187. $uid = Site::getUid();
  6188. $cpid = Site::getCpid();
  6189. $role = Site::getRole();
  6190. $id = getProp($data, 'id');
  6191. $new_name = getProp($data, 'product_name');
  6192. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6193. if (!$id || !$new_name) {
  6194. Utils::throwError('20003:参数不完整');
  6195. }
  6196. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6197. $query_uid = $is_public ? 0 : $uid;
  6198. // 如果是公共库操作,需要admin权限
  6199. if ($is_public && $role !== 'admin') {
  6200. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6201. }
  6202. // 检查是否存在
  6203. $item = DB::table('mp_products')
  6204. ->where('id', $id)
  6205. ->where('cpid', $cpid)
  6206. ->where('user_id', $query_uid)
  6207. ->where('is_deleted', 0)
  6208. ->first();
  6209. if (!$item) {
  6210. Utils::throwError('20003:项目不存在');
  6211. }
  6212. return DB::table('mp_products')
  6213. ->where('id', $id)
  6214. ->where('cpid', $cpid)
  6215. ->where('user_id', $query_uid)
  6216. ->update([
  6217. 'product_name' => $new_name,
  6218. 'updated_at' => date('Y-m-d H:i:s')
  6219. ]);
  6220. }
  6221. /**
  6222. * 移动角色或文件夹到指定文件夹
  6223. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6224. * @return bool
  6225. */
  6226. public function moveProductOrFolder($data) {
  6227. $uid = Site::getUid();
  6228. $cpid = Site::getCpid();
  6229. $role = Site::getRole();
  6230. $id = getProp($data, 'id');
  6231. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6232. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6233. if (!$id) {
  6234. Utils::throwError('20003:请选择要移动的项目');
  6235. }
  6236. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6237. $query_uid = $is_public ? 0 : $uid;
  6238. // 如果是公共库操作,需要admin权限
  6239. if ($is_public && $role !== 'admin') {
  6240. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6241. }
  6242. // 检查要移动的项目
  6243. $item = DB::table('mp_products')
  6244. ->where('id', $id)
  6245. ->where('cpid', $cpid)
  6246. ->where('user_id', $query_uid)
  6247. ->where('is_deleted', 0)
  6248. ->first();
  6249. if (!$item) {
  6250. Utils::throwError('20003:项目不存在');
  6251. }
  6252. // 验证目标文件夹
  6253. $target_level = 0;
  6254. $target_product = $item->product; // 默认使用当前项目的 product
  6255. if ($target_parent_id > 0) {
  6256. $target_parent = DB::table('mp_products')
  6257. ->where('id', $target_parent_id)
  6258. ->where('cpid', $cpid)
  6259. ->where('user_id', $query_uid)
  6260. ->where('type', 2)
  6261. ->where('is_deleted', 0)
  6262. ->first();
  6263. if (!$target_parent) {
  6264. Utils::throwError('20003:目标文件夹不存在');
  6265. }
  6266. // 检查 product 类型是否一致
  6267. if ($target_parent->product != $item->product) {
  6268. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6269. }
  6270. $target_level = $target_parent->level;
  6271. $target_product = $target_parent->product;
  6272. // 如果移动的是文件夹,需要检查层级
  6273. if ($item->type == 2) {
  6274. // 计算移动后的最大层级
  6275. $max_child_level = $this->getMaxChildLevel($id);
  6276. $depth = $max_child_level - $item->level;
  6277. if ($target_level + 1 + $depth > 3) {
  6278. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6279. }
  6280. // 不能移动到自己或自己的子文件夹下
  6281. if ($this->isDescendant($target_parent_id, $id)) {
  6282. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6283. }
  6284. }
  6285. }
  6286. // 更新父文件夹和层级
  6287. $new_level = $target_level + 1;
  6288. DB::table('mp_products')
  6289. ->where('id', $id)
  6290. ->update([
  6291. 'parent_id' => $target_parent_id,
  6292. 'level' => $new_level,
  6293. 'updated_at' => date('Y-m-d H:i:s')
  6294. ]);
  6295. // 如果是文件夹,需要递归更新所有子项的层级
  6296. if ($item->type == 2) {
  6297. $this->updateChildrenLevel($id, $new_level);
  6298. }
  6299. return true;
  6300. }
  6301. /**
  6302. * 获取文件夹下最大子层级
  6303. * @param int $folder_id
  6304. * @return int
  6305. */
  6306. private function getMaxChildLevel($folder_id) {
  6307. $max_level = DB::table('mp_products')
  6308. ->where('parent_id', $folder_id)
  6309. ->where('is_deleted', 0)
  6310. ->max('level');
  6311. if (!$max_level) {
  6312. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6313. }
  6314. // 递归查找子文件夹
  6315. $children = DB::table('mp_products')
  6316. ->where('parent_id', $folder_id)
  6317. ->where('type', 2)
  6318. ->where('is_deleted', 0)
  6319. ->pluck('id');
  6320. foreach ($children as $child_id) {
  6321. $child_max = $this->getMaxChildLevel($child_id);
  6322. if ($child_max > $max_level) {
  6323. $max_level = $child_max;
  6324. }
  6325. }
  6326. return $max_level;
  6327. }
  6328. /**
  6329. * 检查 target_id 是否是 folder_id 的后代
  6330. * @param int $target_id
  6331. * @param int $folder_id
  6332. * @return bool
  6333. */
  6334. private function isDescendant($target_id, $folder_id) {
  6335. if ($target_id == $folder_id) {
  6336. return true;
  6337. }
  6338. $parent = DB::table('mp_products')
  6339. ->where('id', $target_id)
  6340. ->where('is_deleted', 0)
  6341. ->first();
  6342. if (!$parent || $parent->parent_id == 0) {
  6343. return false;
  6344. }
  6345. return $this->isDescendant($parent->parent_id, $folder_id);
  6346. }
  6347. /**
  6348. * 递归更新子项层级
  6349. * @param int $parent_id
  6350. * @param int $parent_level
  6351. */
  6352. private function updateChildrenLevel($parent_id, $parent_level) {
  6353. $children = DB::table('mp_products')
  6354. ->where('parent_id', $parent_id)
  6355. ->where('is_deleted', 0)
  6356. ->get();
  6357. foreach ($children as $child) {
  6358. $new_level = $parent_level + 1;
  6359. DB::table('mp_products')
  6360. ->where('id', $child->id)
  6361. ->update([
  6362. 'level' => $new_level,
  6363. 'updated_at' => date('Y-m-d H:i:s')
  6364. ]);
  6365. // 如果是文件夹,继续递归
  6366. if ($child->type == 2) {
  6367. $this->updateChildrenLevel($child->id, $new_level);
  6368. }
  6369. }
  6370. }
  6371. /**
  6372. * 获取文件夹路径(面包屑导航)
  6373. * @param array $data 包含 folder_id
  6374. * @return array 返回路径数组
  6375. */
  6376. public function getFolderPath($data) {
  6377. $uid = Site::getUid();
  6378. $cpid = Site::getCpid();
  6379. $folder_id = getProp($data, 'id', 0);
  6380. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6381. if ($folder_id == 0) {
  6382. return [
  6383. ['id' => 0, 'name' => '根目录']
  6384. ];
  6385. }
  6386. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6387. $query_uid = $is_public ? 0 : $uid;
  6388. $path = [];
  6389. $current_id = $folder_id;
  6390. while ($current_id > 0) {
  6391. $folder = DB::table('mp_products')
  6392. ->where('id', $current_id)
  6393. ->where('cpid', $cpid)
  6394. ->where('user_id', $query_uid)
  6395. ->where('type', 2)
  6396. ->where('is_deleted', 0)
  6397. ->first();
  6398. if (!$folder) {
  6399. break;
  6400. }
  6401. array_unshift($path, [
  6402. 'id' => $folder->id,
  6403. 'name' => $folder->product_name
  6404. ]);
  6405. $current_id = $folder->parent_id;
  6406. }
  6407. // 添加根目录
  6408. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6409. return $path;
  6410. }
  6411. public function createProduct($data) {
  6412. $uid = Site::getUid();
  6413. $cpid = Site::getCpid();
  6414. $role = Site::getRole();
  6415. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6416. // 如果是公共库操作,需要admin权限
  6417. if ($is_public && $role !== 'admin') {
  6418. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6419. }
  6420. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6421. $store_uid = $is_public ? 0 : $uid;
  6422. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6423. $script_id = (int)getProp($data, 'script_id', 0);
  6424. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6425. if ($script_id && empty($episode_numbers)) {
  6426. Utils::throwError('20003:剧集序号不能为空');
  6427. }
  6428. if (!$script_id && !empty($episode_numbers)) {
  6429. Utils::throwError('20003:请提供剧本ID');
  6430. }
  6431. $product_name = trim(getProp($data, 'product_name'));
  6432. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6433. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6434. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6435. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6436. $url = trim(getProp($data, 'url'));
  6437. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6438. $versions = getProp($data, 'versions');
  6439. // 检查是否是正确的图片格式
  6440. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6441. $urlPath = parse_url($url, PHP_URL_PATH);
  6442. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6443. if (!in_array($extension, $allowedExtensions)) {
  6444. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6445. }
  6446. // 选填三视图图片地址,格式校验与 url 一致
  6447. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6448. if ($three_view_image_url) {
  6449. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6450. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6451. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6452. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6453. }
  6454. }
  6455. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6456. $timbre_url = $this->getProductTimbreUrl($data);
  6457. if ($timbre_url) {
  6458. $this->validateProductAudioUrl($timbre_url);
  6459. }
  6460. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6461. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6462. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6463. $product = getProp($data, 'product');
  6464. if (!in_array($product, [1, 2, 3])) {
  6465. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6466. }
  6467. // 获取父文件夹ID和层级
  6468. $parent_id = getProp($data, 'parent_id', 0);
  6469. $parent_level = 0;
  6470. if ($parent_id > 0) {
  6471. $parent = DB::table('mp_products')
  6472. ->where('id', $parent_id)
  6473. ->where('cpid', $cpid)
  6474. ->where('user_id', $store_uid)
  6475. ->where('type', 2)
  6476. ->where('is_deleted', 0)
  6477. ->first();
  6478. if (!$parent) {
  6479. Utils::throwError('20003:父文件夹不存在');
  6480. }
  6481. $parent_level = $parent->level;
  6482. }
  6483. // 创建资产并保存剧本资产关联关系(同一事务)
  6484. DB::beginTransaction();
  6485. try {
  6486. $id = DB::table('mp_products')->insertGetId([
  6487. 'user_id' => $store_uid,
  6488. 'cpid' => $cpid,
  6489. 'type' => 1, // 1=角色图片
  6490. 'parent_id' => $parent_id,
  6491. 'level' => $parent_level + 1,
  6492. 'product_name' => $product_name,
  6493. 'url' => $url,
  6494. 'three_view_image_url' => $three_view_image_url,
  6495. 'timbre_url' => $timbre_url,
  6496. 'pic_prompt' => $pic_prompt,
  6497. 'product' => $product,
  6498. 'versions' => json_encode($versions, 256),
  6499. 'sort_order' => time(), // 使用时间戳作为排序权重
  6500. 'created_at' => date('Y-m-d H:i:s'),
  6501. 'updated_at' => date('Y-m-d H:i:s')
  6502. ]);
  6503. if (!$id) Utils::throwError('20003:创建失败');
  6504. // 保存剧本资产关联关系
  6505. if ($script_id) {
  6506. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6507. }
  6508. DB::commit();
  6509. } catch (\Exception $e) {
  6510. DB::rollback();
  6511. throw $e;
  6512. }
  6513. return [
  6514. 'id' => $id,
  6515. 'type' => 1,
  6516. 'parent_id' => $parent_id,
  6517. 'level' => $parent_level + 1,
  6518. 'product_name' => $product_name,
  6519. 'url' => $url,
  6520. 'three_view_image_url' => $three_view_image_url,
  6521. 'timbre_url' => $timbre_url,
  6522. 'pic_prompt' => $pic_prompt,
  6523. 'product' => $product,
  6524. 'versions' => $versions
  6525. ];
  6526. }
  6527. public function editProduct($data) {
  6528. $uid = Site::getUid();
  6529. $cpid = Site::getCpid();
  6530. $role = Site::getRole();
  6531. $id = getProp($data, 'id');
  6532. if (!$id) Utils::throwError('20003:ID不能为空');
  6533. $versions = getProp($data, 'versions');
  6534. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6535. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6536. $script_id = (int)getProp($data, 'script_id', 0);
  6537. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6538. if ($script_id && empty($episode_numbers)) {
  6539. Utils::throwError('20003:剧集序号不能为空');
  6540. }
  6541. if (!$script_id && !empty($episode_numbers)) {
  6542. Utils::throwError('20003:请提供剧本ID');
  6543. }
  6544. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6545. $query_uid = $is_public ? 0 : $uid;
  6546. // 如果是公共库操作,需要admin权限
  6547. if ($is_public && $role !== 'admin') {
  6548. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6549. }
  6550. // 检查是否存在且属于当前用户或公共库
  6551. $role = DB::table('mp_products')
  6552. ->where('id', $id)
  6553. ->where('cpid', $cpid)
  6554. ->where('user_id', $query_uid)
  6555. ->where('type', 1)->first();
  6556. if (!$role) Utils::throwError('20003:记录不存在');
  6557. $updateData = [];
  6558. // $needVersionRecord = false; // 是否需要记录版本
  6559. // 名称
  6560. $product_name = trim(getProp($data, 'product_name'));
  6561. if ($product_name) {
  6562. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6563. $updateData['product_name'] = $product_name;
  6564. }
  6565. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6566. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6567. // 图片地址
  6568. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6569. $url = trim(getProp($data, 'url'));
  6570. if ($url) {
  6571. // 检查是否是正确的图片格式
  6572. $urlPath = parse_url($url, PHP_URL_PATH);
  6573. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6574. if (!in_array($extension, $allowedExtensions)) {
  6575. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6576. }
  6577. // // 如果 url 有变更,记录版本
  6578. // if ($url !== $role->url) {
  6579. // $needVersionRecord = true;
  6580. // }
  6581. $updateData['url'] = $url;
  6582. }
  6583. // 三视图图片地址(选填),格式校验与 url 一致;显式传空表示当前版本没有三视图
  6584. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6585. if ($three_view_image_url) {
  6586. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6587. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6588. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6589. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6590. }
  6591. }
  6592. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  6593. if (array_key_exists('three_view_image_url', $data)) {
  6594. $updateData['three_view_image_url'] = $three_view_image_url;
  6595. }
  6596. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6597. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6598. $timbre_url = $this->getProductTimbreUrl($data);
  6599. if ($timbre_url) {
  6600. $this->validateProductAudioUrl($timbre_url);
  6601. }
  6602. $updateData['timbre_url'] = $timbre_url;
  6603. }
  6604. // 提示词
  6605. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6606. if ($pic_prompt) {
  6607. // // 如果 pic_prompt 有变更,记录版本
  6608. // if ($pic_prompt !== $role->pic_prompt) {
  6609. // $needVersionRecord = true;
  6610. // }
  6611. $updateData['pic_prompt'] = $pic_prompt;
  6612. }else {
  6613. Utils::throwError('20003:请输入提示词');
  6614. }
  6615. if (empty($updateData) && !$script_id) {
  6616. Utils::throwError('20003:没有需要更新的数据');
  6617. }
  6618. // // 如果需要记录版本,将数据添加到 versions 数组
  6619. // if ($needVersionRecord) {
  6620. // // 获取现有的 versions 数据
  6621. // $versions = json_decode($role->versions, true) ?: [];
  6622. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6623. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6624. // if ($isFirstVersion) {
  6625. // $oldVersion = [
  6626. // 'url' => $role->url,
  6627. // 'description' => $role->pic_prompt,
  6628. // ];
  6629. // // 旧版本添加到数组末尾
  6630. // $versions[] = $oldVersion;
  6631. // }
  6632. // // 构建新版本(变更后)
  6633. // $newVersion = [
  6634. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6635. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6636. // ];
  6637. // // 检查新版本是否已存在于历史版本中
  6638. // $existingIndex = -1;
  6639. // foreach ($versions as $index => $version) {
  6640. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6641. // $existingIndex = $index;
  6642. // break;
  6643. // }
  6644. // }
  6645. // if ($existingIndex !== -1) {
  6646. // // 如果已存在,移除旧的位置
  6647. // array_splice($versions, $existingIndex, 1);
  6648. // }
  6649. // // 新版本添加到数组开头(最新的在前)
  6650. // array_unshift($versions, $newVersion);
  6651. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6652. // // if (count($versions) > 10) {
  6653. // // $versions = array_slice($versions, 0, 10);
  6654. // // }
  6655. // $updateData['versions'] = json_encode($versions, 256);
  6656. // }
  6657. if ($versions) {
  6658. $updateData['versions'] = json_encode($versions, 256);
  6659. }
  6660. if (!empty($updateData)) {
  6661. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6662. }
  6663. // 更新资产并保存剧本资产关联关系(同一事务)
  6664. DB::beginTransaction();
  6665. try {
  6666. $updated = true;
  6667. if (!empty($updateData)) {
  6668. $updated = DB::table('mp_products')
  6669. ->where('cpid', $cpid)
  6670. ->where('id', $id)
  6671. ->update($updateData);
  6672. }
  6673. // 保存剧本资产关联关系
  6674. if ($script_id) {
  6675. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6676. }
  6677. DB::commit();
  6678. } catch (\Exception $e) {
  6679. DB::rollback();
  6680. throw $e;
  6681. }
  6682. return $updated;
  6683. }
  6684. /**
  6685. * 获取资产音色音频地址
  6686. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6687. *
  6688. * @param array $data
  6689. * @return string
  6690. */
  6691. private function getProductTimbreUrl($data) {
  6692. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6693. if (!array_key_exists($key, $data)) {
  6694. continue;
  6695. }
  6696. $value = $data[$key];
  6697. if (is_array($value)) {
  6698. $value = getProp($value, 'url', $value[0] ?? '');
  6699. }
  6700. if (!is_string($value)) {
  6701. continue;
  6702. }
  6703. return trim($value);
  6704. }
  6705. return '';
  6706. }
  6707. /**
  6708. * 校验资产音色音频地址格式
  6709. *
  6710. * @param string $url 音频地址
  6711. * @return void
  6712. */
  6713. private function validateProductAudioUrl($url) {
  6714. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6715. $urlPath = parse_url($url, PHP_URL_PATH);
  6716. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6717. if (!in_array($extension, $allowedExtensions)) {
  6718. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6719. }
  6720. }
  6721. /**
  6722. * 保存单一资产与剧本剧集的关联关系
  6723. *
  6724. * @param int $product_id 资产ID
  6725. * @param int $script_id 剧本ID
  6726. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6727. * @return int 新增关联数量
  6728. */
  6729. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6730. $uid = Site::getUid();
  6731. // 验证剧本是否存在
  6732. $script = DB::table('mp_scripts')
  6733. ->where('id', $script_id)
  6734. ->where('is_deleted', 0)
  6735. ->first();
  6736. if (!$script) {
  6737. Utils::throwError('20003:剧本不存在');
  6738. }
  6739. // 验证剧本归属:只能关联自己的剧本
  6740. if ((int)$script->user_id !== (int)$uid) {
  6741. Utils::throwError('20003:只能添加到自己的剧本');
  6742. }
  6743. // 使用 splitContent 拆分剧本内容获取总集数
  6744. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6745. // 解析剧集序号(数组)
  6746. $episodes = [];
  6747. foreach ($episode_numbers as $item) {
  6748. if (is_array($item)) {
  6749. continue;
  6750. }
  6751. $item = trim((string)$item);
  6752. if ($item === '' || !is_numeric($item)) {
  6753. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6754. }
  6755. $episodes[] = (int)$item;
  6756. }
  6757. // 去重并校验序号范围(序号从1开始)
  6758. $episodes = array_values(array_unique($episodes));
  6759. if (empty($episodes)) {
  6760. Utils::throwError('20003:剧集序号不能为空');
  6761. }
  6762. foreach ($episodes as $episode) {
  6763. if ($episode < 1 || $episode > $totalEpisodes) {
  6764. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6765. }
  6766. }
  6767. $now = now();
  6768. // 过滤已存在的关联,避免重复
  6769. $existingEpisodes = DB::table('mp_script_product_mappings')
  6770. ->where('script_id', $script_id)
  6771. ->where('product_id', $product_id)
  6772. ->whereIn('episode_number', $episodes)
  6773. ->pluck('episode_number')
  6774. ->all();
  6775. $mappingRecords = [];
  6776. foreach ($episodes as $episode) {
  6777. if (in_array($episode, $existingEpisodes)) {
  6778. continue;
  6779. }
  6780. $mappingRecords[] = [
  6781. 'script_id' => $script_id,
  6782. 'product_id' => $product_id,
  6783. 'episode_number' => $episode,
  6784. 'created_at' => $now,
  6785. 'updated_at' => $now,
  6786. ];
  6787. }
  6788. $insertedCount = 0;
  6789. if (!empty($mappingRecords)) {
  6790. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6791. }
  6792. return $insertedCount;
  6793. }
  6794. /**
  6795. * 规范化剧集序号参数,统一为数组
  6796. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6797. *
  6798. * @param mixed $episode_number 剧集序号参数
  6799. * @return array
  6800. */
  6801. private function normalizeEpisodeNumbers($episode_number) {
  6802. if (!is_array($episode_number)) {
  6803. $episode_number = explode(',', (string)$episode_number);
  6804. }
  6805. $items = [];
  6806. foreach ($episode_number as $item) {
  6807. if (is_array($item)) {
  6808. continue;
  6809. }
  6810. foreach (explode(',', (string)$item) as $part) {
  6811. $part = trim($part);
  6812. if ($part !== '') {
  6813. $items[] = $part;
  6814. }
  6815. }
  6816. }
  6817. return $items;
  6818. }
  6819. /**
  6820. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6821. *
  6822. * @param object $script 剧本记录
  6823. * @return int 总集数
  6824. */
  6825. private function getScriptTotalEpisodeCount($script) {
  6826. if (empty($script->content)) {
  6827. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6828. }
  6829. $totalEpisodes = count(splitContent($script->content));
  6830. if ($totalEpisodes < 1) {
  6831. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6832. }
  6833. return $totalEpisodes;
  6834. }
  6835. /**
  6836. * 获取剧本总集数
  6837. *
  6838. * @param array $data 包含 script_id(剧本ID)
  6839. * @return array
  6840. */
  6841. public function getScriptTotalEpisodes($data) {
  6842. $script_id = (int)getProp($data, 'script_id', 0);
  6843. if (!$script_id) {
  6844. Utils::throwError('20003:请提供剧本ID');
  6845. }
  6846. // 验证剧本是否存在
  6847. $script = DB::table('mp_scripts')
  6848. ->where('id', $script_id)
  6849. ->where('is_deleted', 0)
  6850. ->first();
  6851. if (!$script) {
  6852. Utils::throwError('20003:剧本不存在');
  6853. }
  6854. return [
  6855. 'script_id' => $script_id,
  6856. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6857. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6858. ];
  6859. }
  6860. /**
  6861. * 获取角色版本历史
  6862. * @param array $data 包含 id(角色ID)
  6863. * @return array 返回版本历史列表
  6864. */
  6865. public function getProductVersions($data) {
  6866. $cpid = Site::getCpid();
  6867. $id = getProp($data, 'id');
  6868. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6869. $role = DB::table('mp_products')
  6870. ->where('id', $id)
  6871. ->where('cpid', $cpid)
  6872. ->where('type', 1)
  6873. ->first();
  6874. if (!$role) Utils::throwError('20003:角色不存在');
  6875. // 获取版本历史
  6876. $versions = json_decode($role->versions, true) ?: [];
  6877. // 添加当前版本作为最新版本
  6878. $currentVersion = [
  6879. 'version' => 0, // 0 表示当前版本
  6880. 'url' => $role->url,
  6881. 'pic_prompt' => $role->pic_prompt,
  6882. 'updated_at' => $role->updated_at,
  6883. 'is_current' => true
  6884. ];
  6885. array_unshift($versions, $currentVersion);
  6886. return $versions;
  6887. }
  6888. /**
  6889. * 恢复到指定版本
  6890. * @param array $data 包含 id(角色ID)、version(版本号)
  6891. * @return bool
  6892. */
  6893. public function restoreProductVersion($data) {
  6894. $uid = Site::getUid();
  6895. $cpid = Site::getCpid();
  6896. $id = getProp($data, 'id');
  6897. $version = getProp($data, 'version');
  6898. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6899. if (!$version) Utils::throwError('20003:版本号不能为空');
  6900. $role = DB::table('mp_products')
  6901. ->where('id', $id)
  6902. ->where('cpid', $cpid)
  6903. ->where('type', 1)
  6904. ->first();
  6905. if (!$role) Utils::throwError('20003:角色不存在');
  6906. // 获取版本历史
  6907. $versions = json_decode($role->versions, true) ?: [];
  6908. // 查找指定版本
  6909. $targetVersion = null;
  6910. foreach ($versions as $v) {
  6911. if ($v['version'] == $version) {
  6912. $targetVersion = $v;
  6913. break;
  6914. }
  6915. }
  6916. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6917. // 先将当前版本保存到历史
  6918. $newVersion = [
  6919. 'version' => count($versions) + 1,
  6920. 'url' => $role->url,
  6921. 'pic_prompt' => $role->pic_prompt,
  6922. 'updated_at' => date('Y-m-d H:i:s'),
  6923. 'updated_by' => $uid
  6924. ];
  6925. array_unshift($versions, $newVersion);
  6926. // 限制版本数量
  6927. if (count($versions) > 10) {
  6928. $versions = array_slice($versions, 0, 10);
  6929. }
  6930. // 恢复到指定版本
  6931. return DB::table('mp_products')
  6932. ->where('id', $id)
  6933. ->where('cpid', $cpid)
  6934. ->update([
  6935. 'url' => $targetVersion['url'],
  6936. 'pic_prompt' => $targetVersion['pic_prompt'],
  6937. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6938. 'updated_at' => date('Y-m-d H:i:s')
  6939. ]);
  6940. }
  6941. public function deleteProduct($data) {
  6942. $uid = Site::getUid();
  6943. $cpid = Site::getCpid();
  6944. $role = Site::getRole();
  6945. $id = getProp($data, 'id');
  6946. if (!$id) Utils::throwError('20003:ID不能为空');
  6947. $ids = explode(',', $id);
  6948. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6949. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6950. $query_uid = $is_public ? 0 : $uid;
  6951. // 如果是公共库操作,需要admin权限
  6952. if ($is_public && $role !== 'admin') {
  6953. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6954. }
  6955. // 检查是否存在且属于当前用户或公共库
  6956. $role = DB::table('mp_products')
  6957. ->whereIn('id', $ids)
  6958. ->where('cpid', $cpid)
  6959. ->where('user_id', $query_uid)
  6960. ->get();
  6961. if (!$role) Utils::throwError('20003:记录不存在');
  6962. return DB::table('mp_products')
  6963. ->where('cpid', $cpid)
  6964. ->where('user_id', $query_uid)
  6965. ->whereIn('id', $ids)
  6966. ->update([
  6967. 'is_deleted' => 1,
  6968. 'updated_at' => date('Y-m-d H:i:s')
  6969. ]);
  6970. }
  6971. public function generateThreeView($data) {
  6972. $uid = Site::getUid();
  6973. $cpid = Site::getCpid();
  6974. $role = Site::getRole();
  6975. $id = getProp($data, 'id');
  6976. if (!$id) Utils::throwError('20003:ID不能为空');
  6977. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6978. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6979. $query_uid = $is_public ? 0 : $uid;
  6980. // 如果是公共库操作,需要admin权限
  6981. if ($is_public && $role !== 'admin') {
  6982. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6983. }
  6984. // 检查是否存在且属于当前用户或公共库
  6985. $product = DB::table('mp_products')
  6986. ->where('id', $id)
  6987. ->where('cpid', $cpid)
  6988. ->where('user_id', $query_uid)
  6989. ->where('type', 1)->first();
  6990. if (!$product) Utils::throwError('20003:资产不存在');
  6991. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  6992. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6993. if (!$ref_img_url) {
  6994. // 如果没有传入参考图,使用角色表中的图片
  6995. $ref_img_url = $product->url ?? '';
  6996. if (!$ref_img_url) {
  6997. Utils::throwError('20003:参考图不能为空');
  6998. }
  6999. }
  7000. $pic_prompt = getProp($product, 'pic_prompt');
  7001. if ($pic_prompt) {
  7002. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  7003. }
  7004. // 检查参考图是否是正确的图片格式
  7005. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  7006. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  7007. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  7008. if (!in_array($extension, $allowedExtensions)) {
  7009. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  7010. }
  7011. // 处理图片模型
  7012. $model = getProp($data, 'model');
  7013. if (!$model) {
  7014. // 使用默认模型
  7015. $model = 'gpt-image-2';
  7016. }
  7017. // 验证模型是否在可用模型表中
  7018. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7019. Utils::throwError('20003:该模型已不可用,请更换!');
  7020. }
  7021. $ratio = getProp($data, 'ratio', '16:9');
  7022. $resolution = getProp($data, 'resolution', '2k');
  7023. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  7024. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7025. // 参数验证
  7026. $resolution = strtolower($resolution);
  7027. if (!isset($sizeMap[$resolution])) {
  7028. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7029. }
  7030. if (!isset($sizeMap[$resolution][$ratio])) {
  7031. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7032. }
  7033. // 根据 ratio 和 resolution 确定宽高
  7034. $width = $sizeMap[$resolution][$ratio]['width'];
  7035. $height = $sizeMap[$resolution][$ratio]['height'];
  7036. try {
  7037. // 创建图片生成任务
  7038. $params = [
  7039. 'prompt' => $prompt,
  7040. 'model' => $model,
  7041. 'ref_img_urls' => [$ref_img_url],
  7042. 'width' => $width,
  7043. 'height' => $height
  7044. ];
  7045. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7046. $task_id = $task->id;
  7047. if (!$task_id) {
  7048. Utils::throwError('20003:创建图片生成任务失败');
  7049. }
  7050. // 轮询获取结果
  7051. // 只查询数据库,不调用API,不更新任务表
  7052. $start_time = time();
  7053. $timeout = 1800;
  7054. $img_url = '';
  7055. while (time() - $start_time < $timeout) {
  7056. sleep(5);
  7057. // 只查询数据库中的任务状态,不调用API,不更新任务表
  7058. $task = DB::table('mp_generate_pic_tasks')
  7059. ->where('id', $task_id)
  7060. ->first();
  7061. if (!$task) {
  7062. Utils::throwError('20003:任务不存在');
  7063. }
  7064. if ($task->status === 'success' && $task->result_url) {
  7065. $result_urls = is_string($task->result_url)
  7066. ? json_decode($task->result_url, true)
  7067. : $task->result_url;
  7068. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7069. break;
  7070. } elseif ($task->status === 'failed') {
  7071. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  7072. }
  7073. // 其他状态继续轮询
  7074. }
  7075. if (empty($img_url)) {
  7076. Utils::throwError('20003:三视图生成超时,请稍后重试');
  7077. }
  7078. // 更新 mp_products 表(不是任务表)
  7079. DB::table('mp_products')
  7080. ->where('id', $id)
  7081. ->where('cpid', $cpid)
  7082. ->update([
  7083. 'three_view_image_url' => $img_url,
  7084. 'updated_at' => date('Y-m-d H:i:s')
  7085. ]);
  7086. return ['three_view_image_url' => $img_url];
  7087. } catch (\Exception $e) {
  7088. dLog('anime')->error('生成三视图失败', [
  7089. 'error' => $e->getMessage()
  7090. ]);
  7091. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7092. Utils::throwError('20003:' . $e->getMessage());
  7093. }
  7094. }
  7095. /**
  7096. * 推送(复制)资产或文件夹到目标位置
  7097. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7098. * @return array 返回推送结果
  7099. */
  7100. public function pushProductOrFolder($data) {
  7101. $uid = Site::getUid();
  7102. $cpid = Site::getCpid();
  7103. $role = Site::getRole();
  7104. $product_id = getProp($data, 'product_id');
  7105. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7106. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7107. if (!$product_id) {
  7108. Utils::throwError('20003:请选择要推送的项目');
  7109. }
  7110. // 查询源项目(只通过cpid查询,不限制user_id)
  7111. $sourceItem = DB::table('mp_products')
  7112. ->where('id', $product_id)
  7113. ->where('cpid', $cpid)
  7114. ->where('is_deleted', 0)
  7115. ->first();
  7116. if (!$sourceItem) {
  7117. Utils::throwError('20003:要推送的项目不存在');
  7118. }
  7119. // 通过user_id判断源是公共库还是个人库
  7120. $source_uid = $sourceItem->user_id;
  7121. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7122. // 验证目标文件夹并确定目标是公共库还是个人库
  7123. $target_level = 0;
  7124. $target_uid = $uid; // 默认推送到个人库
  7125. $target_is_public = 0;
  7126. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7127. if ($target_parent_id > 0) {
  7128. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7129. $targetParent = DB::table('mp_products')
  7130. ->where('id', $target_parent_id)
  7131. ->where('cpid', $cpid)
  7132. ->where('type', 2)
  7133. ->where('is_deleted', 0)
  7134. ->first();
  7135. if (!$targetParent) {
  7136. Utils::throwError('20003:目标文件夹不存在');
  7137. }
  7138. // 通过user_id判断目标是公共库还是个人库
  7139. $target_level = $targetParent->level;
  7140. $target_uid = $targetParent->user_id;
  7141. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7142. // 使用目标文件夹的 product 类型
  7143. $final_product_type = $targetParent->product;
  7144. }
  7145. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7146. else {
  7147. $push_to_public = getProp($data, 'push_to_public');
  7148. if ($push_to_public === '') {
  7149. Utils::throwError('20003:请选择是否推送到公共库');
  7150. }
  7151. if ($push_to_public) {
  7152. $target_uid = 0;
  7153. $target_is_public = 1;
  7154. }
  7155. // 推送到根目录时,必须指定 product 类型
  7156. if ($target_product === null || $target_product === '') {
  7157. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7158. }
  7159. $final_product_type = $target_product;
  7160. }
  7161. // 如果目标是公共库,需要admin权限
  7162. if ($target_is_public && $role !== 'admin') {
  7163. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7164. }
  7165. // 权限验证:验证是否符合允许的推送规则
  7166. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7167. try {
  7168. DB::beginTransaction();
  7169. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7170. if ($sourceItem->type == 1) {
  7171. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7172. DB::commit();
  7173. return [
  7174. 'product_id' => $newId,
  7175. ];
  7176. }
  7177. // 如果是文件夹,递归复制(支持跨类型推送)
  7178. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7179. DB::commit();
  7180. return [
  7181. 'product_id' => $newFolderId,
  7182. ];
  7183. } catch (\Exception $e) {
  7184. DB::rollBack();
  7185. dLog('anime')->error('推送失败', [
  7186. 'error' => $e->getMessage(),
  7187. 'product_id' => $product_id
  7188. ]);
  7189. Utils::throwError('20003:' . $e->getMessage());
  7190. }
  7191. }
  7192. /**
  7193. * 验证推送权限
  7194. * 允许的推送规则:
  7195. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7196. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7197. * 3. 公共库推送给公共库(公共库 → 公共库)
  7198. *
  7199. * @param int $source_uid 源的user_id
  7200. * @param int $target_uid 目标的user_id
  7201. * @param int $current_uid 当前用户ID
  7202. * @throws \Exception
  7203. */
  7204. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7205. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7206. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7207. return; // 允许
  7208. }
  7209. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7210. if ($source_uid == 0 && $target_uid == $current_uid) {
  7211. return; // 允许
  7212. }
  7213. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7214. if ($source_uid == 0 && $target_uid == 0) {
  7215. return; // 允许
  7216. }
  7217. // 其他情况都不允许
  7218. if ($source_uid != 0 && $source_uid != $current_uid) {
  7219. // 源是别人的个人库
  7220. Utils::throwError('20003:无权限访问该资产');
  7221. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7222. // 个人库推送给公共库(不允许)
  7223. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7224. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7225. // 不同用户的个人库之间推送(不允许)
  7226. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7227. } else {
  7228. // 其他未知情况
  7229. Utils::throwError('20003:不允许的推送操作');
  7230. }
  7231. }
  7232. /**
  7233. * 复制单个资产
  7234. * @param object $sourceProduct 源资产对象
  7235. * @param int $targetParentId 目标父文件夹ID
  7236. * @param int $targetLevel 目标层级
  7237. * @param int $cpid 公司ID
  7238. * @param int $targetUid 目标用户ID
  7239. * @return int 返回新资产ID
  7240. */
  7241. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7242. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7243. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7244. $newProductData = [
  7245. 'user_id' => $targetUid,
  7246. 'cpid' => $cpid,
  7247. 'type' => 1,
  7248. 'parent_id' => $targetParentId,
  7249. 'level' => $targetLevel,
  7250. 'product_name' => $sourceProduct->product_name,
  7251. 'url' => $sourceProduct->url,
  7252. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7253. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7254. 'timbre_url' => $sourceProduct->timbre_url ?? '',
  7255. 'product' => $finalProductType,
  7256. 'versions' => $sourceProduct->versions ?? '',
  7257. 'sort_order' => time(),
  7258. 'is_deleted' => 0,
  7259. 'created_at' => date('Y-m-d H:i:s'),
  7260. 'updated_at' => date('Y-m-d H:i:s')
  7261. ];
  7262. return DB::table('mp_products')->insertGetId($newProductData);
  7263. }
  7264. /**
  7265. * 递归复制文件夹及其子项
  7266. * @param object $sourceFolder 源文件夹对象
  7267. * @param int $targetParentId 目标父文件夹ID
  7268. * @param int $targetLevel 目标层级
  7269. * @param int $cpid 公司ID
  7270. * @param int $targetUid 目标用户ID
  7271. * @param int $sourceUid 源用户ID
  7272. * @return int 返回新文件夹ID
  7273. */
  7274. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7275. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7276. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7277. // 创建新文件夹
  7278. $newFolderData = [
  7279. 'user_id' => $targetUid,
  7280. 'cpid' => $cpid,
  7281. 'type' => 2,
  7282. 'parent_id' => $targetParentId,
  7283. 'level' => $targetLevel,
  7284. 'product_name' => $sourceFolder->product_name,
  7285. 'product' => $finalProductType,
  7286. 'sort_order' => time(),
  7287. 'is_deleted' => 0,
  7288. 'created_at' => date('Y-m-d H:i:s'),
  7289. 'updated_at' => date('Y-m-d H:i:s')
  7290. ];
  7291. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7292. // 获取源文件夹下的所有子项
  7293. $children = DB::table('mp_products')
  7294. ->where('parent_id', $sourceFolder->id)
  7295. ->where('cpid', $cpid)
  7296. ->where('user_id', $sourceUid)
  7297. ->where('is_deleted', 0)
  7298. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7299. ->get();
  7300. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7301. foreach ($children as $child) {
  7302. if ($child->type == 1) {
  7303. // 资产
  7304. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7305. } else {
  7306. // 文件夹
  7307. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7308. }
  7309. }
  7310. return $newFolderId;
  7311. }
  7312. /**
  7313. * 转让剧本归属(剧本及其关联资产)
  7314. *
  7315. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7316. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7317. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7318. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7319. *
  7320. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7321. * @return array
  7322. */
  7323. public function transferScriptOwner($data) {
  7324. $operatorRole = Site::getRole();
  7325. $operatorCpid = Site::getCpid();
  7326. // 1.权限校验:仅管理员和超管可操作
  7327. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7328. Utils::throwError(ErrorConst::NOT_ACCESS);
  7329. }
  7330. // 2.目标用户校验:必须存在且角色为 user(组员)
  7331. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7332. if ($targetUserId < 1) {
  7333. Utils::throwError('1002:请选择转让的目标用户');
  7334. }
  7335. $targetUser = DB::table('mp_manage_users')
  7336. ->where('id', $targetUserId)
  7337. ->where('is_deleted', 0)
  7338. ->first();
  7339. if (!$targetUser) {
  7340. Utils::throwError('20003:目标用户不存在');
  7341. }
  7342. if ((string)getProp($targetUser, 'role') !== 'user') {
  7343. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7344. }
  7345. $targetCpid = (int)getProp($targetUser, 'cpid');
  7346. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7347. $rawScriptIds = getProp($data, 'script_ids');
  7348. if (empty($rawScriptIds)) {
  7349. $rawScriptIds = getProp($data, 'script_id');
  7350. }
  7351. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7352. if (empty($scriptIds)) {
  7353. Utils::throwError('20003:请提供剧本ID');
  7354. }
  7355. // 预取剧本名称,便于失败结果中回显
  7356. $scriptNameMap = DB::table('mp_scripts')
  7357. ->whereIn('id', $scriptIds)
  7358. ->pluck('script_name', 'id')
  7359. ->all();
  7360. $successList = [];
  7361. $failedList = [];
  7362. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7363. foreach ($scriptIds as $scriptId) {
  7364. DB::beginTransaction();
  7365. try {
  7366. $successList[] = $this->transferSingleScriptOwner(
  7367. $scriptId,
  7368. $targetUserId,
  7369. $targetCpid,
  7370. $operatorRole,
  7371. $operatorCpid,
  7372. Site::getUid()
  7373. );
  7374. DB::commit();
  7375. } catch (\Throwable $e) {
  7376. DB::rollBack();
  7377. $failedList[] = [
  7378. 'script_id' => (int)$scriptId,
  7379. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7380. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7381. ];
  7382. dLog('anime')->error('剧本归属转让失败', [
  7383. 'script_id' => $scriptId,
  7384. 'target_user_id' => $targetUserId,
  7385. 'operator_uid' => Site::getUid(),
  7386. 'error' => $e->getMessage(),
  7387. ]);
  7388. }
  7389. }
  7390. return [
  7391. 'target_user_id' => $targetUserId,
  7392. 'success_count' => count($successList),
  7393. 'failed_count' => count($failedList),
  7394. 'success_list' => $successList,
  7395. 'failed_list' => $failedList,
  7396. ];
  7397. }
  7398. /**
  7399. * 单个剧本的归属转让(需在事务中调用)
  7400. *
  7401. * @param int $scriptId 剧本ID
  7402. * @param int $targetUserId 目标用户ID
  7403. * @param int $targetCpid 目标用户所属公司ID
  7404. * @param string $operatorRole 操作人角色
  7405. * @param int $operatorCpid 操作人所属公司ID
  7406. * @param int $operatorUid 操作人用户ID
  7407. * @return array
  7408. */
  7409. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7410. $script = DB::table('mp_scripts')
  7411. ->where('id', $scriptId)
  7412. ->where('is_deleted', 0)
  7413. ->first();
  7414. if (!$script) {
  7415. Utils::throwError('20003:剧本不存在');
  7416. }
  7417. $scriptCpid = (int)getProp($script, 'cpid');
  7418. $fromUserId = (int)getProp($script, 'user_id');
  7419. // 管理员仅可操作本组剧本
  7420. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7421. Utils::throwError(ErrorConst::NOT_ACCESS);
  7422. }
  7423. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7424. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7425. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7426. }
  7427. // 禁止跨组转让:目标用户必须与剧本同组
  7428. if ($targetCpid !== $scriptCpid) {
  7429. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7430. }
  7431. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7432. $productIds = $this->normalizeIdList(
  7433. DB::table('mp_script_product_mappings')
  7434. ->where('script_id', $scriptId)
  7435. ->pluck('product_id')
  7436. ->all()
  7437. );
  7438. $folderIds = [];
  7439. if (!empty($productIds)) {
  7440. $products = DB::table('mp_products')
  7441. ->whereIn('id', $productIds)
  7442. ->select('id', 'cpid', 'parent_id', 'user_id')
  7443. ->get();
  7444. // 关联资产必须全部存在,否则视为数据异常,不提交
  7445. if ($products->count() !== count($productIds)) {
  7446. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7447. }
  7448. foreach ($products as $product) {
  7449. // 关联资产必须与剧本同组,避免误转让跨组资产
  7450. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7451. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7452. }
  7453. $parentId = (int)getProp($product, 'parent_id', 0);
  7454. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7455. $folderIds[] = $parentId;
  7456. }
  7457. }
  7458. // 仅转让归属于原剧本所有者的资产
  7459. $folderIds = DB::table('mp_products')
  7460. ->whereIn('id', $folderIds)
  7461. ->where('type', 2)
  7462. ->where('cpid', $scriptCpid)
  7463. ->where('user_id', $fromUserId)
  7464. ->pluck('id')
  7465. ->map('intval')
  7466. ->all();
  7467. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7468. if ($operatorRole !== 'superadmin') {
  7469. foreach ($products as $product) {
  7470. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7471. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7472. }
  7473. }
  7474. foreach ($products as $product) {
  7475. $parentId = (int)getProp($product, 'parent_id', 0);
  7476. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7477. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7478. }
  7479. }
  7480. }
  7481. }
  7482. $now = now();
  7483. // 5.更新剧本归属
  7484. DB::table('mp_scripts')
  7485. ->where('id', $scriptId)
  7486. ->update([
  7487. 'user_id' => $targetUserId,
  7488. 'updated_at' => $now,
  7489. ]);
  7490. // 6.更新关联资产归属
  7491. if (!empty($productIds)) {
  7492. DB::table('mp_products')
  7493. ->whereIn('id', $productIds)
  7494. ->update([
  7495. 'user_id' => $targetUserId,
  7496. 'updated_at' => $now,
  7497. ]);
  7498. }
  7499. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7500. if (!empty($folderIds)) {
  7501. DB::table('mp_products')
  7502. ->whereIn('id', $folderIds)
  7503. ->update([
  7504. 'user_id' => $targetUserId,
  7505. 'updated_at' => $now,
  7506. ]);
  7507. }
  7508. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7509. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7510. if ($scriptOwner !== $targetUserId) {
  7511. Utils::throwError('20003:剧本归属更新失败');
  7512. }
  7513. if (!empty($productIds)) {
  7514. $updatedProductCount = DB::table('mp_products')
  7515. ->whereIn('id', $productIds)
  7516. ->where('user_id', $targetUserId)
  7517. ->count();
  7518. if ($updatedProductCount !== count($productIds)) {
  7519. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7520. }
  7521. }
  7522. if (!empty($folderIds)) {
  7523. $updatedFolderCount = DB::table('mp_products')
  7524. ->whereIn('id', $folderIds)
  7525. ->where('user_id', $targetUserId)
  7526. ->count();
  7527. if ($updatedFolderCount !== count($folderIds)) {
  7528. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7529. }
  7530. }
  7531. return [
  7532. 'script_id' => (int)$scriptId,
  7533. 'script_name' => (string)getProp($script, 'script_name', ''),
  7534. 'from_user_id' => $fromUserId,
  7535. 'to_user_id' => $targetUserId,
  7536. 'product_count' => count($productIds),
  7537. 'folder_count' => count($folderIds),
  7538. ];
  7539. }
  7540. /**
  7541. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7542. *
  7543. * @param mixed $ids 待处理的ID集合
  7544. * @return array 去重后的正整数ID数组
  7545. */
  7546. private function normalizeIdList($ids) {
  7547. if (!is_array($ids)) {
  7548. $ids = explode(',', (string)$ids);
  7549. }
  7550. $result = [];
  7551. foreach ($ids as $item) {
  7552. if (is_array($item)) {
  7553. continue;
  7554. }
  7555. foreach (explode(',', (string)$item) as $part) {
  7556. $part = trim($part);
  7557. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7558. $result[] = (int)$part;
  7559. }
  7560. }
  7561. }
  7562. return array_values(array_unique($result));
  7563. }
  7564. /**
  7565. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7566. *
  7567. * 流程:
  7568. * 1. 校验剧本存在且属于当前用户
  7569. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7570. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7571. * 4. 事务内创建类型文件夹、资产与剧本映射
  7572. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7573. *
  7574. * @param array $data 请求参数
  7575. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7576. * @return array|\Generator
  7577. */
  7578. public function importScriptProductsByExcel($data, $file) {
  7579. $uid = Site::getUid();
  7580. $cpid = Site::getCpid();
  7581. $script_id = (int)getProp($data, 'script_id', 0);
  7582. if (!$script_id) {
  7583. Utils::throwError('20003:请提供剧本ID');
  7584. }
  7585. // 验证剧本是否存在,且只能导入自己创建的剧本
  7586. $script = DB::table('mp_scripts')
  7587. ->where('id', $script_id)
  7588. ->where('is_deleted', 0)
  7589. ->where('user_id', $uid)
  7590. ->first();
  7591. if (!$script) {
  7592. Utils::throwError('20003:剧本不存在或无权限操作');
  7593. }
  7594. $script_name = $script->script_name ?? 'script_' . $script_id;
  7595. // 校验上传文件
  7596. if (!$file) {
  7597. Utils::throwError('20003:请上传Excel文件');
  7598. }
  7599. $extension = strtolower($file->getClientOriginalExtension());
  7600. if (!in_array($extension, ['xlsx', 'xls'])) {
  7601. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7602. }
  7603. if ($file->getSize() > 10 * 1024 * 1024) {
  7604. Utils::throwError('20003:文件大小不能超过10M');
  7605. }
  7606. // 解析 Excel(第一行为表头)
  7607. $rows = $this->readImportExcelRows($file);
  7608. if (empty($rows)) {
  7609. Utils::throwError('20003:Excel内容为空');
  7610. }
  7611. $headers = array_shift($rows);
  7612. // 定位强制列
  7613. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7614. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7615. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7616. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7617. $missingColumns = [];
  7618. if ($typeColumnIndex < 0) {
  7619. $missingColumns[] = '资产类型';
  7620. }
  7621. if ($nameColumnIndex < 0) {
  7622. $missingColumns[] = '资产名称';
  7623. }
  7624. if ($rangeColumnIndex < 0) {
  7625. $missingColumns[] = '使用范围';
  7626. }
  7627. if ($promptColumnIndex < 0) {
  7628. $missingColumns[] = '参考提示词';
  7629. }
  7630. if (!empty($missingColumns)) {
  7631. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7632. }
  7633. // 先整体校验 Excel 数据,所有异常行一次性返回
  7634. $validation = $this->validateImportExcelRows(
  7635. $rows,
  7636. $typeColumnIndex,
  7637. $nameColumnIndex,
  7638. $rangeColumnIndex,
  7639. $promptColumnIndex
  7640. );
  7641. $errors = $validation['errors'];
  7642. $checkedRows = $validation['checked_rows'];
  7643. if (empty($checkedRows)) {
  7644. $errors[] = 'Excel中没有有效的数据行';
  7645. }
  7646. if (!empty($errors)) {
  7647. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7648. }
  7649. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7650. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7651. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7652. $validRows = $dedupResult['valid_rows'];
  7653. $skipped = $dedupResult['skipped'];
  7654. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7655. $model = getProp($data, 'model');
  7656. if (!$model) {
  7657. $model = 'gpt-image-2';
  7658. }
  7659. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7660. Utils::throwError('20003:该模型已不可用,请更换!');
  7661. }
  7662. $ratio = getProp($data, 'ratio', '9:16');
  7663. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7664. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7665. if (!isset($sizeMap[$resolution])) {
  7666. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7667. }
  7668. if (!isset($sizeMap[$resolution][$ratio])) {
  7669. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7670. }
  7671. $width = $sizeMap[$resolution][$ratio]['width'];
  7672. $height = $sizeMap[$resolution][$ratio]['height'];
  7673. $autoRaw = getProp($data, 'auto_generate_images', true);
  7674. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7675. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7676. $taskCenterId = $this->createScriptProductTaskCenter(
  7677. $uid,
  7678. $cpid,
  7679. $script_id,
  7680. $validRows,
  7681. $model,
  7682. $ratio,
  7683. $resolution,
  7684. $auto_generate_images
  7685. );
  7686. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7687. if (empty($validRows)) {
  7688. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7689. $script_id,
  7690. $model,
  7691. $width,
  7692. $height,
  7693. $auto_generate_images
  7694. );
  7695. $productTaskMap = $existingTaskInfo['product_task_map'];
  7696. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7697. if (!empty($productTaskMap)) {
  7698. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7699. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7700. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7701. } else {
  7702. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7703. }
  7704. $resultData = [
  7705. 'success' => true,
  7706. 'message' => $message,
  7707. 'script_id' => $script_id,
  7708. 'script_name' => $script_name,
  7709. 'imported_count' => 0,
  7710. 'existing_products' => $existingTaskInfo['product_count'],
  7711. 'skipped_count' => count($skipped),
  7712. 'skipped' => $skipped,
  7713. 'created_products' => [],
  7714. 'type_folder_ids' => $typeFolderIds,
  7715. 'pending_tasks_count' => count($productTaskMap),
  7716. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7717. 'task_center_id' => $taskCenterId,
  7718. ];
  7719. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7720. if (!empty($productTaskMap)) {
  7721. return $this->pollProductImageTasks(
  7722. $script_id,
  7723. $script_name,
  7724. $productTaskMap,
  7725. $typeFolderIds,
  7726. $taskCenterId,
  7727. ['import_result' => $resultData],
  7728. ['import_result' => $resultData]
  7729. );
  7730. }
  7731. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7732. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7733. }
  7734. // 事务内创建资产、类型文件夹与剧本映射
  7735. $typeFolderIds = [];
  7736. $createdProducts = [];
  7737. $mappingRecords = [];
  7738. $now = now();
  7739. DB::beginTransaction();
  7740. try {
  7741. foreach ($validRows as $row) {
  7742. $type = $row['type'];
  7743. if (!isset($typeFolderIds[$type])) {
  7744. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7745. $folder = DB::table('mp_products')
  7746. ->where('cpid', $cpid)
  7747. ->where('type', 2)
  7748. ->where('product', $type)
  7749. ->where('product_name', $script_name)
  7750. ->where('parent_id', 0)
  7751. ->where('is_deleted', 0)
  7752. ->first();
  7753. if ($folder) {
  7754. $typeFolderIds[$type] = $folder->id;
  7755. } else {
  7756. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7757. 'user_id' => $uid,
  7758. 'cpid' => $cpid,
  7759. 'type' => 2, // 文件夹
  7760. 'product' => $type, // 1=角色 2=场景 3=道具
  7761. 'parent_id' => 0,
  7762. 'level' => 1,
  7763. 'product_name' => $script_name,
  7764. 'sort_order' => time() + $type,
  7765. 'is_deleted' => 0,
  7766. 'created_at' => $now,
  7767. 'updated_at' => $now,
  7768. ]);
  7769. }
  7770. }
  7771. $folder_id = $typeFolderIds[$type];
  7772. $product_id = DB::table('mp_products')->insertGetId([
  7773. 'user_id' => $uid,
  7774. 'cpid' => $cpid,
  7775. 'type' => 1, // 资产
  7776. 'product' => $type,
  7777. 'parent_id' => $folder_id,
  7778. 'level' => 2,
  7779. 'product_name' => $row['product_name'],
  7780. 'pic_prompt' => $row['pic_prompt'],
  7781. 'sort_order' => time(),
  7782. 'is_deleted' => 0,
  7783. 'created_at' => $now,
  7784. 'updated_at' => $now,
  7785. ]);
  7786. $createdProducts[] = [
  7787. 'id' => $product_id,
  7788. 'type' => $type,
  7789. 'product_name' => $row['product_name'],
  7790. 'pic_prompt' => $row['pic_prompt'],
  7791. ];
  7792. // 为每个使用范围(集数)创建映射记录
  7793. foreach ($row['episode_numbers'] as $episodeNumber) {
  7794. $mappingRecords[] = [
  7795. 'script_id' => $script_id,
  7796. 'product_id' => $product_id,
  7797. 'episode_number' => $episodeNumber,
  7798. 'created_at' => $now,
  7799. 'updated_at' => $now,
  7800. ];
  7801. }
  7802. }
  7803. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7804. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7805. // 剧本已有资产,同步更新is_products标记
  7806. DB::table('mp_scripts')->where('id', $script_id)->update([
  7807. 'is_products' => 1,
  7808. 'updated_at' => $now,
  7809. ]);
  7810. DB::commit();
  7811. } catch (\Exception $e) {
  7812. DB::rollback();
  7813. if ($taskCenterId) {
  7814. $this->taskCenterService->updateTask($taskCenterId, [
  7815. 'status' => MpTaskCenter::STATUS_FAILED,
  7816. 'error_message' => $e->getMessage(),
  7817. ]);
  7818. }
  7819. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7820. 'script_id' => $script_id,
  7821. 'error' => $e->getMessage(),
  7822. 'trace' => $e->getTraceAsString(),
  7823. ]);
  7824. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7825. }
  7826. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7827. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7828. $script_id,
  7829. $model,
  7830. $width,
  7831. $height,
  7832. $auto_generate_images
  7833. );
  7834. $productTaskMap = $existingTaskInfo['product_task_map'];
  7835. $resultData = [
  7836. 'success' => true,
  7837. 'message' => '导入完成',
  7838. 'script_id' => $script_id,
  7839. 'script_name' => $script_name,
  7840. 'imported_count' => count($createdProducts),
  7841. 'skipped_count' => count($skipped),
  7842. 'skipped' => $skipped,
  7843. 'created_products' => array_map(function ($item) {
  7844. return [
  7845. 'id' => $item['id'],
  7846. 'type' => $item['type'],
  7847. 'product_name' => $item['product_name'],
  7848. ];
  7849. }, $createdProducts),
  7850. 'type_folder_ids' => $typeFolderIds,
  7851. 'pending_tasks_count' => count($productTaskMap),
  7852. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7853. 'task_center_id' => $taskCenterId,
  7854. ];
  7855. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7856. if (!empty($productTaskMap)) {
  7857. return $this->pollProductImageTasks(
  7858. $script_id,
  7859. $script_name,
  7860. $productTaskMap,
  7861. $typeFolderIds,
  7862. $taskCenterId,
  7863. ['import_result' => $resultData],
  7864. ['import_result' => $resultData]
  7865. );
  7866. }
  7867. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7868. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7869. }
  7870. /**
  7871. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7872. *
  7873. * @param array $rows
  7874. * @param int $typeColumnIndex
  7875. * @param int $nameColumnIndex
  7876. * @param int $rangeColumnIndex
  7877. * @param int $promptColumnIndex
  7878. * @return array ['errors' => [], 'checked_rows' => []]
  7879. */
  7880. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7881. $errors = [];
  7882. $checkedRows = [];
  7883. foreach ($rows as $rowIndex => $row) {
  7884. // 数据从第2行开始(表头占第1行)
  7885. $excelRowNo = $rowIndex + 2;
  7886. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7887. continue;
  7888. }
  7889. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7890. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7891. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7892. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7893. $missingFields = [];
  7894. if ($typeRaw === '') {
  7895. $missingFields[] = '资产类型';
  7896. }
  7897. if ($nameRaw === '') {
  7898. $missingFields[] = '资产名称';
  7899. }
  7900. if ($rangeRaw === '') {
  7901. $missingFields[] = '使用范围';
  7902. }
  7903. if ($promptRaw === '') {
  7904. $missingFields[] = '参考提示词';
  7905. }
  7906. if (!empty($missingFields)) {
  7907. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7908. continue;
  7909. }
  7910. // 资产类型校验
  7911. $productType = $this->resolveImportProductType($typeRaw);
  7912. if (!$productType) {
  7913. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7914. continue;
  7915. }
  7916. // 资产名称去除两边特殊符号
  7917. $productName = $this->normalizeImportProductName($nameRaw);
  7918. if ($productName === '') {
  7919. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7920. continue;
  7921. }
  7922. if (mb_strlen($productName, 'UTF-8') > 64) {
  7923. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7924. continue;
  7925. }
  7926. // 解析使用范围(逗号分隔的集数)
  7927. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7928. if (empty($episodeNumbers)) {
  7929. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7930. continue;
  7931. }
  7932. $checkedRows[] = [
  7933. 'row' => $excelRowNo,
  7934. 'type' => $productType,
  7935. 'product_name' => $productName,
  7936. 'episode_numbers' => $episodeNumbers,
  7937. 'pic_prompt' => $promptRaw,
  7938. ];
  7939. }
  7940. return [
  7941. 'errors' => $errors,
  7942. 'checked_rows' => $checkedRows,
  7943. ];
  7944. }
  7945. /**
  7946. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7947. *
  7948. * @param array $checkedRows
  7949. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  7950. * @return array ['valid_rows' => [], 'skipped' => []]
  7951. */
  7952. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  7953. $seenNames = [];
  7954. $validRows = [];
  7955. $skipped = [];
  7956. foreach ($checkedRows as $row) {
  7957. $nameKey = $row['product_name'];
  7958. $typeText = $this->getImportProductTypeText($row['type']);
  7959. if (isset($seenNames[$nameKey])) {
  7960. $skipped[] = [
  7961. 'row' => $row['row'],
  7962. 'type' => $typeText,
  7963. 'product_name' => $row['product_name'],
  7964. 'reason' => 'Excel中资产名称重复',
  7965. ];
  7966. continue;
  7967. }
  7968. if (isset($existingNames[$nameKey])) {
  7969. $skipped[] = [
  7970. 'row' => $row['row'],
  7971. 'type' => $typeText,
  7972. 'product_name' => $row['product_name'],
  7973. 'reason' => '剧本中已存在同名资产',
  7974. ];
  7975. continue;
  7976. }
  7977. $seenNames[$nameKey] = true;
  7978. $validRows[] = $row;
  7979. }
  7980. return [
  7981. 'valid_rows' => $validRows,
  7982. 'skipped' => $skipped,
  7983. ];
  7984. }
  7985. /**
  7986. * 读取 Excel 文件为二维数组(第一行为表头)
  7987. *
  7988. * @param \Illuminate\Http\UploadedFile $file
  7989. * @return array
  7990. */
  7991. private function readImportExcelRows($file) {
  7992. try {
  7993. $reader = IOFactory::createReaderForFile($file->getRealPath());
  7994. $reader->setReadDataOnly(true);
  7995. $spreadsheet = $reader->load($file->getRealPath());
  7996. $sheet = $spreadsheet->getSheet(0);
  7997. $rows = $sheet->toArray(null, true, true, false);
  7998. $spreadsheet->disconnectWorksheets();
  7999. unset($spreadsheet);
  8000. return $rows;
  8001. } catch (\Exception $e) {
  8002. dLog('anime')->error('Excel文件解析失败', [
  8003. 'error' => $e->getMessage(),
  8004. ]);
  8005. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  8006. }
  8007. }
  8008. /**
  8009. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  8010. *
  8011. * @param array $headers
  8012. * @param array $exactKeywords
  8013. * @param array $fuzzyKeywords
  8014. * @return int
  8015. */
  8016. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  8017. foreach ($headers as $index => $header) {
  8018. $header = trim((string)$header);
  8019. if ($header === '') {
  8020. continue;
  8021. }
  8022. foreach ($exactKeywords as $keyword) {
  8023. if ($header === $keyword) {
  8024. return $index;
  8025. }
  8026. }
  8027. }
  8028. foreach ($headers as $index => $header) {
  8029. $header = trim((string)$header);
  8030. if ($header === '') {
  8031. continue;
  8032. }
  8033. foreach ($fuzzyKeywords as $keyword) {
  8034. if (mb_strpos($header, $keyword) !== false) {
  8035. return $index;
  8036. }
  8037. }
  8038. }
  8039. return -1;
  8040. }
  8041. /**
  8042. * 判断 Excel 行是否为空行
  8043. *
  8044. * @param array $row
  8045. * @return bool
  8046. */
  8047. private function isImportExcelRowEmpty(array $row) {
  8048. foreach ($row as $cell) {
  8049. if (trim((string)$cell) !== '') {
  8050. return false;
  8051. }
  8052. }
  8053. return true;
  8054. }
  8055. /**
  8056. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  8057. *
  8058. * @param string $name
  8059. * @return string
  8060. */
  8061. private function normalizeImportProductName($name) {
  8062. $name = trim((string)$name);
  8063. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  8064. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  8065. return '';
  8066. }
  8067. return $name;
  8068. }
  8069. /**
  8070. * 解析 Excel 中的资产类型
  8071. *
  8072. * @param string $value
  8073. * @return int|null 1=角色 2=场景 3=道具
  8074. */
  8075. private function resolveImportProductType($value) {
  8076. $value = trim((string)$value);
  8077. $map = [
  8078. '角色' => 1,
  8079. '主体' => 1,
  8080. '人物' => 1,
  8081. '1' => 1,
  8082. '场景' => 2,
  8083. '2' => 2,
  8084. '道具' => 3,
  8085. '3' => 3,
  8086. ];
  8087. return isset($map[$value]) ? $map[$value] : null;
  8088. }
  8089. /**
  8090. * 资产类型文案
  8091. *
  8092. * @param int $type
  8093. * @return string
  8094. */
  8095. private function getImportProductTypeText($type) {
  8096. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8097. return isset($map[$type]) ? $map[$type] : (string)$type;
  8098. }
  8099. /**
  8100. * 解析使用范围(逗号分隔的集数)
  8101. *
  8102. * @param string $value
  8103. * @return array
  8104. */
  8105. private function parseImportEpisodeNumbers($value) {
  8106. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8107. $episodeNumbers = [];
  8108. foreach ($parts as $part) {
  8109. if ($part === '') {
  8110. continue;
  8111. }
  8112. if (!is_numeric($part)) {
  8113. return [];
  8114. }
  8115. $episodeNumbers[] = (int)$part;
  8116. }
  8117. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8118. sort($episodeNumbers);
  8119. return $episodeNumbers;
  8120. }
  8121. /**
  8122. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8123. *
  8124. * @param int $script_id
  8125. * @param int $cpid
  8126. * @return array
  8127. */
  8128. private function getScriptProductNames($script_id, $cpid) {
  8129. $products = DB::table('mp_script_product_mappings as m')
  8130. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8131. ->where('m.script_id', $script_id)
  8132. ->where('p.cpid', $cpid)
  8133. ->where('p.type', 1)
  8134. ->where('p.is_deleted', 0)
  8135. ->get(['p.product_name']);
  8136. $names = [];
  8137. foreach ($products as $product) {
  8138. $name = $this->normalizeImportProductName($product->product_name);
  8139. if ($name !== '') {
  8140. $names[$name] = true;
  8141. }
  8142. }
  8143. return $names;
  8144. }
  8145. /**
  8146. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8147. *
  8148. * @param int $script_id
  8149. * @return array ['资产名称' => true]
  8150. */
  8151. private function getScriptAssetNames($script_id) {
  8152. $products = DB::table('mp_script_product_mappings as m')
  8153. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8154. ->where('m.script_id', $script_id)
  8155. ->where('p.type', 1)
  8156. ->where('p.is_deleted', 0)
  8157. ->get(['p.product_name']);
  8158. $names = [];
  8159. foreach ($products as $product) {
  8160. $name = $this->normalizeImportProductName($product->product_name);
  8161. if ($name !== '') {
  8162. $names[$name] = true;
  8163. }
  8164. }
  8165. return $names;
  8166. }
  8167. /**
  8168. * 校验并提取本次入参中的新增资产行
  8169. *
  8170. * 规则:
  8171. * - 资产名称为空(或仅剩占位符):跳过
  8172. * - 同一份入参内重名(跨类型):保留最后一条
  8173. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8174. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8175. *
  8176. * @param int $script_id
  8177. * @param mixed $products 入参(数组或 JSON 字符串)
  8178. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8179. */
  8180. private function extractNewScriptProductRows($script_id, $products) {
  8181. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8182. if (is_string($products)) {
  8183. $decoded = json_decode($products, true);
  8184. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8185. }
  8186. if (!is_array($products) || empty($products)) {
  8187. return [];
  8188. }
  8189. $rowMap = [];
  8190. foreach ($products as $productGroup) {
  8191. $type = getProp($productGroup, 'type');
  8192. $content = getProp($productGroup, 'content', []);
  8193. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8194. continue;
  8195. }
  8196. // 获取表头(第一行)并查找关键列的位置
  8197. $headers = $content[0];
  8198. $nameColumnIndex = -1;
  8199. $sequenceColumnIndex = -1;
  8200. $promptColumnIndex = -1;
  8201. $fallbackPromptColumnIndex = -1;
  8202. foreach ($headers as $index => $header) {
  8203. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8204. $nameColumnIndex = $index;
  8205. }
  8206. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8207. $sequenceColumnIndex = $index;
  8208. }
  8209. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8210. $promptColumnIndex = $index;
  8211. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8212. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8213. $fallbackPromptColumnIndex = $index;
  8214. }
  8215. }
  8216. if ($promptColumnIndex === -1) {
  8217. $promptColumnIndex = $fallbackPromptColumnIndex;
  8218. }
  8219. if ($nameColumnIndex === -1) {
  8220. continue;
  8221. }
  8222. for ($i = 1; $i < count($content); $i++) {
  8223. $row = $content[$i];
  8224. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8225. continue;
  8226. }
  8227. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8228. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8229. if ($product_name === '') {
  8230. continue;
  8231. }
  8232. $pic_prompt = '';
  8233. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8234. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8235. }
  8236. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8237. $sequences = [];
  8238. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8239. ? trim((string)$row[$sequenceColumnIndex])
  8240. : '';
  8241. if ($sequence_str !== '') {
  8242. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8243. if (is_numeric($part)) {
  8244. $sequences[] = (int)$part;
  8245. }
  8246. }
  8247. }
  8248. // 跨类型判重,同一份入参内重名保留最后一条
  8249. $rowMap[$product_name] = [
  8250. 'type' => (int)$type,
  8251. 'product_name' => $product_name,
  8252. 'pic_prompt' => $pic_prompt,
  8253. 'episode_numbers' => $sequences,
  8254. ];
  8255. }
  8256. }
  8257. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8258. $existingNames = $this->getScriptAssetNames($script_id);
  8259. $newRows = [];
  8260. $emptyPromptNames = [];
  8261. foreach ($rowMap as $name => $row) {
  8262. if (isset($existingNames[$name])) {
  8263. continue;
  8264. }
  8265. if ($row['pic_prompt'] === '') {
  8266. $emptyPromptNames[] = $name;
  8267. continue;
  8268. }
  8269. $newRows[] = $row;
  8270. }
  8271. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8272. if (!empty($emptyPromptNames)) {
  8273. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8274. }
  8275. return $newRows;
  8276. }
  8277. /**
  8278. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8279. *
  8280. * - 已有图片任务的资产:收集任务ID,交给轮询
  8281. * - 已有图片且生成成功的资产:跳过
  8282. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8283. *
  8284. * @param int $script_id
  8285. * @param string $model
  8286. * @param int $width
  8287. * @param int $height
  8288. * @param bool $auto_generate_images
  8289. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8290. */
  8291. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8292. $productTaskMap = [];
  8293. $typeFolderIds = [];
  8294. $hasAllTasks = true;
  8295. $createdCount = 0;
  8296. $existingMappings = DB::table('mp_script_product_mappings')
  8297. ->where('script_id', $script_id)
  8298. ->get();
  8299. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8300. $productsWithTasks = DB::table('mp_products')
  8301. ->whereIn('id', $productIds)
  8302. ->where('is_deleted', 0)
  8303. ->get();
  8304. foreach ($productsWithTasks as $product) {
  8305. // 收集类型文件夹ID
  8306. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8307. $parentFolder = DB::table('mp_products')
  8308. ->where('id', $product->parent_id)
  8309. ->where('type', 2)
  8310. ->first();
  8311. if ($parentFolder) {
  8312. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8313. }
  8314. }
  8315. // 检查是否有图片生成任务
  8316. if (!empty($product->pic_task_id)) {
  8317. $productTaskMap[$product->id] = $product->pic_task_id;
  8318. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8319. continue;
  8320. } else {
  8321. // 有资产没有图片
  8322. $hasAllTasks = false;
  8323. }
  8324. }
  8325. // 为没有图片的资产补建图片生成任务
  8326. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8327. DB::beginTransaction();
  8328. try {
  8329. foreach ($productsWithTasks as $product) {
  8330. // 跳过已有任务的资产
  8331. if (!empty($product->pic_task_id)) {
  8332. continue;
  8333. }
  8334. // 跳过没有提示词的资产
  8335. if (empty($product->pic_prompt)) {
  8336. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8337. 'product_id' => $product->id,
  8338. 'product_name' => $product->product_name,
  8339. ]);
  8340. continue;
  8341. }
  8342. try {
  8343. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8344. 'prompt' => $product->pic_prompt,
  8345. 'model' => $model,
  8346. 'ref_img_urls' => [],
  8347. 'width' => $width,
  8348. 'height' => $height,
  8349. // 计费锚点(剧本),用于积分明细归属统计
  8350. 'script_id' => $script_id,
  8351. ]);
  8352. $task_id = $task->id;
  8353. if ($task_id) {
  8354. $productTaskMap[$product->id] = $task_id;
  8355. $createdCount++;
  8356. DB::table('mp_products')
  8357. ->where('id', $product->id)
  8358. ->update([
  8359. 'pic_task_id' => $task_id,
  8360. 'pic_task_status' => '生成中',
  8361. 'updated_at' => now(),
  8362. ]);
  8363. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8364. 'product_id' => $product->id,
  8365. 'task_id' => $task_id,
  8366. ]);
  8367. }
  8368. } catch (\Exception $e) {
  8369. dLog('anime')->error('创建资产图片生成任务失败', [
  8370. 'product_id' => $product->id,
  8371. 'error' => $e->getMessage(),
  8372. ]);
  8373. DB::table('mp_products')
  8374. ->where('id', $product->id)
  8375. ->update([
  8376. 'pic_task_status' => '生成失败',
  8377. 'updated_at' => now(),
  8378. ]);
  8379. }
  8380. }
  8381. DB::commit();
  8382. } catch (\Exception $e) {
  8383. DB::rollback();
  8384. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8385. 'script_id' => $script_id,
  8386. 'error' => $e->getMessage(),
  8387. ]);
  8388. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8389. }
  8390. }
  8391. return [
  8392. 'product_task_map' => $productTaskMap,
  8393. 'type_folder_ids' => $typeFolderIds,
  8394. 'has_all_tasks' => $hasAllTasks,
  8395. 'product_count' => count($productIds),
  8396. 'created_count' => $createdCount,
  8397. ];
  8398. }
  8399. /**
  8400. * 保存剧本资产关联关系
  8401. * @param array $data 请求参数
  8402. * @return bool
  8403. */
  8404. public function saveScriptProducts($data) {
  8405. $uid = Site::getUid();
  8406. $cpid = Site::getCpid();
  8407. $script_id = getProp($data, 'script_id');
  8408. $products = getProp($data, 'products', []);
  8409. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8410. if (!$script_id) {
  8411. Utils::throwError('20003:请提供剧本ID');
  8412. }
  8413. // 验证剧本是否存在
  8414. $script = DB::table('mp_scripts')
  8415. ->where('id', $script_id)
  8416. ->where('is_deleted', 0)
  8417. ->first();
  8418. if (!$script) {
  8419. Utils::throwError('20003:剧本不存在');
  8420. }
  8421. // 处理图片模型
  8422. $model = getProp($data, 'model');
  8423. if (!$model) {
  8424. // 使用默认模型
  8425. $model = 'gpt-image-2';
  8426. }
  8427. // 验证模型是否在可用模型表中
  8428. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8429. Utils::throwError('20003:该模型已不可用,请更换!');
  8430. }
  8431. $ratio = getProp($data, 'ratio', '9:16');
  8432. $resolution = getProp($data, 'resolution', '2k');
  8433. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8434. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8435. // 参数验证
  8436. $resolution = strtolower($resolution);
  8437. if (!isset($sizeMap[$resolution])) {
  8438. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8439. }
  8440. if (!isset($sizeMap[$resolution][$ratio])) {
  8441. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8442. }
  8443. // 根据 ratio 和 resolution 确定宽高
  8444. $width = $sizeMap[$resolution][$ratio]['width'];
  8445. $height = $sizeMap[$resolution][$ratio]['height'];
  8446. $script_name = $script->script_name ?? 'script_' . $script_id;
  8447. // 先校验并提取本次入参中的新增资产行:
  8448. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8449. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8450. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8451. $taskCenterId = $this->createScriptProductTaskCenter(
  8452. $uid,
  8453. $cpid,
  8454. $script_id,
  8455. $products,
  8456. $model,
  8457. $ratio,
  8458. $resolution,
  8459. $auto_generate_images
  8460. );
  8461. // 检查是否已经有该剧本的资产数据
  8462. $existingMappings = DB::table('mp_script_product_mappings')
  8463. ->where('script_id', $script_id)
  8464. ->get();
  8465. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8466. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8467. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8468. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8469. // 查询这些资产的图片生成任务状态
  8470. $productsWithTasks = DB::table('mp_products')
  8471. ->whereIn('id', $productIds)
  8472. ->where('is_deleted', 0)
  8473. ->get();
  8474. $productTaskMap = [];
  8475. $typeFolderIds = [];
  8476. $hasAllTasks = true;
  8477. foreach ($productsWithTasks as $product) {
  8478. // 收集类型文件夹ID
  8479. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8480. $parentFolder = DB::table('mp_products')
  8481. ->where('id', $product->parent_id)
  8482. ->where('type', 2)
  8483. ->first();
  8484. if ($parentFolder) {
  8485. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8486. }
  8487. }
  8488. // 检查是否有图片生成任务
  8489. if (!empty($product->pic_task_id)) {
  8490. $productTaskMap[$product->id] = $product->pic_task_id;
  8491. } else if($product->url && $product->pic_task_status == '生成成功') {
  8492. continue;
  8493. } else {
  8494. // 有资产没有图片任务
  8495. $hasAllTasks = false;
  8496. }
  8497. }
  8498. // 如果所有资产都有任务ID,直接轮询返回结果
  8499. if ($hasAllTasks && !empty($productTaskMap)) {
  8500. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8501. 'script_id' => $script_id,
  8502. 'script_name' => $script_name,
  8503. 'product_count' => count($productTaskMap)
  8504. ]);
  8505. // 直接返回 SSE 流轮询结果
  8506. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8507. }
  8508. // 如果部分资产没有任务ID,只为这些资产创建任务
  8509. if (!$hasAllTasks && $auto_generate_images) {
  8510. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8511. 'script_id' => $script_id,
  8512. 'script_name' => $script_name
  8513. ]);
  8514. // 开启事务
  8515. DB::beginTransaction();
  8516. try {
  8517. foreach ($productsWithTasks as $product) {
  8518. // 跳过已有任务的资产
  8519. if (!empty($product->pic_task_id)) {
  8520. continue;
  8521. }
  8522. // 跳过没有提示词的资产
  8523. if (empty($product->pic_prompt)) {
  8524. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8525. 'product_id' => $product->id,
  8526. 'product_name' => $product->product_name
  8527. ]);
  8528. continue;
  8529. }
  8530. try {
  8531. // 创建图片生成任务
  8532. $params = [
  8533. 'prompt' => $product->pic_prompt,
  8534. 'model' => $model,
  8535. 'ref_img_urls' => [],
  8536. 'width' => $width,
  8537. 'height' => $height,
  8538. // 计费锚点(剧本),用于积分明细归属统计
  8539. 'script_id' => $script_id,
  8540. ];
  8541. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8542. $task_id = $task->id;
  8543. if ($task_id) {
  8544. $productTaskMap[$product->id] = $task_id;
  8545. // 在事务中更新资产表的任务ID和状态
  8546. DB::table('mp_products')
  8547. ->where('id', $product->id)
  8548. ->update([
  8549. 'pic_task_id' => $task_id,
  8550. 'pic_task_status' => '生成中',
  8551. 'updated_at' => now()
  8552. ]);
  8553. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8554. 'product_id' => $product->id,
  8555. 'task_id' => $task_id
  8556. ]);
  8557. }
  8558. } catch (\Exception $e) {
  8559. dLog('anime')->error('创建资产图片生成任务失败', [
  8560. 'product_id' => $product->id,
  8561. 'error' => $e->getMessage()
  8562. ]);
  8563. // 标记为失败(仍在事务中)
  8564. DB::table('mp_products')
  8565. ->where('id', $product->id)
  8566. ->update([
  8567. 'pic_task_status' => '生成失败',
  8568. 'updated_at' => now()
  8569. ]);
  8570. }
  8571. }
  8572. // 提交事务
  8573. DB::commit();
  8574. // 如果有新创建的任务,返回 SSE 流
  8575. if (!empty($productTaskMap)) {
  8576. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8577. }
  8578. } catch (\Exception $e) {
  8579. // 回滚事务
  8580. DB::rollback();
  8581. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8582. 'script_id' => $script_id,
  8583. 'error' => $e->getMessage()
  8584. ]);
  8585. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8586. }
  8587. }
  8588. // 如果不需要生成图片,返回已存在的信息
  8589. $resultData = [
  8590. 'success' => true,
  8591. 'message' => '剧本资产已存在',
  8592. 'script_id' => $script_id,
  8593. 'script_name' => $script_name,
  8594. 'type_folder_ids' => $typeFolderIds,
  8595. 'existing_products' => count($productIds),
  8596. 'tasks_count' => count($productTaskMap),
  8597. 'task_center_id' => $taskCenterId
  8598. ];
  8599. // 接口已正常完成,更新任务中心状态和结果
  8600. if ($taskCenterId) {
  8601. $this->taskCenterService->updateTask($taskCenterId, [
  8602. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8603. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8604. 'error_message' => null
  8605. ]);
  8606. }
  8607. return $resultData;
  8608. }
  8609. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8610. if (empty($newRows)) {
  8611. $decodedProducts = $products;
  8612. if (is_string($decodedProducts)) {
  8613. $decodedProducts = json_decode($decodedProducts, true);
  8614. if (json_last_error() !== JSON_ERROR_NONE) {
  8615. Utils::throwError('20003:产品数据格式错误');
  8616. }
  8617. }
  8618. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8619. Utils::throwError('20003:产品数据不能为空');
  8620. }
  8621. Utils::throwError('20003:没有有效的产品数据');
  8622. }
  8623. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8624. $products = [];
  8625. foreach ($newRows as $newRow) {
  8626. if (!isset($products[$newRow['type']])) {
  8627. $products[$newRow['type']] = [
  8628. 'type' => $newRow['type'],
  8629. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8630. ];
  8631. }
  8632. $products[$newRow['type']]['content'][] = [
  8633. $newRow['product_name'],
  8634. implode(',', $newRow['episode_numbers']),
  8635. $newRow['pic_prompt'],
  8636. ];
  8637. }
  8638. $products = array_values($products);
  8639. // 以下是原有的创建逻辑...
  8640. // 开启事务
  8641. DB::beginTransaction();
  8642. try {
  8643. $now = now();
  8644. $mappingRecords = [];
  8645. $createdProductIds = []; // 记录所有创建的资产ID
  8646. // 获取剧本名称
  8647. $script_name = $script->script_name ?? 'script_' . $script_id;
  8648. // 存储每个类型的根文件夹ID
  8649. $typeFolderIds = [];
  8650. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8651. foreach ($products as $productGroup) {
  8652. $type = getProp($productGroup, 'type');
  8653. $title = getProp($productGroup, 'title', '');
  8654. $content = getProp($productGroup, 'content', []);
  8655. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8656. continue;
  8657. }
  8658. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8659. if (!isset($typeFolderIds[$type])) {
  8660. $folder = DB::table('mp_products')
  8661. ->where('cpid', $cpid)
  8662. ->where('type', 2)
  8663. ->where('product', $type)
  8664. ->where('product_name', $script_name)
  8665. ->where('parent_id', 0)
  8666. ->where('is_deleted', 0)
  8667. ->first();
  8668. if ($folder) {
  8669. $typeFolderIds[$type] = $folder->id;
  8670. } else {
  8671. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8672. 'user_id' => $uid,
  8673. 'cpid' => $cpid,
  8674. 'type' => 2, // 1.资产 2文件夹
  8675. 'product' => $type, // 1.主体 2.场景 3.道具
  8676. 'parent_id' => 0, // 根文件夹,parent_id=0
  8677. 'level' => 1, // 第一层级
  8678. 'product_name' => $script_name,
  8679. 'sort_order' => time() + $type,
  8680. 'is_deleted' => 0,
  8681. 'created_at' => $now,
  8682. 'updated_at' => $now
  8683. ]);
  8684. }
  8685. }
  8686. $folder_id = $typeFolderIds[$type];
  8687. // 获取表头(第一行)并查找关键列的位置
  8688. $headers = $content[0];
  8689. $nameColumnIndex = -1; // 资产名称列索引
  8690. $sequenceColumnIndex = -1; // 使用范围列索引
  8691. $promptColumnIndex = -1; // 参考提示词列索引
  8692. foreach ($headers as $index => $header) {
  8693. // 查找"资产名称"列
  8694. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8695. $nameColumnIndex = $index;
  8696. }
  8697. // 查找"使用范围"列
  8698. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8699. $sequenceColumnIndex = $index;
  8700. }
  8701. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8702. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8703. $promptColumnIndex = $index;
  8704. }
  8705. }
  8706. // 验证必要的列是否都找到了
  8707. if ($nameColumnIndex === -1) {
  8708. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8709. continue;
  8710. }
  8711. if ($sequenceColumnIndex === -1) {
  8712. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8713. continue;
  8714. }
  8715. // 跳过表头,解析每一行数据
  8716. for ($i = 1; $i < count($content); $i++) {
  8717. $row = $content[$i];
  8718. // 确保行数据有效
  8719. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8720. continue;
  8721. }
  8722. // 根据动态查找的列索引提取数据
  8723. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8724. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8725. $pic_prompt = '';
  8726. // 提取参考提示词(如果找到了该列)
  8727. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8728. $pic_prompt = trim($row[$promptColumnIndex]);
  8729. }
  8730. // 解析使用范围(逗号分隔的序号)
  8731. $sequences = [];
  8732. if (!empty($sequence_str)) {
  8733. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8734. foreach ($sequenceParts as $part) {
  8735. if (is_numeric($part)) {
  8736. $sequences[] = (int)$part;
  8737. }
  8738. }
  8739. }
  8740. if (empty($product_name)) {
  8741. continue;
  8742. }
  8743. // 处理product_name两边的符号
  8744. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8745. // 如果名称不存在或仅剩占位符号,则跳过
  8746. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8747. dLog('anime')->warning('资产名称无效,跳过保存', [
  8748. 'script_id' => $script_id,
  8749. 'type' => $type,
  8750. 'product_name' => $product_name
  8751. ]);
  8752. continue;
  8753. }
  8754. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8755. $product_id = DB::table('mp_products')->insertGetId([
  8756. 'product_name' => $product_name,
  8757. 'type' => 1, // 1=资产 2.文件夹
  8758. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8759. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8760. 'level' => 2, // 第二层级
  8761. 'pic_prompt' => $pic_prompt,
  8762. 'user_id' => $uid,
  8763. 'cpid' => $cpid,
  8764. 'sort_order' => time(),
  8765. 'is_deleted' => 0,
  8766. 'created_at' => $now,
  8767. 'updated_at' => $now,
  8768. ]);
  8769. // 记录创建的资产ID
  8770. $createdProductIds[] = $product_id;
  8771. // 为每个序号创建映射记录
  8772. if (!empty($sequences)) {
  8773. foreach ($sequences as $sequence) {
  8774. $mappingRecords[] = [
  8775. 'script_id' => $script_id,
  8776. 'product_id' => $product_id,
  8777. 'episode_number' => $sequence,
  8778. 'created_at' => $now,
  8779. 'updated_at' => $now,
  8780. ];
  8781. }
  8782. } else {
  8783. // 如果没有指定序号,创建一个默认映射(序号为0)
  8784. $mappingRecords[] = [
  8785. 'script_id' => $script_id,
  8786. 'product_id' => $product_id,
  8787. 'episode_number' => 0,
  8788. 'created_at' => $now,
  8789. 'updated_at' => $now,
  8790. ];
  8791. }
  8792. }
  8793. }
  8794. if (empty($mappingRecords)) {
  8795. Utils::throwError('20003:没有有效的产品数据');
  8796. }
  8797. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8798. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8799. // 剧本已有资产,同步更新is_products标记
  8800. DB::table('mp_scripts')->where('id', $script_id)->update([
  8801. 'is_products' => 1,
  8802. 'updated_at' => $now
  8803. ]);
  8804. // 如果需要自动生成图片,在事务中创建图片生成任务
  8805. $productTaskMap = [];
  8806. if ($auto_generate_images && !empty($createdProductIds)) {
  8807. // 查询所有创建的资产
  8808. $productsToGenerate = DB::table('mp_products')
  8809. ->whereIn('id', $createdProductIds)
  8810. ->where('is_deleted', 0)
  8811. ->get();
  8812. foreach ($productsToGenerate as $product) {
  8813. if (empty($product->pic_prompt)) {
  8814. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8815. 'product_id' => $product->id,
  8816. 'product_name' => $product->product_name
  8817. ]);
  8818. continue;
  8819. }
  8820. try {
  8821. // 创建图片生成任务
  8822. $params = [
  8823. 'prompt' => $product->pic_prompt,
  8824. 'model' => $model,
  8825. 'ref_img_urls' => [],
  8826. 'width' => $width,
  8827. 'height' => $height,
  8828. // 计费锚点(剧本),用于积分明细归属统计
  8829. 'script_id' => $script_id,
  8830. ];
  8831. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8832. $task_id = $task->id;
  8833. if ($task_id) {
  8834. $productTaskMap[$product->id] = $task_id;
  8835. // 在事务中更新资产表的任务ID和状态
  8836. DB::table('mp_products')
  8837. ->where('id', $product->id)
  8838. ->update([
  8839. 'pic_task_id' => $task_id,
  8840. 'pic_task_status' => '生成中',
  8841. 'updated_at' => now()
  8842. ]);
  8843. dLog('anime')->info('创建资产图片生成任务', [
  8844. 'product_id' => $product->id,
  8845. 'task_id' => $task_id
  8846. ]);
  8847. }
  8848. } catch (\Exception $e) {
  8849. dLog('anime')->error('创建资产图片生成任务失败', [
  8850. 'product_id' => $product->id,
  8851. 'error' => $e->getMessage()
  8852. ]);
  8853. // 标记为失败(仍在事务中)
  8854. DB::table('mp_products')
  8855. ->where('id', $product->id)
  8856. ->update([
  8857. 'pic_task_status' => '生成失败',
  8858. 'updated_at' => now()
  8859. ]);
  8860. }
  8861. }
  8862. }
  8863. // 提交事务
  8864. DB::commit();
  8865. // 本次新增资产创建的图片任务
  8866. $createdTaskMap = $productTaskMap;
  8867. } catch (\Exception $e) {
  8868. // 回滚事务
  8869. DB::rollback();
  8870. // 更新任务中心状态为失败
  8871. if (!empty($taskCenterId)) {
  8872. $this->taskCenterService->updateTask($taskCenterId, [
  8873. 'status' => MpTaskCenter::STATUS_FAILED,
  8874. 'error_message' => $e->getMessage()
  8875. ]);
  8876. }
  8877. // 记录错误日志
  8878. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8879. 'script_id' => $script_id,
  8880. 'error' => $e->getMessage(),
  8881. 'trace' => $e->getTraceAsString()
  8882. ]);
  8883. // 统一使用 Utils::throwError 抛出错误
  8884. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8885. }
  8886. // 落库成功后统一处理图片任务:
  8887. // 1) 本次新增资产的图片任务已在上方事务中创建
  8888. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8889. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8890. $script_id,
  8891. $model,
  8892. $width,
  8893. $height,
  8894. $auto_generate_images
  8895. );
  8896. $productTaskMap = $existingTaskInfo['product_task_map'];
  8897. // 创建阶段解析到的类型根文件夹优先
  8898. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8899. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8900. $resultData = [
  8901. 'success' => true,
  8902. 'message' => '保存完成',
  8903. 'script_id' => $script_id,
  8904. 'script_name' => $script_name,
  8905. 'type_folder_ids' => $typeFolderIds,
  8906. 'inserted_count' => $insertedCount,
  8907. 'total_records' => count($mappingRecords),
  8908. 'created_products' => count($createdProductIds),
  8909. 'pending_tasks_count' => count($productTaskMap),
  8910. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8911. 'task_center_id' => $taskCenterId,
  8912. ];
  8913. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8914. if ($auto_generate_images && !empty($productTaskMap)) {
  8915. return $this->pollProductImageTasks(
  8916. $script_id,
  8917. $script_name,
  8918. $productTaskMap,
  8919. $typeFolderIds,
  8920. $taskCenterId,
  8921. ['import_result' => $resultData],
  8922. ['import_result' => $resultData]
  8923. );
  8924. }
  8925. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8926. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8927. }
  8928. /**
  8929. * 根据入参创建或复用任务中心记录
  8930. *
  8931. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8932. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8933. * 避免生成重复任务。
  8934. *
  8935. * @param int|string $uid
  8936. * @param int|string $cpid
  8937. * @param int|string $script_id
  8938. * @param mixed $products
  8939. * @param string $model
  8940. * @param string $ratio
  8941. * @param string $resolution
  8942. * @param mixed $auto_generate_images
  8943. * @return int 任务中心ID
  8944. */
  8945. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8946. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8947. if (is_string($products)) {
  8948. $decoded = json_decode($products, true);
  8949. if (json_last_error() === JSON_ERROR_NONE) {
  8950. $products = $decoded;
  8951. }
  8952. }
  8953. $params = [
  8954. 'script_id' => (int)$script_id,
  8955. 'products' => $products,
  8956. 'model' => $model,
  8957. 'ratio' => $ratio,
  8958. 'resolution' => $resolution,
  8959. 'auto_generate_images' => (bool)$auto_generate_images,
  8960. ];
  8961. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  8962. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  8963. $existing = DB::table('mp_task_center')
  8964. ->where('uid', (int)$uid)
  8965. ->where('cpid', (int)$cpid)
  8966. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8967. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8968. ->where('params_md5', $paramsMd5)
  8969. ->orderBy('id', 'desc')
  8970. ->first();
  8971. if ($existing) {
  8972. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  8973. 'script_id' => $script_id,
  8974. 'task_center_id' => $existing->id,
  8975. 'params_md5' => $paramsMd5,
  8976. ]);
  8977. return (int)$existing->id;
  8978. }
  8979. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  8980. $now = date('Y-m-d H:i:s');
  8981. DB::table('mp_task_center')->insertOrIgnore([
  8982. 'uid' => (int)$uid,
  8983. 'cpid' => (int)$cpid,
  8984. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  8985. 'title' => '剧本资产图片生成',
  8986. 'ref_task_id' => 0,
  8987. 'status' => MpTaskCenter::STATUS_PROCESSING,
  8988. 'result' => null,
  8989. 'error_message' => null,
  8990. 'prompt' => null,
  8991. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  8992. 'params_md5' => $paramsMd5,
  8993. 'created_at' => $now,
  8994. 'updated_at' => $now,
  8995. ]);
  8996. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  8997. $taskId = (int)DB::table('mp_task_center')
  8998. ->where('uid', (int)$uid)
  8999. ->where('cpid', (int)$cpid)
  9000. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9001. ->where('params_md5', $paramsMd5)
  9002. ->orderBy('id', 'desc')
  9003. ->value('id');
  9004. dLog('anime')->info('创建任务中心记录', [
  9005. 'script_id' => $script_id,
  9006. 'task_center_id' => $taskId,
  9007. 'params_md5' => $paramsMd5,
  9008. ]);
  9009. return $taskId;
  9010. }
  9011. /**
  9012. * 任务结束时更新任务中心记录的状态和结果
  9013. *
  9014. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  9015. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  9016. *
  9017. * @param int|null $taskCenterId
  9018. * @param array $resultData 接口返回结果数组
  9019. * @param bool $timeout 是否超时未完成
  9020. */
  9021. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  9022. if (!$taskCenterId) {
  9023. return;
  9024. }
  9025. $stats = $resultData['stats'] ?? [];
  9026. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  9027. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  9028. $failedCount = $completedCount - $successCount;
  9029. // 与接口返回给客户端的结果保持一致
  9030. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  9031. if ($timeout) {
  9032. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9033. 'status' => MpTaskCenter::STATUS_FAILED,
  9034. 'result' => $result,
  9035. 'error_message' => '部分任务超时,请稍后查看结果',
  9036. ]);
  9037. return;
  9038. }
  9039. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9040. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  9041. 'result' => $result,
  9042. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  9043. ]);
  9044. }
  9045. /**
  9046. * 批量为剧本资产生成图片
  9047. *
  9048. * @param array $data 请求参数
  9049. * @return \Generator 返回 SSE 流
  9050. */
  9051. public function batchGenerateProductImages($data) {
  9052. $script_id = getProp($data, 'script_id');
  9053. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  9054. if (!$script_id) {
  9055. Utils::throwError('20003:请提供剧本ID');
  9056. }
  9057. // 验证剧本是否存在
  9058. $script = DB::table('mp_scripts')
  9059. ->where('id', $script_id)
  9060. ->where('is_deleted', 0)
  9061. ->first();
  9062. if (!$script) {
  9063. Utils::throwError('20003:剧本不存在');
  9064. }
  9065. $script_name = $script->script_name ?? 'script_' . $script_id;
  9066. // 获取需要生成图片的所有资产
  9067. $products = DB::table('mp_products')
  9068. ->whereIn('parent_id', array_values($type_folder_ids))
  9069. ->where('is_deleted', 0)
  9070. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  9071. ->get();
  9072. if ($products->isEmpty()) {
  9073. Utils::throwError('20003:没有找到需要生成图片的资产');
  9074. }
  9075. // 默认参数
  9076. $model = 'gpt-image-2';
  9077. $width = 1600;
  9078. $height = 2848;
  9079. // 开始为每个资产创建图片生成任务
  9080. $taskIds = [];
  9081. $productTaskMap = []; // 资产ID到任务ID的映射
  9082. foreach ($products as $product) {
  9083. if (empty($product->pic_prompt)) {
  9084. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  9085. continue;
  9086. }
  9087. try {
  9088. // 创建图片生成任务
  9089. $params = [
  9090. 'prompt' => $product->pic_prompt,
  9091. 'model' => $model,
  9092. 'ref_img_urls' => [],
  9093. 'width' => $width,
  9094. 'height' => $height,
  9095. // 计费锚点(剧本),用于积分明细归属统计
  9096. 'script_id' => $script_id,
  9097. ];
  9098. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9099. $task_id = $task->id;
  9100. if ($task_id) {
  9101. $taskIds[] = $task_id;
  9102. $productTaskMap[$product->id] = $task_id;
  9103. // 更新资产表的任务ID和状态
  9104. DB::table('mp_products')
  9105. ->where('id', $product->id)
  9106. ->update([
  9107. 'pic_task_id' => $task_id,
  9108. 'pic_task_status' => '生成中',
  9109. 'updated_at' => now()
  9110. ]);
  9111. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9112. }
  9113. } catch (\Exception $e) {
  9114. dLog('anime')->error('创建资产图片生成任务失败', [
  9115. 'product_id' => $product->id,
  9116. 'error' => $e->getMessage()
  9117. ]);
  9118. // 标记为失败
  9119. DB::table('mp_products')
  9120. ->where('id', $product->id)
  9121. ->update([
  9122. 'pic_task_status' => '生成失败',
  9123. 'updated_at' => now()
  9124. ]);
  9125. }
  9126. }
  9127. if (empty($taskIds)) {
  9128. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9129. }
  9130. // 返回 SSE 流
  9131. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9132. }
  9133. /**
  9134. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9135. *
  9136. * @param int $script_id
  9137. * @param string $script_name
  9138. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9139. * @param array $type_folder_ids
  9140. * @param int|null $taskCenterId
  9141. * @return \Generator
  9142. */
  9143. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9144. if ($taskCenterId) {
  9145. $initResponse = [
  9146. 'type' => 'init',
  9147. 'script_id' => $script_id,
  9148. 'script_name' => $script_name,
  9149. 'timestamp' => date('Y-m-d H:i:s'),
  9150. 'task_center_id' => (int)$taskCenterId,
  9151. 'import_result' => $resultData,
  9152. ];
  9153. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9154. }
  9155. $stats = $this->collectScriptProductStats($script_id);
  9156. $response = [
  9157. 'type' => 'complete',
  9158. 'script_id' => $script_id,
  9159. 'script_name' => $script_name,
  9160. 'stats' => $stats,
  9161. 'timestamp' => date('Y-m-d H:i:s'),
  9162. 'import_result' => $resultData,
  9163. ];
  9164. if ($taskCenterId) {
  9165. $response['task_center_id'] = (int)$taskCenterId;
  9166. }
  9167. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9168. // 更新任务中心状态和结果
  9169. $this->finishScriptProductTask($taskCenterId, $response);
  9170. }
  9171. /**
  9172. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9173. *
  9174. * @param int $script_id
  9175. * @return array
  9176. */
  9177. private function collectScriptProductStats($script_id) {
  9178. $stats = [
  9179. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9180. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9181. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9182. ];
  9183. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9184. $productIds = DB::table('mp_script_product_mappings')
  9185. ->where('script_id', $script_id)
  9186. ->pluck('product_id')
  9187. ->unique()
  9188. ->toArray();
  9189. if (empty($productIds)) {
  9190. return [];
  9191. }
  9192. $products = DB::table('mp_products')
  9193. ->whereIn('id', $productIds)
  9194. ->where('is_deleted', 0)
  9195. ->get();
  9196. foreach ($products as $product) {
  9197. $typeName = $typeNames[$product->product] ?? 'unknown';
  9198. if (!isset($stats[$typeName])) {
  9199. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9200. }
  9201. $stats[$typeName]['total']++;
  9202. if ($product->pic_task_status === '生成成功') {
  9203. $stats[$typeName]['success']++;
  9204. $stats[$typeName]['completed']++;
  9205. } elseif ($product->pic_task_status === '生成失败') {
  9206. $stats[$typeName]['completed']++;
  9207. }
  9208. }
  9209. foreach ($stats as $typeName => $stat) {
  9210. if ($stat['total'] === 0) {
  9211. unset($stats[$typeName]);
  9212. }
  9213. }
  9214. return $stats;
  9215. }
  9216. /**
  9217. * 轮询资产图片生成任务状态(SSE流式返回)
  9218. * 只通过查询数据库获取任务状态,不主动调用API
  9219. *
  9220. * @param int $script_id 剧本ID
  9221. * @param string $script_name 剧本名称
  9222. * @param array $productTaskMap 资产ID到任务ID的映射
  9223. * @param array $type_folder_ids 类型文件夹ID映射
  9224. * @param int|null $taskCenterId 任务中心ID
  9225. * @param array $initExtra 追加到 init 事件中的额外数据
  9226. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9227. * @return \Generator
  9228. */
  9229. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9230. $startTime = time();
  9231. $timeout = 1800; // 30分钟超时
  9232. $pollInterval = 10; // 10秒轮询一次
  9233. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9234. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9235. if ($taskCenterId) {
  9236. $initResponse = array_merge([
  9237. 'type' => 'init',
  9238. 'script_id' => $script_id,
  9239. 'script_name' => $script_name,
  9240. 'timestamp' => date('Y-m-d H:i:s'),
  9241. 'task_center_id' => (int)$taskCenterId,
  9242. ], $initExtra);
  9243. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9244. }
  9245. // 定义类型名称映射
  9246. $typeNames = [
  9247. 1 => 'roles', // 角色
  9248. 2 => 'scenes', // 场景
  9249. 3 => 'props' // 道具
  9250. ];
  9251. while (time() - $startTime < $timeout) {
  9252. sleep($pollInterval);
  9253. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9254. $mappings = DB::table('mp_script_product_mappings')
  9255. ->where('script_id', $script_id)
  9256. ->pluck('product_id')
  9257. ->unique()
  9258. ->toArray();
  9259. if (empty($mappings)) {
  9260. dLog('anime')->warning('该剧本没有关联的资产', [
  9261. 'script_id' => $script_id,
  9262. 'script_name' => $script_name
  9263. ]);
  9264. break;
  9265. }
  9266. // 查询所有资产的当前状态
  9267. $products = DB::table('mp_products')
  9268. ->whereIn('id', $mappings)
  9269. ->where('is_deleted', 0)
  9270. ->get();
  9271. // 统计各类型的状态(使用类型名称作为键名)
  9272. $stats = [
  9273. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9274. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9275. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9276. ];
  9277. $allCompleted = true;
  9278. $hasStatusChange = false;
  9279. foreach ($products as $product) {
  9280. $type = $product->product;
  9281. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9282. // 如果类型名称不在 stats 中,初始化
  9283. if (!isset($stats[$typeName])) {
  9284. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9285. }
  9286. $stats[$typeName]['total']++;
  9287. $task_id = $product->pic_task_id;
  9288. $currentStatus = $product->pic_task_status;
  9289. // 检查状态是否有变化
  9290. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9291. $hasStatusChange = true;
  9292. $lastStatus[$product->id] = $currentStatus;
  9293. }
  9294. // 如果是生成中,查询任务表状态
  9295. if ($currentStatus === '生成中' && $task_id) {
  9296. // 只查询数据库,不调用API
  9297. $task = DB::table('mp_generate_pic_tasks')
  9298. ->where('id', $task_id)
  9299. ->first();
  9300. if ($task) {
  9301. // 检查任务状态
  9302. if ($task->status === 'success' && $task->result_url) {
  9303. // 解析图片URL
  9304. $result_urls = $task->result_url;
  9305. if (is_string($result_urls)) {
  9306. $result_urls = json_decode($result_urls, true);
  9307. }
  9308. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9309. // 更新资产表状态
  9310. DB::table('mp_products')
  9311. ->where('id', $product->id)
  9312. ->update([
  9313. 'pic_task_status' => '生成成功',
  9314. 'url' => $img_url,
  9315. 'updated_at' => now()
  9316. ]);
  9317. $stats[$typeName]['success']++;
  9318. $stats[$typeName]['completed']++;
  9319. $hasStatusChange = true;
  9320. dLog('anime')->info('资产图片生成成功', [
  9321. 'product_id' => $product->id,
  9322. 'task_id' => $task_id,
  9323. 'img_url' => $img_url
  9324. ]);
  9325. } elseif ($task->status === 'failed') {
  9326. // 更新资产表状态
  9327. DB::table('mp_products')
  9328. ->where('id', $product->id)
  9329. ->update([
  9330. 'pic_task_status' => '生成失败',
  9331. 'updated_at' => now()
  9332. ]);
  9333. $stats[$typeName]['completed']++;
  9334. $hasStatusChange = true;
  9335. dLog('anime')->warning('资产图片生成失败', [
  9336. 'product_id' => $product->id,
  9337. 'task_id' => $task_id,
  9338. 'error' => $task->error_message ?? '未知错误'
  9339. ]);
  9340. } else {
  9341. // 任务还在处理中
  9342. $allCompleted = false;
  9343. }
  9344. } else {
  9345. // 任务不存在,标记为失败
  9346. DB::table('mp_products')
  9347. ->where('id', $product->id)
  9348. ->update([
  9349. 'pic_task_status' => '生成失败',
  9350. 'updated_at' => now()
  9351. ]);
  9352. $stats[$typeName]['completed']++;
  9353. $hasStatusChange = true;
  9354. dLog('anime')->error('图片生成任务不存在', [
  9355. 'product_id' => $product->id,
  9356. 'task_id' => $task_id
  9357. ]);
  9358. }
  9359. } elseif ($currentStatus === '生成成功') {
  9360. $stats[$typeName]['success']++;
  9361. $stats[$typeName]['completed']++;
  9362. } elseif ($currentStatus === '生成失败') {
  9363. $stats[$typeName]['completed']++;
  9364. } else {
  9365. // 其他状态也认为未完成
  9366. $allCompleted = false;
  9367. }
  9368. }
  9369. // 移除没有数据的类型(total=0)
  9370. foreach ($stats as $typeName => $stat) {
  9371. if ($stat['total'] === 0) {
  9372. unset($stats[$typeName]);
  9373. }
  9374. }
  9375. // 如果有状态变化,发送 SSE 更新
  9376. if ($hasStatusChange) {
  9377. $eventType = $allCompleted ? 'complete' : 'update';
  9378. $response = [
  9379. 'type' => $eventType,
  9380. 'script_id' => $script_id,
  9381. 'script_name' => $script_name,
  9382. 'stats' => $stats,
  9383. 'timestamp' => date('Y-m-d H:i:s')
  9384. ];
  9385. if ($taskCenterId) {
  9386. $response['task_center_id'] = $taskCenterId;
  9387. }
  9388. if ($eventType === 'complete') {
  9389. $response = array_merge($response, $completeExtra);
  9390. }
  9391. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9392. dLog('anime')->info('SSE更新', [
  9393. 'event_type' => $eventType,
  9394. 'script_id' => $script_id,
  9395. 'script_name' => $script_name,
  9396. 'stats' => $stats
  9397. ]);
  9398. if ($allCompleted) {
  9399. dLog('anime')->info('所有资产图片生成任务已完成', [
  9400. 'script_id' => $script_id,
  9401. 'script_name' => $script_name,
  9402. 'stats' => $stats
  9403. ]);
  9404. // 全部任务完成,更新任务中心状态和结果
  9405. $this->finishScriptProductTask($taskCenterId, $response);
  9406. break;
  9407. }
  9408. }
  9409. }
  9410. // 超时处理
  9411. if (time() - $startTime >= $timeout && !$allCompleted) {
  9412. $response = [
  9413. 'type' => 'timeout',
  9414. 'message' => '部分任务超时,请稍后查看结果',
  9415. 'script_id' => $script_id,
  9416. 'script_name' => $script_name,
  9417. 'timestamp' => date('Y-m-d H:i:s')
  9418. ];
  9419. if ($taskCenterId) {
  9420. $response['task_center_id'] = $taskCenterId;
  9421. }
  9422. $response = array_merge($response, $completeExtra);
  9423. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9424. dLog('anime')->warning('资产图片生成任务超时', [
  9425. 'script_id' => $script_id,
  9426. 'script_name' => $script_name,
  9427. 'timeout' => $timeout
  9428. ]);
  9429. // 超时未完成,更新任务中心状态和结果
  9430. $this->finishScriptProductTask($taskCenterId, $response, true);
  9431. }
  9432. }
  9433. /**
  9434. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9435. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9436. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9437. *
  9438. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9439. */
  9440. public function checkProductPicTasks() {
  9441. // 查询所有生成中的产品图片任务
  9442. $products = DB::table('mp_products')
  9443. ->whereNotNull('pic_task_id')
  9444. ->where('pic_task_status', '生成中')
  9445. ->where('is_deleted', 0)
  9446. ->get();
  9447. $stats = [
  9448. 'total' => $products->count(),
  9449. 'success' => 0,
  9450. 'failed' => 0,
  9451. 'pending' => 0,
  9452. ];
  9453. foreach ($products as $product) {
  9454. try {
  9455. $task_id = $product->pic_task_id;
  9456. // 通过 pic_task_id 查询图片生成任务结果
  9457. $task = DB::table('mp_generate_pic_tasks')
  9458. ->where('id', $task_id)
  9459. ->first();
  9460. if ($task) {
  9461. if ($task->status === 'success' && $task->result_url) {
  9462. // 解析图片URL
  9463. $result_urls = $task->result_url;
  9464. if (is_string($result_urls)) {
  9465. $result_urls = json_decode($result_urls, true);
  9466. }
  9467. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9468. // 更新资产表状态
  9469. DB::table('mp_products')
  9470. ->where('id', $product->id)
  9471. ->update([
  9472. 'pic_task_status' => '生成成功',
  9473. 'url' => $img_url,
  9474. 'updated_at' => now()
  9475. ]);
  9476. $stats['success']++;
  9477. dLog('anime')->info('资产图片生成成功', [
  9478. 'product_id' => $product->id,
  9479. 'task_id' => $task_id,
  9480. 'img_url' => $img_url
  9481. ]);
  9482. } elseif ($task->status === 'failed') {
  9483. // 更新资产表状态
  9484. DB::table('mp_products')
  9485. ->where('id', $product->id)
  9486. ->update([
  9487. 'pic_task_status' => '生成失败',
  9488. 'updated_at' => now()
  9489. ]);
  9490. $stats['failed']++;
  9491. dLog('anime')->warning('资产图片生成失败', [
  9492. 'product_id' => $product->id,
  9493. 'task_id' => $task_id,
  9494. 'error' => $task->error_message ?? '未知错误'
  9495. ]);
  9496. } else {
  9497. // 任务还在处理中
  9498. $stats['pending']++;
  9499. }
  9500. } else {
  9501. // 任务不存在,标记为失败
  9502. DB::table('mp_products')
  9503. ->where('id', $product->id)
  9504. ->update([
  9505. 'pic_task_status' => '生成失败',
  9506. 'updated_at' => now()
  9507. ]);
  9508. $stats['failed']++;
  9509. dLog('anime')->error('图片生成任务不存在', [
  9510. 'product_id' => $product->id,
  9511. 'task_id' => $task_id
  9512. ]);
  9513. }
  9514. } catch (\Exception $e) {
  9515. dLog('anime')->error('检查产品图片生成任务异常', [
  9516. 'product_id' => $product->id,
  9517. 'task_id' => $product->pic_task_id ?? null,
  9518. 'error' => $e->getMessage()
  9519. ]);
  9520. }
  9521. }
  9522. return $stats;
  9523. }
  9524. /**
  9525. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9526. *
  9527. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9528. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9529. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9530. *
  9531. * @return int 更新的任务中心记录数
  9532. */
  9533. public function checkSaveScriptProductTaskCenters() {
  9534. $updated = 0;
  9535. // 只扫描尚未结束的 saveScriptProducts 任务
  9536. $tasks = DB::table('mp_task_center')
  9537. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9538. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9539. ->orderBy('id', 'desc')
  9540. ->limit(500)
  9541. ->get();
  9542. // 与 pollProductImageTasks 保持一致的类型名称映射
  9543. $typeNames = [
  9544. 1 => 'roles', // 角色
  9545. 2 => 'scenes', // 场景
  9546. 3 => 'props', // 道具
  9547. ];
  9548. foreach ($tasks as $task) {
  9549. try {
  9550. $taskParams = json_decode((string)$task->params, true);
  9551. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9552. if (!$script_id) {
  9553. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9554. 'task_center_id' => $task->id,
  9555. ]);
  9556. continue;
  9557. }
  9558. // 获取该剧本关联的全部资产ID
  9559. $productIds = DB::table('mp_script_product_mappings')
  9560. ->where('script_id', $script_id)
  9561. ->pluck('product_id')
  9562. ->unique()
  9563. ->toArray();
  9564. if (empty($productIds)) {
  9565. // 剧本没有关联资产,不视为完成,等待下一次检查
  9566. continue;
  9567. }
  9568. $products = DB::table('mp_products')
  9569. ->whereIn('id', $productIds)
  9570. ->where('is_deleted', 0)
  9571. ->get();
  9572. $stats = [];
  9573. $allCompleted = true;
  9574. foreach ($products as $product) {
  9575. $typeName = $typeNames[$product->product] ?? 'unknown';
  9576. if (!isset($stats[$typeName])) {
  9577. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9578. }
  9579. $stats[$typeName]['total']++;
  9580. if ($product->pic_task_status === '生成成功') {
  9581. $stats[$typeName]['success']++;
  9582. $stats[$typeName]['completed']++;
  9583. } elseif ($product->pic_task_status === '生成失败') {
  9584. $stats[$typeName]['completed']++;
  9585. } else {
  9586. // 仍有资产在生成中或未生成,任务未完成
  9587. $allCompleted = false;
  9588. }
  9589. }
  9590. if (!$allCompleted) {
  9591. continue;
  9592. }
  9593. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9594. $script = DB::table('mp_scripts')
  9595. ->where('id', $script_id)
  9596. ->where('is_deleted', 0)
  9597. ->first();
  9598. $script_name = $script->script_name ?? 'script_' . $script_id;
  9599. $this->finishScriptProductTask($task->id, [
  9600. 'type' => 'complete',
  9601. 'script_id' => $script_id,
  9602. 'script_name' => $script_name,
  9603. 'stats' => $stats,
  9604. 'timestamp' => date('Y-m-d H:i:s'),
  9605. 'task_center_id' => (int)$task->id,
  9606. ]);
  9607. $updated++;
  9608. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9609. 'task_center_id' => $task->id,
  9610. 'script_id' => $script_id,
  9611. 'stats' => $stats,
  9612. ]);
  9613. } catch (\Exception $e) {
  9614. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9615. 'task_center_id' => $task->id,
  9616. 'error' => $e->getMessage(),
  9617. ]);
  9618. }
  9619. }
  9620. return $updated;
  9621. }
  9622. /**
  9623. * 获取剧本关联的资产列表
  9624. * @param array $data 请求参数
  9625. * @return array
  9626. */
  9627. public function getScriptProducts($data) {
  9628. $uid = Site::getUid();
  9629. $cpid = Site::getCpid();
  9630. $script_id = getProp($data, 'script_id');
  9631. $episode_number = getProp($data, 'episode_number');
  9632. if (!$script_id) {
  9633. Utils::throwError('20003:请提供剧本ID');
  9634. }
  9635. // 验证剧本是否存在
  9636. $script = DB::table('mp_scripts')
  9637. ->where('id', $script_id)
  9638. ->where('is_deleted', 0)
  9639. ->first();
  9640. if (!$script) {
  9641. Utils::throwError('20003:剧本不存在');
  9642. }
  9643. // 联表查询资产信息
  9644. $query = DB::table('mp_script_product_mappings as mapping')
  9645. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9646. ->where('mapping.script_id', $script_id)
  9647. ->where('product.cpid', $cpid)
  9648. ->where('product.is_deleted', 0);
  9649. // 如果提供了 episode_number,则过滤指定集数
  9650. if ($episode_number !== null && $episode_number !== '') {
  9651. $query->where('mapping.episode_number', $episode_number);
  9652. }
  9653. $mappings = $query->select(
  9654. 'mapping.script_id',
  9655. 'mapping.product_id',
  9656. 'mapping.episode_number',
  9657. 'product.product_name',
  9658. 'product.type',
  9659. 'product.product',
  9660. 'product.pic_prompt',
  9661. 'product.url',
  9662. 'product.pic_task_id',
  9663. 'product.pic_task_status',
  9664. 'product.three_view_image_url',
  9665. 'product.timbre_url',
  9666. 'mapping.created_at'
  9667. )
  9668. ->orderBy('mapping.product_id', 'asc')
  9669. ->orderBy('mapping.episode_number', 'asc')
  9670. ->get();
  9671. // 按 product_id 分组,合并 episode_number
  9672. $productMap = [];
  9673. foreach ($mappings as $item) {
  9674. $product_id = $item->product_id;
  9675. if (!isset($productMap[$product_id])) {
  9676. $productMap[$product_id] = [
  9677. 'product_id' => $product_id,
  9678. 'product_name' => $item->product_name,
  9679. 'type' => (int)$item->type,
  9680. 'product' => (int)$item->product,
  9681. 'pic_prompt' => $item->pic_prompt,
  9682. 'url' => $item->url,
  9683. 'timbre_url' => $item->timbre_url,
  9684. 'pic_task_id' => $item->pic_task_id,
  9685. 'pic_task_status' => $item->pic_task_status,
  9686. 'episode_numbers' => [],
  9687. 'created_at' => $item->created_at,
  9688. ];
  9689. }
  9690. // 添加 episode_number(去重)
  9691. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9692. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9693. }
  9694. }
  9695. // 按类型分组
  9696. $roles = []; // type=1 角色/主体
  9697. $scenes = []; // type=2 场景
  9698. $props = []; // type=3 道具
  9699. foreach ($productMap as $product) {
  9700. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9701. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9702. // 构造返回数据
  9703. $productData = [
  9704. 'product_id' => $product['product_id'],
  9705. 'product_name' => $product['product_name'],
  9706. 'product' => $product['product'],
  9707. 'pic_prompt' => $product['pic_prompt'],
  9708. 'url' => $product['url'],
  9709. 'timbre_url' => $product['timbre_url'] ?? '',
  9710. 'pic_task_id' => $product['pic_task_id'],
  9711. 'pic_task_status' => $product['pic_task_status'],
  9712. 'episode_numbers' => $episodeNumbersStr,
  9713. 'created_at' => $product['created_at'],
  9714. ];
  9715. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9716. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9717. switch ($product['product']) {
  9718. case 1:
  9719. $roles[] = $productData;
  9720. break;
  9721. case 2:
  9722. $scenes[] = $productData;
  9723. break;
  9724. case 3:
  9725. $props[] = $productData;
  9726. break;
  9727. }
  9728. }
  9729. return [
  9730. 'script_id' => $script_id,
  9731. 'script_name' => $script->script_name ?? '',
  9732. 'roles' => $roles, // 主体
  9733. 'scenes' => $scenes, // 场景
  9734. 'props' => $props, // 道具
  9735. ];
  9736. }
  9737. /**
  9738. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9739. * @param string $actContent 原始内容
  9740. * @param array $products 产品数组(包含product_name和url)
  9741. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9742. */
  9743. /**
  9744. * 根据片段内容与资产构建提示词、参考图、参考音频
  9745. *
  9746. * @param string $actContent 片段内容
  9747. * @param array $products 资产数组(角色/场景/道具)
  9748. * @param bool $supportAudioReference 模型是否支持参考音频;支持时角色音色优先使用 timbre_url
  9749. * @return array
  9750. */
  9751. public function processActContentWithProducts($actContent, $products, $supportAudioReference = false) {
  9752. if (empty($actContent) || empty($products)) {
  9753. return [
  9754. 'content' => $actContent,
  9755. 'reference_images' => [],
  9756. 'reference_audios' => [],
  9757. 'audio_voice_fallbacks' => []
  9758. ];
  9759. }
  9760. // 构建产品名称到产品信息的映射
  9761. $product_dict = [];
  9762. foreach ($products as $product) {
  9763. $product_name = getProp($product, 'product_name');
  9764. if ($product_name) {
  9765. $product_dict[$product_name] = [
  9766. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9767. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9768. 'voice_prompt' => getProp($product, 'voice_prompt'),
  9769. // 角色音色参考音频(选填),有值时优先于 voice_prompt
  9770. 'timbre_url' => trim((string)getProp($product, 'timbre_url', '')),
  9771. 'product' => (int)getProp($product, 'product', 1)
  9772. ];
  9773. }
  9774. }
  9775. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9776. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9777. $reference_images = [];
  9778. $product_index_map = []; // 产品名称 => 图片序号的映射
  9779. $reference_audios = [];
  9780. $product_audio_index_map = []; // 产品名称 => 音频序号的映射(与图片序号互相独立)
  9781. $audio_voice_fallbacks = []; // 产品名称 => voice_prompt(参考音频素材不可用时兜底使用)
  9782. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9783. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9784. $current_index = 1;
  9785. $current_audio_index = 1;
  9786. if (!empty($matches[1])) {
  9787. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9788. $seen_products = []; // 用于去重
  9789. foreach ($matches[1] as $product_name) {
  9790. // 跳过已处理的产品
  9791. if (isset($seen_products[$product_name])) {
  9792. continue;
  9793. }
  9794. $seen_products[$product_name] = true;
  9795. // 检查产品是否在字典中
  9796. if (isset($product_dict[$product_name])) {
  9797. $url = $product_dict[$product_name]['url'];
  9798. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9799. $timbre_url = $product_dict[$product_name]['timbre_url'];
  9800. // 分配音频序号(与图片序号互相独立;相同音频URL复用同一序号,保证角色与音频一一对应)
  9801. if ($supportAudioReference && !empty($timbre_url)) {
  9802. if (!in_array($timbre_url, $reference_audios)) {
  9803. $reference_audios[] = $timbre_url;
  9804. $product_audio_index_map[$product_name] = $current_audio_index;
  9805. $current_audio_index++;
  9806. } else {
  9807. $existing_audio_index = array_search($timbre_url, $reference_audios) + 1;
  9808. $product_audio_index_map[$product_name] = $existing_audio_index;
  9809. }
  9810. // 记录该角色的音色提示词:参考音频素材不可用时用它兜底(无提示词时记录空串,用于清理残留说明行)
  9811. $audio_voice_fallbacks[$product_name] = $voice_prompt ?? '';
  9812. }
  9813. // 处理voice_prompt:模型支持参考音频且角色有音频时优先使用音频,不再输出音色提示词(旁白是公共的在后面单独处理)
  9814. if ((!$supportAudioReference || empty($timbre_url)) && !empty($voice_prompt) && $product_name !== '旁白') {
  9815. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9816. }
  9817. // 只有URL非空才分配序号和添加到参考图片
  9818. if (!empty($url)) {
  9819. // 检查URL是否已经在reference_images中(去重)
  9820. if (!in_array($url, $reference_images)) {
  9821. $reference_images[] = $url;
  9822. $product_index_map[$product_name] = $current_index;
  9823. $current_index++;
  9824. } else {
  9825. // URL重复,找到已有的序号
  9826. $existing_index = array_search($url, $reference_images) + 1;
  9827. $product_index_map[$product_name] = $existing_index;
  9828. }
  9829. } else {
  9830. // URL为空,不分配序号(后续直接去掉{})
  9831. $product_index_map[$product_name] = 0;
  9832. }
  9833. } else {
  9834. // 产品不在字典中,不分配序号
  9835. $product_index_map[$product_name] = 0;
  9836. }
  9837. }
  9838. }
  9839. // 第二步:替换内容中的 {产品名称}
  9840. $processedContent = $actContent;
  9841. foreach ($product_index_map as $product_name => $index) {
  9842. $escaped_name = preg_quote($product_name, '/');
  9843. if ($index > 0) {
  9844. // 有图片,替换为:产品名称<图片X>
  9845. $replacement = $product_name . '<图片' . $index . '>';
  9846. } else {
  9847. // 无图片,只保留产品名称
  9848. $replacement = $product_name;
  9849. }
  9850. // 有参考音频的角色追加音频标记(如 角色A<图片1><音频1>),保证角色与音频一一对应
  9851. $audio_index = $product_audio_index_map[$product_name] ?? 0;
  9852. if ($audio_index > 0) {
  9853. $replacement .= '<音频' . $audio_index . '>';
  9854. }
  9855. // 替换所有 {产品名称} 为处理后的格式
  9856. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9857. }
  9858. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9859. foreach ($products as $product) {
  9860. $product_name = getProp($product, 'product_name');
  9861. $voice_prompt = getProp($product, 'voice_prompt');
  9862. if ($product_name === '旁白' && !empty($voice_prompt) && empty($product_audio_index_map['旁白'])) {
  9863. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9864. break; // 找到旁白后退出循环
  9865. }
  9866. }
  9867. // 第四步:将参考音频音色信息和voice_prompt信息添加到内容最前面
  9868. $voice_prompt_prefix = '';
  9869. // 有参考音频的角色:声明"角色名 对应 音频N",统一使用<音频N>标记,
  9870. // 素材上传失败时与正文标记一起被清理/重排,保证角色与音频始终对应
  9871. foreach ($product_audio_index_map as $product_name => $audio_index) {
  9872. $voice_prompt_prefix .= $product_name . ':全程使用<音频' . $audio_index . '>的音色进行配音' . "\n";
  9873. }
  9874. if (!empty($voice_prompts)) {
  9875. $voice_prompt_prefix .= implode('', $voice_prompts);
  9876. }
  9877. // 旁白的voice_prompt放在最后
  9878. if (!empty($narrator_voice_prompt)) {
  9879. $voice_prompt_prefix .= $narrator_voice_prompt;
  9880. }
  9881. // 如果有voice_prompt信息,添加到内容开头
  9882. if (!empty($voice_prompt_prefix)) {
  9883. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9884. }
  9885. return [
  9886. 'content' => $processedContent,
  9887. 'reference_images' => $reference_images,
  9888. 'reference_audios' => $reference_audios,
  9889. 'audio_voice_fallbacks' => $audio_voice_fallbacks
  9890. ];
  9891. }
  9892. /**
  9893. * 用剧本资产关联(mappings)的数据补齐资产数组
  9894. * 批量转视频时资产取值的优先级:剧本资产关联(mappings) > extra_products > 剧集单独设置
  9895. * 资产库对应字段为空时不覆盖,避免把分集里的有效数据清空
  9896. *
  9897. * @param array $products 资产数组
  9898. * @param int $script_id 剧本ID
  9899. * @param bool $overwrite 资产库有值时是否覆盖数组中的已有值(true 表示 mappings 优先级最高)
  9900. * @return array
  9901. */
  9902. public function fillProductsFromMapping($products, $script_id, $overwrite = false) {
  9903. if (empty($products) || !$script_id) {
  9904. return $products;
  9905. }
  9906. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9907. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9908. ->where('mapping.script_id', $script_id)
  9909. ->where('product.is_deleted', 0)
  9910. ->select(
  9911. 'mapping.product_id',
  9912. 'product.product_name',
  9913. 'product.product',
  9914. 'product.pic_prompt',
  9915. 'product.url',
  9916. 'product.three_view_image_url',
  9917. 'product.timbre_url'
  9918. )
  9919. ->get();
  9920. if ($mappingItems->isEmpty()) {
  9921. return $products;
  9922. }
  9923. $mappingMap = [];
  9924. foreach ($mappingItems as $item) {
  9925. $normalized_name = $this->normalizeProductName($item->product_name);
  9926. if ($normalized_name === '' || isset($mappingMap[$normalized_name])) {
  9927. continue;
  9928. }
  9929. // 资产库字段有值才纳入覆盖范围(三视图、音色等为选填,可能为空)
  9930. $mappingProduct = [];
  9931. if (!empty($item->product_id)) {
  9932. $mappingProduct['product_id'] = (int)$item->product_id;
  9933. }
  9934. if (!empty($item->product)) {
  9935. $mappingProduct['product'] = (int)$item->product;
  9936. }
  9937. if (!empty($item->pic_prompt)) {
  9938. $mappingProduct['pic_prompt'] = $item->pic_prompt;
  9939. }
  9940. if (!empty($item->url)) {
  9941. $mappingProduct['url'] = $item->url;
  9942. }
  9943. if (!empty($item->three_view_image_url)) {
  9944. $mappingProduct['three_view_image_url'] = $item->three_view_image_url;
  9945. }
  9946. if (!empty($item->timbre_url)) {
  9947. $mappingProduct['timbre_url'] = $item->timbre_url;
  9948. }
  9949. if (!empty($mappingProduct)) {
  9950. $mappingMap[$normalized_name] = $mappingProduct;
  9951. }
  9952. }
  9953. if (empty($mappingMap)) {
  9954. return $products;
  9955. }
  9956. foreach ($products as &$product) {
  9957. $normalized_name = $this->normalizeProductName(getProp($product, 'product_name'));
  9958. if ($normalized_name === '' || empty($mappingMap[$normalized_name])) {
  9959. continue;
  9960. }
  9961. foreach ($mappingMap[$normalized_name] as $key => $value) {
  9962. // 不覆盖模式:只补齐数组中缺失的字段
  9963. if (!$overwrite && !empty(getProp($product, $key))) {
  9964. continue;
  9965. }
  9966. $product[$key] = $value;
  9967. }
  9968. }
  9969. unset($product);
  9970. return $products;
  9971. }
  9972. /**
  9973. * 资产名称归一化(去掉首尾空白、方括号、花括号等符号)
  9974. *
  9975. * @param string $name
  9976. * @return string
  9977. */
  9978. private function normalizeProductName($name) {
  9979. return trim(preg_replace(
  9980. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  9981. '',
  9982. trim((string)$name)
  9983. ));
  9984. }
  9985. /**
  9986. * 判断视频模型是否支持角色参考音频(音色)
  9987. * 目前支持:智帧统一API、Seedance 2.0 系列(国内百度/海外百度/快快AI)
  9988. *
  9989. * @param string $model
  9990. * @return bool
  9991. */
  9992. public function isActReferenceAudioSupported($model) {
  9993. if (!$model) {
  9994. return false;
  9995. }
  9996. return strpos($model, 'zhizhen') !== false || $this->isSeedance20SeriesModel($model);
  9997. }
  9998. /**
  9999. * 将角色音色参考音频按模型分支上传为素材
  10000. * 上传失败时对应素材的<音频N>标记会从 $prompt 中清理(引用传递),与参考图处理保持一致
  10001. *
  10002. * @param array $referenceAudios 参考音频URL数组(顺序与<音频N>标记一一对应)
  10003. * @param string $model 视频模型
  10004. * @param string $prompt 完整提示词(引用传递)
  10005. * @return array 素材数组(asset://格式),非支持模型返回空数组
  10006. */
  10007. public function processActReferenceAudiosToAssets(array $referenceAudios, $model, &$prompt) {
  10008. if (empty($referenceAudios)) {
  10009. return [];
  10010. }
  10011. if (strpos($model, 'zhizhen') !== false) {
  10012. return $this->aiImageGenerationService->processReferenceAudiosToAssets($referenceAudios, $prompt);
  10013. }
  10014. if ($this->isSeedance20SeriesModel($model)) {
  10015. if ($this->isKuaikuaiSeedanceModel($model)) {
  10016. return $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($referenceAudios, $prompt);
  10017. }
  10018. if ($this->isOverseasBaiduSeedanceModel($model)) {
  10019. return $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($referenceAudios, $prompt);
  10020. }
  10021. return $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($referenceAudios, $prompt);
  10022. }
  10023. return [];
  10024. }
  10025. /**
  10026. * 参考音频素材上传失败时,用该角色原本的音色提示词兜底
  10027. * 说明行中的<音频N>标记被清理即代表该角色的音频素材不可用
  10028. *
  10029. * @param string $prompt 完整提示词
  10030. * @param array $audioVoiceFallbacks 角色名 => voice_prompt(仅包含配置了参考音频的角色)
  10031. * @return string
  10032. */
  10033. public function applyAudioVoiceFallbacks($prompt, array $audioVoiceFallbacks) {
  10034. if (empty($prompt) || empty($audioVoiceFallbacks)) {
  10035. return $prompt;
  10036. }
  10037. foreach ($audioVoiceFallbacks as $product_name => $voice_prompt) {
  10038. $voice_prompt = trim((string)$voice_prompt);
  10039. if ($product_name === '') {
  10040. continue;
  10041. }
  10042. $escaped_name = preg_quote($product_name, '/');
  10043. // 说明行中仍有<音频N>标记,说明该角色的音频素材可用,无需兜底
  10044. if (preg_match('/^' . $escaped_name . ':全程使用<音频\d+>的音色进行配音[^\n]*$/mu', $prompt)) {
  10045. continue;
  10046. }
  10047. $linePattern = '/^' . $escaped_name . ':全程使用[^\n]*的音色进行配音[^\n]*$/mu';
  10048. if (!preg_match($linePattern, $prompt)) {
  10049. continue;
  10050. }
  10051. if ($voice_prompt === '') {
  10052. // 该角色没有音色提示词,素材不可用时直接移除残留的说明行
  10053. $prompt = preg_replace('/^' . $escaped_name . ':全程使用[^\n]*的音色进行配音[^\n]*\n?/mu', '', $prompt, 1);
  10054. } else {
  10055. // 素材不可用:把说明行替换为该角色原本的音色提示词
  10056. $prompt = preg_replace_callback($linePattern, function () use ($product_name, $voice_prompt) {
  10057. return $product_name . ':' . $voice_prompt;
  10058. }, $prompt, 1);
  10059. }
  10060. dLog('anime')->info('参考音频素材不可用,使用音色提示词兜底', [
  10061. 'product_name' => $product_name,
  10062. 'has_voice_prompt' => $voice_prompt === '' ? 0 : 1,
  10063. ]);
  10064. }
  10065. return $prompt;
  10066. }
  10067. /**
  10068. * 整段配音音频素材不可用时,移除对应的提示语句,避免出现残句
  10069. *
  10070. * @param string $prompt 完整提示词
  10071. * @return string
  10072. */
  10073. public function removeUnavailableSegmentAudioPrompt($prompt) {
  10074. if (empty($prompt) || strpos($prompt, '作为视频配音') === false) {
  10075. return $prompt;
  10076. }
  10077. return preg_replace_callback('/^全程使用[^\n]*?作为视频配音。\n?/mu', function ($matches) {
  10078. return strpos($matches[0], '<音频') === false ? '' : $matches[0];
  10079. }, $prompt);
  10080. }
  10081. /**
  10082. * 生成整段配音音频的提示词引用,并返回合并后的参考音频数组
  10083. * 角色音色音频排在前面(音频1..N,与提示词中的<音频N>一一对应),整段配音音频排在其后
  10084. *
  10085. * @param string $prompt 当前提示词
  10086. * @param array $referenceAudios 角色音色参考音频URL数组
  10087. * @param string $segmentAudioUrl 整段配音音频URL(为空表示无整段配音)
  10088. * @return array ['prompt' => 新提示词, 'has_audio_mark' => 是否使用<音频N>标记, 'reference_audios' => 合并后的音频数组]
  10089. */
  10090. public function buildSegmentAudioReference($prompt, array $referenceAudios, $segmentAudioUrl) {
  10091. $result = [
  10092. 'prompt' => $prompt,
  10093. 'has_audio_mark' => false,
  10094. 'reference_audios' => $referenceAudios,
  10095. ];
  10096. if (empty($segmentAudioUrl)) {
  10097. return $result;
  10098. }
  10099. // 有角色音色时整段配音排在角色音色之后,使用<音频N>标记交由素材上传统一做失败清理与序号重排;
  10100. // 没有角色音色时保持原有文案
  10101. $audioReference = $referenceAudios
  10102. ? "使用<音频" . (count($referenceAudios) + 1) . ">"
  10103. : "使用音频1";
  10104. $hasAudioMark = strpos($audioReference, '<音频') !== false;
  10105. // 有角色音色时整段配音独占一行,便于失败时按行清理
  10106. $result['prompt'] = $hasAudioMark
  10107. ? "全程" . $audioReference . "作为视频配音。\n" . $prompt
  10108. : "全程" . $audioReference . "作为视频配音。" . $prompt;
  10109. $result['has_audio_mark'] = $hasAudioMark;
  10110. $result['reference_audios'] = array_merge($referenceAudios, [$segmentAudioUrl]);
  10111. return $result;
  10112. }
  10113. public function saveActVideoGenerateParams($data) {
  10114. $episode_id = getProp($data, 'episode_id');
  10115. $model = getProp($data, 'video_model');
  10116. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  10117. if (!in_array($model, $valid_models)) {
  10118. Utils::throwError('20003:该模型不可用');
  10119. }
  10120. // 验证模型是否在可用模型表中
  10121. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10122. Utils::throwError('20003:该模型已不可用,请更换!');
  10123. }
  10124. $video_resolution = getProp($data, 'video_resolution', '720p');
  10125. $ratio = getProp($data, 'ratio');
  10126. if (!$ratio) $ratio = '9:16';
  10127. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  10128. if (!$episode) {
  10129. Utils::throwError('20003:分集不存在');
  10130. }
  10131. dLog('anime')->info('保存分集视频参数', $data);
  10132. try {
  10133. DB::beginTransaction();
  10134. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10135. 'video_model' => $model,
  10136. 'video_resolution' => $video_resolution,
  10137. 'ratio' => $ratio,
  10138. 'updated_at' => date('Y-m-d H:i:s')
  10139. ]);
  10140. if ($result === false) {
  10141. Utils::throwError('20003:分集视频参数保存失败');
  10142. }
  10143. // 同步更新mp_animes表
  10144. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  10145. 'video_model' => $model,
  10146. 'video_resolution' => $video_resolution,
  10147. 'video_ratio' => $ratio,
  10148. 'updated_at' => date('Y-m-d H:i:s')
  10149. ]);
  10150. if ($anime_result === false) {
  10151. Utils::throwError('20003:动漫视频参数保存失败');
  10152. }
  10153. } catch (\Exception $e) {
  10154. DB::rollBack();
  10155. Utils::throwError('20003:'.$e->getMessage());
  10156. }
  10157. DB::commit();
  10158. return $result;
  10159. }
  10160. public function confirmActs($data) {
  10161. $episode_id = getProp($data, 'episode_id');
  10162. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10163. if (!$episode) {
  10164. Utils::throwError('20003:分集不存在');
  10165. }
  10166. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10167. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10168. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10169. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  10170. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  10171. // 获取所有片段数据
  10172. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10173. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  10174. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  10175. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  10176. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  10177. $products = [];
  10178. // 先处理角色数组
  10179. foreach ($roles as $role) {
  10180. $product = $role;
  10181. // 将role字段重命名为product_name
  10182. if (isset($product['role'])) {
  10183. $product['product_name'] = $product['role'];
  10184. unset($product['role']);
  10185. $product['product'] = 1; // 标记类型为角色
  10186. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10187. }
  10188. }
  10189. // 处理场景数组
  10190. foreach ($scenes as $scene) {
  10191. $product = $scene;
  10192. // 将scene字段重命名为product_name
  10193. if (isset($product['scene'])) {
  10194. $product['product_name'] = $product['scene'];
  10195. unset($product['scene']);
  10196. $product['product'] = 2; // 标记类型为场景
  10197. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10198. }
  10199. }
  10200. // 处理道具数组(逻辑与场景一致)
  10201. foreach ($props as $prop) {
  10202. $product = $prop;
  10203. // 将prop字段重命名为product_name
  10204. if (isset($product['prop'])) {
  10205. $product['product_name'] = $product['prop'];
  10206. unset($product['prop']);
  10207. $product['product'] = 3; // 标记类型为道具
  10208. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10209. }
  10210. }
  10211. // extra_products优先级更高,直接覆盖同名的roles和scenes
  10212. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  10213. foreach ($extra_products as $extra_product) {
  10214. $product_name = getProp($extra_product, 'product_name');
  10215. if ($product_name) {
  10216. $products[$product_name] = $extra_product; // 覆盖同名数据
  10217. }
  10218. }
  10219. // mp_script_product_mappings 信息优先级更高:
  10220. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  10221. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  10222. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  10223. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  10224. if ($script_id && !empty($products)) {
  10225. $currentProductNames = array_keys($products);
  10226. $normalizeName = function($name) {
  10227. return trim(preg_replace(
  10228. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10229. '',
  10230. trim((string)$name)
  10231. ));
  10232. };
  10233. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  10234. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10235. ->where('mapping.script_id', $script_id)
  10236. ->where('product.is_deleted', 0)
  10237. ->whereIn('product.product_name', $currentProductNames)
  10238. ->select(
  10239. 'mapping.product_id',
  10240. 'product.product_name',
  10241. 'product.product',
  10242. 'product.pic_prompt',
  10243. 'product.url',
  10244. 'product.three_view_image_url',
  10245. 'product.timbre_url',
  10246. )
  10247. ->get();
  10248. $mappingByName = [];
  10249. foreach ($mappingItems as $mappingItem) {
  10250. $normalizedName = $normalizeName($mappingItem->product_name);
  10251. if (!$normalizedName) continue;
  10252. $mappingProduct = [
  10253. 'product_id' => (int)$mappingItem->product_id,
  10254. 'product_name' => $mappingItem->product_name,
  10255. 'product' => (int)$mappingItem->product,
  10256. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  10257. 'url' => $mappingItem->url ?? '',
  10258. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  10259. ];
  10260. // 音色音频:资产库有值时才覆盖分集自带的值,避免空值把已有音色清掉
  10261. if (!empty($mappingItem->timbre_url)) {
  10262. $mappingProduct['timbre_url'] = $mappingItem->timbre_url;
  10263. }
  10264. $mappingByName[$normalizedName] = $mappingProduct;
  10265. }
  10266. foreach ($products as $key => &$product) {
  10267. $normalizedKey = $normalizeName($key);
  10268. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  10269. $product = array_merge($product, $mappingByName[$normalizedKey]);
  10270. }
  10271. }
  10272. unset($product);
  10273. }
  10274. // 兼容返回 three_view_image_url / timbre_url 字段(旧数据可能没有该键,统一补空值)
  10275. foreach ($products as &$product) {
  10276. if (!isset($product['three_view_image_url'])) {
  10277. $product['three_view_image_url'] = '';
  10278. }
  10279. if (!isset($product['timbre_url'])) {
  10280. $product['timbre_url'] = '';
  10281. }
  10282. }
  10283. unset($product);
  10284. // 重新索引数组(去除key)
  10285. $products = array_values($products);
  10286. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  10287. $product_names = [];
  10288. foreach ($products as $product) {
  10289. $product_name = getProp($product, 'product_name');
  10290. if ($product_name && $product_name !== '旁白') {
  10291. $product_names[] = $product_name;
  10292. }
  10293. }
  10294. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10295. $product_names = array_unique($product_names);
  10296. usort($product_names, function($a, $b) {
  10297. return mb_strlen($b) - mb_strlen($a);
  10298. });
  10299. try {
  10300. DB::beginTransaction();
  10301. // 处理每个片段
  10302. foreach ($acts as $act) {
  10303. $act_content = getProp($act, 'act_content');
  10304. if (!$act_content) continue;
  10305. $processed_content = $act_content;
  10306. // 统一替换所有资产名称为 {资产名} 格式
  10307. // 使用占位符避免嵌套替换问题
  10308. $placeholder_map = [];
  10309. $placeholder_index = 0;
  10310. foreach ($product_names as $product_name) {
  10311. // 转义特殊字符
  10312. $escaped_product = preg_quote($product_name, '/');
  10313. // 检查是否匹配且未被 {} 包裹
  10314. $processed_content = preg_replace_callback(
  10315. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10316. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10317. // 使用唯一占位符
  10318. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10319. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10320. $placeholder_index++;
  10321. return $placeholder;
  10322. },
  10323. $processed_content
  10324. );
  10325. }
  10326. // 将所有占位符替换回实际内容
  10327. foreach ($placeholder_map as $placeholder => $replacement) {
  10328. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10329. }
  10330. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10331. $shot_counter = 0;
  10332. $processed_content = preg_replace_callback(
  10333. '/【(?:镜头|分镜)(\d+)】/u',
  10334. function($matches) use (&$shot_counter) {
  10335. $shot_counter++;
  10336. return '【镜头' . $shot_counter . '】';
  10337. },
  10338. $processed_content
  10339. );
  10340. // 更新数据库
  10341. $boolen = DB::table('mp_episode_segments')
  10342. ->where('id', $act->id)
  10343. ->update([
  10344. 'act_show_content' => $processed_content,
  10345. 'updated_at' => date('Y-m-d H:i:s')
  10346. ]);
  10347. if (!$boolen) {
  10348. Utils::throwError('20003:片段处理失败');
  10349. }
  10350. }
  10351. }catch (\Exception $e) {
  10352. DB::rollBack();
  10353. Utils::throwError('20003:'.$e->getMessage());
  10354. }
  10355. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10356. 'is_generated' => 1,
  10357. 'updated_at' => date('Y-m-d H:i:s')
  10358. ]);
  10359. if (!$boolen1) {
  10360. DB::rollBack();
  10361. Utils::throwError('20003:分集处理失败!');
  10362. }
  10363. DB::commit();
  10364. // 重新查询更新后的片段数据
  10365. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10366. // 构建返回的acts数组
  10367. $return_acts = [];
  10368. foreach ($acts as $act) {
  10369. $return_acts[] = [
  10370. 'act_id' => getProp($act, 'id'),
  10371. 'act_number' => getProp($act, 'act_number'),
  10372. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10373. 'act_show_content' => getProp($act, 'act_show_content'),
  10374. 'video_url' => getProp($act, 'video_url'),
  10375. 'video_duration' => getProp($act, 'video_duration'),
  10376. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10377. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10378. ];
  10379. }
  10380. return [
  10381. 'anime_id' => getProp($episode, 'anime_id'),
  10382. 'episode_id' => $episode_id,
  10383. 'title' => getProp($episode, 'title'),
  10384. 'episode_number' => getProp($episode, 'episode_number'),
  10385. 'is_generated' => getProp($episode, 'is_generated'),
  10386. 'video_params' => [
  10387. 'video_model' => getProp($episode, 'video_model'),
  10388. 'video_resolution' => getProp($episode, 'video_resolution'),
  10389. 'ratio' => getProp($episode, 'ratio'),
  10390. ],
  10391. 'products' => $products,
  10392. 'acts' => $return_acts
  10393. ];
  10394. }
  10395. /**
  10396. * 参照 episodePicsInfo 的更新与监控逻辑:
  10397. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10398. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10399. */
  10400. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10401. $pollInterval = 5; // 每5秒查询一次
  10402. $maxWaitSeconds = 60; // 最多持续1分钟
  10403. $startTime = time();
  10404. while (true) {
  10405. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10406. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10407. if (!$episode) {
  10408. Utils::throwError('20003:分集不存在');
  10409. }
  10410. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10411. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10412. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10413. $updated = false;
  10414. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10415. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10416. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10417. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10418. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10419. // 有图片任务结果更新时写回分集表
  10420. if ($updated) {
  10421. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10422. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10423. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10424. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10425. 'updated_at' => date('Y-m-d H:i:s')
  10426. ]);
  10427. }
  10428. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10429. if (empty($waitingAssets) && empty($missingAssets)) {
  10430. return;
  10431. }
  10432. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10433. if (empty($waitingAssets)) {
  10434. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10435. }
  10436. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10437. if (time() - $startTime >= $maxWaitSeconds) {
  10438. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10439. }
  10440. sleep($pollInterval);
  10441. }
  10442. }
  10443. /**
  10444. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10445. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10446. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10447. */
  10448. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10449. foreach ($assets as &$asset) {
  10450. $assetName = getProp($asset, $nameKey);
  10451. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10452. continue;
  10453. }
  10454. // 已有图片URL的资产视为已生成
  10455. if (getProp($asset, 'url')) {
  10456. continue;
  10457. }
  10458. $task_id = getProp($asset, 'task_id');
  10459. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10460. if (!$task_id) {
  10461. $missingAssets[] = $assetName;
  10462. continue;
  10463. }
  10464. $task = DB::table('mp_generate_pic_tasks')
  10465. ->where('id', $task_id)
  10466. ->select('status', 'result_url')
  10467. ->first();
  10468. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10469. if (!$task) {
  10470. $missingAssets[] = $assetName;
  10471. continue;
  10472. }
  10473. if ($task->status === 'success') {
  10474. $result_url = getProp($task, 'result_url');
  10475. if ($result_url) {
  10476. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10477. if (is_array($result_urls) && !empty($result_urls[0])) {
  10478. $asset['url'] = $result_urls[0];
  10479. $asset['task_status'] = 'success';
  10480. $updated = true;
  10481. continue;
  10482. }
  10483. }
  10484. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  10485. $waitingAssets[] = $assetName;
  10486. } elseif ($task->status === 'failed') {
  10487. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  10488. $missingAssets[] = $assetName;
  10489. } else {
  10490. // 任务仍在生成中,等待下一次轮询
  10491. $waitingAssets[] = $assetName;
  10492. }
  10493. }
  10494. unset($asset);
  10495. }
  10496. /**
  10497. * 导出动漫剧本为PDF(参照示例PDF版式)
  10498. * @param int $animeId 动漫ID
  10499. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  10500. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  10501. * @return string|null
  10502. */
  10503. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  10504. // 图片下载与转换可能占用较多内存
  10505. ini_set('memory_limit', '512M');
  10506. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  10507. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  10508. $anime = (array)$anime;
  10509. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  10510. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  10511. // 获取分集(默认展示版本,按集数升序)
  10512. $episodeQuery = DB::table('mp_anime_episodes')
  10513. ->where('anime_id', $animeId)
  10514. ->where('is_default', 1)
  10515. ->orderBy('episode_number')
  10516. ->orderBy('id');
  10517. if ($episodeCount > 0) {
  10518. $episodeQuery->limit($episodeCount);
  10519. }
  10520. $episodes = $episodeQuery->get()->map(function ($value) {
  10521. return (array)$value;
  10522. })->toArray();
  10523. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  10524. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  10525. $roles = $this->mergeEpisodeItems($episodes, 'role');
  10526. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  10527. $props = $this->mergeEpisodeItems($episodes, 'prop');
  10528. // 组装分集剧本数据
  10529. $episodeScripts = [];
  10530. foreach ($episodes as $episode) {
  10531. $segments = DB::table('mp_episode_segments')
  10532. ->where('anime_id', $animeId)
  10533. ->where('episode_id', $episode['id'])
  10534. ->get();
  10535. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  10536. $acts = [];
  10537. foreach ($segments as $segment) {
  10538. $segment = (array)$segment;
  10539. $actNumber = (int)getProp($segment, 'act_number', 0);
  10540. if ($actNumber <= 0) continue;
  10541. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  10542. $acts[$actNumber] = [
  10543. 'id' => (int)$segment['id'],
  10544. 'act_number' => $actNumber,
  10545. 'duration' => getProp($segment, 'act_duration', ''),
  10546. 'content' => getProp($segment, 'act_content', ''),
  10547. ];
  10548. }
  10549. }
  10550. ksort($acts);
  10551. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  10552. $segmentCounter = 0;
  10553. foreach ($acts as &$act) {
  10554. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  10555. }
  10556. unset($act);
  10557. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  10558. $narratorVoice = '';
  10559. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  10560. foreach ($episodeRoles as $role) {
  10561. if (getProp($role, 'role') === '旁白') {
  10562. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  10563. break;
  10564. }
  10565. }
  10566. if ($narratorVoice === '') {
  10567. foreach ($acts as $act) {
  10568. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  10569. $narratorVoice = trim($match[1]);
  10570. break;
  10571. }
  10572. }
  10573. }
  10574. $episodeScripts[] = [
  10575. 'episode_number' => getProp($episode, 'episode_number'),
  10576. 'title' => getProp($episode, 'title', ''),
  10577. 'act_count' => count($acts),
  10578. 'narrator_voice' => $narratorVoice,
  10579. 'acts' => array_values($acts),
  10580. ];
  10581. }
  10582. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  10583. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  10584. // 构建PDF
  10585. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  10586. // 图片已嵌入PDF,清理临时文件
  10587. foreach ($imageCache as $imgFile) {
  10588. @unlink($imgFile);
  10589. }
  10590. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  10591. if ($savePath) {
  10592. $pdf->Output($savePath, 'F');
  10593. return $savePath;
  10594. }
  10595. // 直接下载输出
  10596. header('Content-Type: application/pdf');
  10597. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  10598. $pdf->Output($filename . '.pdf', 'D');
  10599. exit();
  10600. }
  10601. /**
  10602. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  10603. * @param array $episodes 分集数据
  10604. * @param string $nameKey role|scene|prop
  10605. * @return array
  10606. */
  10607. private function mergeEpisodeItems(array $episodes, $nameKey) {
  10608. $fieldMap = [
  10609. 'role' => 'roles',
  10610. 'scene' => 'scenes',
  10611. 'prop' => 'props',
  10612. ];
  10613. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  10614. $items = [];
  10615. foreach ($episodes as $episode) {
  10616. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  10617. foreach ($list as $item) {
  10618. if (!is_array($item)) continue;
  10619. $name = trim((string)getProp($item, $nameKey, ''));
  10620. if ($name === '') continue;
  10621. // 旁白不进入主体列表(仅作为旁白音色来源)
  10622. if ($nameKey === 'role' && $name === '旁白') continue;
  10623. if (!isset($items[$name])) {
  10624. $items[$name] = $item;
  10625. }
  10626. }
  10627. }
  10628. return array_values($items);
  10629. }
  10630. /**
  10631. * 构建动漫剧本PDF
  10632. * @param array $anime 动漫信息
  10633. * @param array $roles 主体列表
  10634. * @param array $scenes 场景列表
  10635. * @param array $props 道具列表
  10636. * @param array $episodeScripts 分集剧本数据
  10637. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10638. * @return \TCPDF
  10639. */
  10640. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  10641. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  10642. $pdf->SetCreator('动漫剧本导出系统');
  10643. $pdf->SetAuthor('系统');
  10644. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  10645. $pdf->SetSubject('动漫剧本导出');
  10646. $pdf->SetMargins(15, 15, 15);
  10647. $pdf->SetAutoPageBreak(true, 15);
  10648. // 剧本名
  10649. $pdf->AddPage();
  10650. $pdf->SetFont('simsun', 'B', 20);
  10651. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  10652. $pdf->Ln(5);
  10653. // 故事梗概
  10654. $intro = trim((string)getProp($anime, 'intro', ''));
  10655. if ($intro !== '') {
  10656. $this->pdfSectionTitle($pdf, '故事梗概');
  10657. $this->pdfBody($pdf, $intro);
  10658. }
  10659. // 美术风格
  10660. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  10661. if ($artStyle !== '') {
  10662. $this->pdfSectionTitle($pdf, '美术风格');
  10663. $this->pdfBody($pdf, $artStyle);
  10664. }
  10665. // 主体列表(文字+图片)
  10666. $this->pdfSectionTitle($pdf, '主体列表');
  10667. foreach ($roles as $index => $role) {
  10668. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  10669. }
  10670. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  10671. // 场景列表(文字+图片)
  10672. $this->pdfSectionTitle($pdf, '场景列表');
  10673. foreach ($scenes as $index => $scene) {
  10674. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  10675. }
  10676. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  10677. // 道具列表(文字+图片)
  10678. $this->pdfSectionTitle($pdf, '道具列表');
  10679. foreach ($props as $index => $prop) {
  10680. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  10681. }
  10682. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  10683. // 分镜剧本
  10684. $this->pdfSectionTitle($pdf, '分镜剧本');
  10685. foreach ($episodeScripts as $episodeScript) {
  10686. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  10687. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  10688. if ($episodeTitleRaw !== '') {
  10689. // title 字段可能已带"第N集"前缀,避免重复
  10690. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  10691. $episodeTitle = $episodeTitleRaw;
  10692. } else {
  10693. $episodeTitle .= ':' . $episodeTitleRaw;
  10694. }
  10695. }
  10696. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  10697. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  10698. if (getProp($episodeScript, 'narrator_voice') !== '') {
  10699. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  10700. }
  10701. foreach (getProp($episodeScript, 'acts', []) as $act) {
  10702. $actTitle = '片段' . getProp($act, 'act_number');
  10703. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  10704. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  10705. }
  10706. $this->pdfSubTitle($pdf, $actTitle, 12);
  10707. if (getProp($act, 'content') !== '') {
  10708. $this->pdfBody($pdf, getProp($act, 'content'));
  10709. }
  10710. }
  10711. }
  10712. return $pdf;
  10713. }
  10714. /**
  10715. * PDF章节标题(带分隔线)
  10716. */
  10717. private function pdfSectionTitle($pdf, $title) {
  10718. if ($pdf->GetY() > 230) {
  10719. $pdf->AddPage();
  10720. }
  10721. $pdf->SetFont('simsun', 'B', 15);
  10722. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  10723. $y = $pdf->GetY();
  10724. $pdf->SetLineWidth(0.4);
  10725. $pdf->Line(15, $y, 195, $y);
  10726. $pdf->Ln(4);
  10727. }
  10728. /**
  10729. * PDF子标题(集数/片段标题)
  10730. */
  10731. private function pdfSubTitle($pdf, $title, $size = 13) {
  10732. if ($pdf->GetY() > 240) {
  10733. $pdf->AddPage();
  10734. }
  10735. $pdf->SetFont('simsun', 'B', $size);
  10736. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  10737. $pdf->Ln(1);
  10738. }
  10739. /**
  10740. * PDF正文段落
  10741. */
  10742. private function pdfBody($pdf, $text) {
  10743. $pdf->SetFont('simsun', '', 11);
  10744. $pdf->MultiCell(0, 6, $text, 0, 'L');
  10745. $pdf->Ln(2);
  10746. }
  10747. /**
  10748. * 输出列表项图片(每张图单独一页,图下标注名称)
  10749. * @param \TCPDF $pdf
  10750. * @param array $items 列表项
  10751. * @param string $nameKey role|scene|prop
  10752. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10753. */
  10754. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  10755. foreach ($items as $item) {
  10756. $url = trim((string)getProp($item, 'url', ''));
  10757. $name = trim((string)getProp($item, $nameKey, ''));
  10758. if ($url === '' || !isset($imageCache[$url])) continue;
  10759. $imgPath = $imageCache[$url];
  10760. $size = @getimagesize($imgPath);
  10761. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  10762. continue;
  10763. }
  10764. $pdf->AddPage();
  10765. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  10766. $maxW = 160;
  10767. $maxH = 170;
  10768. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  10769. $drawW = $size[0] * $ratio;
  10770. $drawH = $size[1] * $ratio;
  10771. $x = (210 - $drawW) / 2;
  10772. $y = max(15, (297 - $drawH) / 2 - 10);
  10773. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  10774. // 图下标注名称
  10775. $pdf->SetFont('simsun', 'B', 13);
  10776. $pdf->SetY(297 - 28);
  10777. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  10778. }
  10779. }
  10780. /**
  10781. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  10782. * @param array $items 包含url字段的列表项
  10783. * @return array url => 临时文件路径
  10784. */
  10785. private function downloadImagesConcurrently(array $items) {
  10786. // 收集唯一的图片URL
  10787. $urls = [];
  10788. foreach ($items as $item) {
  10789. $url = trim((string)getProp($item, 'url', ''));
  10790. if ($url !== '') $urls[$url] = true;
  10791. }
  10792. if (!$urls) return [];
  10793. $urls = array_keys($urls);
  10794. $tmpDir = sys_get_temp_dir();
  10795. $rawFiles = [];
  10796. foreach ($urls as $url) {
  10797. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  10798. $rawFiles[$url] = $rawFile;
  10799. }
  10800. $client = new Client(['timeout' => 180, 'verify' => false]);
  10801. // 低并发下载,sink写入文件避免大图占用内存
  10802. $generator = (function () use ($urls, $client, $rawFiles) {
  10803. foreach ($urls as $url) {
  10804. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  10805. }
  10806. })();
  10807. $errors = [];
  10808. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  10809. 'concurrency' => 4,
  10810. 'rejected' => function ($reason, $url) use (&$errors) {
  10811. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  10812. },
  10813. ]);
  10814. $each->promise()->wait();
  10815. // 失败的图片串行重试一次(独占带宽,提高成功率)
  10816. foreach ($urls as $url) {
  10817. if (!isset($errors[$url])) continue;
  10818. try {
  10819. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  10820. unset($errors[$url]);
  10821. } catch (\Throwable $e) {
  10822. // 重试仍失败
  10823. }
  10824. }
  10825. $cache = [];
  10826. foreach ($urls as $url) {
  10827. $rawFile = $rawFiles[$url];
  10828. if (isset($errors[$url])) {
  10829. dLog('anime')->error('导出PDF图片下载失败', [
  10830. 'url' => $url,
  10831. 'error' => $errors[$url],
  10832. ]);
  10833. @unlink($rawFile);
  10834. continue;
  10835. }
  10836. $converted = $this->convertImageFile($rawFile, $url);
  10837. if ($converted !== null) {
  10838. $cache[$url] = $converted;
  10839. } else {
  10840. @unlink($rawFile);
  10841. }
  10842. }
  10843. return $cache;
  10844. }
  10845. /**
  10846. * 将已下载的图片文件缩放并转为JPEG
  10847. * @param string $rawFile 原始图片临时文件
  10848. * @param string $url 图片地址(用于命名)
  10849. * @return string|null 转换后的文件路径,转换失败返回null
  10850. */
  10851. private function convertImageFile($rawFile, $url) {
  10852. $content = @file_get_contents($rawFile);
  10853. if ($content === false || $content === '') return null;
  10854. if (!function_exists('imagecreatefromstring')) return null;
  10855. $image = @imagecreatefromstring($content);
  10856. if ($image === false) return null;
  10857. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  10858. imagedestroy($image);
  10859. if ($jpeg !== null) {
  10860. @unlink($rawFile);
  10861. }
  10862. return $jpeg;
  10863. }
  10864. /**
  10865. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  10866. * @param resource $srcImage GD图片资源
  10867. * @param string $rawFile 原始图片临时文件
  10868. * @param string $url 图片地址(用于命名)
  10869. * @return string|null 压缩后的JPEG文件路径
  10870. */
  10871. private function compressImageForPdf($srcImage, $rawFile, $url) {
  10872. $maxBytes = 2 * 1024 * 1024; // 2MB
  10873. $sizes = [2048, 1600, 1280, 1024, 800];
  10874. $qualities = [85, 70, 55, 40];
  10875. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  10876. foreach ($sizes as $size) {
  10877. $resized = $this->copyAndResize($srcImage, $size);
  10878. $flat = $this->flattenToWhite($resized);
  10879. imagedestroy($resized);
  10880. foreach ($qualities as $quality) {
  10881. ob_start();
  10882. $saved = imagejpeg($flat, null, $quality);
  10883. $data = ob_get_clean();
  10884. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  10885. file_put_contents($jpeg, $data);
  10886. imagedestroy($flat);
  10887. dLog('anime')->info('导出PDF图片压缩完成', [
  10888. 'url' => $url,
  10889. 'size' => filesize($jpeg),
  10890. 'edge' => $size,
  10891. 'quality' => $quality,
  10892. ]);
  10893. return $jpeg;
  10894. }
  10895. }
  10896. imagedestroy($flat);
  10897. }
  10898. // 兜底:最小尺寸、最低质量强制输出
  10899. $resized = $this->copyAndResize($srcImage, 800);
  10900. $flat = $this->flattenToWhite($resized);
  10901. imagedestroy($resized);
  10902. $saved = imagejpeg($flat, $jpeg, 30);
  10903. imagedestroy($flat);
  10904. if (!$saved) return null;
  10905. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  10906. 'url' => $url,
  10907. 'size' => filesize($jpeg),
  10908. ]);
  10909. return $jpeg;
  10910. }
  10911. /**
  10912. * 等比缩放图片副本(不销毁原图)
  10913. * @param resource $srcImage GD图片资源
  10914. * @param int $maxEdge 最大边长
  10915. * @return resource
  10916. */
  10917. private function copyAndResize($srcImage, $maxEdge) {
  10918. $width = imagesx($srcImage);
  10919. $height = imagesy($srcImage);
  10920. $max = max($width, $height);
  10921. if ($max <= $maxEdge) {
  10922. $copy = imagecreatetruecolor($width, $height);
  10923. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  10924. return $copy;
  10925. }
  10926. $ratio = $maxEdge / $max;
  10927. $newWidth = max(1, (int)round($width * $ratio));
  10928. $newHeight = max(1, (int)round($height * $ratio));
  10929. $resized = imagecreatetruecolor($newWidth, $newHeight);
  10930. imagealphablending($resized, false);
  10931. imagesavealpha($resized, true);
  10932. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  10933. return $resized;
  10934. }
  10935. /**
  10936. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  10937. * @param resource $image GD图片资源
  10938. * @return resource
  10939. */
  10940. private function flattenToWhite($image) {
  10941. $width = imagesx($image);
  10942. $height = imagesy($image);
  10943. $flat = imagecreatetruecolor($width, $height);
  10944. $white = imagecolorallocate($flat, 255, 255, 255);
  10945. imagefill($flat, 0, 0, $white);
  10946. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  10947. return $flat;
  10948. }
  10949. /**
  10950. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  10951. * @param string $content 片段内容
  10952. * @param int $counter 当前已编号数量(引用传递,整集累计)
  10953. * @return string
  10954. */
  10955. private function renumberSegmentBlocks($content, &$counter) {
  10956. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  10957. $counter++;
  10958. return '【' . $match[1] . $counter . '】';
  10959. }, $content);
  10960. }
  10961. }