AnimeService.php 452 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Models\MpTaskCenter;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use App\Services\AIGeneration\AIVideoGenerationService;
  11. use App\Services\DeepSeek\DeepSeekService;
  12. use App\Services\PointsService;
  13. use App\Services\TaskCenterService;
  14. use Dflydev\DotAccessData\Util;
  15. use GuzzleHttp\Client;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Redis;
  19. use OSS\Core\OssException;
  20. use OSS\OssClient;
  21. class AnimeService
  22. {
  23. protected $aiImageGenerationService;
  24. protected $aiVideoGenerationService;
  25. protected $DeepSeekService;
  26. protected $pointsService;
  27. protected $taskCenterService;
  28. private $url;
  29. private $api_key;
  30. private $headers;
  31. public function __construct(
  32. AIImageGenerationService $aiImageGenerationService,
  33. AIVideoGenerationService $aiVideoGenerationService,
  34. DeepSeekService $DeepSeekService,
  35. PointsService $pointsService,
  36. TaskCenterService $taskCenterService
  37. ) {
  38. $this->aiImageGenerationService = $aiImageGenerationService;
  39. $this->aiVideoGenerationService = $aiVideoGenerationService;
  40. $this->DeepSeekService = $DeepSeekService;
  41. $this->pointsService = $pointsService;
  42. $this->taskCenterService = $taskCenterService;
  43. $this->url = 'https://api.deepseek.com/chat/completions';
  44. $this->api_key = env('DEEPSEEK_API_KEY');
  45. $this->headers = [
  46. 'Authorization' => 'Bearer '.$this->api_key,
  47. 'Content-Type' => 'application/json; charset=UTF-8'
  48. ];
  49. }
  50. /**
  51. * 构建统一的分镜数据结构(episodeInfo格式)
  52. * @param array $segments 分镜数据数组
  53. * @return array 返回包含acts和total_duration的数组
  54. */
  55. public function buildEpisodeSegmentsStructure($segments) {
  56. $acts = [];
  57. $totalDuration = 0; // 初始化总时长
  58. foreach($segments as $segment) {
  59. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  60. $videoDuration = getProp($segment, 'video_duration');
  61. $audioDuration = getProp($segment, 'audio_duration');
  62. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  63. $totalDuration += floatval($videoDuration);
  64. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  65. $totalDuration += floatval($audioDuration);
  66. } else {
  67. $totalDuration += 5; // 默认5秒
  68. }
  69. $segment_content = getProp($segment, 'segment_content');
  70. // 判断是否有尾帧描述,如果有则去掉这部分内容
  71. if (strpos($segment_content, '尾帧') !== false) {
  72. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  73. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  74. }
  75. // 构建分镜信息
  76. $segmentInfo = [
  77. 'segment_id' => getProp($segment, 'segment_id'),
  78. 'segment_number' => getProp($segment, 'segment_number'),
  79. 'segment_content' => $segment_content,
  80. 'description' => getProp($segment, 'description'),
  81. 'composition' => getProp($segment, 'composition'),
  82. 'camera_movement' => getProp($segment, 'camera_movement'),
  83. 'voice_actor' => getProp($segment, 'voice_actor'),
  84. 'dialogue' => getProp($segment, 'dialogue'),
  85. 'frame_type' => getProp($segment, 'frame_type'),
  86. 'scene' => getProp($segment, 'scene'),
  87. 'characters' => getProp($segment, 'characters'),
  88. 'tail_frame' => getProp($segment, 'tail_frame'),
  89. 'emotion' => getProp($segment, 'emotion'),
  90. 'emotion_type' => getProp($segment, 'emotion_type'),
  91. 'gender' => getProp($segment, 'gender'),
  92. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  93. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  94. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  95. 'pitch' => getProp($segment, 'pitch'),
  96. 'voice_name' => getProp($segment, 'voice_name'),
  97. 'voice_type' => getProp($segment, 'voice_type'),
  98. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  99. 'img_url' => getProp($segment, 'img_url'),
  100. 'audio_url' => getProp($segment, 'audio_url'),
  101. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  102. 'video_url' => getProp($segment, 'video_url'),
  103. 'video_duration' => getProp($segment, 'video_duration', 0),
  104. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  105. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  106. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  107. 'current_type' => getProp($segment, 'current_type'),
  108. ];
  109. $actNumber = getProp($segment, 'act_number');
  110. if (isset($acts[$actNumber])) {
  111. $acts[$actNumber]['segments'][] = $segmentInfo;
  112. } else {
  113. $acts[$actNumber] = [
  114. 'act_number' => $actNumber,
  115. 'act_title' => getProp($segment, 'act_title'),
  116. 'act_duration' => getProp($segment, 'act_duration'),
  117. 'segments' => [$segmentInfo]
  118. ];
  119. }
  120. }
  121. return [
  122. 'acts' => array_values($acts),
  123. 'total_duration' => intval(round($totalDuration))
  124. ];
  125. }
  126. /**
  127. * 构建统一的分段数据结构(episodeInfoForAce格式)
  128. * @param array $segments 分段数据数组
  129. * @return array 返回包含acts和total_duration的数组
  130. */
  131. public function buildEpisodeActsStructureForAce($segments) {
  132. $acts = [];
  133. $totalDuration = 0; // 初始化总时长
  134. foreach($segments as $segment) {
  135. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  136. $videoDuration = getProp($segment, 'video_duration');
  137. $actDuration = getProp($segment, 'act_duration');
  138. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  139. $totalDuration += floatval($videoDuration);
  140. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  141. $totalDuration += floatval($actDuration);
  142. } else {
  143. $totalDuration += 5; // 默认5秒
  144. }
  145. // 构建分镜信息
  146. $segmentInfo = [
  147. 'act_id' => getProp($segment, 'id'),
  148. 'act_number' => getProp($segment, 'act_number'),
  149. 'act_title' => getProp($segment, 'act_title'),
  150. 'act_duration' => getProp($segment, 'act_duration'),
  151. 'act_content' => getProp($segment, 'act_content'),
  152. 'video_url' => getProp($segment, 'video_url'),
  153. 'video_duration' => getProp($segment, 'video_duration', 0),
  154. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  155. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  156. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  157. 'current_type' => getProp($segment, 'current_type'),
  158. ];
  159. $acts[] = $segmentInfo;
  160. }
  161. return [
  162. 'acts' => array_values($acts),
  163. 'total_duration' => intval(round($totalDuration))
  164. ];
  165. }
  166. /**
  167. * 验证画面比例是否有效
  168. * @param string $ratio 画面比例
  169. * @return bool
  170. */
  171. public function validateRatio($ratio) {
  172. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  173. }
  174. /**
  175. * 获取画面比例对应的宽高
  176. * @param string $ratio 画面比例
  177. * @return array ['width' => int, 'height' => int]
  178. * @throws \Exception
  179. */
  180. private function getRatioDimensions($ratio) {
  181. if ($ratio && !$this->validateRatio($ratio)) {
  182. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  183. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  184. }
  185. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  186. }
  187. public function createAnime($data) {
  188. $uid = Site::getUid();
  189. $cpid = Site::getCpid();
  190. $input_art_style = getProp($data, 'art_style');
  191. $file = getProp($data, 'file');
  192. $content = getProp($data, 'content', '');
  193. $bid = getProp($data, 'bid', 0);
  194. $script_id = getProp($data, 'script_id', 0);
  195. $ace_mode = getProp($data, 'ace_mode', 0);
  196. $extra_products = getProp($data, 'products', []);
  197. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  198. if (!is_array($extra_products)) {
  199. Utils::throwError('20003:传入的资产格式不正确');
  200. }
  201. // 替换美术风格
  202. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  203. // 提取文件内容
  204. if ($file) {
  205. $content = $this->DeepSeekService->extractFileContent($file);
  206. if (!$content) {
  207. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  208. }
  209. } elseif ($script_id) {
  210. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  213. }
  214. } elseif ($bid) {
  215. $content = $this->DeepSeekService->getContentByBid($bid);
  216. if (!$content) {
  217. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  218. }
  219. } elseif ($content) {
  220. $content = filterContent($content);
  221. }else {
  222. $content = '';
  223. }
  224. $anime_data = [
  225. 'user_id' => $uid,
  226. 'cpid' => $cpid,
  227. 'anime_name' => '新剧本策划',
  228. 'is_multi' => getProp($data, 'is_multi', 1),
  229. 'content' => $content,
  230. 'art_style_type' => $input_art_style,
  231. 'ace_mode' => $ace_mode,
  232. 'script_id' => $script_id,
  233. 'extra_products' => json_encode($extra_products, 256),
  234. 'created_at' => date('Y-m-d H:i:s'),
  235. 'updated_at' => date('Y-m-d H:i:s'),
  236. ];
  237. // 处理文本模型
  238. $model = getProp($data, 'model');
  239. if (!$model) {
  240. // 用户没有输入,使用默认值
  241. $model = 'deepseek-v4-pro';
  242. }
  243. // 验证模型是否在可用模型表中
  244. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  245. $model = 'deepseek-v4-pro';
  246. }
  247. $anime_data['model'] = $model;
  248. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  249. return DB::table('mp_animes')->insertGetId($anime_data);
  250. }
  251. public function chatList($data) {
  252. $uid = Site::getUid();
  253. $anime_name = getProp($data, 'anime_name');
  254. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  255. if ($anime_name) {
  256. $query->where('anime_name', 'like', "%$anime_name%");
  257. }
  258. return $query->orderBy('id', 'desc')->paginate();
  259. }
  260. public function chatHistory($data) {
  261. $anime_id = getProp($data, 'anime_id');
  262. $sequence = getProp($data, 'sequence', 0);
  263. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  264. $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)
  265. ->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');
  266. return $query->orderBy('ar.id')->get()->map(function ($value) {
  267. $value = (array)$value;
  268. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  269. $value['created_at'] = transDate($value['created_at']);
  270. $value['episode_created_at'] = transDate($value['episode_created_at']);
  271. return $value;
  272. })->toArray();
  273. }
  274. public function batchSetRoleImg($data) {
  275. $episode_id = getProp($data, 'episode_id');
  276. if (!$episode_id) Utils::throwError('1002:请选择分集');
  277. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  278. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  279. $art_style = getProp($episode, 'art_style');
  280. $anime_id = getProp($episode, 'anime_id');
  281. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  282. $art_style_type = getProp($anime, 'art_style_type');
  283. $character_prefix = '';
  284. $scene_prefix = '';
  285. if ($art_style_type) {
  286. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  287. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  288. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  289. }
  290. foreach ($roles as &$role) {
  291. $role_name = getProp($role, 'role');
  292. if ($role_name == '旁白') continue;
  293. // 优先使用 pic_prompt,如果没有则使用 description
  294. $pic_prompt = getProp($role, 'pic_prompt');
  295. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  296. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  297. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  298. // 参考图地址
  299. $ref_img_url = getProp($role, 'url');
  300. if ($ref_img_url) continue; // 已有图片则跳过
  301. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  302. try {
  303. $params = [
  304. 'prompt' => $description,
  305. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  306. ];
  307. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  308. $task_id = $task->id;
  309. if (!$task_id) {
  310. Utils::throwError("20003:角色({$role_name})生成图片失败");
  311. }
  312. $role['task_id'] = $task_id;
  313. $role['task_status'] = 'processing';
  314. } catch (\Exception $e) {
  315. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  316. Utils::throwError("20003:" . $e->getMessage());
  317. }
  318. }
  319. // 保存角色信息
  320. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  321. 'roles' => json_encode($roles, 256),
  322. 'generate_status' => '执行中',
  323. 'generate_at' => date('Y-m-d H:i:s'),
  324. 'updated_at' => date('Y-m-d H:i:s')
  325. ]);
  326. if (!$boolen) {
  327. Utils::throwError('20003:保存角色信息失败');
  328. }
  329. return $boolen;
  330. }
  331. public function batchSetSceneImg($data) {
  332. $episode_id = getProp($data, 'episode_id');
  333. if (!$episode_id) Utils::throwError('1002:请选择分集');
  334. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  335. $scenes = json_decode(getProp($episode, 'scenes'), true);
  336. $art_style = getProp($episode, 'art_style');
  337. $target_scene = getProp($data, 'target_scene');
  338. $anime_id = getProp($episode, 'anime_id');
  339. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  340. $art_style_type = getProp($anime, 'art_style_type');
  341. $character_prefix = '';
  342. $scene_prefix = '';
  343. if ($art_style_type) {
  344. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  345. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  346. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  347. }
  348. foreach ($scenes as &$scene) {
  349. $scene_name = getProp($scene, 'scene');
  350. if ($scene_name != $target_scene) continue;
  351. // 优先使用 pic_prompt,如果没有则使用 description
  352. $pic_prompt = getProp($scene, 'pic_prompt');
  353. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  354. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  355. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  356. // 参考图地址
  357. $ref_img_url = getProp($scene, 'url');
  358. if ($ref_img_url) continue; // 已有图片则跳过
  359. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  360. try {
  361. $params = [
  362. 'prompt' => $description,
  363. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  364. ];
  365. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  366. $task_id = $task->id;
  367. if (!$task_id) {
  368. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  369. }
  370. $scene['task_id'] = $task_id;
  371. $scene['task_status'] = 'processing';
  372. } catch (\Exception $e) {
  373. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  374. Utils::throwError("20003:" . $e->getMessage());
  375. }
  376. }
  377. // 保存场景信息
  378. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  379. 'scenes' => json_encode($scenes, 256),
  380. 'generate_status' => '执行中',
  381. 'generate_at' => date('Y-m-d H:i:s'),
  382. 'updated_at' => date('Y-m-d H:i:s')
  383. ]);
  384. if (!$boolen) {
  385. Utils::throwError('20003:保存角色信息失败');
  386. }
  387. return $boolen;
  388. }
  389. public function editAnime($data) {
  390. $anime_id = getProp($data, 'anime_id');
  391. $anime_name = trim(getProp($data, 'anime_name'));
  392. // 确认对话名称唯一性
  393. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  394. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  395. }
  396. if (!$anime_id || !$anime_name) {
  397. Utils::throwError('20003:参数异常');
  398. }
  399. return DB::table('mp_animes')->where('id', $anime_id)->update([
  400. 'anime_name' => $anime_name,
  401. 'updated_at' => date('Y-m-d H:i:s')
  402. ]);
  403. // $script_arr =getProp($data, 'script', []);
  404. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  405. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  406. // $anime_id = getProp($data, 'anime_id');
  407. // try {
  408. // DB::beginTransaction();
  409. // $table_data = [
  410. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  411. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  412. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  413. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  414. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  415. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  416. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  417. // 'status' => 3,
  418. // 'start_episode_sequence' => $start_episode_sequence,
  419. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  420. // 'episode_num' => count($script_arr['episodes']),
  421. // 'updated_at' => date('Y-m-d H:i:s')
  422. // ];
  423. // // 保存剧本内容
  424. // if (!empty($anime_id)) {
  425. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  426. // if (!$boolen) {
  427. // dLog('anime')->info('对话保存失败', $table_data);
  428. // Utils::throwError('20003:对话保存失败');
  429. // }
  430. // }else {
  431. // $table['created_at'] = $table_data['updated_at'];
  432. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  433. // if (!$anime_id) {
  434. // dLog('anime')->info('对话保存失败', $table_data);
  435. // Utils::throwError('20003:对话保存失败');
  436. // }
  437. // }
  438. // // 保存分集内容
  439. // // 删除历史分集内容
  440. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  441. // $episodes = [];
  442. // $sequence = 1;
  443. // foreach ($script_arr['episodes'] as $episode) {
  444. // $segment_number = 1;
  445. // foreach($episode['segments'] as $segment) {
  446. // $episodes[] = [
  447. // 'anime_id' => $anime_id,
  448. // 'episode_number' => $episode['episode_number'],
  449. // 'title' => $episode['title'],
  450. // // 'content' => $episode['content'],
  451. // 'content' => '',
  452. // 'segment_number' => $segment_number,
  453. // 'segment_content' => $segment['segment_content'],
  454. // 'sequence' => $sequence,
  455. // 'created_at' => date('Y-m-d H:i:s'),
  456. // 'updated_at' => date('Y-m-d H:i:s')
  457. // ];
  458. // $sequence++;
  459. // $segment_number++;
  460. // }
  461. // }
  462. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  463. // if (!$boolen2) {
  464. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  465. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  466. // Utils::throwError('20003:分集内容保存失败');
  467. // }
  468. // } catch (\Exception $e) {
  469. // DB::rollBack();
  470. // Utils::throwError('20003:'.$e->getMessage());
  471. // }
  472. // DB::commit();
  473. // return true;
  474. }
  475. public function delAnime($data) {
  476. $anime_id = getProp($data, 'anime_id');
  477. if (!$anime_id) {
  478. Utils::throwError('20003:请选择剧本');
  479. }
  480. return DB::table('mp_animes')->where('id', $anime_id)->update([
  481. 'is_deleted' => 1,
  482. 'updated_at' => date('Y-m-d H:i:s')
  483. ]);
  484. }
  485. public function animeDetail($data) {
  486. $uid = Site::getUid();
  487. $anime_id = getProp($data, 'anime_id');
  488. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  489. ->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();
  490. if (!$anime) Utils::throwError('20003:权限不足');
  491. $anime = (array)$anime;
  492. $anime['roles'] = json_decode($anime['roles']);
  493. $anime['scenes'] = json_decode($anime['scenes']);
  494. // 获取分集信息
  495. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  496. ->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"))
  497. ->orderBy('episode_number')->get()->map(function ($value) {
  498. return (array)$value;
  499. })->toArray();
  500. $anime['episodes'] = $episodes;
  501. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  502. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  503. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  504. ->where('anime_id', $anime_id)
  505. ->orderBy('episode_number')
  506. ->get()
  507. ->map(function ($task) use ($episodeNumbers) {
  508. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  509. return null;
  510. }
  511. $item = [
  512. 'episode_number' => (int)$task->episode_number,
  513. 'status' => $task->status,
  514. 'error_message' => $task->status === 'failed' ? ($task->error_message ?? '') : '',
  515. ];
  516. return $item;
  517. })
  518. ->filter()
  519. ->values()
  520. ->toArray();
  521. $anime['episode_tasks'] = $episodeTasks;
  522. return $anime;
  523. }
  524. public function episodeInfo($data) {
  525. $uid = Site::getUid();
  526. $anime_id = getProp($data, 'anime_id');
  527. $episode_id = getProp($data, 'episode_id');
  528. if (!$anime_id || !$episode_id) {
  529. Utils::throwError('1002:请选择剧集');
  530. }
  531. // 验证用户权限
  532. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  533. if (!$anime) Utils::throwError('20003:权限不足');
  534. $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();
  535. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  536. $episode = (array)$episode;
  537. $episode['roles'] = json_decode($episode['roles'], true);
  538. // foreach($episode['roles'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  540. // }
  541. $episode['scenes'] = json_decode($episode['scenes'], true);
  542. // foreach($episode['scenes'] as &$item) {
  543. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  544. // }
  545. // 获取分镜信息
  546. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  547. ->select('*')->get()->map(function ($value) {
  548. return (array)$value;
  549. })->toArray();
  550. // 使用公共方法构建分镜结构
  551. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  552. $episode['acts'] = $segmentsStructure['acts'];
  553. $episode['total_duration'] = $segmentsStructure['total_duration'];
  554. return $episode;
  555. }
  556. public function episodeInfoForAce($data) {
  557. $anime_id = getProp($data, 'anime_id');
  558. $episode_id = getProp($data, 'episode_id');
  559. if (!$anime_id || !$episode_id) {
  560. Utils::throwError('1002:请选择剧集');
  561. }
  562. $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();
  563. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  564. $episode = (array)$episode;
  565. $episode['roles'] = json_decode($episode['roles'], true);
  566. // foreach($episode['roles'] as &$item) {
  567. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  568. // }
  569. $episode['scenes'] = json_decode($episode['scenes'], true);
  570. // foreach($episode['scenes'] as &$item) {
  571. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  572. // }
  573. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  574. // 获取分镜信息
  575. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  576. ->select('*')->get()->map(function ($value) {
  577. return (array)$value;
  578. })->toArray();
  579. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  580. $episode['acts'] = $segmentsStructure['acts'];
  581. $episode['total_duration'] = $segmentsStructure['total_duration'];
  582. // 获取mp_animes表中的视频参数
  583. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  584. $episode['video_params'] = [
  585. 'video_model' => getProp($anime, 'video_model'),
  586. 'video_resolution' => getProp($anime, 'video_resolution'),
  587. 'ratio' => getProp($anime, 'video_ratio'),
  588. ];
  589. return $episode;
  590. }
  591. public function segmentInfo($data) {
  592. $uid = Site::getUid();
  593. $segment_id = getProp($data, 'segment_id');
  594. if (!$segment_id) {
  595. Utils::throwError('1002:请选择分镜');
  596. }
  597. // 获取分镜信息
  598. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  599. // 验证用户权限
  600. if ($segment) {
  601. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  602. if (!$anime) Utils::throwError('20003:权限不足');
  603. }
  604. $result = [
  605. 'segment_id' => getProp($segment, 'segment_id'),
  606. 'segment_number' => getProp($segment, 'segment_number'),
  607. 'segment_content' => getProp($segment, 'segment_content'),
  608. 'description' => getProp($segment, 'description'),
  609. 'composition' => getProp($segment, 'composition'),
  610. 'camera_movement' => getProp($segment, 'camera_movement'),
  611. 'voice_actor' => getProp($segment, 'voice_actor'),
  612. 'dialogue' => getProp($segment, 'dialogue'),
  613. 'frame_type' => getProp($segment, 'frame_type'),
  614. 'scene' => getProp($segment, 'scene'),
  615. 'characters' => getProp($segment, 'characters'),
  616. 'tail_frame' => getProp($segment, 'tail_frame'),
  617. 'emotion' => getProp($segment, 'emotion'),
  618. 'emotion_type' => getProp($segment, 'emotion_type'),
  619. 'gender' => getProp($segment, 'gender'),
  620. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  621. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  622. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  623. 'pitch' => getProp($segment, 'pitch'),
  624. 'voice_name' => getProp($segment, 'voice_name'),
  625. 'voice_type' => getProp($segment, 'voice_type'),
  626. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  627. 'img_url' => getProp($segment, 'img_url'),
  628. 'video_url' => getProp($segment, 'video_url'),
  629. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  630. ];
  631. return $result;
  632. }
  633. public function copyEpisodeVersion($data) {
  634. $episode_id = getProp($data, 'episode_id');
  635. $uid = Site::getUid();
  636. $cpid = Site::getCpid();
  637. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  638. if (!$episode) Utils::throwError('20003:该剧集不存在');
  639. $episode = (array)$episode;
  640. $anime_id = $episode['anime_id'];
  641. $episode_number = $episode['episode_number'];
  642. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  643. $sequence = $count + 1;
  644. unset($episode['id']);
  645. $now = date('Y-m-d H:i:s');
  646. $episode['created_at'] = $now;
  647. $episode['updated_at'] = $now;
  648. $episode['is_default'] = 1;
  649. // 获取版本中含有"(副本"字样的个数
  650. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  651. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  652. $episode['sequence'] = $sequence;
  653. $episode['is_generated'] = 0;
  654. $episode['cpid'] = $cpid;
  655. // 获取ace_mode
  656. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  657. try {
  658. DB::beginTransaction();
  659. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  660. // 新增副本
  661. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  662. if (!$new_episode_id) {
  663. Utils::throwError('20003:创建副本失败!');
  664. }
  665. // 获取分镜数据并准备插入
  666. $segments_for_insert = DB::table('mp_episode_segments')
  667. ->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')
  668. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  669. $item = (array)$item;
  670. $item['episode_id'] = $new_episode_id;
  671. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  672. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  673. return $item;
  674. })->toArray();
  675. // 写入分镜数据
  676. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  677. if (!$boolen2) {
  678. Utils::throwError('20003:写入分镜数据失败!');
  679. }
  680. // 写入对话历史
  681. $records = [
  682. [
  683. 'uid' => $uid,
  684. 'anime_id' => $anime_id,
  685. 'role' => 'user',
  686. 'content' => '创建副本',
  687. 'sequence' => $episode_number,
  688. 'episode_id' => $new_episode_id,
  689. 'created_at' => $now,
  690. 'updated_at' => $now
  691. ],
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'assistant',
  696. 'content' => '好的,已为您创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ]
  702. ];
  703. $boolen3 = DB::table('mp_anime_records')->insert($records);
  704. if (!$boolen3) {
  705. Utils::throwError('20003:对话记录保存失败');
  706. }
  707. }catch (\Exception $e) {
  708. DB::rollBack();
  709. Utils::throwError('20003:'.$e->getMessage());
  710. }
  711. DB::commit();
  712. // 构建与 episodeInfo 方法一致的返回数据结构
  713. $result = [
  714. 'episode_id' => $new_episode_id,
  715. 'anime_id' => $anime_id,
  716. 'episode_number' => $episode_number,
  717. 'title' => $episode['title'],
  718. 'intro' => $episode['intro'],
  719. 'art_style' => $episode['art_style'],
  720. 'roles' => json_decode($episode['roles'], true),
  721. 'scenes' => json_decode($episode['scenes'], true),
  722. 'is_generated' => (int)$episode['is_generated']
  723. ];
  724. if ((int)$ace_mode === 1) {
  725. // 获取分镜信息
  726. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  727. ->select('*')->get()->map(function ($value) {
  728. return (array)$value;
  729. })->toArray();
  730. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  731. }else {
  732. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  733. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  734. }
  735. $result['acts'] = $segmentsStructure['acts'];
  736. $result['total_duration'] = $segmentsStructure['total_duration'];
  737. return $result;
  738. }
  739. public function episodeVersions($data) {
  740. $anime_id = getProp($data, 'anime_id');
  741. $episode_id = getProp($data, 'episode_id');
  742. if (!$anime_id || !$episode_id) {
  743. Utils::throwError('1002:请选择剧集');
  744. }
  745. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  746. $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) {
  747. return (array)$value;
  748. })->toArray();
  749. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  750. foreach($episodes as &$episode) {
  751. $episode['version'] = 'V'.$episode['sequence'];
  752. $episode['roles'] = json_decode($episode['roles'], true);
  753. $episode['scenes'] = json_decode($episode['scenes'], true);
  754. // 获取分镜信息
  755. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  756. ->select('*')->get()->map(function ($value) {
  757. return (array)$value;
  758. })->toArray();
  759. // 使用公共方法构建分镜结构
  760. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  761. $episode['acts'] = $segmentsStructure['acts'];
  762. $episode['total_duration'] = $segmentsStructure['total_duration'];
  763. }
  764. return $episodes;
  765. }
  766. public function bindEpisodeVersion($data) {
  767. $episode_id = getProp($data, 'episode_id');
  768. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  769. if (!$episode) Utils::throwError('20003:该剧集不存在');
  770. $episode = (array)$episode;
  771. if ((int)$episode['is_default'] === 1) return true;
  772. try {
  773. DB::beginTransaction();
  774. // 移除is_default标志
  775. $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')]);
  776. if (!$boolen) {
  777. Utils::throwError('20003:更新失败!');
  778. }
  779. // 绑定副本
  780. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  781. if (!$boolen2) {
  782. Utils::throwError('20003:绑定失败!');
  783. }
  784. }catch (\Exception $e) {
  785. DB::rollBack();
  786. Utils::throwError('20003:'.$e->getMessage());
  787. }
  788. DB::commit();
  789. return true;
  790. }
  791. public function chatChangeImg($data) {
  792. $segment_id = getProp($data, 'segment_id');
  793. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  794. $prompt = getProp($data, 'prompt');
  795. if (!$prompt || !$segment_id) {
  796. Utils::throwError('1002:请输入提示词,并且选择分镜');
  797. }
  798. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  799. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  800. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  801. else $ref_img_url = '';
  802. // $ref_img_url = '';
  803. if (empty($prompt)) {
  804. if (empty($ref_img_url)) {
  805. $prompt = getProp($segment, 'segment_content');
  806. }else {
  807. $prompt = '请根据图片生成';
  808. }
  809. }
  810. $anime_id = getProp($segment, 'anime_id');
  811. $episode_id = getProp($segment, 'episode_id');
  812. $episode_number = getProp($segment, 'episode_number');
  813. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  814. $ratio = getProp($data, 'ratio');
  815. if (!$ratio) {
  816. $ratio = getProp($episode, 'ratio');
  817. if (!$ratio) $ratio = '9:16';
  818. }
  819. $art_style = getProp($episode, 'art_style');
  820. if ($art_style) {
  821. $prompt = "美术风格:{$art_style}\n{$prompt}";
  822. }
  823. $dimensions = $this->getRatioDimensions($ratio);
  824. $width = $dimensions['width'];
  825. $height = $dimensions['height'];
  826. try {
  827. $params = [
  828. 'alias_segment_id' => $segment_id,
  829. 'prompt' => $prompt,
  830. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  831. 'width' => $width,
  832. 'height' => $height
  833. ];
  834. // 优化提示词(不要生成字幕)
  835. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  836. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  837. $task_id = $task->id;
  838. if (!$task_id) {
  839. Utils::throwError("20003:生成图片失败");
  840. }
  841. // 更新任务ID
  842. $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')]);
  843. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  844. } catch (\Exception $e) {
  845. Utils::throwError("20003:" . $e->getMessage());
  846. }
  847. // 创建任务之后先暂停10s等待异步任务完成
  848. sleep(10);
  849. $img_url = $this->loopGetPicTaskResult($task_id);
  850. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  851. // 图片生成后新增对话记录
  852. try {
  853. $uid = Site::getUid();
  854. $now = date('Y-m-d H:i:s');
  855. // 使用AI反推图片提示词
  856. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  857. // 保存对话记录
  858. $records = [
  859. [
  860. 'uid' => $uid,
  861. 'anime_id' => $anime_id,
  862. 'sequence' => $episode_number,
  863. 'role' => 'user',
  864. 'content' => $prompt,
  865. 'segment_id' => $segment_id,
  866. 'pic_task_id' => $task_id,
  867. 'image_url' => '',
  868. 'created_at' => $now,
  869. 'updated_at' => $now
  870. ],
  871. [
  872. 'uid' => $uid,
  873. 'anime_id' => $anime_id,
  874. 'sequence' => $episode_number,
  875. 'role' => 'assistant',
  876. 'content' => $pic_prompt,
  877. 'segment_id' => $segment_id,
  878. 'pic_task_id' => $task_id,
  879. 'image_url' => $img_url,
  880. 'created_at' => $now,
  881. 'updated_at' => $now
  882. ]
  883. ];
  884. DB::table('mp_anime_records')->insert($records);
  885. } catch (\Exception $e) {
  886. // 记录日志但不影响主流程
  887. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  888. 'segment_id' => $segment_id,
  889. 'img_url' => $img_url
  890. ]);
  891. logDB('anime', 'error', '保存对话记录失败', [
  892. 'segment_id' => $segment_id,
  893. 'img_url' => $img_url,
  894. 'error' => $e->getMessage()
  895. ]);
  896. }
  897. return $img_url;
  898. }
  899. public function segmentChatHistory($data) {
  900. $segment_id = getProp($data, 'segment_id');
  901. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  902. $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');
  903. $chat = $query->orderBy('id')->get()->map(function ($value) {
  904. $value = (array)$value;
  905. $value['created_at'] = transDate($value['created_at']);
  906. return $value;
  907. })->toArray();
  908. // 获取历史图片
  909. $url = [];
  910. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  911. foreach($pic_history as $task) {
  912. $result_url = getProp($task, 'result_url');
  913. if (is_json($result_url)) {
  914. $url = array_merge($url, json_decode($result_url, true));
  915. }else {
  916. $url[] = $result_url;
  917. }
  918. }
  919. // 获取历史视频
  920. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($video_history as $task) {
  922. $result_url = getProp($task, 'compressed_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. return compact('chat', 'url');
  930. }
  931. public function changeEpisodeRoles($data) {
  932. $anime_id = getProp($data, 'anime_id');
  933. $episode_id = getProp($data, 'episode_id');
  934. $target_roles = getProp($data, 'roles');
  935. $is_deleted = getProp($data, 'is_deleted', 0);
  936. // 参数验证
  937. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  938. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  939. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  940. // 验证剧集是否存在
  941. $episode = DB::table('mp_anime_episodes')
  942. ->where('anime_id', $anime_id)
  943. ->where('id', $episode_id)
  944. ->first();
  945. if (!$episode) Utils::throwError('20003:该剧集不存在');
  946. $roles = json_decode(getProp($episode, 'roles'), true);
  947. // 获取anime信息,检查是否有关联的script_id
  948. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  949. if (!$anime) Utils::throwError('20003:动漫不存在');
  950. $script_id = getProp($anime, 'script_id');
  951. $episode_number = getProp($episode, 'episode_number', 1);
  952. $uid = Site::getUid();
  953. $cpid = Site::getCpid();
  954. try {
  955. $target_role_name = getProp($target_roles, 'role');
  956. if (empty($target_role_name)) {
  957. Utils::throwError('20003:角色名称不能为空');
  958. }
  959. // 如果是删除操作
  960. if ($is_deleted == 1) {
  961. // 从角色列表中移除该角色
  962. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  963. return getProp($role, 'role') !== $target_role_name;
  964. }));
  965. // 更新角色列表
  966. $result = DB::table('mp_anime_episodes')
  967. ->where('anime_id', $anime_id)
  968. ->where('id', $episode_id)
  969. ->update([
  970. 'roles' => json_encode($roles, 256),
  971. 'updated_at' => date('Y-m-d H:i:s')
  972. ]);
  973. if ($result === false) {
  974. Utils::throwError('20003:删除角色失败');
  975. }
  976. } else {
  977. // 新增或更新操作
  978. $role_found = false;
  979. $is_new_role = false;
  980. // 查找并更新已存在的角色
  981. foreach($roles as &$role) {
  982. if (getProp($role, 'role') === $target_role_name) {
  983. $role = $target_roles;
  984. $role_found = true;
  985. break;
  986. }
  987. }
  988. // 如果角色不存在,则新增
  989. if (!$role_found) {
  990. $roles[] = $target_roles;
  991. $is_new_role = true;
  992. }
  993. // 更新角色列表
  994. $result = DB::table('mp_anime_episodes')
  995. ->where('anime_id', $anime_id)
  996. ->where('id', $episode_id)
  997. ->update([
  998. 'roles' => json_encode($roles, 256),
  999. 'updated_at' => date('Y-m-d H:i:s')
  1000. ]);
  1001. if ($result === false) {
  1002. Utils::throwError('20003:更新角色列表失败');
  1003. }
  1004. // 同步更新分镜表中对应主体的音色信息
  1005. $voice_name = getProp($target_roles, 'voice_name');
  1006. $voice_type = getProp($target_roles, 'voice_type');
  1007. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1008. DB::table('mp_episode_segments')
  1009. ->where('anime_id', $anime_id)
  1010. ->where('episode_id', $episode_id)
  1011. ->where('voice_actor', $target_role_name)
  1012. ->update([
  1013. 'voice_name' => $voice_name,
  1014. 'voice_type' => $voice_type,
  1015. 'voice_audio_url' => $voice_audio_url,
  1016. 'updated_at' => date('Y-m-d H:i:s')
  1017. ]);
  1018. // 如果有关联的script_id,则同步到mp_products表
  1019. if ($script_id) {
  1020. // 查询剧本信息
  1021. $script = DB::table('mp_scripts')
  1022. ->where('id', $script_id)
  1023. ->where('is_deleted', 0)
  1024. ->first();
  1025. if ($script) {
  1026. $script_name = $script->script_name ?? 'script_' . $script_id;
  1027. $product_name = getProp($target_roles, 'role');
  1028. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1029. $url = getProp($target_roles, 'url', '');
  1030. $product_type = 1; // 1=角色
  1031. // 查找或创建以script_name命名的文件夹
  1032. $folder = DB::table('mp_products')
  1033. ->where('cpid', $cpid)
  1034. ->where('type', 2) // 文件夹类型
  1035. ->where('product', $product_type) // 角色类型
  1036. ->where('product_name', $script_name)
  1037. ->where('parent_id', 0)
  1038. ->where('is_deleted', 0)
  1039. ->first();
  1040. if (!$folder) {
  1041. // 创建文件夹
  1042. $folder_id = DB::table('mp_products')->insertGetId([
  1043. 'user_id' => $uid,
  1044. 'cpid' => $cpid,
  1045. 'type' => 2, // 文件夹
  1046. 'product' => $product_type, // 角色类型
  1047. 'parent_id' => 0,
  1048. 'level' => 1,
  1049. 'product_name' => $script_name,
  1050. 'sort_order' => time(),
  1051. 'is_deleted' => 0,
  1052. 'created_at' => date('Y-m-d H:i:s'),
  1053. 'updated_at' => date('Y-m-d H:i:s')
  1054. ]);
  1055. } else {
  1056. $folder_id = $folder->id;
  1057. }
  1058. // 查找该文件夹下是否已存在同名资产
  1059. $existing_product = DB::table('mp_products')
  1060. ->where('cpid', $cpid)
  1061. ->where('type', 1) // 资产类型
  1062. ->where('product', $product_type)
  1063. ->where('parent_id', $folder_id)
  1064. ->where('product_name', $product_name)
  1065. ->where('is_deleted', 0)
  1066. ->first();
  1067. if ($existing_product) {
  1068. // 更新已存在的资产
  1069. $updateData = [
  1070. 'pic_task_status' => '生成成功',
  1071. ];
  1072. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1073. if ($url) $updateData['url'] = $url;
  1074. // 处理versions字段
  1075. $versions = getProp($target_roles, 'versions', []);
  1076. if ($versions && is_array($versions)) {
  1077. $updateData['versions'] = json_encode($versions, 256);
  1078. }
  1079. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1080. DB::table('mp_products')
  1081. ->where('id', $existing_product->id)
  1082. ->update($updateData);
  1083. $product_id = $existing_product->id;
  1084. } else {
  1085. // 创建新资产
  1086. $versions = getProp($target_roles, 'versions', []);
  1087. $product_id = DB::table('mp_products')->insertGetId([
  1088. 'user_id' => $uid,
  1089. 'cpid' => $cpid,
  1090. 'type' => 1, // 资产
  1091. 'product' => $product_type, // 角色
  1092. 'parent_id' => $folder_id,
  1093. 'level' => 2,
  1094. 'product_name' => $product_name,
  1095. 'url' => $url,
  1096. 'pic_prompt' => $pic_prompt,
  1097. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1098. 'sort_order' => time(),
  1099. 'is_deleted' => 0,
  1100. 'pic_task_status' => '生成成功',
  1101. 'created_at' => date('Y-m-d H:i:s'),
  1102. 'updated_at' => date('Y-m-d H:i:s')
  1103. ]);
  1104. }
  1105. // 建立或更新绑定关系
  1106. $existing_mapping = DB::table('mp_script_product_mappings')
  1107. ->where('script_id', $script_id)
  1108. ->where('product_id', $product_id)
  1109. ->where('episode_number', $episode_number)
  1110. ->first();
  1111. if (!$existing_mapping) {
  1112. // 创建绑定关系
  1113. DB::table('mp_script_product_mappings')->insert([
  1114. 'script_id' => $script_id,
  1115. 'product_id' => $product_id,
  1116. 'episode_number' => $episode_number,
  1117. 'created_at' => date('Y-m-d H:i:s'),
  1118. 'updated_at' => date('Y-m-d H:i:s')
  1119. ]);
  1120. }
  1121. }
  1122. }
  1123. }
  1124. } catch (\Exception $e) {
  1125. dLog('anime')->error('更新剧集角色失败', [
  1126. 'anime_id' => $anime_id,
  1127. 'episode_id' => $episode_id,
  1128. 'error' => $e->getMessage()
  1129. ]);
  1130. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1131. }
  1132. return true;
  1133. }
  1134. public function changeEpisodeScenes($data) {
  1135. $anime_id = getProp($data, 'anime_id');
  1136. $episode_id = getProp($data, 'episode_id');
  1137. $target_scenes = getProp($data, 'scenes');
  1138. $is_deleted = getProp($data, 'is_deleted', 0);
  1139. // 参数验证
  1140. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1141. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1142. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1143. // 验证剧集是否存在
  1144. $episode = DB::table('mp_anime_episodes')
  1145. ->where('anime_id', $anime_id)
  1146. ->where('id', $episode_id)
  1147. ->first();
  1148. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1149. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1150. // 获取anime信息,检查是否有关联的script_id
  1151. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1152. if (!$anime) Utils::throwError('20003:动漫不存在');
  1153. $script_id = getProp($anime, 'script_id');
  1154. $episode_number = getProp($episode, 'episode_number', 1);
  1155. $uid = Site::getUid();
  1156. $cpid = Site::getCpid();
  1157. try {
  1158. $target_scene_name = getProp($target_scenes, 'scene');
  1159. if (empty($target_scene_name)) {
  1160. Utils::throwError('20003:场景名称不能为空');
  1161. }
  1162. // 如果是删除操作
  1163. if ($is_deleted == 1) {
  1164. // 从场景列表中移除该场景
  1165. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1166. return getProp($scene, 'scene') !== $target_scene_name;
  1167. }));
  1168. // 更新场景列表
  1169. $result = DB::table('mp_anime_episodes')
  1170. ->where('anime_id', $anime_id)
  1171. ->where('id', $episode_id)
  1172. ->update([
  1173. 'scenes' => json_encode($scenes, 256),
  1174. 'updated_at' => date('Y-m-d H:i:s')
  1175. ]);
  1176. if ($result === false) {
  1177. Utils::throwError('20003:删除场景失败');
  1178. }
  1179. } else {
  1180. // 新增或更新操作
  1181. $scene_found = false;
  1182. $is_new_scene = false;
  1183. // 查找并更新已存在的场景
  1184. foreach($scenes as &$scene) {
  1185. if (getProp($scene, 'scene') === $target_scene_name) {
  1186. $scene = $target_scenes;
  1187. $scene_found = true;
  1188. break;
  1189. }
  1190. }
  1191. // 如果场景不存在,则新增
  1192. if (!$scene_found) {
  1193. $scenes[] = $target_scenes;
  1194. $is_new_scene = true;
  1195. }
  1196. // 更新场景列表
  1197. $result = DB::table('mp_anime_episodes')
  1198. ->where('anime_id', $anime_id)
  1199. ->where('id', $episode_id)
  1200. ->update([
  1201. 'scenes' => json_encode($scenes, 256),
  1202. 'updated_at' => date('Y-m-d H:i:s')
  1203. ]);
  1204. if ($result === false) {
  1205. Utils::throwError('20003:更新场景列表失败');
  1206. }
  1207. // 如果有关联的script_id,则同步到mp_products表
  1208. if ($script_id) {
  1209. // 查询剧本信息
  1210. $script = DB::table('mp_scripts')
  1211. ->where('id', $script_id)
  1212. ->where('is_deleted', 0)
  1213. ->first();
  1214. if ($script) {
  1215. $script_name = $script->script_name ?? 'script_' . $script_id;
  1216. $product_name = getProp($target_scenes, 'scene');
  1217. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1218. $url = getProp($target_scenes, 'url', '');
  1219. $product_type = 2; // 2=场景
  1220. // 查找或创建以script_name命名的文件夹
  1221. $folder = DB::table('mp_products')
  1222. ->where('cpid', $cpid)
  1223. ->where('type', 2) // 文件夹类型
  1224. ->where('product', $product_type) // 场景类型
  1225. ->where('product_name', $script_name)
  1226. ->where('parent_id', 0)
  1227. ->where('is_deleted', 0)
  1228. ->first();
  1229. if (!$folder) {
  1230. // 创建文件夹
  1231. $folder_id = DB::table('mp_products')->insertGetId([
  1232. 'user_id' => $uid,
  1233. 'cpid' => $cpid,
  1234. 'type' => 2, // 文件夹
  1235. 'product' => $product_type, // 场景类型
  1236. 'parent_id' => 0,
  1237. 'level' => 1,
  1238. 'product_name' => $script_name,
  1239. 'sort_order' => time(),
  1240. 'is_deleted' => 0,
  1241. 'created_at' => date('Y-m-d H:i:s'),
  1242. 'updated_at' => date('Y-m-d H:i:s')
  1243. ]);
  1244. } else {
  1245. $folder_id = $folder->id;
  1246. }
  1247. // 查找该文件夹下是否已存在同名资产
  1248. $existing_product = DB::table('mp_products')
  1249. ->where('cpid', $cpid)
  1250. ->where('type', 1) // 资产类型
  1251. ->where('product', $product_type)
  1252. ->where('parent_id', $folder_id)
  1253. ->where('product_name', $product_name)
  1254. ->where('is_deleted', 0)
  1255. ->first();
  1256. if ($existing_product) {
  1257. // 更新已存在的资产
  1258. $updateData = [
  1259. 'pic_task_status' => '生成成功'
  1260. ];
  1261. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1262. if ($url) $updateData['url'] = $url;
  1263. // 处理versions字段
  1264. $versions = getProp($target_scenes, 'versions', []);
  1265. if ($versions && is_array($versions)) {
  1266. $updateData['versions'] = json_encode($versions, 256);
  1267. }
  1268. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1269. DB::table('mp_products')
  1270. ->where('id', $existing_product->id)
  1271. ->update($updateData);
  1272. $product_id = $existing_product->id;
  1273. } else {
  1274. // 创建新资产
  1275. $versions = getProp($target_scenes, 'versions', []);
  1276. $product_id = DB::table('mp_products')->insertGetId([
  1277. 'user_id' => $uid,
  1278. 'cpid' => $cpid,
  1279. 'type' => 1, // 资产
  1280. 'product' => $product_type, // 场景
  1281. 'parent_id' => $folder_id,
  1282. 'level' => 2,
  1283. 'product_name' => $product_name,
  1284. 'url' => $url,
  1285. 'pic_prompt' => $pic_prompt,
  1286. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1287. 'sort_order' => time(),
  1288. 'is_deleted' => 0,
  1289. 'pic_task_status' => '生成成功',
  1290. 'created_at' => date('Y-m-d H:i:s'),
  1291. 'updated_at' => date('Y-m-d H:i:s')
  1292. ]);
  1293. }
  1294. // 建立或更新绑定关系
  1295. $existing_mapping = DB::table('mp_script_product_mappings')
  1296. ->where('script_id', $script_id)
  1297. ->where('product_id', $product_id)
  1298. ->where('episode_number', $episode_number)
  1299. ->first();
  1300. if (!$existing_mapping) {
  1301. // 创建绑定关系
  1302. DB::table('mp_script_product_mappings')->insert([
  1303. 'script_id' => $script_id,
  1304. 'product_id' => $product_id,
  1305. 'episode_number' => $episode_number,
  1306. 'created_at' => date('Y-m-d H:i:s'),
  1307. 'updated_at' => date('Y-m-d H:i:s')
  1308. ]);
  1309. }
  1310. }
  1311. }
  1312. }
  1313. } catch (\Exception $e) {
  1314. dLog('anime')->error('更新剧集场景失败', [
  1315. 'anime_id' => $anime_id,
  1316. 'episode_id' => $episode_id,
  1317. 'error' => $e->getMessage()
  1318. ]);
  1319. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1320. }
  1321. return true;
  1322. }
  1323. public function changeEpisodeProps($data) {
  1324. $anime_id = getProp($data, 'anime_id');
  1325. $episode_id = getProp($data, 'episode_id');
  1326. $target_props = getProp($data, 'props');
  1327. $is_deleted = getProp($data, 'is_deleted', 0);
  1328. // 参数验证
  1329. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1330. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1331. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1332. // 验证剧集是否存在
  1333. $episode = DB::table('mp_anime_episodes')
  1334. ->where('anime_id', $anime_id)
  1335. ->where('id', $episode_id)
  1336. ->first();
  1337. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1338. $props = json_decode(getProp($episode, 'props'), true);
  1339. // 获取anime信息,检查是否有关联的script_id
  1340. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1341. if (!$anime) Utils::throwError('20003:动漫不存在');
  1342. $script_id = getProp($anime, 'script_id');
  1343. $episode_number = getProp($episode, 'episode_number', 1);
  1344. $uid = Site::getUid();
  1345. $cpid = Site::getCpid();
  1346. try {
  1347. $target_prop_name = getProp($target_props, 'prop');
  1348. if (empty($target_prop_name)) {
  1349. Utils::throwError('20003:道具名称不能为空');
  1350. }
  1351. // 如果是删除操作
  1352. if ($is_deleted == 1) {
  1353. // 从道具列表中移除该道具
  1354. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1355. return getProp($prop, 'prop') !== $target_prop_name;
  1356. }));
  1357. // 更新道具列表
  1358. $result = DB::table('mp_anime_episodes')
  1359. ->where('anime_id', $anime_id)
  1360. ->where('id', $episode_id)
  1361. ->update([
  1362. 'props' => json_encode($props, 256),
  1363. 'updated_at' => date('Y-m-d H:i:s')
  1364. ]);
  1365. if ($result === false) {
  1366. Utils::throwError('20003:删除道具失败');
  1367. }
  1368. } else {
  1369. // 新增或更新操作
  1370. $prop_found = false;
  1371. $is_new_prop = false;
  1372. // 查找并更新已存在的道具
  1373. foreach($props as &$prop) {
  1374. if (getProp($prop, 'prop') === $target_prop_name) {
  1375. $prop = $target_props;
  1376. $prop_found = true;
  1377. break;
  1378. }
  1379. }
  1380. // 如果道具不存在,则新增
  1381. if (!$prop_found) {
  1382. $props[] = $target_props;
  1383. $is_new_prop = true;
  1384. }
  1385. // 更新道具列表
  1386. $result = DB::table('mp_anime_episodes')
  1387. ->where('anime_id', $anime_id)
  1388. ->where('id', $episode_id)
  1389. ->update([
  1390. 'props' => json_encode($props, 256),
  1391. 'updated_at' => date('Y-m-d H:i:s')
  1392. ]);
  1393. if ($result === false) {
  1394. Utils::throwError('20003:更新道具列表失败');
  1395. }
  1396. // 如果有关联的script_id,则同步到mp_products表
  1397. if ($script_id) {
  1398. // 查询剧本信息
  1399. $script = DB::table('mp_scripts')
  1400. ->where('id', $script_id)
  1401. ->where('is_deleted', 0)
  1402. ->first();
  1403. if ($script) {
  1404. $script_name = $script->script_name ?? 'script_' . $script_id;
  1405. $product_name = getProp($target_props, 'prop');
  1406. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1407. $url = getProp($target_props, 'url', '');
  1408. $product_type = 3; // 3=道具
  1409. // 查找或创建以script_name命名的文件夹
  1410. $folder = DB::table('mp_products')
  1411. ->where('cpid', $cpid)
  1412. ->where('type', 2) // 文件夹类型
  1413. ->where('product', $product_type) // 道具类型
  1414. ->where('product_name', $script_name)
  1415. ->where('parent_id', 0)
  1416. ->where('is_deleted', 0)
  1417. ->first();
  1418. if (!$folder) {
  1419. // 创建文件夹
  1420. $folder_id = DB::table('mp_products')->insertGetId([
  1421. 'user_id' => $uid,
  1422. 'cpid' => $cpid,
  1423. 'type' => 2, // 文件夹
  1424. 'product' => $product_type, // 道具类型
  1425. 'parent_id' => 0,
  1426. 'level' => 1,
  1427. 'product_name' => $script_name,
  1428. 'sort_order' => time(),
  1429. 'is_deleted' => 0,
  1430. 'created_at' => date('Y-m-d H:i:s'),
  1431. 'updated_at' => date('Y-m-d H:i:s')
  1432. ]);
  1433. } else {
  1434. $folder_id = $folder->id;
  1435. }
  1436. // 查找该文件夹下是否已存在同名资产
  1437. $existing_product = DB::table('mp_products')
  1438. ->where('cpid', $cpid)
  1439. ->where('type', 1) // 资产类型
  1440. ->where('product', $product_type)
  1441. ->where('parent_id', $folder_id)
  1442. ->where('product_name', $product_name)
  1443. ->where('is_deleted', 0)
  1444. ->first();
  1445. if ($existing_product) {
  1446. // 更新已存在的资产
  1447. $updateData = [
  1448. 'pic_task_status' => '生成成功'
  1449. ];
  1450. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1451. if ($url) $updateData['url'] = $url;
  1452. // 处理versions字段
  1453. $versions = getProp($target_props, 'versions', []);
  1454. if ($versions && is_array($versions)) {
  1455. $updateData['versions'] = json_encode($versions, 256);
  1456. }
  1457. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1458. DB::table('mp_products')
  1459. ->where('id', $existing_product->id)
  1460. ->update($updateData);
  1461. $product_id = $existing_product->id;
  1462. } else {
  1463. // 创建新资产
  1464. $versions = getProp($target_props, 'versions', []);
  1465. $product_id = DB::table('mp_products')->insertGetId([
  1466. 'user_id' => $uid,
  1467. 'cpid' => $cpid,
  1468. 'type' => 1, // 资产
  1469. 'product' => $product_type, // 道具
  1470. 'parent_id' => $folder_id,
  1471. 'level' => 2,
  1472. 'product_name' => $product_name,
  1473. 'url' => $url,
  1474. 'pic_prompt' => $pic_prompt,
  1475. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1476. 'sort_order' => time(),
  1477. 'is_deleted' => 0,
  1478. 'pic_task_status' => '生成成功',
  1479. 'created_at' => date('Y-m-d H:i:s'),
  1480. 'updated_at' => date('Y-m-d H:i:s')
  1481. ]);
  1482. }
  1483. // 建立或更新绑定关系
  1484. $existing_mapping = DB::table('mp_script_product_mappings')
  1485. ->where('script_id', $script_id)
  1486. ->where('product_id', $product_id)
  1487. ->where('episode_number', $episode_number)
  1488. ->first();
  1489. if (!$existing_mapping) {
  1490. // 创建绑定关系
  1491. DB::table('mp_script_product_mappings')->insert([
  1492. 'script_id' => $script_id,
  1493. 'product_id' => $product_id,
  1494. 'episode_number' => $episode_number,
  1495. 'created_at' => date('Y-m-d H:i:s'),
  1496. 'updated_at' => date('Y-m-d H:i:s')
  1497. ]);
  1498. }
  1499. }
  1500. }
  1501. }
  1502. } catch (\Exception $e) {
  1503. dLog('anime')->error('更新剧集道具失败', [
  1504. 'anime_id' => $anime_id,
  1505. 'episode_id' => $episode_id,
  1506. 'error' => $e->getMessage()
  1507. ]);
  1508. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1509. }
  1510. return true;
  1511. }
  1512. public function editSegment($data) {
  1513. $segment_id = getProp($data, 'segment_id');
  1514. $segment_content = getProp($data, 'segment_content');
  1515. $image_url = getProp($data, 'image_url');
  1516. $video_url = getProp($data, 'video_url');
  1517. // 参数验证
  1518. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1519. // 验证分镜是否存在
  1520. $segment = DB::table('mp_episode_segments')
  1521. ->where('segment_id', $segment_id)
  1522. ->first();
  1523. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1524. $dubTaskId = 0;
  1525. try {
  1526. DB::beginTransaction();
  1527. // 准备更新数据
  1528. $update_data = [
  1529. 'updated_at' => date('Y-m-d H:i:s')
  1530. ];
  1531. if ($segment_content) {
  1532. // 先将segment_content赋值到update_data
  1533. $update_data['segment_content'] = $segment_content;
  1534. // 使用现有方法分析segment_content,提取各个字段
  1535. $this->handleSegmentContent($update_data);
  1536. // 如果有对话内容,创建视频配音合成任务
  1537. $dialogue = getProp($update_data, 'dialogue');
  1538. if (!empty($dialogue)) {
  1539. $now = date('Y-m-d H:i:s');
  1540. $generate_json = [
  1541. 'text' => $dialogue,
  1542. 'role' => getProp($update_data, 'voice_actor'),
  1543. 'voice_type' => getProp($update_data, 'voice_type'),
  1544. 'voice_name' => getProp($update_data, 'voice_name'),
  1545. 'emotion' => getProp($update_data, 'emotion'),
  1546. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1547. 'gender' => getProp($update_data, 'gender'),
  1548. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1549. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1550. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1551. 'pitch' => getProp($update_data, 'pitch', 0),
  1552. ];
  1553. // 插入视频配音合成任务
  1554. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1555. 'alias_segment_id' => $segment_id,
  1556. 'generate_status' => '执行中',
  1557. 'audio_url' => '',
  1558. 'generate_json' => json_encode($generate_json, 256),
  1559. 'created_at' => $now,
  1560. 'updated_at' => $now,
  1561. ]);
  1562. if (!$dubTaskId) {
  1563. Utils::throwError('20003:创建配音任务失败!');
  1564. }
  1565. $update_data['audio_url'] = '';
  1566. } else {
  1567. // dialogue为空时,直接写入默认音频信息
  1568. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1569. $update_data['audio_duration'] = 2.0;
  1570. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1571. }
  1572. }
  1573. if ($image_url) {
  1574. $update_data['img_url'] = $image_url;
  1575. // 同时写入一个简单的图片生成任务
  1576. $pic_task = [
  1577. 'alias_segment_id' => $segment_id,
  1578. 'ref_img_url' => json_encode([]),
  1579. 'status' => 'success',
  1580. 'result_url' => json_encode([$image_url], 256),
  1581. 'model' => '',
  1582. 'created_at' => date('Y-m-d H:i:s'),
  1583. 'updated_at' => date('Y-m-d H:i:s'),
  1584. ];
  1585. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1586. }
  1587. if ($video_url) {
  1588. $update_data['origin_video_url'] = $video_url;
  1589. $compressed_video_url = compressVideo($video_url);
  1590. $update_data['current_type'] = 2;
  1591. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1592. // 同时写入一个简单的视频生成任务
  1593. $video_task = [
  1594. 'alias_segment_id' => $segment_id,
  1595. 'status' => 'success',
  1596. 'result_url' => $update_data['origin_video_url'],
  1597. 'compressed_url' => $update_data['video_url'],
  1598. 'created_at' => date('Y-m-d H:i:s'),
  1599. 'updated_at' => date('Y-m-d H:i:s'),
  1600. ];
  1601. DB::table('mp_generate_video_tasks')->insert($video_task);
  1602. }
  1603. // 更新分镜信息
  1604. $result = DB::table('mp_episode_segments')
  1605. ->where('segment_id', $segment_id)
  1606. ->update($update_data);
  1607. if ($result === false) {
  1608. Utils::throwError('20003:更新分镜剧本失败');
  1609. }
  1610. DB::commit();
  1611. // 如果有创建音频生成任务则调用API
  1612. if ($dubTaskId) {
  1613. // 请求远程服务器执行生成
  1614. $client = new Client(['timeout' => 300, 'verify' => false]);
  1615. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1616. $response = $result->getBody()->getContents();
  1617. $response_arr = json_decode($response, true);
  1618. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1619. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1620. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1621. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1622. Utils::throwError('20003:火山生成音频失败');
  1623. }
  1624. }
  1625. return true;
  1626. } catch (\Exception $e) {
  1627. DB::rollBack();
  1628. dLog('anime')->error('更新分镜剧本失败', [
  1629. 'segment_id' => $segment_id,
  1630. 'error' => $e->getMessage()
  1631. ]);
  1632. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1633. }
  1634. }
  1635. public function batchSetSegmentPics($data) {
  1636. $anime_id = getProp($data, 'anime_id');
  1637. $episode_id = getProp($data, 'episode_id');
  1638. $ratio = getProp($data, 'ratio');
  1639. $dimensions = $this->getRatioDimensions($ratio);
  1640. $width = $dimensions['width'];
  1641. $height = $dimensions['height'];
  1642. if (!$anime_id || !$episode_id) {
  1643. Utils::throwError('1002:请选择剧集');
  1644. }
  1645. // 获取剧集信息
  1646. $episode = DB::table('mp_anime_episodes')
  1647. ->where('anime_id', $anime_id)
  1648. ->where('id', $episode_id)
  1649. ->where('is_default', 1)
  1650. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1651. ->first();
  1652. if (!$episode) {
  1653. Utils::throwError('20003:该剧集不存在');
  1654. }
  1655. $model = getProp($data, 'model');
  1656. if (!$model) {
  1657. $model = getProp($episode, 'image_model');
  1658. if (!$model) {
  1659. // episode表也没有,使用默认值
  1660. $model = 'doubao-seedream-5-0-lite-260128';
  1661. }
  1662. }
  1663. // 验证模型是否在可用模型表中
  1664. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1665. $model = 'doubao-seedream-5-0-lite-260128';
  1666. }
  1667. $roles = json_decode(getProp($episode, 'roles'), true);
  1668. if (!$roles) {
  1669. Utils::throwError('20003:角色信息格式错误');
  1670. }
  1671. // 构建角色名称到参考图的映射
  1672. $role_map = [];
  1673. foreach ($roles as $role) {
  1674. $role_name = getProp($role, 'role');
  1675. $role_url = getProp($role, 'url');
  1676. if (!empty($role_name) && !empty($role_url)) {
  1677. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1678. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1679. // $role_map[$base_name] = $role_url;
  1680. // 同时保存完整名称的映射
  1681. $role_map[$role_name] = $role_url;
  1682. }
  1683. }
  1684. $scenes = json_decode(getProp($episode, 'roles'), true);
  1685. if (!$scenes) {
  1686. Utils::throwError('20003:场景信息格式错误');
  1687. }
  1688. // 构建角色名称到参考图的映射
  1689. $scene_map = [];
  1690. foreach ($scenes as $scene) {
  1691. $scene_name = getProp($scene, 'scene');
  1692. $scene_url = getProp($scene, 'url');
  1693. if (!empty($scene_name) && !empty($scene_url)) {
  1694. $scene_map[$scene_name] = $scene_url;
  1695. }
  1696. }
  1697. // 获取所有分镜信息
  1698. $segments = DB::table('mp_episode_segments')
  1699. ->where('anime_id', $anime_id)
  1700. ->where('episode_id', $episode_id)
  1701. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1702. ->orderBy('segment_number')
  1703. ->get()
  1704. ->toArray();
  1705. if (empty($segments)) {
  1706. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1707. }
  1708. // 保存图片比例
  1709. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1710. $updated_segments = [];
  1711. $failed_segments = [];
  1712. // 批量为每个分镜生成图片任务
  1713. foreach ($segments as $segment) {
  1714. $segment_id = $segment->segment_id;
  1715. $segment_content = $segment->segment_content;
  1716. if (empty($segment_content)) {
  1717. $failed_segments[] = [
  1718. 'segment_id' => $segment_id,
  1719. 'error' => '分镜内容为空'
  1720. ];
  1721. continue;
  1722. }
  1723. try {
  1724. $dubTaskId = 0;
  1725. // 解析分镜内容,提取画面描述作为主要提示词
  1726. $prompt = $segment_content;
  1727. $ref_img_urls = [];
  1728. // 分镜场景
  1729. $scene = getProp($segment, 'scene');
  1730. $matched_scene = '';
  1731. if (isset($scene_map[$scene])) {
  1732. $img_index = count($ref_img_urls) + 1;
  1733. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1734. $ref_img_urls[] = $scene_map[$scene];
  1735. $matched_scene = $scene;
  1736. }
  1737. // 分镜角色
  1738. $characters = getProp($segment, 'characters');
  1739. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1740. $roles = explode(',', $characters);
  1741. // 从分镜内容中提取涉及的角色
  1742. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1743. // 获取匹配角色的参考图
  1744. foreach ($segment_characters as $character) {
  1745. if (isset($role_map[$character])) {
  1746. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1747. $img_index = count($ref_img_urls) + 1;
  1748. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1749. $ref_img_urls[] = $role_map[$character];
  1750. }
  1751. }
  1752. // 如果没有找到匹配的角色参考图,不使用参考图
  1753. if (empty($ref_img_urls)) {
  1754. $ref_img_urls = [];
  1755. }
  1756. // 准备生成任务参数
  1757. $params = [
  1758. 'model' => $model,
  1759. 'alias_segment_id' => $segment_id,
  1760. 'prompt' => $prompt,
  1761. 'ref_img_urls' => $ref_img_urls,
  1762. 'width' => $width,
  1763. 'height' => $height,
  1764. ];
  1765. // 优化提示词(不要生成字幕)
  1766. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1767. // $task_id = mt_rand(100000, 999999);
  1768. // 调用AI图片生成服务
  1769. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1770. $task_id = $task->id;
  1771. if (!$task_id) {
  1772. $failed_segments[] = [
  1773. 'segment_id' => $segment_id,
  1774. 'error' => '创建生成任务失败'
  1775. ];
  1776. continue;
  1777. }
  1778. $update_data = [
  1779. 'pic_task_id' => $task_id,
  1780. 'pic_task_status' => '生成中',
  1781. 'audio_url' => '',
  1782. 'updated_at' => date('Y-m-d H:i:s')
  1783. ];
  1784. // 如果有对话内容,创建视频配音合成任务
  1785. $dialogue = getProp($segment, 'dialogue');
  1786. if (!empty($dialogue)) {
  1787. $now = date('Y-m-d H:i:s');
  1788. $generate_json = [
  1789. 'text' => $dialogue,
  1790. 'role' => getProp($segment, 'voice_actor'),
  1791. 'voice_type' => getProp($segment, 'voice_type'),
  1792. 'voice_name' => getProp($segment, 'voice_name'),
  1793. 'emotion' => getProp($segment, 'emotion'),
  1794. 'emotion_type' => getProp($segment, 'emotion_type'),
  1795. 'gender' => getProp($segment, 'gender'),
  1796. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1797. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1798. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1799. 'pitch' => getProp($segment, 'pitch', 0),
  1800. ];
  1801. // 插入视频配音合成任务
  1802. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1803. 'alias_segment_id' => $segment_id,
  1804. 'generate_status' => '执行中',
  1805. 'audio_url' => '',
  1806. 'generate_json' => json_encode($generate_json, 256),
  1807. 'created_at' => $now,
  1808. 'updated_at' => $now,
  1809. ]);
  1810. if (!$dubTaskId) {
  1811. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1812. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1813. // Utils::throwError('20003:创建配音任务失败!');
  1814. }
  1815. } else {
  1816. // dialogue为空时,直接写入默认音频信息到分镜表
  1817. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1818. $update_data['audio_duration'] = 2.0;
  1819. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1820. }
  1821. // 更新分镜的任务信息
  1822. $update_result = DB::table('mp_episode_segments')
  1823. ->where('segment_id', $segment_id)
  1824. ->update($update_data);
  1825. // 如果是第一集的首帧图片,则存入待更新数组
  1826. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1827. Redis::sadd('anime_first_frame_urls', $segment_id);
  1828. }
  1829. if ($update_result) {
  1830. $updated_segments[] = [
  1831. 'segment_id' => $segment_id,
  1832. 'task_id' => $task_id,
  1833. 'status' => '生成中',
  1834. 'matched_scenes' => $matched_scene,
  1835. 'matched_roles' => $segment_characters,
  1836. 'ref_urls_count' => count($ref_img_urls)
  1837. ];
  1838. } else {
  1839. $failed_segments[] = [
  1840. 'segment_id' => $segment_id,
  1841. 'error' => '更新分镜任务状态失败'
  1842. ];
  1843. }
  1844. if ($dubTaskId) {
  1845. sleep(1);
  1846. // 请求远程服务器执行生成
  1847. $client = new Client(['timeout' => 300, 'verify' => false]);
  1848. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1849. $response = $result->getBody()->getContents();
  1850. $response_arr = json_decode($response, true);
  1851. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1852. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1853. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1854. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1855. }
  1856. }
  1857. } catch (\Exception $e) {
  1858. $failed_segments[] = [
  1859. 'segment_id' => $segment_id,
  1860. 'error' => $e->getMessage()
  1861. ];
  1862. }
  1863. }
  1864. // 更新剧集生成状态
  1865. if (!empty($updated_segments)) {
  1866. DB::table('mp_anime_episodes')
  1867. ->where('id', $episode_id)
  1868. ->update([
  1869. 'is_generated' => 1,
  1870. 'updated_at' => date('Y-m-d H:i:s')
  1871. ]);
  1872. }
  1873. return [
  1874. 'success_count' => count($updated_segments),
  1875. 'failed_count' => count($failed_segments),
  1876. 'success_segments' => $updated_segments,
  1877. 'failed_segments' => $failed_segments,
  1878. 'total_segments' => count($segments)
  1879. ];
  1880. }
  1881. public function reGenerateSegment($data) {
  1882. $segment_id = getProp($data, 'segment_id');
  1883. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1884. $anime_id = getProp($segment, 'anime_id');
  1885. $episode_id = getProp($segment, 'episode_id');
  1886. $episode_number = getProp($segment, 'episode_number');
  1887. $segment_content = getProp($data, 'segment_content');
  1888. $ratio = getProp($data, 'ratio');
  1889. if (!$ratio) {
  1890. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1891. if (!$ratio) $ratio = '9:16';
  1892. }
  1893. $dimensions = $this->getRatioDimensions($ratio);
  1894. $width = $dimensions['width'];
  1895. $height = $dimensions['height'];
  1896. if (!$anime_id || !$episode_id) {
  1897. Utils::throwError('1002:请选择分镜');
  1898. }
  1899. // 使用文生文模型重新解析segment_content
  1900. if (!empty($segment_content)) {
  1901. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1902. }
  1903. // 获取动漫的角色信息(包含参考图)
  1904. $anime = DB::table('mp_animes')
  1905. ->where('id', $anime_id)
  1906. ->select('roles', 'scenes')
  1907. ->first();
  1908. if (!$anime || !$anime->roles) {
  1909. Utils::throwError('20003:未找到角色信息');
  1910. }
  1911. $roles = json_decode($anime->roles, true);
  1912. if (!$roles) {
  1913. Utils::throwError('20003:角色信息格式错误');
  1914. }
  1915. // 构建角色名称到参考图的映射
  1916. $role_map = [];
  1917. foreach ($roles as $role) {
  1918. $role_name = getProp($role, 'role');
  1919. $role_url = getProp($role, 'url');
  1920. if (!empty($role_name) && !empty($role_url)) {
  1921. $role_map[$role_name] = $role_url;
  1922. }
  1923. }
  1924. $scenes = json_decode($anime->scenes, true);
  1925. if (!$scenes) {
  1926. Utils::throwError('20003:角色信息格式错误');
  1927. }
  1928. // 构建角色名称到参考图的映射
  1929. $scene_map = [];
  1930. foreach ($scenes as $scene) {
  1931. $scene_name = getProp($scene, 'scene');
  1932. $scene_url = getProp($scene, 'url');
  1933. if (!empty($scene_name) && !empty($scene_url)) {
  1934. $scene_map[$scene_name] = $scene_url;
  1935. }
  1936. }
  1937. $segment_id = $segment->segment_id;
  1938. $original_segment_content = $segment->segment_content;
  1939. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1940. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1941. if (empty($final_segment_content)) {
  1942. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1943. }
  1944. try {
  1945. $dubTaskId = 0;
  1946. // 分镜剧本数组
  1947. $update_data = [
  1948. 'segment_content' => $final_segment_content,
  1949. 'pic_task_status' => '生成中',
  1950. 'updated_at' => date('Y-m-d H:i:s')
  1951. ];
  1952. // 解析分镜内容,提取画面描述作为主要提示词
  1953. $prompt = $final_segment_content;
  1954. $ref_img_urls = [];
  1955. // 分镜场景
  1956. $scene = getProp($data, 'scene');
  1957. if ($scene) {
  1958. $matched_scene = '';
  1959. if (isset($scene_map[$scene])) {
  1960. $img_index = count($ref_img_urls) + 1;
  1961. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1962. $ref_img_urls[] = $scene_map[$scene];
  1963. $matched_scene = $scene;
  1964. }
  1965. $update_data['scene'] = $scene;
  1966. }
  1967. // 分镜角色
  1968. $characters = getProp($data, 'characters');
  1969. if ($characters) {
  1970. $update_data['characters'] = $characters;
  1971. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1972. $characters = explode(',', $characters);
  1973. // 从分镜内容中提取涉及的角色
  1974. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1975. // 获取匹配角色的参考图
  1976. foreach ($segment_characters as $character) {
  1977. if (isset($role_map[$character])) {
  1978. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1979. $img_index = count($ref_img_urls) + 1;
  1980. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1981. $ref_img_urls[] = $role_map[$character];
  1982. }
  1983. }
  1984. }
  1985. // 如果没有找到匹配的角色参考图,不使用参考图
  1986. if (empty($ref_img_urls)) {
  1987. $ref_img_urls = [];
  1988. }
  1989. // 准备生成任务参数
  1990. $params = [
  1991. 'alias_segment_id' => $segment_id,
  1992. 'prompt' => $prompt,
  1993. 'ref_img_urls' => $ref_img_urls,
  1994. 'width' => $width,
  1995. 'height' => $height,
  1996. ];
  1997. // 优化提示词(不要生成字幕)
  1998. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1999. // 调用AI图片生成服务
  2000. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2001. $task_id = $task->id;
  2002. if (!$task_id) {
  2003. Utils::throwError('20003:创建生成任务失败!');
  2004. }
  2005. $update_data['pic_task_id'] = $task_id;
  2006. // 更新分镜剧本信息
  2007. $this->handleSegmentContent($update_data);
  2008. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2009. if ($segment_content) {
  2010. $dialogue = getProp($update_data, 'dialogue');
  2011. if (!empty($dialogue)) {
  2012. $now = date('Y-m-d H:i:s');
  2013. $generate_json = [
  2014. 'text' => $dialogue,
  2015. 'role' => getProp($update_data, 'voice_actor'),
  2016. 'voice_type' => getProp($update_data, 'voice_type'),
  2017. 'voice_name' => getProp($update_data, 'voice_name'),
  2018. 'emotion' => getProp($update_data, 'emotion'),
  2019. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2020. 'gender' => getProp($update_data, 'gender'),
  2021. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2022. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2023. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2024. 'pitch' => getProp($update_data, 'pitch', 0),
  2025. ];
  2026. // 插入视频配音合成任务
  2027. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2028. 'alias_segment_id' => $segment_id,
  2029. 'generate_status' => '执行中',
  2030. 'audio_url' => '',
  2031. 'generate_json' => json_encode($generate_json, 256),
  2032. 'created_at' => date('Y-m-d H:i:s'),
  2033. 'updated_at' => date('Y-m-d H:i:s'),
  2034. ]);
  2035. if (!$dubTaskId) {
  2036. Utils::throwError('20003:创建配音任务失败!');
  2037. }
  2038. $update_data['audio_url'] = '';
  2039. } else {
  2040. // dialogue为空时,直接写入默认音频信息
  2041. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2042. $update_data['audio_duration'] = 2.0;
  2043. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2044. }
  2045. }
  2046. $boolen = DB::table('mp_episode_segments')
  2047. ->where('segment_id', $segment_id)
  2048. ->update($update_data);
  2049. // 如果是第一集的首帧图片,则存入待更新数组
  2050. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2051. Redis::sadd('anime_first_frame_urls', $segment_id);
  2052. }
  2053. if ($dubTaskId) {
  2054. // 请求远程服务器执行生成
  2055. $client = new Client(['timeout' => 300, 'verify' => false]);
  2056. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2057. $response = $result->getBody()->getContents();
  2058. $response_arr = json_decode($response, true);
  2059. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2060. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2061. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2062. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2063. Utils::throwError('20003:火山生成音频失败');
  2064. }
  2065. }
  2066. } catch (\Exception $e) {
  2067. $failed_segments[] = [
  2068. 'segment_id' => $segment_id,
  2069. 'error' => $e->getMessage()
  2070. ];
  2071. }
  2072. // 创建任务之后先暂停10s等待异步任务完成
  2073. sleep(10);
  2074. $img_url = $this->loopGetPicTaskResult($task_id);
  2075. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2076. // 图片生成后新增对话记录
  2077. try {
  2078. $uid = Site::getUid();
  2079. $now = date('Y-m-d H:i:s');
  2080. // 使用AI反推图片提示词
  2081. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2082. // 保存对话记录
  2083. $records = [
  2084. [
  2085. 'uid' => $uid,
  2086. 'anime_id' => $anime_id,
  2087. 'sequence' => $episode_number,
  2088. 'role' => 'user',
  2089. 'content' => '重新生成',
  2090. 'segment_id' => $segment_id,
  2091. 'pic_task_id' => $task_id,
  2092. 'image_url' => '',
  2093. 'created_at' => $now,
  2094. 'updated_at' => $now
  2095. ],
  2096. [
  2097. 'uid' => $uid,
  2098. 'anime_id' => $anime_id,
  2099. 'sequence' => $episode_number,
  2100. 'role' => 'assistant',
  2101. 'content' => $pic_prompt,
  2102. 'segment_id' => $segment_id,
  2103. 'pic_task_id' => $task_id,
  2104. 'image_url' => $img_url,
  2105. 'created_at' => $now,
  2106. 'updated_at' => $now
  2107. ]
  2108. ];
  2109. DB::table('mp_anime_records')->insert($records);
  2110. } catch (\Exception $e) {
  2111. // 记录日志但不影响主流程
  2112. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2113. 'segment_id' => $segment_id,
  2114. 'img_url' => $img_url
  2115. ]);
  2116. }
  2117. return $img_url;
  2118. }
  2119. public function addSegment($data) {
  2120. $prev_segment_id = getProp($data, 'prev_segment_id');
  2121. $img_url = getProp($data, 'img_url');
  2122. $video_url = getProp($data, 'video_url');
  2123. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2124. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2125. $anime_id = getProp($segment, 'anime_id');
  2126. $episode_id = getProp($segment, 'episode_id');
  2127. $episode_number = getProp($segment, 'episode_number');
  2128. $segment_number = getProp($segment, 'segment_number');
  2129. $new_segment_number = $segment_number + 1;
  2130. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2131. // 分镜剧本数组
  2132. $insert_data = [
  2133. 'anime_id' => $anime_id,
  2134. 'episode_id' => $episode_id,
  2135. 'episode_number' => $episode_number,
  2136. 'act_number' => getProp($segment, 'act_number'),
  2137. 'act_title' => getProp($segment, 'act_title'),
  2138. 'segment_id' => $segment_id,
  2139. 'segment_number' => $new_segment_number,
  2140. 'segment_content' => '',
  2141. 'img_url' => '',
  2142. 'video_url' => '',
  2143. 'created_at' => date('Y-m-d H:i:s'),
  2144. 'updated_at' => date('Y-m-d H:i:s')
  2145. ];
  2146. if ($img_url) $insert_data['img_url'] = $img_url;
  2147. if ($video_url) {
  2148. $insert_data['origin_video_url'] = $video_url;
  2149. $insert_data['current_type'] = 2;
  2150. $compressed_video_url = compressVideo($video_url);
  2151. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2152. }
  2153. try {
  2154. DB::beginTransaction();
  2155. // 先更新序号
  2156. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2157. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2158. if (!$id) {
  2159. Utils::throwError('20003:新增分镜失败!');
  2160. }
  2161. }catch (\Exception $e) {
  2162. DB::rollBack();
  2163. Utils::throwError('20003:'.$e->getMessage());
  2164. }
  2165. DB::commit();
  2166. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2167. $segment = $segment ? (array)$segment : [];
  2168. return $segment;
  2169. // 以下代码暂弃用
  2170. $anime_id = getProp($segment, 'anime_id');
  2171. $episode_id = getProp($segment, 'episode_id');
  2172. $episode_number = getProp($segment, 'episode_number');
  2173. $segment_number = getProp($segment, 'segment_number');
  2174. $segment_content = getProp($data, 'segment_content');
  2175. $img_url = getProp($data, 'img_url');
  2176. $video_url = getProp($data, 'video_url');
  2177. $ratio = getProp($data, 'ratio');
  2178. $dimensions = $this->getRatioDimensions($ratio);
  2179. $width = $dimensions['width'];
  2180. $height = $dimensions['height'];
  2181. if (!$anime_id || !$episode_id) {
  2182. Utils::throwError('1002:请选择分镜');
  2183. }
  2184. // 使用文生文模型重新解析segment_content
  2185. if (!empty($segment_content)) {
  2186. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2187. }
  2188. // 获取动漫的角色信息(包含参考图)
  2189. $anime = DB::table('mp_animes')
  2190. ->where('id', $anime_id)
  2191. ->select('roles', 'scenes')
  2192. ->first();
  2193. if (!$anime || !$anime->roles) {
  2194. Utils::throwError('20003:未找到角色信息');
  2195. }
  2196. $roles = json_decode($anime->roles, true);
  2197. if (!$roles) {
  2198. Utils::throwError('20003:角色信息格式错误');
  2199. }
  2200. // 构建角色名称到参考图的映射
  2201. $role_map = [];
  2202. foreach ($roles as $role) {
  2203. $role_name = getProp($role, 'role');
  2204. $role_url = getProp($role, 'url');
  2205. if (!empty($role_name) && !empty($role_url)) {
  2206. $role_map[$role_name] = $role_url;
  2207. }
  2208. }
  2209. $scenes = json_decode($anime->scenes, true);
  2210. if (!$scenes) {
  2211. Utils::throwError('20003:角色信息格式错误');
  2212. }
  2213. // 构建角色名称到参考图的映射
  2214. $scene_map = [];
  2215. foreach ($scenes as $scene) {
  2216. $scene_name = getProp($scene, 'scene');
  2217. $scene_url = getProp($scene, 'url');
  2218. if (!empty($scene_name) && !empty($scene_url)) {
  2219. $scene_map[$scene_name] = $scene_url;
  2220. }
  2221. }
  2222. $segment_id = $segment->segment_id;
  2223. $original_segment_content = $segment->segment_content;
  2224. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2225. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2226. if (empty($final_segment_content)) {
  2227. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2228. }
  2229. try {
  2230. $dubTaskId = 0;
  2231. DB::beginTransaction();
  2232. $new_segment_number = $segment_number + 1;
  2233. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2234. // 分镜剧本数组
  2235. $insert_data = [
  2236. 'anime_id' => $anime_id,
  2237. 'episode_id' => $episode_id,
  2238. 'episode_number' => $episode_number,
  2239. 'act_number' => getProp($segment, 'act_number'),
  2240. 'act_title' => getProp($segment, 'act_title'),
  2241. 'segment_id' => $segment_id,
  2242. 'segment_number' => $new_segment_number,
  2243. 'segment_content' => $final_segment_content,
  2244. 'img_url' => $img_url,
  2245. 'video_url' => $video_url,
  2246. 'created_at' => date('Y-m-d H:i:s'),
  2247. 'updated_at' => date('Y-m-d H:i:s')
  2248. ];
  2249. // 更新分镜剧本信息
  2250. $this->handleSegmentContent($insert_data);
  2251. // 如果有对话内容,创建视频配音合成任务
  2252. $dialogue = getProp($insert_data, 'dialogue');
  2253. if (!empty($dialogue)) {
  2254. $now = date('Y-m-d H:i:s');
  2255. $generate_json = [
  2256. 'text' => $dialogue,
  2257. 'role' => getProp($insert_data, 'voice_actor'),
  2258. 'voice_type' => getProp($insert_data, 'voice_type'),
  2259. 'voice_name' => getProp($insert_data, 'voice_name'),
  2260. 'emotion' => getProp($insert_data, 'emotion'),
  2261. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2262. 'gender' => getProp($insert_data, 'gender'),
  2263. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2264. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2265. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2266. 'pitch' => getProp($insert_data, 'pitch', 0),
  2267. ];
  2268. // 插入视频配音合成任务
  2269. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2270. 'alias_segment_id' => $segment_id,
  2271. 'generate_status' => '执行中',
  2272. 'audio_url' => '',
  2273. 'generate_json' => json_encode($generate_json, 256),
  2274. 'created_at' => $now,
  2275. 'updated_at' => $now,
  2276. ]);
  2277. if (!$dubTaskId) {
  2278. Utils::throwError('20003:创建配音任务失败!');
  2279. }
  2280. $insert_data['audio_url'] = '';
  2281. } else {
  2282. // dialogue为空时,直接写入默认音频信息
  2283. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2284. $insert_data['audio_duration'] = 2.0;
  2285. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2286. }
  2287. // 如果没有上传图片则使用当前描述进行生成
  2288. if (!$img_url) {
  2289. // 解析分镜内容,提取画面描述作为主要提示词
  2290. $prompt = $final_segment_content;
  2291. $ref_img_urls = [];
  2292. // 分镜场景
  2293. $scene = getProp($insert_data, 'scene');
  2294. if ($scene) {
  2295. $matched_scene = '';
  2296. if (isset($scene_map[$scene])) {
  2297. $img_index = count($ref_img_urls) + 1;
  2298. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2299. $ref_img_urls[] = $scene_map[$scene];
  2300. $matched_scene = $scene;
  2301. }
  2302. $update_data['scene'] = $scene;
  2303. }
  2304. // 分镜角色
  2305. $characters = getProp($insert_data, 'characters');
  2306. if ($characters) {
  2307. $update_data['characters'] = $characters;
  2308. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2309. $characters = explode(',', $characters);
  2310. // 从分镜内容中提取涉及的角色
  2311. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2312. // 获取匹配角色的参考图
  2313. foreach ($segment_characters as $character) {
  2314. if (isset($role_map[$character])) {
  2315. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2316. $img_index = count($ref_img_urls) + 1;
  2317. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2318. $ref_img_urls[] = $role_map[$character];
  2319. }
  2320. }
  2321. }
  2322. // 如果没有找到匹配的角色参考图,不使用参考图
  2323. if (empty($ref_img_urls)) {
  2324. $ref_img_urls = [];
  2325. }
  2326. // 准备生成任务参数
  2327. $params = [
  2328. 'alias_segment_id' => $segment_id,
  2329. 'prompt' => $prompt,
  2330. 'ref_img_urls' => $ref_img_urls,
  2331. 'width' => $width,
  2332. 'height' => $height,
  2333. ];
  2334. // 调用AI图片生成服务
  2335. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2336. $task_id = $task->id;
  2337. // $task_id = 'whatever';
  2338. if (!$task_id) {
  2339. Utils::throwError('20003:创建生成任务失败!');
  2340. }
  2341. $insert_data['pic_task_status'] = '生成中';
  2342. $insert_data['pic_task_id'] = $task_id;
  2343. }
  2344. // 先更新序号
  2345. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2346. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2347. if (!$boolen) {
  2348. Utils::throwError('20003:新增分镜失败!');
  2349. }
  2350. // 如果是第一集的首帧图片,则存入待更新数组
  2351. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2352. Redis::sadd('anime_first_frame_urls', $segment_id);
  2353. }
  2354. if ($dubTaskId) {
  2355. // 请求远程服务器执行生成
  2356. $client = new Client(['timeout' => 300, 'verify' => false]);
  2357. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2358. $response = $result->getBody()->getContents();
  2359. $response_arr = json_decode($response, true);
  2360. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2361. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2362. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2363. Utils::throwError('20003:火山生成音频失败');
  2364. }
  2365. }
  2366. } catch (\Exception $e) {
  2367. DB::rollBack();
  2368. Utils::throwError('20003:'.$e->getMessage());
  2369. }
  2370. DB::commit();
  2371. // 创建任务之后先暂停10s等待异步任务完成
  2372. sleep(10);
  2373. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2374. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2375. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2376. $segment = $segment ? (array)$segment : [];
  2377. return $segment;
  2378. }
  2379. public function copySegment($data) {
  2380. $segment_id = getProp($data, 'segment_id');
  2381. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2382. if (!$segment) Utils::throwError('20003:请选择分镜');
  2383. $anime_id = getProp($segment, 'anime_id');
  2384. $episode_id = getProp($segment, 'episode_id');
  2385. $episode_number = getProp($segment, 'episode_number');
  2386. $segment_number = getProp($segment, 'segment_number');
  2387. $new_segment_id = 0;
  2388. try {
  2389. DB::beginTransaction();
  2390. $segment = (array)$segment;
  2391. unset($segment['id']);
  2392. $segment['segment_number'] += 1;
  2393. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2394. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2395. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2396. // 更新其他分镜序号
  2397. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2398. // 复制分镜
  2399. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2400. if (!$id) {
  2401. Utils::throwError('20003:复制分镜失败');
  2402. }
  2403. }catch (\Exception $e) {
  2404. DB::rollBack();
  2405. Utils::throwError('20003:'.$e->getMessage());
  2406. }
  2407. DB::commit();
  2408. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2409. $segment = $segment ? (array)$segment : [];
  2410. return $segment;
  2411. }
  2412. public function moveSegment($data) {
  2413. $segment_id = getProp($data, 'segment_id');
  2414. $target_segment_id = getProp($data, 'target_segment_id');
  2415. // 获取源分镜信息
  2416. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2417. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2418. // 获取目标分镜信息
  2419. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2420. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2421. $anime_id = getProp($source_segment, 'anime_id');
  2422. $episode_id = getProp($source_segment, 'episode_id');
  2423. $episode_number = getProp($source_segment, 'episode_number');
  2424. $source_segment_number = getProp($source_segment, 'segment_number');
  2425. $target_segment_number = getProp($target_segment, 'segment_number');
  2426. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2427. $target_anime_id = getProp($target_segment, 'anime_id');
  2428. $target_episode_number = getProp($target_segment, 'episode_number');
  2429. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2430. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2431. }
  2432. // 如果源分镜和目标分镜相同,无需移动
  2433. if ($source_segment_number == $target_segment_number) {
  2434. return true;
  2435. }
  2436. try {
  2437. DB::beginTransaction();
  2438. if ($source_segment_number < $target_segment_number) {
  2439. // 向后移动:源分镜移动到目标分镜之后
  2440. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2441. DB::table('mp_episode_segments')
  2442. ->where('anime_id', $anime_id)
  2443. ->where('episode_id', $episode_id)
  2444. ->where('segment_number', '>', $source_segment_number)
  2445. ->where('segment_number', '<=', $target_segment_number)
  2446. ->decrement('segment_number');
  2447. // 2. 将源分镜移动到目标分镜之后
  2448. $new_segment_number = $target_segment_number;
  2449. } else {
  2450. // 向前移动:源分镜移动到目标分镜之后
  2451. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2452. DB::table('mp_episode_segments')
  2453. ->where('anime_id', $anime_id)
  2454. ->where('episode_id', $episode_id)
  2455. ->where('segment_number', '>', $target_segment_number)
  2456. ->where('segment_number', '<', $source_segment_number)
  2457. ->increment('segment_number');
  2458. // 2. 将源分镜移动到目标分镜之后
  2459. $new_segment_number = $target_segment_number + 1;
  2460. }
  2461. // 3. 更新源分镜的序号
  2462. $update_result = DB::table('mp_episode_segments')
  2463. ->where('segment_id', $segment_id)
  2464. ->update([
  2465. 'segment_number' => $new_segment_number,
  2466. 'updated_at' => date('Y-m-d H:i:s')
  2467. ]);
  2468. if (!$update_result) {
  2469. Utils::throwError('20003:更新分镜序号失败');
  2470. }
  2471. DB::commit();
  2472. return true;
  2473. } catch (\Exception $e) {
  2474. DB::rollBack();
  2475. Utils::throwError('20003:' . $e->getMessage());
  2476. }
  2477. }
  2478. public function delSegment($data) {
  2479. $segment_id = getProp($data, 'segment_id');
  2480. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2481. if (!$segment) Utils::throwError('20003:请选择分镜');
  2482. $anime_id = getProp($segment, 'anime_id');
  2483. $episode_id = getProp($segment, 'episode_id');
  2484. $episode_number = getProp($segment, 'episode_number');
  2485. $segment_number = getProp($segment, 'segment_number');
  2486. try {
  2487. DB::beginTransaction();
  2488. // 删除分镜
  2489. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2490. if (!$boolen) {
  2491. Utils::throwError('20003:删除分镜失败');
  2492. }
  2493. // 更新其他分镜序号
  2494. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2495. }catch (\Exception $e) {
  2496. DB::rollBack();
  2497. Utils::throwError('20003:'.$e->getMessage());
  2498. }
  2499. DB::commit();
  2500. return true;
  2501. }
  2502. public function applySegment($data) {
  2503. $segment_id = getProp($data, 'segment_id');
  2504. $url = getProp($data, 'url');
  2505. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2506. if (!$url) Utils::throwError('20003:URL不能为空');
  2507. // 获取URL的文件扩展名
  2508. $urlPath = parse_url($url, PHP_URL_PATH);
  2509. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2510. // 定义图片和视频的扩展名
  2511. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2512. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2513. // 判断是图片还是视频
  2514. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2515. if (in_array($extension, $imageExtensions)) {
  2516. // 图片类型
  2517. $updateData['img_url'] = $url;
  2518. $updateData['current_type'] = 1;
  2519. } elseif (in_array($extension, $videoExtensions)) {
  2520. // 视频类型
  2521. $updateData['video_url'] = $url;
  2522. $updateData['current_type'] = 2;
  2523. } else {
  2524. Utils::throwError('20003:不支持的文件类型');
  2525. }
  2526. // 更新分镜表
  2527. $result = DB::table('mp_episode_segments')
  2528. ->where('segment_id', $segment_id)
  2529. ->update($updateData);
  2530. if (!$result) {
  2531. Utils::throwError('20003:更新分镜失败');
  2532. }
  2533. return true;
  2534. }
  2535. public function segmentHistory($data) {
  2536. $segment_id = getProp($data, 'segment_id');
  2537. // 获取历史图片
  2538. $pics = [];
  2539. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2540. foreach($pic_history as $task) {
  2541. $result_url = getProp($task, 'result_url');
  2542. if (is_json($result_url)) {
  2543. $pics = array_merge($pics, json_decode($result_url, true));
  2544. }else {
  2545. $pics[] = $result_url;
  2546. }
  2547. }
  2548. // 获取历史视频
  2549. $videos = [];
  2550. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2551. foreach($video_history as $task) {
  2552. $result_url = getProp($task, 'result_url');
  2553. if (is_json($result_url)) {
  2554. $videos = array_merge($videos, json_decode($result_url, true));
  2555. }else {
  2556. $videos[] = $result_url;
  2557. }
  2558. }
  2559. return compact('pics', 'videos');
  2560. }
  2561. public function addAct($data) {
  2562. $prev_act_id = getProp($data, 'prev_act_id');
  2563. $act_title = getProp($data, 'act_title', '');
  2564. $act_content = getProp($data, 'act_content', '');
  2565. $act_duration = getProp($data, 'act_duration', 5);
  2566. $video_url = getProp($data, 'video_url');
  2567. // 根据prev_act_id获取记录
  2568. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2569. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2570. $anime_id = getProp($prev_segment, 'anime_id');
  2571. $episode_id = getProp($prev_segment, 'episode_id');
  2572. $episode_number = getProp($prev_segment, 'episode_number');
  2573. $prev_act_number = getProp($prev_segment, 'act_number');
  2574. // 获取新的act_number
  2575. $new_act_number = $prev_act_number + 1;
  2576. try {
  2577. DB::beginTransaction();
  2578. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2579. DB::table('mp_episode_segments')
  2580. ->where('anime_id', $anime_id)
  2581. ->where('episode_id', $episode_id)
  2582. ->where('act_number', '>', $prev_act_number)
  2583. ->increment('act_number');
  2584. // 插入新片段记录
  2585. $insert_data = [
  2586. 'anime_id' => $anime_id,
  2587. 'episode_id' => $episode_id,
  2588. 'episode_number' => $episode_number,
  2589. 'act_number' => $new_act_number,
  2590. 'created_at' => date('Y-m-d H:i:s'),
  2591. 'updated_at' => date('Y-m-d H:i:s')
  2592. ];
  2593. if ($act_title) {
  2594. $insert_data['act_title'] = $act_title;
  2595. }
  2596. if ($act_content) {
  2597. $insert_data['act_content'] = $act_content;
  2598. }
  2599. if ($act_duration) {
  2600. $insert_data['act_duration'] = $act_duration;
  2601. }
  2602. if ($video_url) {
  2603. $insert_data['origin_video_url'] = $video_url;
  2604. $insert_data['current_type'] = 2;
  2605. $compressed_video_url = compressVideo($video_url);
  2606. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2607. }
  2608. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2609. if (!$id) {
  2610. Utils::throwError('20003:新增片段失败!');
  2611. }
  2612. DB::commit();
  2613. }catch (\Exception $e) {
  2614. DB::rollBack();
  2615. Utils::throwError('20003:'.$e->getMessage());
  2616. }
  2617. $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();
  2618. $segment = $segment ? (array)$segment : [];
  2619. return $segment;
  2620. }
  2621. public function editAct($data) {
  2622. $act_id = getProp($data, 'act_id');
  2623. $act_content = getProp($data, 'act_content');
  2624. $act_duration = getProp($data, 'act_duration');
  2625. $act_title = getProp($data, 'act_title');
  2626. $image_url = getProp($data, 'image_url');
  2627. $video_url = getProp($data, 'video_url');
  2628. // 参数验证
  2629. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2630. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2631. $segment = DB::table('mp_episode_segments')
  2632. ->where('id', $act_id)
  2633. ->first();
  2634. if (!$segment) Utils::throwError('20003:该片段不存在');
  2635. try {
  2636. DB::beginTransaction();
  2637. // 准备更新数据
  2638. $update_data = [
  2639. 'updated_at' => date('Y-m-d H:i:s')
  2640. ];
  2641. // 更新act相关字段
  2642. if (!empty($act_content)) {
  2643. $update_data['act_show_content'] = $act_content;
  2644. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2645. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2646. $shot_counter = 0;
  2647. $update_data['act_show_content'] = preg_replace_callback(
  2648. '/【(?:镜头|分镜)(\d+)】/u',
  2649. function($matches) use (&$shot_counter) {
  2650. $shot_counter++;
  2651. return '【镜头' . $shot_counter . '】';
  2652. },
  2653. $update_data['act_show_content']
  2654. );
  2655. }
  2656. if (!empty($act_duration)) {
  2657. $update_data['act_duration'] = $act_duration;
  2658. }
  2659. if (!empty($act_title)) {
  2660. $update_data['act_title'] = $act_title;
  2661. }
  2662. // 处理图片上传
  2663. if ($image_url) {
  2664. $update_data['img_url'] = $image_url;
  2665. $update_data['current_type'] = 1;
  2666. // 同时写入一个图片生成任务记录
  2667. if ($act_id) {
  2668. $pic_task = [
  2669. 'alias_act_id' => $act_id,
  2670. 'ref_img_url' => json_encode([]),
  2671. 'status' => 'success',
  2672. 'result_url' => json_encode([$image_url], 256),
  2673. 'model' => '',
  2674. 'created_at' => date('Y-m-d H:i:s'),
  2675. 'updated_at' => date('Y-m-d H:i:s'),
  2676. ];
  2677. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2678. }
  2679. }
  2680. // 处理视频上传
  2681. if ($video_url) {
  2682. $update_data['origin_video_url'] = $video_url;
  2683. $compressed_video_url = compressVideo($video_url);
  2684. $update_data['current_type'] = 2;
  2685. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2686. // 同时写入一个视频生成任务记录
  2687. if ($act_id) {
  2688. $video_task = [
  2689. 'alias_act_id' => $act_id,
  2690. 'status' => 'success',
  2691. 'result_url' => $update_data['origin_video_url'],
  2692. 'compressed_url' => $update_data['video_url'],
  2693. 'created_at' => date('Y-m-d H:i:s'),
  2694. 'updated_at' => date('Y-m-d H:i:s'),
  2695. ];
  2696. DB::table('mp_generate_video_tasks')->insert($video_task);
  2697. }
  2698. }
  2699. // 更新片段信息
  2700. $result = DB::table('mp_episode_segments')
  2701. ->where('id', $act_id)
  2702. ->update($update_data);
  2703. if ($result === false) {
  2704. Utils::throwError('20003:更新片段失败');
  2705. }
  2706. DB::commit();
  2707. // 返回新复制的记录
  2708. $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();
  2709. $new_segment = (array)$new_segment;
  2710. return $new_segment;
  2711. } catch (\Exception $e) {
  2712. DB::rollBack();
  2713. dLog('anime')->error('更新片段失败', [
  2714. 'act_id' => $act_id,
  2715. 'error' => $e->getMessage()
  2716. ]);
  2717. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2718. }
  2719. }
  2720. public function copyAct($data) {
  2721. $act_id = getProp($data, 'act_id');
  2722. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2723. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2724. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2725. $anime_id = getProp($source_segment, 'anime_id');
  2726. $episode_id = getProp($source_segment, 'episode_id');
  2727. $episode_number = getProp($source_segment, 'episode_number');
  2728. $act_number = getProp($source_segment, 'act_number');
  2729. try {
  2730. DB::beginTransaction();
  2731. // 新act的编号
  2732. $new_act_number = $act_number + 1;
  2733. // 更新后续所有act的act_number
  2734. DB::table('mp_episode_segments')
  2735. ->where('anime_id', $anime_id)
  2736. ->where('episode_id', $episode_id)
  2737. ->where('act_number', '>', $act_number)
  2738. ->increment('act_number');
  2739. // 复制该片段记录
  2740. $segment_data = (array)$source_segment;
  2741. unset($segment_data['id']);
  2742. $segment_data['video_url'] = '';
  2743. $segment_data['video_task_id'] = '';
  2744. $segment_data['video_task_status'] = '';
  2745. $segment_data['act_number'] = $new_act_number;
  2746. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2747. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2748. if (!$id) {
  2749. Utils::throwError('20003:复制片段失败');
  2750. }
  2751. DB::commit();
  2752. }catch (\Exception $e) {
  2753. DB::rollBack();
  2754. Utils::throwError('20003:'.$e->getMessage());
  2755. }
  2756. // 返回新复制的记录
  2757. $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();
  2758. $new_segment = $new_segment ? (array)$new_segment : [];
  2759. $new_segment['act_id'] = $id;
  2760. return $new_segment;
  2761. }
  2762. public function moveAct($data) {
  2763. $act_id = getProp($data, 'act_id');
  2764. $target_act_id = getProp($data, 'target_act_id');
  2765. // 获取源片段信息
  2766. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2767. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2768. // 获取目标片段信息
  2769. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2770. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2771. $anime_id = getProp($source_segment, 'anime_id');
  2772. $episode_id = getProp($source_segment, 'episode_id');
  2773. $source_act_number = getProp($source_segment, 'act_number');
  2774. $target_act_number = getProp($target_segment, 'act_number');
  2775. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2776. $target_anime_id = getProp($target_segment, 'anime_id');
  2777. $target_episode_id = getProp($target_segment, 'episode_id');
  2778. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2779. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2780. }
  2781. // 如果源片段和目标片段相同,无需移动
  2782. if ($source_act_number == $target_act_number) {
  2783. return true;
  2784. }
  2785. try {
  2786. DB::beginTransaction();
  2787. if ($source_act_number < $target_act_number) {
  2788. // 向后移动:源片段移动到目标片段之后
  2789. // 1. 将源片段和目标片段之间的所有片段编号减1
  2790. DB::table('mp_episode_segments')
  2791. ->where('anime_id', $anime_id)
  2792. ->where('episode_id', $episode_id)
  2793. ->where('act_number', '>', $source_act_number)
  2794. ->where('act_number', '<=', $target_act_number)
  2795. ->decrement('act_number');
  2796. // 2. 将源片段移动到目标片段之后
  2797. $new_act_number = $target_act_number;
  2798. } else {
  2799. // 向前移动:源片段移动到目标片段之后
  2800. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2801. DB::table('mp_episode_segments')
  2802. ->where('anime_id', $anime_id)
  2803. ->where('episode_id', $episode_id)
  2804. ->where('act_number', '>', $target_act_number)
  2805. ->where('act_number', '<', $source_act_number)
  2806. ->increment('act_number');
  2807. // 2. 将源片段移动到目标片段之后
  2808. $new_act_number = $target_act_number + 1;
  2809. }
  2810. // 3. 更新源片段的编号
  2811. $update_result = DB::table('mp_episode_segments')
  2812. ->where('id', $act_id)
  2813. ->update([
  2814. 'act_number' => $new_act_number,
  2815. 'updated_at' => date('Y-m-d H:i:s')
  2816. ]);
  2817. if (!$update_result) {
  2818. Utils::throwError('20003:更新片段编号失败');
  2819. }
  2820. DB::commit();
  2821. return true;
  2822. } catch (\Exception $e) {
  2823. DB::rollBack();
  2824. Utils::throwError('20003:' . $e->getMessage());
  2825. }
  2826. }
  2827. public function delAct($data) {
  2828. $act_id = getProp($data, 'act_id');
  2829. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2830. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2831. if (!$segment) Utils::throwError('20003:请选择片段');
  2832. $anime_id = getProp($segment, 'anime_id');
  2833. $episode_id = getProp($segment, 'episode_id');
  2834. $act_number = getProp($segment, 'act_number');
  2835. try {
  2836. DB::beginTransaction();
  2837. // 删除该片段记录
  2838. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2839. if (!$deleted) {
  2840. Utils::throwError('20003:删除片段失败');
  2841. }
  2842. // 更新后续act的编号
  2843. DB::table('mp_episode_segments')
  2844. ->where('anime_id', $anime_id)
  2845. ->where('episode_id', $episode_id)
  2846. ->where('act_number', '>', $act_number)
  2847. ->decrement('act_number');
  2848. DB::commit();
  2849. }catch (\Exception $e) {
  2850. DB::rollBack();
  2851. Utils::throwError('20003:'.$e->getMessage());
  2852. }
  2853. return true;
  2854. }
  2855. public function applyAct($data) {
  2856. $act_id = getProp($data, 'act_id');
  2857. $url = getProp($data, 'url');
  2858. if (!$act_id) Utils::throwError('20003:请选择片段');
  2859. if (!$url) Utils::throwError('20003:URL不能为空');
  2860. // 获取URL的文件扩展名
  2861. $urlPath = parse_url($url, PHP_URL_PATH);
  2862. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2863. // 定义图片和视频的扩展名
  2864. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2865. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2866. // 判断是图片还是视频
  2867. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2868. if (in_array($extension, $imageExtensions)) {
  2869. // 图片类型
  2870. $updateData['img_url'] = $url;
  2871. $updateData['current_type'] = 1;
  2872. } elseif (in_array($extension, $videoExtensions)) {
  2873. // 视频类型
  2874. $updateData['video_url'] = $url;
  2875. $updateData['current_type'] = 2;
  2876. } else {
  2877. Utils::throwError('20003:不支持的文件类型');
  2878. }
  2879. // 更新片段记录(全能模式下每个act只有一条记录)
  2880. $result = DB::table('mp_episode_segments')
  2881. ->where('id', $act_id)
  2882. ->update($updateData);
  2883. if (!$result) {
  2884. Utils::throwError('20003:更新片段失败');
  2885. }
  2886. return true;
  2887. }
  2888. public function actChatHistory($data) {
  2889. $act_id = getProp($data, 'act_id');
  2890. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2891. $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');
  2892. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2893. $value = (array)$value;
  2894. $value['created_at'] = transDate($value['created_at']);
  2895. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2896. else $value['reference_images'] = [];
  2897. return $value;
  2898. })->toArray();
  2899. // 获取历史图片
  2900. $url = [];
  2901. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2902. foreach($pic_history as $task) {
  2903. $result_url = getProp($task, 'result_url');
  2904. if (is_json($result_url)) {
  2905. $url = array_merge($url, json_decode($result_url, true));
  2906. }else {
  2907. $url[] = $result_url;
  2908. }
  2909. }
  2910. // 获取历史视频
  2911. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2912. foreach($video_history as $task) {
  2913. $result_url = getProp($task, 'result_url');
  2914. if (is_json($result_url)) {
  2915. $url = array_merge($url, json_decode($result_url, true));
  2916. }else {
  2917. $url[] = $result_url;
  2918. }
  2919. }
  2920. // 获取资产库
  2921. $products = [];
  2922. // 通过act_id查询片段信息获取episode_id
  2923. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2924. if ($segment) {
  2925. $episode_id = getProp($segment, 'episode_id');
  2926. // 查询剧集信息获取roles、scenes和extra_products
  2927. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2928. if ($episode) {
  2929. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2930. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2931. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2932. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2933. // 先合并roles、scenes和props
  2934. // 处理角色数组
  2935. foreach ($roles as $role) {
  2936. $product = $role;
  2937. // 将role字段重命名为product_name
  2938. if (is_array($product) && !empty($product['role'] ?? null)) {
  2939. $product['product_name'] = $product['role'];
  2940. unset($product['role']);
  2941. $product['product'] = 1; // 标记类型为角色
  2942. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2943. }
  2944. }
  2945. // 处理场景数组
  2946. foreach ($scenes as $scene) {
  2947. $product = $scene;
  2948. // 将scene字段重命名为product_name
  2949. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2950. $product['product_name'] = $product['scene'];
  2951. unset($product['scene']);
  2952. $product['product'] = 2; // 标记类型为场景
  2953. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2954. }
  2955. }
  2956. // 处理道具数组
  2957. foreach ($props as $prop) {
  2958. $product = $prop;
  2959. // 将prop字段重命名为product_name
  2960. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2961. $product['product_name'] = $product['prop'];
  2962. unset($product['prop']);
  2963. $product['product'] = 3; // 标记类型为道具
  2964. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2965. }
  2966. }
  2967. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2968. foreach ($extra_products as $extra_product) {
  2969. $product_name = getProp($extra_product, 'product_name');
  2970. if ($product_name) {
  2971. $products[$product_name] = $extra_product; // 覆盖同名数据
  2972. }
  2973. }
  2974. // 重新索引数组(去除key)
  2975. $products = array_values($products);
  2976. }
  2977. }
  2978. // 获取执行中的任务
  2979. $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) {
  2980. $value = (array)$value;
  2981. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2982. else $value['ref_image_url'] = [];
  2983. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2984. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2985. if (!empty($value['prompt'])) {
  2986. $prompt = $value['prompt'];
  2987. // 查找第一个【镜头】的位置
  2988. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2989. // 从【镜头】开始截取
  2990. $prompt = substr($prompt, $matches[0][1]);
  2991. }
  2992. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2993. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2994. $value['prompt'] = $prompt;
  2995. }
  2996. return $value;
  2997. })->toArray();
  2998. return compact('chat', 'url', 'products', 'tasks');
  2999. }
  3000. public function applyAudioData($data) {
  3001. $segment_id = getProp($data, 'segment_id');
  3002. $global_data = getProp($data, 'global_data');
  3003. $segment_data = getProp($data, 'segment_data');
  3004. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3005. $global_data = is_array($global_data) ? $global_data : [];
  3006. $segment_data = is_array($segment_data) ? $segment_data : [];
  3007. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3008. $dialogue_item = null;
  3009. foreach ($global_data as $key => $item) {
  3010. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3011. $dialogue_item = $item;
  3012. unset($global_data[$key]);
  3013. break;
  3014. }
  3015. }
  3016. if ($dialogue_item) {
  3017. $segment_data[] = $dialogue_item;
  3018. }
  3019. // 特殊参数: audio_url,audio_duration,subtitle_info
  3020. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3021. // 如果不是全部存在,则仍需创建音频任务
  3022. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3023. $special_update_data = [];
  3024. $has_all_special_params = false;
  3025. // 从segment_data中提取特殊参数
  3026. $filtered_segment_data = [];
  3027. foreach ($segment_data as $item) {
  3028. $field_name = trim((string)getProp($item, 'name'));
  3029. if (in_array($field_name, $special_fields)) {
  3030. $special_update_data[$field_name] = getProp($item, 'value');
  3031. } else {
  3032. // 非特殊参数保留,继续后续处理
  3033. $filtered_segment_data[] = $item;
  3034. }
  3035. }
  3036. // 检查是否三个特殊参数都存在
  3037. if (count($special_update_data) === 3 &&
  3038. isset($special_update_data['audio_url']) &&
  3039. isset($special_update_data['audio_duration']) &&
  3040. isset($special_update_data['subtitle_info'])) {
  3041. $has_all_special_params = true;
  3042. // 立即更新到当前分镜
  3043. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3044. DB::table('mp_episode_segments')
  3045. ->where('segment_id', $segment_id)
  3046. ->update($special_update_data);
  3047. }
  3048. // 使用过滤后的segment_data继续处理其他参数
  3049. $segment_data = $filtered_segment_data;
  3050. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3051. $global_update_data = [];
  3052. $segment_update_data = [];
  3053. $global_voice_type = '';
  3054. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3055. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3056. $episode_id = getProp($target_segment, 'episode_id');
  3057. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3058. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3059. if (!$episode) Utils::throwError('20003:分集不存在');
  3060. foreach ($global_data as $item) {
  3061. $field_name = trim((string)getProp($item, 'name'));
  3062. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3063. continue;
  3064. }
  3065. $global_update_data[$field_name] = getProp($item, 'value');
  3066. if ($field_name === 'voice_type') {
  3067. $global_voice_type = trim((string)getProp($item, 'value'));
  3068. }
  3069. }
  3070. foreach ($segment_data as $item) {
  3071. $field_name = trim((string)getProp($item, 'name'));
  3072. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3073. continue;
  3074. }
  3075. $segment_update_data[$field_name] = getProp($item, 'value');
  3076. }
  3077. if ($global_voice_type) {
  3078. $timbre_info = DB::table('mp_timbres')
  3079. ->where('timbre_type', $global_voice_type)
  3080. ->select('audio_url', 'timbre_name')
  3081. ->first();
  3082. if ($timbre_info) {
  3083. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3084. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3085. }
  3086. }
  3087. try {
  3088. DB::beginTransaction();
  3089. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3090. $segment_ids_to_create_task = [];
  3091. $segments_data = [];
  3092. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3093. if (!empty($global_update_data)) {
  3094. // 如果角色不存在,则只更新当前分镜
  3095. if (!$target_voice_actor) {
  3096. // 只处理当前分镜
  3097. $affected_segments = DB::table('mp_episode_segments')
  3098. ->where('segment_id', $segment_id)
  3099. ->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')
  3100. ->get();
  3101. } else {
  3102. // 获取该角色的所有分镜
  3103. $affected_segments = DB::table('mp_episode_segments')
  3104. ->where('episode_id', $episode_id)
  3105. ->where('voice_actor', $target_voice_actor)
  3106. ->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')
  3107. ->get();
  3108. }
  3109. foreach ($affected_segments as $seg) {
  3110. $seg = (array)$seg;
  3111. $sid = getProp($seg, 'segment_id');
  3112. // 检查参数是否发生变化
  3113. $has_changed = false;
  3114. foreach ($global_update_data as $field => $new_value) {
  3115. $old_value = getProp($seg, $field);
  3116. if ($old_value != $new_value) {
  3117. $has_changed = true;
  3118. break;
  3119. }
  3120. }
  3121. if ($has_changed) {
  3122. $segment_ids_to_create_task[] = $sid;
  3123. $segments_data[$sid] = $seg;
  3124. }
  3125. }
  3126. // 只有在有变化的分镜时才更新
  3127. if (!empty($segment_ids_to_create_task)) {
  3128. $global_segment_update_data = $global_update_data;
  3129. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3130. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3131. DB::table('mp_episode_segments')
  3132. ->where('episode_id', $episode_id)
  3133. ->where('voice_actor', $target_voice_actor)
  3134. ->whereIn('segment_id', $segment_ids_to_create_task)
  3135. ->update($global_segment_update_data);
  3136. }
  3137. if ($global_voice_type) {
  3138. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3139. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3140. $roles_updated = false;
  3141. foreach ($episode_roles as &$role) {
  3142. // 通过 role 字段匹配角色名,而不是 voice_name
  3143. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3144. continue;
  3145. }
  3146. $role['voice_type'] = $global_voice_type;
  3147. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3148. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3149. $roles_updated = true;
  3150. }
  3151. unset($role);
  3152. if ($roles_updated) {
  3153. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3154. 'roles' => json_encode($episode_roles, 256),
  3155. 'updated_at' => date('Y-m-d H:i:s'),
  3156. ]);
  3157. }
  3158. }
  3159. }
  3160. // 如果有单个分镜更新,检查是否有变化
  3161. if (!empty($segment_update_data)) {
  3162. // 获取当前分镜数据
  3163. $current_segment = DB::table('mp_episode_segments')
  3164. ->where('segment_id', $segment_id)
  3165. ->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')
  3166. ->first();
  3167. if ($current_segment) {
  3168. $current_segment = (array)$current_segment;
  3169. // 检查参数是否发生变化
  3170. $has_changed = false;
  3171. foreach ($segment_update_data as $field => $new_value) {
  3172. $old_value = getProp($current_segment, $field);
  3173. if ($old_value != $new_value) {
  3174. $has_changed = true;
  3175. break;
  3176. }
  3177. }
  3178. if ($has_changed) {
  3179. // 如果该分镜还未在列表中,添加进去
  3180. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3181. $segment_ids_to_create_task[] = $segment_id;
  3182. $segments_data[$segment_id] = $current_segment;
  3183. }
  3184. // 更新分镜数据并清空音频URL
  3185. $segment_update_data['audio_url'] = '';
  3186. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3187. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3188. }
  3189. }
  3190. }
  3191. // 为所有有变化的分镜创建音频合成任务
  3192. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3193. if (!empty($segment_ids_to_create_task)) {
  3194. foreach ($segment_ids_to_create_task as $sid) {
  3195. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3196. if ($sid === $segment_id && $has_all_special_params) {
  3197. continue;
  3198. }
  3199. // 重新获取更新后的分镜数据
  3200. $updated_segment = DB::table('mp_episode_segments')
  3201. ->where('segment_id', $sid)
  3202. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3203. ->first();
  3204. if (!$updated_segment) continue;
  3205. $updated_segment = (array)$updated_segment;
  3206. // 检查dialogue是否为空
  3207. $dialogue = getProp($updated_segment, 'dialogue');
  3208. if (empty($dialogue)) {
  3209. // dialogue为空时,直接写入默认音频信息
  3210. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3211. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3212. 'audio_duration' => 2.0,
  3213. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3214. 'updated_at' => date('Y-m-d H:i:s')
  3215. ]);
  3216. continue;
  3217. }
  3218. $generate_json = [
  3219. 'text' => $dialogue,
  3220. 'role' => getProp($updated_segment, 'voice_actor'),
  3221. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3222. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3223. 'emotion' => getProp($updated_segment, 'emotion'),
  3224. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3225. 'gender' => getProp($updated_segment, 'gender'),
  3226. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3227. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3228. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3229. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3230. ];
  3231. // 插入视频配音合成任务
  3232. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3233. 'alias_segment_id' => $sid,
  3234. 'generate_status' => '执行中',
  3235. 'audio_url' => '',
  3236. 'generate_json' => json_encode($generate_json, 256),
  3237. 'created_at' => date('Y-m-d H:i:s'),
  3238. 'updated_at' => date('Y-m-d H:i:s'),
  3239. ]);
  3240. if (!$dubTaskId) {
  3241. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3242. continue;
  3243. }
  3244. // 将任务ID添加到Redis列表中
  3245. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3246. // 请求远程服务器执行生成
  3247. try {
  3248. sleep(1);
  3249. $client = new Client(['timeout' => 300, 'verify' => false]);
  3250. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3251. $response = $result->getBody()->getContents();
  3252. $response_arr = json_decode($response, true);
  3253. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3254. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3255. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3256. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3257. }
  3258. } catch (\Exception $e) {
  3259. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3260. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3261. }
  3262. }
  3263. }
  3264. DB::commit();
  3265. } catch (\Exception $e) {
  3266. DB::rollBack();
  3267. Utils::throwError('20003:'.$e->getMessage());
  3268. }
  3269. return true;
  3270. }
  3271. public function episodePicsInfo($data) {
  3272. $anime_id = getProp($data, 'anime_id');
  3273. $episode_id = getProp($data, 'episode_id');
  3274. // 参数验证
  3275. if (!$anime_id && !$episode_id) {
  3276. Utils::throwError('20003:请提供动漫ID或分集ID');
  3277. }
  3278. // 根据参数获取数据源
  3279. if ($episode_id) {
  3280. // 从剧集表获取
  3281. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3282. if (!$source) Utils::throwError('20003:该剧集不存在');
  3283. $table_name = 'mp_anime_episodes';
  3284. $id_field = 'id';
  3285. $id_value = $episode_id;
  3286. // 获取剧集的anime_id用于继承全局数据
  3287. $anime_id = getProp($source, 'anime_id');
  3288. } else {
  3289. // 从动漫表获取
  3290. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3291. if (!$source) Utils::throwError('20003:该动漫不存在');
  3292. $table_name = 'mp_animes';
  3293. $id_field = 'id';
  3294. $id_value = $anime_id;
  3295. }
  3296. $source = (array)$source;
  3297. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3298. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3299. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3300. // 如果是分集数据,需要处理继承和任务创建逻辑
  3301. if ($episode_id) {
  3302. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3303. }
  3304. // 返回生成器函数,用于 SSE 流式输出
  3305. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3306. $startTime = time();
  3307. $maxDuration = 600; // 10分钟超时
  3308. $checkInterval = 3; // 每3秒检查一次
  3309. // Redis 缓存键
  3310. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3311. // 生成当前数据的哈希值用于比较
  3312. $generateHash = function($roles, $scenes, $props) {
  3313. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3314. };
  3315. // 发送初始数据
  3316. $currentHash = $generateHash($roles, $scenes, $props);
  3317. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3318. echo "data: " . json_encode([
  3319. 'type' => 'init',
  3320. 'data' => [
  3321. 'roles' => $roles,
  3322. 'scenes' => $scenes,
  3323. 'props' => $props,
  3324. 'start_time' => $startTime
  3325. ]
  3326. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3327. if (ob_get_level() > 0) {
  3328. ob_flush();
  3329. }
  3330. flush();
  3331. // 持续轮询任务状态
  3332. while (time() - $startTime < $maxDuration) {
  3333. $hasProcessing = false;
  3334. $updated = false;
  3335. // 检查角色任务状态
  3336. foreach ($roles as $index => &$role) {
  3337. $task_id = getProp($role, 'task_id');
  3338. $task_status = getProp($role, 'task_status');
  3339. $existing_url = getProp($role, 'url');
  3340. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3341. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3342. $hasProcessing = ($task_status === 'processing');
  3343. // 查询任务状态
  3344. $task = DB::table('mp_generate_pic_tasks')
  3345. ->where('id', $task_id)
  3346. ->select('id', 'status', 'result_url', 'error_message')
  3347. ->first();
  3348. if ($task) {
  3349. $task = (array)$task;
  3350. $status = getProp($task, 'status');
  3351. // 如果任务完成或失败
  3352. if (in_array($status, ['success', 'failed'])) {
  3353. $role['task_status'] = $status;
  3354. if ($status === 'success') {
  3355. $result_url = getProp($task, 'result_url');
  3356. if ($result_url) {
  3357. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3358. if (is_array($result_urls) && !empty($result_urls[0])) {
  3359. $role['url'] = $result_urls[0];
  3360. }
  3361. }
  3362. }
  3363. $updated = true;
  3364. } else if ($status === 'processing') {
  3365. $hasProcessing = true;
  3366. }
  3367. }
  3368. }
  3369. }
  3370. // 检查场景任务状态
  3371. foreach ($scenes as $index => &$scene) {
  3372. $task_id = getProp($scene, 'task_id');
  3373. $task_status = getProp($scene, 'task_status');
  3374. $existing_url = getProp($scene, 'url');
  3375. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3376. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3377. $hasProcessing = ($task_status === 'processing');
  3378. // 查询任务状态
  3379. $task = DB::table('mp_generate_pic_tasks')
  3380. ->where('id', $task_id)
  3381. ->select('id', 'status', 'result_url', 'error_message')
  3382. ->first();
  3383. if ($task) {
  3384. $task = (array)$task;
  3385. $status = getProp($task, 'status');
  3386. // 如果任务完成或失败
  3387. if (in_array($status, ['success', 'failed'])) {
  3388. $scene['task_status'] = $status;
  3389. if ($status === 'success') {
  3390. $result_url = getProp($task, 'result_url');
  3391. if ($result_url) {
  3392. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3393. if (is_array($result_urls) && !empty($result_urls[0])) {
  3394. $scene['url'] = $result_urls[0];
  3395. }
  3396. }
  3397. }
  3398. $updated = true;
  3399. } else if ($status === 'processing') {
  3400. $hasProcessing = true;
  3401. }
  3402. }
  3403. }
  3404. }
  3405. // 检查道具任务状态
  3406. foreach ($props as $index => &$prop) {
  3407. $task_id = getProp($prop, 'task_id');
  3408. $task_status = getProp($prop, 'task_status');
  3409. $existing_url = getProp($prop, 'url');
  3410. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3411. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3412. $hasProcessing = ($task_status === 'processing');
  3413. // 查询任务状态
  3414. $task = DB::table('mp_generate_pic_tasks')
  3415. ->where('id', $task_id)
  3416. ->select('id', 'status', 'result_url', 'error_message')
  3417. ->first();
  3418. if ($task) {
  3419. $task = (array)$task;
  3420. $status = getProp($task, 'status');
  3421. // 如果任务完成或失败
  3422. if (in_array($status, ['success', 'failed'])) {
  3423. $prop['task_status'] = $status;
  3424. if ($status === 'success') {
  3425. $result_url = getProp($task, 'result_url');
  3426. if ($result_url) {
  3427. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3428. if (is_array($result_urls) && !empty($result_urls[0])) {
  3429. $prop['url'] = $result_urls[0];
  3430. }
  3431. }
  3432. }
  3433. $updated = true;
  3434. } else if ($status === 'processing') {
  3435. $hasProcessing = true;
  3436. }
  3437. }
  3438. }
  3439. }
  3440. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3441. if ($updated) {
  3442. $newHash = $generateHash($roles, $scenes, $props);
  3443. $cachedHash = Redis::get($cacheKey);
  3444. // 只有当数据真正变化时才更新数据库和发送事件
  3445. if ($newHash !== $cachedHash) {
  3446. try {
  3447. // 更新数据库
  3448. DB::table($table_name)->where($id_field, $id_value)->update([
  3449. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3450. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3451. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3452. 'updated_at' => date('Y-m-d H:i:s')
  3453. ]);
  3454. // 更新缓存
  3455. Redis::setex($cacheKey, 600, $newHash);
  3456. // 发送更新事件
  3457. echo "data: " . json_encode([
  3458. 'type' => 'update',
  3459. 'data' => [
  3460. 'roles' => $roles,
  3461. 'scenes' => $scenes,
  3462. 'props' => $props,
  3463. 'elapsed_time' => time() - $startTime
  3464. ]
  3465. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3466. if (ob_get_level() > 0) {
  3467. ob_flush();
  3468. }
  3469. flush();
  3470. } catch (\Exception $e) {
  3471. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3472. }
  3473. } else {
  3474. // 即使哈希相同,如果有URL更新也要发送事件
  3475. $hasUrlUpdate = false;
  3476. foreach ($roles as $role) {
  3477. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3478. $hasUrlUpdate = true;
  3479. break;
  3480. }
  3481. }
  3482. if (!$hasUrlUpdate) {
  3483. foreach ($scenes as $scene) {
  3484. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3485. $hasUrlUpdate = true;
  3486. break;
  3487. }
  3488. }
  3489. }
  3490. if (!$hasUrlUpdate) {
  3491. foreach ($props as $prop) {
  3492. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3493. $hasUrlUpdate = true;
  3494. break;
  3495. }
  3496. }
  3497. }
  3498. if ($hasUrlUpdate) {
  3499. // 强制更新数据库和发送事件
  3500. try {
  3501. DB::table($table_name)->where($id_field, $id_value)->update([
  3502. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3503. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3504. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3505. 'updated_at' => date('Y-m-d H:i:s')
  3506. ]);
  3507. // 更新缓存
  3508. Redis::setex($cacheKey, 600, $newHash);
  3509. // 发送更新事件
  3510. echo "data: " . json_encode([
  3511. 'type' => 'update',
  3512. 'data' => [
  3513. 'roles' => $roles,
  3514. 'scenes' => $scenes,
  3515. 'props' => $props,
  3516. 'elapsed_time' => time() - $startTime
  3517. ]
  3518. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3519. if (ob_get_level() > 0) {
  3520. ob_flush();
  3521. }
  3522. flush();
  3523. } catch (\Exception $e) {
  3524. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3525. }
  3526. }
  3527. }
  3528. }
  3529. // 如果所有任务都已完成,发送完成事件并退出
  3530. if (!$hasProcessing) {
  3531. // 查询数据库中的最终数据,确保返回最新的完整数据
  3532. try {
  3533. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3534. if ($finalSource) {
  3535. $finalSource = (array)$finalSource;
  3536. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3537. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3538. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3539. // 使用数据库中的最终数据
  3540. $roles = $finalRoles;
  3541. $scenes = $finalScenes;
  3542. $props = $finalProps;
  3543. }
  3544. } catch (\Exception $e) {
  3545. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3546. // 如果查询失败,继续使用内存中的数据
  3547. }
  3548. // 清理缓存
  3549. Redis::del($cacheKey);
  3550. echo "data: " . json_encode([
  3551. 'type' => 'completed',
  3552. 'data' => [
  3553. 'roles' => $roles,
  3554. 'scenes' => $scenes,
  3555. 'props' => $props,
  3556. 'total_time' => time() - $startTime
  3557. ]
  3558. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3559. if (ob_get_level() > 0) {
  3560. ob_flush();
  3561. }
  3562. flush();
  3563. break;
  3564. }
  3565. // 等待下次检查
  3566. sleep($checkInterval);
  3567. }
  3568. // 超时处理
  3569. if (time() - $startTime >= $maxDuration) {
  3570. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3571. try {
  3572. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3573. if ($finalSource) {
  3574. $finalSource = (array)$finalSource;
  3575. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3576. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3577. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3578. // 使用数据库中的最终数据
  3579. $roles = $finalRoles;
  3580. $scenes = $finalScenes;
  3581. $props = $finalProps;
  3582. }
  3583. } catch (\Exception $e) {
  3584. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3585. // 如果查询失败,继续使用内存中的数据
  3586. }
  3587. // 清理缓存
  3588. Redis::del($cacheKey);
  3589. echo "data: " . json_encode([
  3590. 'type' => 'timeout',
  3591. 'message' => '轮询超时,请刷新页面查看最新状态',
  3592. 'data' => [
  3593. 'roles' => $roles,
  3594. 'scenes' => $scenes,
  3595. 'props' => $props
  3596. ]
  3597. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3598. if (ob_get_level() > 0) {
  3599. ob_flush();
  3600. }
  3601. flush();
  3602. }
  3603. };
  3604. }
  3605. public function clipSegmentVideo($data) {
  3606. $segment_id = getProp($data, 'segment_id');
  3607. $video_time_point_start = getProp($data, 'video_time_point_start');
  3608. $video_time_point_end = getProp($data, 'video_time_point_end');
  3609. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3610. Utils::throwError('20003:参数异常');
  3611. }
  3612. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3613. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3614. }
  3615. $video_duration = $video_time_point_end - $video_time_point_start;
  3616. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3617. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3618. 'video_duration' => $video_duration,
  3619. 'video_time_point_start' => $video_time_point_start,
  3620. 'video_time_point_end' => $video_time_point_end,
  3621. 'updated_at' => date('Y-m-d H:i:s')
  3622. ]);
  3623. }
  3624. // 轮训获取图片任务结果
  3625. private function loopGetPicTaskResult($task_id) {
  3626. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3627. if (!$task) {
  3628. return '';
  3629. }
  3630. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3631. $model = getProp($task, 'model');
  3632. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3633. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3634. $isSyncModel = $isVolcModel || $isGptModel;
  3635. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3636. $start_count = 0;
  3637. $img_url = '';
  3638. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3639. sleep(3);
  3640. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3641. // 如果任务已经完成,直接返回结果
  3642. if ($task->status === 'success' && $task->result_url) {
  3643. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3644. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3645. }
  3646. // 如果任务已失败,返回空
  3647. if ($task->status === 'failed') {
  3648. return '';
  3649. }
  3650. if ($isSyncModel) continue;
  3651. // 查询任务状态
  3652. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3653. if ($statusInfo['status'] === 'success') {
  3654. $task->updateStatus('success', [
  3655. 'result_url' => $statusInfo['result_url'],
  3656. 'result_json' => $statusInfo['result_json'] ?? []
  3657. ]);
  3658. // 同步调整分镜图片状态和结果
  3659. if (getProp($task, 'alias_segment_id')) {
  3660. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3661. 'img_url' => $statusInfo['result_url'][0],
  3662. 'pic_task_status' => '已完成',
  3663. ]);
  3664. }
  3665. $img_url = $statusInfo['result_url'][0];
  3666. break;
  3667. } elseif ($statusInfo['status'] === 'failed') {
  3668. $task->updateStatus('failed', [
  3669. 'error_message' => $statusInfo['error_message'],
  3670. 'result_json' => $statusInfo['result_json'] ?? []
  3671. ]);
  3672. if (getProp($task, 'alias_segment_id')) {
  3673. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3674. 'pic_task_status' => '失败',
  3675. ]);
  3676. }
  3677. break;
  3678. }
  3679. $start_count++;
  3680. }
  3681. return $img_url;
  3682. }
  3683. /**
  3684. * 从分镜内容中提取涉及的角色
  3685. */
  3686. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3687. $found_characters = [];
  3688. foreach ($available_characters as $character) {
  3689. // 检查角色名称是否在分镜内容中出现
  3690. if (strpos($segment_content, $character) !== false) {
  3691. $found_characters[] = $character;
  3692. }
  3693. }
  3694. if (!$found_characters) {
  3695. foreach ($roles as $character) {
  3696. // 检查角色名称是否在分镜内容中出现
  3697. if (strpos($segment_content, $character) !== false) {
  3698. $found_characters[] = $character;
  3699. }
  3700. }
  3701. }
  3702. return array_unique($found_characters);
  3703. }
  3704. // 从分镜剧本中提取关键字段
  3705. private function handleSegmentContent(&$data) {
  3706. $segmentContent = getProp($data, 'segment_content');
  3707. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3708. $segmentData = [
  3709. 'description' => '',
  3710. 'composition' => '',
  3711. 'camera_movement' => '',
  3712. 'voice_actor' => '',
  3713. 'dialogue' => '',
  3714. 'frame_type' => '',
  3715. 'scene' => '', // 场景
  3716. 'characters' => '', // 出镜角色
  3717. 'tail_frame' => '', // 尾帧描述
  3718. 'emotion' => '中性', // 情感
  3719. 'gender' => '0', // 性别(0未知,1男,2女)
  3720. 'speed_ratio' => 0, // 语速
  3721. 'loudness_ratio' => 0, // 音量
  3722. 'emotion_scale' => 4, // 情感强度
  3723. 'pitch' => 0, // 音调
  3724. ];
  3725. // 用于存储需要从 segment_content 中移除的匹配项
  3726. $replaceEmptyArr = [];
  3727. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3728. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3729. $segmentData['description'] = trim($descMatch[1]);
  3730. $data['description'] = trim($descMatch[1]);
  3731. }
  3732. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3733. $segmentData['composition'] = trim($compMatch[1]);
  3734. $data['composition'] = trim($compMatch[1]);
  3735. }
  3736. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3737. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3738. $data['camera_movement'] = trim($cameraMatch[1]);
  3739. }
  3740. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3741. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3742. $data['voice_actor'] = trim($voiceMatch[1]);
  3743. }
  3744. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3745. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3746. $data['dialogue'] = trim($dialogueMatch[1]);
  3747. }
  3748. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3749. $segmentData['frame_type'] = trim($frameMatch[1]);
  3750. $data['frame_type'] = trim($frameMatch[1]);
  3751. }
  3752. // 场景字段
  3753. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3754. $segmentData['scene'] = trim($sceneMatch[1]);
  3755. $data['scene'] = trim($sceneMatch[1]);
  3756. }
  3757. // 出镜角色字段
  3758. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3759. $segmentData['characters'] = trim($charactersMatch[1]);
  3760. $data['characters'] = trim($charactersMatch[1]);
  3761. }
  3762. // 尾帧描述字段
  3763. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3764. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3765. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3766. }
  3767. // 情感字段
  3768. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3769. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3770. $segmentData['emotion'] = trim($emotionMatch[1]);
  3771. $data['emotion'] = trim($emotionMatch[1]);
  3772. }
  3773. // 性别字段
  3774. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3775. $replaceEmptyArr[] = trim($genderMatch[0]);
  3776. $genderStr = trim($genderMatch[1]);
  3777. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3778. $segmentData['gender'] = '1';
  3779. $data['gender'] = '1';
  3780. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3781. $segmentData['gender'] = '2';
  3782. $data['gender'] = '2';
  3783. } else {
  3784. $segmentData['gender'] = '0';
  3785. $data['gender'] = '0';
  3786. }
  3787. }
  3788. // 语速字段
  3789. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3790. $replaceEmptyArr[] = trim($speedMatch[0]);
  3791. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3792. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3793. }
  3794. // 音量字段
  3795. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3796. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3797. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3798. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3799. }
  3800. // 情感强度字段
  3801. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3802. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3803. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3804. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3805. }
  3806. // 音调字段
  3807. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3808. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3809. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3810. $data['pitch'] = (int)trim($pitchMatch[1]);
  3811. }
  3812. // 从 segment_content 中移除已提取的配音参数字段
  3813. if (!empty($replaceEmptyArr)) {
  3814. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3815. }
  3816. // 如果有配音角色,查询音色信息并验证情感
  3817. $voice_actor = $segmentData['voice_actor'];
  3818. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3819. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3820. $anime_id = getProp($data, 'anime_id');
  3821. $episode_id = getProp($data, 'episode_id');
  3822. // 优先从剧集的角色列表中查找
  3823. $roles = [];
  3824. if ($episode_id) {
  3825. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3826. if ($episode && getProp($episode, 'roles')) {
  3827. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3828. }
  3829. }
  3830. // 如果剧集中没有,从动漫的角色列表中查找
  3831. if (empty($roles) && $anime_id) {
  3832. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3833. if ($anime && getProp($anime, 'roles')) {
  3834. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3835. }
  3836. }
  3837. // 查找匹配的角色音色信息
  3838. $timbre_info = null;
  3839. foreach ($roles as $role) {
  3840. if (getProp($role, 'role') === $voice_actor) {
  3841. $timbre_info = $role;
  3842. break;
  3843. }
  3844. }
  3845. // 如果找到音色信息,添加到数据中
  3846. if ($timbre_info) {
  3847. $voice_type = getProp($timbre_info, 'voice_type');
  3848. $voice_name = getProp($timbre_info, 'voice_name');
  3849. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3850. if ($voice_type) {
  3851. $data['voice_type'] = $voice_type;
  3852. $segmentData['voice_type'] = $voice_type;
  3853. }
  3854. if ($voice_name) {
  3855. $data['voice_name'] = $voice_name;
  3856. $segmentData['voice_name'] = $voice_name;
  3857. }
  3858. if ($voice_audio_url) {
  3859. $data['voice_audio_url'] = $voice_audio_url;
  3860. $segmentData['voice_audio_url'] = $voice_audio_url;
  3861. }
  3862. // 验证情感是否在音色支持的情感列表中
  3863. if ($voice_type) {
  3864. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3865. if ($timbre_emotion) {
  3866. $timbre_emotion = explode(',', $timbre_emotion);
  3867. } else {
  3868. $timbre_emotion = [];
  3869. }
  3870. $emotion = getProp($segmentData, 'emotion', '中性');
  3871. if (!in_array($emotion, $timbre_emotion)) {
  3872. $emotion = '中性';
  3873. }
  3874. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3875. $emotion_list = array_flip($emotion_list);
  3876. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3877. $data['emotion_type'] = $emotion_type;
  3878. $segmentData['emotion_type'] = $emotion_type;
  3879. }
  3880. }
  3881. }
  3882. return $segmentData;
  3883. }
  3884. public function createSegmentVideoTask($data) {
  3885. $segment_id = getProp($data, 'segment_id');
  3886. $tail_frame = getProp($data, 'tail_frame');
  3887. $first_frame_url = getProp($data, 'first_frame_url');
  3888. $tail_frame_url = getProp($data, 'tail_frame_url');
  3889. $generate_audio = getProp($data, 'generate_audio', 0);
  3890. if (!$segment_id) {
  3891. Utils::throwError('1002:分镜ID不能为空');
  3892. }
  3893. // 获取分镜信息
  3894. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3895. if (!$segment) {
  3896. Utils::throwError('20003:分镜不存在');
  3897. }
  3898. $segment = (array)$segment;
  3899. $episode_id = getProp($segment, 'episode_id');
  3900. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3901. if (!$ratio) $ratio = '9:16';
  3902. // 获取分镜内容
  3903. $segmentContent = getProp($segment, 'segment_content', '');
  3904. // 检查 $segmentContent 中是否已有尾帧描述
  3905. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3906. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3907. $finalTailFrame = '';
  3908. if ($tail_frame) {
  3909. // 用户输入了尾帧描述,优先使用
  3910. $finalTailFrame = $tail_frame;
  3911. // 如果 segmentContent 中已有尾帧描述,需要替换
  3912. if ($contentHasTailFrame) {
  3913. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3914. }
  3915. } elseif ($contentHasTailFrame) {
  3916. // segmentContent 中有尾帧描述,使用它
  3917. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3918. } else {
  3919. // 两者都没有,使用分镜表中的尾帧描述
  3920. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3921. }
  3922. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3923. $hasDialogue = false;
  3924. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3925. $dialogue = trim($dialogueMatch[1]);
  3926. // 如果台词不为空且不是"无"
  3927. if (!empty($dialogue) && $dialogue !== '无') {
  3928. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3929. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3930. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3931. $hasDialogue = true;
  3932. }
  3933. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3934. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3935. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3936. if (!preg_match('/^[“]/', $dialogue)) {
  3937. $dialogue = '“' . $dialogue;
  3938. }
  3939. if (!preg_match('/[”]$/', $dialogue)) {
  3940. $dialogue .= '”';
  3941. }
  3942. // 将修改后的台词替换回 $segmentContent
  3943. $originalDialogue = $dialogueMatch[1];
  3944. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3945. }
  3946. }
  3947. // 构建完整的提示词
  3948. $fullPrompt = $segmentContent;
  3949. if ($finalTailFrame && !$contentHasTailFrame) {
  3950. // 只有当 segmentContent 中没有尾帧描述时才追加
  3951. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3952. }
  3953. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3954. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3955. $fullPrompt = trim($fullPrompt);
  3956. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3957. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3958. // 智能选择视频时长
  3959. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3960. $videoDuration = -1;
  3961. // 处理视频模型
  3962. $model = getProp($data, 'model');
  3963. if (!$model) {
  3964. // 用户没有输入,从episode表获取
  3965. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3966. $model = getProp($episode, 'video_model');
  3967. if (!$model) {
  3968. // episode表也没有,使用默认值
  3969. $model = 'doubao-seedance-1-5-pro-251215';
  3970. }
  3971. }
  3972. // 验证模型是否在可用模型表中
  3973. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3974. $model = 'doubao-seedance-1-5-pro-251215';
  3975. }
  3976. // 保存到episode表
  3977. $episode_id = getProp($segment, 'episode_id');
  3978. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3979. 'video_model' => $model,
  3980. 'updated_at' => date('Y-m-d H:i:s')
  3981. ]);
  3982. // 构建视频生成参数
  3983. $videoParams = [
  3984. 'model' => $model,
  3985. 'alias_segment_id' => $segment_id,
  3986. 'prompt' => trim($fullPrompt),
  3987. 'video_duration' => $videoDuration,
  3988. 'video_resolution' => '720P',
  3989. 'seed' => -1,
  3990. 'ratio' => $ratio,
  3991. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3992. 'draft' => false,
  3993. 'watermark' => false,
  3994. 'camera_fixed' => false,
  3995. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3996. ];
  3997. // 如果分镜有图片,作为首帧
  3998. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3999. $hasVideo = !empty(getProp($segment, 'video_url'));
  4000. if ($hasImage) {
  4001. if ($first_frame_url) {
  4002. $videoParams['first_frame_url'] = $first_frame_url;
  4003. }else {
  4004. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4005. }
  4006. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4007. }
  4008. // 构建content数组
  4009. $videoParams['content'] = [
  4010. [
  4011. 'type' => 'text',
  4012. 'text' => $videoParams['prompt'],
  4013. ]
  4014. ];
  4015. // 如果有首帧图片,添加到content中
  4016. if ($hasImage) {
  4017. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4018. $videoParams['content'][] = [
  4019. 'type' => 'image_url',
  4020. 'image_url' => [
  4021. 'url' => $videoParams['first_frame_url'],
  4022. ],
  4023. 'role' => 'reference_image',
  4024. ];
  4025. if (isset($videoParams['tail_frame_url'])) {
  4026. $videoParams['content'][] = [
  4027. 'type' => 'image_url',
  4028. 'image_url' => [
  4029. 'url' => $videoParams['tail_frame_url'],
  4030. ],
  4031. 'role' => 'reference_image',
  4032. ];
  4033. }
  4034. }else {
  4035. $videoParams['content'][] = [
  4036. 'type' => 'image_url',
  4037. 'image_url' => [
  4038. 'url' => $videoParams['first_frame_url'],
  4039. ],
  4040. 'role' => 'first_frame',
  4041. ];
  4042. if (isset($videoParams['tail_frame_url'])) {
  4043. $videoParams['content'][] = [
  4044. 'type' => 'image_url',
  4045. 'image_url' => [
  4046. 'url' => $videoParams['tail_frame_url'],
  4047. ],
  4048. 'role' => 'last_frame',
  4049. ];
  4050. }
  4051. }
  4052. }
  4053. // 获取配音音频URL
  4054. $audioUrl = getProp($segment, 'audio_url');
  4055. $audioDuration = getProp($segment, 'audio_duration');
  4056. // 音频传入的前提:必须有至少一张图片或一个视频
  4057. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4058. // 余额预检:按预估时长计算所需积分,不足直接报错
  4059. $chargeDuration = (int)ceil((float)$audioDuration);
  4060. if ($chargeDuration <= 0) {
  4061. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4062. }
  4063. $this->pointsService->checkUserPointsEnough(
  4064. $this->pointsService->getVideoChargePoints([
  4065. 'model' => $model,
  4066. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4067. 'video_duration' => $chargeDuration,
  4068. 'ratio' => $ratio,
  4069. 'generate_audio' => $current_generate_audio,
  4070. ])
  4071. );
  4072. // dd($videoParams);
  4073. // 根据模型选择不同的视频生成方法
  4074. if (strpos($model, 'jimeng') !== false) {
  4075. // 即梦模型参数调整
  4076. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4077. unset($videoParams['content']); // 即梦不使用content格式
  4078. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4079. } elseif (strpos($model, 'kling') !== false) {
  4080. // Keling模型参数调整
  4081. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4082. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4083. unset($videoParams['ratio']);
  4084. unset($videoParams['content']); // Keling不使用content格式
  4085. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4086. } elseif (strpos($model, 'zhizhen') !== false) {
  4087. // 智帧20等新模型使用统一API
  4088. // 构建统一API参数
  4089. $unifiedParams = [
  4090. 'model_code' => $model,
  4091. 'alias_segment_id' => $segment_id,
  4092. 'prompt' => trim($fullPrompt),
  4093. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4094. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4095. 'video_ratio' => $ratio,
  4096. 'seed' => -1,
  4097. ];
  4098. // 构建parameters参数
  4099. $parameters = [
  4100. 'seconds' => $unifiedParams['video_duration'],
  4101. 'resolution' => $unifiedParams['video_resolution'],
  4102. 'ratio' => $ratio,
  4103. // 'video_mode' => 'multi_image',
  4104. // 'mode' => 'multi_image',
  4105. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4106. ];
  4107. $hasImage = false;
  4108. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4109. if ($hasImage) {
  4110. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4111. if (isset($videoParams['tail_frame_url'])) {
  4112. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4113. }
  4114. // 只有在有图片的情况下才能添加参考音频
  4115. if ($audioUrl) {
  4116. // $parameters['reference_audios'] = [$audioUrl];
  4117. }
  4118. } else {
  4119. // 没有图片时,记录错误日志
  4120. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4121. 'segment_id' => $segment_id,
  4122. 'model' => $model
  4123. ]);
  4124. }
  4125. $unifiedParams['parameters'] = $parameters;
  4126. // 调用统一API创建任务
  4127. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4128. } else {
  4129. // Seedance模型(默认)
  4130. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4131. if ($this->isKuaikuaiSeedanceModel($model)) {
  4132. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4133. if ($canUseAudio && $audioUrl) {
  4134. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4135. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4136. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4137. // 优化提示词,增加音频相关描述
  4138. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4139. $videoParams['prompt'] = $audioPrompt;
  4140. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4141. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4142. }
  4143. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4144. } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4145. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4146. // 添加配音音频到content中
  4147. $videoParams['content'][] = [
  4148. 'type' => 'audio_url',
  4149. 'audio_url' => [
  4150. 'url' => $audioUrl,
  4151. ],
  4152. 'role' => 'reference_audio',
  4153. ];
  4154. // 优化提示词,增加音频相关描述
  4155. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4156. $videoParams['prompt'] = $audioPrompt;
  4157. $videoParams['content'][0]['text'] = $audioPrompt;
  4158. } else {
  4159. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4160. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4161. }
  4162. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4163. }
  4164. }
  4165. // 更新分镜表的视频任务信息
  4166. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4167. 'video_task_id' => $task->id,
  4168. 'video_task_status' => '生成中',
  4169. 'generate_audio' => $generate_audio,
  4170. 'updated_at' => date('Y-m-d H:i:s')
  4171. ]);
  4172. return [
  4173. 'task_id' => $task->id,
  4174. 'status' => $task->status,
  4175. 'segment_id' => $segment_id,
  4176. 'video_duration' => $videoDuration
  4177. ];
  4178. }
  4179. /**
  4180. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4181. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4182. *
  4183. * @param string $model
  4184. * @return bool
  4185. */
  4186. private function isKuaikuaiSeedanceModel(string $model): bool
  4187. {
  4188. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4189. }
  4190. public function createActVideoTask($data) {
  4191. $act_id = getProp($data, 'act_id');
  4192. $first_frame_url = getProp($data, 'first_frame_url');
  4193. $tail_frame_url = getProp($data, 'tail_frame_url');
  4194. $generate_audio = getProp($data, 'generate_audio', 1);
  4195. $video_duration = getProp($data, 'video_duration');
  4196. $video_resolution = getProp($data, 'video_resolution');
  4197. $ratio = getProp($data, 'ratio');
  4198. $products = getProp($data, 'products', []);
  4199. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4200. if (!is_array($reference_images) || !is_array($products)) {
  4201. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4202. }
  4203. if (!$act_id) {
  4204. Utils::throwError('1002:片段ID不能为空');
  4205. }
  4206. // 获取片段信息
  4207. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4208. if (!$act) {
  4209. Utils::throwError('20003:片段不存在');
  4210. }
  4211. $act = (array)$act;
  4212. $anime_id = getProp($act, 'anime_id');
  4213. $episode_id = getProp($act, 'episode_id');
  4214. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4215. $ace_mode = getProp($anime, 'ace_mode');
  4216. $art_style_type = getProp($anime, 'art_style_type');
  4217. $art_style = getProp($anime, 'art_style');
  4218. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4219. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4220. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4221. // 将资产中新出现的资产放到extra_products中
  4222. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4223. if (!empty($products) && $episode) {
  4224. // 获取剧集中的角色、场景和道具列表
  4225. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4226. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4227. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4228. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4229. // 构建角色名称列表
  4230. $role_names = array_column($roles, 'role');
  4231. // 构建场景名称列表
  4232. $scene_names = array_column($scenes, 'scene');
  4233. // 构建道具名称列表
  4234. $prop_names = array_column($props, 'prop');
  4235. // 遍历传入的products
  4236. foreach ($products as $product) {
  4237. $product_name = getProp($product, 'product_name');
  4238. // 如果product_name不在roles、scenes和props中
  4239. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4240. // 查找是否在extra_products中存在同名的
  4241. $found = false;
  4242. foreach ($extra_products as $key => $extra_product) {
  4243. if (getProp($extra_product, 'product_name') === $product_name) {
  4244. // 有同名的则覆盖
  4245. $extra_products[$key] = $product;
  4246. $found = true;
  4247. break;
  4248. }
  4249. }
  4250. // 没有则新增
  4251. if (!$found) {
  4252. $extra_products[] = $product;
  4253. }
  4254. }
  4255. }
  4256. if ($extra_products) {
  4257. // 保存到数据库
  4258. DB::table('mp_anime_episodes')
  4259. ->where('id', $episode_id)
  4260. ->update([
  4261. 'extra_products' => json_encode($extra_products, 256),
  4262. 'updated_at' => date('Y-m-d H:i:s')
  4263. ]);
  4264. }
  4265. }
  4266. // 获取分镜内容
  4267. $actContent = getProp($act, 'act_show_content', '');
  4268. // 音效同出(默认使用)
  4269. $current_generate_audio = $generate_audio ? 1 : 0;
  4270. // 构建完整的提示词
  4271. $processResult = $this->processActContentWithProducts($actContent, $products);
  4272. $fullPrompt = $processResult['content'];
  4273. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4274. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4275. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4276. // 处理视频模型
  4277. $model = getProp($data, 'model');
  4278. if (!$model) {
  4279. $model = getProp($episode, 'video_model');
  4280. if (!$model) {
  4281. // episode表也没有,使用默认值
  4282. $model = 'zhizhen-20';
  4283. }
  4284. }
  4285. // 验证模型是否在可用模型表中
  4286. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4287. $model = 'zhizhen-20';
  4288. }
  4289. // 保存到episode表(仅在专用方法中更新模型)
  4290. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4291. // 'video_model' => $model,
  4292. // 'updated_at' => date('Y-m-d H:i:s')
  4293. // ]);
  4294. // 余额预检:按预估时长计算所需积分,不足直接报错
  4295. $chargeDuration = (int)$videoDuration;
  4296. if ($chargeDuration <= 0) {
  4297. $chargeDuration = 5; // 无时长时按默认5秒预估
  4298. }
  4299. $this->pointsService->checkUserPointsEnough(
  4300. $this->pointsService->getVideoChargePoints([
  4301. 'model' => $model,
  4302. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4303. 'video_duration' => $chargeDuration,
  4304. 'ratio' => $ratio,
  4305. 'generate_audio' => $current_generate_audio,
  4306. ])
  4307. );
  4308. // 构建视频生成参数
  4309. $videoParams = [
  4310. 'model' => $model,
  4311. 'alias_act_id' => $act_id,
  4312. 'prompt' => trim($fullPrompt),
  4313. 'video_duration' => $videoDuration,
  4314. 'video_resolution' => $video_resolution,
  4315. 'seed' => -1,
  4316. 'ratio' => $ratio,
  4317. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4318. 'draft' => false,
  4319. 'watermark' => false,
  4320. 'camera_fixed' => false,
  4321. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4322. ];
  4323. // 如果分镜有图片,作为首帧
  4324. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4325. $hasVideo = !empty(getProp($act, 'video_url'));
  4326. if ($hasImage) {
  4327. if ($first_frame_url) {
  4328. $videoParams['first_frame_url'] = $first_frame_url;
  4329. }else {
  4330. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4331. }
  4332. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4333. }
  4334. // 构建content数组
  4335. $videoParams['content'] = [
  4336. [
  4337. 'type' => 'text',
  4338. 'text' => $videoParams['prompt'],
  4339. ]
  4340. ];
  4341. // 如果有首帧图片,添加到content中
  4342. if ($hasImage) {
  4343. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4344. $videoParams['content'][] = [
  4345. 'type' => 'image_url',
  4346. 'image_url' => [
  4347. 'url' => $videoParams['first_frame_url'],
  4348. ],
  4349. 'role' => 'reference_image',
  4350. ];
  4351. if (isset($videoParams['tail_frame_url'])) {
  4352. $videoParams['content'][] = [
  4353. 'type' => 'image_url',
  4354. 'image_url' => [
  4355. 'url' => $videoParams['tail_frame_url'],
  4356. ],
  4357. 'role' => 'reference_image',
  4358. ];
  4359. }
  4360. }else {
  4361. $videoParams['content'][] = [
  4362. 'type' => 'image_url',
  4363. 'image_url' => [
  4364. 'url' => $videoParams['first_frame_url'],
  4365. ],
  4366. 'role' => 'first_frame',
  4367. ];
  4368. if (isset($videoParams['tail_frame_url'])) {
  4369. $videoParams['content'][] = [
  4370. 'type' => 'image_url',
  4371. 'image_url' => [
  4372. 'url' => $videoParams['tail_frame_url'],
  4373. ],
  4374. 'role' => 'last_frame',
  4375. ];
  4376. }
  4377. }
  4378. }
  4379. // dd($videoParams);
  4380. // 根据模型选择不同的视频生成方法
  4381. if (strpos($model, 'jimeng') !== false) {
  4382. // 即梦模型参数调整
  4383. unset($videoParams['content']); // 即梦不使用content格式
  4384. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4385. } elseif (strpos($model, 'kling') !== false) {
  4386. // Keling模型参数调整
  4387. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4388. unset($videoParams['ratio']);
  4389. unset($videoParams['content']); // Keling不使用content格式
  4390. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4391. } elseif (strpos($model, 'zhizhen') !== false) {
  4392. // 智帧20等新模型使用统一API
  4393. // 构建统一API参数
  4394. $unifiedParams = [
  4395. 'model_code' => $model,
  4396. 'alias_act_id' => $act_id,
  4397. 'prompt' => trim($fullPrompt),
  4398. 'video_duration' => $videoDuration,
  4399. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4400. 'video_ratio' => $ratio,
  4401. 'seed' => -1,
  4402. ];
  4403. // 构建parameters参数
  4404. $parameters = [
  4405. 'seconds' => $unifiedParams['video_duration'],
  4406. 'resolution' => $unifiedParams['video_resolution'],
  4407. 'ratio' => $ratio,
  4408. // 'video_mode' => 'multi_image',
  4409. // 'mode' => 'multi_image',
  4410. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4411. ];
  4412. $hasImage = false;
  4413. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4414. if ($hasImage) {
  4415. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4416. if (isset($videoParams['tail_frame_url'])) {
  4417. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4418. }
  4419. } else {
  4420. // 没有图片时,记录错误日志
  4421. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4422. 'act_id' => $act_id,
  4423. 'model' => $model
  4424. ]);
  4425. }
  4426. if ($reference_images) {
  4427. // 限制只传入9张参考图
  4428. $reference_images = array_slice($reference_images, 0, 9);
  4429. // 在处理之前先保存原始reference_images到任务参数中
  4430. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4431. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4432. $parameters['reference_images'] = $reference_images;
  4433. $parameters['video_mode'] = 'multi_image';
  4434. $parameters['mode'] = 'multi_image';
  4435. }
  4436. $unifiedParams['parameters'] = $parameters;
  4437. // 调用统一API创建任务
  4438. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4439. } elseif (strpos($model, 'doubao-seedance-2.0') !== false || $this->isKuaikuaiSeedanceModel($model)) {
  4440. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4441. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4442. // 保存原始参考图用于任务记录
  4443. $videoParams['reference_images'] = $reference_images;
  4444. if ($reference_images) {
  4445. // 限制只传入9张参考图
  4446. $reference_images = array_slice($reference_images, 0, 9);
  4447. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4448. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4449. // 参考图上传为素材(百度网关/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4450. $reference_image_assets = $isKuaikuai
  4451. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4452. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4453. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4454. $videoParams['prompt'] = trim($fullPrompt);
  4455. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4456. $videoParams['reference_image_assets'] = $reference_image_assets;
  4457. }
  4458. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4459. if ($isKuaikuai) {
  4460. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4461. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4462. } else {
  4463. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4464. }
  4465. } else {
  4466. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4467. }
  4468. // 更新分镜表的视频任务信息
  4469. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4470. 'video_task_id' => $task->id,
  4471. 'video_task_status' => '生成中',
  4472. 'generate_audio' => $generate_audio,
  4473. 'updated_at' => date('Y-m-d H:i:s')
  4474. ]);
  4475. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4476. $episode_number = getProp($act, 'episode_number');
  4477. $act_number = getProp($act, 'act_number');
  4478. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4479. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4480. }
  4481. return [
  4482. 'task_id' => $task->id,
  4483. 'status' => $task->status,
  4484. 'act_id' => $act_id,
  4485. 'video_duration' => $videoDuration
  4486. ];
  4487. }
  4488. /**
  4489. * 文生视频通用方法
  4490. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4491. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4492. *
  4493. * @param array $data 请求参数
  4494. * @return array
  4495. */
  4496. public function generateVideo($data) {
  4497. $prompt = getProp($data, 'prompt');
  4498. if (empty($prompt)) {
  4499. Utils::throwError('20003:提示词不能为空');
  4500. }
  4501. $model = getProp($data, 'model');
  4502. if (!$model) {
  4503. $model = 'zhizhen-20';
  4504. }
  4505. // 验证模型是否在可用模型表中
  4506. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4507. Utils::throwError('20003:该模型已不可用,请更换!');
  4508. }
  4509. $video_duration = getProp($data, 'video_duration', 5);
  4510. $video_resolution = getProp($data, 'video_resolution', '480p');
  4511. $ratio = getProp($data, 'ratio', '9:16');
  4512. $generate_audio = getProp($data, 'generate_audio', 1);
  4513. $seed = getProp($data, 'seed', -1);
  4514. $first_frame_url = getProp($data, 'first_frame_url');
  4515. $tail_frame_url = getProp($data, 'tail_frame_url');
  4516. // 参考图(支持数组或JSON字符串,最多9张)
  4517. $reference_images = getProp($data, 'reference_images', []);
  4518. if (is_string($reference_images)) {
  4519. $reference_images = json_decode($reference_images, true) ?: [];
  4520. }
  4521. if (!is_array($reference_images)) {
  4522. Utils::throwError('20003:参考图格式不正确');
  4523. }
  4524. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4525. $reference_images = array_slice($reference_images, 0, 9);
  4526. // 参考视频(支持数组或JSON字符串,最多3个)
  4527. $reference_videos = getProp($data, 'reference_videos', []);
  4528. if (is_string($reference_videos)) {
  4529. $reference_videos = json_decode($reference_videos, true) ?: [];
  4530. }
  4531. if (!is_array($reference_videos)) {
  4532. Utils::throwError('20003:参考视频格式不正确');
  4533. }
  4534. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4535. if (count($reference_videos) > 3) {
  4536. Utils::throwError('20003:参考视频最多选择3个');
  4537. }
  4538. $reference_videos = array_slice($reference_videos, 0, 3);
  4539. // 参考音频(支持数组或JSON字符串,最多3个)
  4540. $reference_audios = getProp($data, 'reference_audios', []);
  4541. if (is_string($reference_audios)) {
  4542. $reference_audios = json_decode($reference_audios, true) ?: [];
  4543. }
  4544. if (!is_array($reference_audios)) {
  4545. Utils::throwError('20003:参考音频格式不正确');
  4546. }
  4547. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4548. if (count($reference_audios) > 3) {
  4549. Utils::throwError('20003:参考音频最多选择3个');
  4550. }
  4551. $reference_audios = array_slice($reference_audios, 0, 3);
  4552. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4553. $videoParams = [
  4554. 'model' => $model,
  4555. 'prompt' => $prompt,
  4556. 'video_duration' => $video_duration,
  4557. 'video_resolution' => $video_resolution,
  4558. 'seed' => $seed,
  4559. 'ratio' => $ratio,
  4560. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4561. 'draft' => getProp($data, 'draft', false),
  4562. 'watermark' => getProp($data, 'watermark', false),
  4563. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4564. ];
  4565. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4566. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4567. // 构建content数组
  4568. $videoParams['content'] = [
  4569. [
  4570. 'type' => 'text',
  4571. 'text' => $prompt,
  4572. ]
  4573. ];
  4574. // 根据模型选择不同的视频生成方法
  4575. if (strpos($model, 'jimeng') !== false) {
  4576. // 即梦模型参数调整
  4577. unset($videoParams['content']); // 即梦不使用content格式
  4578. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4579. } elseif (strpos($model, 'kling') !== false) {
  4580. // 可灵模型参数调整
  4581. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4582. unset($videoParams['ratio']);
  4583. unset($videoParams['content']); // 可灵不使用content格式
  4584. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4585. } elseif (strpos($model, 'zhizhen') !== false) {
  4586. // 智帧等新模型使用统一API
  4587. $unifiedParams = [
  4588. 'model_code' => $model,
  4589. 'prompt' => $prompt,
  4590. 'video_duration' => $video_duration,
  4591. 'video_resolution' => strtolower($video_resolution),
  4592. 'video_ratio' => $ratio,
  4593. 'seed' => $seed,
  4594. ];
  4595. // 构建parameters参数
  4596. $parameters = [
  4597. 'seconds' => $unifiedParams['video_duration'],
  4598. 'resolution' => $unifiedParams['video_resolution'],
  4599. 'ratio' => $ratio,
  4600. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4601. ];
  4602. // 首帧和尾帧
  4603. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4604. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4605. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4606. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4607. if ($refImageUrls) {
  4608. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4609. }
  4610. // 参考图处理
  4611. if ($reference_images) {
  4612. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4613. $parameters['reference_images'] = $reference_images;
  4614. $parameters['video_mode'] = 'multi_image';
  4615. $parameters['mode'] = 'multi_image';
  4616. }
  4617. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4618. if ($reference_videos) {
  4619. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4620. $parameters['reference_videos'] = $reference_videos;
  4621. }
  4622. if ($reference_audios) {
  4623. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4624. $parameters['reference_audios'] = $reference_audios;
  4625. }
  4626. $unifiedParams['parameters'] = $parameters;
  4627. // 调用统一API创建任务
  4628. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4629. } elseif (strpos($model, 'doubao-seedance-2.0') !== false || $this->isKuaikuaiSeedanceModel($model)) {
  4630. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4631. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4632. $videoParams['reference_images'] = $reference_images;
  4633. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4634. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4635. if ($refImageUrls) {
  4636. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4637. }
  4638. if ($reference_images) {
  4639. // 参考图上传为素材(百度网关/快快AI)
  4640. $reference_image_assets = $isKuaikuai
  4641. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4642. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4643. $videoParams['reference_image_assets'] = $reference_image_assets;
  4644. }
  4645. // 参考视频上传为素材(百度网关/快快AI)
  4646. if ($reference_videos) {
  4647. $reference_video_assets = $isKuaikuai
  4648. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4649. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4650. $videoParams['reference_video_assets'] = $reference_video_assets;
  4651. }
  4652. // 参考音频上传为素材(百度网关/快快AI)
  4653. if ($reference_audios) {
  4654. $reference_audio_assets = $isKuaikuai
  4655. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4656. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4657. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4658. }
  4659. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4660. if ($reference_images || $reference_videos || $reference_audios) {
  4661. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4662. }
  4663. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4664. if ($isKuaikuai) {
  4665. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4666. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4667. } else {
  4668. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4669. }
  4670. } else {
  4671. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4672. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4673. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4674. if ($refImageUrls) {
  4675. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4676. }
  4677. if ($reference_videos) {
  4678. foreach ($reference_videos as $videoUrl) {
  4679. $videoParams['content'][] = [
  4680. 'type' => 'video_url',
  4681. 'video_url' => [
  4682. 'url' => $videoUrl,
  4683. ],
  4684. 'role' => 'reference_video',
  4685. ];
  4686. }
  4687. }
  4688. if ($reference_audios) {
  4689. foreach ($reference_audios as $audioUrl) {
  4690. $videoParams['content'][] = [
  4691. 'type' => 'audio_url',
  4692. 'audio_url' => [
  4693. 'url' => $audioUrl,
  4694. ],
  4695. 'role' => 'reference_audio',
  4696. ];
  4697. }
  4698. }
  4699. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4700. }
  4701. return [
  4702. 'task_id' => $task->id,
  4703. 'status' => $task->status,
  4704. 'model' => $model,
  4705. 'video_duration' => $video_duration,
  4706. 'video_resolution' => $video_resolution,
  4707. 'ratio' => $ratio
  4708. ];
  4709. }
  4710. /**
  4711. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4712. *
  4713. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4714. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4715. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4716. *
  4717. * @param array $data
  4718. * @return array
  4719. */
  4720. public function previewCharge(array $data): array
  4721. {
  4722. $mode = (string)getProp($data, 'mode', '');
  4723. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4724. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4725. }
  4726. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4727. $scene = (string)getProp($data, 'scene', 'video_generation');
  4728. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4729. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4730. $scene = 'video_to_video';
  4731. }
  4732. $items = [];
  4733. $model = '';
  4734. $resolution = '';
  4735. if ($mode === 'video') {
  4736. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4737. $model = (string)getProp($data, 'model', '');
  4738. if (!$model) {
  4739. Utils::throwError('1002:model参数不能为空');
  4740. }
  4741. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4742. $duration = (int)getProp($data, 'video_duration', 5);
  4743. if ($duration <= 0) {
  4744. $duration = 5;
  4745. }
  4746. $count = max(1, (int)getProp($data, 'count', 1));
  4747. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4748. 'model' => $model,
  4749. 'video_resolution' => $resolution,
  4750. 'video_duration' => $duration,
  4751. 'mode' => $scene,
  4752. ]);
  4753. $points = $pointsPerVideo * $count;
  4754. $items[] = [
  4755. 'type' => 'video',
  4756. 'model' => $model,
  4757. 'video_resolution' => $resolution,
  4758. 'video_duration' => $duration,
  4759. 'count' => $count,
  4760. 'points' => $points,
  4761. ];
  4762. } elseif ($mode === 'image') {
  4763. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4764. $model = (string)getProp($data, 'model', '');
  4765. if (!$model) {
  4766. Utils::throwError('1002:model参数不能为空');
  4767. }
  4768. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4769. if (!$resolution) {
  4770. $width = (int)getProp($data, 'width', 0);
  4771. $height = (int)getProp($data, 'height', 0);
  4772. if ($width <= 0 || $height <= 0) {
  4773. $width = 1600;
  4774. $height = 2848;
  4775. }
  4776. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4777. }
  4778. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4779. $points = $this->pointsService->getImageChargePoints([
  4780. 'model' => $model,
  4781. 'resolution' => $resolution,
  4782. ]) * $imageNum;
  4783. $items[] = [
  4784. 'type' => 'image',
  4785. 'model' => $model,
  4786. 'resolution' => $resolution,
  4787. 'image_num' => $imageNum,
  4788. 'points' => $points,
  4789. ];
  4790. } else {
  4791. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4792. $count = max(1, (int)getProp($data, 'count', 1));
  4793. $animeId = getProp($data, 'anime_id');
  4794. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4795. if ($animeId && $generateEpisodes > 0) {
  4796. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4797. ->where('anime_id', $animeId)
  4798. ->where('is_default', 1)
  4799. ->max('episode_number');
  4800. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4801. $startEpisodeNumber = $currentMaxEpisode + 1;
  4802. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4803. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4804. ->where('anime_id', $animeId)
  4805. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4806. ->whereIn('status', ['pending', 'processing', 'completed'])
  4807. ->count();
  4808. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4809. if ($count < 0) {
  4810. $count = 0;
  4811. }
  4812. }
  4813. $points = $this->pointsService->getChatChargePoints((string)$model) * $count;
  4814. $items[] = [
  4815. 'type' => 'chat',
  4816. 'count' => $count,
  4817. 'points' => $points,
  4818. ];
  4819. }
  4820. $totalPoints = 0;
  4821. foreach ($items as $item) {
  4822. $totalPoints += $item['points'];
  4823. }
  4824. return [
  4825. 'mode' => $mode,
  4826. 'total_points' => $totalPoints,
  4827. 'items' => $items,
  4828. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4829. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4830. ];
  4831. }
  4832. /**
  4833. * 根据提示词内容智能计算最优视频时长
  4834. *
  4835. * @param string $segmentContent 分镜内容
  4836. * @param string $tailFrame 尾帧描述
  4837. * @return int 视频时长(2-12秒)
  4838. */
  4839. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4840. // 合并所有文本内容
  4841. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4842. // 如果没有内容,返回默认时长
  4843. if (empty($fullText)) {
  4844. return 5;
  4845. }
  4846. // 计算文本长度(中文字符按2个字符计算)
  4847. $textLength = mb_strlen($fullText, 'UTF-8');
  4848. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4849. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4850. // 分析内容复杂度
  4851. $complexityScore = $this->analyzeContentComplexity($fullText);
  4852. // 基础时长计算(根据文本长度)
  4853. $baseDuration = 3; // 默认2秒
  4854. // if ($adjustedLength <= 20) {
  4855. // $baseDuration = 3;
  4856. // } elseif ($adjustedLength <= 40) {
  4857. // $baseDuration = 4;
  4858. // } elseif ($adjustedLength <= 60) {
  4859. // $baseDuration = 5;
  4860. // } elseif ($adjustedLength <= 80) {
  4861. // $baseDuration = 6;
  4862. // } elseif ($adjustedLength <= 100) {
  4863. // $baseDuration = 7;
  4864. // } elseif ($adjustedLength <= 120) {
  4865. // $baseDuration = 8;
  4866. // } else {
  4867. // $baseDuration = 9;
  4868. // }
  4869. // 根据内容复杂度调整时长
  4870. $finalDuration = $baseDuration + $complexityScore;
  4871. // 确保时长在2-12秒范围内
  4872. return max(4, min(12, $finalDuration));
  4873. }
  4874. /**
  4875. * 分析内容复杂度,返回时长调整值
  4876. *
  4877. * @param string $text 文本内容
  4878. * @return int 调整值(-2到+3)
  4879. */
  4880. private function analyzeContentComplexity($text) {
  4881. $score = 0;
  4882. // 动作关键词(需要更长时间展现)
  4883. $actionKeywords = [
  4884. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4885. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4886. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4887. ];
  4888. // 静态关键词(可以用较短时间)
  4889. $staticKeywords = [
  4890. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4891. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4892. ];
  4893. // 复杂场景关键词(需要更长时间)
  4894. $complexSceneKeywords = [
  4895. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4896. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4897. ];
  4898. // 情感关键词(需要适中时间表现)
  4899. $emotionKeywords = [
  4900. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4901. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4902. ];
  4903. // 检查动作关键词
  4904. foreach ($actionKeywords as $keyword) {
  4905. if (strpos($text, $keyword) !== false) {
  4906. $score += 1;
  4907. break; // 避免重复加分
  4908. }
  4909. }
  4910. // 检查静态关键词
  4911. foreach ($staticKeywords as $keyword) {
  4912. if (strpos($text, $keyword) !== false) {
  4913. $score -= 1;
  4914. break;
  4915. }
  4916. }
  4917. // 检查复杂场景关键词
  4918. foreach ($complexSceneKeywords as $keyword) {
  4919. if (strpos($text, $keyword) !== false) {
  4920. $score += 1;
  4921. break;
  4922. }
  4923. }
  4924. // 检查情感关键词
  4925. foreach ($emotionKeywords as $keyword) {
  4926. if (strpos($text, $keyword) !== false) {
  4927. $score += 1;
  4928. break;
  4929. }
  4930. }
  4931. // 检查时间相关词汇
  4932. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4933. $score += 1;
  4934. }
  4935. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4936. $score -= 1;
  4937. }
  4938. // 检查转场词汇
  4939. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4940. $score += 1;
  4941. }
  4942. // 检查环境描述(复杂环境需要更多时间)
  4943. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4944. $score += 1;
  4945. }
  4946. // 检查对话内容(对话需要更多时间)
  4947. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4948. $score += 1;
  4949. }
  4950. // 限制调整范围
  4951. return max(-1, min(4, $score));
  4952. }
  4953. /**
  4954. * 创建完整视频合成任务
  4955. *
  4956. * @param array $data
  4957. * @return array
  4958. */
  4959. public function createCompleteVideoTask($data)
  4960. {
  4961. $animeId = getProp($data, 'anime_id');
  4962. $episodeId = getProp($data, 'episode_id');
  4963. // 验证参数
  4964. if (!$animeId || !$episodeId) {
  4965. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4966. }
  4967. // 检查是否已存在处理中的任务
  4968. $existingTask = DB::table('mp_complete_video_tasks')
  4969. ->where('anime_id', $animeId)
  4970. ->where('episode_id', $episodeId)
  4971. ->whereIn('generate_status', ['执行中'])
  4972. ->first();
  4973. if ($existingTask) {
  4974. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4975. }
  4976. // 获取全能模式状态
  4977. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4978. if ((int)$ace_mode === 1) {
  4979. // 获取所有片段的配音视频,按 act_number 排序
  4980. $segments = DB::table('mp_episode_segments')
  4981. ->where('anime_id', $animeId)
  4982. ->where('episode_id', $episodeId)
  4983. ->orderBy('segment_number')
  4984. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4985. ->get();
  4986. // 检查是否所有片段都有视频
  4987. $missingVideos = $segments->filter(function($segment) {
  4988. return empty($segment->video_url);
  4989. });
  4990. if ($missingVideos->isNotEmpty()) {
  4991. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4992. }
  4993. }else {
  4994. // 获取所有分镜的配音视频,按 segment_number 排序
  4995. $segments = DB::table('mp_episode_segments')
  4996. ->where('anime_id', $animeId)
  4997. ->where('episode_id', $episodeId)
  4998. ->orderBy('segment_number')
  4999. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5000. ->get();
  5001. // 检查是否所有分镜都有配音和视频
  5002. $missingVideos = $segments->filter(function($segment) {
  5003. return empty($segment->audio_url) || empty($segment->video_url);
  5004. });
  5005. if ($missingVideos->isNotEmpty()) {
  5006. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5007. }
  5008. }
  5009. if ($segments->isEmpty()) {
  5010. Utils::throwError('20003:未找到该剧集的分镜数据');
  5011. }
  5012. // 获取当前完整视频url
  5013. $completeVideoUrl = DB::table('mp_anime_episodes')
  5014. ->where('anime_id', $animeId)
  5015. ->where('id', $episodeId)
  5016. ->value('complete_video_url');
  5017. // 构建 generate_json
  5018. $generateJson = [];
  5019. $sequence = 1;
  5020. foreach ($segments as $segment) {
  5021. if ((int)$ace_mode === 1) {
  5022. $generateJson[] = [
  5023. 'sequence' => $sequence++,
  5024. 'video_url' => $segment->video_url,
  5025. 'video_time_point_start' => $segment->video_time_point_start,
  5026. 'video_time_point_end' => $segment->video_time_point_end
  5027. ];
  5028. }else {
  5029. $generateJson[] = [
  5030. 'sequence' => $sequence++,
  5031. 'video_url' => $segment->video_url,
  5032. 'audio_url' => $segment->audio_url,
  5033. 'video_time_point_start' => $segment->video_time_point_start,
  5034. 'video_time_point_end' => $segment->video_time_point_end
  5035. ];
  5036. }
  5037. }
  5038. // 创建任务
  5039. $now = date('Y-m-d H:i:s');
  5040. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5041. 'anime_id' => $animeId,
  5042. 'episode_id' => $episodeId,
  5043. 'generate_json' => json_encode($generateJson, 256),
  5044. 'generate_status' => '执行中',
  5045. 'complete_video_url' => '',
  5046. 'created_at' => $now,
  5047. 'updated_at' => $now
  5048. ]);
  5049. if (!$taskId) {
  5050. Utils::throwError('20003:创建任务失败');
  5051. }
  5052. // 更新剧集表的任务ID和状态
  5053. $boolen = DB::table('mp_anime_episodes')
  5054. ->where('anime_id', $animeId)
  5055. ->where('id', $episodeId)
  5056. ->update([
  5057. 'complete_video_task_id' => $taskId,
  5058. 'complete_video_task_status' => '执行中',
  5059. 'updated_at' => $now
  5060. ]);
  5061. if (!$boolen) {
  5062. Utils::throwError('20003:更新剧集表失败');
  5063. }
  5064. dLog('anime')->info('创建完整视频合成任务', [
  5065. 'task_id' => $taskId,
  5066. 'anime_id' => $animeId,
  5067. 'episode_id' => $episodeId,
  5068. 'segment_count' => count($generateJson)
  5069. ]);
  5070. // 请求远程服务器执行生成
  5071. $client = new Client(['timeout' => 600, 'verify' => false]);
  5072. try {
  5073. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5074. $response = $result->getBody()->getContents();
  5075. $response_arr = json_decode($response, true);
  5076. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5077. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5078. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5079. // // 更新任务状态为失败
  5080. // DB::table('mp_complete_video_tasks')
  5081. // ->where('id', $taskId)
  5082. // ->update([
  5083. // 'generate_status' => '执行失败',
  5084. // 'error_message' => $error_msg,
  5085. // 'updated_at' => date('Y-m-d H:i:s')
  5086. // ]);
  5087. // // 同步更新剧集表状态
  5088. // DB::table('mp_anime_episodes')
  5089. // ->where('complete_video_task_id', $taskId)
  5090. // ->update([
  5091. // 'complete_video_task_status' => '执行失败',
  5092. // 'updated_at' => date('Y-m-d H:i:s')
  5093. // ]);
  5094. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5095. }
  5096. } catch (\Exception $e) {
  5097. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5098. // 更新任务状态为失败
  5099. DB::table('mp_complete_video_tasks')
  5100. ->where('id', $taskId)
  5101. ->update([
  5102. 'generate_status' => '执行失败',
  5103. 'error_message' => $e->getMessage(),
  5104. 'updated_at' => date('Y-m-d H:i:s')
  5105. ]);
  5106. // 同步更新剧集表状态
  5107. DB::table('mp_anime_episodes')
  5108. ->where('complete_video_task_id', $taskId)
  5109. ->update([
  5110. 'complete_video_task_status' => '执行失败',
  5111. 'updated_at' => date('Y-m-d H:i:s')
  5112. ]);
  5113. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5114. }
  5115. // 开始轮询任务状态
  5116. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5117. $pollInterval = 5; // 每5秒轮询一次
  5118. $attempt = 0;
  5119. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5120. while ($attempt < $maxAttempts) {
  5121. sleep($pollInterval);
  5122. $attempt++;
  5123. // 查询任务状态
  5124. $task = DB::table('mp_complete_video_tasks')
  5125. ->where('id', $taskId)
  5126. ->first();
  5127. if (!$task) {
  5128. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5129. Utils::throwError('20003:任务不存在');
  5130. }
  5131. dLog('anime')->info('轮询任务状态', [
  5132. 'task_id' => $taskId,
  5133. 'attempt' => $attempt,
  5134. 'status' => $task->generate_status
  5135. ]);
  5136. // 检查任务是否完成
  5137. if ($task->generate_status === '执行成功') {
  5138. // 同步更新剧集表状态
  5139. $boolen3 = DB::table('mp_anime_episodes')
  5140. ->where('anime_id', $animeId)
  5141. ->where('id', $episodeId)
  5142. ->update([
  5143. 'complete_video_url' => $task->complete_video_url,
  5144. 'complete_video_task_status' => '执行成功',
  5145. 'updated_at' => date('Y-m-d H:i:s')
  5146. ]);
  5147. dLog('anime')->info('视频合成任务完成', [
  5148. 'task_id' => $taskId,
  5149. 'video_url' => $task->complete_video_url,
  5150. 'attempts' => $attempt
  5151. ]);
  5152. // 如果更新成功则远程删除之前的文件
  5153. if ($boolen3 && $completeVideoUrl) {
  5154. $encode_url = urlencode($completeVideoUrl);
  5155. $client = new Client(['timeout' => 300, 'verify' => false]);
  5156. // 根据ID通过API通知合成音频
  5157. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5158. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5159. $response = $result->getBody()->getContents();
  5160. $response_arr = json_decode($response, true);
  5161. Log::info('火山删除音频返回: '.$response);
  5162. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5163. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5164. Log::info('火山删除音频失败: '.$error_msg);
  5165. // Utils::throwError('20003:火山删除音频失败');
  5166. }
  5167. }
  5168. return [
  5169. 'task_id' => $taskId,
  5170. 'anime_id' => $animeId,
  5171. 'episode_id' => $episodeId,
  5172. 'segment_count' => count($generateJson),
  5173. 'generate_status' => '执行成功',
  5174. 'complete_video_url' => $task->complete_video_url,
  5175. ];
  5176. }
  5177. // 检查任务是否失败
  5178. if ($task->generate_status === '执行失败') {
  5179. // 同步更新剧集表状态
  5180. DB::table('mp_anime_episodes')
  5181. ->where('anime_id', $animeId)
  5182. ->where('id', $episodeId)
  5183. ->update([
  5184. 'complete_video_task_status' => '执行失败',
  5185. 'updated_at' => date('Y-m-d H:i:s')
  5186. ]);
  5187. $errorMessage = $task->error_message ?? '未知错误';
  5188. dLog('anime')->error('视频合成任务失败', [
  5189. 'task_id' => $taskId,
  5190. 'error' => $errorMessage,
  5191. 'attempts' => $attempt
  5192. ]);
  5193. return [
  5194. 'task_id' => $taskId,
  5195. 'anime_id' => $animeId,
  5196. 'episode_id' => $episodeId,
  5197. 'segment_count' => count($generateJson),
  5198. 'generate_status' => '执行失败',
  5199. 'error_message' => $errorMessage
  5200. ];
  5201. }
  5202. }
  5203. // 超时处理
  5204. dLog('anime')->warning('视频合成任务超时', [
  5205. 'task_id' => $taskId,
  5206. 'max_attempts' => $maxAttempts,
  5207. 'timeout_seconds' => $maxAttempts * $pollInterval
  5208. ]);
  5209. // 更新任务状态为超时
  5210. DB::table('mp_complete_video_tasks')
  5211. ->where('id', $taskId)
  5212. ->update([
  5213. 'generate_status' => '超时',
  5214. 'error_message' => '任务执行超时(5分钟)',
  5215. 'updated_at' => date('Y-m-d H:i:s')
  5216. ]);
  5217. return [
  5218. 'task_id' => $taskId,
  5219. 'anime_id' => $animeId,
  5220. 'episode_id' => $episodeId,
  5221. 'segment_count' => count($generateJson),
  5222. 'generate_status' => '超时',
  5223. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5224. ];
  5225. }
  5226. /**
  5227. * 根据 inner_prompt_type 附加内置提示词
  5228. *
  5229. * @param string $prompt 用户提示词
  5230. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5231. * @return string 合并后的提示词
  5232. */
  5233. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5234. {
  5235. $innerPromptMap = [
  5236. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5237. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5238. ];
  5239. if (!isset($innerPromptMap[$innerPromptType])) {
  5240. return $prompt;
  5241. }
  5242. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5243. }
  5244. /**
  5245. * 根据 inner_prompt_type 获取生成图片数量
  5246. *
  5247. * @param int $innerPromptType 内置提示词类型
  5248. * @param int $imageNum 传入的图片张数
  5249. * @return int 图片数量
  5250. */
  5251. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5252. {
  5253. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5254. }
  5255. /**
  5256. * 提取图片生成结果URL
  5257. *
  5258. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5259. * @param int $innerPromptType 内置提示词类型
  5260. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5261. */
  5262. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5263. {
  5264. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5265. if (is_array($resultUrls) && !empty($resultUrls)) {
  5266. $resultUrls = array_values($resultUrls);
  5267. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5268. }
  5269. if (!empty($resultUrl)) {
  5270. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5271. }
  5272. return (int)$innerPromptType === 2 ? [] : '';
  5273. }
  5274. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5275. $prompt = getProp($data, 'prompt');
  5276. $episode_id = getProp($data, 'episode_id');
  5277. $ref_img_urls = getProp($data, 'ref_img_urls');
  5278. $ratio = getProp($data, 'ratio', '9:16');
  5279. $resolution = getProp($data, 'resolution', '2k');
  5280. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5281. $imageNum = (int)getProp($data, 'image_num', 1);
  5282. // 定义分辨率和宽高比对应的尺寸映射表
  5283. $sizeMap = [
  5284. '2k' => [
  5285. '1:1' => ['width' => 2048, 'height' => 2048],
  5286. '4:3' => ['width' => 2304, 'height' => 1728],
  5287. '3:4' => ['width' => 1728, 'height' => 2304],
  5288. '16:9' => ['width' => 2848, 'height' => 1600],
  5289. '9:16' => ['width' => 1600, 'height' => 2848],
  5290. '3:2' => ['width' => 2496, 'height' => 1664],
  5291. '2:3' => ['width' => 1664, 'height' => 2496],
  5292. '21:9' => ['width' => 3136, 'height' => 1344],
  5293. ],
  5294. '3k' => [
  5295. '1:1' => ['width' => 3072, 'height' => 3072],
  5296. '4:3' => ['width' => 3456, 'height' => 2592],
  5297. '3:4' => ['width' => 2592, 'height' => 3456],
  5298. '16:9' => ['width' => 4096, 'height' => 2304],
  5299. '9:16' => ['width' => 2304, 'height' => 4096],
  5300. '2:3' => ['width' => 2496, 'height' => 3744],
  5301. '3:2' => ['width' => 3744, 'height' => 2496],
  5302. '21:9' => ['width' => 4704, 'height' => 2016],
  5303. ],
  5304. '4k' => [
  5305. '1:1' => ['width' => 4096, 'height' => 4096],
  5306. '3:4' => ['width' => 3520, 'height' => 4704],
  5307. '4:3' => ['width' => 4704, 'height' => 3520],
  5308. '16:9' => ['width' => 5504, 'height' => 3040],
  5309. '9:16' => ['width' => 3040, 'height' => 5504],
  5310. '2:3' => ['width' => 3328, 'height' => 4992],
  5311. '3:2' => ['width' => 4992, 'height' => 3328],
  5312. '21:9' => ['width' => 6240, 'height' => 2656],
  5313. ],
  5314. ];
  5315. // 参数验证
  5316. $resolution = strtolower($resolution);
  5317. if (!isset($sizeMap[$resolution])) {
  5318. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5319. }
  5320. if (!isset($sizeMap[$resolution][$ratio])) {
  5321. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5322. }
  5323. // 根据 ratio 和 resolution 确定宽高
  5324. $width = $sizeMap[$resolution][$ratio]['width'];
  5325. $height = $sizeMap[$resolution][$ratio]['height'];
  5326. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5327. if (is_json($ref_img_urls)) {
  5328. $ref_img_urls = json_decode($ref_img_urls, true);
  5329. }else {
  5330. $ref_img_urls = explode(',', $ref_img_urls);
  5331. }
  5332. }
  5333. // 处理图片模型
  5334. $model = getProp($data, 'model');
  5335. if (!$model) {
  5336. // 用户没有输入,从episode表获取
  5337. if ($episode_id) {
  5338. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5339. $model = getProp($episode, 'image_model');
  5340. }
  5341. if (!$model) {
  5342. // episode表也没有,使用默认值
  5343. $model = 'doubao-seedream-5-0-lite-260128';
  5344. }
  5345. }
  5346. // 验证模型是否在可用模型表中
  5347. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5348. // $model = 'doubao-seedream-5-0-lite-260128';
  5349. Utils::throwError('20003:该模型已不可用,请更换!');
  5350. }
  5351. // 保存到episode表
  5352. if ($episode_id) {
  5353. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5354. 'image_model' => $model,
  5355. 'updated_at' => date('Y-m-d H:i:s')
  5356. ]);
  5357. }
  5358. // 参数验证
  5359. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5360. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5361. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5362. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5363. try {
  5364. // 创建图片生成任务
  5365. $params = [
  5366. 'prompt' => $prompt,
  5367. 'model' => $model,
  5368. 'ref_img_urls' => '',
  5369. 'width' => $width,
  5370. 'height' => $height,
  5371. 'image_num' => $imageNum
  5372. ];
  5373. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5374. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5375. $task_id = $task->id;
  5376. if (!$task_id) {
  5377. Utils::throwError('20003:创建图片生成任务失败');
  5378. }
  5379. // 创建任务中心记录并关联图片任务ID
  5380. $taskCenter = $this->taskCenterService->createTask('image', [
  5381. 'title' => '文生图',
  5382. 'ref_task_id' => $task_id,
  5383. // 'prompt' => $prompt,
  5384. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5385. ]);
  5386. $taskCenterId = $taskCenter->id;
  5387. // 组装本次任务信息(用于init消息,类似generateVideo)
  5388. $taskInfo = [
  5389. 'task_id' => $task_id,
  5390. 'status' => getProp($task, 'status', 'processing'),
  5391. 'model' => $model,
  5392. 'ratio' => $ratio,
  5393. 'resolution' => $resolution,
  5394. 'image_num' => $imageNum,
  5395. ];
  5396. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5397. if (is_callable($onTaskCreated)) {
  5398. $onTaskCreated($taskCenterId, $taskInfo);
  5399. }
  5400. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5401. $model = getProp($task, 'model');
  5402. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5403. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5404. $isSyncModel = $isVolcModel || $isGptModel;
  5405. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5406. $start_time = time();
  5407. $timeout = 300; // 5分钟
  5408. $img_url = '';
  5409. $img_urls = [];
  5410. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5411. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5412. while (time() - $start_time < $timeout) {
  5413. sleep(3);
  5414. // 每分钟发送一次队列状态消息(仅流式模式)
  5415. if (is_callable($onPoll)) {
  5416. $currentTime = time();
  5417. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5418. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5419. $lastQueueMessageTime = $currentTime;
  5420. }
  5421. }
  5422. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5423. if ($isSyncModel) {
  5424. // 刷新任务状态
  5425. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5426. if ($task->status === 'success' && $task->result_url) {
  5427. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5428. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5429. if (!empty($resultUrls)) {
  5430. $img_urls = $resultUrls;
  5431. $img_url = $resultUrls[0];
  5432. } else {
  5433. $img_url = (string)$task->result_url;
  5434. }
  5435. break;
  5436. } elseif ($task->status === 'failed') {
  5437. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5438. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5439. }
  5440. // // 如果还在处理中,提示用户稍后查看
  5441. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5442. }else {
  5443. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5444. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5445. if ($statusInfo['status'] === 'success') {
  5446. $task->updateStatus('success', [
  5447. 'result_url' => $statusInfo['result_url'],
  5448. 'result_json' => $statusInfo['result_json'] ?? []
  5449. ]);
  5450. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5451. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5452. if (!empty($resultUrls)) {
  5453. $img_urls = $resultUrls;
  5454. $img_url = $resultUrls[0];
  5455. } else {
  5456. $img_url = (string)$statusInfo['result_url'];
  5457. }
  5458. break;
  5459. } elseif ($statusInfo['status'] === 'failed') {
  5460. $task->updateStatus('failed', [
  5461. 'error_message' => $statusInfo['error_message'],
  5462. 'result_json' => $statusInfo['result_json'] ?? []
  5463. ]);
  5464. dLog('anime')->error('图片生成失败,', [
  5465. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5466. ]);
  5467. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5468. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5469. }
  5470. }
  5471. }
  5472. if (empty($img_url)) {
  5473. Utils::throwError('20003:图片生成超时,请稍后重试');
  5474. }
  5475. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5476. if (count($img_urls) > 1) {
  5477. return [
  5478. 'img_url' => $img_url,
  5479. 'image_urls' => $img_urls,
  5480. 'task_id' => $taskCenterId,
  5481. ];
  5482. }
  5483. return [
  5484. 'img_url' => $img_url,
  5485. 'task_id' => $taskCenterId,
  5486. ];
  5487. } catch (\Exception $e) {
  5488. dLog('anime')->error('更新角色或场景失败', [
  5489. 'error' => $e->getMessage()
  5490. ]);
  5491. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5492. Utils::throwError('20003:' . $e->getMessage());
  5493. }
  5494. }
  5495. /**
  5496. * 使用文生文模型解析分镜内容
  5497. */
  5498. private function parseSegmentContentWithAI($segment_content) {
  5499. try {
  5500. // 使用DeepSeek服务的公开方法解析分镜内容
  5501. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5502. } catch (\Exception $e) {
  5503. // 如果AI解析失败,记录日志并返回原内容
  5504. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5505. return $segment_content;
  5506. }
  5507. }
  5508. /**
  5509. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5510. *
  5511. * @param int $episode_id 分集ID
  5512. * @param int $anime_id 动漫ID
  5513. * @param array $roles 分集角色数组(引用传递)
  5514. * @param array $scenes 分集场景数组(引用传递)
  5515. * @param array $episode 分集数据
  5516. */
  5517. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5518. // 获取全局动漫的角色和场景数据
  5519. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5520. if (!$anime) return;
  5521. $art_style_type = getProp($anime, 'art_style_type');
  5522. $character_prefix = '';
  5523. $scene_prefix = '';
  5524. if ($art_style_type) {
  5525. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5526. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5527. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5528. }
  5529. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5530. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5531. $roles_updated = false;
  5532. $scenes_updated = false;
  5533. // 处理角色
  5534. foreach ($roles as &$role) {
  5535. $role_name = getProp($role, 'role');
  5536. $role_description = getProp($role, 'description');
  5537. $role_pic_prompt = getProp($role, 'pic_prompt');
  5538. $role_url = getProp($role, 'url');
  5539. $role_task_id = getProp($role, 'task_id');
  5540. // 如果已有URL或已有任务ID,跳过
  5541. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5542. continue;
  5543. }
  5544. $url_inherited = false;
  5545. // 尝试从全局数据中继承
  5546. foreach ($global_roles as $global_role) {
  5547. $global_role_name = getProp($global_role, 'role');
  5548. $global_role_description = getProp($global_role, 'description');
  5549. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5550. $global_role_url = getProp($global_role, 'url');
  5551. $global_role_task_id = getProp($global_role, 'task_id');
  5552. $global_role_task_status = getProp($global_role, 'task_status');
  5553. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5554. if ($role_name === $global_role_name
  5555. && $role_description === $global_role_description
  5556. && $role_pic_prompt === $global_role_pic_prompt
  5557. && !empty($global_role_url)) {
  5558. // 继承 task_id、task_status 和 url
  5559. $role['task_id'] = $global_role_task_id;
  5560. $role['task_status'] = $global_role_task_status;
  5561. $role['url'] = $global_role_url;
  5562. $roles_updated = true;
  5563. $url_inherited = true;
  5564. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5565. break;
  5566. }
  5567. }
  5568. // 如果无法继承且没有任务ID,创建新任务
  5569. if (!$url_inherited && empty($role_task_id)) {
  5570. try {
  5571. $art_style = getProp($episode, 'art_style');
  5572. // 优先使用 pic_prompt,如果没有则使用 description
  5573. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5574. // if ($art_style) {
  5575. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5576. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5577. // }
  5578. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5579. $params = [
  5580. 'prompt' => $description,
  5581. 'ref_img_urls' => []
  5582. ];
  5583. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5584. $task_id = $task->id;
  5585. if ($task_id) {
  5586. $role['task_id'] = $task_id;
  5587. $role['task_status'] = 'processing';
  5588. $roles_updated = true;
  5589. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5590. }
  5591. } catch (\Exception $e) {
  5592. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5593. }
  5594. }
  5595. }
  5596. // 处理场景
  5597. foreach ($scenes as &$scene) {
  5598. $scene_name = getProp($scene, 'scene');
  5599. $scene_description = getProp($scene, 'description');
  5600. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5601. $scene_url = getProp($scene, 'url');
  5602. $scene_task_id = getProp($scene, 'task_id');
  5603. // 如果已有URL或已有任务ID,跳过
  5604. if (!empty($scene_url) || !empty($scene_task_id)) {
  5605. continue;
  5606. }
  5607. $url_inherited = false;
  5608. // 尝试从全局数据中继承
  5609. foreach ($global_scenes as $global_scene) {
  5610. $global_scene_name = getProp($global_scene, 'scene');
  5611. $global_scene_description = getProp($global_scene, 'description');
  5612. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5613. $global_scene_url = getProp($global_scene, 'url');
  5614. $global_scene_task_id = getProp($global_scene, 'task_id');
  5615. $global_scene_task_status = getProp($global_scene, 'task_status');
  5616. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5617. if ($scene_name === $global_scene_name
  5618. && $scene_description === $global_scene_description
  5619. && $scene_pic_prompt === $global_scene_pic_prompt
  5620. && !empty($global_scene_url)) {
  5621. // 继承 task_id、task_status 和 url
  5622. $scene['task_id'] = $global_scene_task_id;
  5623. $scene['task_status'] = $global_scene_task_status;
  5624. $scene['url'] = $global_scene_url;
  5625. $scenes_updated = true;
  5626. $url_inherited = true;
  5627. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5628. break;
  5629. }
  5630. }
  5631. // 如果无法继承且没有任务ID,创建新任务
  5632. if (!$url_inherited && empty($scene_task_id)) {
  5633. try {
  5634. $art_style = getProp($episode, 'art_style');
  5635. // 优先使用 pic_prompt,如果没有则使用 description
  5636. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5637. // if ($art_style) {
  5638. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5639. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5640. // }
  5641. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5642. $params = [
  5643. 'prompt' => $description,
  5644. 'ref_img_urls' => []
  5645. ];
  5646. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5647. $task_id = $task->id;
  5648. if ($task_id) {
  5649. $scene['task_id'] = $task_id;
  5650. $scene['task_status'] = 'processing';
  5651. $scenes_updated = true;
  5652. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5653. }
  5654. } catch (\Exception $e) {
  5655. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5656. }
  5657. }
  5658. }
  5659. // 如果有更新,保存到数据库
  5660. if ($roles_updated || $scenes_updated) {
  5661. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5662. if ($roles_updated) {
  5663. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5664. }
  5665. if ($scenes_updated) {
  5666. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5667. }
  5668. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5669. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5670. }
  5671. }
  5672. /**
  5673. * 根据图片URL使用AI反推图片提示词
  5674. *
  5675. * @param string $img_url 图片URL
  5676. * @return string 反推的提示词
  5677. */
  5678. private function generateImagePromptFromUrl($img_url) {
  5679. try {
  5680. // 获取默认模型
  5681. $model = 'doubao-seed-2-0-mini-260215';
  5682. // 构建messages参数
  5683. $messages = [
  5684. [
  5685. 'role' => 'user',
  5686. 'content' => [
  5687. [
  5688. 'type' => 'text',
  5689. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5690. ],
  5691. [
  5692. 'type' => 'image_url',
  5693. 'image_url' => [
  5694. 'url' => $img_url
  5695. ]
  5696. ]
  5697. ]
  5698. ]
  5699. ];
  5700. // 构建请求参数
  5701. $params = [
  5702. 'model' => $model,
  5703. 'messages' => $messages,
  5704. 'stream' => false,
  5705. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5706. ];
  5707. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5708. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5709. // 仅记录 token 使用明细(不扣积分)
  5710. $uid = 0;
  5711. try {
  5712. $uid = (int)Site::getUid();
  5713. } catch (\Throwable $e) {
  5714. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5715. }
  5716. $this->pointsService->recordTokenOnlyDetail(
  5717. $uid,
  5718. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5719. [
  5720. 'model' => $model,
  5721. 'img_url' => $img_url,
  5722. 'source' => 'generateImagePromptFromUrl',
  5723. ],
  5724. 'chat',
  5725. $model,
  5726. ''
  5727. );
  5728. // 返回生成的内容
  5729. return getProp($result, 'fullContent', '图片描述生成失败');
  5730. } catch (\Exception $e) {
  5731. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5732. 'img_url' => $img_url
  5733. ]);
  5734. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5735. 'error' => $e->getMessage(),
  5736. 'img_url' => $img_url
  5737. ]);
  5738. return '图片描述生成失败: ' . $e->getMessage();
  5739. }
  5740. }
  5741. /**
  5742. * 音频试听接口
  5743. * 创建音频任务并轮询获取结果
  5744. *
  5745. * @param array $data 参数数组
  5746. * @return array 返回音频URL或错误信息
  5747. */
  5748. public function previewAudio($data) {
  5749. $dialogue = getProp($data, 'dialogue');
  5750. // 必填参数验证
  5751. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5752. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5753. $voice_type = getProp($data, 'voice_type');
  5754. $voice_name = getProp($data, 'voice_name');
  5755. $voice_actor = getProp($data, 'voice_actor');
  5756. $emotion_type = getProp($data, 'emotion_type');
  5757. $gender = getProp($data, 'gender', 0);
  5758. $emotion = getProp($data, 'emotion');
  5759. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5760. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5761. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5762. $pitch = getProp($data, 'pitch', 0);
  5763. try {
  5764. $now = date('Y-m-d H:i:s');
  5765. // 构建生成参数
  5766. $generate_json = json_encode([
  5767. 'text' => $dialogue,
  5768. 'role' => $voice_actor,
  5769. 'voice_type' => $voice_type,
  5770. 'voice_name' => $voice_name,
  5771. 'emotion' => $emotion,
  5772. 'emotion_type' => $emotion_type,
  5773. 'gender' => $gender,
  5774. 'speed_ratio' => $speed_ratio,
  5775. 'loudness_ratio' => $loudness_ratio,
  5776. 'emotion_scale' => $emotion_scale,
  5777. 'pitch' => $pitch,
  5778. ], 256);
  5779. // 请求远程服务器执行生成
  5780. $client = new Client(['timeout' => 600, 'verify' => false]);
  5781. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5782. $response = $result->getBody()->getContents();
  5783. $response_arr = json_decode($response, true);
  5784. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5785. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5786. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5787. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5788. }
  5789. $arr = $response_arr['data'];
  5790. $subtitle_info = $arr['subtitle_info'];
  5791. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5792. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5793. return [
  5794. 'audio_url' => $arr['url'],
  5795. 'subtitle_info' => $subtitle_info,
  5796. 'audio_duration' => round($audio_duration, 2)
  5797. ];
  5798. } catch (\Exception $e) {
  5799. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5800. Utils::throwError('20003:' . $e->getMessage());
  5801. }
  5802. }
  5803. /**
  5804. * 获取角色库列表(支持文件夹递归查询)
  5805. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5806. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5807. */
  5808. public function globalProducts($data) {
  5809. $uid = Site::getUid();
  5810. $cpid = Site::getCpid();
  5811. $role = Site::getRole();
  5812. $id = getProp($data, 'id', 0);
  5813. $parent_id = getProp($data, 'parent_id', 0);
  5814. $product_name = getProp($data, 'product_name');
  5815. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5816. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5817. if (!$product) {
  5818. Utils::throwError('20003:请选择产品类型');
  5819. }
  5820. // 根据角色和is_public参数确定查询范围
  5821. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5822. // user角色:根据is_public参数筛选
  5823. $query_user_ids = [];
  5824. if ($role === 'admin') {
  5825. // admin获取所有个人库和公共库
  5826. $query_user_ids = [$uid, 0];
  5827. } else {
  5828. // user角色根据is_public参数筛选
  5829. if ($is_public == 2) {
  5830. // 个人库+公共库
  5831. $query_user_ids = [$uid, 0];
  5832. } elseif ($is_public == 0) {
  5833. // 仅个人库
  5834. $query_user_ids = [$uid];
  5835. } elseif ($is_public == 1) {
  5836. // 仅公共库
  5837. $query_user_ids = [0];
  5838. }
  5839. }
  5840. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5841. if ($id || $product_name) {
  5842. $query = DB::table('mp_products')
  5843. ->where('cpid', $cpid)
  5844. ->whereIn('user_id', $query_user_ids)
  5845. ->where('is_deleted', 0);
  5846. // 如果指定了 id,按 id 精确查询
  5847. if ($id) {
  5848. $query->where('id', $id);
  5849. }
  5850. // 如果指定了 product_name,按名称模糊查询
  5851. if ($product_name) {
  5852. $query->where('product_name', 'like', "%{$product_name}%");
  5853. }
  5854. // 如果指定了 product,添加筛选条件
  5855. if ($product) {
  5856. $query->where('product', $product);
  5857. }
  5858. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5859. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5860. ->get()
  5861. ->map(function($value) {
  5862. $value = (array)$value;
  5863. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5864. $value['type'] = (int)$value['type'];
  5865. $value['parent_id'] = (int)$value['parent_id'];
  5866. $value['level'] = (int)$value['level'];
  5867. $value['product'] = (int)($value['product'] ?? 1);
  5868. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5869. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5870. unset($value['user_id']);
  5871. return $value;
  5872. })
  5873. ->toArray();
  5874. return $result;
  5875. }
  5876. // 递归获取所有子目录和角色
  5877. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5878. }
  5879. /**
  5880. * 递归获取指定目录下的所有子目录和角色
  5881. * @param int $cpid 公司ID
  5882. * @param int $parent_id 父目录ID
  5883. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5884. * @param array $query_user_ids 用户ID数组(支持多个)
  5885. * @param int $current_uid 当前用户ID(用于排序)
  5886. * @return array
  5887. */
  5888. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5889. // 查询当前层级的所有项(文件夹和角色)
  5890. $query = DB::table('mp_products')
  5891. ->where('cpid', $cpid)
  5892. ->where('is_deleted', 0)
  5893. ->where('parent_id', $parent_id);
  5894. // 添加用户ID验证(支持多个user_id)
  5895. if (!empty($query_user_ids)) {
  5896. $query->whereIn('user_id', $query_user_ids);
  5897. }
  5898. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5899. if ($product) {
  5900. $query->where('product', $product);
  5901. }
  5902. // 排序规则:
  5903. // 1. 文件夹在前(type DESC)
  5904. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5905. // 3. 其他排序规则
  5906. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5907. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5908. ->get();
  5909. $result = [];
  5910. foreach ($items as $item) {
  5911. $itemArray = [
  5912. 'id' => $item->id,
  5913. 'type' => (int)$item->type,
  5914. 'parent_id' => (int)$item->parent_id,
  5915. 'level' => (int)$item->level,
  5916. 'product_name' => $item->product_name,
  5917. 'url' => $item->url,
  5918. 'pic_prompt' => $item->pic_prompt ?? '',
  5919. 'three_view_image_url' => $item->three_view_image_url,
  5920. 'product' => (int)($item->product ?? 1),
  5921. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5922. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5923. ];
  5924. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5925. // 如果是文件夹,递归获取其子项
  5926. if ($item->type == 2) {
  5927. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5928. if (!empty($children)) {
  5929. $itemArray['children'] = $children;
  5930. }
  5931. }
  5932. $result[] = $itemArray;
  5933. }
  5934. return $result;
  5935. }
  5936. /**
  5937. * 创建文件夹
  5938. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5939. * @return int 返回新建文件夹ID
  5940. */
  5941. public function createFolder($data) {
  5942. $uid = Site::getUid();
  5943. $cpid = Site::getCpid();
  5944. $role = Site::getRole();
  5945. $parent_id = getProp($data, 'parent_id', 0);
  5946. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5947. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5948. // 如果是公共库操作,需要admin权限
  5949. if ($is_public && $role !== 'admin') {
  5950. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5951. }
  5952. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5953. $store_uid = $is_public ? 0 : $uid;
  5954. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5955. $product = getProp($data, 'product');
  5956. if (!in_array($product, [1, 2, 3])) {
  5957. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5958. }
  5959. // 验证父文件夹
  5960. $parent_level = 0;
  5961. if ($parent_id > 0) {
  5962. $parent = DB::table('mp_products')
  5963. ->where('id', $parent_id)
  5964. ->where('cpid', $cpid)
  5965. ->where('user_id', $store_uid)
  5966. ->where('type', 2)
  5967. ->where('is_deleted', 0)
  5968. ->first();
  5969. if (!$parent) {
  5970. Utils::throwError('20003:父文件夹不存在');
  5971. }
  5972. // 检查父文件夹的 product 类型是否一致
  5973. if ($parent->product != $product) {
  5974. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5975. }
  5976. $parent_level = $parent->level;
  5977. // 检查层级限制(最多3层)
  5978. if ($parent_level >= 3) {
  5979. Utils::throwError('20003:文件夹层级不能超过3层');
  5980. }
  5981. }
  5982. // 检查当前目录下是否已存在空白文件夹
  5983. $empty_folder_exists = DB::table('mp_products')
  5984. ->where('parent_id', $parent_id)
  5985. ->where('cpid', $cpid)
  5986. ->where('user_id', $store_uid)
  5987. ->where('type', 2)
  5988. ->where('product', $product)
  5989. ->where('product_name', '新建文件夹')
  5990. ->where('is_deleted', 0)
  5991. ->exists();
  5992. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5993. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5994. }
  5995. // 创建文件夹
  5996. $folder_id = DB::table('mp_products')->insertGetId([
  5997. 'user_id' => $store_uid,
  5998. 'cpid' => $cpid,
  5999. 'type' => 2,
  6000. 'parent_id' => $parent_id,
  6001. 'level' => $parent_level + 1,
  6002. 'product_name' => $folder_name,
  6003. 'product' => $product,
  6004. 'sort_order' => time(), // 使用时间戳作为排序权重
  6005. 'is_deleted' => 0,
  6006. 'created_at' => date('Y-m-d H:i:s'),
  6007. 'updated_at' => date('Y-m-d H:i:s')
  6008. ]);
  6009. return [
  6010. 'id' => $folder_id,
  6011. 'type' => 2,
  6012. 'parent_id' => $parent_id,
  6013. 'level' => $parent_level + 1,
  6014. 'product_name' => $folder_name,
  6015. 'product' => $product,
  6016. ];
  6017. }
  6018. /**
  6019. * 重命名文件夹或角色
  6020. * @param array $data 包含 id、product_name(新名称)
  6021. * @return bool
  6022. */
  6023. public function renameFolder($data) {
  6024. $uid = Site::getUid();
  6025. $cpid = Site::getCpid();
  6026. $role = Site::getRole();
  6027. $id = getProp($data, 'id');
  6028. $new_name = getProp($data, 'product_name');
  6029. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6030. if (!$id || !$new_name) {
  6031. Utils::throwError('20003:参数不完整');
  6032. }
  6033. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6034. $query_uid = $is_public ? 0 : $uid;
  6035. // 如果是公共库操作,需要admin权限
  6036. if ($is_public && $role !== 'admin') {
  6037. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6038. }
  6039. // 检查是否存在
  6040. $item = DB::table('mp_products')
  6041. ->where('id', $id)
  6042. ->where('cpid', $cpid)
  6043. ->where('user_id', $query_uid)
  6044. ->where('is_deleted', 0)
  6045. ->first();
  6046. if (!$item) {
  6047. Utils::throwError('20003:项目不存在');
  6048. }
  6049. return DB::table('mp_products')
  6050. ->where('id', $id)
  6051. ->where('cpid', $cpid)
  6052. ->where('user_id', $query_uid)
  6053. ->update([
  6054. 'product_name' => $new_name,
  6055. 'updated_at' => date('Y-m-d H:i:s')
  6056. ]);
  6057. }
  6058. /**
  6059. * 移动角色或文件夹到指定文件夹
  6060. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6061. * @return bool
  6062. */
  6063. public function moveProductOrFolder($data) {
  6064. $uid = Site::getUid();
  6065. $cpid = Site::getCpid();
  6066. $role = Site::getRole();
  6067. $id = getProp($data, 'id');
  6068. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6069. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6070. if (!$id) {
  6071. Utils::throwError('20003:请选择要移动的项目');
  6072. }
  6073. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6074. $query_uid = $is_public ? 0 : $uid;
  6075. // 如果是公共库操作,需要admin权限
  6076. if ($is_public && $role !== 'admin') {
  6077. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6078. }
  6079. // 检查要移动的项目
  6080. $item = DB::table('mp_products')
  6081. ->where('id', $id)
  6082. ->where('cpid', $cpid)
  6083. ->where('user_id', $query_uid)
  6084. ->where('is_deleted', 0)
  6085. ->first();
  6086. if (!$item) {
  6087. Utils::throwError('20003:项目不存在');
  6088. }
  6089. // 验证目标文件夹
  6090. $target_level = 0;
  6091. $target_product = $item->product; // 默认使用当前项目的 product
  6092. if ($target_parent_id > 0) {
  6093. $target_parent = DB::table('mp_products')
  6094. ->where('id', $target_parent_id)
  6095. ->where('cpid', $cpid)
  6096. ->where('user_id', $query_uid)
  6097. ->where('type', 2)
  6098. ->where('is_deleted', 0)
  6099. ->first();
  6100. if (!$target_parent) {
  6101. Utils::throwError('20003:目标文件夹不存在');
  6102. }
  6103. // 检查 product 类型是否一致
  6104. if ($target_parent->product != $item->product) {
  6105. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6106. }
  6107. $target_level = $target_parent->level;
  6108. $target_product = $target_parent->product;
  6109. // 如果移动的是文件夹,需要检查层级
  6110. if ($item->type == 2) {
  6111. // 计算移动后的最大层级
  6112. $max_child_level = $this->getMaxChildLevel($id);
  6113. $depth = $max_child_level - $item->level;
  6114. if ($target_level + 1 + $depth > 3) {
  6115. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6116. }
  6117. // 不能移动到自己或自己的子文件夹下
  6118. if ($this->isDescendant($target_parent_id, $id)) {
  6119. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6120. }
  6121. }
  6122. }
  6123. // 更新父文件夹和层级
  6124. $new_level = $target_level + 1;
  6125. DB::table('mp_products')
  6126. ->where('id', $id)
  6127. ->update([
  6128. 'parent_id' => $target_parent_id,
  6129. 'level' => $new_level,
  6130. 'updated_at' => date('Y-m-d H:i:s')
  6131. ]);
  6132. // 如果是文件夹,需要递归更新所有子项的层级
  6133. if ($item->type == 2) {
  6134. $this->updateChildrenLevel($id, $new_level);
  6135. }
  6136. return true;
  6137. }
  6138. /**
  6139. * 获取文件夹下最大子层级
  6140. * @param int $folder_id
  6141. * @return int
  6142. */
  6143. private function getMaxChildLevel($folder_id) {
  6144. $max_level = DB::table('mp_products')
  6145. ->where('parent_id', $folder_id)
  6146. ->where('is_deleted', 0)
  6147. ->max('level');
  6148. if (!$max_level) {
  6149. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6150. }
  6151. // 递归查找子文件夹
  6152. $children = DB::table('mp_products')
  6153. ->where('parent_id', $folder_id)
  6154. ->where('type', 2)
  6155. ->where('is_deleted', 0)
  6156. ->pluck('id');
  6157. foreach ($children as $child_id) {
  6158. $child_max = $this->getMaxChildLevel($child_id);
  6159. if ($child_max > $max_level) {
  6160. $max_level = $child_max;
  6161. }
  6162. }
  6163. return $max_level;
  6164. }
  6165. /**
  6166. * 检查 target_id 是否是 folder_id 的后代
  6167. * @param int $target_id
  6168. * @param int $folder_id
  6169. * @return bool
  6170. */
  6171. private function isDescendant($target_id, $folder_id) {
  6172. if ($target_id == $folder_id) {
  6173. return true;
  6174. }
  6175. $parent = DB::table('mp_products')
  6176. ->where('id', $target_id)
  6177. ->where('is_deleted', 0)
  6178. ->first();
  6179. if (!$parent || $parent->parent_id == 0) {
  6180. return false;
  6181. }
  6182. return $this->isDescendant($parent->parent_id, $folder_id);
  6183. }
  6184. /**
  6185. * 递归更新子项层级
  6186. * @param int $parent_id
  6187. * @param int $parent_level
  6188. */
  6189. private function updateChildrenLevel($parent_id, $parent_level) {
  6190. $children = DB::table('mp_products')
  6191. ->where('parent_id', $parent_id)
  6192. ->where('is_deleted', 0)
  6193. ->get();
  6194. foreach ($children as $child) {
  6195. $new_level = $parent_level + 1;
  6196. DB::table('mp_products')
  6197. ->where('id', $child->id)
  6198. ->update([
  6199. 'level' => $new_level,
  6200. 'updated_at' => date('Y-m-d H:i:s')
  6201. ]);
  6202. // 如果是文件夹,继续递归
  6203. if ($child->type == 2) {
  6204. $this->updateChildrenLevel($child->id, $new_level);
  6205. }
  6206. }
  6207. }
  6208. /**
  6209. * 获取文件夹路径(面包屑导航)
  6210. * @param array $data 包含 folder_id
  6211. * @return array 返回路径数组
  6212. */
  6213. public function getFolderPath($data) {
  6214. $uid = Site::getUid();
  6215. $cpid = Site::getCpid();
  6216. $folder_id = getProp($data, 'id', 0);
  6217. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6218. if ($folder_id == 0) {
  6219. return [
  6220. ['id' => 0, 'name' => '根目录']
  6221. ];
  6222. }
  6223. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6224. $query_uid = $is_public ? 0 : $uid;
  6225. $path = [];
  6226. $current_id = $folder_id;
  6227. while ($current_id > 0) {
  6228. $folder = DB::table('mp_products')
  6229. ->where('id', $current_id)
  6230. ->where('cpid', $cpid)
  6231. ->where('user_id', $query_uid)
  6232. ->where('type', 2)
  6233. ->where('is_deleted', 0)
  6234. ->first();
  6235. if (!$folder) {
  6236. break;
  6237. }
  6238. array_unshift($path, [
  6239. 'id' => $folder->id,
  6240. 'name' => $folder->product_name
  6241. ]);
  6242. $current_id = $folder->parent_id;
  6243. }
  6244. // 添加根目录
  6245. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6246. return $path;
  6247. }
  6248. public function createProduct($data) {
  6249. $uid = Site::getUid();
  6250. $cpid = Site::getCpid();
  6251. $role = Site::getRole();
  6252. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6253. // 如果是公共库操作,需要admin权限
  6254. if ($is_public && $role !== 'admin') {
  6255. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6256. }
  6257. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6258. $store_uid = $is_public ? 0 : $uid;
  6259. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6260. $script_id = (int)getProp($data, 'script_id', 0);
  6261. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6262. if ($script_id && empty($episode_numbers)) {
  6263. Utils::throwError('20003:剧集序号不能为空');
  6264. }
  6265. if (!$script_id && !empty($episode_numbers)) {
  6266. Utils::throwError('20003:请提供剧本ID');
  6267. }
  6268. $product_name = trim(getProp($data, 'product_name'));
  6269. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6270. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6271. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6272. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6273. $url = trim(getProp($data, 'url'));
  6274. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6275. $versions = getProp($data, 'versions');
  6276. // 检查是否是正确的图片格式
  6277. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6278. $urlPath = parse_url($url, PHP_URL_PATH);
  6279. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6280. if (!in_array($extension, $allowedExtensions)) {
  6281. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6282. }
  6283. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6284. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6285. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6286. $product = getProp($data, 'product');
  6287. if (!in_array($product, [1, 2, 3])) {
  6288. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6289. }
  6290. // 获取父文件夹ID和层级
  6291. $parent_id = getProp($data, 'parent_id', 0);
  6292. $parent_level = 0;
  6293. if ($parent_id > 0) {
  6294. $parent = DB::table('mp_products')
  6295. ->where('id', $parent_id)
  6296. ->where('cpid', $cpid)
  6297. ->where('user_id', $store_uid)
  6298. ->where('type', 2)
  6299. ->where('is_deleted', 0)
  6300. ->first();
  6301. if (!$parent) {
  6302. Utils::throwError('20003:父文件夹不存在');
  6303. }
  6304. $parent_level = $parent->level;
  6305. }
  6306. // 创建资产并保存剧本资产关联关系(同一事务)
  6307. DB::beginTransaction();
  6308. try {
  6309. $id = DB::table('mp_products')->insertGetId([
  6310. 'user_id' => $store_uid,
  6311. 'cpid' => $cpid,
  6312. 'type' => 1, // 1=角色图片
  6313. 'parent_id' => $parent_id,
  6314. 'level' => $parent_level + 1,
  6315. 'product_name' => $product_name,
  6316. 'url' => $url,
  6317. 'pic_prompt' => $pic_prompt,
  6318. 'product' => $product,
  6319. 'versions' => json_encode($versions, 256),
  6320. 'sort_order' => time(), // 使用时间戳作为排序权重
  6321. 'created_at' => date('Y-m-d H:i:s'),
  6322. 'updated_at' => date('Y-m-d H:i:s')
  6323. ]);
  6324. if (!$id) Utils::throwError('20003:创建失败');
  6325. // 保存剧本资产关联关系
  6326. if ($script_id) {
  6327. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6328. }
  6329. DB::commit();
  6330. } catch (\Exception $e) {
  6331. DB::rollback();
  6332. throw $e;
  6333. }
  6334. return [
  6335. 'id' => $id,
  6336. 'type' => 1,
  6337. 'parent_id' => $parent_id,
  6338. 'level' => $parent_level + 1,
  6339. 'product_name' => $product_name,
  6340. 'url' => $url,
  6341. 'pic_prompt' => $pic_prompt,
  6342. 'product' => $product,
  6343. 'versions' => $versions
  6344. ];
  6345. }
  6346. public function editProduct($data) {
  6347. $uid = Site::getUid();
  6348. $cpid = Site::getCpid();
  6349. $role = Site::getRole();
  6350. $id = getProp($data, 'id');
  6351. if (!$id) Utils::throwError('20003:ID不能为空');
  6352. $versions = getProp($data, 'versions');
  6353. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6354. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6355. $script_id = (int)getProp($data, 'script_id', 0);
  6356. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6357. if ($script_id && empty($episode_numbers)) {
  6358. Utils::throwError('20003:剧集序号不能为空');
  6359. }
  6360. if (!$script_id && !empty($episode_numbers)) {
  6361. Utils::throwError('20003:请提供剧本ID');
  6362. }
  6363. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6364. $query_uid = $is_public ? 0 : $uid;
  6365. // 如果是公共库操作,需要admin权限
  6366. if ($is_public && $role !== 'admin') {
  6367. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6368. }
  6369. // 检查是否存在且属于当前用户或公共库
  6370. $role = DB::table('mp_products')
  6371. ->where('id', $id)
  6372. ->where('cpid', $cpid)
  6373. ->where('user_id', $query_uid)
  6374. ->where('type', 1)->first();
  6375. if (!$role) Utils::throwError('20003:记录不存在');
  6376. $updateData = [];
  6377. // $needVersionRecord = false; // 是否需要记录版本
  6378. // 名称
  6379. $product_name = trim(getProp($data, 'product_name'));
  6380. if ($product_name) {
  6381. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6382. $updateData['product_name'] = $product_name;
  6383. }
  6384. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6385. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6386. // 图片地址
  6387. $url = trim(getProp($data, 'url'));
  6388. if ($url) {
  6389. // 检查是否是正确的图片格式
  6390. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6391. $urlPath = parse_url($url, PHP_URL_PATH);
  6392. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6393. if (!in_array($extension, $allowedExtensions)) {
  6394. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6395. }
  6396. // // 如果 url 有变更,记录版本
  6397. // if ($url !== $role->url) {
  6398. // $needVersionRecord = true;
  6399. // }
  6400. $updateData['url'] = $url;
  6401. }
  6402. // 提示词
  6403. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6404. if ($pic_prompt) {
  6405. // // 如果 pic_prompt 有变更,记录版本
  6406. // if ($pic_prompt !== $role->pic_prompt) {
  6407. // $needVersionRecord = true;
  6408. // }
  6409. $updateData['pic_prompt'] = $pic_prompt;
  6410. }
  6411. if (empty($updateData) && !$script_id) {
  6412. Utils::throwError('20003:没有需要更新的数据');
  6413. }
  6414. // // 如果需要记录版本,将数据添加到 versions 数组
  6415. // if ($needVersionRecord) {
  6416. // // 获取现有的 versions 数据
  6417. // $versions = json_decode($role->versions, true) ?: [];
  6418. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6419. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6420. // if ($isFirstVersion) {
  6421. // $oldVersion = [
  6422. // 'url' => $role->url,
  6423. // 'description' => $role->pic_prompt,
  6424. // ];
  6425. // // 旧版本添加到数组末尾
  6426. // $versions[] = $oldVersion;
  6427. // }
  6428. // // 构建新版本(变更后)
  6429. // $newVersion = [
  6430. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6431. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6432. // ];
  6433. // // 检查新版本是否已存在于历史版本中
  6434. // $existingIndex = -1;
  6435. // foreach ($versions as $index => $version) {
  6436. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6437. // $existingIndex = $index;
  6438. // break;
  6439. // }
  6440. // }
  6441. // if ($existingIndex !== -1) {
  6442. // // 如果已存在,移除旧的位置
  6443. // array_splice($versions, $existingIndex, 1);
  6444. // }
  6445. // // 新版本添加到数组开头(最新的在前)
  6446. // array_unshift($versions, $newVersion);
  6447. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6448. // // if (count($versions) > 10) {
  6449. // // $versions = array_slice($versions, 0, 10);
  6450. // // }
  6451. // $updateData['versions'] = json_encode($versions, 256);
  6452. // }
  6453. if ($versions) {
  6454. $updateData['versions'] = json_encode($versions, 256);
  6455. }
  6456. if (!empty($updateData)) {
  6457. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6458. }
  6459. // 更新资产并保存剧本资产关联关系(同一事务)
  6460. DB::beginTransaction();
  6461. try {
  6462. $updated = true;
  6463. if (!empty($updateData)) {
  6464. $updated = DB::table('mp_products')
  6465. ->where('cpid', $cpid)
  6466. ->where('id', $id)
  6467. ->update($updateData);
  6468. }
  6469. // 保存剧本资产关联关系
  6470. if ($script_id) {
  6471. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6472. }
  6473. DB::commit();
  6474. } catch (\Exception $e) {
  6475. DB::rollback();
  6476. throw $e;
  6477. }
  6478. return $updated;
  6479. }
  6480. /**
  6481. * 保存单一资产与剧本剧集的关联关系
  6482. *
  6483. * @param int $product_id 资产ID
  6484. * @param int $script_id 剧本ID
  6485. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6486. * @return int 新增关联数量
  6487. */
  6488. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6489. $uid = Site::getUid();
  6490. // 验证剧本是否存在
  6491. $script = DB::table('mp_scripts')
  6492. ->where('id', $script_id)
  6493. ->where('is_deleted', 0)
  6494. ->first();
  6495. if (!$script) {
  6496. Utils::throwError('20003:剧本不存在');
  6497. }
  6498. // 验证剧本归属:只能关联自己的剧本
  6499. if ((int)$script->user_id !== (int)$uid) {
  6500. Utils::throwError('20003:只能添加到自己的剧本');
  6501. }
  6502. // 使用 splitContent 拆分剧本内容获取总集数
  6503. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6504. // 解析剧集序号(数组)
  6505. $episodes = [];
  6506. foreach ($episode_numbers as $item) {
  6507. if (is_array($item)) {
  6508. continue;
  6509. }
  6510. $item = trim((string)$item);
  6511. if ($item === '' || !is_numeric($item)) {
  6512. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6513. }
  6514. $episodes[] = (int)$item;
  6515. }
  6516. // 去重并校验序号范围(序号从1开始)
  6517. $episodes = array_values(array_unique($episodes));
  6518. if (empty($episodes)) {
  6519. Utils::throwError('20003:剧集序号不能为空');
  6520. }
  6521. foreach ($episodes as $episode) {
  6522. if ($episode < 1 || $episode > $totalEpisodes) {
  6523. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6524. }
  6525. }
  6526. $now = now();
  6527. // 过滤已存在的关联,避免重复
  6528. $existingEpisodes = DB::table('mp_script_product_mappings')
  6529. ->where('script_id', $script_id)
  6530. ->where('product_id', $product_id)
  6531. ->whereIn('episode_number', $episodes)
  6532. ->pluck('episode_number')
  6533. ->all();
  6534. $mappingRecords = [];
  6535. foreach ($episodes as $episode) {
  6536. if (in_array($episode, $existingEpisodes)) {
  6537. continue;
  6538. }
  6539. $mappingRecords[] = [
  6540. 'script_id' => $script_id,
  6541. 'product_id' => $product_id,
  6542. 'episode_number' => $episode,
  6543. 'created_at' => $now,
  6544. 'updated_at' => $now,
  6545. ];
  6546. }
  6547. $insertedCount = 0;
  6548. if (!empty($mappingRecords)) {
  6549. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6550. }
  6551. return $insertedCount;
  6552. }
  6553. /**
  6554. * 规范化剧集序号参数,统一为数组
  6555. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6556. *
  6557. * @param mixed $episode_number 剧集序号参数
  6558. * @return array
  6559. */
  6560. private function normalizeEpisodeNumbers($episode_number) {
  6561. if (!is_array($episode_number)) {
  6562. $episode_number = explode(',', (string)$episode_number);
  6563. }
  6564. $items = [];
  6565. foreach ($episode_number as $item) {
  6566. if (is_array($item)) {
  6567. continue;
  6568. }
  6569. foreach (explode(',', (string)$item) as $part) {
  6570. $part = trim($part);
  6571. if ($part !== '') {
  6572. $items[] = $part;
  6573. }
  6574. }
  6575. }
  6576. return $items;
  6577. }
  6578. /**
  6579. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6580. *
  6581. * @param object $script 剧本记录
  6582. * @return int 总集数
  6583. */
  6584. private function getScriptTotalEpisodeCount($script) {
  6585. if (empty($script->content)) {
  6586. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6587. }
  6588. $totalEpisodes = count(splitContent($script->content));
  6589. if ($totalEpisodes < 1) {
  6590. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6591. }
  6592. return $totalEpisodes;
  6593. }
  6594. /**
  6595. * 获取剧本总集数
  6596. *
  6597. * @param array $data 包含 script_id(剧本ID)
  6598. * @return array
  6599. */
  6600. public function getScriptTotalEpisodes($data) {
  6601. $script_id = (int)getProp($data, 'script_id', 0);
  6602. if (!$script_id) {
  6603. Utils::throwError('20003:请提供剧本ID');
  6604. }
  6605. // 验证剧本是否存在
  6606. $script = DB::table('mp_scripts')
  6607. ->where('id', $script_id)
  6608. ->where('is_deleted', 0)
  6609. ->first();
  6610. if (!$script) {
  6611. Utils::throwError('20003:剧本不存在');
  6612. }
  6613. return [
  6614. 'script_id' => $script_id,
  6615. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6616. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6617. ];
  6618. }
  6619. /**
  6620. * 获取角色版本历史
  6621. * @param array $data 包含 id(角色ID)
  6622. * @return array 返回版本历史列表
  6623. */
  6624. public function getProductVersions($data) {
  6625. $cpid = Site::getCpid();
  6626. $id = getProp($data, 'id');
  6627. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6628. $role = DB::table('mp_products')
  6629. ->where('id', $id)
  6630. ->where('cpid', $cpid)
  6631. ->where('type', 1)
  6632. ->first();
  6633. if (!$role) Utils::throwError('20003:角色不存在');
  6634. // 获取版本历史
  6635. $versions = json_decode($role->versions, true) ?: [];
  6636. // 添加当前版本作为最新版本
  6637. $currentVersion = [
  6638. 'version' => 0, // 0 表示当前版本
  6639. 'url' => $role->url,
  6640. 'pic_prompt' => $role->pic_prompt,
  6641. 'updated_at' => $role->updated_at,
  6642. 'is_current' => true
  6643. ];
  6644. array_unshift($versions, $currentVersion);
  6645. return $versions;
  6646. }
  6647. /**
  6648. * 恢复到指定版本
  6649. * @param array $data 包含 id(角色ID)、version(版本号)
  6650. * @return bool
  6651. */
  6652. public function restoreProductVersion($data) {
  6653. $uid = Site::getUid();
  6654. $cpid = Site::getCpid();
  6655. $id = getProp($data, 'id');
  6656. $version = getProp($data, 'version');
  6657. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6658. if (!$version) Utils::throwError('20003:版本号不能为空');
  6659. $role = DB::table('mp_products')
  6660. ->where('id', $id)
  6661. ->where('cpid', $cpid)
  6662. ->where('type', 1)
  6663. ->first();
  6664. if (!$role) Utils::throwError('20003:角色不存在');
  6665. // 获取版本历史
  6666. $versions = json_decode($role->versions, true) ?: [];
  6667. // 查找指定版本
  6668. $targetVersion = null;
  6669. foreach ($versions as $v) {
  6670. if ($v['version'] == $version) {
  6671. $targetVersion = $v;
  6672. break;
  6673. }
  6674. }
  6675. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6676. // 先将当前版本保存到历史
  6677. $newVersion = [
  6678. 'version' => count($versions) + 1,
  6679. 'url' => $role->url,
  6680. 'pic_prompt' => $role->pic_prompt,
  6681. 'updated_at' => date('Y-m-d H:i:s'),
  6682. 'updated_by' => $uid
  6683. ];
  6684. array_unshift($versions, $newVersion);
  6685. // 限制版本数量
  6686. if (count($versions) > 10) {
  6687. $versions = array_slice($versions, 0, 10);
  6688. }
  6689. // 恢复到指定版本
  6690. return DB::table('mp_products')
  6691. ->where('id', $id)
  6692. ->where('cpid', $cpid)
  6693. ->update([
  6694. 'url' => $targetVersion['url'],
  6695. 'pic_prompt' => $targetVersion['pic_prompt'],
  6696. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6697. 'updated_at' => date('Y-m-d H:i:s')
  6698. ]);
  6699. }
  6700. public function deleteProduct($data) {
  6701. $uid = Site::getUid();
  6702. $cpid = Site::getCpid();
  6703. $role = Site::getRole();
  6704. $id = getProp($data, 'id');
  6705. if (!$id) Utils::throwError('20003:ID不能为空');
  6706. $ids = explode(',', $id);
  6707. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6708. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6709. $query_uid = $is_public ? 0 : $uid;
  6710. // 如果是公共库操作,需要admin权限
  6711. if ($is_public && $role !== 'admin') {
  6712. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6713. }
  6714. // 检查是否存在且属于当前用户或公共库
  6715. $role = DB::table('mp_products')
  6716. ->whereIn('id', $ids)
  6717. ->where('cpid', $cpid)
  6718. ->where('user_id', $query_uid)
  6719. ->get();
  6720. if (!$role) Utils::throwError('20003:记录不存在');
  6721. return DB::table('mp_products')
  6722. ->where('cpid', $cpid)
  6723. ->where('user_id', $query_uid)
  6724. ->whereIn('id', $ids)
  6725. ->update([
  6726. 'is_deleted' => 1,
  6727. 'updated_at' => date('Y-m-d H:i:s')
  6728. ]);
  6729. }
  6730. public function generateThreeView($data) {
  6731. $uid = Site::getUid();
  6732. $cpid = Site::getCpid();
  6733. $role = Site::getRole();
  6734. $id = getProp($data, 'id');
  6735. if (!$id) Utils::throwError('20003:ID不能为空');
  6736. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6737. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6738. $query_uid = $is_public ? 0 : $uid;
  6739. // 如果是公共库操作,需要admin权限
  6740. if ($is_public && $role !== 'admin') {
  6741. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6742. }
  6743. // 检查是否存在且属于当前用户或公共库
  6744. $product = DB::table('mp_products')
  6745. ->where('id', $id)
  6746. ->where('cpid', $cpid)
  6747. ->where('user_id', $query_uid)
  6748. ->where('type', 1)->first();
  6749. if (!$product) Utils::throwError('20003:资产不存在');
  6750. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6751. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6752. if (!$ref_img_url) {
  6753. // 如果没有传入参考图,使用角色表中的图片
  6754. $ref_img_url = $product->url ?? '';
  6755. if (!$ref_img_url) {
  6756. Utils::throwError('20003:参考图不能为空');
  6757. }
  6758. }
  6759. $pic_prompt = getProp($product, 'pic_prompt');
  6760. if ($pic_prompt) {
  6761. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6762. }
  6763. // 检查参考图是否是正确的图片格式
  6764. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6765. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6766. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6767. if (!in_array($extension, $allowedExtensions)) {
  6768. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6769. }
  6770. // 处理图片模型
  6771. $model = getProp($data, 'model');
  6772. if (!$model) {
  6773. // 使用默认模型
  6774. $model = 'doubao-seedream-5-0-lite-260128';
  6775. }
  6776. // 验证模型是否在可用模型表中
  6777. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6778. Utils::throwError('20003:该模型已不可用,请更换!');
  6779. }
  6780. $ratio = getProp($data, 'ratio', '16:9');
  6781. $resolution = getProp($data, 'resolution', '2k');
  6782. // 定义分辨率和宽高比对应的尺寸映射表
  6783. $sizeMap = [
  6784. '2k' => [
  6785. '1:1' => ['width' => 2048, 'height' => 2048],
  6786. '4:3' => ['width' => 2304, 'height' => 1728],
  6787. '3:4' => ['width' => 1728, 'height' => 2304],
  6788. '16:9' => ['width' => 2848, 'height' => 1600],
  6789. '9:16' => ['width' => 1600, 'height' => 2848],
  6790. '3:2' => ['width' => 2496, 'height' => 1664],
  6791. '2:3' => ['width' => 1664, 'height' => 2496],
  6792. '21:9' => ['width' => 3136, 'height' => 1344],
  6793. ],
  6794. '3k' => [
  6795. '1:1' => ['width' => 3072, 'height' => 3072],
  6796. '4:3' => ['width' => 3456, 'height' => 2592],
  6797. '3:4' => ['width' => 2592, 'height' => 3456],
  6798. '16:9' => ['width' => 4096, 'height' => 2304],
  6799. '9:16' => ['width' => 2304, 'height' => 4096],
  6800. '2:3' => ['width' => 2496, 'height' => 3744],
  6801. '3:2' => ['width' => 3744, 'height' => 2496],
  6802. '21:9' => ['width' => 4704, 'height' => 2016],
  6803. ],
  6804. '4k' => [
  6805. '1:1' => ['width' => 4096, 'height' => 4096],
  6806. '3:4' => ['width' => 3520, 'height' => 4704],
  6807. '4:3' => ['width' => 4704, 'height' => 3520],
  6808. '16:9' => ['width' => 5504, 'height' => 3040],
  6809. '9:16' => ['width' => 3040, 'height' => 5504],
  6810. '2:3' => ['width' => 3328, 'height' => 4992],
  6811. '3:2' => ['width' => 4992, 'height' => 3328],
  6812. '21:9' => ['width' => 6240, 'height' => 2656],
  6813. ],
  6814. ];
  6815. // 参数验证
  6816. $resolution = strtolower($resolution);
  6817. if (!isset($sizeMap[$resolution])) {
  6818. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6819. }
  6820. if (!isset($sizeMap[$resolution][$ratio])) {
  6821. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6822. }
  6823. // 根据 ratio 和 resolution 确定宽高
  6824. $width = $sizeMap[$resolution][$ratio]['width'];
  6825. $height = $sizeMap[$resolution][$ratio]['height'];
  6826. try {
  6827. // 创建图片生成任务
  6828. $params = [
  6829. 'prompt' => $prompt,
  6830. 'model' => $model,
  6831. 'ref_img_urls' => [$ref_img_url],
  6832. 'width' => $width,
  6833. 'height' => $height
  6834. ];
  6835. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6836. $task_id = $task->id;
  6837. if (!$task_id) {
  6838. Utils::throwError('20003:创建图片生成任务失败');
  6839. }
  6840. // 轮询获取结果
  6841. // 只查询数据库,不调用API,不更新任务表
  6842. $start_time = time();
  6843. $timeout = 1800;
  6844. $img_url = '';
  6845. while (time() - $start_time < $timeout) {
  6846. sleep(5);
  6847. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6848. $task = DB::table('mp_generate_pic_tasks')
  6849. ->where('id', $task_id)
  6850. ->first();
  6851. if (!$task) {
  6852. Utils::throwError('20003:任务不存在');
  6853. }
  6854. if ($task->status === 'success' && $task->result_url) {
  6855. $result_urls = is_string($task->result_url)
  6856. ? json_decode($task->result_url, true)
  6857. : $task->result_url;
  6858. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6859. break;
  6860. } elseif ($task->status === 'failed') {
  6861. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6862. }
  6863. // 其他状态继续轮询
  6864. }
  6865. if (empty($img_url)) {
  6866. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6867. }
  6868. // 更新 mp_products 表(不是任务表)
  6869. DB::table('mp_products')
  6870. ->where('id', $id)
  6871. ->where('cpid', $cpid)
  6872. ->update([
  6873. 'three_view_image_url' => $img_url,
  6874. 'updated_at' => date('Y-m-d H:i:s')
  6875. ]);
  6876. return ['three_view_image_url' => $img_url];
  6877. } catch (\Exception $e) {
  6878. dLog('anime')->error('生成三视图失败', [
  6879. 'error' => $e->getMessage()
  6880. ]);
  6881. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6882. Utils::throwError('20003:' . $e->getMessage());
  6883. }
  6884. }
  6885. /**
  6886. * 推送(复制)资产或文件夹到目标位置
  6887. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6888. * @return array 返回推送结果
  6889. */
  6890. public function pushProductOrFolder($data) {
  6891. $uid = Site::getUid();
  6892. $cpid = Site::getCpid();
  6893. $role = Site::getRole();
  6894. $product_id = getProp($data, 'product_id');
  6895. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6896. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6897. if (!$product_id) {
  6898. Utils::throwError('20003:请选择要推送的项目');
  6899. }
  6900. // 查询源项目(只通过cpid查询,不限制user_id)
  6901. $sourceItem = DB::table('mp_products')
  6902. ->where('id', $product_id)
  6903. ->where('cpid', $cpid)
  6904. ->where('is_deleted', 0)
  6905. ->first();
  6906. if (!$sourceItem) {
  6907. Utils::throwError('20003:要推送的项目不存在');
  6908. }
  6909. // 通过user_id判断源是公共库还是个人库
  6910. $source_uid = $sourceItem->user_id;
  6911. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6912. // 验证目标文件夹并确定目标是公共库还是个人库
  6913. $target_level = 0;
  6914. $target_uid = $uid; // 默认推送到个人库
  6915. $target_is_public = 0;
  6916. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6917. if ($target_parent_id > 0) {
  6918. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6919. $targetParent = DB::table('mp_products')
  6920. ->where('id', $target_parent_id)
  6921. ->where('cpid', $cpid)
  6922. ->where('type', 2)
  6923. ->where('is_deleted', 0)
  6924. ->first();
  6925. if (!$targetParent) {
  6926. Utils::throwError('20003:目标文件夹不存在');
  6927. }
  6928. // 通过user_id判断目标是公共库还是个人库
  6929. $target_level = $targetParent->level;
  6930. $target_uid = $targetParent->user_id;
  6931. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6932. // 使用目标文件夹的 product 类型
  6933. $final_product_type = $targetParent->product;
  6934. }
  6935. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6936. else {
  6937. $push_to_public = getProp($data, 'push_to_public');
  6938. if ($push_to_public === '') {
  6939. Utils::throwError('20003:请选择是否推送到公共库');
  6940. }
  6941. if ($push_to_public) {
  6942. $target_uid = 0;
  6943. $target_is_public = 1;
  6944. }
  6945. // 推送到根目录时,必须指定 product 类型
  6946. if ($target_product === null || $target_product === '') {
  6947. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6948. }
  6949. $final_product_type = $target_product;
  6950. }
  6951. // 如果目标是公共库,需要admin权限
  6952. if ($target_is_public && $role !== 'admin') {
  6953. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6954. }
  6955. // 权限验证:验证是否符合允许的推送规则
  6956. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6957. try {
  6958. DB::beginTransaction();
  6959. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6960. if ($sourceItem->type == 1) {
  6961. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6962. DB::commit();
  6963. return [
  6964. 'product_id' => $newId,
  6965. ];
  6966. }
  6967. // 如果是文件夹,递归复制(支持跨类型推送)
  6968. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6969. DB::commit();
  6970. return [
  6971. 'product_id' => $newFolderId,
  6972. ];
  6973. } catch (\Exception $e) {
  6974. DB::rollBack();
  6975. dLog('anime')->error('推送失败', [
  6976. 'error' => $e->getMessage(),
  6977. 'product_id' => $product_id
  6978. ]);
  6979. Utils::throwError('20003:' . $e->getMessage());
  6980. }
  6981. }
  6982. /**
  6983. * 验证推送权限
  6984. * 允许的推送规则:
  6985. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6986. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6987. * 3. 公共库推送给公共库(公共库 → 公共库)
  6988. *
  6989. * @param int $source_uid 源的user_id
  6990. * @param int $target_uid 目标的user_id
  6991. * @param int $current_uid 当前用户ID
  6992. * @throws \Exception
  6993. */
  6994. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6995. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6996. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6997. return; // 允许
  6998. }
  6999. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7000. if ($source_uid == 0 && $target_uid == $current_uid) {
  7001. return; // 允许
  7002. }
  7003. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7004. if ($source_uid == 0 && $target_uid == 0) {
  7005. return; // 允许
  7006. }
  7007. // 其他情况都不允许
  7008. if ($source_uid != 0 && $source_uid != $current_uid) {
  7009. // 源是别人的个人库
  7010. Utils::throwError('20003:无权限访问该资产');
  7011. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7012. // 个人库推送给公共库(不允许)
  7013. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7014. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7015. // 不同用户的个人库之间推送(不允许)
  7016. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7017. } else {
  7018. // 其他未知情况
  7019. Utils::throwError('20003:不允许的推送操作');
  7020. }
  7021. }
  7022. /**
  7023. * 复制单个资产
  7024. * @param object $sourceProduct 源资产对象
  7025. * @param int $targetParentId 目标父文件夹ID
  7026. * @param int $targetLevel 目标层级
  7027. * @param int $cpid 公司ID
  7028. * @param int $targetUid 目标用户ID
  7029. * @return int 返回新资产ID
  7030. */
  7031. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7032. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7033. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7034. $newProductData = [
  7035. 'user_id' => $targetUid,
  7036. 'cpid' => $cpid,
  7037. 'type' => 1,
  7038. 'parent_id' => $targetParentId,
  7039. 'level' => $targetLevel,
  7040. 'product_name' => $sourceProduct->product_name,
  7041. 'url' => $sourceProduct->url,
  7042. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7043. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7044. 'product' => $finalProductType,
  7045. 'versions' => $sourceProduct->versions ?? '',
  7046. 'sort_order' => time(),
  7047. 'is_deleted' => 0,
  7048. 'created_at' => date('Y-m-d H:i:s'),
  7049. 'updated_at' => date('Y-m-d H:i:s')
  7050. ];
  7051. return DB::table('mp_products')->insertGetId($newProductData);
  7052. }
  7053. /**
  7054. * 递归复制文件夹及其子项
  7055. * @param object $sourceFolder 源文件夹对象
  7056. * @param int $targetParentId 目标父文件夹ID
  7057. * @param int $targetLevel 目标层级
  7058. * @param int $cpid 公司ID
  7059. * @param int $targetUid 目标用户ID
  7060. * @param int $sourceUid 源用户ID
  7061. * @return int 返回新文件夹ID
  7062. */
  7063. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7064. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7065. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7066. // 创建新文件夹
  7067. $newFolderData = [
  7068. 'user_id' => $targetUid,
  7069. 'cpid' => $cpid,
  7070. 'type' => 2,
  7071. 'parent_id' => $targetParentId,
  7072. 'level' => $targetLevel,
  7073. 'product_name' => $sourceFolder->product_name,
  7074. 'product' => $finalProductType,
  7075. 'sort_order' => time(),
  7076. 'is_deleted' => 0,
  7077. 'created_at' => date('Y-m-d H:i:s'),
  7078. 'updated_at' => date('Y-m-d H:i:s')
  7079. ];
  7080. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7081. // 获取源文件夹下的所有子项
  7082. $children = DB::table('mp_products')
  7083. ->where('parent_id', $sourceFolder->id)
  7084. ->where('cpid', $cpid)
  7085. ->where('user_id', $sourceUid)
  7086. ->where('is_deleted', 0)
  7087. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7088. ->get();
  7089. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7090. foreach ($children as $child) {
  7091. if ($child->type == 1) {
  7092. // 资产
  7093. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7094. } else {
  7095. // 文件夹
  7096. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7097. }
  7098. }
  7099. return $newFolderId;
  7100. }
  7101. /**
  7102. * 保存剧本资产关联关系
  7103. * @param array $data 请求参数
  7104. * @return bool
  7105. */
  7106. public function saveScriptProducts($data) {
  7107. $uid = Site::getUid();
  7108. $cpid = Site::getCpid();
  7109. $script_id = getProp($data, 'script_id');
  7110. $products = getProp($data, 'products', []);
  7111. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7112. if (!$script_id) {
  7113. Utils::throwError('20003:请提供剧本ID');
  7114. }
  7115. // 验证剧本是否存在
  7116. $script = DB::table('mp_scripts')
  7117. ->where('id', $script_id)
  7118. ->where('is_deleted', 0)
  7119. ->first();
  7120. if (!$script) {
  7121. Utils::throwError('20003:剧本不存在');
  7122. }
  7123. // 处理图片模型
  7124. $model = getProp($data, 'model');
  7125. if (!$model) {
  7126. // 使用默认模型
  7127. $model = 'doubao-seedream-5-0-lite-260128';
  7128. }
  7129. // 验证模型是否在可用模型表中
  7130. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7131. Utils::throwError('20003:该模型已不可用,请更换!');
  7132. }
  7133. $ratio = getProp($data, 'ratio', '9:16');
  7134. $resolution = getProp($data, 'resolution', '2k');
  7135. // 定义分辨率和宽高比对应的尺寸映射表
  7136. $sizeMap = [
  7137. '2k' => [
  7138. '1:1' => ['width' => 2048, 'height' => 2048],
  7139. '4:3' => ['width' => 2304, 'height' => 1728],
  7140. '3:4' => ['width' => 1728, 'height' => 2304],
  7141. '16:9' => ['width' => 2848, 'height' => 1600],
  7142. '9:16' => ['width' => 1600, 'height' => 2848],
  7143. '3:2' => ['width' => 2496, 'height' => 1664],
  7144. '2:3' => ['width' => 1664, 'height' => 2496],
  7145. '21:9' => ['width' => 3136, 'height' => 1344],
  7146. ],
  7147. '3k' => [
  7148. '1:1' => ['width' => 3072, 'height' => 3072],
  7149. '4:3' => ['width' => 3456, 'height' => 2592],
  7150. '3:4' => ['width' => 2592, 'height' => 3456],
  7151. '16:9' => ['width' => 4096, 'height' => 2304],
  7152. '9:16' => ['width' => 2304, 'height' => 4096],
  7153. '2:3' => ['width' => 2496, 'height' => 3744],
  7154. '3:2' => ['width' => 3744, 'height' => 2496],
  7155. '21:9' => ['width' => 4704, 'height' => 2016],
  7156. ],
  7157. '4k' => [
  7158. '1:1' => ['width' => 4096, 'height' => 4096],
  7159. '3:4' => ['width' => 3520, 'height' => 4704],
  7160. '4:3' => ['width' => 4704, 'height' => 3520],
  7161. '16:9' => ['width' => 5504, 'height' => 3040],
  7162. '9:16' => ['width' => 3040, 'height' => 5504],
  7163. '2:3' => ['width' => 3328, 'height' => 4992],
  7164. '3:2' => ['width' => 4992, 'height' => 3328],
  7165. '21:9' => ['width' => 6240, 'height' => 2656],
  7166. ],
  7167. ];
  7168. // 参数验证
  7169. $resolution = strtolower($resolution);
  7170. if (!isset($sizeMap[$resolution])) {
  7171. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7172. }
  7173. if (!isset($sizeMap[$resolution][$ratio])) {
  7174. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7175. }
  7176. // 根据 ratio 和 resolution 确定宽高
  7177. $width = $sizeMap[$resolution][$ratio]['width'];
  7178. $height = $sizeMap[$resolution][$ratio]['height'];
  7179. $script_name = $script->script_name ?? 'script_' . $script_id;
  7180. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  7181. $taskCenterId = $this->createScriptProductTaskCenter(
  7182. $uid,
  7183. $cpid,
  7184. $script_id,
  7185. $products,
  7186. $model,
  7187. $ratio,
  7188. $resolution,
  7189. $auto_generate_images
  7190. );
  7191. // 检查是否已经有该剧本的资产数据
  7192. $existingMappings = DB::table('mp_script_product_mappings')
  7193. ->where('script_id', $script_id)
  7194. ->get();
  7195. if ($existingMappings->isNotEmpty()) {
  7196. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7197. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7198. // 查询这些资产的图片生成任务状态
  7199. $productsWithTasks = DB::table('mp_products')
  7200. ->whereIn('id', $productIds)
  7201. ->where('is_deleted', 0)
  7202. ->get();
  7203. $productTaskMap = [];
  7204. $typeFolderIds = [];
  7205. $hasAllTasks = true;
  7206. foreach ($productsWithTasks as $product) {
  7207. // 收集类型文件夹ID
  7208. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7209. $parentFolder = DB::table('mp_products')
  7210. ->where('id', $product->parent_id)
  7211. ->where('type', 2)
  7212. ->first();
  7213. if ($parentFolder) {
  7214. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7215. }
  7216. }
  7217. // 检查是否有图片生成任务
  7218. if (!empty($product->pic_task_id)) {
  7219. $productTaskMap[$product->id] = $product->pic_task_id;
  7220. } else if($product->url && $product->pic_task_status == '生成成功') {
  7221. continue;
  7222. } else {
  7223. // 有资产没有图片任务
  7224. $hasAllTasks = false;
  7225. }
  7226. }
  7227. // 如果所有资产都有任务ID,直接轮询返回结果
  7228. if ($hasAllTasks && !empty($productTaskMap)) {
  7229. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7230. 'script_id' => $script_id,
  7231. 'script_name' => $script_name,
  7232. 'product_count' => count($productTaskMap)
  7233. ]);
  7234. // 直接返回 SSE 流轮询结果
  7235. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7236. }
  7237. // 如果部分资产没有任务ID,只为这些资产创建任务
  7238. if (!$hasAllTasks && $auto_generate_images) {
  7239. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7240. 'script_id' => $script_id,
  7241. 'script_name' => $script_name
  7242. ]);
  7243. // 开启事务
  7244. DB::beginTransaction();
  7245. try {
  7246. foreach ($productsWithTasks as $product) {
  7247. // 跳过已有任务的资产
  7248. if (!empty($product->pic_task_id)) {
  7249. continue;
  7250. }
  7251. // 跳过没有提示词的资产
  7252. if (empty($product->pic_prompt)) {
  7253. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7254. 'product_id' => $product->id,
  7255. 'product_name' => $product->product_name
  7256. ]);
  7257. continue;
  7258. }
  7259. try {
  7260. // 创建图片生成任务
  7261. $params = [
  7262. 'prompt' => $product->pic_prompt,
  7263. 'model' => $model,
  7264. 'ref_img_urls' => [],
  7265. 'width' => $width,
  7266. 'height' => $height
  7267. ];
  7268. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7269. $task_id = $task->id;
  7270. if ($task_id) {
  7271. $productTaskMap[$product->id] = $task_id;
  7272. // 在事务中更新资产表的任务ID和状态
  7273. DB::table('mp_products')
  7274. ->where('id', $product->id)
  7275. ->update([
  7276. 'pic_task_id' => $task_id,
  7277. 'pic_task_status' => '生成中',
  7278. 'updated_at' => now()
  7279. ]);
  7280. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7281. 'product_id' => $product->id,
  7282. 'task_id' => $task_id
  7283. ]);
  7284. }
  7285. } catch (\Exception $e) {
  7286. dLog('anime')->error('创建资产图片生成任务失败', [
  7287. 'product_id' => $product->id,
  7288. 'error' => $e->getMessage()
  7289. ]);
  7290. // 标记为失败(仍在事务中)
  7291. DB::table('mp_products')
  7292. ->where('id', $product->id)
  7293. ->update([
  7294. 'pic_task_status' => '生成失败',
  7295. 'updated_at' => now()
  7296. ]);
  7297. }
  7298. }
  7299. // 提交事务
  7300. DB::commit();
  7301. // 如果有新创建的任务,返回 SSE 流
  7302. if (!empty($productTaskMap)) {
  7303. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7304. }
  7305. } catch (\Exception $e) {
  7306. // 回滚事务
  7307. DB::rollback();
  7308. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7309. 'script_id' => $script_id,
  7310. 'error' => $e->getMessage()
  7311. ]);
  7312. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7313. }
  7314. }
  7315. // 如果不需要生成图片,返回已存在的信息
  7316. $resultData = [
  7317. 'success' => true,
  7318. 'message' => '剧本资产已存在',
  7319. 'script_id' => $script_id,
  7320. 'script_name' => $script_name,
  7321. 'type_folder_ids' => $typeFolderIds,
  7322. 'existing_products' => count($productIds),
  7323. 'tasks_count' => count($productTaskMap),
  7324. 'task_center_id' => $taskCenterId
  7325. ];
  7326. // 接口已正常完成,更新任务中心状态和结果
  7327. if ($taskCenterId) {
  7328. $this->taskCenterService->updateTask($taskCenterId, [
  7329. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7330. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7331. 'error_message' => null
  7332. ]);
  7333. }
  7334. return $resultData;
  7335. }
  7336. // 解析 products(可能是 JSON 字符串或数组)
  7337. if (is_string($products)) {
  7338. $products = json_decode($products, true);
  7339. if (json_last_error() !== JSON_ERROR_NONE) {
  7340. Utils::throwError('20003:产品数据格式错误');
  7341. }
  7342. }
  7343. if (!is_array($products) || empty($products)) {
  7344. Utils::throwError('20003:产品数据不能为空');
  7345. }
  7346. // 以下是原有的创建逻辑...
  7347. // 开启事务
  7348. DB::beginTransaction();
  7349. try {
  7350. $now = now();
  7351. $mappingRecords = [];
  7352. $createdProductIds = []; // 记录所有创建的资产ID
  7353. // 获取剧本名称
  7354. $script_name = $script->script_name ?? 'script_' . $script_id;
  7355. // 存储每个类型的根文件夹ID
  7356. $typeFolderIds = [];
  7357. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7358. foreach ($products as $productGroup) {
  7359. $type = getProp($productGroup, 'type');
  7360. $title = getProp($productGroup, 'title', '');
  7361. $content = getProp($productGroup, 'content', []);
  7362. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7363. continue;
  7364. }
  7365. // 为当前类型创建根文件夹(如果还未创建)
  7366. if (!isset($typeFolderIds[$type])) {
  7367. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7368. 'user_id' => $uid,
  7369. 'cpid' => $cpid,
  7370. 'type' => 2, // 1.资产 2文件夹
  7371. 'product' => $type, // 1.主体 2.场景 3.道具
  7372. 'parent_id' => 0, // 根文件夹,parent_id=0
  7373. 'level' => 1, // 第一层级
  7374. 'product_name' => $script_name,
  7375. 'sort_order' => time() + $type,
  7376. 'is_deleted' => 0,
  7377. 'created_at' => $now,
  7378. 'updated_at' => $now
  7379. ]);
  7380. }
  7381. $folder_id = $typeFolderIds[$type];
  7382. // 获取表头(第一行)并查找关键列的位置
  7383. $headers = $content[0];
  7384. $nameColumnIndex = -1; // 资产名称列索引
  7385. $sequenceColumnIndex = -1; // 使用范围列索引
  7386. $promptColumnIndex = -1; // 参考提示词列索引
  7387. foreach ($headers as $index => $header) {
  7388. // 查找"资产名称"列
  7389. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7390. $nameColumnIndex = $index;
  7391. }
  7392. // 查找"使用范围"列
  7393. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7394. $sequenceColumnIndex = $index;
  7395. }
  7396. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7397. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7398. $promptColumnIndex = $index;
  7399. }
  7400. }
  7401. // 验证必要的列是否都找到了
  7402. if ($nameColumnIndex === -1) {
  7403. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7404. continue;
  7405. }
  7406. if ($sequenceColumnIndex === -1) {
  7407. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7408. continue;
  7409. }
  7410. // 跳过表头,解析每一行数据
  7411. for ($i = 1; $i < count($content); $i++) {
  7412. $row = $content[$i];
  7413. // 确保行数据有效
  7414. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7415. continue;
  7416. }
  7417. // 根据动态查找的列索引提取数据
  7418. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7419. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7420. $pic_prompt = '';
  7421. // 提取参考提示词(如果找到了该列)
  7422. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7423. $pic_prompt = trim($row[$promptColumnIndex]);
  7424. }
  7425. // 解析使用范围(逗号分隔的序号)
  7426. $sequences = [];
  7427. if (!empty($sequence_str)) {
  7428. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7429. foreach ($sequenceParts as $part) {
  7430. if (is_numeric($part)) {
  7431. $sequences[] = (int)$part;
  7432. }
  7433. }
  7434. }
  7435. if (empty($product_name)) {
  7436. continue;
  7437. }
  7438. // 处理product_name两边的符号
  7439. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7440. // 如果名称不存在或仅剩占位符号,则跳过
  7441. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7442. dLog('anime')->warning('资产名称无效,跳过保存', [
  7443. 'script_id' => $script_id,
  7444. 'type' => $type,
  7445. 'product_name' => $product_name
  7446. ]);
  7447. continue;
  7448. }
  7449. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7450. $product_id = DB::table('mp_products')->insertGetId([
  7451. 'product_name' => $product_name,
  7452. 'type' => 1, // 1=资产 2.文件夹
  7453. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7454. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7455. 'level' => 2, // 第二层级
  7456. 'pic_prompt' => $pic_prompt,
  7457. 'user_id' => $uid,
  7458. 'cpid' => $cpid,
  7459. 'sort_order' => time(),
  7460. 'is_deleted' => 0,
  7461. 'created_at' => $now,
  7462. 'updated_at' => $now,
  7463. ]);
  7464. // 记录创建的资产ID
  7465. $createdProductIds[] = $product_id;
  7466. // 为每个序号创建映射记录
  7467. if (!empty($sequences)) {
  7468. foreach ($sequences as $sequence) {
  7469. $mappingRecords[] = [
  7470. 'script_id' => $script_id,
  7471. 'product_id' => $product_id,
  7472. 'episode_number' => $sequence,
  7473. 'created_at' => $now,
  7474. 'updated_at' => $now,
  7475. ];
  7476. }
  7477. } else {
  7478. // 如果没有指定序号,创建一个默认映射(序号为0)
  7479. $mappingRecords[] = [
  7480. 'script_id' => $script_id,
  7481. 'product_id' => $product_id,
  7482. 'episode_number' => 0,
  7483. 'created_at' => $now,
  7484. 'updated_at' => $now,
  7485. ];
  7486. }
  7487. }
  7488. }
  7489. if (empty($mappingRecords)) {
  7490. Utils::throwError('20003:没有有效的产品数据');
  7491. }
  7492. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7493. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7494. // 剧本已有资产,同步更新is_products标记
  7495. DB::table('mp_scripts')->where('id', $script_id)->update([
  7496. 'is_products' => 1,
  7497. 'updated_at' => $now
  7498. ]);
  7499. // 如果需要自动生成图片,在事务中创建图片生成任务
  7500. $productTaskMap = [];
  7501. if ($auto_generate_images && !empty($createdProductIds)) {
  7502. // 查询所有创建的资产
  7503. $productsToGenerate = DB::table('mp_products')
  7504. ->whereIn('id', $createdProductIds)
  7505. ->where('is_deleted', 0)
  7506. ->get();
  7507. foreach ($productsToGenerate as $product) {
  7508. if (empty($product->pic_prompt)) {
  7509. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7510. 'product_id' => $product->id,
  7511. 'product_name' => $product->product_name
  7512. ]);
  7513. continue;
  7514. }
  7515. try {
  7516. // 创建图片生成任务
  7517. $params = [
  7518. 'prompt' => $product->pic_prompt,
  7519. 'model' => $model,
  7520. 'ref_img_urls' => [],
  7521. 'width' => $width,
  7522. 'height' => $height
  7523. ];
  7524. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7525. $task_id = $task->id;
  7526. if ($task_id) {
  7527. $productTaskMap[$product->id] = $task_id;
  7528. // 在事务中更新资产表的任务ID和状态
  7529. DB::table('mp_products')
  7530. ->where('id', $product->id)
  7531. ->update([
  7532. 'pic_task_id' => $task_id,
  7533. 'pic_task_status' => '生成中',
  7534. 'updated_at' => now()
  7535. ]);
  7536. dLog('anime')->info('创建资产图片生成任务', [
  7537. 'product_id' => $product->id,
  7538. 'task_id' => $task_id
  7539. ]);
  7540. }
  7541. } catch (\Exception $e) {
  7542. dLog('anime')->error('创建资产图片生成任务失败', [
  7543. 'product_id' => $product->id,
  7544. 'error' => $e->getMessage()
  7545. ]);
  7546. // 标记为失败(仍在事务中)
  7547. DB::table('mp_products')
  7548. ->where('id', $product->id)
  7549. ->update([
  7550. 'pic_task_status' => '生成失败',
  7551. 'updated_at' => now()
  7552. ]);
  7553. }
  7554. }
  7555. }
  7556. // 提交事务
  7557. DB::commit();
  7558. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7559. if ($auto_generate_images && !empty($productTaskMap)) {
  7560. // 返回 SSE 流(事务外轮询)
  7561. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7562. }
  7563. // 如果不需要生成图片,返回普通结果
  7564. $resultData = [
  7565. 'success' => true,
  7566. 'type_folder_ids' => $typeFolderIds,
  7567. 'inserted_count' => $insertedCount,
  7568. 'total_records' => count($mappingRecords),
  7569. 'created_products' => count($createdProductIds),
  7570. 'image_tasks_created' => count($productTaskMap),
  7571. 'task_center_id' => $taskCenterId
  7572. ];
  7573. // 接口已正常完成,更新任务中心状态和结果
  7574. if ($taskCenterId) {
  7575. $this->taskCenterService->updateTask($taskCenterId, [
  7576. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7577. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7578. 'error_message' => null
  7579. ]);
  7580. }
  7581. return $resultData;
  7582. } catch (\Exception $e) {
  7583. // 回滚事务
  7584. DB::rollback();
  7585. // 更新任务中心状态为失败
  7586. if (!empty($taskCenterId)) {
  7587. $this->taskCenterService->updateTask($taskCenterId, [
  7588. 'status' => MpTaskCenter::STATUS_FAILED,
  7589. 'error_message' => $e->getMessage()
  7590. ]);
  7591. }
  7592. // 记录错误日志
  7593. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7594. 'script_id' => $script_id,
  7595. 'error' => $e->getMessage(),
  7596. 'trace' => $e->getTraceAsString()
  7597. ]);
  7598. // 统一使用 Utils::throwError 抛出错误
  7599. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7600. }
  7601. }
  7602. /**
  7603. * 根据入参创建或复用任务中心记录
  7604. *
  7605. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  7606. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  7607. * 避免生成重复任务。
  7608. *
  7609. * @param int|string $uid
  7610. * @param int|string $cpid
  7611. * @param int|string $script_id
  7612. * @param mixed $products
  7613. * @param string $model
  7614. * @param string $ratio
  7615. * @param string $resolution
  7616. * @param mixed $auto_generate_images
  7617. * @return int 任务中心ID
  7618. */
  7619. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  7620. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  7621. if (is_string($products)) {
  7622. $decoded = json_decode($products, true);
  7623. if (json_last_error() === JSON_ERROR_NONE) {
  7624. $products = $decoded;
  7625. }
  7626. }
  7627. $params = [
  7628. 'script_id' => (int)$script_id,
  7629. 'products' => $products,
  7630. 'model' => $model,
  7631. 'ratio' => $ratio,
  7632. 'resolution' => $resolution,
  7633. 'auto_generate_images' => (bool)$auto_generate_images,
  7634. ];
  7635. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  7636. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  7637. $existing = DB::table('mp_task_center')
  7638. ->where('uid', (int)$uid)
  7639. ->where('cpid', (int)$cpid)
  7640. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7641. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  7642. ->where('params_md5', $paramsMd5)
  7643. ->orderBy('id', 'desc')
  7644. ->first();
  7645. if ($existing) {
  7646. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  7647. 'script_id' => $script_id,
  7648. 'task_center_id' => $existing->id,
  7649. 'params_md5' => $paramsMd5,
  7650. ]);
  7651. return (int)$existing->id;
  7652. }
  7653. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  7654. $now = date('Y-m-d H:i:s');
  7655. DB::table('mp_task_center')->insertOrIgnore([
  7656. 'uid' => (int)$uid,
  7657. 'cpid' => (int)$cpid,
  7658. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  7659. 'title' => '剧本资产图片生成',
  7660. 'ref_task_id' => 0,
  7661. 'status' => MpTaskCenter::STATUS_PROCESSING,
  7662. 'result' => null,
  7663. 'error_message' => null,
  7664. 'prompt' => null,
  7665. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  7666. 'params_md5' => $paramsMd5,
  7667. 'created_at' => $now,
  7668. 'updated_at' => $now,
  7669. ]);
  7670. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  7671. $taskId = (int)DB::table('mp_task_center')
  7672. ->where('uid', (int)$uid)
  7673. ->where('cpid', (int)$cpid)
  7674. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7675. ->where('params_md5', $paramsMd5)
  7676. ->orderBy('id', 'desc')
  7677. ->value('id');
  7678. dLog('anime')->info('创建任务中心记录', [
  7679. 'script_id' => $script_id,
  7680. 'task_center_id' => $taskId,
  7681. 'params_md5' => $paramsMd5,
  7682. ]);
  7683. return $taskId;
  7684. }
  7685. /**
  7686. * 任务结束时更新任务中心记录的状态和结果
  7687. *
  7688. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  7689. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  7690. *
  7691. * @param int|null $taskCenterId
  7692. * @param array $resultData 接口返回结果数组
  7693. * @param bool $timeout 是否超时未完成
  7694. */
  7695. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  7696. if (!$taskCenterId) {
  7697. return;
  7698. }
  7699. $stats = $resultData['stats'] ?? [];
  7700. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  7701. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  7702. $failedCount = $completedCount - $successCount;
  7703. // 与接口返回给客户端的结果保持一致
  7704. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  7705. if ($timeout) {
  7706. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7707. 'status' => MpTaskCenter::STATUS_FAILED,
  7708. 'result' => $result,
  7709. 'error_message' => '部分任务超时,请稍后查看结果',
  7710. ]);
  7711. return;
  7712. }
  7713. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7714. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  7715. 'result' => $result,
  7716. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  7717. ]);
  7718. }
  7719. /**
  7720. * 批量为剧本资产生成图片
  7721. *
  7722. * @param array $data 请求参数
  7723. * @return \Generator 返回 SSE 流
  7724. */
  7725. public function batchGenerateProductImages($data) {
  7726. $script_id = getProp($data, 'script_id');
  7727. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7728. if (!$script_id) {
  7729. Utils::throwError('20003:请提供剧本ID');
  7730. }
  7731. // 验证剧本是否存在
  7732. $script = DB::table('mp_scripts')
  7733. ->where('id', $script_id)
  7734. ->where('is_deleted', 0)
  7735. ->first();
  7736. if (!$script) {
  7737. Utils::throwError('20003:剧本不存在');
  7738. }
  7739. $script_name = $script->script_name ?? 'script_' . $script_id;
  7740. // 获取需要生成图片的所有资产
  7741. $products = DB::table('mp_products')
  7742. ->whereIn('parent_id', array_values($type_folder_ids))
  7743. ->where('is_deleted', 0)
  7744. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7745. ->get();
  7746. if ($products->isEmpty()) {
  7747. Utils::throwError('20003:没有找到需要生成图片的资产');
  7748. }
  7749. // 默认参数
  7750. $model = 'doubao-seedream-5-0-lite-260128';
  7751. $width = 1600;
  7752. $height = 2848;
  7753. // 开始为每个资产创建图片生成任务
  7754. $taskIds = [];
  7755. $productTaskMap = []; // 资产ID到任务ID的映射
  7756. foreach ($products as $product) {
  7757. if (empty($product->pic_prompt)) {
  7758. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7759. continue;
  7760. }
  7761. try {
  7762. // 创建图片生成任务
  7763. $params = [
  7764. 'prompt' => $product->pic_prompt,
  7765. 'model' => $model,
  7766. 'ref_img_urls' => [],
  7767. 'width' => $width,
  7768. 'height' => $height
  7769. ];
  7770. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7771. $task_id = $task->id;
  7772. if ($task_id) {
  7773. $taskIds[] = $task_id;
  7774. $productTaskMap[$product->id] = $task_id;
  7775. // 更新资产表的任务ID和状态
  7776. DB::table('mp_products')
  7777. ->where('id', $product->id)
  7778. ->update([
  7779. 'pic_task_id' => $task_id,
  7780. 'pic_task_status' => '生成中',
  7781. 'updated_at' => now()
  7782. ]);
  7783. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7784. }
  7785. } catch (\Exception $e) {
  7786. dLog('anime')->error('创建资产图片生成任务失败', [
  7787. 'product_id' => $product->id,
  7788. 'error' => $e->getMessage()
  7789. ]);
  7790. // 标记为失败
  7791. DB::table('mp_products')
  7792. ->where('id', $product->id)
  7793. ->update([
  7794. 'pic_task_status' => '生成失败',
  7795. 'updated_at' => now()
  7796. ]);
  7797. }
  7798. }
  7799. if (empty($taskIds)) {
  7800. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7801. }
  7802. // 返回 SSE 流
  7803. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7804. }
  7805. /**
  7806. * 轮询资产图片生成任务状态(SSE流式返回)
  7807. * 只通过查询数据库获取任务状态,不主动调用API
  7808. *
  7809. * @param int $script_id 剧本ID
  7810. * @param string $script_name 剧本名称
  7811. * @param array $productTaskMap 资产ID到任务ID的映射
  7812. * @param array $type_folder_ids 类型文件夹ID映射
  7813. * @return \Generator
  7814. */
  7815. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null) {
  7816. $startTime = time();
  7817. $timeout = 1800; // 30分钟超时
  7818. $pollInterval = 10; // 10秒轮询一次
  7819. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7820. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  7821. if ($taskCenterId) {
  7822. $initResponse = [
  7823. 'type' => 'init',
  7824. 'script_id' => $script_id,
  7825. 'script_name' => $script_name,
  7826. 'timestamp' => date('Y-m-d H:i:s'),
  7827. 'task_center_id' => (int)$taskCenterId,
  7828. ];
  7829. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  7830. }
  7831. // 定义类型名称映射
  7832. $typeNames = [
  7833. 1 => 'roles', // 角色
  7834. 2 => 'scenes', // 场景
  7835. 3 => 'props' // 道具
  7836. ];
  7837. while (time() - $startTime < $timeout) {
  7838. sleep($pollInterval);
  7839. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7840. $mappings = DB::table('mp_script_product_mappings')
  7841. ->where('script_id', $script_id)
  7842. ->pluck('product_id')
  7843. ->unique()
  7844. ->toArray();
  7845. if (empty($mappings)) {
  7846. dLog('anime')->warning('该剧本没有关联的资产', [
  7847. 'script_id' => $script_id,
  7848. 'script_name' => $script_name
  7849. ]);
  7850. break;
  7851. }
  7852. // 查询所有资产的当前状态
  7853. $products = DB::table('mp_products')
  7854. ->whereIn('id', $mappings)
  7855. ->where('is_deleted', 0)
  7856. ->get();
  7857. // 统计各类型的状态(使用类型名称作为键名)
  7858. $stats = [
  7859. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7860. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7861. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7862. ];
  7863. $allCompleted = true;
  7864. $hasStatusChange = false;
  7865. foreach ($products as $product) {
  7866. $type = $product->product;
  7867. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7868. // 如果类型名称不在 stats 中,初始化
  7869. if (!isset($stats[$typeName])) {
  7870. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7871. }
  7872. $stats[$typeName]['total']++;
  7873. $task_id = $product->pic_task_id;
  7874. $currentStatus = $product->pic_task_status;
  7875. // 检查状态是否有变化
  7876. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7877. $hasStatusChange = true;
  7878. $lastStatus[$product->id] = $currentStatus;
  7879. }
  7880. // 如果是生成中,查询任务表状态
  7881. if ($currentStatus === '生成中' && $task_id) {
  7882. // 只查询数据库,不调用API
  7883. $task = DB::table('mp_generate_pic_tasks')
  7884. ->where('id', $task_id)
  7885. ->first();
  7886. if ($task) {
  7887. // 检查任务状态
  7888. if ($task->status === 'success' && $task->result_url) {
  7889. // 解析图片URL
  7890. $result_urls = $task->result_url;
  7891. if (is_string($result_urls)) {
  7892. $result_urls = json_decode($result_urls, true);
  7893. }
  7894. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7895. // 更新资产表状态
  7896. DB::table('mp_products')
  7897. ->where('id', $product->id)
  7898. ->update([
  7899. 'pic_task_status' => '生成成功',
  7900. 'url' => $img_url,
  7901. 'updated_at' => now()
  7902. ]);
  7903. $stats[$typeName]['success']++;
  7904. $stats[$typeName]['completed']++;
  7905. $hasStatusChange = true;
  7906. dLog('anime')->info('资产图片生成成功', [
  7907. 'product_id' => $product->id,
  7908. 'task_id' => $task_id,
  7909. 'img_url' => $img_url
  7910. ]);
  7911. } elseif ($task->status === 'failed') {
  7912. // 更新资产表状态
  7913. DB::table('mp_products')
  7914. ->where('id', $product->id)
  7915. ->update([
  7916. 'pic_task_status' => '生成失败',
  7917. 'updated_at' => now()
  7918. ]);
  7919. $stats[$typeName]['completed']++;
  7920. $hasStatusChange = true;
  7921. dLog('anime')->warning('资产图片生成失败', [
  7922. 'product_id' => $product->id,
  7923. 'task_id' => $task_id,
  7924. 'error' => $task->error_message ?? '未知错误'
  7925. ]);
  7926. } else {
  7927. // 任务还在处理中
  7928. $allCompleted = false;
  7929. }
  7930. } else {
  7931. // 任务不存在,标记为失败
  7932. DB::table('mp_products')
  7933. ->where('id', $product->id)
  7934. ->update([
  7935. 'pic_task_status' => '生成失败',
  7936. 'updated_at' => now()
  7937. ]);
  7938. $stats[$type]['completed']++;
  7939. $hasStatusChange = true;
  7940. dLog('anime')->error('图片生成任务不存在', [
  7941. 'product_id' => $product->id,
  7942. 'task_id' => $task_id
  7943. ]);
  7944. }
  7945. } elseif ($currentStatus === '生成成功') {
  7946. $stats[$typeName]['success']++;
  7947. $stats[$typeName]['completed']++;
  7948. } elseif ($currentStatus === '生成失败') {
  7949. $stats[$typeName]['completed']++;
  7950. } else {
  7951. // 其他状态也认为未完成
  7952. $allCompleted = false;
  7953. }
  7954. }
  7955. // 移除没有数据的类型(total=0)
  7956. foreach ($stats as $typeName => $stat) {
  7957. if ($stat['total'] === 0) {
  7958. unset($stats[$typeName]);
  7959. }
  7960. }
  7961. // 如果有状态变化,发送 SSE 更新
  7962. if ($hasStatusChange) {
  7963. $eventType = $allCompleted ? 'complete' : 'update';
  7964. $response = [
  7965. 'type' => $eventType,
  7966. 'script_id' => $script_id,
  7967. 'script_name' => $script_name,
  7968. 'stats' => $stats,
  7969. 'timestamp' => date('Y-m-d H:i:s')
  7970. ];
  7971. if ($taskCenterId) {
  7972. $response['task_center_id'] = $taskCenterId;
  7973. }
  7974. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7975. dLog('anime')->info('SSE更新', [
  7976. 'event_type' => $eventType,
  7977. 'script_id' => $script_id,
  7978. 'script_name' => $script_name,
  7979. 'stats' => $stats
  7980. ]);
  7981. if ($allCompleted) {
  7982. dLog('anime')->info('所有资产图片生成任务已完成', [
  7983. 'script_id' => $script_id,
  7984. 'script_name' => $script_name,
  7985. 'stats' => $stats
  7986. ]);
  7987. // 全部任务完成,更新任务中心状态和结果
  7988. $this->finishScriptProductTask($taskCenterId, $response);
  7989. break;
  7990. }
  7991. }
  7992. }
  7993. // 超时处理
  7994. if (time() - $startTime >= $timeout && !$allCompleted) {
  7995. $response = [
  7996. 'type' => 'timeout',
  7997. 'message' => '部分任务超时,请稍后查看结果',
  7998. 'script_id' => $script_id,
  7999. 'script_name' => $script_name,
  8000. 'timestamp' => date('Y-m-d H:i:s')
  8001. ];
  8002. if ($taskCenterId) {
  8003. $response['task_center_id'] = $taskCenterId;
  8004. }
  8005. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8006. dLog('anime')->warning('资产图片生成任务超时', [
  8007. 'script_id' => $script_id,
  8008. 'script_name' => $script_name,
  8009. 'timeout' => $timeout
  8010. ]);
  8011. // 超时未完成,更新任务中心状态和结果
  8012. $this->finishScriptProductTask($taskCenterId, $response, true);
  8013. }
  8014. }
  8015. /**
  8016. * 定时任务:检查产品图片生成任务状态并更新产品记录
  8017. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  8018. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  8019. *
  8020. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  8021. */
  8022. public function checkProductPicTasks() {
  8023. // 查询所有生成中的产品图片任务
  8024. $products = DB::table('mp_products')
  8025. ->whereNotNull('pic_task_id')
  8026. ->where('pic_task_status', '生成中')
  8027. ->where('is_deleted', 0)
  8028. ->get();
  8029. $stats = [
  8030. 'total' => $products->count(),
  8031. 'success' => 0,
  8032. 'failed' => 0,
  8033. 'pending' => 0,
  8034. ];
  8035. foreach ($products as $product) {
  8036. try {
  8037. $task_id = $product->pic_task_id;
  8038. // 通过 pic_task_id 查询图片生成任务结果
  8039. $task = DB::table('mp_generate_pic_tasks')
  8040. ->where('id', $task_id)
  8041. ->first();
  8042. if ($task) {
  8043. if ($task->status === 'success' && $task->result_url) {
  8044. // 解析图片URL
  8045. $result_urls = $task->result_url;
  8046. if (is_string($result_urls)) {
  8047. $result_urls = json_decode($result_urls, true);
  8048. }
  8049. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  8050. // 更新资产表状态
  8051. DB::table('mp_products')
  8052. ->where('id', $product->id)
  8053. ->update([
  8054. 'pic_task_status' => '生成成功',
  8055. 'url' => $img_url,
  8056. 'updated_at' => now()
  8057. ]);
  8058. $stats['success']++;
  8059. dLog('anime')->info('资产图片生成成功', [
  8060. 'product_id' => $product->id,
  8061. 'task_id' => $task_id,
  8062. 'img_url' => $img_url
  8063. ]);
  8064. } elseif ($task->status === 'failed') {
  8065. // 更新资产表状态
  8066. DB::table('mp_products')
  8067. ->where('id', $product->id)
  8068. ->update([
  8069. 'pic_task_status' => '生成失败',
  8070. 'updated_at' => now()
  8071. ]);
  8072. $stats['failed']++;
  8073. dLog('anime')->warning('资产图片生成失败', [
  8074. 'product_id' => $product->id,
  8075. 'task_id' => $task_id,
  8076. 'error' => $task->error_message ?? '未知错误'
  8077. ]);
  8078. } else {
  8079. // 任务还在处理中
  8080. $stats['pending']++;
  8081. }
  8082. } else {
  8083. // 任务不存在,标记为失败
  8084. DB::table('mp_products')
  8085. ->where('id', $product->id)
  8086. ->update([
  8087. 'pic_task_status' => '生成失败',
  8088. 'updated_at' => now()
  8089. ]);
  8090. $stats['failed']++;
  8091. dLog('anime')->error('图片生成任务不存在', [
  8092. 'product_id' => $product->id,
  8093. 'task_id' => $task_id
  8094. ]);
  8095. }
  8096. } catch (\Exception $e) {
  8097. dLog('anime')->error('检查产品图片生成任务异常', [
  8098. 'product_id' => $product->id,
  8099. 'task_id' => $product->pic_task_id ?? null,
  8100. 'error' => $e->getMessage()
  8101. ]);
  8102. }
  8103. }
  8104. return $stats;
  8105. }
  8106. /**
  8107. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  8108. *
  8109. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  8110. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  8111. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  8112. *
  8113. * @return int 更新的任务中心记录数
  8114. */
  8115. public function checkSaveScriptProductTaskCenters() {
  8116. $updated = 0;
  8117. // 只扫描尚未结束的 saveScriptProducts 任务
  8118. $tasks = DB::table('mp_task_center')
  8119. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8120. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8121. ->orderBy('id', 'desc')
  8122. ->limit(500)
  8123. ->get();
  8124. // 与 pollProductImageTasks 保持一致的类型名称映射
  8125. $typeNames = [
  8126. 1 => 'roles', // 角色
  8127. 2 => 'scenes', // 场景
  8128. 3 => 'props', // 道具
  8129. ];
  8130. foreach ($tasks as $task) {
  8131. try {
  8132. $taskParams = json_decode((string)$task->params, true);
  8133. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  8134. if (!$script_id) {
  8135. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  8136. 'task_center_id' => $task->id,
  8137. ]);
  8138. continue;
  8139. }
  8140. // 获取该剧本关联的全部资产ID
  8141. $productIds = DB::table('mp_script_product_mappings')
  8142. ->where('script_id', $script_id)
  8143. ->pluck('product_id')
  8144. ->unique()
  8145. ->toArray();
  8146. if (empty($productIds)) {
  8147. // 剧本没有关联资产,不视为完成,等待下一次检查
  8148. continue;
  8149. }
  8150. $products = DB::table('mp_products')
  8151. ->whereIn('id', $productIds)
  8152. ->where('is_deleted', 0)
  8153. ->get();
  8154. $stats = [];
  8155. $allCompleted = true;
  8156. foreach ($products as $product) {
  8157. $typeName = $typeNames[$product->product] ?? 'unknown';
  8158. if (!isset($stats[$typeName])) {
  8159. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8160. }
  8161. $stats[$typeName]['total']++;
  8162. if ($product->pic_task_status === '生成成功') {
  8163. $stats[$typeName]['success']++;
  8164. $stats[$typeName]['completed']++;
  8165. } elseif ($product->pic_task_status === '生成失败') {
  8166. $stats[$typeName]['completed']++;
  8167. } else {
  8168. // 仍有资产在生成中或未生成,任务未完成
  8169. $allCompleted = false;
  8170. }
  8171. }
  8172. if (!$allCompleted) {
  8173. continue;
  8174. }
  8175. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  8176. $script = DB::table('mp_scripts')
  8177. ->where('id', $script_id)
  8178. ->where('is_deleted', 0)
  8179. ->first();
  8180. $script_name = $script->script_name ?? 'script_' . $script_id;
  8181. $this->finishScriptProductTask($task->id, [
  8182. 'type' => 'complete',
  8183. 'script_id' => $script_id,
  8184. 'script_name' => $script_name,
  8185. 'stats' => $stats,
  8186. 'timestamp' => date('Y-m-d H:i:s'),
  8187. 'task_center_id' => (int)$task->id,
  8188. ]);
  8189. $updated++;
  8190. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  8191. 'task_center_id' => $task->id,
  8192. 'script_id' => $script_id,
  8193. 'stats' => $stats,
  8194. ]);
  8195. } catch (\Exception $e) {
  8196. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  8197. 'task_center_id' => $task->id,
  8198. 'error' => $e->getMessage(),
  8199. ]);
  8200. }
  8201. }
  8202. return $updated;
  8203. }
  8204. /**
  8205. * 获取剧本关联的资产列表
  8206. * @param array $data 请求参数
  8207. * @return array
  8208. */
  8209. public function getScriptProducts($data) {
  8210. $uid = Site::getUid();
  8211. $cpid = Site::getCpid();
  8212. $script_id = getProp($data, 'script_id');
  8213. $episode_number = getProp($data, 'episode_number');
  8214. if (!$script_id) {
  8215. Utils::throwError('20003:请提供剧本ID');
  8216. }
  8217. // 验证剧本是否存在
  8218. $script = DB::table('mp_scripts')
  8219. ->where('id', $script_id)
  8220. ->where('is_deleted', 0)
  8221. ->first();
  8222. if (!$script) {
  8223. Utils::throwError('20003:剧本不存在');
  8224. }
  8225. // 联表查询资产信息
  8226. $query = DB::table('mp_script_product_mappings as mapping')
  8227. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8228. ->where('mapping.script_id', $script_id)
  8229. ->where('product.cpid', $cpid)
  8230. ->where('product.is_deleted', 0);
  8231. // 如果提供了 episode_number,则过滤指定集数
  8232. if ($episode_number !== null && $episode_number !== '') {
  8233. $query->where('mapping.episode_number', $episode_number);
  8234. }
  8235. $mappings = $query->select(
  8236. 'mapping.script_id',
  8237. 'mapping.product_id',
  8238. 'mapping.episode_number',
  8239. 'product.product_name',
  8240. 'product.type',
  8241. 'product.product',
  8242. 'product.pic_prompt',
  8243. 'product.url',
  8244. 'product.pic_task_id',
  8245. 'product.pic_task_status',
  8246. 'product.three_view_image_url',
  8247. 'mapping.created_at'
  8248. )
  8249. ->orderBy('mapping.product_id', 'asc')
  8250. ->orderBy('mapping.episode_number', 'asc')
  8251. ->get();
  8252. // 按 product_id 分组,合并 episode_number
  8253. $productMap = [];
  8254. foreach ($mappings as $item) {
  8255. $product_id = $item->product_id;
  8256. if (!isset($productMap[$product_id])) {
  8257. $productMap[$product_id] = [
  8258. 'product_id' => $product_id,
  8259. 'product_name' => $item->product_name,
  8260. 'type' => (int)$item->type,
  8261. 'product' => (int)$item->product,
  8262. 'pic_prompt' => $item->pic_prompt,
  8263. 'url' => $item->url,
  8264. 'pic_task_id' => $item->pic_task_id,
  8265. 'pic_task_status' => $item->pic_task_status,
  8266. 'episode_numbers' => [],
  8267. 'created_at' => $item->created_at,
  8268. ];
  8269. }
  8270. // 添加 episode_number(去重)
  8271. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8272. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8273. }
  8274. }
  8275. // 按类型分组
  8276. $roles = []; // type=1 角色/主体
  8277. $scenes = []; // type=2 场景
  8278. $props = []; // type=3 道具
  8279. foreach ($productMap as $product) {
  8280. // 将 episode_numbers 数组转换为逗号分隔的字符串
  8281. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  8282. // 构造返回数据
  8283. $productData = [
  8284. 'product_id' => $product['product_id'],
  8285. 'product_name' => $product['product_name'],
  8286. 'product' => $product['product'],
  8287. 'pic_prompt' => $product['pic_prompt'],
  8288. 'url' => $product['url'],
  8289. 'pic_task_id' => $product['pic_task_id'],
  8290. 'pic_task_status' => $product['pic_task_status'],
  8291. 'episode_numbers' => $episodeNumbersStr,
  8292. 'created_at' => $product['created_at'],
  8293. ];
  8294. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  8295. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  8296. switch ($product['product']) {
  8297. case 1:
  8298. $roles[] = $productData;
  8299. break;
  8300. case 2:
  8301. $scenes[] = $productData;
  8302. break;
  8303. case 3:
  8304. $props[] = $productData;
  8305. break;
  8306. }
  8307. }
  8308. return [
  8309. 'script_id' => $script_id,
  8310. 'script_name' => $script->script_name ?? '',
  8311. 'roles' => $roles, // 主体
  8312. 'scenes' => $scenes, // 场景
  8313. 'props' => $props, // 道具
  8314. ];
  8315. }
  8316. /**
  8317. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  8318. * @param string $actContent 原始内容
  8319. * @param array $products 产品数组(包含product_name和url)
  8320. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  8321. */
  8322. public function processActContentWithProducts($actContent, $products) {
  8323. if (empty($actContent) || empty($products)) {
  8324. return [
  8325. 'content' => $actContent,
  8326. 'reference_images' => []
  8327. ];
  8328. }
  8329. // 构建产品名称到产品信息的映射
  8330. $product_dict = [];
  8331. foreach ($products as $product) {
  8332. $product_name = getProp($product, 'product_name');
  8333. if ($product_name) {
  8334. $product_dict[$product_name] = [
  8335. 'url' => getProp($product, 'url'),
  8336. 'voice_prompt' => getProp($product, 'voice_prompt')
  8337. ];
  8338. }
  8339. }
  8340. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  8341. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  8342. $reference_images = [];
  8343. $product_index_map = []; // 产品名称 => 图片序号的映射
  8344. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  8345. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  8346. $current_index = 1;
  8347. if (!empty($matches[1])) {
  8348. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  8349. $seen_products = []; // 用于去重
  8350. foreach ($matches[1] as $product_name) {
  8351. // 跳过已处理的产品
  8352. if (isset($seen_products[$product_name])) {
  8353. continue;
  8354. }
  8355. $seen_products[$product_name] = true;
  8356. // 检查产品是否在字典中
  8357. if (isset($product_dict[$product_name])) {
  8358. $url = $product_dict[$product_name]['url'];
  8359. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8360. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8361. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8362. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8363. }
  8364. // 只有URL非空才分配序号和添加到参考图片
  8365. if (!empty($url)) {
  8366. // 检查URL是否已经在reference_images中(去重)
  8367. if (!in_array($url, $reference_images)) {
  8368. $reference_images[] = $url;
  8369. $product_index_map[$product_name] = $current_index;
  8370. $current_index++;
  8371. } else {
  8372. // URL重复,找到已有的序号
  8373. $existing_index = array_search($url, $reference_images) + 1;
  8374. $product_index_map[$product_name] = $existing_index;
  8375. }
  8376. } else {
  8377. // URL为空,不分配序号(后续直接去掉{})
  8378. $product_index_map[$product_name] = 0;
  8379. }
  8380. } else {
  8381. // 产品不在字典中,不分配序号
  8382. $product_index_map[$product_name] = 0;
  8383. }
  8384. }
  8385. }
  8386. // 第二步:替换内容中的 {产品名称}
  8387. $processedContent = $actContent;
  8388. foreach ($product_index_map as $product_name => $index) {
  8389. $escaped_name = preg_quote($product_name, '/');
  8390. if ($index > 0) {
  8391. // 有图片,替换为:产品名称(图X)
  8392. $replacement = $product_name . '<图片' . $index . '>';
  8393. } else {
  8394. // 无图片,只保留产品名称
  8395. $replacement = $product_name;
  8396. }
  8397. // 替换所有 {产品名称} 为处理后的格式
  8398. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8399. }
  8400. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8401. foreach ($products as $product) {
  8402. $product_name = getProp($product, 'product_name');
  8403. $voice_prompt = getProp($product, 'voice_prompt');
  8404. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8405. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8406. break; // 找到旁白后退出循环
  8407. }
  8408. }
  8409. // 第四步:将voice_prompt信息添加到内容最前面
  8410. $voice_prompt_prefix = '';
  8411. if (!empty($voice_prompts)) {
  8412. $voice_prompt_prefix .= implode('', $voice_prompts);
  8413. }
  8414. // 旁白的voice_prompt放在最后
  8415. if (!empty($narrator_voice_prompt)) {
  8416. $voice_prompt_prefix .= $narrator_voice_prompt;
  8417. }
  8418. // 如果有voice_prompt信息,添加到内容开头
  8419. if (!empty($voice_prompt_prefix)) {
  8420. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8421. }
  8422. return [
  8423. 'content' => $processedContent,
  8424. 'reference_images' => $reference_images
  8425. ];
  8426. }
  8427. public function saveActVideoGenerateParams($data) {
  8428. $episode_id = getProp($data, 'episode_id');
  8429. $model = getProp($data, 'video_model');
  8430. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  8431. Utils::throwError('20003:该模型不可用');
  8432. }
  8433. if (!$model) {
  8434. // 使用默认模型
  8435. $model = 'zhizhen-20';
  8436. }
  8437. // 验证模型是否在可用模型表中
  8438. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8439. Utils::throwError('20003:该模型已不可用,请更换!');
  8440. }
  8441. $video_resolution = getProp($data, 'video_resolution', '720p');
  8442. $ratio = getProp($data, 'ratio');
  8443. if (!$ratio) $ratio = '9:16';
  8444. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8445. if (!$episode) {
  8446. Utils::throwError('20003:分集不存在');
  8447. }
  8448. try {
  8449. DB::beginTransaction();
  8450. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8451. 'video_model' => $model,
  8452. 'video_resolution' => $video_resolution,
  8453. 'ratio' => $ratio,
  8454. 'updated_at' => date('Y-m-d H:i:s')
  8455. ]);
  8456. if ($result === false) {
  8457. Utils::throwError('20003:分集视频参数保存失败');
  8458. }
  8459. // 同步更新mp_animes表
  8460. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8461. 'video_model' => $model,
  8462. 'video_resolution' => $video_resolution,
  8463. 'video_ratio' => $ratio,
  8464. 'updated_at' => date('Y-m-d H:i:s')
  8465. ]);
  8466. if ($anime_result === false) {
  8467. Utils::throwError('20003:动漫视频参数保存失败');
  8468. }
  8469. } catch (\Exception $e) {
  8470. DB::rollBack();
  8471. Utils::throwError('20003:'.$e->getMessage());
  8472. }
  8473. DB::commit();
  8474. return $result;
  8475. }
  8476. public function confirmActs($data) {
  8477. $episode_id = getProp($data, 'episode_id');
  8478. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8479. if (!$episode) {
  8480. Utils::throwError('20003:分集不存在');
  8481. }
  8482. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8483. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8484. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8485. // 获取所有片段数据
  8486. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8487. // 收集所有资产名称(角色、场景、道具)
  8488. $product_names = [];
  8489. // 收集角色名称
  8490. foreach ($roles as $role) {
  8491. $role_name = getProp($role, 'role');
  8492. if ($role_name && $role_name != '旁白') {
  8493. $product_names[] = $role_name;
  8494. }
  8495. }
  8496. // 收集场景名称
  8497. foreach ($scenes as $scene) {
  8498. $scene_name = getProp($scene, 'scene');
  8499. if ($scene_name) {
  8500. $product_names[] = $scene_name;
  8501. }
  8502. }
  8503. // 收集道具名称
  8504. foreach ($props as $prop) {
  8505. $prop_name = getProp($prop, 'prop');
  8506. if ($prop_name) {
  8507. $product_names[] = $prop_name;
  8508. }
  8509. }
  8510. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8511. $product_names = array_unique($product_names);
  8512. usort($product_names, function($a, $b) {
  8513. return mb_strlen($b) - mb_strlen($a);
  8514. });
  8515. try {
  8516. DB::beginTransaction();
  8517. // 处理每个片段
  8518. foreach ($acts as $act) {
  8519. $act_content = getProp($act, 'act_content');
  8520. if (!$act_content) continue;
  8521. $processed_content = $act_content;
  8522. // 统一替换所有资产名称为 {资产名} 格式
  8523. // 使用占位符避免嵌套替换问题
  8524. $placeholder_map = [];
  8525. $placeholder_index = 0;
  8526. foreach ($product_names as $product_name) {
  8527. // 转义特殊字符
  8528. $escaped_product = preg_quote($product_name, '/');
  8529. // 检查是否匹配且未被 {} 包裹
  8530. $processed_content = preg_replace_callback(
  8531. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8532. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8533. // 使用唯一占位符
  8534. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8535. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8536. $placeholder_index++;
  8537. return $placeholder;
  8538. },
  8539. $processed_content
  8540. );
  8541. }
  8542. // 将所有占位符替换回实际内容
  8543. foreach ($placeholder_map as $placeholder => $replacement) {
  8544. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8545. }
  8546. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8547. $shot_counter = 0;
  8548. $processed_content = preg_replace_callback(
  8549. '/【(?:镜头|分镜)(\d+)】/u',
  8550. function($matches) use (&$shot_counter) {
  8551. $shot_counter++;
  8552. return '【镜头' . $shot_counter . '】';
  8553. },
  8554. $processed_content
  8555. );
  8556. // 更新数据库
  8557. $boolen = DB::table('mp_episode_segments')
  8558. ->where('id', $act->id)
  8559. ->update([
  8560. 'act_show_content' => $processed_content,
  8561. 'updated_at' => date('Y-m-d H:i:s')
  8562. ]);
  8563. if (!$boolen) {
  8564. Utils::throwError('20003:片段处理失败');
  8565. }
  8566. }
  8567. }catch (\Exception $e) {
  8568. DB::rollBack();
  8569. Utils::throwError('20003:'.$e->getMessage());
  8570. }
  8571. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8572. 'is_generated' => 1,
  8573. 'updated_at' => date('Y-m-d H:i:s')
  8574. ]);
  8575. if (!$boolen1) {
  8576. DB::rollBack();
  8577. Utils::throwError('20003:分集处理失败!');
  8578. }
  8579. DB::commit();
  8580. // 重新查询更新后的片段数据
  8581. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8582. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8583. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8584. $products = [];
  8585. // 先处理角色数组
  8586. foreach ($roles as $role) {
  8587. $product = $role;
  8588. // 将role字段重命名为product_name
  8589. if (isset($product['role'])) {
  8590. $product['product_name'] = $product['role'];
  8591. unset($product['role']);
  8592. $product['product'] = 1; // 标记类型为角色
  8593. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8594. }
  8595. }
  8596. // 处理场景数组
  8597. foreach ($scenes as $scene) {
  8598. $product = $scene;
  8599. // 将scene字段重命名为product_name
  8600. if (isset($product['scene'])) {
  8601. $product['product_name'] = $product['scene'];
  8602. unset($product['scene']);
  8603. $product['product'] = 2; // 标记类型为场景
  8604. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8605. }
  8606. }
  8607. // 处理道具数组(逻辑与场景一致)
  8608. foreach ($props as $prop) {
  8609. $product = $prop;
  8610. // 将prop字段重命名为product_name
  8611. if (isset($product['prop'])) {
  8612. $product['product_name'] = $product['prop'];
  8613. unset($product['prop']);
  8614. $product['product'] = 3; // 标记类型为道具
  8615. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8616. }
  8617. }
  8618. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8619. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8620. foreach ($extra_products as $extra_product) {
  8621. $product_name = getProp($extra_product, 'product_name');
  8622. if ($product_name) {
  8623. $products[$product_name] = $extra_product; // 覆盖同名数据
  8624. }
  8625. }
  8626. // 重新索引数组(去除key)
  8627. $products = array_values($products);
  8628. // 构建返回的acts数组
  8629. $return_acts = [];
  8630. foreach ($acts as $act) {
  8631. $return_acts[] = [
  8632. 'act_id' => getProp($act, 'id'),
  8633. 'act_number' => getProp($act, 'act_number'),
  8634. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8635. 'act_show_content' => getProp($act, 'act_show_content'),
  8636. 'video_url' => getProp($act, 'video_url'),
  8637. 'video_duration' => getProp($act, 'video_duration'),
  8638. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8639. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8640. ];
  8641. }
  8642. return [
  8643. 'anime_id' => getProp($episode, 'anime_id'),
  8644. 'episode_id' => $episode_id,
  8645. 'title' => getProp($episode, 'title'),
  8646. 'episode_number' => getProp($episode, 'episode_number'),
  8647. 'is_generated' => getProp($episode, 'is_generated'),
  8648. 'video_params' => [
  8649. 'video_model' => getProp($episode, 'video_model'),
  8650. 'video_resolution' => getProp($episode, 'video_resolution'),
  8651. 'ratio' => getProp($episode, 'ratio'),
  8652. ],
  8653. 'products' => $products,
  8654. 'acts' => $return_acts
  8655. ];
  8656. }
  8657. /**
  8658. * 导出动漫剧本为PDF(参照示例PDF版式)
  8659. * @param int $animeId 动漫ID
  8660. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8661. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8662. * @return string|null
  8663. */
  8664. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8665. // 图片下载与转换可能占用较多内存
  8666. ini_set('memory_limit', '512M');
  8667. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8668. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8669. $anime = (array)$anime;
  8670. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8671. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8672. // 获取分集(默认展示版本,按集数升序)
  8673. $episodeQuery = DB::table('mp_anime_episodes')
  8674. ->where('anime_id', $animeId)
  8675. ->where('is_default', 1)
  8676. ->orderBy('episode_number')
  8677. ->orderBy('id');
  8678. if ($episodeCount > 0) {
  8679. $episodeQuery->limit($episodeCount);
  8680. }
  8681. $episodes = $episodeQuery->get()->map(function ($value) {
  8682. return (array)$value;
  8683. })->toArray();
  8684. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8685. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8686. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8687. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8688. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8689. // 组装分集剧本数据
  8690. $episodeScripts = [];
  8691. foreach ($episodes as $episode) {
  8692. $segments = DB::table('mp_episode_segments')
  8693. ->where('anime_id', $animeId)
  8694. ->where('episode_id', $episode['id'])
  8695. ->get();
  8696. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8697. $acts = [];
  8698. foreach ($segments as $segment) {
  8699. $segment = (array)$segment;
  8700. $actNumber = (int)getProp($segment, 'act_number', 0);
  8701. if ($actNumber <= 0) continue;
  8702. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8703. $acts[$actNumber] = [
  8704. 'id' => (int)$segment['id'],
  8705. 'act_number' => $actNumber,
  8706. 'duration' => getProp($segment, 'act_duration', ''),
  8707. 'content' => getProp($segment, 'act_content', ''),
  8708. ];
  8709. }
  8710. }
  8711. ksort($acts);
  8712. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8713. $segmentCounter = 0;
  8714. foreach ($acts as &$act) {
  8715. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8716. }
  8717. unset($act);
  8718. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8719. $narratorVoice = '';
  8720. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8721. foreach ($episodeRoles as $role) {
  8722. if (getProp($role, 'role') === '旁白') {
  8723. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8724. break;
  8725. }
  8726. }
  8727. if ($narratorVoice === '') {
  8728. foreach ($acts as $act) {
  8729. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8730. $narratorVoice = trim($match[1]);
  8731. break;
  8732. }
  8733. }
  8734. }
  8735. $episodeScripts[] = [
  8736. 'episode_number' => getProp($episode, 'episode_number'),
  8737. 'title' => getProp($episode, 'title', ''),
  8738. 'act_count' => count($acts),
  8739. 'narrator_voice' => $narratorVoice,
  8740. 'acts' => array_values($acts),
  8741. ];
  8742. }
  8743. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8744. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8745. // 构建PDF
  8746. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8747. // 图片已嵌入PDF,清理临时文件
  8748. foreach ($imageCache as $imgFile) {
  8749. @unlink($imgFile);
  8750. }
  8751. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8752. if ($savePath) {
  8753. $pdf->Output($savePath, 'F');
  8754. return $savePath;
  8755. }
  8756. // 直接下载输出
  8757. header('Content-Type: application/pdf');
  8758. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8759. $pdf->Output($filename . '.pdf', 'D');
  8760. exit();
  8761. }
  8762. /**
  8763. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8764. * @param array $episodes 分集数据
  8765. * @param string $nameKey role|scene|prop
  8766. * @return array
  8767. */
  8768. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8769. $fieldMap = [
  8770. 'role' => 'roles',
  8771. 'scene' => 'scenes',
  8772. 'prop' => 'props',
  8773. ];
  8774. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8775. $items = [];
  8776. foreach ($episodes as $episode) {
  8777. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8778. foreach ($list as $item) {
  8779. if (!is_array($item)) continue;
  8780. $name = trim((string)getProp($item, $nameKey, ''));
  8781. if ($name === '') continue;
  8782. // 旁白不进入主体列表(仅作为旁白音色来源)
  8783. if ($nameKey === 'role' && $name === '旁白') continue;
  8784. if (!isset($items[$name])) {
  8785. $items[$name] = $item;
  8786. }
  8787. }
  8788. }
  8789. return array_values($items);
  8790. }
  8791. /**
  8792. * 构建动漫剧本PDF
  8793. * @param array $anime 动漫信息
  8794. * @param array $roles 主体列表
  8795. * @param array $scenes 场景列表
  8796. * @param array $props 道具列表
  8797. * @param array $episodeScripts 分集剧本数据
  8798. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8799. * @return \TCPDF
  8800. */
  8801. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8802. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8803. $pdf->SetCreator('动漫剧本导出系统');
  8804. $pdf->SetAuthor('系统');
  8805. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8806. $pdf->SetSubject('动漫剧本导出');
  8807. $pdf->SetMargins(15, 15, 15);
  8808. $pdf->SetAutoPageBreak(true, 15);
  8809. // 剧本名
  8810. $pdf->AddPage();
  8811. $pdf->SetFont('simsun', 'B', 20);
  8812. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8813. $pdf->Ln(5);
  8814. // 故事梗概
  8815. $intro = trim((string)getProp($anime, 'intro', ''));
  8816. if ($intro !== '') {
  8817. $this->pdfSectionTitle($pdf, '故事梗概');
  8818. $this->pdfBody($pdf, $intro);
  8819. }
  8820. // 美术风格
  8821. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  8822. if ($artStyle !== '') {
  8823. $this->pdfSectionTitle($pdf, '美术风格');
  8824. $this->pdfBody($pdf, $artStyle);
  8825. }
  8826. // 主体列表(文字+图片)
  8827. $this->pdfSectionTitle($pdf, '主体列表');
  8828. foreach ($roles as $index => $role) {
  8829. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  8830. }
  8831. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  8832. // 场景列表(文字+图片)
  8833. $this->pdfSectionTitle($pdf, '场景列表');
  8834. foreach ($scenes as $index => $scene) {
  8835. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  8836. }
  8837. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  8838. // 道具列表(文字+图片)
  8839. $this->pdfSectionTitle($pdf, '道具列表');
  8840. foreach ($props as $index => $prop) {
  8841. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  8842. }
  8843. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  8844. // 分镜剧本
  8845. $this->pdfSectionTitle($pdf, '分镜剧本');
  8846. foreach ($episodeScripts as $episodeScript) {
  8847. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  8848. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  8849. if ($episodeTitleRaw !== '') {
  8850. // title 字段可能已带"第N集"前缀,避免重复
  8851. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  8852. $episodeTitle = $episodeTitleRaw;
  8853. } else {
  8854. $episodeTitle .= ':' . $episodeTitleRaw;
  8855. }
  8856. }
  8857. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  8858. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  8859. if (getProp($episodeScript, 'narrator_voice') !== '') {
  8860. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  8861. }
  8862. foreach (getProp($episodeScript, 'acts', []) as $act) {
  8863. $actTitle = '片段' . getProp($act, 'act_number');
  8864. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  8865. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  8866. }
  8867. $this->pdfSubTitle($pdf, $actTitle, 12);
  8868. if (getProp($act, 'content') !== '') {
  8869. $this->pdfBody($pdf, getProp($act, 'content'));
  8870. }
  8871. }
  8872. }
  8873. return $pdf;
  8874. }
  8875. /**
  8876. * PDF章节标题(带分隔线)
  8877. */
  8878. private function pdfSectionTitle($pdf, $title) {
  8879. if ($pdf->GetY() > 230) {
  8880. $pdf->AddPage();
  8881. }
  8882. $pdf->SetFont('simsun', 'B', 15);
  8883. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  8884. $y = $pdf->GetY();
  8885. $pdf->SetLineWidth(0.4);
  8886. $pdf->Line(15, $y, 195, $y);
  8887. $pdf->Ln(4);
  8888. }
  8889. /**
  8890. * PDF子标题(集数/片段标题)
  8891. */
  8892. private function pdfSubTitle($pdf, $title, $size = 13) {
  8893. if ($pdf->GetY() > 240) {
  8894. $pdf->AddPage();
  8895. }
  8896. $pdf->SetFont('simsun', 'B', $size);
  8897. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  8898. $pdf->Ln(1);
  8899. }
  8900. /**
  8901. * PDF正文段落
  8902. */
  8903. private function pdfBody($pdf, $text) {
  8904. $pdf->SetFont('simsun', '', 11);
  8905. $pdf->MultiCell(0, 6, $text, 0, 'L');
  8906. $pdf->Ln(2);
  8907. }
  8908. /**
  8909. * 输出列表项图片(每张图单独一页,图下标注名称)
  8910. * @param \TCPDF $pdf
  8911. * @param array $items 列表项
  8912. * @param string $nameKey role|scene|prop
  8913. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8914. */
  8915. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  8916. foreach ($items as $item) {
  8917. $url = trim((string)getProp($item, 'url', ''));
  8918. $name = trim((string)getProp($item, $nameKey, ''));
  8919. if ($url === '' || !isset($imageCache[$url])) continue;
  8920. $imgPath = $imageCache[$url];
  8921. $size = @getimagesize($imgPath);
  8922. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  8923. continue;
  8924. }
  8925. $pdf->AddPage();
  8926. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  8927. $maxW = 160;
  8928. $maxH = 170;
  8929. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  8930. $drawW = $size[0] * $ratio;
  8931. $drawH = $size[1] * $ratio;
  8932. $x = (210 - $drawW) / 2;
  8933. $y = max(15, (297 - $drawH) / 2 - 10);
  8934. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  8935. // 图下标注名称
  8936. $pdf->SetFont('simsun', 'B', 13);
  8937. $pdf->SetY(297 - 28);
  8938. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  8939. }
  8940. }
  8941. /**
  8942. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  8943. * @param array $items 包含url字段的列表项
  8944. * @return array url => 临时文件路径
  8945. */
  8946. private function downloadImagesConcurrently(array $items) {
  8947. // 收集唯一的图片URL
  8948. $urls = [];
  8949. foreach ($items as $item) {
  8950. $url = trim((string)getProp($item, 'url', ''));
  8951. if ($url !== '') $urls[$url] = true;
  8952. }
  8953. if (!$urls) return [];
  8954. $urls = array_keys($urls);
  8955. $tmpDir = sys_get_temp_dir();
  8956. $rawFiles = [];
  8957. foreach ($urls as $url) {
  8958. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  8959. $rawFiles[$url] = $rawFile;
  8960. }
  8961. $client = new Client(['timeout' => 180, 'verify' => false]);
  8962. // 低并发下载,sink写入文件避免大图占用内存
  8963. $generator = (function () use ($urls, $client, $rawFiles) {
  8964. foreach ($urls as $url) {
  8965. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  8966. }
  8967. })();
  8968. $errors = [];
  8969. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  8970. 'concurrency' => 4,
  8971. 'rejected' => function ($reason, $url) use (&$errors) {
  8972. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  8973. },
  8974. ]);
  8975. $each->promise()->wait();
  8976. // 失败的图片串行重试一次(独占带宽,提高成功率)
  8977. foreach ($urls as $url) {
  8978. if (!isset($errors[$url])) continue;
  8979. try {
  8980. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  8981. unset($errors[$url]);
  8982. } catch (\Throwable $e) {
  8983. // 重试仍失败
  8984. }
  8985. }
  8986. $cache = [];
  8987. foreach ($urls as $url) {
  8988. $rawFile = $rawFiles[$url];
  8989. if (isset($errors[$url])) {
  8990. dLog('anime')->error('导出PDF图片下载失败', [
  8991. 'url' => $url,
  8992. 'error' => $errors[$url],
  8993. ]);
  8994. @unlink($rawFile);
  8995. continue;
  8996. }
  8997. $converted = $this->convertImageFile($rawFile, $url);
  8998. if ($converted !== null) {
  8999. $cache[$url] = $converted;
  9000. } else {
  9001. @unlink($rawFile);
  9002. }
  9003. }
  9004. return $cache;
  9005. }
  9006. /**
  9007. * 将已下载的图片文件缩放并转为JPEG
  9008. * @param string $rawFile 原始图片临时文件
  9009. * @param string $url 图片地址(用于命名)
  9010. * @return string|null 转换后的文件路径,转换失败返回null
  9011. */
  9012. private function convertImageFile($rawFile, $url) {
  9013. $content = @file_get_contents($rawFile);
  9014. if ($content === false || $content === '') return null;
  9015. if (!function_exists('imagecreatefromstring')) return null;
  9016. $image = @imagecreatefromstring($content);
  9017. if ($image === false) return null;
  9018. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  9019. imagedestroy($image);
  9020. if ($jpeg !== null) {
  9021. @unlink($rawFile);
  9022. }
  9023. return $jpeg;
  9024. }
  9025. /**
  9026. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  9027. * @param resource $srcImage GD图片资源
  9028. * @param string $rawFile 原始图片临时文件
  9029. * @param string $url 图片地址(用于命名)
  9030. * @return string|null 压缩后的JPEG文件路径
  9031. */
  9032. private function compressImageForPdf($srcImage, $rawFile, $url) {
  9033. $maxBytes = 2 * 1024 * 1024; // 2MB
  9034. $sizes = [2048, 1600, 1280, 1024, 800];
  9035. $qualities = [85, 70, 55, 40];
  9036. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  9037. foreach ($sizes as $size) {
  9038. $resized = $this->copyAndResize($srcImage, $size);
  9039. $flat = $this->flattenToWhite($resized);
  9040. imagedestroy($resized);
  9041. foreach ($qualities as $quality) {
  9042. ob_start();
  9043. $saved = imagejpeg($flat, null, $quality);
  9044. $data = ob_get_clean();
  9045. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  9046. file_put_contents($jpeg, $data);
  9047. imagedestroy($flat);
  9048. dLog('anime')->info('导出PDF图片压缩完成', [
  9049. 'url' => $url,
  9050. 'size' => filesize($jpeg),
  9051. 'edge' => $size,
  9052. 'quality' => $quality,
  9053. ]);
  9054. return $jpeg;
  9055. }
  9056. }
  9057. imagedestroy($flat);
  9058. }
  9059. // 兜底:最小尺寸、最低质量强制输出
  9060. $resized = $this->copyAndResize($srcImage, 800);
  9061. $flat = $this->flattenToWhite($resized);
  9062. imagedestroy($resized);
  9063. $saved = imagejpeg($flat, $jpeg, 30);
  9064. imagedestroy($flat);
  9065. if (!$saved) return null;
  9066. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  9067. 'url' => $url,
  9068. 'size' => filesize($jpeg),
  9069. ]);
  9070. return $jpeg;
  9071. }
  9072. /**
  9073. * 等比缩放图片副本(不销毁原图)
  9074. * @param resource $srcImage GD图片资源
  9075. * @param int $maxEdge 最大边长
  9076. * @return resource
  9077. */
  9078. private function copyAndResize($srcImage, $maxEdge) {
  9079. $width = imagesx($srcImage);
  9080. $height = imagesy($srcImage);
  9081. $max = max($width, $height);
  9082. if ($max <= $maxEdge) {
  9083. $copy = imagecreatetruecolor($width, $height);
  9084. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  9085. return $copy;
  9086. }
  9087. $ratio = $maxEdge / $max;
  9088. $newWidth = max(1, (int)round($width * $ratio));
  9089. $newHeight = max(1, (int)round($height * $ratio));
  9090. $resized = imagecreatetruecolor($newWidth, $newHeight);
  9091. imagealphablending($resized, false);
  9092. imagesavealpha($resized, true);
  9093. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  9094. return $resized;
  9095. }
  9096. /**
  9097. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  9098. * @param resource $image GD图片资源
  9099. * @return resource
  9100. */
  9101. private function flattenToWhite($image) {
  9102. $width = imagesx($image);
  9103. $height = imagesy($image);
  9104. $flat = imagecreatetruecolor($width, $height);
  9105. $white = imagecolorallocate($flat, 255, 255, 255);
  9106. imagefill($flat, 0, 0, $white);
  9107. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  9108. return $flat;
  9109. }
  9110. /**
  9111. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  9112. * @param string $content 片段内容
  9113. * @param int $counter 当前已编号数量(引用传递,整集累计)
  9114. * @return string
  9115. */
  9116. private function renumberSegmentBlocks($content, &$counter) {
  9117. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  9118. $counter++;
  9119. return '【' . $match[1] . $counter . '】';
  9120. }, $content);
  9121. }
  9122. }