| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686 |
- <?php
- namespace App\Services\Anime;
- use App\Consts\BaseConst;
- use App\Consts\ErrorConst;
- use App\Facade\Site;
- use App\Libs\Utils;
- use App\Models\MpGeneratePicTask;
- use App\Services\AIGeneration\AIImageGenerationService;
- use App\Services\AIGeneration\AIVideoGenerationService;
- use App\Services\DeepSeek\DeepSeekService;
- use Dflydev\DotAccessData\Util;
- use GuzzleHttp\Client;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use OSS\Core\OssException;
- use OSS\OssClient;
- class AnimeService
- {
- protected $aiImageGenerationService;
- protected $aiVideoGenerationService;
- protected $DeepSeekService;
- private $url;
- private $api_key;
- private $headers;
- public function __construct(
- AIImageGenerationService $aiImageGenerationService,
- AIVideoGenerationService $aiVideoGenerationService,
- DeepSeekService $DeepSeekService
- ) {
- $this->aiImageGenerationService = $aiImageGenerationService;
- $this->aiVideoGenerationService = $aiVideoGenerationService;
- $this->DeepSeekService = $DeepSeekService;
- $this->url = 'https://api.deepseek.com/chat/completions';
- $this->api_key = env('DEEPSEEK_API_KEY');
- $this->headers = [
- 'Authorization' => 'Bearer '.$this->api_key,
- 'Content-Type' => 'application/json; charset=UTF-8'
- ];
- }
- /**
- * 构建统一的分镜数据结构(episodeInfo格式)
- * @param array $segments 分镜数据数组
- * @return array 返回包含acts和total_duration的数组
- */
- public function buildEpisodeSegmentsStructure($segments) {
- $acts = [];
- $totalDuration = 0; // 初始化总时长
-
- foreach($segments as $segment) {
- // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
- $videoDuration = getProp($segment, 'video_duration');
- $audioDuration = getProp($segment, 'audio_duration');
-
- if (!empty($videoDuration) && is_numeric($videoDuration)) {
- $totalDuration += floatval($videoDuration);
- } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
- $totalDuration += floatval($audioDuration);
- } else {
- $totalDuration += 5; // 默认5秒
- }
-
- $segment_content = getProp($segment, 'segment_content');
- // 判断是否有尾帧描述,如果有则去掉这部分内容
- if (strpos($segment_content, '尾帧') !== false) {
- // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
- $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
- }
- // 构建分镜信息
- $segmentInfo = [
- 'segment_id' => getProp($segment, 'segment_id'),
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => $segment_content,
- 'description' => getProp($segment, 'description'),
- 'composition' => getProp($segment, 'composition'),
- 'camera_movement' => getProp($segment, 'camera_movement'),
- 'voice_actor' => getProp($segment, 'voice_actor'),
- 'dialogue' => getProp($segment, 'dialogue'),
- 'frame_type' => getProp($segment, 'frame_type'),
- 'scene' => getProp($segment, 'scene'),
- 'characters' => getProp($segment, 'characters'),
- 'tail_frame' => getProp($segment, 'tail_frame'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio'),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
- 'emotion_scale' => getProp($segment, 'emotion_scale'),
- 'pitch' => getProp($segment, 'pitch'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
- 'img_url' => getProp($segment, 'img_url'),
- 'audio_url' => getProp($segment, 'audio_url'),
- 'audio_duration' => getProp($segment, 'audio_duration', 0),
- 'video_url' => getProp($segment, 'video_url'),
- 'video_duration' => getProp($segment, 'video_duration', 0),
- 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
- 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- 'current_type' => getProp($segment, 'current_type'),
- ];
-
- $actNumber = getProp($segment, 'act_number');
- if (isset($acts[$actNumber])) {
- $acts[$actNumber]['segments'][] = $segmentInfo;
- } else {
- $acts[$actNumber] = [
- 'act_number' => $actNumber,
- 'act_title' => getProp($segment, 'act_title'),
- 'act_duration' => getProp($segment, 'act_duration'),
- 'segments' => [$segmentInfo]
- ];
- }
- }
-
- return [
- 'acts' => array_values($acts),
- 'total_duration' => intval(round($totalDuration))
- ];
- }
- /**
- * 构建统一的分段数据结构(episodeInfoForAce格式)
- * @param array $segments 分段数据数组
- * @return array 返回包含acts和total_duration的数组
- */
- public function buildEpisodeActsStructureForAce($segments) {
- $acts = [];
- $totalDuration = 0; // 初始化总时长
-
- foreach($segments as $segment) {
- // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
- $videoDuration = getProp($segment, 'video_duration');
- $actDuration = getProp($segment, 'act_duration');
-
- if (!empty($videoDuration) && is_numeric($videoDuration)) {
- $totalDuration += floatval($videoDuration);
- } elseif (!empty($actDuration) && is_numeric($actDuration)) {
- $totalDuration += floatval($actDuration);
- } else {
- $totalDuration += 5; // 默认5秒
- }
- // 构建分镜信息
- $segmentInfo = [
- 'act_id' => getProp($segment, 'id'),
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'act_duration' => getProp($segment, 'act_duration'),
- 'act_content' => getProp($segment, 'act_content'),
- 'video_url' => getProp($segment, 'video_url'),
- 'video_duration' => getProp($segment, 'video_duration', 0),
- 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
- 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- 'current_type' => getProp($segment, 'current_type'),
- ];
- $acts[] = $segmentInfo;
- }
-
- return [
- 'acts' => array_values($acts),
- 'total_duration' => intval(round($totalDuration))
- ];
- }
- /**
- * 验证画面比例是否有效
- * @param string $ratio 画面比例
- * @return bool
- */
- public function validateRatio($ratio) {
- return isset(BaseConst::IMAGE_RATIOS[$ratio]);
- }
- /**
- * 获取画面比例对应的宽高
- * @param string $ratio 画面比例
- * @return array ['width' => int, 'height' => int]
- * @throws \Exception
- */
- private function getRatioDimensions($ratio) {
- if ($ratio && !$this->validateRatio($ratio)) {
- $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
- Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
- }
- return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
- }
- public function createAnime($data) {
- $uid = Site::getUid();
- $input_art_style = getProp($data, 'art_style');
- $file = getProp($data, 'file');
- $content = getProp($data, 'content', '');
- $bid = getProp($data, 'bid', 0);
- $script_id = getProp($data, 'script_id', 0);
- $ace_mode = getProp($data, 'ace_mode', 0);
- $extra_products = getProp($data, 'products', []);
- if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
- if (!is_array($extra_products)) {
- Utils::throwError('20003:传入的资产格式不正确');
- }
-
- // 替换美术风格
- $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
- // 提取文件内容
- if ($file) {
- $content = $this->DeepSeekService->extractFileContent($file);
- if (!$content) {
- Utils::throwError('20003:无法提取文件内容,请检查文件格式');
- }
- } elseif ($script_id) {
- $content = $this->DeepSeekService->getContentByScriptId($script_id);
- if (!$content) {
- Utils::throwError('20003:无法获取剧本内容,请检查剧本');
- }
- } elseif ($bid) {
- $content = $this->DeepSeekService->getContentByBid($bid);
- if (!$content) {
- Utils::throwError('20003:无法获取书籍内容,请检查书籍');
- }
- } elseif ($content) {
- $content = filterContent($content);
- }else {
- $content = '';
- }
- $anime_data = [
- 'user_id' => $uid,
- 'anime_name' => '新剧本策划',
- 'is_multi' => getProp($data, 'is_multi', 1),
- 'content' => $content,
- 'art_style_type' => $input_art_style,
- 'ace_mode' => $ace_mode,
- 'extra_products' => json_encode($extra_products, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- // 处理文本模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,使用默认值
- $model = 'doubao-seed-2-0-mini-260215';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seed-2-0-mini-260215';
- }
- $anime_data['model'] = $model;
- if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
- return DB::table('mp_animes')->insertGetId($anime_data);
- }
- public function chatList($data) {
- $uid = Site::getUid();
- $anime_name = getProp($data, 'anime_name');
- $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
- if ($anime_name) {
- $query->where('anime_name', 'like', "%$anime_name%");
- }
- return $query->orderBy('id', 'desc')->paginate();
- }
- public function chatHistory($data) {
- $anime_id = getProp($data, 'anime_id');
- $sequence = getProp($data, 'sequence', 0);
- if (!$anime_id) Utils::throwError('20003:请选择对话!');
- $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)
- ->where('ar.sequence', $sequence)->where('segment_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');
-
- return $query->orderBy('ar.id')->get()->map(function ($value) {
- $value = (array)$value;
- if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
- $value['created_at'] = transDate($value['created_at']);
- $value['episode_created_at'] = transDate($value['episode_created_at']);
- return $value;
- })->toArray();
- }
- public function batchSetRoleImg($data) {
- $episode_id = getProp($data, 'episode_id');
- if (!$episode_id) Utils::throwError('1002:请选择分集');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $roles = json_decode(getProp($data, 'roles'), true) ?: [];
- $art_style = getProp($episode, 'art_style');
- $anime_id = getProp($episode, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- foreach ($roles as &$role) {
- $role_name = getProp($role, 'role');
- if ($role_name == '旁白') continue;
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $pic_prompt = getProp($role, 'pic_prompt');
- $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
-
- // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
- // 参考图地址
- $ref_img_url = getProp($role, 'url');
- if ($ref_img_url) continue; // 已有图片则跳过
-
- // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
- try {
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:角色({$role_name})生成图片失败");
- }
-
- $role['task_id'] = $task_id;
- $role['task_status'] = 'processing';
- } catch (\Exception $e) {
- logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
- Utils::throwError("20003:" . $e->getMessage());
- }
- }
-
- // 保存角色信息
- $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($roles, 256),
- 'generate_status' => '执行中',
- 'generate_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:保存角色信息失败');
- }
- return $boolen;
- }
- public function batchSetSceneImg($data) {
- $episode_id = getProp($data, 'episode_id');
- if (!$episode_id) Utils::throwError('1002:请选择分集');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $scenes = json_decode(getProp($episode, 'scenes'), true);
- $art_style = getProp($episode, 'art_style');
- $target_scene = getProp($data, 'target_scene');
- $anime_id = getProp($episode, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- foreach ($scenes as &$scene) {
- $scene_name = getProp($scene, 'scene');
- if ($scene_name != $target_scene) continue;
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $pic_prompt = getProp($scene, 'pic_prompt');
- $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
-
- // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
- // 参考图地址
- $ref_img_url = getProp($scene, 'url');
- if ($ref_img_url) continue; // 已有图片则跳过
-
- // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
- try {
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:场景({$scene_name})生成图片失败");
- }
-
- $scene['task_id'] = $task_id;
- $scene['task_status'] = 'processing';
- } catch (\Exception $e) {
- logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
- Utils::throwError("20003:" . $e->getMessage());
- }
- }
-
- // 保存场景信息
- $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'scenes' => json_encode($scenes, 256),
- 'generate_status' => '执行中',
- 'generate_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:保存角色信息失败');
- }
- return $boolen;
- }
- public function editAnime($data) {
- $anime_id = getProp($data, 'anime_id');
- $anime_name = trim(getProp($data, 'anime_name'));
- // 确认对话名称唯一性
- if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
- if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
- }
- if (!$anime_id || !$anime_name) {
- Utils::throwError('20003:参数异常');
- }
- return DB::table('mp_animes')->where('id', $anime_id)->update([
- 'anime_name' => $anime_name,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // $script_arr =getProp($data, 'script', []);
- // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
- // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
- // $anime_id = getProp($data, 'anime_id');
- // try {
- // DB::beginTransaction();
- // $table_data = [
- // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
- // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
- // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
- // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
- // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
- // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
- // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
- // 'status' => 3,
- // 'start_episode_sequence' => $start_episode_sequence,
- // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
- // 'episode_num' => count($script_arr['episodes']),
- // 'updated_at' => date('Y-m-d H:i:s')
- // ];
- // // 保存剧本内容
- // if (!empty($anime_id)) {
- // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
- // if (!$boolen) {
- // dLog('anime')->info('对话保存失败', $table_data);
- // Utils::throwError('20003:对话保存失败');
- // }
- // }else {
- // $table['created_at'] = $table_data['updated_at'];
- // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
- // if (!$anime_id) {
- // dLog('anime')->info('对话保存失败', $table_data);
- // Utils::throwError('20003:对话保存失败');
- // }
- // }
-
-
- // // 保存分集内容
- // // 删除历史分集内容
- // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
-
- // $episodes = [];
- // $sequence = 1;
- // foreach ($script_arr['episodes'] as $episode) {
- // $segment_number = 1;
- // foreach($episode['segments'] as $segment) {
- // $episodes[] = [
- // 'anime_id' => $anime_id,
- // 'episode_number' => $episode['episode_number'],
- // 'title' => $episode['title'],
- // // 'content' => $episode['content'],
- // 'content' => '',
- // 'segment_number' => $segment_number,
- // 'segment_content' => $segment['segment_content'],
- // 'sequence' => $sequence,
- // 'created_at' => date('Y-m-d H:i:s'),
- // 'updated_at' => date('Y-m-d H:i:s')
- // ];
- // $sequence++;
- // $segment_number++;
- // }
-
- // }
- // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
- // if (!$boolen2) {
- // dLog('deepseek')->info('分集内容保存失败', $episodes);
- // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
- // Utils::throwError('20003:分集内容保存失败');
- // }
- // } catch (\Exception $e) {
- // DB::rollBack();
- // Utils::throwError('20003:'.$e->getMessage());
- // }
- // DB::commit();
- // return true;
- }
- public function delAnime($data) {
- $anime_id = getProp($data, 'anime_id');
- if (!$anime_id) {
- Utils::throwError('20003:请选择剧本');
- }
- return DB::table('mp_animes')->where('id', $anime_id)->update([
- 'is_deleted' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function animeDetail($data) {
- $uid = Site::getUid();
- $anime_id = getProp($data, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
- ->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')->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- $anime = (array)$anime;
- $anime['roles'] = json_decode($anime['roles']);
- $anime['scenes'] = json_decode($anime['scenes']);
- // 获取分集信息
- $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
- ->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"))
- ->orderBy('episode_number')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- $anime['episodes'] = $episodes;
- return $anime;
- }
- public function episodeInfo($data) {
- $uid = Site::getUid();
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- // 验证用户权限
- $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- $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();
- if (!$episode) Utils::throwError('20003:该剧集不存在!');
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- // foreach($episode['roles'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
- // }
- $episode['scenes'] = json_decode($episode['scenes'], true);
- // foreach($episode['scenes'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
- // }
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 使用公共方法构建分镜结构
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- return $episode;
- }
- public function episodeInfoForAce($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- $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();
- if (!$episode) Utils::throwError('20003:该剧集不存在!');
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- // foreach($episode['roles'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
- // }
- $episode['scenes'] = json_decode($episode['scenes'], true);
- // foreach($episode['scenes'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
- // }
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- return $episode;
- }
- public function segmentInfo($data) {
- $uid = Site::getUid();
- $segment_id = getProp($data, 'segment_id');
- if (!$segment_id) {
- Utils::throwError('1002:请选择分镜');
- }
-
- // 获取分镜信息
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
-
- // 验证用户权限
- if ($segment) {
- $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- }
-
- $result = [
- 'segment_id' => getProp($segment, 'segment_id'),
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => getProp($segment, 'segment_content'),
- 'description' => getProp($segment, 'description'),
- 'composition' => getProp($segment, 'composition'),
- 'camera_movement' => getProp($segment, 'camera_movement'),
- 'voice_actor' => getProp($segment, 'voice_actor'),
- 'dialogue' => getProp($segment, 'dialogue'),
- 'frame_type' => getProp($segment, 'frame_type'),
- 'scene' => getProp($segment, 'scene'),
- 'characters' => getProp($segment, 'characters'),
- 'tail_frame' => getProp($segment, 'tail_frame'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio'),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
- 'emotion_scale' => getProp($segment, 'emotion_scale'),
- 'pitch' => getProp($segment, 'pitch'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
- 'img_url' => getProp($segment, 'img_url'),
- 'video_url' => getProp($segment, 'video_url'),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- ];
- return $result;
- }
- public function copyEpisodeVersion($data) {
- $episode_id = getProp($data, 'episode_id');
- $uid = Site::getUid();
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $episode = (array)$episode;
- $anime_id = $episode['anime_id'];
- $episode_number = $episode['episode_number'];
- $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
- $sequence = $count + 1;
- unset($episode['id']);
- $now = date('Y-m-d H:i:s');
- $episode['created_at'] = $now;
- $episode['updated_at'] = $now;
- $episode['is_default'] = 1;
- // 获取版本中含有"(副本"字样的个数
- $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
- $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
- $episode['sequence'] = $sequence;
- $episode['is_generated'] = 0;
- // 获取ace_mode
- $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
- try {
- DB::beginTransaction();
- DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
- // 新增副本
- $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
- if (!$new_episode_id) {
- Utils::throwError('20003:创建副本失败!');
- }
- // 获取分镜数据并准备插入
- $segments_for_insert = DB::table('mp_episode_segments')
- ->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')
- ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
- $item = (array)$item;
- $item['episode_id'] = $new_episode_id;
- if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
- $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
- return $item;
- })->toArray();
- // 写入分镜数据
- $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
- if (!$boolen2) {
- Utils::throwError('20003:写入分镜数据失败!');
- }
- // 写入对话历史
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'role' => 'user',
- 'content' => '创建副本',
- 'sequence' => $episode_number,
- 'episode_id' => $new_episode_id,
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'role' => 'assistant',
- 'content' => '好的,已为您创建副本',
- 'sequence' => $episode_number,
- 'episode_id' => $new_episode_id,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
- $boolen3 = DB::table('mp_anime_records')->insert($records);
- if (!$boolen3) {
- Utils::throwError('20003:对话记录保存失败');
- }
-
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- // 构建与 episodeInfo 方法一致的返回数据结构
- $result = [
- 'episode_id' => $new_episode_id,
- 'anime_id' => $anime_id,
- 'episode_number' => $episode_number,
- 'title' => $episode['title'],
- 'intro' => $episode['intro'],
- 'art_style' => $episode['art_style'],
- 'roles' => json_decode($episode['roles'], true),
- 'scenes' => json_decode($episode['scenes'], true),
- 'is_generated' => (int)$episode['is_generated']
- ];
- if ((int)$ace_mode === 1) {
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
- }else {
- // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
- }
- $result['acts'] = $segmentsStructure['acts'];
- $result['total_duration'] = $segmentsStructure['total_duration'];
- return $result;
- }
- public function episodeVersions($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
- $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) {
- return (array)$value;
- })->toArray();
- if (!$episodes) Utils::throwError('20003:该剧集不存在!');
-
- foreach($episodes as &$episode) {
- $episode['version'] = 'V'.$episode['sequence'];
- $episode['roles'] = json_decode($episode['roles'], true);
- $episode['scenes'] = json_decode($episode['scenes'], true);
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 使用公共方法构建分镜结构
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- }
- return $episodes;
- }
- public function bindEpisodeVersion($data) {
- $episode_id = getProp($data, 'episode_id');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $episode = (array)$episode;
- if ((int)$episode['is_default'] === 1) return true;
- try {
- DB::beginTransaction();
- // 移除is_default标志
- $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')]);
- if (!$boolen) {
- Utils::throwError('20003:更新失败!');
- }
- // 绑定副本
- $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
- if (!$boolen2) {
- Utils::throwError('20003:绑定失败!');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return true;
- }
- public function chatChangeImg($data) {
- $segment_id = getProp($data, 'segment_id');
- $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
- $prompt = getProp($data, 'prompt');
- if (!$prompt || !$segment_id) {
- Utils::throwError('1002:请输入提示词,并且选择分镜');
- }
- $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:该分镜不存在!');
- if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
- else $ref_img_url = '';
- // $ref_img_url = '';
- if (empty($prompt)) {
- if (empty($ref_img_url)) {
- $prompt = getProp($segment, 'segment_content');
- }else {
- $prompt = '请根据图片生成';
- }
- }
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $ratio = getProp($data, 'ratio');
- if (!$ratio) {
- $ratio = getProp($episode, 'ratio');
- if (!$ratio) $ratio = '9:16';
- }
- $art_style = getProp($episode, 'art_style');
- if ($art_style) {
- $prompt = "美术风格:{$art_style}\n{$prompt}";
- }
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
- try {
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
- 'width' => $width,
- 'height' => $height
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:生成图片失败");
- }
-
- // 更新任务ID
- $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')]);
- if (!$boolen) Utils::throwError('20003:更新任务ID失败');
- } catch (\Exception $e) {
- Utils::throwError("20003:" . $e->getMessage());
- }
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
- // 图片生成后新增对话记录
- try {
- $uid = Site::getUid();
- $now = date('Y-m-d H:i:s');
-
- // 使用AI反推图片提示词
- $pic_prompt = $this->generateImagePromptFromUrl($img_url);
-
- // 保存对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'user',
- 'content' => $prompt,
- 'segment_id' => $segment_id,
- 'image_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'assistant',
- 'content' => $pic_prompt,
- 'segment_id' => $segment_id,
- 'image_url' => $img_url,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
-
- DB::table('mp_anime_records')->insert($records);
-
- } catch (\Exception $e) {
- // 记录日志但不影响主流程
- dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url
- ]);
- logDB('anime', 'error', '保存对话记录失败', [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url,
- 'error' => $e->getMessage()
- ]);
- }
- return $img_url;
- }
- public function segmentChatHistory($data) {
- $segment_id = getProp($data, 'segment_id');
- if (!$segment_id) Utils::throwError('20003:请选择分镜!');
- $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
-
- $chat = $query->orderBy('id')->get()->map(function ($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at']);
- return $value;
- })->toArray();
- // 获取历史图片
- $url = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
-
- // 获取历史视频
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'compressed_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
- return compact('chat', 'url');
- }
- public function changeEpisodeRoles($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_roles = getProp($data, 'roles');
- $is_deleted = getProp($data, 'is_deleted', 0);
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_roles) Utils::throwError('20003:请提供角色信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $roles = json_decode(getProp($episode, 'roles'), true);
- try {
- $target_role_name = getProp($target_roles, 'role');
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从角色列表中移除该角色
- $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
- return getProp($role, 'role') !== $target_role_name;
- }));
-
- // 更新角色列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'roles' => json_encode($roles, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除角色失败');
- }
- } else {
- // 新增或更新操作
- $role_found = false;
-
- // 查找并更新已存在的角色
- foreach($roles as &$role) {
- if (getProp($role, 'role') === $target_role_name) {
- $role = $target_roles;
- $role_found = true;
- break;
- }
- }
-
- // 如果角色不存在,则新增
- if (!$role_found) {
- $roles[] = $target_roles;
- }
- // 更新角色列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'roles' => json_encode($roles, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:更新角色列表失败');
- }
-
- // 同步更新分镜表中对应主体的音色信息
- $voice_name = getProp($target_roles, 'voice_name');
- $voice_type = getProp($target_roles, 'voice_type');
- $voice_audio_url = getProp($target_roles, 'voice_audio_url');
-
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_role_name)
- ->update([
- 'voice_name' => $voice_name,
- 'voice_type' => $voice_type,
- 'voice_audio_url' => $voice_audio_url,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('更新剧集角色失败', [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
- }
- return true;
- }
- public function changeEpisodeScenes($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_scenes = getProp($data, 'scenes');
- $is_deleted = getProp($data, 'is_deleted', 0);
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $scenes = json_decode(getProp($episode, 'scenes'), true);
- try {
- $target_scene_name = getProp($target_scenes, 'scene');
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从场景列表中移除该场景
- $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
- return getProp($scene, 'scene') !== $target_scene_name;
- }));
-
- // 更新场景列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'scenes' => json_encode($scenes, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除场景失败');
- }
- } else {
- // 新增或更新操作
- $scene_found = false;
-
- // 查找并更新已存在的场景
- foreach($scenes as &$scene) {
- if (getProp($scene, 'scene') === $target_scene_name) {
- $scene = $target_scenes;
- $scene_found = true;
- break;
- }
- }
-
- // 如果场景不存在,则新增
- if (!$scene_found) {
- $scenes[] = $target_scenes;
- }
- // 更新场景列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'scenes' => json_encode($scenes, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:更新场景列表失败');
- }
- }
- } catch (\Exception $e) {
- dLog('anime')->error('更新剧集场景失败', [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
- }
- return true;
- }
- public function editSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment_content = getProp($data, 'segment_content');
- $image_url = getProp($data, 'image_url');
- $video_url = getProp($data, 'video_url');
- // 参数验证
- if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
- // 验证分镜是否存在
- $segment = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->first();
-
- if (!$segment) Utils::throwError('20003:该分镜不存在');
- $dubTaskId = 0;
- try {
- DB::beginTransaction();
- // 准备更新数据
- $update_data = [
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($segment_content) {
- // 先将segment_content赋值到update_data
- $update_data['segment_content'] = $segment_content;
-
- // 使用现有方法分析segment_content,提取各个字段
- $this->handleSegmentContent($update_data);
-
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($update_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($update_data, 'voice_actor'),
- 'voice_type' => getProp($update_data, 'voice_type'),
- 'voice_name' => getProp($update_data, 'voice_name'),
- 'emotion' => getProp($update_data, 'emotion'),
- 'emotion_type' => getProp($update_data, 'emotion_type'),
- 'gender' => getProp($update_data, 'gender'),
- 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
- 'pitch' => getProp($update_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
- $update_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- }
- if ($image_url) {
- $update_data['img_url'] = $image_url;
- // 同时写入一个简单的图片生成任务
- $pic_task = [
- 'alias_segment_id' => $segment_id,
- 'ref_img_url' => json_encode([]),
- 'status' => 'success',
- 'result_url' => json_encode([$image_url], 256),
- 'model' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_pic_tasks')->insert($pic_task);
- }
- if ($video_url) {
- $update_data['origin_video_url'] = $video_url;
- $compressed_video_url = compressVideo($video_url);
- $update_data['current_type'] = 2;
- $update_data['video_url'] = $compressed_video_url ?: $video_url;
- // 同时写入一个简单的视频生成任务
- $video_task = [
- 'alias_segment_id' => $segment_id,
- 'status' => 'success',
- 'result_url' => $update_data['origin_video_url'],
- 'compressed_url' => $update_data['video_url'],
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_video_tasks')->insert($video_task);
- }
- // 更新分镜信息
- $result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- if ($result === false) {
- Utils::throwError('20003:更新分镜剧本失败');
- }
- DB::commit();
- // 如果有创建音频生成任务则调用API
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
- return true;
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('更新分镜剧本失败', [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
- }
- }
- public function batchSetSegmentPics($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $ratio = getProp($data, 'ratio');
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- // 获取剧集信息
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->where('is_default', 1)
- ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
- ->first();
-
- if (!$episode) {
- Utils::throwError('20003:该剧集不存在');
- }
- $model = getProp($data, 'model');
- if (!$model) {
- $model = getProp($episode, 'image_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- $roles = json_decode(getProp($episode, 'roles'), true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
- // $base_name = preg_replace('/[--].*$/u', '', $role_name);
- // $role_map[$base_name] = $role_url;
- // 同时保存完整名称的映射
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode(getProp($episode, 'roles'), true);
- if (!$scenes) {
- Utils::throwError('20003:场景信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- // 获取所有分镜信息
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->whereNotIn('pic_task_status', ['已完成', '生成中'])
- ->orderBy('segment_number')
- ->get()
- ->toArray();
- if (empty($segments)) {
- Utils::throwError('20003:所有分镜图片已完成或正在生成中');
- }
- // 保存图片比例
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
- $updated_segments = [];
- $failed_segments = [];
- // 批量为每个分镜生成图片任务
- foreach ($segments as $segment) {
- $segment_id = $segment->segment_id;
- $segment_content = $segment->segment_content;
-
- if (empty($segment_content)) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '分镜内容为空'
- ];
- continue;
- }
- try {
- $dubTaskId = 0;
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($segment, 'scene');
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- // 分镜角色
- $characters = getProp($segment, 'characters');
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $roles = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'model' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- // $task_id = mt_rand(100000, 999999);
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '创建生成任务失败'
- ];
- continue;
- }
- $update_data = [
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'audio_url' => '',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($segment, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($segment, 'voice_actor'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
- 'pitch' => getProp($segment, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
- logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
- // Utils::throwError('20003:创建配音任务失败!');
- }
-
- } else {
- // dialogue为空时,直接写入默认音频信息到分镜表
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
-
- // 更新分镜的任务信息
- $update_result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
-
- if ($update_result) {
- $updated_segments[] = [
- 'segment_id' => $segment_id,
- 'task_id' => $task_id,
- 'status' => '生成中',
- 'matched_scenes' => $matched_scene,
- 'matched_roles' => $segment_characters,
- 'ref_urls_count' => count($ref_img_urls)
- ];
- } else {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '更新分镜任务状态失败'
- ];
- }
- if ($dubTaskId) {
- sleep(1);
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
- }
- }
-
- } catch (\Exception $e) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ];
- }
- }
- // 更新剧集生成状态
- if (!empty($updated_segments)) {
- DB::table('mp_anime_episodes')
- ->where('id', $episode_id)
- ->update([
- 'is_generated' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- return [
- 'success_count' => count($updated_segments),
- 'failed_count' => count($failed_segments),
- 'success_segments' => $updated_segments,
- 'failed_segments' => $failed_segments,
- 'total_segments' => count($segments)
- ];
- }
- public function reGenerateSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_content = getProp($data, 'segment_content');
- $ratio = getProp($data, 'ratio');
- if (!$ratio) {
- $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
- if (!$ratio) $ratio = '9:16';
- }
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择分镜');
- }
- // 使用文生文模型重新解析segment_content
- if (!empty($segment_content)) {
- $segment_content = $this->parseSegmentContentWithAI($segment_content);
- }
- // 获取动漫的角色信息(包含参考图)
- $anime = DB::table('mp_animes')
- ->where('id', $anime_id)
- ->select('roles', 'scenes')
- ->first();
-
- if (!$anime || !$anime->roles) {
- Utils::throwError('20003:未找到角色信息');
- }
- $roles = json_decode($anime->roles, true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode($anime->scenes, true);
- if (!$scenes) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- $segment_id = $segment->segment_id;
- $original_segment_content = $segment->segment_content;
-
- // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
- $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
-
- if (empty($final_segment_content)) {
- Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
- }
- try {
- $dubTaskId = 0;
- // 分镜剧本数组
- $update_data = [
- 'segment_content' => $final_segment_content,
- 'pic_task_status' => '生成中',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $final_segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($data, 'scene');
- if ($scene) {
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- $update_data['scene'] = $scene;
- }
- // 分镜角色
- $characters = getProp($data, 'characters');
- if ($characters) {
- $update_data['characters'] = $characters;
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $characters = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
- }
-
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建生成任务失败!');
- }
- $update_data['pic_task_id'] = $task_id;
-
- // 更新分镜剧本信息
- $this->handleSegmentContent($update_data);
- // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
- if ($segment_content) {
- $dialogue = getProp($update_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($update_data, 'voice_actor'),
- 'voice_type' => getProp($update_data, 'voice_type'),
- 'voice_name' => getProp($update_data, 'voice_name'),
- 'emotion' => getProp($update_data, 'emotion'),
- 'emotion_type' => getProp($update_data, 'emotion_type'),
- 'gender' => getProp($update_data, 'gender'),
- 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
- 'pitch' => getProp($update_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
-
- $update_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- }
- $boolen = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
-
- } catch (\Exception $e) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ];
- }
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
-
- // 图片生成后新增对话记录
- try {
- $uid = Site::getUid();
- $now = date('Y-m-d H:i:s');
-
- // 使用AI反推图片提示词
- $pic_prompt = $this->generateImagePromptFromUrl($img_url);
-
- // 保存对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'user',
- 'content' => '重新生成',
- 'segment_id' => $segment_id,
- 'image_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'assistant',
- 'content' => $pic_prompt,
- 'segment_id' => $segment_id,
- 'image_url' => $img_url,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
-
- DB::table('mp_anime_records')->insert($records);
- } catch (\Exception $e) {
- // 记录日志但不影响主流程
- dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url
- ]);
- }
-
- return $img_url;
- }
- public function addSegment($data) {
- $prev_segment_id = getProp($data, 'prev_segment_id');
- $img_url = getProp($data, 'img_url');
- $video_url = getProp($data, 'video_url');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
- if (!$segment) Utils::throwError('20003:该分镜不存在');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $new_segment_number = $segment_number + 1;
- $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
- // 分镜剧本数组
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'segment_id' => $segment_id,
- 'segment_number' => $new_segment_number,
- 'segment_content' => '',
- 'img_url' => '',
- 'video_url' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($img_url) $insert_data['img_url'] = $img_url;
- if ($video_url) {
- $insert_data['origin_video_url'] = $video_url;
- $insert_data['current_type'] = 2;
- $compressed_video_url = compressVideo($video_url);
- $insert_data['video_url'] = $compressed_video_url ?: $video_url;
- }
- try {
- DB::beginTransaction();
- // 先更新序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
- if (!$id) {
- Utils::throwError('20003:新增分镜失败!');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- // 以下代码暂弃用
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $segment_content = getProp($data, 'segment_content');
- $img_url = getProp($data, 'img_url');
- $video_url = getProp($data, 'video_url');
- $ratio = getProp($data, 'ratio');
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择分镜');
- }
- // 使用文生文模型重新解析segment_content
- if (!empty($segment_content)) {
- $segment_content = $this->parseSegmentContentWithAI($segment_content);
- }
- // 获取动漫的角色信息(包含参考图)
- $anime = DB::table('mp_animes')
- ->where('id', $anime_id)
- ->select('roles', 'scenes')
- ->first();
-
- if (!$anime || !$anime->roles) {
- Utils::throwError('20003:未找到角色信息');
- }
- $roles = json_decode($anime->roles, true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode($anime->scenes, true);
- if (!$scenes) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- $segment_id = $segment->segment_id;
- $original_segment_content = $segment->segment_content;
-
- // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
- $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
-
- if (empty($final_segment_content)) {
- Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
- }
- try {
- $dubTaskId = 0;
- DB::beginTransaction();
- $new_segment_number = $segment_number + 1;
- $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
- // 分镜剧本数组
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'segment_id' => $segment_id,
- 'segment_number' => $new_segment_number,
- 'segment_content' => $final_segment_content,
- 'img_url' => $img_url,
- 'video_url' => $video_url,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 更新分镜剧本信息
- $this->handleSegmentContent($insert_data);
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($insert_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($insert_data, 'voice_actor'),
- 'voice_type' => getProp($insert_data, 'voice_type'),
- 'voice_name' => getProp($insert_data, 'voice_name'),
- 'emotion' => getProp($insert_data, 'emotion'),
- 'emotion_type' => getProp($insert_data, 'emotion_type'),
- 'gender' => getProp($insert_data, 'gender'),
- 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
- 'pitch' => getProp($insert_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
- $insert_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $insert_data['audio_duration'] = 2.0;
- $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- // 如果没有上传图片则使用当前描述进行生成
- if (!$img_url) {
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $final_segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($insert_data, 'scene');
- if ($scene) {
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- $update_data['scene'] = $scene;
- }
- // 分镜角色
- $characters = getProp($insert_data, 'characters');
- if ($characters) {
- $update_data['characters'] = $characters;
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $characters = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
- }
-
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
-
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
- // $task_id = 'whatever';
- if (!$task_id) {
- Utils::throwError('20003:创建生成任务失败!');
- }
- $insert_data['pic_task_status'] = '生成中';
- $insert_data['pic_task_id'] = $task_id;
- }
-
- // 先更新序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- $boolen = DB::table('mp_episode_segments')->insert($insert_data);
- if (!$boolen) {
- Utils::throwError('20003:新增分镜失败!');
- }
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
-
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function copySegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:请选择分镜');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $new_segment_id = 0;
- try {
- DB::beginTransaction();
- $segment = (array)$segment;
- unset($segment['id']);
- $segment['segment_number'] += 1;
- $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
- // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
- $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
- // 更新其他分镜序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- // 复制分镜
- $id = DB::table('mp_episode_segments')->insertGetId($segment);
- if (!$id) {
- Utils::throwError('20003:复制分镜失败');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function moveSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $target_segment_id = getProp($data, 'target_segment_id');
-
- // 获取源分镜信息
- $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择分镜');
-
- // 获取目标分镜信息
- $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
- if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $episode_number = getProp($source_segment, 'episode_number');
- $source_segment_number = getProp($source_segment, 'segment_number');
- $target_segment_number = getProp($target_segment, 'segment_number');
-
- // 验证源分镜和目标分镜必须属于同一个动漫的同一集
- $target_anime_id = getProp($target_segment, 'anime_id');
- $target_episode_number = getProp($target_segment, 'episode_number');
-
- if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
- Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
- }
-
- // 如果源分镜和目标分镜相同,无需移动
- if ($source_segment_number == $target_segment_number) {
- return true;
- }
- try {
- DB::beginTransaction();
- if ($source_segment_number < $target_segment_number) {
- // 向后移动:源分镜移动到目标分镜之后
- // 1. 将源分镜和目标分镜之间的所有分镜序号减1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('segment_number', '>', $source_segment_number)
- ->where('segment_number', '<=', $target_segment_number)
- ->decrement('segment_number');
-
- // 2. 将源分镜移动到目标分镜之后
- $new_segment_number = $target_segment_number;
-
- } else {
- // 向前移动:源分镜移动到目标分镜之后
- // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('segment_number', '>', $target_segment_number)
- ->where('segment_number', '<', $source_segment_number)
- ->increment('segment_number');
-
- // 2. 将源分镜移动到目标分镜之后
- $new_segment_number = $target_segment_number + 1;
- }
-
- // 3. 更新源分镜的序号
- $update_result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update([
- 'segment_number' => $new_segment_number,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$update_result) {
- Utils::throwError('20003:更新分镜序号失败');
- }
- DB::commit();
- return true;
-
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- public function delSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:请选择分镜');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- try {
- DB::beginTransaction();
- // 删除分镜
- $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
- if (!$boolen) {
- Utils::throwError('20003:删除分镜失败');
- }
- // 更新其他分镜序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return true;
- }
- public function applySegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $url = getProp($data, 'url');
- if (!$segment_id) Utils::throwError('20003:请选择分镜');
- if (!$url) Utils::throwError('20003:URL不能为空');
-
- // 获取URL的文件扩展名
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- // 定义图片和视频的扩展名
- $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
- $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
-
- // 判断是图片还是视频
- $updateData = ['updated_at' => date('Y-m-d H:i:s')];
-
- if (in_array($extension, $imageExtensions)) {
- // 图片类型
- $updateData['img_url'] = $url;
- $updateData['current_type'] = 1;
- } elseif (in_array($extension, $videoExtensions)) {
- // 视频类型
- $updateData['video_url'] = $url;
- $updateData['current_type'] = 2;
- } else {
- Utils::throwError('20003:不支持的文件类型');
- }
-
- // 更新分镜表
- $result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($updateData);
-
- if (!$result) {
- Utils::throwError('20003:更新分镜失败');
- }
-
- return true;
- }
- public function segmentHistory($data) {
- $segment_id = getProp($data, 'segment_id');
- // 获取历史图片
- $pics = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $pics = array_merge($pics, json_decode($result_url, true));
- }else {
- $pics[] = $result_url;
- }
- }
-
- // 获取历史视频
- $videos = [];
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $videos = array_merge($videos, json_decode($result_url, true));
- }else {
- $videos[] = $result_url;
- }
- }
- return compact('pics', 'videos');
- }
- public function addAct($data) {
- $prev_act_id = getProp($data, 'prev_act_id');
- $act_title = getProp($data, 'act_title', '');
- $act_content = getProp($data, 'act_content', '');
- $act_duration = getProp($data, 'act_duration', 5);
- $video_url = getProp($data, 'video_url');
-
- // 根据prev_act_id获取记录
- $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
- if (!$prev_segment) Utils::throwError('20003:该片段不存在');
-
- $anime_id = getProp($prev_segment, 'anime_id');
- $episode_id = getProp($prev_segment, 'episode_id');
- $episode_number = getProp($prev_segment, 'episode_number');
- $prev_act_number = getProp($prev_segment, 'act_number');
-
- // 获取新的act_number
- $new_act_number = $prev_act_number + 1;
- try {
- DB::beginTransaction();
-
- // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $prev_act_number)
- ->increment('act_number');
- // 插入新片段记录
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => $new_act_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($act_title) {
- $insert_data['act_title'] = $act_title;
- }
- if ($act_content) {
- $insert_data['act_content'] = $act_content;
- }
- if ($act_duration) {
- $insert_data['act_duration'] = $act_duration;
- }
- if ($video_url) {
- $insert_data['origin_video_url'] = $video_url;
- $insert_data['current_type'] = 2;
- $compressed_video_url = compressVideo($video_url);
- $insert_data['video_url'] = $compressed_video_url ?: $video_url;
- }
- $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
- if (!$id) {
- Utils::throwError('20003:新增片段失败!');
- }
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
-
- $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();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function editAct($data) {
- $act_id = getProp($data, 'act_id');
- $act_content = getProp($data, 'act_content');
- $act_duration = getProp($data, 'act_duration');
- $act_title = getProp($data, 'act_title');
- $image_url = getProp($data, 'image_url');
- $video_url = getProp($data, 'video_url');
- // 参数验证
- if (!$act_id) Utils::throwError('20003:请提供片段ID');
- // 验证片段是否存在(全能模式下每个act只有一条记录)
- $segment = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->first();
-
- if (!$segment) Utils::throwError('20003:该片段不存在');
- try {
- DB::beginTransaction();
-
- // 准备更新数据
- $update_data = [
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 更新act相关字段
- if (!empty($act_content)) {
- $update_data['act_content'] = $act_content;
- }
-
- if (!empty($act_duration)) {
- $update_data['act_duration'] = $act_duration;
- }
-
- if (!empty($act_title)) {
- $update_data['act_title'] = $act_title;
- }
- // 处理图片上传
- if ($image_url) {
- $update_data['img_url'] = $image_url;
- $update_data['current_type'] = 1;
- // 同时写入一个图片生成任务记录
- if ($act_id) {
- $pic_task = [
- 'alias_act_id' => $act_id,
- 'ref_img_url' => json_encode([]),
- 'status' => 'success',
- 'result_url' => json_encode([$image_url], 256),
- 'model' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_pic_tasks')->insert($pic_task);
- }
- }
- // 处理视频上传
- if ($video_url) {
- $update_data['origin_video_url'] = $video_url;
- $compressed_video_url = compressVideo($video_url);
- $update_data['current_type'] = 2;
- $update_data['video_url'] = $compressed_video_url ?: $video_url;
- // 同时写入一个视频生成任务记录
- if ($act_id) {
- $video_task = [
- 'alias_act_id' => $act_id,
- 'status' => 'success',
- 'result_url' => $update_data['origin_video_url'],
- 'compressed_url' => $update_data['video_url'],
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_video_tasks')->insert($video_task);
- }
- }
- // 更新片段信息
- $result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update($update_data);
- if ($result === false) {
- Utils::throwError('20003:更新片段失败');
- }
- DB::commit();
- return true;
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('更新片段失败', [
- 'act_id' => $act_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
- }
- }
- public function copyAct($data) {
- $act_id = getProp($data, 'act_id');
-
- // 根据act_id获取记录(全能模式下每个act只有一条记录)
- $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择片段');
- $video_url = getProp($source_segment, 'video_url');
- if (!$video_url) Utils::throwError('20003:该片段没有视频无法复制');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $episode_number = getProp($source_segment, 'episode_number');
- $act_number = getProp($source_segment, 'act_number');
- try {
- DB::beginTransaction();
- // 新act的编号
- $new_act_number = $act_number + 1;
-
- // 更新后续所有act的act_number
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $act_number)
- ->increment('act_number');
- // 复制该片段记录
- $segment_data = (array)$source_segment;
- unset($segment_data['id']);
- $segment_data['act_number'] = $new_act_number;
- $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
- $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
- if (!$id) {
- Utils::throwError('20003:复制片段失败');
- }
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- // 返回新复制的记录
- $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,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
- $new_segment = $new_segment ? (array)$new_segment : [];
- $new_segment['act_id'] = $id;
- return $new_segment;
- }
- public function moveAct($data) {
- $act_id = getProp($data, 'act_id');
- $target_act_id = getProp($data, 'target_act_id');
-
- // 获取源片段信息
- $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择片段');
-
- // 获取目标片段信息
- $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
- if (!$target_segment) Utils::throwError('20003:目标片段不存在');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $source_act_number = getProp($source_segment, 'act_number');
- $target_act_number = getProp($target_segment, 'act_number');
-
- // 验证源片段和目标片段必须属于同一个动漫的同一集
- $target_anime_id = getProp($target_segment, 'anime_id');
- $target_episode_id = getProp($target_segment, 'episode_id');
-
- if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
- Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
- }
-
- // 如果源片段和目标片段相同,无需移动
- if ($source_act_number == $target_act_number) {
- return true;
- }
- try {
- DB::beginTransaction();
- if ($source_act_number < $target_act_number) {
- // 向后移动:源片段移动到目标片段之后
- // 1. 将源片段和目标片段之间的所有片段编号减1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $source_act_number)
- ->where('act_number', '<=', $target_act_number)
- ->decrement('act_number');
-
- // 2. 将源片段移动到目标片段之后
- $new_act_number = $target_act_number;
-
- } else {
- // 向前移动:源片段移动到目标片段之后
- // 1. 将目标片段之后到源片段之前的所有片段编号加1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $target_act_number)
- ->where('act_number', '<', $source_act_number)
- ->increment('act_number');
-
- // 2. 将源片段移动到目标片段之后
- $new_act_number = $target_act_number + 1;
- }
-
- // 3. 更新源片段的编号
- $update_result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update([
- 'act_number' => $new_act_number,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$update_result) {
- Utils::throwError('20003:更新片段编号失败');
- }
- DB::commit();
- return true;
-
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- public function delAct($data) {
- $act_id = getProp($data, 'act_id');
-
- // 根据act_id获取记录(全能模式下每个act只有一条记录)
- $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$segment) Utils::throwError('20003:请选择片段');
-
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $act_number = getProp($segment, 'act_number');
- try {
- DB::beginTransaction();
- // 删除该片段记录
- $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
- if (!$deleted) {
- Utils::throwError('20003:删除片段失败');
- }
- // 更新后续act的编号
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $act_number)
- ->decrement('act_number');
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- return true;
- }
- public function applyAct($data) {
- $act_id = getProp($data, 'act_id');
- $url = getProp($data, 'url');
-
- if (!$act_id) Utils::throwError('20003:请选择片段');
- if (!$url) Utils::throwError('20003:URL不能为空');
-
- // 获取URL的文件扩展名
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- // 定义图片和视频的扩展名
- $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
- $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
-
- // 判断是图片还是视频
- $updateData = ['updated_at' => date('Y-m-d H:i:s')];
-
- if (in_array($extension, $imageExtensions)) {
- // 图片类型
- $updateData['img_url'] = $url;
- $updateData['current_type'] = 1;
- } elseif (in_array($extension, $videoExtensions)) {
- // 视频类型
- $updateData['video_url'] = $url;
- $updateData['current_type'] = 2;
- } else {
- Utils::throwError('20003:不支持的文件类型');
- }
-
- // 更新片段记录(全能模式下每个act只有一条记录)
- $result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update($updateData);
-
- if (!$result) {
- Utils::throwError('20003:更新片段失败');
- }
-
- return true;
- }
- public function actChatHistory($data) {
- $act_id = getProp($data, 'act_id');
- if (!$act_id) Utils::throwError('20003:请选择片段!');
- $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
-
- $chat = $query->orderBy('id')->get()->map(function ($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at']);
- if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
- else $value['reference_images'] = [];
- return $value;
- })->toArray();
- // 获取历史图片
- $url = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
-
- // 获取历史视频
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
- // 获取资产库
- $products = [];
-
- // 通过act_id查询片段信息获取episode_id
- $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if ($segment) {
- $episode_id = getProp($segment, 'episode_id');
-
- // 查询剧集信息获取roles、scenes和extra_products
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if ($episode) {
- $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 先合并roles和scenes
- // 处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (isset($product['role'])) {
- $product['product_name'] = $product['role'];
- unset($product['role']);
- }
- $product['product'] = 1; // 标记类型为角色
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // 处理场景数组
- foreach ($scenes as $scene) {
- $product = $scene;
- // 将scene字段重命名为product_name
- if (isset($product['scene'])) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- }
- $product['product'] = 2; // 标记类型为场景
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // extra_products优先级更高,直接覆盖同名的roles和scenes
- foreach ($extra_products as $extra_product) {
- $product_name = getProp($extra_product, 'product_name');
- if ($product_name) {
- $products[$product_name] = $extra_product; // 覆盖同名数据
- }
- }
-
- // 重新索引数组(去除key)
- $products = array_values($products);
- }
- }
- // 获取执行中的任务
- $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) {
- $value = (array)$value;
- if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
- else $value['ref_image_url'] = [];
- $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
- // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
- if (!empty($value['prompt'])) {
- $prompt = $value['prompt'];
-
- // 查找第一个【镜头】的位置
- if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
- // 从【镜头】开始截取
- $prompt = substr($prompt, $matches[0][1]);
- }
-
- // 去除所有<图片X>格式的标记(X可以是任意数字)
- $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
-
- $value['prompt'] = $prompt;
- }
-
- return $value;
- })->toArray();
- return compact('chat', 'url', 'products', 'tasks');
- }
- public function applyAudioData($data) {
- $segment_id = getProp($data, 'segment_id');
- $global_data = getProp($data, 'global_data');
- $segment_data = getProp($data, 'segment_data');
- if (!$segment_id) Utils::throwError('20003:请选择分镜');
- $global_data = is_array($global_data) ? $global_data : [];
- $segment_data = is_array($segment_data) ? $segment_data : [];
-
- // dialogue只能在segment_data中,如果在global_data中则移到segment_data
- $dialogue_item = null;
- foreach ($global_data as $key => $item) {
- if (trim((string)getProp($item, 'name')) === 'dialogue') {
- $dialogue_item = $item;
- unset($global_data[$key]);
- break;
- }
- }
- if ($dialogue_item) {
- $segment_data[] = $dialogue_item;
- }
- // 特殊参数: audio_url,audio_duration,subtitle_info
- // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
- // 如果不是全部存在,则仍需创建音频任务
- $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
- $special_update_data = [];
- $has_all_special_params = false;
-
- // 从segment_data中提取特殊参数
- $filtered_segment_data = [];
- foreach ($segment_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (in_array($field_name, $special_fields)) {
- $special_update_data[$field_name] = getProp($item, 'value');
- } else {
- // 非特殊参数保留,继续后续处理
- $filtered_segment_data[] = $item;
- }
- }
-
- // 检查是否三个特殊参数都存在
- if (count($special_update_data) === 3 &&
- isset($special_update_data['audio_url']) &&
- isset($special_update_data['audio_duration']) &&
- isset($special_update_data['subtitle_info'])) {
- $has_all_special_params = true;
-
- // 立即更新到当前分镜
- $special_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($special_update_data);
- }
-
- // 使用过滤后的segment_data继续处理其他参数
- $segment_data = $filtered_segment_data;
-
- $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
- $global_update_data = [];
- $segment_update_data = [];
- $global_voice_type = '';
- $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$target_segment) Utils::throwError('20003:分镜不存在');
- $episode_id = getProp($target_segment, 'episode_id');
- $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:分集不存在');
- foreach ($global_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (!$field_name || !in_array($field_name, $allow_fields)) {
- continue;
- }
- $global_update_data[$field_name] = getProp($item, 'value');
- if ($field_name === 'voice_type') {
- $global_voice_type = trim((string)getProp($item, 'value'));
- }
- }
- foreach ($segment_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (!$field_name || !in_array($field_name, $allow_fields)) {
- continue;
- }
- $segment_update_data[$field_name] = getProp($item, 'value');
- }
- if ($global_voice_type) {
- $timbre_info = DB::table('mp_timbres')
- ->where('timbre_type', $global_voice_type)
- ->select('audio_url', 'timbre_name')
- ->first();
- if ($timbre_info) {
- $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
- $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
- }
- }
- try {
- DB::beginTransaction();
-
- // 收集需要创建音频合成任务的segment_id和对应的分镜数据
- $segment_ids_to_create_task = [];
- $segments_data = [];
- // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
- if (!empty($global_update_data)) {
- // 如果角色不存在,则只更新当前分镜
- if (!$target_voice_actor) {
- // 只处理当前分镜
- $affected_segments = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->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')
- ->get();
- } else {
- // 获取该角色的所有分镜
- $affected_segments = DB::table('mp_episode_segments')
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_voice_actor)
- ->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')
- ->get();
- }
-
- foreach ($affected_segments as $seg) {
- $seg = (array)$seg;
- $sid = getProp($seg, 'segment_id');
-
- // 检查参数是否发生变化
- $has_changed = false;
- foreach ($global_update_data as $field => $new_value) {
- $old_value = getProp($seg, $field);
- if ($old_value != $new_value) {
- $has_changed = true;
- break;
- }
- }
-
- if ($has_changed) {
- $segment_ids_to_create_task[] = $sid;
- $segments_data[$sid] = $seg;
- }
- }
-
- // 只有在有变化的分镜时才更新
- if (!empty($segment_ids_to_create_task)) {
- $global_segment_update_data = $global_update_data;
- $global_segment_update_data['audio_url'] = ''; // 清空音频URL
- $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_voice_actor)
- ->whereIn('segment_id', $segment_ids_to_create_task)
- ->update($global_segment_update_data);
- }
- if ($global_voice_type) {
- $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
- $episode_roles = is_array($episode_roles) ? $episode_roles : [];
- $roles_updated = false;
- foreach ($episode_roles as &$role) {
- // 通过 role 字段匹配角色名,而不是 voice_name
- if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
- continue;
- }
- $role['voice_type'] = $global_voice_type;
- $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
- $role['voice_name'] = getProp($global_update_data, 'voice_name');
- $roles_updated = true;
- }
- unset($role);
- if ($roles_updated) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($episode_roles, 256),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
- }
- }
- }
- // 如果有单个分镜更新,检查是否有变化
- if (!empty($segment_update_data)) {
- // 获取当前分镜数据
- $current_segment = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->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')
- ->first();
-
- if ($current_segment) {
- $current_segment = (array)$current_segment;
-
- // 检查参数是否发生变化
- $has_changed = false;
- foreach ($segment_update_data as $field => $new_value) {
- $old_value = getProp($current_segment, $field);
- if ($old_value != $new_value) {
- $has_changed = true;
- break;
- }
- }
-
- if ($has_changed) {
- // 如果该分镜还未在列表中,添加进去
- if (!in_array($segment_id, $segment_ids_to_create_task)) {
- $segment_ids_to_create_task[] = $segment_id;
- $segments_data[$segment_id] = $current_segment;
- }
-
- // 更新分镜数据并清空音频URL
- $segment_update_data['audio_url'] = '';
- $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
- }
- }
- }
- // 为所有有变化的分镜创建音频合成任务
- // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
- if (!empty($segment_ids_to_create_task)) {
- foreach ($segment_ids_to_create_task as $sid) {
- // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
- if ($sid === $segment_id && $has_all_special_params) {
- continue;
- }
-
- // 重新获取更新后的分镜数据
- $updated_segment = DB::table('mp_episode_segments')
- ->where('segment_id', $sid)
- ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
- ->first();
-
- if (!$updated_segment) continue;
-
- $updated_segment = (array)$updated_segment;
-
- // 检查dialogue是否为空
- $dialogue = getProp($updated_segment, 'dialogue');
- if (empty($dialogue)) {
- // dialogue为空时,直接写入默认音频信息
- DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
- 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
- 'audio_duration' => 2.0,
- 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- continue;
- }
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($updated_segment, 'voice_actor'),
- 'voice_type' => getProp($updated_segment, 'voice_type'),
- 'voice_name' => getProp($updated_segment, 'voice_name'),
- 'emotion' => getProp($updated_segment, 'emotion'),
- 'emotion_type' => getProp($updated_segment, 'emotion_type'),
- 'gender' => getProp($updated_segment, 'gender'),
- 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
- 'pitch' => getProp($updated_segment, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $sid,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
-
- if (!$dubTaskId) {
- dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
- continue;
- }
- // 将任务ID添加到Redis列表中
- Redis::lpush('dub_video_task_queue', $dubTaskId);
-
- // 请求远程服务器执行生成
- try {
- sleep(1);
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
-
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- }
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- return true;
- }
- public function episodePicsInfo($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- // 参数验证
- if (!$anime_id && !$episode_id) {
- Utils::throwError('20003:请提供动漫ID或分集ID');
- }
- // 根据参数获取数据源
- if ($episode_id) {
- // 从剧集表获取
- $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$source) Utils::throwError('20003:该剧集不存在');
- $table_name = 'mp_anime_episodes';
- $id_field = 'id';
- $id_value = $episode_id;
-
- // 获取剧集的anime_id用于继承全局数据
- $anime_id = getProp($source, 'anime_id');
- } else {
- // 从动漫表获取
- $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
- if (!$source) Utils::throwError('20003:该动漫不存在');
- $table_name = 'mp_animes';
- $id_field = 'id';
- $id_value = $anime_id;
- }
- $source = (array)$source;
- $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
-
- // 如果是分集数据,需要处理继承和任务创建逻辑
- if ($episode_id) {
- $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
- }
- // 返回生成器函数,用于 SSE 流式输出
- return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
- $startTime = time();
- $maxDuration = 600; // 10分钟超时
- $checkInterval = 3; // 每3秒检查一次
- // Redis 缓存键
- $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
-
- // 生成当前数据的哈希值用于比较
- $generateHash = function($roles, $scenes) {
- return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
- };
- // 发送初始数据
- $currentHash = $generateHash($roles, $scenes);
- Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
- echo "data: " . json_encode([
- 'type' => 'init',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'start_time' => $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- // 持续轮询任务状态
- while (time() - $startTime < $maxDuration) {
- $hasProcessing = false;
- $updated = false;
- // 检查角色任务状态
- foreach ($roles as $index => &$role) {
- $task_id = getProp($role, 'task_id');
- $task_status = getProp($role, 'task_status');
- $existing_url = getProp($role, 'url');
- // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
- if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
- $hasProcessing = ($task_status === 'processing');
-
- // 查询任务状态
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('id', 'status', 'result_url', 'error_message')
- ->first();
- if ($task) {
- $task = (array)$task;
- $status = getProp($task, 'status');
- // 如果任务完成或失败
- if (in_array($status, ['success', 'failed'])) {
- $role['task_status'] = $status;
-
- if ($status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $role['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 检查场景任务状态
- foreach ($scenes as $index => &$scene) {
- $task_id = getProp($scene, 'task_id');
- $task_status = getProp($scene, 'task_status');
- $existing_url = getProp($scene, 'url');
- // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
- if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
- $hasProcessing = ($task_status === 'processing');
-
- // 查询任务状态
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('id', 'status', 'result_url', 'error_message')
- ->first();
- if ($task) {
- $task = (array)$task;
- $status = getProp($task, 'status');
- // 如果任务完成或失败
- if (in_array($status, ['success', 'failed'])) {
- $scene['task_status'] = $status;
-
- if ($status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $scene['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 如果有更新,检查数据是否真的变化了(通过哈希对比)
- if ($updated) {
- $newHash = $generateHash($roles, $scenes);
- $cachedHash = Redis::get($cacheKey);
- // 只有当数据真正变化时才更新数据库和发送事件
- if ($newHash !== $cachedHash) {
- try {
- // 更新数据库
- DB::table($table_name)->where($id_field, $id_value)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 更新缓存
- Redis::setex($cacheKey, 600, $newHash);
- // 发送更新事件
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- } catch (\Exception $e) {
- dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
- }
- } else {
- // 即使哈希相同,如果有URL更新也要发送事件
- $hasUrlUpdate = false;
- foreach ($roles as $role) {
- if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
- $hasUrlUpdate = true;
- break;
- }
- }
- if (!$hasUrlUpdate) {
- foreach ($scenes as $scene) {
- if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
- $hasUrlUpdate = true;
- break;
- }
- }
- }
-
- if ($hasUrlUpdate) {
- // 强制更新数据库和发送事件
- try {
- DB::table($table_name)->where($id_field, $id_value)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 更新缓存
- Redis::setex($cacheKey, 600, $newHash);
- // 发送更新事件
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- } catch (\Exception $e) {
- dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
- }
- }
- }
- }
- // 如果所有任务都已完成,发送完成事件并退出
- if (!$hasProcessing) {
- // 查询数据库中的最终数据,确保返回最新的完整数据
- try {
- $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
- if ($finalSource) {
- $finalSource = (array)$finalSource;
- $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
- $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'total_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- break;
- }
- // 等待下次检查
- sleep($checkInterval);
- }
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- // 查询数据库中的最终数据,即使超时也要返回最新数据
- try {
- $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
- if ($finalSource) {
- $finalSource = (array)$finalSource;
- $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
- $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'timeout',
- 'message' => '轮询超时,请刷新页面查看最新状态',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- }
- };
- }
- public function clipSegmentVideo($data) {
- $segment_id = getProp($data, 'segment_id');
- $video_time_point_start = getProp($data, 'video_time_point_start');
- $video_time_point_end = getProp($data, 'video_time_point_end');
- if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
- Utils::throwError('20003:参数异常');
- }
- if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
- Utils::throwError('20003:该分镜没有视频,无法裁剪');
- }
- $video_duration = $video_time_point_end - $video_time_point_start;
- if (!$video_duration < 0) Utils::throwError('20003:参数异常');
- return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'video_duration' => $video_duration,
- 'video_time_point_start' => $video_time_point_start,
- 'video_time_point_end' => $video_time_point_end,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 轮训获取图片任务结果
- private function loopGetPicTaskResult($task_id) {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- if (!$task) {
- return '';
- }
- // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
- $model = getProp($task, 'model');
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 轮询查询任务状态(火山API和即梦AI都需要轮询)
- $start_count = 0;
- $img_url = '';
- while ($start_count <= 60) { // 循环20次请求,每3s一次
- sleep(3);
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- // 如果任务已经完成,直接返回结果
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
- return is_array($result_urls) ? $result_urls[0] : $task->result_url;
- }
-
- // 如果任务已失败,返回空
- if ($task->status === 'failed') {
- return '';
- }
- if ($isSyncModel) continue;
-
- // 查询任务状态
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- // 同步调整分镜图片状态和结果
- if (getProp($task, 'alias_segment_id')) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'img_url' => $statusInfo['result_url'][0],
- 'pic_task_status' => '已完成',
- ]);
- }
- $img_url = $statusInfo['result_url'][0];
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- if (getProp($task, 'alias_segment_id')) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'pic_task_status' => '失败',
- ]);
- }
- break;
- }
- $start_count++;
- }
- return $img_url;
- }
- /**
- * 从分镜内容中提取涉及的角色
- */
- private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
- $found_characters = [];
-
- foreach ($available_characters as $character) {
- // 检查角色名称是否在分镜内容中出现
- if (strpos($segment_content, $character) !== false) {
- $found_characters[] = $character;
- }
- }
- if (!$found_characters) {
- foreach ($roles as $character) {
- // 检查角色名称是否在分镜内容中出现
- if (strpos($segment_content, $character) !== false) {
- $found_characters[] = $character;
- }
- }
- }
-
- return array_unique($found_characters);
- }
- // 从分镜剧本中提取关键字段
- private function handleSegmentContent(&$data) {
- $segmentContent = getProp($data, 'segment_content');
- // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
- $segmentData = [
- 'description' => '',
- 'composition' => '',
- 'camera_movement' => '',
- 'voice_actor' => '',
- 'dialogue' => '',
- 'frame_type' => '',
- 'scene' => '', // 场景
- 'characters' => '', // 出镜角色
- 'tail_frame' => '', // 尾帧描述
- 'emotion' => '中性', // 情感
- 'gender' => '0', // 性别(0未知,1男,2女)
- 'speed_ratio' => 0, // 语速
- 'loudness_ratio' => 0, // 音量
- 'emotion_scale' => 4, // 情感强度
- 'pitch' => 0, // 音调
- ];
-
- // 用于存储需要从 segment_content 中移除的匹配项
- $replaceEmptyArr = [];
-
- // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
- if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
- $segmentData['description'] = trim($descMatch[1]);
- $data['description'] = trim($descMatch[1]);
- }
- if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
- $segmentData['composition'] = trim($compMatch[1]);
- $data['composition'] = trim($compMatch[1]);
- }
- if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
- $segmentData['camera_movement'] = trim($cameraMatch[1]);
- $data['camera_movement'] = trim($cameraMatch[1]);
- }
- if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
- $segmentData['voice_actor'] = trim($voiceMatch[1]);
- $data['voice_actor'] = trim($voiceMatch[1]);
- }
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $segmentData['dialogue'] = trim($dialogueMatch[1]);
- $data['dialogue'] = trim($dialogueMatch[1]);
- }
- if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
- $segmentData['frame_type'] = trim($frameMatch[1]);
- $data['frame_type'] = trim($frameMatch[1]);
- }
- // 场景字段
- if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
- $segmentData['scene'] = trim($sceneMatch[1]);
- $data['scene'] = trim($sceneMatch[1]);
- }
- // 出镜角色字段
- if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
- $segmentData['characters'] = trim($charactersMatch[1]);
- $data['characters'] = trim($charactersMatch[1]);
- }
- // 尾帧描述字段
- if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
- $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
- $data['tail_frame'] = trim($tailFrameMatch[1]);
- }
-
- // 情感字段
- if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
- $replaceEmptyArr[] = trim($emotionMatch[0]);
- $segmentData['emotion'] = trim($emotionMatch[1]);
- $data['emotion'] = trim($emotionMatch[1]);
- }
-
- // 性别字段
- if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
- $replaceEmptyArr[] = trim($genderMatch[0]);
- $genderStr = trim($genderMatch[1]);
- if (strpos($genderStr, '男') !== false || $genderStr === '1') {
- $segmentData['gender'] = '1';
- $data['gender'] = '1';
- } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
- $segmentData['gender'] = '2';
- $data['gender'] = '2';
- } else {
- $segmentData['gender'] = '0';
- $data['gender'] = '0';
- }
- }
-
- // 语速字段
- if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
- $replaceEmptyArr[] = trim($speedMatch[0]);
- $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
- $data['speed_ratio'] = (float)trim($speedMatch[1]);
- }
-
- // 音量字段
- if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
- $replaceEmptyArr[] = trim($loudnessMatch[0]);
- $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- }
-
- // 情感强度字段
- if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
- $replaceEmptyArr[] = trim($scaleMatch[0]);
- $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
- $data['emotion_scale'] = (int)trim($scaleMatch[1]);
- }
-
- // 音调字段
- if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
- $replaceEmptyArr[] = trim($pitchMatch[0]);
- $segmentData['pitch'] = (int)trim($pitchMatch[1]);
- $data['pitch'] = (int)trim($pitchMatch[1]);
- }
-
- // 从 segment_content 中移除已提取的配音参数字段
- if (!empty($replaceEmptyArr)) {
- $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
- }
-
- // 如果有配音角色,查询音色信息并验证情感
- $voice_actor = $segmentData['voice_actor'];
- if (!empty($voice_actor) && $voice_actor !== '旁白') {
- // 从当前分镜所属的剧集或动漫中查找角色音色信息
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
-
- // 优先从剧集的角色列表中查找
- $roles = [];
- if ($episode_id) {
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if ($episode && getProp($episode, 'roles')) {
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- }
- }
-
- // 如果剧集中没有,从动漫的角色列表中查找
- if (empty($roles) && $anime_id) {
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if ($anime && getProp($anime, 'roles')) {
- $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
- }
- }
-
- // 查找匹配的角色音色信息
- $timbre_info = null;
- foreach ($roles as $role) {
- if (getProp($role, 'role') === $voice_actor) {
- $timbre_info = $role;
- break;
- }
- }
-
- // 如果找到音色信息,添加到数据中
- if ($timbre_info) {
- $voice_type = getProp($timbre_info, 'voice_type');
- $voice_name = getProp($timbre_info, 'voice_name');
- $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
-
- if ($voice_type) {
- $data['voice_type'] = $voice_type;
- $segmentData['voice_type'] = $voice_type;
- }
- if ($voice_name) {
- $data['voice_name'] = $voice_name;
- $segmentData['voice_name'] = $voice_name;
- }
- if ($voice_audio_url) {
- $data['voice_audio_url'] = $voice_audio_url;
- $segmentData['voice_audio_url'] = $voice_audio_url;
- }
-
- // 验证情感是否在音色支持的情感列表中
- if ($voice_type) {
- $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
- if ($timbre_emotion) {
- $timbre_emotion = explode(',', $timbre_emotion);
- } else {
- $timbre_emotion = [];
- }
- $emotion = getProp($segmentData, 'emotion', '中性');
- if (!in_array($emotion, $timbre_emotion)) {
- $emotion = '中性';
- }
- $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
- $emotion_list = array_flip($emotion_list);
- $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
- $data['emotion_type'] = $emotion_type;
- $segmentData['emotion_type'] = $emotion_type;
- }
- }
- }
- return $segmentData;
- }
- public function createSegmentVideoTask($data) {
- $segment_id = getProp($data, 'segment_id');
- $tail_frame = getProp($data, 'tail_frame');
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- $generate_audio = getProp($data, 'generate_audio', 0);
-
- if (!$segment_id) {
- Utils::throwError('1002:分镜ID不能为空');
- }
-
- // 获取分镜信息
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) {
- Utils::throwError('20003:分镜不存在');
- }
-
- $segment = (array)$segment;
- $episode_id = getProp($segment, 'episode_id');
- $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
- if (!$ratio) $ratio = '9:16';
-
- // 获取分镜内容
- $segmentContent = getProp($segment, 'segment_content', '');
-
- // 检查 $segmentContent 中是否已有尾帧描述
- $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
-
- // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
- $finalTailFrame = '';
- if ($tail_frame) {
- // 用户输入了尾帧描述,优先使用
- $finalTailFrame = $tail_frame;
-
- // 如果 segmentContent 中已有尾帧描述,需要替换
- if ($contentHasTailFrame) {
- $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
- }
- } elseif ($contentHasTailFrame) {
- // segmentContent 中有尾帧描述,使用它
- $finalTailFrame = trim($contentTailFrameMatch[1]);
- } else {
- // 两者都没有,使用分镜表中的尾帧描述
- $finalTailFrame = getProp($segment, 'tail_frame', '');
- }
-
- // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
- $hasDialogue = false;
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $dialogue = trim($dialogueMatch[1]);
-
- // 如果台词不为空且不是"无"
- if (!empty($dialogue) && $dialogue !== '无') {
- // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
- $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
- if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
- $hasDialogue = true;
- }
- $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
- $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
- // 句首或句尾没有中文双引号,则分别添加中文左右双引号
- if (!preg_match('/^[“]/', $dialogue)) {
- $dialogue = '“' . $dialogue;
- }
- if (!preg_match('/[”]$/', $dialogue)) {
- $dialogue .= '”';
- }
-
- // 将修改后的台词替换回 $segmentContent
- $originalDialogue = $dialogueMatch[1];
- $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
- }
- }
- // 构建完整的提示词
- $fullPrompt = $segmentContent;
- if ($finalTailFrame && !$contentHasTailFrame) {
- // 只有当 segmentContent 中没有尾帧描述时才追加
- $fullPrompt .= "\n尾帧描述:$finalTailFrame";
- }
-
- // 去除多余的换行符(将连续多个换行符替换为单个换行符)
- $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
- $fullPrompt = trim($fullPrompt);
- // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
- $current_generate_audio = $hasDialogue ? $generate_audio : 0;
-
- // 智能选择视频时长
- // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
- $videoDuration = -1;
-
- // 处理视频模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,从episode表获取
- $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
- $model = getProp($episode, 'video_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedance-1-5-pro-251215';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seedance-1-5-pro-251215';
- }
- // 保存到episode表
- $episode_id = getProp($segment, 'episode_id');
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => '720P',
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
-
- // 如果分镜有图片,作为首帧
- $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
- $hasVideo = !empty(getProp($segment, 'video_url'));
-
- if ($hasImage) {
- if ($first_frame_url) {
- $videoParams['first_frame_url'] = $first_frame_url;
- }else {
- $videoParams['first_frame_url'] = getProp($segment, 'img_url');
- }
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'last_frame',
- ];
- }
- }
- }
-
- // 获取配音音频URL
- $audioUrl = getProp($segment, 'audio_url');
- $audioDuration = getProp($segment, 'audio_duration');
-
- // 音频传入的前提:必须有至少一张图片或一个视频
- $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
- // dd($videoParams);
-
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧20等新模型使用统一API
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- // 'video_mode' => 'multi_image',
- // 'mode' => 'multi_image',
- 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
- ];
-
- $hasImage = false;
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
- if (isset($videoParams['tail_frame_url'])) {
- $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
- }
-
- // 只有在有图片的情况下才能添加参考音频
- if ($audioUrl) {
- // $parameters['reference_audios'] = [$audioUrl];
- }
- } else {
- // 没有图片时,记录错误日志
- logDB('anime', 'error', '智帧20模型缺少首帧图片', [
- 'segment_id' => $segment_id,
- 'model' => $model
- ]);
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } else {
- // Seedance模型(默认)
- // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
- if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- // 添加配音音频到content中
- $videoParams['content'][] = [
- 'type' => 'audio_url',
- 'audio_url' => [
- 'url' => $audioUrl,
- ],
- 'role' => 'reference_audio',
- ];
-
- // 优化提示词,增加音频相关描述
- $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
- $videoParams['prompt'] = $audioPrompt;
- $videoParams['content'][0]['text'] = $audioPrompt;
- } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
- $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
- }
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'generate_audio' => $generate_audio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'segment_id' => $segment_id,
- 'video_duration' => $videoDuration
- ];
- }
-
- public function createActVideoTask($data) {
- $act_id = getProp($data, 'act_id');
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- $generate_audio = getProp($data, 'generate_audio', 1);
- $video_duration = getProp($data, 'video_duration');
- $video_resolution = getProp($data, 'video_resolution');
- $ratio = getProp($data, 'ratio');
- $products = getProp($data, 'products', []);
- $reference_images = array_unique(getProp($data, 'reference_images', []));
- if (!is_array($reference_images) || !is_array($products)) {
- Utils::throwError('20003:传入的参考图或资产格式不正确');
- }
-
- if (!$act_id) {
- Utils::throwError('1002:片段ID不能为空');
- }
-
- // 获取片段信息
- $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$act) {
- Utils::throwError('20003:片段不存在');
- }
-
- $act = (array)$act;
- $episode_id = getProp($act, 'episode_id');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
- if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
- // 将资产中新出现的资产放到extra_products中
- // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
- if (!empty($products) && $episode) {
- // 获取剧集中的角色和场景列表
- $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 构建角色名称列表
- $role_names = array_column($roles, 'role');
- // 构建场景名称列表
- $scene_names = array_column($scenes, 'scene');
-
- // 遍历传入的products
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
-
- // 如果product_name不在roles和scenes中
- if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
- // 查找是否在extra_products中存在同名的
- $found = false;
- foreach ($extra_products as $key => $extra_product) {
- if (getProp($extra_product, 'product_name') === $product_name) {
- // 有同名的则覆盖
- $extra_products[$key] = $product;
- $found = true;
- break;
- }
- }
-
- // 没有则新增
- if (!$found) {
- $extra_products[] = $product;
- }
- }
- }
-
- if ($extra_products) {
- // 保存到数据库
- DB::table('mp_anime_episodes')
- ->where('id', $episode_id)
- ->update([
- 'extra_products' => json_encode($extra_products, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- }
-
- // 获取分镜内容
- $actContent = getProp($act, 'act_show_content', '');
- // 音效同出(默认使用)
- $current_generate_audio = $generate_audio ? 1 : 0;
- // 构建完整的提示词
- $processResult = $this->processActContentWithProducts($actContent, $products);
- $fullPrompt = $processResult['content'];
- $reference_images = array_merge($processResult['reference_images'], $reference_images);
-
- $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
-
- // 处理视频模型
- $model = getProp($data, 'model');
- if (!$model) {
- $model = getProp($episode, 'video_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'zhizhen-20-mini';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'zhizhen-20-mini';
- }
- // 保存到episode表
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_act_id' => $act_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => $video_resolution,
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
-
- // 如果分镜有图片,作为首帧
- $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
- $hasVideo = !empty(getProp($act, 'video_url'));
-
- if ($hasImage) {
- if ($first_frame_url) {
- $videoParams['first_frame_url'] = $first_frame_url;
- }else {
- $videoParams['first_frame_url'] = getProp($act, 'img_url');
- }
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'last_frame',
- ];
- }
- }
- }
- // dd($videoParams);
-
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧20等新模型使用统一API
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_act_id' => $act_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- // 'video_mode' => 'multi_image',
- // 'mode' => 'multi_image',
- 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
- ];
-
- $hasImage = false;
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
- if (isset($videoParams['tail_frame_url'])) {
- $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
- }
- } else {
- // 没有图片时,记录错误日志
- logDB('anime', 'error', '智帧20模型缺少首帧图片', [
- 'act_id' => $act_id,
- 'model' => $model
- ]);
- }
- if ($reference_images) {
- // 在处理之前先保存原始reference_images到任务参数中
- $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
- $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
- $parameters['reference_images'] = $reference_images;
- $parameters['video_mode'] = 'multi_image';
- $parameters['mode'] = 'multi_image';
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } else {
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')->where('id', $act_id)->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'generate_audio' => $generate_audio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'act_id' => $act_id,
- 'video_duration' => $videoDuration
- ];
- }
- /**
- * 根据提示词内容智能计算最优视频时长
- *
- * @param string $segmentContent 分镜内容
- * @param string $tailFrame 尾帧描述
- * @return int 视频时长(2-12秒)
- */
- public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
- // 合并所有文本内容
- $fullText = trim($segmentContent . ' ' . $tailFrame);
-
- // 如果没有内容,返回默认时长
- if (empty($fullText)) {
- return 5;
- }
-
- // 计算文本长度(中文字符按2个字符计算)
- $textLength = mb_strlen($fullText, 'UTF-8');
- $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
- $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
-
- // 分析内容复杂度
- $complexityScore = $this->analyzeContentComplexity($fullText);
-
- // 基础时长计算(根据文本长度)
- $baseDuration = 3; // 默认2秒
-
- // if ($adjustedLength <= 20) {
- // $baseDuration = 3;
- // } elseif ($adjustedLength <= 40) {
- // $baseDuration = 4;
- // } elseif ($adjustedLength <= 60) {
- // $baseDuration = 5;
- // } elseif ($adjustedLength <= 80) {
- // $baseDuration = 6;
- // } elseif ($adjustedLength <= 100) {
- // $baseDuration = 7;
- // } elseif ($adjustedLength <= 120) {
- // $baseDuration = 8;
- // } else {
- // $baseDuration = 9;
- // }
-
- // 根据内容复杂度调整时长
- $finalDuration = $baseDuration + $complexityScore;
-
- // 确保时长在2-12秒范围内
- return max(4, min(12, $finalDuration));
- }
- /**
- * 分析内容复杂度,返回时长调整值
- *
- * @param string $text 文本内容
- * @return int 调整值(-2到+3)
- */
- private function analyzeContentComplexity($text) {
- $score = 0;
-
- // 动作关键词(需要更长时间展现)
- $actionKeywords = [
- '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
- '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
- '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
- ];
-
- // 静态关键词(可以用较短时间)
- $staticKeywords = [
- '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
- '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
- ];
-
- // 复杂场景关键词(需要更长时间)
- $complexSceneKeywords = [
- '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
- '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
- ];
-
- // 情感关键词(需要适中时间表现)
- $emotionKeywords = [
- '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
- '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
- ];
-
- // 检查动作关键词
- foreach ($actionKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break; // 避免重复加分
- }
- }
-
- // 检查静态关键词
- foreach ($staticKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score -= 1;
- break;
- }
- }
-
- // 检查复杂场景关键词
- foreach ($complexSceneKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break;
- }
- }
-
- // 检查情感关键词
- foreach ($emotionKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break;
- }
- }
-
- // 检查时间相关词汇
- if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
- $score += 1;
- }
-
- if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
- $score -= 1;
- }
-
- // 检查转场词汇
- if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
- $score += 1;
- }
-
- // 检查环境描述(复杂环境需要更多时间)
- if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
- $score += 1;
- }
-
- // 检查对话内容(对话需要更多时间)
- if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
- $score += 1;
- }
-
- // 限制调整范围
- return max(-1, min(4, $score));
- }
- /**
- * 创建完整视频合成任务
- *
- * @param array $data
- * @return array
- */
- public function createCompleteVideoTask($data)
- {
- $animeId = getProp($data, 'anime_id');
- $episodeId = getProp($data, 'episode_id');
- // 验证参数
- if (!$animeId || !$episodeId) {
- Utils::throwError('20003:anime_id 和 episode_id 不能为空');
- }
- // 检查是否已存在处理中的任务
- $existingTask = DB::table('mp_complete_video_tasks')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->whereIn('generate_status', ['执行中'])
- ->first();
- if ($existingTask) {
- Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
- }
- // 获取全能模式状态
- $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
- if ((int)$ace_mode === 1) {
- // 获取所有片段的配音视频,按 act_number 排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
- ->get();
-
- // 检查是否所有片段都有视频
- $missingVideos = $segments->filter(function($segment) {
- return empty($segment->video_url);
- });
- if ($missingVideos->isNotEmpty()) {
- Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
- }
- }else {
- // 获取所有分镜的配音视频,按 segment_number 排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
- ->get();
- // 检查是否所有分镜都有配音和视频
- $missingVideos = $segments->filter(function($segment) {
- return empty($segment->audio_url) || empty($segment->video_url);
- });
- if ($missingVideos->isNotEmpty()) {
- Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
- }
- }
- if ($segments->isEmpty()) {
- Utils::throwError('20003:未找到该剧集的分镜数据');
- }
- // 获取当前完整视频url
- $completeVideoUrl = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->value('complete_video_url');
- // 构建 generate_json
- $generateJson = [];
- $sequence = 1;
- foreach ($segments as $segment) {
- if ((int)$ace_mode === 1) {
- $generateJson[] = [
- 'sequence' => $sequence++,
- 'video_url' => $segment->video_url,
- 'video_time_point_start' => $segment->video_time_point_start,
- 'video_time_point_end' => $segment->video_time_point_end
- ];
- }else {
- $generateJson[] = [
- 'sequence' => $sequence++,
- 'video_url' => $segment->video_url,
- 'audio_url' => $segment->audio_url,
- 'video_time_point_start' => $segment->video_time_point_start,
- 'video_time_point_end' => $segment->video_time_point_end
- ];
- }
- }
- // 创建任务
- $now = date('Y-m-d H:i:s');
- $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'generate_json' => json_encode($generateJson, 256),
- 'generate_status' => '执行中',
- 'complete_video_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ]);
- if (!$taskId) {
- Utils::throwError('20003:创建任务失败');
- }
- // 更新剧集表的任务ID和状态
- $boolen = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_task_id' => $taskId,
- 'complete_video_task_status' => '执行中',
- 'updated_at' => $now
- ]);
- if (!$boolen) {
- Utils::throwError('20003:更新剧集表失败');
- }
- dLog('anime')->info('创建完整视频合成任务', [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson)
- ]);
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 600, 'verify' => false]);
- try {
- $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
-
- // // 更新任务状态为失败
- // DB::table('mp_complete_video_tasks')
- // ->where('id', $taskId)
- // ->update([
- // 'generate_status' => '执行失败',
- // 'error_message' => $error_msg,
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
-
- // // 同步更新剧集表状态
- // DB::table('mp_anime_episodes')
- // ->where('complete_video_task_id', $taskId)
- // ->update([
- // 'complete_video_task_status' => '执行失败',
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
-
- Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
-
- // 更新任务状态为失败
- DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->update([
- 'generate_status' => '执行失败',
- 'error_message' => $e->getMessage(),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 同步更新剧集表状态
- DB::table('mp_anime_episodes')
- ->where('complete_video_task_id', $taskId)
- ->update([
- 'complete_video_task_status' => '执行失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
- }
- // 开始轮询任务状态
- $maxAttempts = 60; // 5分钟 = 60次 * 5秒
- $pollInterval = 5; // 每5秒轮询一次
- $attempt = 0;
- dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
- while ($attempt < $maxAttempts) {
- sleep($pollInterval);
- $attempt++;
- // 查询任务状态
- $task = DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->first();
- if (!$task) {
- dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
- Utils::throwError('20003:任务不存在');
- }
- dLog('anime')->info('轮询任务状态', [
- 'task_id' => $taskId,
- 'attempt' => $attempt,
- 'status' => $task->generate_status
- ]);
- // 检查任务是否完成
- if ($task->generate_status === '执行成功') {
- // 同步更新剧集表状态
- $boolen3 = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_url' => $task->complete_video_url,
- 'complete_video_task_status' => '执行成功',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- dLog('anime')->info('视频合成任务完成', [
- 'task_id' => $taskId,
- 'video_url' => $task->complete_video_url,
- 'attempts' => $attempt
- ]);
- // 如果更新成功则远程删除之前的文件
- if ($boolen3 && $completeVideoUrl) {
- $encode_url = urlencode($completeVideoUrl);
- $client = new Client(['timeout' => 300, 'verify' => false]);
- // 根据ID通过API通知合成音频
- // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
- $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- Log::info('火山删除音频返回: '.$response);
- if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- Log::info('火山删除音频失败: '.$error_msg);
- // Utils::throwError('20003:火山删除音频失败');
- }
- }
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '执行成功',
- 'complete_video_url' => $task->complete_video_url,
- ];
- }
- // 检查任务是否失败
- if ($task->generate_status === '执行失败') {
- // 同步更新剧集表状态
- DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_task_status' => '执行失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- $errorMessage = $task->error_message ?? '未知错误';
- dLog('anime')->error('视频合成任务失败', [
- 'task_id' => $taskId,
- 'error' => $errorMessage,
- 'attempts' => $attempt
- ]);
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '执行失败',
- 'error_message' => $errorMessage
- ];
- }
- }
- // 超时处理
- dLog('anime')->warning('视频合成任务超时', [
- 'task_id' => $taskId,
- 'max_attempts' => $maxAttempts,
- 'timeout_seconds' => $maxAttempts * $pollInterval
- ]);
- // 更新任务状态为超时
- DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->update([
- 'generate_status' => '超时',
- 'error_message' => '任务执行超时(5分钟)',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '超时',
- 'error_message' => '任务执行超时,请稍后查询任务状态'
- ];
- }
- public function generateImg($data) {
- $prompt = getProp($data, 'prompt');
- $episode_id = getProp($data, 'episode_id');
- $ref_img_urls = getProp($data, 'ref_img_urls');
- $ratio = getProp($data, 'ratio', '9:16');
- $resolution = getProp($data, 'resolution', '2k');
-
- // 定义分辨率和宽高比对应的尺寸映射表
- $sizeMap = [
- '2k' => [
- '1:1' => ['width' => 2048, 'height' => 2048],
- '4:3' => ['width' => 2304, 'height' => 1728],
- '3:4' => ['width' => 1728, 'height' => 2304],
- '16:9' => ['width' => 2848, 'height' => 1600],
- '9:16' => ['width' => 1600, 'height' => 2848],
- '3:2' => ['width' => 2496, 'height' => 1664],
- '2:3' => ['width' => 1664, 'height' => 2496],
- '21:9' => ['width' => 3136, 'height' => 1344],
- ],
- '3k' => [
- '1:1' => ['width' => 3072, 'height' => 3072],
- '4:3' => ['width' => 3456, 'height' => 2592],
- '3:4' => ['width' => 2592, 'height' => 3456],
- '16:9' => ['width' => 4096, 'height' => 2304],
- '9:16' => ['width' => 2304, 'height' => 4096],
- '2:3' => ['width' => 2496, 'height' => 3744],
- '3:2' => ['width' => 3744, 'height' => 2496],
- '21:9' => ['width' => 4704, 'height' => 2016],
- ],
- '4k' => [
- '1:1' => ['width' => 4096, 'height' => 4096],
- '3:4' => ['width' => 3520, 'height' => 4704],
- '4:3' => ['width' => 4704, 'height' => 3520],
- '16:9' => ['width' => 5504, 'height' => 3040],
- '9:16' => ['width' => 3040, 'height' => 5504],
- '2:3' => ['width' => 3328, 'height' => 4992],
- '3:2' => ['width' => 4992, 'height' => 3328],
- '21:9' => ['width' => 6240, 'height' => 2656],
- ],
- ];
-
- // 参数验证
- $resolution = strtolower($resolution);
- if (!isset($sizeMap[$resolution])) {
- Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
- }
-
- if (!isset($sizeMap[$resolution][$ratio])) {
- Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
- }
-
- // 根据 ratio 和 resolution 确定宽高
- $width = $sizeMap[$resolution][$ratio]['width'];
- $height = $sizeMap[$resolution][$ratio]['height'];
-
- if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
- if (is_json($ref_img_urls)) {
- $ref_img_urls = json_decode($ref_img_urls, true);
- }else {
- $ref_img_urls = explode(',', $ref_img_urls);
- }
- }
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,从episode表获取
- if ($episode_id) {
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $model = getProp($episode, 'image_model');
- }
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- // $model = 'doubao-seedream-5-0-lite-260128';
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- // 保存到episode表
- if ($episode_id) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'image_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 参数验证
- if (!$prompt) Utils::throwError('20003:请提供提示词');
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => '',
- 'width' => $width,
- 'height' => $height
- ];
- if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建图片生成任务失败');
- }
-
- // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
- $model = getProp($task, 'model');
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
- $start_time = time();
- $timeout = 300; // 5分钟
- $img_url = '';
-
- while (time() - $start_time < $timeout) {
- sleep(3);
- // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
- if ($isSyncModel) {
- // 刷新任务状态
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
- break;
- } elseif ($task->status === 'failed') {
- Utils::throwError('20003:图片生成失败,' . ($task->error_message ?? '未知错误'));
- }
-
- // // 如果还在处理中,提示用户稍后查看
- // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
- }else {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
-
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
-
- $img_url = $statusInfo['result_url'][0];
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- dLog('anime')->error('图片生成失败,', [
- 'error' => $statusInfo['error_message'] ?? '未知错误'
- ]);
- Utils::throwError('20003:图片生成失败,' . ($statusInfo['error_message'] ?? '未知错误'));
- }
- }
- }
-
- if (empty($img_url)) {
- Utils::throwError('20003:图片生成超时,请稍后重试');
- }
-
- return $img_url;
-
- } catch (\Exception $e) {
- dLog('anime')->error('更新角色或场景失败', [
- 'error' => $e->getMessage()
- ]);
- logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
-
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 使用文生文模型解析分镜内容
- */
- private function parseSegmentContentWithAI($segment_content) {
- try {
- // 使用DeepSeek服务的公开方法解析分镜内容
- return $this->DeepSeekService->parseSegmentContent($segment_content);
- } catch (\Exception $e) {
- // 如果AI解析失败,记录日志并返回原内容
- dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
- return $segment_content;
- }
- }
- /**
- * 处理分集的角色和场景数据(继承全局数据或创建新任务)
- *
- * @param int $episode_id 分集ID
- * @param int $anime_id 动漫ID
- * @param array $roles 分集角色数组(引用传递)
- * @param array $scenes 分集场景数组(引用传递)
- * @param array $episode 分集数据
- */
- private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
- // 获取全局动漫的角色和场景数据
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) return;
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
- $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
-
- $roles_updated = false;
- $scenes_updated = false;
-
- // 处理角色
- foreach ($roles as &$role) {
- $role_name = getProp($role, 'role');
- $role_description = getProp($role, 'description');
- $role_pic_prompt = getProp($role, 'pic_prompt');
- $role_url = getProp($role, 'url');
- $role_task_id = getProp($role, 'task_id');
-
- // 如果已有URL或已有任务ID,跳过
- if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
- continue;
- }
-
- $url_inherited = false;
-
- // 尝试从全局数据中继承
- foreach ($global_roles as $global_role) {
- $global_role_name = getProp($global_role, 'role');
- $global_role_description = getProp($global_role, 'description');
- $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
- $global_role_url = getProp($global_role, 'url');
- $global_role_task_id = getProp($global_role, 'task_id');
- $global_role_task_status = getProp($global_role, 'task_status');
-
- // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
- if ($role_name === $global_role_name
- && $role_description === $global_role_description
- && $role_pic_prompt === $global_role_pic_prompt
- && !empty($global_role_url)) {
- // 继承 task_id、task_status 和 url
- $role['task_id'] = $global_role_task_id;
- $role['task_status'] = $global_role_task_status;
- $role['url'] = $global_role_url;
- $roles_updated = true;
- $url_inherited = true;
- dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
- break;
- }
- }
-
- // 如果无法继承且没有任务ID,创建新任务
- if (!$url_inherited && empty($role_task_id)) {
- try {
- $art_style = getProp($episode, 'art_style');
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
-
- // if ($art_style) {
- // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- // }
- $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
-
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $role['task_id'] = $task_id;
- $role['task_status'] = 'processing';
- $roles_updated = true;
- dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
- }
- } catch (\Exception $e) {
- dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
- }
- }
- }
-
- // 处理场景
- foreach ($scenes as &$scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_description = getProp($scene, 'description');
- $scene_pic_prompt = getProp($scene, 'pic_prompt');
- $scene_url = getProp($scene, 'url');
- $scene_task_id = getProp($scene, 'task_id');
-
- // 如果已有URL或已有任务ID,跳过
- if (!empty($scene_url) || !empty($scene_task_id)) {
- continue;
- }
-
- $url_inherited = false;
-
- // 尝试从全局数据中继承
- foreach ($global_scenes as $global_scene) {
- $global_scene_name = getProp($global_scene, 'scene');
- $global_scene_description = getProp($global_scene, 'description');
- $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
- $global_scene_url = getProp($global_scene, 'url');
- $global_scene_task_id = getProp($global_scene, 'task_id');
- $global_scene_task_status = getProp($global_scene, 'task_status');
-
- // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
- if ($scene_name === $global_scene_name
- && $scene_description === $global_scene_description
- && $scene_pic_prompt === $global_scene_pic_prompt
- && !empty($global_scene_url)) {
- // 继承 task_id、task_status 和 url
- $scene['task_id'] = $global_scene_task_id;
- $scene['task_status'] = $global_scene_task_status;
- $scene['url'] = $global_scene_url;
- $scenes_updated = true;
- $url_inherited = true;
- dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
- break;
- }
- }
-
- // 如果无法继承且没有任务ID,创建新任务
- if (!$url_inherited && empty($scene_task_id)) {
- try {
- $art_style = getProp($episode, 'art_style');
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
-
- // if ($art_style) {
- // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- // }
- $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
-
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $scene['task_id'] = $task_id;
- $scene['task_status'] = 'processing';
- $scenes_updated = true;
- dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
- }
- } catch (\Exception $e) {
- dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
- }
- }
- }
-
- // 如果有更新,保存到数据库
- if ($roles_updated || $scenes_updated) {
- $update_data = ['updated_at' => date('Y-m-d H:i:s')];
-
- if ($roles_updated) {
- $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
- }
-
- if ($scenes_updated) {
- $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
- }
-
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
- dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
- }
- }
- /**
- * 根据图片URL使用AI反推图片提示词
- *
- * @param string $img_url 图片URL
- * @return string 反推的提示词
- */
- private function generateImagePromptFromUrl($img_url) {
- try {
- // 获取默认模型
- $model = 'doubao-seed-2-0-mini-260215';
-
- // 构建messages参数
- $messages = [
- [
- 'role' => 'user',
- 'content' => [
- [
- 'type' => 'text',
- 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
- ],
- [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $img_url
- ]
- ]
- ]
- ]
- ];
-
- // 构建请求参数
- $params = [
- 'model' => $model,
- 'messages' => $messages,
- 'stream' => false,
- 'thinking' => ['type' => 'disabled'] // 不使用思考模式
- ];
-
- // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
- $result = $this->DeepSeekService->volcEngineChatCompletion($params);
-
- // 返回生成的内容
- return getProp($result, 'fullContent', '图片描述生成失败');
-
- } catch (\Exception $e) {
- dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
- 'img_url' => $img_url
- ]);
- logDB('anime', 'error', 'AI反推图片提示词失败', [
- 'error' => $e->getMessage(),
- 'img_url' => $img_url
- ]);
- return '图片描述生成失败: ' . $e->getMessage();
- }
- }
- /**
- * 音频试听接口
- * 创建音频任务并轮询获取结果
- *
- * @param array $data 参数数组
- * @return array 返回音频URL或错误信息
- */
- public function previewAudio($data) {
- $dialogue = getProp($data, 'dialogue');
-
- // 必填参数验证
- if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
-
- // 获取参数,优先使用传入的参数,否则使用分镜中的参数
- $voice_type = getProp($data, 'voice_type');
- $voice_name = getProp($data, 'voice_name');
- $voice_actor = getProp($data, 'voice_actor');
- $emotion_type = getProp($data, 'emotion_type');
- $gender = getProp($data, 'gender', 0);
- $emotion = getProp($data, 'emotion');
- $speed_ratio = getProp($data, 'speed_ratio', 0);
- $loudness_ratio = getProp($data, 'loudness_ratio', 0);
- $emotion_scale = getProp($data, 'emotion_scale', 0);
- $pitch = getProp($data, 'pitch', 0);
-
- try {
- $now = date('Y-m-d H:i:s');
-
- // 构建生成参数
- $generate_json = json_encode([
- 'text' => $dialogue,
- 'role' => $voice_actor,
- 'voice_type' => $voice_type,
- 'voice_name' => $voice_name,
- 'emotion' => $emotion,
- 'emotion_type' => $emotion_type,
- 'gender' => $gender,
- 'speed_ratio' => $speed_ratio,
- 'loudness_ratio' => $loudness_ratio,
- 'emotion_scale' => $emotion_scale,
- 'pitch' => $pitch,
- ], 256);
-
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 600, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
-
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
- Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
- }
- $arr = $response_arr['data'];
- $subtitle_info = $arr['subtitle_info'];
- $audio_duration = json_decode($subtitle_info, true)['duration'];
- if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
- return [
- 'audio_url' => $arr['url'],
- 'subtitle_info' => $subtitle_info,
- 'audio_duration' => round($audio_duration, 2)
- ];
-
- } catch (\Exception $e) {
- dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 获取角色库列表(支持文件夹递归查询)
- * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)
- * @return array 返回当前目录下的所有子目录和角色列表(递归)
- */
- public function globalProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id', 0);
- $parent_id = getProp($data, 'parent_id', 0);
- $product_name = getProp($data, 'product_name');
- $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
- if (!$product) {
- Utils::throwError('20003:请选择产品类型');
- }
-
- // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
- if ($id || $product_name) {
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('user_id', $uid)
- ->where('is_deleted', 0);
-
- // 如果指定了 id,按 id 精确查询
- if ($id) {
- $query->where('id', $id);
- }
-
- // 如果指定了 product_name,按名称模糊查询
- if ($product_name) {
- $query->where('product_name', 'like', "%{$product_name}%");
- }
-
- // 如果指定了 product,添加筛选条件
- if ($product) {
- $query->where('product', $product);
- }
-
- $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
- ->orderByRaw('sort_order DESC, created_at DESC')
- ->get()
- ->map(function($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
- $value['type'] = (int)$value['type'];
- $value['parent_id'] = (int)$value['parent_id'];
- $value['level'] = (int)$value['level'];
- $value['product'] = (int)($value['product'] ?? 1);
- $value['versions'] = json_decode($value['versions'], true) ?: [];
- return $value;
- })
- ->toArray();
-
- return $result;
- }
-
- // 递归获取所有子目录和角色
- return $this->getChildrenRecursive($cpid, $parent_id, $product, $uid);
- }
-
- /**
- * 递归获取指定目录下的所有子目录和角色
- * @param int $cpid 公司ID
- * @param int $parent_id 父目录ID
- * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
- * @param int $uid 用户ID
- * @return array
- */
- private function getChildrenRecursive($cpid, $parent_id, $product = null, $uid = null) {
- // 查询当前层级的所有项(文件夹和角色)
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->where('parent_id', $parent_id);
-
- // 添加用户ID验证
- if ($uid) {
- $query->where('user_id', $uid);
- }
-
- // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
- if ($product) {
- $query->where('product', $product);
- }
-
- $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
- ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
- ->get();
-
- $result = [];
-
- foreach ($items as $item) {
- $itemArray = [
- 'id' => $item->id,
- 'type' => (int)$item->type,
- 'parent_id' => (int)$item->parent_id,
- 'level' => (int)$item->level,
- 'product_name' => $item->product_name,
- 'url' => $item->url,
- 'pic_prompt' => $item->pic_prompt ?? '',
- 'three_view_image_url' => $item->three_view_image_url,
- 'product' => (int)($item->product ?? 1),
- 'created_at' => transDate($item->created_at, 'Y-m-d')
- ];
- $itemArray['versions'] = json_decode($item->versions, true) ?: [];
-
- // 如果是文件夹,递归获取其子项
- if ($item->type == 2) {
- $children = $this->getChildrenRecursive($cpid, $item->id, $product, $uid);
- if (!empty($children)) {
- $itemArray['children'] = $children;
- }
- }
-
- $result[] = $itemArray;
- }
-
- return $result;
- }
-
- /**
- * 创建文件夹
- * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
- * @return int 返回新建文件夹ID
- */
- public function createFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $parent_id = getProp($data, 'parent_id', 0);
- $folder_name = getProp($data, 'product_name', '新建文件夹');
-
- // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
- $product = getProp($data, 'product');
- if (!in_array($product, [1, 2, 3])) {
- // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
- }
-
- // 验证父文件夹
- $parent_level = 0;
- if ($parent_id > 0) {
- $parent = DB::table('mp_products')
- ->where('id', $parent_id)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent) {
- Utils::throwError('20003:父文件夹不存在');
- }
-
- // 检查父文件夹的 product 类型是否一致
- if ($parent->product != $product) {
- Utils::throwError('20003:文件夹类型必须与父文件夹一致');
- }
-
- $parent_level = $parent->level;
-
- // 检查层级限制(最多3层)
- if ($parent_level >= 3) {
- Utils::throwError('20003:文件夹层级不能超过3层');
- }
- }
-
- // 检查当前目录下是否已存在空白文件夹
- $empty_folder_exists = DB::table('mp_products')
- ->where('parent_id', $parent_id)
- ->where('type', 2)
- ->where('product', $product)
- ->where('product_name', '新建文件夹')
- ->where('is_deleted', 0)
- ->exists();
-
- if ($empty_folder_exists && $folder_name == '新建文件夹') {
- Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
- }
-
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $folder_name,
- 'product' => $product,
- 'sort_order' => time(), // 使用时间戳作为排序权重
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return [
- 'id' => $folder_id,
- 'type' => 2,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $folder_name,
- 'product' => $product,
- ];
- }
-
- /**
- * 重命名文件夹或角色
- * @param array $data 包含 id、product_name(新名称)
- * @return bool
- */
- public function renameFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- $new_name = getProp($data, 'product_name');
-
- if (!$id || !$new_name) {
- Utils::throwError('20003:参数不完整');
- }
-
- // 检查是否存在
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$item) {
- Utils::throwError('20003:项目不存在');
- }
-
- return DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'product_name' => $new_name,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- /**
- * 移动角色或文件夹到指定文件夹
- * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
- * @return bool
- */
- public function moveProductOrFolder($data) {
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- $target_parent_id = getProp($data, 'target_parent_id', 0);
-
- if (!$id) {
- Utils::throwError('20003:请选择要移动的项目');
- }
-
- // 检查要移动的项目
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$item) {
- Utils::throwError('20003:项目不存在');
- }
-
- // 验证目标文件夹
- $target_level = 0;
- $target_product = $item->product; // 默认使用当前项目的 product
-
- if ($target_parent_id > 0) {
- $target_parent = DB::table('mp_products')
- ->where('id', $target_parent_id)
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$target_parent) {
- Utils::throwError('20003:目标文件夹不存在');
- }
-
- // 检查 product 类型是否一致
- if ($target_parent->product != $item->product) {
- Utils::throwError('20003:不能移动到不同类型的文件夹下');
- }
-
- $target_level = $target_parent->level;
- $target_product = $target_parent->product;
-
- // 如果移动的是文件夹,需要检查层级
- if ($item->type == 2) {
- // 计算移动后的最大层级
- $max_child_level = $this->getMaxChildLevel($id);
- $depth = $max_child_level - $item->level;
-
- if ($target_level + 1 + $depth > 3) {
- Utils::throwError('20003:移动后文件夹层级将超过3层限制');
- }
-
- // 不能移动到自己或自己的子文件夹下
- if ($this->isDescendant($target_parent_id, $id)) {
- Utils::throwError('20003:不能移动到自己或子文件夹下');
- }
- }
- }
-
- // 更新父文件夹和层级
- $new_level = $target_level + 1;
- DB::table('mp_products')
- ->where('id', $id)
- ->update([
- 'parent_id' => $target_parent_id,
- 'level' => $new_level,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是文件夹,需要递归更新所有子项的层级
- if ($item->type == 2) {
- $this->updateChildrenLevel($id, $new_level);
- }
-
- return true;
- }
-
- /**
- * 获取文件夹下最大子层级
- * @param int $folder_id
- * @return int
- */
- private function getMaxChildLevel($folder_id) {
- $max_level = DB::table('mp_products')
- ->where('parent_id', $folder_id)
- ->where('is_deleted', 0)
- ->max('level');
-
- if (!$max_level) {
- return DB::table('mp_products')->where('id', $folder_id)->value('level');
- }
-
- // 递归查找子文件夹
- $children = DB::table('mp_products')
- ->where('parent_id', $folder_id)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->pluck('id');
-
- foreach ($children as $child_id) {
- $child_max = $this->getMaxChildLevel($child_id);
- if ($child_max > $max_level) {
- $max_level = $child_max;
- }
- }
-
- return $max_level;
- }
-
- /**
- * 检查 target_id 是否是 folder_id 的后代
- * @param int $target_id
- * @param int $folder_id
- * @return bool
- */
- private function isDescendant($target_id, $folder_id) {
- if ($target_id == $folder_id) {
- return true;
- }
-
- $parent = DB::table('mp_products')
- ->where('id', $target_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent || $parent->parent_id == 0) {
- return false;
- }
-
- return $this->isDescendant($parent->parent_id, $folder_id);
- }
-
- /**
- * 递归更新子项层级
- * @param int $parent_id
- * @param int $parent_level
- */
- private function updateChildrenLevel($parent_id, $parent_level) {
- $children = DB::table('mp_products')
- ->where('parent_id', $parent_id)
- ->where('is_deleted', 0)
- ->get();
-
- foreach ($children as $child) {
- $new_level = $parent_level + 1;
- DB::table('mp_products')
- ->where('id', $child->id)
- ->update([
- 'level' => $new_level,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是文件夹,继续递归
- if ($child->type == 2) {
- $this->updateChildrenLevel($child->id, $new_level);
- }
- }
- }
-
- /**
- * 获取文件夹路径(面包屑导航)
- * @param array $data 包含 folder_id
- * @return array 返回路径数组
- */
- public function getFolderPath($data) {
- $folder_id = getProp($data, 'id', 0);
-
- if ($folder_id == 0) {
- return [
- ['id' => 0, 'name' => '根目录']
- ];
- }
-
- $path = [];
- $current_id = $folder_id;
-
- while ($current_id > 0) {
- $folder = DB::table('mp_products')
- ->where('id', $current_id)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- break;
- }
-
- array_unshift($path, [
- 'id' => $folder->id,
- 'name' => $folder->product_name
- ]);
-
- $current_id = $folder->parent_id;
- }
-
- // 添加根目录
- array_unshift($path, ['id' => 0, 'name' => '根目录']);
-
- return $path;
- }
- public function createProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $product_name = trim(getProp($data, 'product_name'));
- if (!$product_name) Utils::throwError('20003:名称不能为空');
- $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
- if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
- $url = trim(getProp($data, 'url'));
- if (!$url) Utils::throwError('20003:图片地址不能为空');
- $versions = getProp($data, 'versions');
-
- // 检查是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
- $pic_prompt = trim(getProp($data, 'pic_prompt'));
- if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
-
- // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
- $product = getProp($data, 'product');
- if (!in_array($product, [1, 2, 3])) {
- // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
- }
-
- // 获取父文件夹ID和层级
- $parent_id = getProp($data, 'parent_id', 0);
- $parent_level = 0;
-
- if ($parent_id > 0) {
- $parent = DB::table('mp_products')
- ->where('id', $parent_id)
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent) {
- Utils::throwError('20003:父文件夹不存在');
- }
-
- $parent_level = $parent->level;
- }
- $id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 1=角色图片
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'product' => $product,
- 'versions' => json_encode($versions, 256),
- 'sort_order' => time(), // 使用时间戳作为排序权重
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$id) Utils::throwError('20003:创建失败');
- return [
- 'id' => $id,
- 'type' => 1,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'product' => $product,
- 'versions' => $versions
- ];
- }
- public function editProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $versions = getProp($data, 'versions');
-
- // 检查是否存在且属于当前用户
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)->first();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- $updateData = [];
- // $needVersionRecord = false; // 是否需要记录版本
-
- // 名称
- $product_name = trim(getProp($data, 'product_name'));
- if ($product_name) {
- $updateData['product_name'] = $product_name;
- }
- $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
- if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
-
- // 图片地址
- $url = trim(getProp($data, 'url'));
- if ($url) {
- // 检查是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
-
- // // 如果 url 有变更,记录版本
- // if ($url !== $role->url) {
- // $needVersionRecord = true;
- // }
-
- $updateData['url'] = $url;
- }
-
- // 提示词
- $pic_prompt = trim(getProp($data, 'pic_prompt'));
- if ($pic_prompt) {
- // // 如果 pic_prompt 有变更,记录版本
- // if ($pic_prompt !== $role->pic_prompt) {
- // $needVersionRecord = true;
- // }
-
- $updateData['pic_prompt'] = $pic_prompt;
- }
-
- if (empty($updateData)) {
- Utils::throwError('20003:没有需要更新的数据');
- }
-
- // // 如果需要记录版本,将数据添加到 versions 数组
- // if ($needVersionRecord) {
- // // 获取现有的 versions 数据
- // $versions = json_decode($role->versions, true) ?: [];
- // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
-
- // // 如果是第一次记录版本,先添加旧版本(变更前)
- // if ($isFirstVersion) {
- // $oldVersion = [
- // 'url' => $role->url,
- // 'description' => $role->pic_prompt,
- // ];
- // // 旧版本添加到数组末尾
- // $versions[] = $oldVersion;
- // }
-
- // // 构建新版本(变更后)
- // $newVersion = [
- // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
- // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
- // ];
-
- // // 检查新版本是否已存在于历史版本中
- // $existingIndex = -1;
- // foreach ($versions as $index => $version) {
- // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
- // $existingIndex = $index;
- // break;
- // }
- // }
-
- // if ($existingIndex !== -1) {
- // // 如果已存在,移除旧的位置
- // array_splice($versions, $existingIndex, 1);
- // }
-
- // // 新版本添加到数组开头(最新的在前)
- // array_unshift($versions, $newVersion);
-
- // // // 限制版本数量(可选,例如只保留最近10个版本)
- // // if (count($versions) > 10) {
- // // $versions = array_slice($versions, 0, 10);
- // // }
-
- // $updateData['versions'] = json_encode($versions, 256);
- // }
- if ($versions) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- $updateData['updated_at'] = date('Y-m-d H:i:s');
-
- return DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('id', $id)->update($updateData);
- }
-
- /**
- * 获取角色版本历史
- * @param array $data 包含 id(角色ID)
- * @return array 返回版本历史列表
- */
- public function getProductVersions($data) {
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:角色ID不能为空');
-
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)
- ->first();
-
- if (!$role) Utils::throwError('20003:角色不存在');
-
- // 获取版本历史
- $versions = json_decode($role->versions, true) ?: [];
-
- // 添加当前版本作为最新版本
- $currentVersion = [
- 'version' => 0, // 0 表示当前版本
- 'url' => $role->url,
- 'pic_prompt' => $role->pic_prompt,
- 'updated_at' => $role->updated_at,
- 'is_current' => true
- ];
-
- array_unshift($versions, $currentVersion);
-
- return $versions;
- }
-
- /**
- * 恢复到指定版本
- * @param array $data 包含 id(角色ID)、version(版本号)
- * @return bool
- */
- public function restoreProductVersion($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- $version = getProp($data, 'version');
-
- if (!$id) Utils::throwError('20003:角色ID不能为空');
- if (!$version) Utils::throwError('20003:版本号不能为空');
-
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)
- ->first();
-
- if (!$role) Utils::throwError('20003:角色不存在');
-
- // 获取版本历史
- $versions = json_decode($role->versions, true) ?: [];
-
- // 查找指定版本
- $targetVersion = null;
- foreach ($versions as $v) {
- if ($v['version'] == $version) {
- $targetVersion = $v;
- break;
- }
- }
-
- if (!$targetVersion) Utils::throwError('20003:版本不存在');
-
- // 先将当前版本保存到历史
- $newVersion = [
- 'version' => count($versions) + 1,
- 'url' => $role->url,
- 'pic_prompt' => $role->pic_prompt,
- 'updated_at' => date('Y-m-d H:i:s'),
- 'updated_by' => $uid
- ];
-
- array_unshift($versions, $newVersion);
-
- // 限制版本数量
- if (count($versions) > 10) {
- $versions = array_slice($versions, 0, 10);
- }
-
- // 恢复到指定版本
- return DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'url' => $targetVersion['url'],
- 'pic_prompt' => $targetVersion['pic_prompt'],
- 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function deleteProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $ids = explode(',', $id);
-
- // 检查是否存在且属于当前用户
- $role = DB::table('mp_products')
- ->whereIn('id', $ids)
- ->where('cpid', $cpid)
- ->get();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- return DB::table('mp_products')
- ->where('cpid', $cpid)
- ->whereIn('id', $ids)
- ->update([
- 'is_deleted' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function generateThreeView($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
-
- // 检查是否存在且属于当前用户
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)->first();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
- $ref_img_url = trim(getProp($data, 'ref_img_url'));
- if (!$ref_img_url) {
- // 如果没有传入参考图,使用角色表中的图片
- $ref_img_url = $role->url ?? '';
- if (!$ref_img_url) {
- Utils::throwError('20003:参考图不能为空');
- }
- }
-
- // 检查参考图是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
-
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 使用默认模型
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => [$ref_img_url],
- 'width' => 1600,
- 'height' => 2848
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建图片生成任务失败');
- }
-
- // 检查任务模型类型
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 轮询获取结果(5分钟超时,每3秒查询一次)
- $start_time = time();
- $timeout = 300; // 5分钟
- $img_url = '';
-
- while (time() - $start_time < $timeout) {
- sleep(3);
- // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
- if ($isSyncModel) {
- // 刷新任务状态
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
- break;
- } elseif ($task->status === 'failed') {
- Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
- }
- } else {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
-
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
-
- $img_url = $statusInfo['result_url'][0];
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- dLog('anime')->error('三视图生成失败', [
- 'error' => $statusInfo['error_message'] ?? '未知错误'
- ]);
- Utils::throwError('20003:三视图生成失败,' . ($statusInfo['error_message'] ?? '未知错误'));
- }
- }
- }
-
- if (empty($img_url)) {
- Utils::throwError('20003:三视图生成超时,请稍后重试');
- }
-
- // 保存三视图到 mp_products 表
- DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'three_view_image_url' => $img_url,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return ['three_view_image_url' => $img_url];
-
- } catch (\Exception $e) {
- dLog('anime')->error('生成三视图失败', [
- 'error' => $e->getMessage()
- ]);
- logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
-
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
- * @param string $actContent 原始内容
- * @param array $products 产品数组(包含product_name和url)
- * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
- */
- public function processActContentWithProducts($actContent, $products) {
- if (empty($actContent) || empty($products)) {
- return [
- 'content' => $actContent,
- 'reference_images' => []
- ];
- }
-
- // 构建产品名称到产品信息的映射
- $product_dict = [];
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- if ($product_name) {
- $product_dict[$product_name] = [
- 'url' => getProp($product, 'url'),
- 'voice_prompt' => getProp($product, 'voice_prompt')
- ];
- }
- }
-
- // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
- preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
-
- $reference_images = [];
- $product_index_map = []; // 产品名称 => 图片序号的映射
- $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
- $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
- $current_index = 1;
-
- if (!empty($matches[1])) {
- // 按照在内容中第一次出现的顺序,为每个产品分配序号
- $seen_products = []; // 用于去重
-
- foreach ($matches[1] as $product_name) {
- // 跳过已处理的产品
- if (isset($seen_products[$product_name])) {
- continue;
- }
-
- $seen_products[$product_name] = true;
-
- // 检查产品是否在字典中
- if (isset($product_dict[$product_name])) {
- $url = $product_dict[$product_name]['url'];
- $voice_prompt = $product_dict[$product_name]['voice_prompt'];
-
- // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
- if (!empty($voice_prompt) && $product_name !== '旁白') {
- $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
- }
-
- // 只有URL非空才分配序号和添加到参考图片
- if (!empty($url)) {
- // 检查URL是否已经在reference_images中(去重)
- if (!in_array($url, $reference_images)) {
- $reference_images[] = $url;
- $product_index_map[$product_name] = $current_index;
- $current_index++;
- } else {
- // URL重复,找到已有的序号
- $existing_index = array_search($url, $reference_images) + 1;
- $product_index_map[$product_name] = $existing_index;
- }
- } else {
- // URL为空,不分配序号(后续直接去掉{})
- $product_index_map[$product_name] = 0;
- }
- } else {
- // 产品不在字典中,不分配序号
- $product_index_map[$product_name] = 0;
- }
- }
- }
-
- // 第二步:替换内容中的 {产品名称}
- $processedContent = $actContent;
- foreach ($product_index_map as $product_name => $index) {
- $escaped_name = preg_quote($product_name, '/');
-
- if ($index > 0) {
- // 有图片,替换为:产品名称(图X)
- $replacement = $product_name . '<图片' . $index . '>';
- } else {
- // 无图片,只保留产品名称
- $replacement = $product_name;
- }
-
- // 替换所有 {产品名称} 为处理后的格式
- $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
- }
-
- // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- $voice_prompt = getProp($product, 'voice_prompt');
-
- if ($product_name === '旁白' && !empty($voice_prompt)) {
- $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
- break; // 找到旁白后退出循环
- }
- }
-
- // 第四步:将voice_prompt信息添加到内容最前面
- $voice_prompt_prefix = '';
- if (!empty($voice_prompts)) {
- $voice_prompt_prefix .= implode('', $voice_prompts);
- }
- // 旁白的voice_prompt放在最后
- if (!empty($narrator_voice_prompt)) {
- $voice_prompt_prefix .= $narrator_voice_prompt;
- }
-
- // 如果有voice_prompt信息,添加到内容开头
- if (!empty($voice_prompt_prefix)) {
- $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
- }
-
- return [
- 'content' => $processedContent,
- 'reference_images' => $reference_images
- ];
- }
- public function saveActVideoGenerateParams($data) {
- $episode_id = getProp($data, 'episode_id');
- $model = getProp($data, 'video_model');
- if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
- Utils::throwError('20003:该模型不可用');
- }
- if (!$model) {
- // 使用默认模型
- $model = 'zhizhen-20-mini';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $video_resolution = getProp($data, 'video_resolution', '720p');
- $ratio = getProp($data, 'ratio');
- if (!$ratio) $ratio = '9:16';
- return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'video_resolution' => $video_resolution,
- 'ratio' => $ratio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- }
- public function confirmActs($data) {
- $episode_id = getProp($data, 'episode_id');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) {
- Utils::throwError('20003:分集不存在');
- }
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
- // 获取所有片段数据
- $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
-
- // 构建角色和场景名称数组
- $role_names = [];
- $scene_names = [];
-
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- if ($role_name && $role_name != '旁白') {
- $role_names[] = $role_name;
- }
- }
-
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- if ($scene_name) {
- $scene_names[] = $scene_name;
- }
- }
-
- // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
- usort($role_names, function($a, $b) {
- return mb_strlen($b) - mb_strlen($a);
- });
- usort($scene_names, function($a, $b) {
- return mb_strlen($b) - mb_strlen($a);
- });
- try {
- DB::beginTransaction();
- // 处理每个片段
- foreach ($acts as $act) {
- $act_content = getProp($act, 'act_content');
- if (!$act_content) continue;
-
- $processed_content = $act_content;
-
- // 标记已处理的位置,避免重复标记
- $marked_positions = [];
-
- // 先匹配场景(在"场景:"后面)
- foreach ($scene_names as $scene_name) {
- // 转义特殊字符
- $escaped_scene = preg_quote($scene_name, '/');
- // 匹配场景:后面的场景名称(可能换行,也可能不换行)
- $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
-
- $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
- $full_match = $matches[0];
- $prefix = $matches[1];
- $scene_name = $matches[2];
-
- // 检查是否已经被标记
- if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
- return $prefix . '{' . $scene_name . '}';
- }
- return $full_match;
- }, $processed_content);
- }
-
- // 再匹配角色名称(只在"画面:"部分)
- foreach ($role_names as $role_name) {
- // 转义特殊字符
- $escaped_role = preg_quote($role_name, '/');
-
- // 只匹配"画面:"开始到换行之前的内容
- $pattern = '/(画面:[^\n]*)/u';
- $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
- $line = $matches[1]; // 整行"画面:xxxxx"
-
- // 在这一行中匹配所有角色名(避免重复标记)
- $new_line = preg_replace(
- '/(?<![{])(' . $escaped_role . ')(?![}])/u',
- '{$1}',
- $line
- );
-
- return $new_line;
- }, $processed_content);
- }
-
- // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
- $shot_counter = 0;
- $processed_content = preg_replace_callback(
- '/【(?:镜头|分镜)(\d+)】/u',
- function($matches) use (&$shot_counter) {
- $shot_counter++;
- return '【镜头' . $shot_counter . '】';
- },
- $processed_content
- );
-
- // 更新数据库
- $boolen = DB::table('mp_episode_segments')
- ->where('id', $act->id)
- ->update([
- 'act_show_content' => $processed_content,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:片段处理失败');
- }
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
-
- $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'is_generated' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen1) {
- DB::rollBack();
- Utils::throwError('20003:分集处理失败!');
- }
- DB::commit();
- // 重新查询更新后的片段数据
- $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
- // 合并角色、场景和extra_products作为products,统一字段名为product_name
- // extra_products优先级更高,会覆盖同名的roles和scenes
- $products = [];
-
- // 先处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (isset($product['role'])) {
- $product['product_name'] = $product['role'];
- unset($product['role']);
- }
- $product['product'] = 1; // 标记类型为角色
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // 处理场景数组
- foreach ($scenes as $scene) {
- $product = $scene;
- // 将scene字段重命名为product_name
- if (isset($product['scene'])) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- }
- $product['product'] = 2; // 标记类型为场景
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // extra_products优先级更高,直接覆盖同名的roles和scenes
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
- foreach ($extra_products as $extra_product) {
- $product_name = getProp($extra_product, 'product_name');
- if ($product_name) {
- $products[$product_name] = $extra_product; // 覆盖同名数据
- }
- }
-
- // 重新索引数组(去除key)
- $products = array_values($products);
-
- // 构建返回的acts数组
- $return_acts = [];
- foreach ($acts as $act) {
- $return_acts[] = [
- 'act_id' => getProp($act, 'id'),
- 'act_number' => getProp($act, 'act_number'),
- 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
- 'act_show_content' => getProp($act, 'act_show_content'),
- 'video_url' => getProp($act, 'video_url'),
- 'video_duration' => getProp($act, 'video_duration'),
- 'video_time_point_start' => getProp($act, 'video_time_point_start'),
- 'video_time_point_end' => getProp($act, 'video_time_point_end'),
- ];
- }
- return [
- 'anime_id' => getProp($episode, 'anime_id'),
- 'episode_id' => $episode_id,
- 'title' => getProp($episode, 'title'),
- 'episode_number' => getProp($episode, 'episode_number'),
- 'is_generated' => getProp($episode, 'is_generated'),
- 'products' => $products,
- 'acts' => $return_acts
- ];
- }
- }
|